From e0e860f330f3529669b4662e1be6ffb0e8689dfb Mon Sep 17 00:00:00 2001 From: enoch Date: Fri, 27 Nov 2026 17:34:16 +0800 Subject: [PATCH] save --- .env | 14 + .gitignore | 7 - ...f846f7389ec7ea7b18c365741889027e0d3be5.php | 67 + runtime/logs/stdout.log | 0 runtime/logs/webman-2026-11-26.log | 6 + runtime/logs/workerman.log | 4 + runtime/release-update.lock | 0 .../session_4642ca1e97f07570602f6a23b52f53a8 | 1 + .../session_5d4813b2ce9ef52ca809292e2ca0a39d | 1 + .../session_9866b4738ae5a72c352c798a74a5bd67 | 1 + .../session_be3a99224d70dba62cfccfd756a26382 | 1 + .../session_f393e9966092010277f6c9a34d76b55a | 1 + runtime/webman.pid | 1 + storage/laysite.sqlite | Bin 0 -> 212992 bytes storage/laysite.sqlite-shm | Bin 0 -> 32768 bytes storage/laysite.sqlite-wal | Bin 0 -> 70072 bytes .../56e075e3c9857fbb7f39e35f89041583.png | Bin 0 -> 54010 bytes .../6e5c7e924efdb0106ee52ca13957320e.jpg | Bin 0 -> 84398 bytes update.php | 575 +++ vendor/autoload.php | 25 + vendor/composer/ClassLoader.php | 579 +++ vendor/composer/InstalledVersions.php | 359 ++ vendor/composer/LICENSE | 21 + vendor/composer/autoload_classmap.php | 99 + vendor/composer/autoload_files.php | 16 + vendor/composer/autoload_namespaces.php | 9 + vendor/composer/autoload_psr4.php | 41 + vendor/composer/autoload_real.php | 50 + vendor/composer/autoload_static.php | 323 ++ vendor/composer/installed.json | 2266 ++++++++++++ vendor/composer/installed.php | 308 ++ vendor/composer/platform_check.php | 26 + vendor/dflydev/dot-access-data/CHANGELOG.md | 74 + vendor/dflydev/dot-access-data/LICENSE | 19 + vendor/dflydev/dot-access-data/README.md | 158 + vendor/dflydev/dot-access-data/composer.json | 67 + vendor/dflydev/dot-access-data/src/Data.php | 286 ++ .../dot-access-data/src/DataInterface.php | 131 + .../src/Exception/DataException.php | 21 + .../src/Exception/InvalidPathException.php | 21 + .../src/Exception/MissingPathException.php | 37 + vendor/dflydev/dot-access-data/src/Util.php | 78 + vendor/firebase/php-jwt/CHANGELOG.md | 272 ++ vendor/firebase/php-jwt/LICENSE | 30 + vendor/firebase/php-jwt/README.md | 469 +++ vendor/firebase/php-jwt/VERSION | 1 + vendor/firebase/php-jwt/composer.json | 53 + .../php-jwt/src/BeforeValidException.php | 18 + vendor/firebase/php-jwt/src/CachedKeySet.php | 275 ++ .../firebase/php-jwt/src/ExpiredException.php | 30 + vendor/firebase/php-jwt/src/JWK.php | 376 ++ vendor/firebase/php-jwt/src/JWT.php | 835 +++++ .../src/JWTExceptionWithPayloadInterface.php | 20 + vendor/firebase/php-jwt/src/Key.php | 53 + .../php-jwt/src/SignatureInvalidException.php | 7 + vendor/graham-campbell/result-type/LICENSE | 21 + .../graham-campbell/result-type/composer.json | 33 + .../graham-campbell/result-type/src/Error.php | 119 + .../result-type/src/Result.php | 69 + .../result-type/src/Success.php | 119 + vendor/guzzlehttp/guzzle/AGENTS.md | 76 + vendor/guzzlehttp/guzzle/CHANGELOG.md | 2403 +++++++++++++ vendor/guzzlehttp/guzzle/CLAUDE.md | 1 + vendor/guzzlehttp/guzzle/LICENSE | 27 + vendor/guzzlehttp/guzzle/README.md | 95 + vendor/guzzlehttp/guzzle/UPGRADING.md | 2785 +++++++++++++++ vendor/guzzlehttp/guzzle/composer.json | 132 + .../guzzlehttp/guzzle/src/Auth/DigestAuth.php | 515 +++ .../guzzle/src/Auth/DigestChallenge.php | 29 + .../guzzlehttp/guzzle/src/AuthMiddleware.php | 846 +++++ .../guzzlehttp/guzzle/src/BodySummarizer.php | 29 + .../guzzle/src/BodySummarizerInterface.php | 15 + vendor/guzzlehttp/guzzle/src/Client.php | 1716 +++++++++ .../guzzlehttp/guzzle/src/ClientInterface.php | 370 ++ vendor/guzzlehttp/guzzle/src/ClientTrait.php | 1315 +++++++ .../guzzle/src/Cookie/CookieJar.php | 452 +++ .../guzzle/src/Cookie/CookieJarInterface.php | 82 + .../guzzle/src/Cookie/FileCookieJar.php | 168 + .../guzzle/src/Cookie/SessionCookieJar.php | 150 + .../guzzle/src/Cookie/SetCookie.php | 601 ++++ vendor/guzzlehttp/guzzle/src/Env.php | 33 + .../src/Exception/BadResponseException.php | 12 + .../guzzle/src/Exception/ClientException.php | 12 + .../guzzle/src/Exception/ConnectException.php | 12 + .../src/Exception/ConnectTimeoutException.php | 12 + .../guzzle/src/Exception/GuzzleException.php | 11 + .../src/Exception/HandlerClosedException.php | 12 + .../Exception/InvalidArgumentException.php | 12 + .../guzzle/src/Exception/NetworkException.php | 22 + .../src/Exception/NetworkTimeoutException.php | 13 + .../guzzle/src/Exception/RequestException.php | 91 + .../src/Exception/ResponseException.php | 63 + .../Exception/ResponseTimeoutException.php | 13 + .../Exception/ResponseTransferException.php | 13 + .../guzzle/src/Exception/ServerException.php | 12 + .../Exception/TooManyRedirectsException.php | 12 + .../src/Exception/TransferException.php | 33 + .../guzzle/src/Handler/ChunkedBodyStream.php | 431 +++ .../guzzlehttp/guzzle/src/Handler/Clock.php | 32 + .../guzzle/src/Handler/CurlFactory.php | 3179 +++++++++++++++++ .../src/Handler/CurlFactoryInterface.php | 31 + .../guzzle/src/Handler/CurlHandler.php | 174 + .../guzzle/src/Handler/CurlMultiHandler.php | 1673 +++++++++ .../src/Handler/CurlShareHandleState.php | 276 ++ .../guzzle/src/Handler/CurlVersion.php | 407 +++ .../src/Handler/DeadlineSourceStream.php | 82 + .../guzzle/src/Handler/DebugResource.php | 36 + .../src/Handler/DeclaredLengthStream.php | 103 + .../guzzle/src/Handler/EasyHandle.php | 260 ++ .../guzzle/src/Handler/EncodedBodyStream.php | 83 + .../guzzle/src/Handler/HeaderProcessor.php | 330 ++ .../guzzle/src/Handler/HostValidator.php | 162 + .../guzzle/src/Handler/InflateBodyStream.php | 330 ++ .../guzzle/src/Handler/MockHandler.php | 276 ++ .../guzzle/src/Handler/Protocols.php | 47 + .../guzzlehttp/guzzle/src/Handler/Proxy.php | 66 + .../guzzle/src/Handler/ProxyEnv.php | 159 + .../guzzle/src/Handler/RequestFraming.php | 256 ++ .../guzzle/src/Handler/StreamHandler.php | 2073 +++++++++++ .../src/Handler/StreamTlsSessionCache.php | 583 +++ .../guzzlehttp/guzzle/src/Handler/Timeout.php | 41 + .../guzzle/src/Handler/TlsVersion.php | 70 + .../src/Handler/TransferByteCounter.php | 62 + .../guzzle/src/Handler/TransportStream.php | 48 + .../guzzle/src/Handler/UriDiagnostic.php | 39 + vendor/guzzlehttp/guzzle/src/HandlerStack.php | 274 ++ vendor/guzzlehttp/guzzle/src/HostIdentity.php | 233 ++ vendor/guzzlehttp/guzzle/src/Idn.php | 106 + .../guzzle/src/MessageFormatter.php | 207 ++ .../guzzle/src/MessageFormatterInterface.php | 20 + vendor/guzzlehttp/guzzle/src/Middleware.php | 348 ++ vendor/guzzlehttp/guzzle/src/Multiplexing.php | 28 + .../guzzle/src/NonSerializableTrait.php | 21 + vendor/guzzlehttp/guzzle/src/Pool.php | 524 +++ .../guzzle/src/PrepareBodyMiddleware.php | 123 + vendor/guzzlehttp/guzzle/src/ProxyOptions.php | 624 ++++ .../guzzlehttp/guzzle/src/ProxySelection.php | 66 + .../guzzle/src/RedirectMiddleware.php | 368 ++ .../guzzlehttp/guzzle/src/RequestOptions.php | 526 +++ .../guzzlehttp/guzzle/src/RetryMiddleware.php | 137 + .../guzzlehttp/guzzle/src/TransferStats.php | 123 + .../guzzle/src/TransportSharing.php | 18 + vendor/guzzlehttp/guzzle/src/Utils.php | 366 ++ vendor/guzzlehttp/promises/AGENTS.md | 62 + vendor/guzzlehttp/promises/CHANGELOG.md | 303 ++ vendor/guzzlehttp/promises/CLAUDE.md | 1 + vendor/guzzlehttp/promises/LICENSE | 24 + vendor/guzzlehttp/promises/README.md | 100 + vendor/guzzlehttp/promises/UPGRADING.md | 279 ++ vendor/guzzlehttp/promises/composer.json | 61 + .../promises/docs/implementation-notes.md | 72 + .../guzzlehttp/promises/docs/promise-api.md | 177 + .../promises/docs/promise-interoperability.md | 78 + .../promises/docs/promise-quick-start.md | 319 ++ .../promises/src/AggregateException.php | 19 + .../promises/src/CancellationException.php | 12 + vendor/guzzlehttp/promises/src/Coroutine.php | 199 ++ vendor/guzzlehttp/promises/src/Create.php | 117 + vendor/guzzlehttp/promises/src/Each.php | 118 + .../guzzlehttp/promises/src/EachPromise.php | 295 ++ .../promises/src/FulfilledPromise.php | 113 + vendor/guzzlehttp/promises/src/Is.php | 91 + .../promises/src/NonSerializableTrait.php | 21 + vendor/guzzlehttp/promises/src/Promise.php | 358 ++ .../promises/src/PromiseInterface.php | 119 + .../promises/src/PromisorInterface.php | 21 + .../promises/src/RejectedPromise.php | 122 + .../promises/src/RejectionException.php | 49 + vendor/guzzlehttp/promises/src/State.php | 44 + vendor/guzzlehttp/promises/src/TaskQueue.php | 84 + .../promises/src/TaskQueueInterface.php | 26 + vendor/guzzlehttp/promises/src/Utils.php | 385 ++ vendor/guzzlehttp/psr7/AGENTS.md | 69 + vendor/guzzlehttp/psr7/CHANGELOG.md | 840 +++++ vendor/guzzlehttp/psr7/CLAUDE.md | 1 + vendor/guzzlehttp/psr7/LICENSE | 26 + vendor/guzzlehttp/psr7/README.md | 88 + vendor/guzzlehttp/psr7/UPGRADING.md | 1101 ++++++ vendor/guzzlehttp/psr7/composer.json | 111 + .../guzzlehttp/psr7/docs/diagnostic-values.md | 30 + vendor/guzzlehttp/psr7/docs/error-scopes.md | 64 + .../psr7/docs/header-and-query-helpers.md | 107 + .../guzzlehttp/psr7/docs/message-helpers.md | 112 + .../guzzlehttp/psr7/docs/psr-17-factories.md | 33 + vendor/guzzlehttp/psr7/docs/psr-7-messages.md | 402 +++ vendor/guzzlehttp/psr7/docs/stream-helpers.md | 150 + .../psr7/docs/streams-and-decorators.md | 397 ++ .../psr7/docs/uri-and-mime-helpers.md | 83 + vendor/guzzlehttp/psr7/docs/uri-helpers.md | 511 +++ vendor/guzzlehttp/psr7/src/AppendStream.php | 257 ++ vendor/guzzlehttp/psr7/src/BufferStream.php | 151 + vendor/guzzlehttp/psr7/src/CachingStream.php | 239 ++ .../guzzlehttp/psr7/src/DiagnosticValue.php | 63 + vendor/guzzlehttp/psr7/src/DroppingStream.php | 48 + vendor/guzzlehttp/psr7/src/ErrorScope.php | 138 + .../src/Exception/MalformedUriException.php | 14 + .../psr7/src/Exception/TimeoutException.php | 14 + vendor/guzzlehttp/psr7/src/FnStream.php | 250 ++ vendor/guzzlehttp/psr7/src/Header.php | 167 + vendor/guzzlehttp/psr7/src/HttpFactory.php | 111 + vendor/guzzlehttp/psr7/src/Idna.php | 162 + vendor/guzzlehttp/psr7/src/InflateStream.php | 146 + vendor/guzzlehttp/psr7/src/Integers.php | 104 + vendor/guzzlehttp/psr7/src/LazyOpenStream.php | 52 + vendor/guzzlehttp/psr7/src/LimitStream.php | 197 + vendor/guzzlehttp/psr7/src/Message.php | 262 ++ vendor/guzzlehttp/psr7/src/MessageParser.php | 371 ++ vendor/guzzlehttp/psr7/src/MessageTrait.php | 279 ++ vendor/guzzlehttp/psr7/src/MimeType.php | 1309 +++++++ .../guzzlehttp/psr7/src/MultipartStream.php | 286 ++ vendor/guzzlehttp/psr7/src/NoSeekStream.php | 28 + .../psr7/src/NonSerializableStreamTrait.php | 21 + vendor/guzzlehttp/psr7/src/PumpStream.php | 190 + vendor/guzzlehttp/psr7/src/Query.php | 156 + .../psr7/src/ReadFailureCapturingStream.php | 61 + vendor/guzzlehttp/psr7/src/Request.php | 215 ++ vendor/guzzlehttp/psr7/src/Response.php | 159 + vendor/guzzlehttp/psr7/src/Rfc3986.php | 361 ++ vendor/guzzlehttp/psr7/src/Rfc9110.php | 41 + vendor/guzzlehttp/psr7/src/Rfc9112.php | 126 + vendor/guzzlehttp/psr7/src/ServerRequest.php | 234 ++ .../psr7/src/ServerRequestGlobalsFactory.php | 523 +++ vendor/guzzlehttp/psr7/src/Stream.php | 334 ++ .../psr7/src/StreamDecoratorTrait.php | 149 + vendor/guzzlehttp/psr7/src/StreamTimeout.php | 106 + vendor/guzzlehttp/psr7/src/StreamWrapper.php | 254 ++ vendor/guzzlehttp/psr7/src/UploadedFile.php | 188 + .../psr7/src/UploadedFileNormalizer.php | 130 + vendor/guzzlehttp/psr7/src/Uri.php | 882 +++++ vendor/guzzlehttp/psr7/src/UriComparator.php | 96 + vendor/guzzlehttp/psr7/src/UriNormalizer.php | 456 +++ vendor/guzzlehttp/psr7/src/UriParser.php | 173 + vendor/guzzlehttp/psr7/src/UriRedactor.php | 131 + vendor/guzzlehttp/psr7/src/UriResolver.php | 309 ++ vendor/guzzlehttp/psr7/src/Utils.php | 903 +++++ vendor/league/commonmark/.phpstorm.meta.php | 108 + vendor/league/commonmark/CHANGELOG.md | 946 +++++ vendor/league/commonmark/LICENSE | 28 + vendor/league/commonmark/README.md | 226 ++ vendor/league/commonmark/composer.json | 129 + .../commonmark/src/CommonMarkConverter.php | 46 + .../commonmark/src/ConverterInterface.php | 30 + .../commonmark/src/Delimiter/Bracket.php | 83 + .../commonmark/src/Delimiter/Delimiter.php | 134 + .../src/Delimiter/DelimiterInterface.php | 56 + .../src/Delimiter/DelimiterParser.php | 106 + .../src/Delimiter/DelimiterStack.php | 396 ++ .../CacheableDelimiterProcessorInterface.php | 46 + .../DelimiterProcessorCollection.php | 89 + .../DelimiterProcessorCollectionInterface.php | 46 + .../Processor/DelimiterProcessorInterface.php | 81 + .../Processor/StaggeredDelimiterProcessor.php | 111 + .../src/Environment/Environment.php | 454 +++ .../Environment/EnvironmentAwareInterface.php | 19 + .../EnvironmentBuilderInterface.php | 97 + .../src/Environment/EnvironmentInterface.php | 55 + .../commonmark/src/Event/AbstractEvent.php | 54 + .../src/Event/DocumentParsedEvent.php | 35 + .../src/Event/DocumentPreParsedEvent.php | 49 + .../src/Event/DocumentPreRenderEvent.php | 44 + .../src/Event/DocumentRenderedEvent.php | 42 + .../commonmark/src/Event/ListenerData.php | 50 + .../Exception/AlreadyInitializedException.php | 18 + .../src/Exception/CommonMarkException.php | 21 + .../commonmark/src/Exception/IOException.php | 18 + .../Exception/InvalidArgumentException.php | 18 + .../src/Exception/LogicException.php | 18 + .../Exception/MissingDependencyException.php | 18 + .../Exception/UnexpectedEncodingException.php | 18 + .../Attributes/AttributesExtension.php | 44 + .../Attributes/Event/AttributesListener.php | 406 +++ .../Extension/Attributes/Node/Attributes.php | 65 + .../Attributes/Node/AttributesInline.php | 57 + .../Parser/AttributesBlockContinueParser.php | 155 + .../Parser/AttributesBlockStartParser.php | 40 + .../Parser/AttributesInlineParser.php | 54 + .../Attributes/Util/AttributesHelper.php | 207 ++ .../Extension/Autolink/AutolinkExtension.php | 39 + .../Autolink/EmailAutolinkParser.php | 48 + .../Extension/Autolink/UrlAutolinkParser.php | 155 + .../CommonMark/CommonMarkCoreExtension.php | 92 + .../Processor/EmphasisDelimiterProcessor.php | 122 + .../CommonMark/Node/Block/BlockQuote.php | 20 + .../CommonMark/Node/Block/FencedCode.php | 100 + .../CommonMark/Node/Block/Heading.php | 41 + .../CommonMark/Node/Block/HtmlBlock.php | 79 + .../CommonMark/Node/Block/IndentedCode.php | 32 + .../CommonMark/Node/Block/ListBlock.php | 56 + .../CommonMark/Node/Block/ListData.php | 47 + .../CommonMark/Node/Block/ListItem.php | 37 + .../CommonMark/Node/Block/ThematicBreak.php | 20 + .../Node/Inline/AbstractWebResource.php | 41 + .../Extension/CommonMark/Node/Inline/Code.php | 23 + .../CommonMark/Node/Inline/Emphasis.php | 42 + .../CommonMark/Node/Inline/HtmlInline.php | 24 + .../CommonMark/Node/Inline/Image.php | 49 + .../Extension/CommonMark/Node/Inline/Link.php | 49 + .../CommonMark/Node/Inline/Strong.php | 42 + .../Parser/Block/BlockQuoteParser.php | 60 + .../Parser/Block/BlockQuoteStartParser.php | 39 + .../Parser/Block/FencedCodeParser.php | 85 + .../Parser/Block/FencedCodeStartParser.php | 40 + .../CommonMark/Parser/Block/HeadingParser.php | 51 + .../Parser/Block/HeadingStartParser.php | 80 + .../Parser/Block/HtmlBlockParser.php | 82 + .../Parser/Block/HtmlBlockStartParser.php | 62 + .../Parser/Block/IndentedCodeParser.php | 76 + .../Parser/Block/IndentedCodeStartParser.php | 42 + .../Parser/Block/ListBlockParser.php | 93 + .../Parser/Block/ListBlockStartParser.php | 154 + .../Parser/Block/ListItemParser.php | 82 + .../Parser/Block/ThematicBreakParser.php | 42 + .../Parser/Block/ThematicBreakStartParser.php | 40 + .../Parser/Inline/AutolinkParser.php | 54 + .../Parser/Inline/BacktickParser.php | 132 + .../CommonMark/Parser/Inline/BangParser.php | 44 + .../Parser/Inline/CloseBracketParser.php | 224 ++ .../CommonMark/Parser/Inline/EntityParser.php | 42 + .../Parser/Inline/EscapableParser.php | 57 + .../Parser/Inline/HtmlInlineParser.php | 41 + .../Parser/Inline/OpenBracketParser.php | 42 + .../Renderer/Block/BlockQuoteRenderer.php | 70 + .../Renderer/Block/FencedCodeRenderer.php | 81 + .../Renderer/Block/HeadingRenderer.php | 64 + .../Renderer/Block/HtmlBlockRenderer.php | 66 + .../Renderer/Block/IndentedCodeRenderer.php | 61 + .../Renderer/Block/ListBlockRenderer.php | 86 + .../Renderer/Block/ListItemRenderer.php | 80 + .../Renderer/Block/ThematicBreakRenderer.php | 56 + .../Renderer/Inline/CodeRenderer.php | 57 + .../Renderer/Inline/EmphasisRenderer.php | 56 + .../Renderer/Inline/HtmlInlineRenderer.php | 66 + .../Renderer/Inline/ImageRenderer.php | 107 + .../Renderer/Inline/LinkRenderer.php | 89 + .../Renderer/Inline/StrongRenderer.php | 56 + .../ConfigurableExtensionInterface.php | 21 + .../ApplyDefaultAttributesProcessor.php | 151 + .../DefaultAttributesExtension.php | 76 + .../DescriptionListExtension.php | 42 + .../ConsecutiveDescriptionListMerger.php | 41 + .../Event/LooseDescriptionHandler.php | 66 + .../DescriptionList/Node/Description.php | 39 + .../DescriptionList/Node/DescriptionList.php | 20 + .../DescriptionList/Node/DescriptionTerm.php | 20 + .../Parser/DescriptionContinueParser.php | 71 + .../Parser/DescriptionListContinueParser.php | 53 + .../Parser/DescriptionStartParser.php | 73 + .../Parser/DescriptionTermContinueParser.php | 52 + .../Renderer/DescriptionListRenderer.php | 39 + .../Renderer/DescriptionRenderer.php | 37 + .../Renderer/DescriptionTermRenderer.php | 37 + .../DisallowedRawHtmlExtension.php | 51 + .../DisallowedRawHtmlRenderer.php | 64 + .../Embed/Bridge/OscaroteroEmbedAdapter.php | 50 + .../Embed/DomainFilteringAdapter.php | 62 + .../commonmark/src/Extension/Embed/Embed.php | 50 + .../Extension/Embed/EmbedAdapterInterface.php | 25 + .../src/Extension/Embed/EmbedExtension.php | 48 + .../src/Extension/Embed/EmbedParser.php | 62 + .../src/Extension/Embed/EmbedProcessor.php | 72 + .../src/Extension/Embed/EmbedRenderer.php | 35 + .../src/Extension/Embed/EmbedStartParser.php | 53 + .../src/Extension/ExtensionInterface.php | 24 + .../ExternalLink/ExternalLinkExtension.php | 47 + .../ExternalLink/ExternalLinkProcessor.php | 141 + .../Event/AnonymousFootnotesListener.php | 62 + .../FixOrphanedFootnotesAndRefsListener.php | 68 + .../Event/GatherFootnotesListener.php | 138 + .../Event/NumberFootnotesListener.php | 83 + .../Extension/Footnote/FootnoteExtension.php | 74 + .../src/Extension/Footnote/Node/Footnote.php | 37 + .../Footnote/Node/FootnoteBackref.php | 40 + .../Footnote/Node/FootnoteContainer.php | 21 + .../Extension/Footnote/Node/FootnoteRef.php | 57 + .../Parser/AnonymousFootnoteRefParser.php | 66 + .../Footnote/Parser/FootnoteParser.php | 68 + .../Footnote/Parser/FootnoteRefParser.php | 57 + .../Footnote/Parser/FootnoteStartParser.php | 56 + .../Renderer/FootnoteBackrefRenderer.php | 87 + .../Renderer/FootnoteContainerRenderer.php | 71 + .../Footnote/Renderer/FootnoteRefRenderer.php | 93 + .../Footnote/Renderer/FootnoteRenderer.php | 80 + .../Data/FrontMatterDataParserInterface.php | 26 + .../Data/LibYamlFrontMatterParser.php | 47 + .../Data/SymfonyYamlFrontMatterParser.php | 39 + .../Exception/InvalidFrontMatterException.php | 24 + .../FrontMatter/FrontMatterExtension.php | 46 + .../FrontMatter/FrontMatterParser.php | 64 + .../FrontMatterParserInterface.php | 21 + .../FrontMatterProviderInterface.php | 22 + .../Input/MarkdownInputWithFrontMatter.php | 43 + .../FrontMatterPostRenderListener.php | 35 + .../Listener/FrontMatterPreParser.php | 37 + .../Output/RenderedContentWithFrontMatter.php | 51 + .../GithubFlavoredMarkdownExtension.php | 33 + .../HeadingPermalink/HeadingPermalink.php | 37 + .../HeadingPermalinkExtension.php | 49 + .../HeadingPermalinkProcessor.php | 105 + .../HeadingPermalinkRenderer.php | 109 + .../Highlight/HighlightExtension.php | 26 + .../src/Extension/Highlight/Mark.php | 39 + .../Highlight/MarkDelimiterProcessor.php | 73 + .../src/Extension/Highlight/MarkRenderer.php | 50 + .../Extension/InlinesOnly/ChildRenderer.php | 35 + .../InlinesOnly/InlinesOnlyExtension.php | 74 + .../Mention/Generator/CallbackGenerator.php | 54 + .../Generator/MentionGeneratorInterface.php | 22 + .../Generator/StringTemplateLinkGenerator.php | 34 + .../src/Extension/Mention/Mention.php | 93 + .../Extension/Mention/MentionExtension.php | 61 + .../src/Extension/Mention/MentionParser.php | 87 + .../NormalizeHeadingsExtension.php | 44 + .../NormalizeHeadingsProcessor.php | 78 + .../src/Extension/SmartPunct/DashParser.php | 59 + .../Extension/SmartPunct/EllipsesParser.php | 38 + .../src/Extension/SmartPunct/Quote.php | 30 + .../src/Extension/SmartPunct/QuoteParser.php | 98 + .../Extension/SmartPunct/QuoteProcessor.php | 82 + .../ReplaceUnpairedQuotesListener.php | 43 + .../SmartPunct/SmartPunctExtension.php | 64 + .../Extension/Strikethrough/Strikethrough.php | 39 + .../StrikethroughDelimiterProcessor.php | 73 + .../Strikethrough/StrikethroughExtension.php | 26 + .../Strikethrough/StrikethroughRenderer.php | 50 + .../commonmark/src/Extension/Table/Table.php | 22 + .../src/Extension/Table/TableCell.php | 99 + .../src/Extension/Table/TableCellRenderer.php | 89 + .../src/Extension/Table/TableExtension.php | 63 + .../src/Extension/Table/TableParser.php | 227 ++ .../src/Extension/Table/TableRenderer.php | 58 + .../src/Extension/Table/TableRow.php | 22 + .../src/Extension/Table/TableRowRenderer.php | 56 + .../src/Extension/Table/TableSection.php | 64 + .../Extension/Table/TableSectionRenderer.php | 70 + .../src/Extension/Table/TableStartParser.php | 177 + .../TableOfContents/Node/TableOfContents.php | 20 + .../Node/TableOfContentsPlaceholder.php | 20 + .../Node/TableOfContentsReference.php | 47 + .../Normalizer/AsIsNormalizerStrategy.php | 72 + .../Normalizer/FlatNormalizerStrategy.php | 33 + .../NormalizerStrategyInterface.php | 21 + .../Normalizer/RelativeNormalizerStrategy.php | 67 + .../TableOfContentsBuilder.php | 159 + .../TableOfContentsExtension.php | 62 + .../TableOfContentsGenerator.php | 164 + .../TableOfContentsGeneratorInterface.php | 22 + .../TableOfContentsPlaceholderParser.php | 74 + .../TableOfContentsPlaceholderRenderer.php | 40 + .../TableOfContentsReferenceRenderer.php | 44 + .../TableOfContentsRenderCache.php | 34 + .../TableOfContentsRenderer.php | 56 + .../Extension/TaskList/TaskListExtension.php | 26 + .../Extension/TaskList/TaskListItemMarker.php | 39 + .../TaskList/TaskListItemMarkerParser.php | 58 + .../TaskList/TaskListItemMarkerRenderer.php | 70 + .../src/GithubFlavoredMarkdownConverter.php | 45 + .../commonmark/src/Input/MarkdownInput.php | 102 + .../src/Input/MarkdownInputInterface.php | 26 + .../commonmark/src/MarkdownConverter.php | 93 + .../src/MarkdownConverterInterface.php | 34 + .../src/Node/Block/AbstractBlock.php | 64 + .../commonmark/src/Node/Block/Document.php | 56 + .../commonmark/src/Node/Block/Paragraph.php | 23 + .../src/Node/Block/TightBlockInterface.php | 21 + .../src/Node/Inline/AbstractInline.php | 23 + .../Node/Inline/AbstractStringContainer.php | 47 + .../src/Node/Inline/AdjacentTextMerger.php | 101 + .../src/Node/Inline/DelimitedInterface.php | 21 + .../commonmark/src/Node/Inline/Newline.php | 40 + .../commonmark/src/Node/Inline/Text.php | 25 + vendor/league/commonmark/src/Node/Node.php | 266 ++ .../commonmark/src/Node/NodeIterator.php | 58 + .../league/commonmark/src/Node/NodeWalker.php | 80 + .../commonmark/src/Node/NodeWalkerEvent.php | 42 + vendor/league/commonmark/src/Node/Query.php | 139 + .../commonmark/src/Node/Query/AndExpr.php | 55 + .../src/Node/Query/ExpressionInterface.php | 21 + .../commonmark/src/Node/Query/OrExpr.php | 55 + .../src/Node/RawMarkupContainerInterface.php | 21 + .../src/Node/StringContainerHelper.php | 54 + .../src/Node/StringContainerInterface.php | 27 + .../src/Normalizer/SlugNormalizer.php | 57 + .../src/Normalizer/TextNormalizer.php | 44 + .../Normalizer/TextNormalizerInterface.php | 33 + .../src/Normalizer/UniqueSlugNormalizer.php | 83 + .../UniqueSlugNormalizerInterface.php | 28 + .../commonmark/src/Output/RenderedContent.php | 49 + .../src/Output/RenderedContentInterface.php | 29 + .../Block/AbstractBlockContinueParser.php | 47 + .../src/Parser/Block/BlockContinue.php | 73 + .../Block/BlockContinueParserInterface.php | 68 + ...lockContinueParserWithInlinesInterface.php | 24 + .../src/Parser/Block/BlockStart.php | 124 + .../Block/BlockStartParserInterface.php | 33 + .../src/Parser/Block/DocumentBlockParser.php | 80 + .../src/Parser/Block/ParagraphParser.php | 85 + .../SkipLinesStartingWithLettersParser.php | 45 + .../league/commonmark/src/Parser/Cursor.php | 744 ++++ .../commonmark/src/Parser/CursorState.php | 56 + .../Parser/Inline/InlineParserInterface.php | 23 + .../src/Parser/Inline/InlineParserMatch.php | 87 + .../src/Parser/Inline/NewlineParser.php | 53 + .../src/Parser/InlineParserContext.php | 120 + .../src/Parser/InlineParserEngine.php | 182 + .../Parser/InlineParserEngineInterface.php | 27 + .../commonmark/src/Parser/MarkdownParser.php | 356 ++ .../src/Parser/MarkdownParserInterface.php | 25 + .../src/Parser/MarkdownParserState.php | 57 + .../Parser/MarkdownParserStateInterface.php | 36 + .../src/Parser/ParserLogicException.php | 20 + .../Reference/MemoryLimitedReferenceMap.php | 68 + .../commonmark/src/Reference/Reference.php | 54 + .../src/Reference/ReferenceInterface.php | 29 + .../commonmark/src/Reference/ReferenceMap.php | 85 + .../src/Reference/ReferenceMapInterface.php | 31 + .../src/Reference/ReferenceParser.php | 334 ++ .../src/Reference/ReferenceableInterface.php | 19 + .../src/Renderer/Block/DocumentRenderer.php | 57 + .../src/Renderer/Block/ParagraphRenderer.php | 74 + .../Renderer/ChildNodeRendererInterface.php | 31 + .../Renderer/DocumentRendererInterface.php | 28 + .../commonmark/src/Renderer/HtmlDecorator.php | 45 + .../commonmark/src/Renderer/HtmlRenderer.php | 100 + .../src/Renderer/Inline/NewlineRenderer.php | 76 + .../src/Renderer/Inline/TextRenderer.php | 54 + .../Renderer/MarkdownRendererInterface.php | 30 + .../Renderer/NoMatchingRendererException.php | 20 + .../src/Renderer/NodeRendererInterface.php | 27 + .../commonmark/src/Util/ArrayCollection.php | 175 + .../src/Util/Html5EntityDecoder.php | 75 + .../commonmark/src/Util/HtmlElement.php | 160 + .../league/commonmark/src/Util/HtmlFilter.php | 55 + .../commonmark/src/Util/LinkParserHelper.php | 174 + .../commonmark/src/Util/PrioritizedList.php | 73 + .../commonmark/src/Util/RegexHelper.php | 260 ++ .../league/commonmark/src/Util/SpecReader.php | 72 + .../league/commonmark/src/Util/UrlEncoder.php | 69 + vendor/league/commonmark/src/Util/Xml.php | 33 + .../src/Xml/FallbackNodeXmlRenderer.php | 85 + .../src/Xml/MarkdownToXmlConverter.php | 59 + .../src/Xml/XmlNodeRendererInterface.php | 28 + .../league/commonmark/src/Xml/XmlRenderer.php | 143 + vendor/league/config/CHANGELOG.md | 42 + vendor/league/config/LICENSE.md | 28 + vendor/league/config/README.md | 153 + vendor/league/config/composer.json | 69 + vendor/league/config/src/Configuration.php | 255 ++ .../src/ConfigurationAwareInterface.php | 22 + .../src/ConfigurationBuilderInterface.php | 21 + .../config/src/ConfigurationInterface.php | 46 + .../src/ConfigurationProviderInterface.php | 22 + .../ConfigurationExceptionInterface.php | 21 + .../InvalidConfigurationException.php | 46 + .../src/Exception/UnknownOptionException.php | 33 + .../src/Exception/ValidationException.php | 37 + .../src/MutableConfigurationInterface.php | 34 + .../config/src/ReadOnlyConfiguration.php | 40 + .../config/src/SchemaBuilderInterface.php | 27 + vendor/league/oauth2-client/LICENSE | 21 + vendor/league/oauth2-client/README.md | 54 + vendor/league/oauth2-client/composer.json | 58 + vendor/league/oauth2-client/phpunit.xml.dist | 36 + .../oauth2-client/src/Grant/AbstractGrant.php | 80 + .../src/Grant/AuthorizationCode.php | 41 + .../src/Grant/ClientCredentials.php | 39 + .../Grant/Exception/InvalidGrantException.php | 26 + .../oauth2-client/src/Grant/GrantFactory.php | 104 + .../oauth2-client/src/Grant/Password.php | 42 + .../oauth2-client/src/Grant/RefreshToken.php | 41 + .../HttpBasicAuthOptionProvider.php | 42 + .../OptionProviderInterface.php | 30 + .../OptionProvider/PostAuthOptionProvider.php | 51 + .../src/Provider/AbstractProvider.php | 961 +++++ .../Exception/IdentityProviderException.php | 48 + .../src/Provider/GenericProvider.php | 247 ++ .../src/Provider/GenericResourceOwner.php | 61 + .../src/Provider/ResourceOwnerInterface.php | 36 + .../oauth2-client/src/Token/AccessToken.php | 251 ++ .../src/Token/AccessTokenInterface.php | 74 + .../ResourceOwnerAccessTokenInterface.php | 25 + .../Token/SettableRefreshTokenInterface.php | 26 + .../src/Tool/ArrayAccessorTrait.php | 52 + .../src/Tool/BearerAuthorizationTrait.php | 36 + .../src/Tool/GuardedPropertyTrait.php | 70 + .../src/Tool/MacAuthorizationTrait.php | 83 + .../src/Tool/ProviderRedirectTrait.php | 122 + .../src/Tool/QueryBuilderTrait.php | 33 + .../oauth2-client/src/Tool/RequestFactory.php | 87 + .../src/Tool/RequiredParameterTrait.php | 56 + vendor/monolog/monolog/CHANGELOG.md | 864 +++++ vendor/monolog/monolog/LICENSE | 19 + vendor/monolog/monolog/README.md | 136 + vendor/monolog/monolog/composer.json | 84 + .../Monolog/Attribute/AsMonologProcessor.php | 38 + .../Monolog/Attribute/WithMonologChannel.php | 30 + .../monolog/src/Monolog/DateTimeImmutable.php | 24 + .../monolog/src/Monolog/ErrorHandler.php | 337 ++ .../Monolog/Formatter/ChromePHPFormatter.php | 87 + .../Monolog/Formatter/ElasticaFormatter.php | 84 + .../Formatter/ElasticsearchFormatter.php | 86 + .../Monolog/Formatter/FlowdockFormatter.php | 106 + .../Monolog/Formatter/FluentdFormatter.php | 85 + .../Monolog/Formatter/FormatterInterface.php | 38 + .../Formatter/GelfMessageFormatter.php | 152 + .../Formatter/GoogleCloudLoggingFormatter.php | 40 + .../src/Monolog/Formatter/HtmlFormatter.php | 142 + .../src/Monolog/Formatter/JsonFormatter.php | 242 ++ .../src/Monolog/Formatter/LineFormatter.php | 345 ++ .../src/Monolog/Formatter/LogglyFormatter.php | 47 + .../Monolog/Formatter/LogmaticFormatter.php | 70 + .../Monolog/Formatter/LogstashFormatter.php | 100 + .../Monolog/Formatter/MongoDBFormatter.php | 129 + .../Monolog/Formatter/NormalizerFormatter.php | 394 ++ .../Monolog/Formatter/RedactingFormatter.php | 393 ++ .../src/Monolog/Formatter/ScalarFormatter.php | 49 + .../src/Monolog/Formatter/SyslogFormatter.php | 66 + .../Monolog/Formatter/WildfireFormatter.php | 137 + .../Formatter/WrappingFormatterInterface.php | 28 + .../src/Monolog/Handler/AbstractHandler.php | 104 + .../Handler/AbstractProcessingHandler.php | 60 + .../Monolog/Handler/AbstractSyslogHandler.php | 95 + .../src/Monolog/Handler/AmqpHandler.php | 170 + .../Monolog/Handler/BrowserConsoleHandler.php | 300 ++ .../src/Monolog/Handler/BufferHandler.php | 170 + .../src/Monolog/Handler/ChromePHPHandler.php | 186 + .../src/Monolog/Handler/CouchDBHandler.php | 97 + .../src/Monolog/Handler/CubeHandler.php | 167 + .../monolog/src/Monolog/Handler/Curl/Util.php | 60 + .../Monolog/Handler/DeduplicationHandler.php | 184 + .../Handler/DoctrineCouchDBHandler.php | 47 + .../src/Monolog/Handler/DynamoDbHandler.php | 80 + .../src/Monolog/Handler/ElasticaHandler.php | 144 + .../Monolog/Handler/ElasticsearchHandler.php | 239 ++ .../src/Monolog/Handler/ErrorLogHandler.php | 93 + .../Monolog/Handler/FallbackGroupHandler.php | 68 + .../src/Monolog/Handler/FilterHandler.php | 202 ++ .../ActivationStrategyInterface.php | 27 + .../ChannelLevelActivationStrategy.php | 69 + .../ErrorLevelActivationStrategy.php | 42 + .../Monolog/Handler/FingersCrossedHandler.php | 242 ++ .../src/Monolog/Handler/FirePHPHandler.php | 174 + .../src/Monolog/Handler/FleepHookHandler.php | 132 + .../src/Monolog/Handler/FlowdockHandler.php | 127 + .../Handler/FormattableHandlerInterface.php | 34 + .../Handler/FormattableHandlerTrait.php | 57 + .../src/Monolog/Handler/FrankenPhpHandler.php | 100 + .../src/Monolog/Handler/GelfHandler.php | 58 + .../src/Monolog/Handler/GroupHandler.php | 130 + .../monolog/src/Monolog/Handler/Handler.php | 53 + .../src/Monolog/Handler/HandlerInterface.php | 76 + .../src/Monolog/Handler/HandlerWrapper.php | 134 + .../src/Monolog/Handler/IFTTTHandler.php | 75 + .../src/Monolog/Handler/InsightOpsHandler.php | 74 + .../src/Monolog/Handler/LogEntriesHandler.php | 68 + .../src/Monolog/Handler/LogMonsterHandler.php | 192 + .../src/Monolog/Handler/LogglyHandler.php | 156 + .../src/Monolog/Handler/LogmaticHandler.php | 98 + .../src/Monolog/Handler/MailHandler.php | 91 + .../src/Monolog/Handler/MandrillHandler.php | 83 + .../Handler/MissingExtensionException.php | 21 + .../src/Monolog/Handler/MongoDBHandler.php | 83 + .../Monolog/Handler/NativeMailerHandler.php | 179 + .../src/Monolog/Handler/NewRelicHandler.php | 180 + .../src/Monolog/Handler/NoopHandler.php | 42 + .../src/Monolog/Handler/NullHandler.php | 56 + .../src/Monolog/Handler/OverflowHandler.php | 139 + .../src/Monolog/Handler/PHPConsoleHandler.php | 303 ++ .../src/Monolog/Handler/ProcessHandler.php | 191 + .../Handler/ProcessableHandlerInterface.php | 43 + .../Handler/ProcessableHandlerTrait.php | 70 + .../src/Monolog/Handler/PsrHandler.php | 92 + .../src/Monolog/Handler/PushoverHandler.php | 246 ++ .../src/Monolog/Handler/RedisHandler.php | 94 + .../Monolog/Handler/RedisPubSubHandler.php | 65 + .../src/Monolog/Handler/RollbarHandler.php | 132 + .../Monolog/Handler/RotatingFileHandler.php | 386 ++ .../src/Monolog/Handler/SamplingHandler.php | 121 + .../src/Monolog/Handler/SendGridHandler.php | 95 + .../src/Monolog/Handler/Slack/SlackRecord.php | 381 ++ .../src/Monolog/Handler/SlackHandler.php | 267 ++ .../Monolog/Handler/SlackWebhookHandler.php | 130 + .../src/Monolog/Handler/SocketHandler.php | 443 +++ .../src/Monolog/Handler/SqsHandler.php | 61 + .../src/Monolog/Handler/StreamHandler.php | 311 ++ .../Monolog/Handler/SymfonyMailerHandler.php | 109 + .../src/Monolog/Handler/SyslogHandler.php | 63 + .../Monolog/Handler/SyslogUdp/UdpSocket.php | 87 + .../src/Monolog/Handler/SyslogUdpHandler.php | 162 + .../Monolog/Handler/TelegramBotHandler.php | 467 +++ .../src/Monolog/Handler/TestHandler.php | 203 ++ .../Handler/WebRequestRecognizerTrait.php | 23 + .../Handler/WhatFailureGroupHandler.php | 80 + .../Monolog/Handler/ZendMonitorHandler.php | 90 + .../JsonSerializableDateTimeImmutable.php | 48 + vendor/monolog/monolog/src/Monolog/Level.php | 209 ++ .../monolog/monolog/src/Monolog/LogRecord.php | 127 + vendor/monolog/monolog/src/Monolog/Logger.php | 819 +++++ .../Processor/ClosureContextProcessor.php | 51 + .../src/Monolog/Processor/GitProcessor.php | 75 + .../Monolog/Processor/HostnameProcessor.php | 37 + .../Processor/IntrospectionProcessor.php | 126 + .../Processor/LoadAverageProcessor.php | 66 + .../Processor/MemoryPeakUsageProcessor.php | 39 + .../src/Monolog/Processor/MemoryProcessor.php | 60 + .../Processor/MemoryUsageProcessor.php | 39 + .../Monolog/Processor/MercurialProcessor.php | 80 + .../Monolog/Processor/ProcessIdProcessor.php | 32 + .../Monolog/Processor/ProcessorInterface.php | 27 + .../Processor/PsrLogMessageProcessor.php | 87 + .../src/Monolog/Processor/TagProcessor.php | 65 + .../src/Monolog/Processor/UidProcessor.php | 67 + .../src/Monolog/Processor/WebProcessor.php | 115 + .../monolog/monolog/src/Monolog/Registry.php | 133 + .../src/Monolog/ResettableInterface.php | 31 + .../monolog/src/Monolog/SignalHandler.php | 113 + .../src/Monolog/Test/MonologTestCase.php | 71 + .../monolog/src/Monolog/Test/TestCase.php | 23 + vendor/monolog/monolog/src/Monolog/Utils.php | 327 ++ vendor/nette/schema/composer.json | 45 + vendor/nette/schema/license.md | 60 + vendor/nette/schema/readme.md | 802 +++++ vendor/nette/schema/src/Schema/Context.php | 66 + .../schema/src/Schema/DynamicParameter.php | 13 + .../schema/src/Schema/Elements/AnyOf.php | 212 ++ .../schema/src/Schema/Elements/ArrayType.php | 65 + .../nette/schema/src/Schema/Elements/Base.php | 224 ++ .../schema/src/Schema/Elements/EnumType.php | 49 + .../schema/src/Schema/Elements/NumberType.php | 40 + .../schema/src/Schema/Elements/StringType.php | 32 + .../schema/src/Schema/Elements/Structure.php | 274 ++ .../schema/src/Schema/Elements/TupleType.php | 125 + .../nette/schema/src/Schema/Elements/Type.php | 359 ++ vendor/nette/schema/src/Schema/Expect.php | 188 + vendor/nette/schema/src/Schema/Helpers.php | 250 ++ vendor/nette/schema/src/Schema/JsonSchema.php | 292 ++ vendor/nette/schema/src/Schema/Message.php | 97 + vendor/nette/schema/src/Schema/Processor.php | 111 + vendor/nette/schema/src/Schema/Schema.php | 39 + .../schema/src/Schema/TypeExpression.php | 150 + .../schema/src/Schema/ValidationException.php | 50 + vendor/nette/schema/src/Schema/enums.php | 48 + vendor/nette/utils/.phpstorm.meta.php | 11 + vendor/nette/utils/composer.json | 61 + vendor/nette/utils/license.md | 60 + vendor/nette/utils/readme.md | 55 + vendor/nette/utils/src/HtmlStringable.php | 23 + .../utils/src/Iterators/CachingIterator.php | 133 + vendor/nette/utils/src/Iterators/Mapper.php | 30 + vendor/nette/utils/src/SmartObject.php | 141 + vendor/nette/utils/src/StaticClass.php | 22 + vendor/nette/utils/src/Translator.php | 23 + vendor/nette/utils/src/Utils/ArrayHash.php | 100 + vendor/nette/utils/src/Utils/ArrayList.php | 130 + vendor/nette/utils/src/Utils/Arrays.php | 572 +++ vendor/nette/utils/src/Utils/Callback.php | 142 + vendor/nette/utils/src/Utils/DateTime.php | 207 ++ .../utils/src/Utils/DateTimeImmutable.php | 187 + vendor/nette/utils/src/Utils/FileInfo.php | 65 + vendor/nette/utils/src/Utils/FileSystem.php | 390 ++ vendor/nette/utils/src/Utils/Finder.php | 551 +++ vendor/nette/utils/src/Utils/Floats.php | 105 + vendor/nette/utils/src/Utils/Helpers.php | 125 + vendor/nette/utils/src/Utils/Html.php | 892 +++++ vendor/nette/utils/src/Utils/Image.php | 855 +++++ vendor/nette/utils/src/Utils/ImageColor.php | 81 + vendor/nette/utils/src/Utils/ImageType.php | 23 + vendor/nette/utils/src/Utils/Iterables.php | 271 ++ vendor/nette/utils/src/Utils/Json.php | 81 + .../nette/utils/src/Utils/ObjectHelpers.php | 233 ++ vendor/nette/utils/src/Utils/Paginator.php | 210 ++ vendor/nette/utils/src/Utils/Process.php | 564 +++ vendor/nette/utils/src/Utils/Random.php | 52 + vendor/nette/utils/src/Utils/Reflection.php | 334 ++ .../utils/src/Utils/ReflectionMethod.php | 39 + vendor/nette/utils/src/Utils/Strings.php | 742 ++++ vendor/nette/utils/src/Utils/Type.php | 314 ++ vendor/nette/utils/src/Utils/Validators.php | 419 +++ vendor/nette/utils/src/Utils/exceptions.php | 64 + vendor/nette/utils/src/compatibility.php | 30 + vendor/nette/utils/src/exceptions.php | 112 + vendor/nikic/fast-route/.hhconfig | 1 + vendor/nikic/fast-route/FastRoute.hhi | 126 + vendor/nikic/fast-route/LICENSE | 31 + vendor/nikic/fast-route/README.md | 313 ++ vendor/nikic/fast-route/composer.json | 24 + .../fast-route/src/BadRouteException.php | 7 + vendor/nikic/fast-route/src/DataGenerator.php | 26 + .../src/DataGenerator/CharCountBased.php | 31 + .../src/DataGenerator/GroupCountBased.php | 30 + .../src/DataGenerator/GroupPosBased.php | 27 + .../src/DataGenerator/MarkBased.php | 27 + .../src/DataGenerator/RegexBasedAbstract.php | 186 + vendor/nikic/fast-route/src/Dispatcher.php | 26 + .../src/Dispatcher/CharCountBased.php | 31 + .../src/Dispatcher/GroupCountBased.php | 31 + .../src/Dispatcher/GroupPosBased.php | 33 + .../fast-route/src/Dispatcher/MarkBased.php | 31 + .../src/Dispatcher/RegexBasedAbstract.php | 88 + vendor/nikic/fast-route/src/Route.php | 47 + .../nikic/fast-route/src/RouteCollector.php | 165 + vendor/nikic/fast-route/src/RouteParser.php | 37 + .../nikic/fast-route/src/RouteParser/Std.php | 87 + vendor/nikic/fast-route/src/bootstrap.php | 12 + vendor/nikic/fast-route/src/functions.php | 74 + vendor/phpoption/phpoption/LICENSE | 201 ++ vendor/phpoption/phpoption/composer.json | 50 + .../phpoption/src/PhpOption/LazyOption.php | 177 + .../phpoption/src/PhpOption/None.php | 168 + .../phpoption/src/PhpOption/Option.php | 443 +++ .../phpoption/src/PhpOption/Some.php | 197 + vendor/psr/container/.gitignore | 3 + vendor/psr/container/LICENSE | 21 + vendor/psr/container/README.md | 13 + vendor/psr/container/composer.json | 27 + .../src/ContainerExceptionInterface.php | 12 + .../psr/container/src/ContainerInterface.php | 36 + .../src/NotFoundExceptionInterface.php | 10 + vendor/psr/event-dispatcher/.editorconfig | 15 + vendor/psr/event-dispatcher/.gitignore | 2 + vendor/psr/event-dispatcher/LICENSE | 21 + vendor/psr/event-dispatcher/README.md | 6 + vendor/psr/event-dispatcher/composer.json | 26 + .../src/EventDispatcherInterface.php | 21 + .../src/ListenerProviderInterface.php | 19 + .../src/StoppableEventInterface.php | 26 + vendor/psr/http-client/CHANGELOG.md | 31 + vendor/psr/http-client/LICENSE | 19 + vendor/psr/http-client/README.md | 12 + vendor/psr/http-client/composer.json | 30 + .../src/ClientExceptionInterface.php | 10 + .../psr/http-client/src/ClientInterface.php | 20 + .../src/NetworkExceptionInterface.php | 24 + .../src/RequestExceptionInterface.php | 24 + vendor/psr/http-factory/LICENSE | 21 + vendor/psr/http-factory/README.md | 12 + vendor/psr/http-factory/composer.json | 38 + .../src/RequestFactoryInterface.php | 18 + .../src/ResponseFactoryInterface.php | 18 + .../src/ServerRequestFactoryInterface.php | 24 + .../src/StreamFactoryInterface.php | 45 + .../src/UploadedFileFactoryInterface.php | 34 + .../http-factory/src/UriFactoryInterface.php | 17 + vendor/psr/http-message/CHANGELOG.md | 36 + vendor/psr/http-message/LICENSE | 19 + vendor/psr/http-message/README.md | 16 + vendor/psr/http-message/composer.json | 26 + .../psr/http-message/docs/PSR7-Interfaces.md | 130 + vendor/psr/http-message/docs/PSR7-Usage.md | 159 + .../psr/http-message/src/MessageInterface.php | 187 + .../psr/http-message/src/RequestInterface.php | 130 + .../http-message/src/ResponseInterface.php | 68 + .../src/ServerRequestInterface.php | 261 ++ .../psr/http-message/src/StreamInterface.php | 158 + .../src/UploadedFileInterface.php | 123 + vendor/psr/http-message/src/UriInterface.php | 324 ++ vendor/psr/log/LICENSE | 19 + vendor/psr/log/README.md | 58 + vendor/psr/log/composer.json | 26 + vendor/psr/log/src/AbstractLogger.php | 15 + .../psr/log/src/InvalidArgumentException.php | 7 + vendor/psr/log/src/LogLevel.php | 18 + vendor/psr/log/src/LoggerAwareInterface.php | 14 + vendor/psr/log/src/LoggerAwareTrait.php | 22 + vendor/psr/log/src/LoggerInterface.php | 98 + vendor/psr/log/src/LoggerTrait.php | 98 + vendor/psr/log/src/NullLogger.php | 26 + .../deprecation-contracts/CHANGELOG.md | 5 + vendor/symfony/deprecation-contracts/LICENSE | 19 + .../symfony/deprecation-contracts/README.md | 26 + .../deprecation-contracts/composer.json | 35 + .../deprecation-contracts/function.php | 27 + vendor/symfony/polyfill-ctype/Ctype.php | 232 ++ vendor/symfony/polyfill-ctype/LICENSE | 19 + vendor/symfony/polyfill-ctype/README.md | 12 + vendor/symfony/polyfill-ctype/bootstrap.php | 50 + vendor/symfony/polyfill-ctype/bootstrap80.php | 46 + vendor/symfony/polyfill-ctype/composer.json | 38 + vendor/symfony/polyfill-mbstring/LICENSE | 19 + vendor/symfony/polyfill-mbstring/Mbstring.php | 1662 +++++++++ vendor/symfony/polyfill-mbstring/README.md | 13 + .../Resources/unidata/caseFolding.php | 119 + .../unidata/eastAsianWidthRegexp.php | 5 + .../Resources/unidata/lowerCase.php | 1397 ++++++++ .../Resources/unidata/titleCase.php | 139 + .../Resources/unidata/titleCaseRegexp.php | 5 + .../Resources/unidata/upperCase.php | 1489 ++++++++ .../symfony/polyfill-mbstring/bootstrap.php | 16 + .../symfony/polyfill-mbstring/bootstrap72.php | 173 + .../symfony/polyfill-mbstring/bootstrap80.php | 167 + .../symfony/polyfill-mbstring/composer.json | 39 + vendor/symfony/polyfill-php80/LICENSE | 19 + vendor/symfony/polyfill-php80/Php80.php | 115 + vendor/symfony/polyfill-php80/PhpToken.php | 108 + vendor/symfony/polyfill-php80/README.md | 25 + .../Resources/stubs/Attribute.php | 31 + .../Resources/stubs/PhpToken.php | 16 + .../Resources/stubs/Stringable.php | 20 + .../Resources/stubs/UnhandledMatchError.php | 16 + .../Resources/stubs/ValueError.php | 16 + vendor/symfony/polyfill-php80/bootstrap.php | 42 + vendor/symfony/polyfill-php80/composer.json | 37 + vendor/symfony/polyfill-php82/LICENSE | 19 + .../polyfill-php82/NoDynamicProperties.php | 23 + vendor/symfony/polyfill-php82/Php82.php | 399 +++ vendor/symfony/polyfill-php82/README.md | 23 + .../polyfill-php82/Random/Engine/Secure.php | 50 + .../stubs/AllowDynamicProperties.php | 20 + .../stubs/Random/BrokenRandomEngineError.php | 18 + .../stubs/Random/CryptoSafeEngine.php | 18 + .../Resources/stubs/Random/Engine.php | 19 + .../Resources/stubs/Random/Engine/Secure.php | 20 + .../Resources/stubs/Random/RandomError.php | 21 + .../stubs/Random/RandomException.php | 21 + .../Resources/stubs/SensitiveParameter.php | 20 + .../stubs/SensitiveParameterValue.php | 16 + .../SensitiveParameterValue.php | 47 + vendor/symfony/polyfill-php82/bootstrap.php | 38 + vendor/symfony/polyfill-php82/composer.json | 33 + vendor/vlucas/phpdotenv/LICENSE | 30 + vendor/vlucas/phpdotenv/composer.json | 60 + vendor/vlucas/phpdotenv/src/Dotenv.php | 267 ++ .../src/Exception/ExceptionInterface.php | 12 + .../Exception/InvalidEncodingException.php | 12 + .../src/Exception/InvalidFileException.php | 12 + .../src/Exception/InvalidPathException.php | 12 + .../src/Exception/ValidationException.php | 12 + vendor/vlucas/phpdotenv/src/Loader/Loader.php | 43 + .../phpdotenv/src/Loader/LoaderInterface.php | 20 + .../vlucas/phpdotenv/src/Loader/Resolver.php | 235 ++ vendor/vlucas/phpdotenv/src/Parser/Entry.php | 59 + .../phpdotenv/src/Parser/EntryParser.php | 363 ++ vendor/vlucas/phpdotenv/src/Parser/Lexer.php | 58 + vendor/vlucas/phpdotenv/src/Parser/Lines.php | 120 + vendor/vlucas/phpdotenv/src/Parser/Parser.php | 58 + .../phpdotenv/src/Parser/ParserInterface.php | 19 + vendor/vlucas/phpdotenv/src/Parser/Value.php | 101 + .../Repository/Adapter/AdapterInterface.php | 15 + .../src/Repository/Adapter/ApacheAdapter.php | 88 + .../src/Repository/Adapter/ArrayAdapter.php | 79 + .../Repository/Adapter/EnvConstAdapter.php | 88 + .../src/Repository/Adapter/GuardedWriter.php | 85 + .../Repository/Adapter/ImmutableWriter.php | 110 + .../src/Repository/Adapter/MultiReader.php | 48 + .../src/Repository/Adapter/MultiWriter.php | 64 + .../src/Repository/Adapter/PutenvAdapter.php | 102 + .../Repository/Adapter/ReaderInterface.php | 17 + .../Repository/Adapter/ReplacingWriter.php | 104 + .../Repository/Adapter/ServerConstAdapter.php | 88 + .../Repository/Adapter/WriterInterface.php | 27 + .../src/Repository/AdapterRepository.php | 107 + .../src/Repository/RepositoryBuilder.php | 272 ++ .../src/Repository/RepositoryInterface.php | 51 + .../vlucas/phpdotenv/src/Store/File/Paths.php | 44 + .../phpdotenv/src/Store/File/Reader.php | 81 + .../vlucas/phpdotenv/src/Store/FileStore.php | 72 + .../phpdotenv/src/Store/StoreBuilder.php | 141 + .../phpdotenv/src/Store/StoreInterface.php | 17 + .../phpdotenv/src/Store/StringStore.php | 41 + vendor/vlucas/phpdotenv/src/Util/Regex.php | 101 + vendor/vlucas/phpdotenv/src/Util/Str.php | 129 + vendor/vlucas/phpdotenv/src/Validator.php | 216 ++ vendor/workerman/coroutine/.gitignore | 5 + vendor/workerman/coroutine/LICENSE | 21 + vendor/workerman/coroutine/README.md | 3 + vendor/workerman/coroutine/composer.json | 32 + vendor/workerman/coroutine/src/Barrier.php | 65 + .../src/Barrier/BarrierInterface.php | 39 + .../workerman/coroutine/src/Barrier/Fiber.php | 85 + .../coroutine/src/Barrier/Swoole.php | 39 + .../workerman/coroutine/src/Barrier/Swow.php | 47 + vendor/workerman/coroutine/src/Channel.php | 114 + .../src/Channel/ChannelInterface.php | 76 + .../workerman/coroutine/src/Channel/Fiber.php | 252 ++ .../coroutine/src/Channel/Memory.php | 69 + .../coroutine/src/Channel/Swoole.php | 165 + .../workerman/coroutine/src/Channel/Swow.php | 110 + vendor/workerman/coroutine/src/Context.php | 90 + .../src/Context/ContextInterface.php | 50 + .../workerman/coroutine/src/Context/Fiber.php | 107 + .../coroutine/src/Context/Swoole.php | 63 + .../workerman/coroutine/src/Context/Swow.php | 81 + vendor/workerman/coroutine/src/Coroutine.php | 129 + .../src/Coroutine/CoroutineInterface.php | 90 + .../coroutine/src/Coroutine/Fiber.php | 154 + .../coroutine/src/Coroutine/Swoole.php | 148 + .../coroutine/src/Coroutine/Swow.php | 91 + .../coroutine/src/Exception/PoolException.php | 8 + vendor/workerman/coroutine/src/Locker.php | 66 + vendor/workerman/coroutine/src/Parallel.php | 117 + vendor/workerman/coroutine/src/Pool.php | 414 +++ .../workerman/coroutine/src/PoolInterface.php | 69 + .../src/Utils/DestructionWatcher.php | 67 + vendor/workerman/coroutine/src/WaitGroup.php | 77 + .../coroutine/src/WaitGroup/Fiber.php | 66 + .../coroutine/src/WaitGroup/Swoole.php | 61 + .../coroutine/src/WaitGroup/Swow.php | 64 + .../src/WaitGroup/WaitGroupInterface.php | 42 + vendor/workerman/coroutine/stubs/SwowStub.php | 36 + .../workerman/coroutine/tests/BarrierTest.php | 43 + .../workerman/coroutine/tests/ChannelTest.php | 313 ++ .../workerman/coroutine/tests/ContextTest.php | 169 + .../coroutine/tests/CoroutineTest.php | 184 + .../coroutine/tests/FiberChannelTest.php | 346 ++ .../workerman/coroutine/tests/LockerTest.php | 130 + .../coroutine/tests/ParallelTest.php | 329 ++ vendor/workerman/coroutine/tests/PoolTest.php | 678 ++++ .../coroutine/tests/WaitGroupTest.php | 56 + vendor/workerman/coroutine/tests/start.php | 109 + vendor/workerman/webman-framework/.gitignore | 5 + vendor/workerman/webman-framework/README.md | 5 + .../workerman/webman-framework/composer.json | 52 + vendor/workerman/webman-framework/src/App.php | 1384 +++++++ .../webman-framework/src/Bootstrap.php | 28 + .../workerman/webman-framework/src/Config.php | 322 ++ .../webman-framework/src/Container.php | 84 + .../webman-framework/src/Context.php | 24 + .../src/Exception/BusinessException.php | 117 + .../src/Exception/ExceptionHandler.php | 121 + .../Exception/ExceptionHandlerInterface.php | 35 + .../src/Exception/FileException.php | 25 + .../src/Exception/NotFoundException.php | 25 + .../workerman/webman-framework/src/File.php | 56 + .../src/Finder/ControllerFinder.php | 239 ++ .../webman-framework/src/Finder/FileInfo.php | 142 + .../webman-framework/src/Finder/Finder.php | 912 +++++ .../webman-framework/src/Http/Request.php | 433 +++ .../webman-framework/src/Http/Response.php | 89 + .../webman-framework/src/Http/UploadFile.php | 111 + .../webman-framework/src/Install.php | 59 + .../webman-framework/src/Middleware.php | 162 + .../src/MiddlewareInterface.php | 30 + .../workerman/webman-framework/src/Route.php | 858 +++++ .../webman-framework/src/Route/Route.php | 199 ++ .../src/Session/FileSessionHandler.php | 26 + .../Session/RedisClusterSessionHandler.php | 22 + .../src/Session/RedisSessionHandler.php | 26 + .../workerman/webman-framework/src/Util.php | 44 + .../workerman/webman-framework/src/View.php | 27 + .../workerman/webman-framework/src/start.php | 5 + .../webman-framework/src/support/App.php | 167 + .../src/support/Container.php | 47 + .../webman-framework/src/support/Context.php | 25 + .../webman-framework/src/support/Log.php | 143 + .../src/support/PharStream.php | 368 ++ .../webman-framework/src/support/Plugin.php | 124 + .../webman-framework/src/support/Request.php | 24 + .../webman-framework/src/support/Response.php | 24 + .../src/support/Translation.php | 108 + .../webman-framework/src/support/View.php | 35 + .../annotation/DisableDefaultRoute.php | 13 + .../src/support/annotation/Middleware.php | 41 + .../src/support/annotation/route/Any.php | 22 + .../src/support/annotation/route/Delete.php | 22 + .../annotation/route/DisableDefaultRoute.php | 13 + .../src/support/annotation/route/Get.php | 22 + .../src/support/annotation/route/Head.php | 22 + .../src/support/annotation/route/Options.php | 22 + .../src/support/annotation/route/Patch.php | 22 + .../src/support/annotation/route/Post.php | 22 + .../src/support/annotation/route/Put.php | 22 + .../src/support/annotation/route/Route.php | 40 + .../support/annotation/route/RouteGroup.php | 26 + .../src/support/bootstrap.php | 139 + .../src/support/bootstrap/Session.php | 61 + .../support/exception/BusinessException.php | 24 + .../src/support/exception/Handler.php | 43 + .../support/exception/InputTypeException.php | 24 + .../support/exception/InputValueException.php | 24 + .../exception/MissingInputException.php | 46 + .../support/exception/NotFoundException.php | 20 + .../exception/PageNotFoundException.php | 93 + .../webman-framework/src/support/helpers.php | 681 ++++ .../src/support/view/Blade.php | 84 + .../webman-framework/src/support/view/Raw.php | 79 + .../src/support/view/ThinkPHP.php | 87 + .../src/support/view/Twig.php | 87 + .../webman-framework/src/windows.php | 136 + .../tests/CoroutineControllerLoadTest.php | 117 + vendor/workerman/workerman/MIT-LICENSE.txt | 21 + vendor/workerman/workerman/README.md | 477 +++ vendor/workerman/workerman/SECURITY.md | 6 + vendor/workerman/workerman/composer.json | 65 + .../src/Connection/AsyncTcpConnection.php | 582 +++ .../src/Connection/AsyncUdpConnection.php | 222 ++ .../src/Connection/ConnectionInterface.php | 187 + .../src/Connection/TcpConnection.php | 1339 +++++++ .../src/Connection/UdpConnection.php | 246 ++ vendor/workerman/workerman/src/Events/Ev.php | 238 ++ .../workerman/workerman/src/Events/Event.php | 294 ++ .../workerman/src/Events/EventInterface.php | 143 + .../workerman/workerman/src/Events/Fiber.php | 276 ++ .../workerman/workerman/src/Events/Select.php | 492 +++ .../workerman/workerman/src/Events/Swoole.php | 298 ++ .../workerman/workerman/src/Events/Swow.php | 307 ++ .../workerman/src/Protocols/Frame.php | 66 + .../workerman/src/Protocols/Http.php | 518 +++ .../workerman/src/Protocols/Http/Chunk.php | 37 + .../workerman/src/Protocols/Http/Request.php | 847 +++++ .../workerman/src/Protocols/Http/Response.php | 591 +++ .../src/Protocols/Http/ServerSentEvents.php | 56 + .../workerman/src/Protocols/Http/Session.php | 464 +++ .../Http/Session/FileSessionHandler.php | 209 ++ .../Session/RedisClusterSessionHandler.php | 59 + .../Http/Session/RedisSessionHandler.php | 220 ++ .../Http/Session/SessionHandlerInterface.php | 117 + .../src/Protocols/ProtocolInterface.php | 55 + .../workerman/src/Protocols/Text.php | 76 + .../workerman/src/Protocols/Websocket.php | 581 +++ .../workerman/workerman/src/Protocols/Ws.php | 546 +++ vendor/workerman/workerman/src/Timer.php | 274 ++ vendor/workerman/workerman/src/Worker.php | 2876 +++++++++++++++ 1111 files changed, 153644 insertions(+), 7 deletions(-) create mode 100644 .env delete mode 100644 .gitignore create mode 100644 runtime/cache/framework/finder/php_files_91921f4982732bde0f9f40e4b3f846f7389ec7ea7b18c365741889027e0d3be5.php create mode 100644 runtime/logs/stdout.log create mode 100644 runtime/logs/webman-2026-11-26.log create mode 100644 runtime/logs/workerman.log create mode 100644 runtime/release-update.lock create mode 100644 runtime/sessions/session_4642ca1e97f07570602f6a23b52f53a8 create mode 100644 runtime/sessions/session_5d4813b2ce9ef52ca809292e2ca0a39d create mode 100644 runtime/sessions/session_9866b4738ae5a72c352c798a74a5bd67 create mode 100644 runtime/sessions/session_be3a99224d70dba62cfccfd756a26382 create mode 100644 runtime/sessions/session_f393e9966092010277f6c9a34d76b55a create mode 100644 runtime/webman.pid create mode 100644 storage/laysite.sqlite create mode 100644 storage/laysite.sqlite-shm create mode 100644 storage/laysite.sqlite-wal create mode 100644 storage/media/56e075e3c9857fbb7f39e35f89041583.png create mode 100644 storage/media/6e5c7e924efdb0106ee52ca13957320e.jpg create mode 100644 update.php create mode 100644 vendor/autoload.php create mode 100644 vendor/composer/ClassLoader.php create mode 100644 vendor/composer/InstalledVersions.php create mode 100644 vendor/composer/LICENSE create mode 100644 vendor/composer/autoload_classmap.php create mode 100644 vendor/composer/autoload_files.php create mode 100644 vendor/composer/autoload_namespaces.php create mode 100644 vendor/composer/autoload_psr4.php create mode 100644 vendor/composer/autoload_real.php create mode 100644 vendor/composer/autoload_static.php create mode 100644 vendor/composer/installed.json create mode 100644 vendor/composer/installed.php create mode 100644 vendor/composer/platform_check.php create mode 100644 vendor/dflydev/dot-access-data/CHANGELOG.md create mode 100644 vendor/dflydev/dot-access-data/LICENSE create mode 100644 vendor/dflydev/dot-access-data/README.md create mode 100644 vendor/dflydev/dot-access-data/composer.json create mode 100644 vendor/dflydev/dot-access-data/src/Data.php create mode 100644 vendor/dflydev/dot-access-data/src/DataInterface.php create mode 100644 vendor/dflydev/dot-access-data/src/Exception/DataException.php create mode 100644 vendor/dflydev/dot-access-data/src/Exception/InvalidPathException.php create mode 100644 vendor/dflydev/dot-access-data/src/Exception/MissingPathException.php create mode 100644 vendor/dflydev/dot-access-data/src/Util.php create mode 100644 vendor/firebase/php-jwt/CHANGELOG.md create mode 100644 vendor/firebase/php-jwt/LICENSE create mode 100644 vendor/firebase/php-jwt/README.md create mode 100644 vendor/firebase/php-jwt/VERSION create mode 100644 vendor/firebase/php-jwt/composer.json create mode 100644 vendor/firebase/php-jwt/src/BeforeValidException.php create mode 100644 vendor/firebase/php-jwt/src/CachedKeySet.php create mode 100644 vendor/firebase/php-jwt/src/ExpiredException.php create mode 100644 vendor/firebase/php-jwt/src/JWK.php create mode 100644 vendor/firebase/php-jwt/src/JWT.php create mode 100644 vendor/firebase/php-jwt/src/JWTExceptionWithPayloadInterface.php create mode 100644 vendor/firebase/php-jwt/src/Key.php create mode 100644 vendor/firebase/php-jwt/src/SignatureInvalidException.php create mode 100644 vendor/graham-campbell/result-type/LICENSE create mode 100644 vendor/graham-campbell/result-type/composer.json create mode 100644 vendor/graham-campbell/result-type/src/Error.php create mode 100644 vendor/graham-campbell/result-type/src/Result.php create mode 100644 vendor/graham-campbell/result-type/src/Success.php create mode 100644 vendor/guzzlehttp/guzzle/AGENTS.md create mode 100644 vendor/guzzlehttp/guzzle/CHANGELOG.md create mode 100644 vendor/guzzlehttp/guzzle/CLAUDE.md create mode 100644 vendor/guzzlehttp/guzzle/LICENSE create mode 100644 vendor/guzzlehttp/guzzle/README.md create mode 100644 vendor/guzzlehttp/guzzle/UPGRADING.md create mode 100644 vendor/guzzlehttp/guzzle/composer.json create mode 100644 vendor/guzzlehttp/guzzle/src/Auth/DigestAuth.php create mode 100644 vendor/guzzlehttp/guzzle/src/Auth/DigestChallenge.php create mode 100644 vendor/guzzlehttp/guzzle/src/AuthMiddleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/BodySummarizer.php create mode 100644 vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php create mode 100644 vendor/guzzlehttp/guzzle/src/Client.php create mode 100644 vendor/guzzlehttp/guzzle/src/ClientInterface.php create mode 100644 vendor/guzzlehttp/guzzle/src/ClientTrait.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php create mode 100644 vendor/guzzlehttp/guzzle/src/Env.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ClientException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ConnectException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ConnectTimeoutException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/HandlerClosedException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/InvalidArgumentException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/NetworkException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/NetworkTimeoutException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/RequestException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ResponseException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ResponseTimeoutException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ResponseTransferException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ServerException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/TooManyRedirectsException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/TransferException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/ChunkedBodyStream.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/Clock.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlShareHandleState.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlVersion.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/DeadlineSourceStream.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/DebugResource.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/DeclaredLengthStream.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/EncodedBodyStream.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/HostValidator.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/InflateBodyStream.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/Protocols.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/Proxy.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/ProxyEnv.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/RequestFraming.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/StreamTlsSessionCache.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/Timeout.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/TlsVersion.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/TransferByteCounter.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/TransportStream.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/UriDiagnostic.php create mode 100644 vendor/guzzlehttp/guzzle/src/HandlerStack.php create mode 100644 vendor/guzzlehttp/guzzle/src/HostIdentity.php create mode 100644 vendor/guzzlehttp/guzzle/src/Idn.php create mode 100644 vendor/guzzlehttp/guzzle/src/MessageFormatter.php create mode 100644 vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php create mode 100644 vendor/guzzlehttp/guzzle/src/Middleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/Multiplexing.php create mode 100644 vendor/guzzlehttp/guzzle/src/NonSerializableTrait.php create mode 100644 vendor/guzzlehttp/guzzle/src/Pool.php create mode 100644 vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/ProxyOptions.php create mode 100644 vendor/guzzlehttp/guzzle/src/ProxySelection.php create mode 100644 vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/RequestOptions.php create mode 100644 vendor/guzzlehttp/guzzle/src/RetryMiddleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/TransferStats.php create mode 100644 vendor/guzzlehttp/guzzle/src/TransportSharing.php create mode 100644 vendor/guzzlehttp/guzzle/src/Utils.php create mode 100644 vendor/guzzlehttp/promises/AGENTS.md create mode 100644 vendor/guzzlehttp/promises/CHANGELOG.md create mode 100644 vendor/guzzlehttp/promises/CLAUDE.md create mode 100644 vendor/guzzlehttp/promises/LICENSE create mode 100644 vendor/guzzlehttp/promises/README.md create mode 100644 vendor/guzzlehttp/promises/UPGRADING.md create mode 100644 vendor/guzzlehttp/promises/composer.json create mode 100644 vendor/guzzlehttp/promises/docs/implementation-notes.md create mode 100644 vendor/guzzlehttp/promises/docs/promise-api.md create mode 100644 vendor/guzzlehttp/promises/docs/promise-interoperability.md create mode 100644 vendor/guzzlehttp/promises/docs/promise-quick-start.md create mode 100644 vendor/guzzlehttp/promises/src/AggregateException.php create mode 100644 vendor/guzzlehttp/promises/src/CancellationException.php create mode 100644 vendor/guzzlehttp/promises/src/Coroutine.php create mode 100644 vendor/guzzlehttp/promises/src/Create.php create mode 100644 vendor/guzzlehttp/promises/src/Each.php create mode 100644 vendor/guzzlehttp/promises/src/EachPromise.php create mode 100644 vendor/guzzlehttp/promises/src/FulfilledPromise.php create mode 100644 vendor/guzzlehttp/promises/src/Is.php create mode 100644 vendor/guzzlehttp/promises/src/NonSerializableTrait.php create mode 100644 vendor/guzzlehttp/promises/src/Promise.php create mode 100644 vendor/guzzlehttp/promises/src/PromiseInterface.php create mode 100644 vendor/guzzlehttp/promises/src/PromisorInterface.php create mode 100644 vendor/guzzlehttp/promises/src/RejectedPromise.php create mode 100644 vendor/guzzlehttp/promises/src/RejectionException.php create mode 100644 vendor/guzzlehttp/promises/src/State.php create mode 100644 vendor/guzzlehttp/promises/src/TaskQueue.php create mode 100644 vendor/guzzlehttp/promises/src/TaskQueueInterface.php create mode 100644 vendor/guzzlehttp/promises/src/Utils.php create mode 100644 vendor/guzzlehttp/psr7/AGENTS.md create mode 100644 vendor/guzzlehttp/psr7/CHANGELOG.md create mode 100644 vendor/guzzlehttp/psr7/CLAUDE.md create mode 100644 vendor/guzzlehttp/psr7/LICENSE create mode 100644 vendor/guzzlehttp/psr7/README.md create mode 100644 vendor/guzzlehttp/psr7/UPGRADING.md create mode 100644 vendor/guzzlehttp/psr7/composer.json create mode 100644 vendor/guzzlehttp/psr7/docs/diagnostic-values.md create mode 100644 vendor/guzzlehttp/psr7/docs/error-scopes.md create mode 100644 vendor/guzzlehttp/psr7/docs/header-and-query-helpers.md create mode 100644 vendor/guzzlehttp/psr7/docs/message-helpers.md create mode 100644 vendor/guzzlehttp/psr7/docs/psr-17-factories.md create mode 100644 vendor/guzzlehttp/psr7/docs/psr-7-messages.md create mode 100644 vendor/guzzlehttp/psr7/docs/stream-helpers.md create mode 100644 vendor/guzzlehttp/psr7/docs/streams-and-decorators.md create mode 100644 vendor/guzzlehttp/psr7/docs/uri-and-mime-helpers.md create mode 100644 vendor/guzzlehttp/psr7/docs/uri-helpers.md create mode 100644 vendor/guzzlehttp/psr7/src/AppendStream.php create mode 100644 vendor/guzzlehttp/psr7/src/BufferStream.php create mode 100644 vendor/guzzlehttp/psr7/src/CachingStream.php create mode 100644 vendor/guzzlehttp/psr7/src/DiagnosticValue.php create mode 100644 vendor/guzzlehttp/psr7/src/DroppingStream.php create mode 100644 vendor/guzzlehttp/psr7/src/ErrorScope.php create mode 100644 vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php create mode 100644 vendor/guzzlehttp/psr7/src/Exception/TimeoutException.php create mode 100644 vendor/guzzlehttp/psr7/src/FnStream.php create mode 100644 vendor/guzzlehttp/psr7/src/Header.php create mode 100644 vendor/guzzlehttp/psr7/src/HttpFactory.php create mode 100644 vendor/guzzlehttp/psr7/src/Idna.php create mode 100644 vendor/guzzlehttp/psr7/src/InflateStream.php create mode 100644 vendor/guzzlehttp/psr7/src/Integers.php create mode 100644 vendor/guzzlehttp/psr7/src/LazyOpenStream.php create mode 100644 vendor/guzzlehttp/psr7/src/LimitStream.php create mode 100644 vendor/guzzlehttp/psr7/src/Message.php create mode 100644 vendor/guzzlehttp/psr7/src/MessageParser.php create mode 100644 vendor/guzzlehttp/psr7/src/MessageTrait.php create mode 100644 vendor/guzzlehttp/psr7/src/MimeType.php create mode 100644 vendor/guzzlehttp/psr7/src/MultipartStream.php create mode 100644 vendor/guzzlehttp/psr7/src/NoSeekStream.php create mode 100644 vendor/guzzlehttp/psr7/src/NonSerializableStreamTrait.php create mode 100644 vendor/guzzlehttp/psr7/src/PumpStream.php create mode 100644 vendor/guzzlehttp/psr7/src/Query.php create mode 100644 vendor/guzzlehttp/psr7/src/ReadFailureCapturingStream.php create mode 100644 vendor/guzzlehttp/psr7/src/Request.php create mode 100644 vendor/guzzlehttp/psr7/src/Response.php create mode 100644 vendor/guzzlehttp/psr7/src/Rfc3986.php create mode 100644 vendor/guzzlehttp/psr7/src/Rfc9110.php create mode 100644 vendor/guzzlehttp/psr7/src/Rfc9112.php create mode 100644 vendor/guzzlehttp/psr7/src/ServerRequest.php create mode 100644 vendor/guzzlehttp/psr7/src/ServerRequestGlobalsFactory.php create mode 100644 vendor/guzzlehttp/psr7/src/Stream.php create mode 100644 vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php create mode 100644 vendor/guzzlehttp/psr7/src/StreamTimeout.php create mode 100644 vendor/guzzlehttp/psr7/src/StreamWrapper.php create mode 100644 vendor/guzzlehttp/psr7/src/UploadedFile.php create mode 100644 vendor/guzzlehttp/psr7/src/UploadedFileNormalizer.php create mode 100644 vendor/guzzlehttp/psr7/src/Uri.php create mode 100644 vendor/guzzlehttp/psr7/src/UriComparator.php create mode 100644 vendor/guzzlehttp/psr7/src/UriNormalizer.php create mode 100644 vendor/guzzlehttp/psr7/src/UriParser.php create mode 100644 vendor/guzzlehttp/psr7/src/UriRedactor.php create mode 100644 vendor/guzzlehttp/psr7/src/UriResolver.php create mode 100644 vendor/guzzlehttp/psr7/src/Utils.php create mode 100644 vendor/league/commonmark/.phpstorm.meta.php create mode 100644 vendor/league/commonmark/CHANGELOG.md create mode 100644 vendor/league/commonmark/LICENSE create mode 100644 vendor/league/commonmark/README.md create mode 100644 vendor/league/commonmark/composer.json create mode 100644 vendor/league/commonmark/src/CommonMarkConverter.php create mode 100644 vendor/league/commonmark/src/ConverterInterface.php create mode 100644 vendor/league/commonmark/src/Delimiter/Bracket.php create mode 100644 vendor/league/commonmark/src/Delimiter/Delimiter.php create mode 100644 vendor/league/commonmark/src/Delimiter/DelimiterInterface.php create mode 100644 vendor/league/commonmark/src/Delimiter/DelimiterParser.php create mode 100644 vendor/league/commonmark/src/Delimiter/DelimiterStack.php create mode 100644 vendor/league/commonmark/src/Delimiter/Processor/CacheableDelimiterProcessorInterface.php create mode 100644 vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollection.php create mode 100644 vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollectionInterface.php create mode 100644 vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorInterface.php create mode 100644 vendor/league/commonmark/src/Delimiter/Processor/StaggeredDelimiterProcessor.php create mode 100644 vendor/league/commonmark/src/Environment/Environment.php create mode 100644 vendor/league/commonmark/src/Environment/EnvironmentAwareInterface.php create mode 100644 vendor/league/commonmark/src/Environment/EnvironmentBuilderInterface.php create mode 100644 vendor/league/commonmark/src/Environment/EnvironmentInterface.php create mode 100644 vendor/league/commonmark/src/Event/AbstractEvent.php create mode 100644 vendor/league/commonmark/src/Event/DocumentParsedEvent.php create mode 100644 vendor/league/commonmark/src/Event/DocumentPreParsedEvent.php create mode 100644 vendor/league/commonmark/src/Event/DocumentPreRenderEvent.php create mode 100644 vendor/league/commonmark/src/Event/DocumentRenderedEvent.php create mode 100644 vendor/league/commonmark/src/Event/ListenerData.php create mode 100644 vendor/league/commonmark/src/Exception/AlreadyInitializedException.php create mode 100644 vendor/league/commonmark/src/Exception/CommonMarkException.php create mode 100644 vendor/league/commonmark/src/Exception/IOException.php create mode 100644 vendor/league/commonmark/src/Exception/InvalidArgumentException.php create mode 100644 vendor/league/commonmark/src/Exception/LogicException.php create mode 100644 vendor/league/commonmark/src/Exception/MissingDependencyException.php create mode 100644 vendor/league/commonmark/src/Exception/UnexpectedEncodingException.php create mode 100644 vendor/league/commonmark/src/Extension/Attributes/AttributesExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Attributes/Event/AttributesListener.php create mode 100644 vendor/league/commonmark/src/Extension/Attributes/Node/Attributes.php create mode 100644 vendor/league/commonmark/src/Extension/Attributes/Node/AttributesInline.php create mode 100644 vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockContinueParser.php create mode 100644 vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesInlineParser.php create mode 100644 vendor/league/commonmark/src/Extension/Attributes/Util/AttributesHelper.php create mode 100644 vendor/league/commonmark/src/Extension/Autolink/AutolinkExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Autolink/EmailAutolinkParser.php create mode 100644 vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/CommonMarkCoreExtension.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Delimiter/Processor/EmphasisDelimiterProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/BlockQuote.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/FencedCode.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/Heading.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/HtmlBlock.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/IndentedCode.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListBlock.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListData.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListItem.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ThematicBreak.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/AbstractWebResource.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Code.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Emphasis.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/HtmlInline.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Image.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Link.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Strong.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListItemParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/AutolinkParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BacktickParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BangParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/CloseBracketParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EntityParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EscapableParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/HtmlInlineParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/OpenBracketParser.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/BlockQuoteRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/FencedCodeRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HeadingRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HtmlBlockRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/IndentedCodeRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListBlockRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListItemRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ThematicBreakRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/CodeRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/EmphasisRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/HtmlInlineRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/ImageRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/LinkRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/StrongRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/ConfigurableExtensionInterface.php create mode 100644 vendor/league/commonmark/src/Extension/DefaultAttributes/ApplyDefaultAttributesProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/DefaultAttributes/DefaultAttributesExtension.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/DescriptionListExtension.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Event/ConsecutiveDescriptionListMerger.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Event/LooseDescriptionHandler.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Node/Description.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionList.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionTerm.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionContinueParser.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionListContinueParser.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionTermContinueParser.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionListRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionTermRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlExtension.php create mode 100644 vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/Bridge/OscaroteroEmbedAdapter.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/DomainFilteringAdapter.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/Embed.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/EmbedAdapterInterface.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/EmbedExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/EmbedParser.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/EmbedProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/EmbedRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Embed/EmbedStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/ExtensionInterface.php create mode 100644 vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkExtension.php create mode 100644 vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Event/AnonymousFootnotesListener.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Event/FixOrphanedFootnotesAndRefsListener.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Event/GatherFootnotesListener.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Event/NumberFootnotesListener.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/FootnoteExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Node/Footnote.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteBackref.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteContainer.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteRef.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Parser/AnonymousFootnoteRefParser.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteParser.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteRefParser.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteContainerRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/Data/FrontMatterDataParserInterface.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/Data/LibYamlFrontMatterParser.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/Data/SymfonyYamlFrontMatterParser.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/Exception/InvalidFrontMatterException.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterExtension.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParser.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParserInterface.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterProviderInterface.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/Input/MarkdownInputWithFrontMatter.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPostRenderListener.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPreParser.php create mode 100644 vendor/league/commonmark/src/Extension/FrontMatter/Output/RenderedContentWithFrontMatter.php create mode 100644 vendor/league/commonmark/src/Extension/GithubFlavoredMarkdownExtension.php create mode 100644 vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalink.php create mode 100644 vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkExtension.php create mode 100644 vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Highlight/HighlightExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Highlight/Mark.php create mode 100644 vendor/league/commonmark/src/Extension/Highlight/MarkDelimiterProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/Highlight/MarkRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/InlinesOnly/ChildRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Mention/Generator/CallbackGenerator.php create mode 100644 vendor/league/commonmark/src/Extension/Mention/Generator/MentionGeneratorInterface.php create mode 100644 vendor/league/commonmark/src/Extension/Mention/Generator/StringTemplateLinkGenerator.php create mode 100644 vendor/league/commonmark/src/Extension/Mention/Mention.php create mode 100644 vendor/league/commonmark/src/Extension/Mention/MentionExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Mention/MentionParser.php create mode 100644 vendor/league/commonmark/src/Extension/NormalizeHeadings/NormalizeHeadingsExtension.php create mode 100644 vendor/league/commonmark/src/Extension/NormalizeHeadings/NormalizeHeadingsProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/SmartPunct/DashParser.php create mode 100644 vendor/league/commonmark/src/Extension/SmartPunct/EllipsesParser.php create mode 100644 vendor/league/commonmark/src/Extension/SmartPunct/Quote.php create mode 100644 vendor/league/commonmark/src/Extension/SmartPunct/QuoteParser.php create mode 100644 vendor/league/commonmark/src/Extension/SmartPunct/QuoteProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/SmartPunct/ReplaceUnpairedQuotesListener.php create mode 100644 vendor/league/commonmark/src/Extension/SmartPunct/SmartPunctExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Strikethrough/Strikethrough.php create mode 100644 vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughDelimiterProcessor.php create mode 100644 vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Table/Table.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableCell.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableCellRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableExtension.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableParser.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableRow.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableRowRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableSection.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableSectionRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/Table/TableStartParser.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContents.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsPlaceholder.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsReference.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/AsIsNormalizerStrategy.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/FlatNormalizerStrategy.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/NormalizerStrategyInterface.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/RelativeNormalizerStrategy.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsBuilder.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsExtension.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGenerator.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGeneratorInterface.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderParser.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsReferenceRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderCache.php create mode 100644 vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderer.php create mode 100644 vendor/league/commonmark/src/Extension/TaskList/TaskListExtension.php create mode 100644 vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarker.php create mode 100644 vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php create mode 100644 vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerRenderer.php create mode 100644 vendor/league/commonmark/src/GithubFlavoredMarkdownConverter.php create mode 100644 vendor/league/commonmark/src/Input/MarkdownInput.php create mode 100644 vendor/league/commonmark/src/Input/MarkdownInputInterface.php create mode 100644 vendor/league/commonmark/src/MarkdownConverter.php create mode 100644 vendor/league/commonmark/src/MarkdownConverterInterface.php create mode 100644 vendor/league/commonmark/src/Node/Block/AbstractBlock.php create mode 100644 vendor/league/commonmark/src/Node/Block/Document.php create mode 100644 vendor/league/commonmark/src/Node/Block/Paragraph.php create mode 100644 vendor/league/commonmark/src/Node/Block/TightBlockInterface.php create mode 100644 vendor/league/commonmark/src/Node/Inline/AbstractInline.php create mode 100644 vendor/league/commonmark/src/Node/Inline/AbstractStringContainer.php create mode 100644 vendor/league/commonmark/src/Node/Inline/AdjacentTextMerger.php create mode 100644 vendor/league/commonmark/src/Node/Inline/DelimitedInterface.php create mode 100644 vendor/league/commonmark/src/Node/Inline/Newline.php create mode 100644 vendor/league/commonmark/src/Node/Inline/Text.php create mode 100644 vendor/league/commonmark/src/Node/Node.php create mode 100644 vendor/league/commonmark/src/Node/NodeIterator.php create mode 100644 vendor/league/commonmark/src/Node/NodeWalker.php create mode 100644 vendor/league/commonmark/src/Node/NodeWalkerEvent.php create mode 100644 vendor/league/commonmark/src/Node/Query.php create mode 100644 vendor/league/commonmark/src/Node/Query/AndExpr.php create mode 100644 vendor/league/commonmark/src/Node/Query/ExpressionInterface.php create mode 100644 vendor/league/commonmark/src/Node/Query/OrExpr.php create mode 100644 vendor/league/commonmark/src/Node/RawMarkupContainerInterface.php create mode 100644 vendor/league/commonmark/src/Node/StringContainerHelper.php create mode 100644 vendor/league/commonmark/src/Node/StringContainerInterface.php create mode 100644 vendor/league/commonmark/src/Normalizer/SlugNormalizer.php create mode 100644 vendor/league/commonmark/src/Normalizer/TextNormalizer.php create mode 100644 vendor/league/commonmark/src/Normalizer/TextNormalizerInterface.php create mode 100644 vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizer.php create mode 100644 vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizerInterface.php create mode 100644 vendor/league/commonmark/src/Output/RenderedContent.php create mode 100644 vendor/league/commonmark/src/Output/RenderedContentInterface.php create mode 100644 vendor/league/commonmark/src/Parser/Block/AbstractBlockContinueParser.php create mode 100644 vendor/league/commonmark/src/Parser/Block/BlockContinue.php create mode 100644 vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php create mode 100644 vendor/league/commonmark/src/Parser/Block/BlockContinueParserWithInlinesInterface.php create mode 100644 vendor/league/commonmark/src/Parser/Block/BlockStart.php create mode 100644 vendor/league/commonmark/src/Parser/Block/BlockStartParserInterface.php create mode 100644 vendor/league/commonmark/src/Parser/Block/DocumentBlockParser.php create mode 100644 vendor/league/commonmark/src/Parser/Block/ParagraphParser.php create mode 100644 vendor/league/commonmark/src/Parser/Block/SkipLinesStartingWithLettersParser.php create mode 100644 vendor/league/commonmark/src/Parser/Cursor.php create mode 100644 vendor/league/commonmark/src/Parser/CursorState.php create mode 100644 vendor/league/commonmark/src/Parser/Inline/InlineParserInterface.php create mode 100644 vendor/league/commonmark/src/Parser/Inline/InlineParserMatch.php create mode 100644 vendor/league/commonmark/src/Parser/Inline/NewlineParser.php create mode 100644 vendor/league/commonmark/src/Parser/InlineParserContext.php create mode 100644 vendor/league/commonmark/src/Parser/InlineParserEngine.php create mode 100644 vendor/league/commonmark/src/Parser/InlineParserEngineInterface.php create mode 100644 vendor/league/commonmark/src/Parser/MarkdownParser.php create mode 100644 vendor/league/commonmark/src/Parser/MarkdownParserInterface.php create mode 100644 vendor/league/commonmark/src/Parser/MarkdownParserState.php create mode 100644 vendor/league/commonmark/src/Parser/MarkdownParserStateInterface.php create mode 100644 vendor/league/commonmark/src/Parser/ParserLogicException.php create mode 100644 vendor/league/commonmark/src/Reference/MemoryLimitedReferenceMap.php create mode 100644 vendor/league/commonmark/src/Reference/Reference.php create mode 100644 vendor/league/commonmark/src/Reference/ReferenceInterface.php create mode 100644 vendor/league/commonmark/src/Reference/ReferenceMap.php create mode 100644 vendor/league/commonmark/src/Reference/ReferenceMapInterface.php create mode 100644 vendor/league/commonmark/src/Reference/ReferenceParser.php create mode 100644 vendor/league/commonmark/src/Reference/ReferenceableInterface.php create mode 100644 vendor/league/commonmark/src/Renderer/Block/DocumentRenderer.php create mode 100644 vendor/league/commonmark/src/Renderer/Block/ParagraphRenderer.php create mode 100644 vendor/league/commonmark/src/Renderer/ChildNodeRendererInterface.php create mode 100644 vendor/league/commonmark/src/Renderer/DocumentRendererInterface.php create mode 100644 vendor/league/commonmark/src/Renderer/HtmlDecorator.php create mode 100644 vendor/league/commonmark/src/Renderer/HtmlRenderer.php create mode 100644 vendor/league/commonmark/src/Renderer/Inline/NewlineRenderer.php create mode 100644 vendor/league/commonmark/src/Renderer/Inline/TextRenderer.php create mode 100644 vendor/league/commonmark/src/Renderer/MarkdownRendererInterface.php create mode 100644 vendor/league/commonmark/src/Renderer/NoMatchingRendererException.php create mode 100644 vendor/league/commonmark/src/Renderer/NodeRendererInterface.php create mode 100644 vendor/league/commonmark/src/Util/ArrayCollection.php create mode 100644 vendor/league/commonmark/src/Util/Html5EntityDecoder.php create mode 100644 vendor/league/commonmark/src/Util/HtmlElement.php create mode 100644 vendor/league/commonmark/src/Util/HtmlFilter.php create mode 100644 vendor/league/commonmark/src/Util/LinkParserHelper.php create mode 100644 vendor/league/commonmark/src/Util/PrioritizedList.php create mode 100644 vendor/league/commonmark/src/Util/RegexHelper.php create mode 100644 vendor/league/commonmark/src/Util/SpecReader.php create mode 100644 vendor/league/commonmark/src/Util/UrlEncoder.php create mode 100644 vendor/league/commonmark/src/Util/Xml.php create mode 100644 vendor/league/commonmark/src/Xml/FallbackNodeXmlRenderer.php create mode 100644 vendor/league/commonmark/src/Xml/MarkdownToXmlConverter.php create mode 100644 vendor/league/commonmark/src/Xml/XmlNodeRendererInterface.php create mode 100644 vendor/league/commonmark/src/Xml/XmlRenderer.php create mode 100644 vendor/league/config/CHANGELOG.md create mode 100644 vendor/league/config/LICENSE.md create mode 100644 vendor/league/config/README.md create mode 100644 vendor/league/config/composer.json create mode 100644 vendor/league/config/src/Configuration.php create mode 100644 vendor/league/config/src/ConfigurationAwareInterface.php create mode 100644 vendor/league/config/src/ConfigurationBuilderInterface.php create mode 100644 vendor/league/config/src/ConfigurationInterface.php create mode 100644 vendor/league/config/src/ConfigurationProviderInterface.php create mode 100644 vendor/league/config/src/Exception/ConfigurationExceptionInterface.php create mode 100644 vendor/league/config/src/Exception/InvalidConfigurationException.php create mode 100644 vendor/league/config/src/Exception/UnknownOptionException.php create mode 100644 vendor/league/config/src/Exception/ValidationException.php create mode 100644 vendor/league/config/src/MutableConfigurationInterface.php create mode 100644 vendor/league/config/src/ReadOnlyConfiguration.php create mode 100644 vendor/league/config/src/SchemaBuilderInterface.php create mode 100644 vendor/league/oauth2-client/LICENSE create mode 100644 vendor/league/oauth2-client/README.md create mode 100644 vendor/league/oauth2-client/composer.json create mode 100644 vendor/league/oauth2-client/phpunit.xml.dist create mode 100644 vendor/league/oauth2-client/src/Grant/AbstractGrant.php create mode 100644 vendor/league/oauth2-client/src/Grant/AuthorizationCode.php create mode 100644 vendor/league/oauth2-client/src/Grant/ClientCredentials.php create mode 100644 vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php create mode 100644 vendor/league/oauth2-client/src/Grant/GrantFactory.php create mode 100644 vendor/league/oauth2-client/src/Grant/Password.php create mode 100644 vendor/league/oauth2-client/src/Grant/RefreshToken.php create mode 100644 vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php create mode 100644 vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php create mode 100644 vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php create mode 100644 vendor/league/oauth2-client/src/Provider/AbstractProvider.php create mode 100644 vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php create mode 100644 vendor/league/oauth2-client/src/Provider/GenericProvider.php create mode 100644 vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php create mode 100644 vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php create mode 100644 vendor/league/oauth2-client/src/Token/AccessToken.php create mode 100644 vendor/league/oauth2-client/src/Token/AccessTokenInterface.php create mode 100644 vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php create mode 100644 vendor/league/oauth2-client/src/Token/SettableRefreshTokenInterface.php create mode 100644 vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php create mode 100644 vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php create mode 100644 vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php create mode 100644 vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php create mode 100644 vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php create mode 100644 vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php create mode 100644 vendor/league/oauth2-client/src/Tool/RequestFactory.php create mode 100644 vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php create mode 100644 vendor/monolog/monolog/CHANGELOG.md create mode 100644 vendor/monolog/monolog/LICENSE create mode 100644 vendor/monolog/monolog/README.md create mode 100644 vendor/monolog/monolog/composer.json create mode 100644 vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Attribute/WithMonologChannel.php create mode 100644 vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php create mode 100644 vendor/monolog/monolog/src/Monolog/ErrorHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/RedactingFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/SyslogFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/WrappingFormatterInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FrankenPhpHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/Handler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/LogMonsterHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/JsonSerializableDateTimeImmutable.php create mode 100644 vendor/monolog/monolog/src/Monolog/Level.php create mode 100644 vendor/monolog/monolog/src/Monolog/LogRecord.php create mode 100644 vendor/monolog/monolog/src/Monolog/Logger.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/ClosureContextProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/LoadAverageProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Registry.php create mode 100644 vendor/monolog/monolog/src/Monolog/ResettableInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/SignalHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Test/MonologTestCase.php create mode 100644 vendor/monolog/monolog/src/Monolog/Test/TestCase.php create mode 100644 vendor/monolog/monolog/src/Monolog/Utils.php create mode 100644 vendor/nette/schema/composer.json create mode 100644 vendor/nette/schema/license.md create mode 100644 vendor/nette/schema/readme.md create mode 100644 vendor/nette/schema/src/Schema/Context.php create mode 100644 vendor/nette/schema/src/Schema/DynamicParameter.php create mode 100644 vendor/nette/schema/src/Schema/Elements/AnyOf.php create mode 100644 vendor/nette/schema/src/Schema/Elements/ArrayType.php create mode 100644 vendor/nette/schema/src/Schema/Elements/Base.php create mode 100644 vendor/nette/schema/src/Schema/Elements/EnumType.php create mode 100644 vendor/nette/schema/src/Schema/Elements/NumberType.php create mode 100644 vendor/nette/schema/src/Schema/Elements/StringType.php create mode 100644 vendor/nette/schema/src/Schema/Elements/Structure.php create mode 100644 vendor/nette/schema/src/Schema/Elements/TupleType.php create mode 100644 vendor/nette/schema/src/Schema/Elements/Type.php create mode 100644 vendor/nette/schema/src/Schema/Expect.php create mode 100644 vendor/nette/schema/src/Schema/Helpers.php create mode 100644 vendor/nette/schema/src/Schema/JsonSchema.php create mode 100644 vendor/nette/schema/src/Schema/Message.php create mode 100644 vendor/nette/schema/src/Schema/Processor.php create mode 100644 vendor/nette/schema/src/Schema/Schema.php create mode 100644 vendor/nette/schema/src/Schema/TypeExpression.php create mode 100644 vendor/nette/schema/src/Schema/ValidationException.php create mode 100644 vendor/nette/schema/src/Schema/enums.php create mode 100644 vendor/nette/utils/.phpstorm.meta.php create mode 100644 vendor/nette/utils/composer.json create mode 100644 vendor/nette/utils/license.md create mode 100644 vendor/nette/utils/readme.md create mode 100644 vendor/nette/utils/src/HtmlStringable.php create mode 100644 vendor/nette/utils/src/Iterators/CachingIterator.php create mode 100644 vendor/nette/utils/src/Iterators/Mapper.php create mode 100644 vendor/nette/utils/src/SmartObject.php create mode 100644 vendor/nette/utils/src/StaticClass.php create mode 100644 vendor/nette/utils/src/Translator.php create mode 100644 vendor/nette/utils/src/Utils/ArrayHash.php create mode 100644 vendor/nette/utils/src/Utils/ArrayList.php create mode 100644 vendor/nette/utils/src/Utils/Arrays.php create mode 100644 vendor/nette/utils/src/Utils/Callback.php create mode 100644 vendor/nette/utils/src/Utils/DateTime.php create mode 100644 vendor/nette/utils/src/Utils/DateTimeImmutable.php create mode 100644 vendor/nette/utils/src/Utils/FileInfo.php create mode 100644 vendor/nette/utils/src/Utils/FileSystem.php create mode 100644 vendor/nette/utils/src/Utils/Finder.php create mode 100644 vendor/nette/utils/src/Utils/Floats.php create mode 100644 vendor/nette/utils/src/Utils/Helpers.php create mode 100644 vendor/nette/utils/src/Utils/Html.php create mode 100644 vendor/nette/utils/src/Utils/Image.php create mode 100644 vendor/nette/utils/src/Utils/ImageColor.php create mode 100644 vendor/nette/utils/src/Utils/ImageType.php create mode 100644 vendor/nette/utils/src/Utils/Iterables.php create mode 100644 vendor/nette/utils/src/Utils/Json.php create mode 100644 vendor/nette/utils/src/Utils/ObjectHelpers.php create mode 100644 vendor/nette/utils/src/Utils/Paginator.php create mode 100644 vendor/nette/utils/src/Utils/Process.php create mode 100644 vendor/nette/utils/src/Utils/Random.php create mode 100644 vendor/nette/utils/src/Utils/Reflection.php create mode 100644 vendor/nette/utils/src/Utils/ReflectionMethod.php create mode 100644 vendor/nette/utils/src/Utils/Strings.php create mode 100644 vendor/nette/utils/src/Utils/Type.php create mode 100644 vendor/nette/utils/src/Utils/Validators.php create mode 100644 vendor/nette/utils/src/Utils/exceptions.php create mode 100644 vendor/nette/utils/src/compatibility.php create mode 100644 vendor/nette/utils/src/exceptions.php create mode 100644 vendor/nikic/fast-route/.hhconfig create mode 100644 vendor/nikic/fast-route/FastRoute.hhi create mode 100644 vendor/nikic/fast-route/LICENSE create mode 100644 vendor/nikic/fast-route/README.md create mode 100644 vendor/nikic/fast-route/composer.json create mode 100644 vendor/nikic/fast-route/src/BadRouteException.php create mode 100644 vendor/nikic/fast-route/src/DataGenerator.php create mode 100644 vendor/nikic/fast-route/src/DataGenerator/CharCountBased.php create mode 100644 vendor/nikic/fast-route/src/DataGenerator/GroupCountBased.php create mode 100644 vendor/nikic/fast-route/src/DataGenerator/GroupPosBased.php create mode 100644 vendor/nikic/fast-route/src/DataGenerator/MarkBased.php create mode 100644 vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php create mode 100644 vendor/nikic/fast-route/src/Dispatcher.php create mode 100644 vendor/nikic/fast-route/src/Dispatcher/CharCountBased.php create mode 100644 vendor/nikic/fast-route/src/Dispatcher/GroupCountBased.php create mode 100644 vendor/nikic/fast-route/src/Dispatcher/GroupPosBased.php create mode 100644 vendor/nikic/fast-route/src/Dispatcher/MarkBased.php create mode 100644 vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php create mode 100644 vendor/nikic/fast-route/src/Route.php create mode 100644 vendor/nikic/fast-route/src/RouteCollector.php create mode 100644 vendor/nikic/fast-route/src/RouteParser.php create mode 100644 vendor/nikic/fast-route/src/RouteParser/Std.php create mode 100644 vendor/nikic/fast-route/src/bootstrap.php create mode 100644 vendor/nikic/fast-route/src/functions.php create mode 100644 vendor/phpoption/phpoption/LICENSE create mode 100644 vendor/phpoption/phpoption/composer.json create mode 100644 vendor/phpoption/phpoption/src/PhpOption/LazyOption.php create mode 100644 vendor/phpoption/phpoption/src/PhpOption/None.php create mode 100644 vendor/phpoption/phpoption/src/PhpOption/Option.php create mode 100644 vendor/phpoption/phpoption/src/PhpOption/Some.php create mode 100644 vendor/psr/container/.gitignore create mode 100644 vendor/psr/container/LICENSE create mode 100644 vendor/psr/container/README.md create mode 100644 vendor/psr/container/composer.json create mode 100644 vendor/psr/container/src/ContainerExceptionInterface.php create mode 100644 vendor/psr/container/src/ContainerInterface.php create mode 100644 vendor/psr/container/src/NotFoundExceptionInterface.php create mode 100644 vendor/psr/event-dispatcher/.editorconfig create mode 100644 vendor/psr/event-dispatcher/.gitignore create mode 100644 vendor/psr/event-dispatcher/LICENSE create mode 100644 vendor/psr/event-dispatcher/README.md create mode 100644 vendor/psr/event-dispatcher/composer.json create mode 100644 vendor/psr/event-dispatcher/src/EventDispatcherInterface.php create mode 100644 vendor/psr/event-dispatcher/src/ListenerProviderInterface.php create mode 100644 vendor/psr/event-dispatcher/src/StoppableEventInterface.php create mode 100644 vendor/psr/http-client/CHANGELOG.md create mode 100644 vendor/psr/http-client/LICENSE create mode 100644 vendor/psr/http-client/README.md create mode 100644 vendor/psr/http-client/composer.json create mode 100644 vendor/psr/http-client/src/ClientExceptionInterface.php create mode 100644 vendor/psr/http-client/src/ClientInterface.php create mode 100644 vendor/psr/http-client/src/NetworkExceptionInterface.php create mode 100644 vendor/psr/http-client/src/RequestExceptionInterface.php create mode 100644 vendor/psr/http-factory/LICENSE create mode 100644 vendor/psr/http-factory/README.md create mode 100644 vendor/psr/http-factory/composer.json create mode 100644 vendor/psr/http-factory/src/RequestFactoryInterface.php create mode 100644 vendor/psr/http-factory/src/ResponseFactoryInterface.php create mode 100644 vendor/psr/http-factory/src/ServerRequestFactoryInterface.php create mode 100644 vendor/psr/http-factory/src/StreamFactoryInterface.php create mode 100644 vendor/psr/http-factory/src/UploadedFileFactoryInterface.php create mode 100644 vendor/psr/http-factory/src/UriFactoryInterface.php create mode 100644 vendor/psr/http-message/CHANGELOG.md create mode 100644 vendor/psr/http-message/LICENSE create mode 100644 vendor/psr/http-message/README.md create mode 100644 vendor/psr/http-message/composer.json create mode 100644 vendor/psr/http-message/docs/PSR7-Interfaces.md create mode 100644 vendor/psr/http-message/docs/PSR7-Usage.md create mode 100644 vendor/psr/http-message/src/MessageInterface.php create mode 100644 vendor/psr/http-message/src/RequestInterface.php create mode 100644 vendor/psr/http-message/src/ResponseInterface.php create mode 100644 vendor/psr/http-message/src/ServerRequestInterface.php create mode 100644 vendor/psr/http-message/src/StreamInterface.php create mode 100644 vendor/psr/http-message/src/UploadedFileInterface.php create mode 100644 vendor/psr/http-message/src/UriInterface.php create mode 100644 vendor/psr/log/LICENSE create mode 100644 vendor/psr/log/README.md create mode 100644 vendor/psr/log/composer.json create mode 100644 vendor/psr/log/src/AbstractLogger.php create mode 100644 vendor/psr/log/src/InvalidArgumentException.php create mode 100644 vendor/psr/log/src/LogLevel.php create mode 100644 vendor/psr/log/src/LoggerAwareInterface.php create mode 100644 vendor/psr/log/src/LoggerAwareTrait.php create mode 100644 vendor/psr/log/src/LoggerInterface.php create mode 100644 vendor/psr/log/src/LoggerTrait.php create mode 100644 vendor/psr/log/src/NullLogger.php create mode 100644 vendor/symfony/deprecation-contracts/CHANGELOG.md create mode 100644 vendor/symfony/deprecation-contracts/LICENSE create mode 100644 vendor/symfony/deprecation-contracts/README.md create mode 100644 vendor/symfony/deprecation-contracts/composer.json create mode 100644 vendor/symfony/deprecation-contracts/function.php create mode 100644 vendor/symfony/polyfill-ctype/Ctype.php create mode 100644 vendor/symfony/polyfill-ctype/LICENSE create mode 100644 vendor/symfony/polyfill-ctype/README.md create mode 100644 vendor/symfony/polyfill-ctype/bootstrap.php create mode 100644 vendor/symfony/polyfill-ctype/bootstrap80.php create mode 100644 vendor/symfony/polyfill-ctype/composer.json create mode 100644 vendor/symfony/polyfill-mbstring/LICENSE create mode 100644 vendor/symfony/polyfill-mbstring/Mbstring.php create mode 100644 vendor/symfony/polyfill-mbstring/README.md create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/eastAsianWidthRegexp.php create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/titleCase.php create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.php create mode 100644 vendor/symfony/polyfill-mbstring/bootstrap.php create mode 100644 vendor/symfony/polyfill-mbstring/bootstrap72.php create mode 100644 vendor/symfony/polyfill-mbstring/bootstrap80.php create mode 100644 vendor/symfony/polyfill-mbstring/composer.json create mode 100644 vendor/symfony/polyfill-php80/LICENSE create mode 100644 vendor/symfony/polyfill-php80/Php80.php create mode 100644 vendor/symfony/polyfill-php80/PhpToken.php create mode 100644 vendor/symfony/polyfill-php80/README.md create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php create mode 100644 vendor/symfony/polyfill-php80/bootstrap.php create mode 100644 vendor/symfony/polyfill-php80/composer.json create mode 100644 vendor/symfony/polyfill-php82/LICENSE create mode 100644 vendor/symfony/polyfill-php82/NoDynamicProperties.php create mode 100644 vendor/symfony/polyfill-php82/Php82.php create mode 100644 vendor/symfony/polyfill-php82/README.md create mode 100644 vendor/symfony/polyfill-php82/Random/Engine/Secure.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php create mode 100644 vendor/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php create mode 100644 vendor/symfony/polyfill-php82/SensitiveParameterValue.php create mode 100644 vendor/symfony/polyfill-php82/bootstrap.php create mode 100644 vendor/symfony/polyfill-php82/composer.json create mode 100644 vendor/vlucas/phpdotenv/LICENSE create mode 100644 vendor/vlucas/phpdotenv/composer.json create mode 100644 vendor/vlucas/phpdotenv/src/Dotenv.php create mode 100644 vendor/vlucas/phpdotenv/src/Exception/ExceptionInterface.php create mode 100644 vendor/vlucas/phpdotenv/src/Exception/InvalidEncodingException.php create mode 100644 vendor/vlucas/phpdotenv/src/Exception/InvalidFileException.php create mode 100644 vendor/vlucas/phpdotenv/src/Exception/InvalidPathException.php create mode 100644 vendor/vlucas/phpdotenv/src/Exception/ValidationException.php create mode 100644 vendor/vlucas/phpdotenv/src/Loader/Loader.php create mode 100644 vendor/vlucas/phpdotenv/src/Loader/LoaderInterface.php create mode 100644 vendor/vlucas/phpdotenv/src/Loader/Resolver.php create mode 100644 vendor/vlucas/phpdotenv/src/Parser/Entry.php create mode 100644 vendor/vlucas/phpdotenv/src/Parser/EntryParser.php create mode 100644 vendor/vlucas/phpdotenv/src/Parser/Lexer.php create mode 100644 vendor/vlucas/phpdotenv/src/Parser/Lines.php create mode 100644 vendor/vlucas/phpdotenv/src/Parser/Parser.php create mode 100644 vendor/vlucas/phpdotenv/src/Parser/ParserInterface.php create mode 100644 vendor/vlucas/phpdotenv/src/Parser/Value.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/AdapterInterface.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/ApacheAdapter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/ArrayAdapter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/EnvConstAdapter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/GuardedWriter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/ImmutableWriter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiReader.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiWriter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/PutenvAdapter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/ReaderInterface.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/ReplacingWriter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/ServerConstAdapter.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/Adapter/WriterInterface.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/AdapterRepository.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/RepositoryBuilder.php create mode 100644 vendor/vlucas/phpdotenv/src/Repository/RepositoryInterface.php create mode 100644 vendor/vlucas/phpdotenv/src/Store/File/Paths.php create mode 100644 vendor/vlucas/phpdotenv/src/Store/File/Reader.php create mode 100644 vendor/vlucas/phpdotenv/src/Store/FileStore.php create mode 100644 vendor/vlucas/phpdotenv/src/Store/StoreBuilder.php create mode 100644 vendor/vlucas/phpdotenv/src/Store/StoreInterface.php create mode 100644 vendor/vlucas/phpdotenv/src/Store/StringStore.php create mode 100644 vendor/vlucas/phpdotenv/src/Util/Regex.php create mode 100644 vendor/vlucas/phpdotenv/src/Util/Str.php create mode 100644 vendor/vlucas/phpdotenv/src/Validator.php create mode 100644 vendor/workerman/coroutine/.gitignore create mode 100644 vendor/workerman/coroutine/LICENSE create mode 100644 vendor/workerman/coroutine/README.md create mode 100644 vendor/workerman/coroutine/composer.json create mode 100644 vendor/workerman/coroutine/src/Barrier.php create mode 100644 vendor/workerman/coroutine/src/Barrier/BarrierInterface.php create mode 100644 vendor/workerman/coroutine/src/Barrier/Fiber.php create mode 100644 vendor/workerman/coroutine/src/Barrier/Swoole.php create mode 100644 vendor/workerman/coroutine/src/Barrier/Swow.php create mode 100644 vendor/workerman/coroutine/src/Channel.php create mode 100644 vendor/workerman/coroutine/src/Channel/ChannelInterface.php create mode 100644 vendor/workerman/coroutine/src/Channel/Fiber.php create mode 100644 vendor/workerman/coroutine/src/Channel/Memory.php create mode 100644 vendor/workerman/coroutine/src/Channel/Swoole.php create mode 100644 vendor/workerman/coroutine/src/Channel/Swow.php create mode 100644 vendor/workerman/coroutine/src/Context.php create mode 100644 vendor/workerman/coroutine/src/Context/ContextInterface.php create mode 100644 vendor/workerman/coroutine/src/Context/Fiber.php create mode 100644 vendor/workerman/coroutine/src/Context/Swoole.php create mode 100644 vendor/workerman/coroutine/src/Context/Swow.php create mode 100644 vendor/workerman/coroutine/src/Coroutine.php create mode 100644 vendor/workerman/coroutine/src/Coroutine/CoroutineInterface.php create mode 100644 vendor/workerman/coroutine/src/Coroutine/Fiber.php create mode 100644 vendor/workerman/coroutine/src/Coroutine/Swoole.php create mode 100644 vendor/workerman/coroutine/src/Coroutine/Swow.php create mode 100644 vendor/workerman/coroutine/src/Exception/PoolException.php create mode 100644 vendor/workerman/coroutine/src/Locker.php create mode 100644 vendor/workerman/coroutine/src/Parallel.php create mode 100644 vendor/workerman/coroutine/src/Pool.php create mode 100644 vendor/workerman/coroutine/src/PoolInterface.php create mode 100644 vendor/workerman/coroutine/src/Utils/DestructionWatcher.php create mode 100644 vendor/workerman/coroutine/src/WaitGroup.php create mode 100644 vendor/workerman/coroutine/src/WaitGroup/Fiber.php create mode 100644 vendor/workerman/coroutine/src/WaitGroup/Swoole.php create mode 100644 vendor/workerman/coroutine/src/WaitGroup/Swow.php create mode 100644 vendor/workerman/coroutine/src/WaitGroup/WaitGroupInterface.php create mode 100644 vendor/workerman/coroutine/stubs/SwowStub.php create mode 100644 vendor/workerman/coroutine/tests/BarrierTest.php create mode 100644 vendor/workerman/coroutine/tests/ChannelTest.php create mode 100644 vendor/workerman/coroutine/tests/ContextTest.php create mode 100644 vendor/workerman/coroutine/tests/CoroutineTest.php create mode 100644 vendor/workerman/coroutine/tests/FiberChannelTest.php create mode 100644 vendor/workerman/coroutine/tests/LockerTest.php create mode 100644 vendor/workerman/coroutine/tests/ParallelTest.php create mode 100644 vendor/workerman/coroutine/tests/PoolTest.php create mode 100644 vendor/workerman/coroutine/tests/WaitGroupTest.php create mode 100644 vendor/workerman/coroutine/tests/start.php create mode 100644 vendor/workerman/webman-framework/.gitignore create mode 100644 vendor/workerman/webman-framework/README.md create mode 100644 vendor/workerman/webman-framework/composer.json create mode 100644 vendor/workerman/webman-framework/src/App.php create mode 100644 vendor/workerman/webman-framework/src/Bootstrap.php create mode 100644 vendor/workerman/webman-framework/src/Config.php create mode 100644 vendor/workerman/webman-framework/src/Container.php create mode 100644 vendor/workerman/webman-framework/src/Context.php create mode 100644 vendor/workerman/webman-framework/src/Exception/BusinessException.php create mode 100644 vendor/workerman/webman-framework/src/Exception/ExceptionHandler.php create mode 100644 vendor/workerman/webman-framework/src/Exception/ExceptionHandlerInterface.php create mode 100644 vendor/workerman/webman-framework/src/Exception/FileException.php create mode 100644 vendor/workerman/webman-framework/src/Exception/NotFoundException.php create mode 100644 vendor/workerman/webman-framework/src/File.php create mode 100644 vendor/workerman/webman-framework/src/Finder/ControllerFinder.php create mode 100644 vendor/workerman/webman-framework/src/Finder/FileInfo.php create mode 100644 vendor/workerman/webman-framework/src/Finder/Finder.php create mode 100644 vendor/workerman/webman-framework/src/Http/Request.php create mode 100644 vendor/workerman/webman-framework/src/Http/Response.php create mode 100644 vendor/workerman/webman-framework/src/Http/UploadFile.php create mode 100644 vendor/workerman/webman-framework/src/Install.php create mode 100644 vendor/workerman/webman-framework/src/Middleware.php create mode 100644 vendor/workerman/webman-framework/src/MiddlewareInterface.php create mode 100644 vendor/workerman/webman-framework/src/Route.php create mode 100644 vendor/workerman/webman-framework/src/Route/Route.php create mode 100644 vendor/workerman/webman-framework/src/Session/FileSessionHandler.php create mode 100644 vendor/workerman/webman-framework/src/Session/RedisClusterSessionHandler.php create mode 100644 vendor/workerman/webman-framework/src/Session/RedisSessionHandler.php create mode 100644 vendor/workerman/webman-framework/src/Util.php create mode 100644 vendor/workerman/webman-framework/src/View.php create mode 100755 vendor/workerman/webman-framework/src/start.php create mode 100644 vendor/workerman/webman-framework/src/support/App.php create mode 100644 vendor/workerman/webman-framework/src/support/Container.php create mode 100644 vendor/workerman/webman-framework/src/support/Context.php create mode 100644 vendor/workerman/webman-framework/src/support/Log.php create mode 100644 vendor/workerman/webman-framework/src/support/PharStream.php create mode 100644 vendor/workerman/webman-framework/src/support/Plugin.php create mode 100644 vendor/workerman/webman-framework/src/support/Request.php create mode 100644 vendor/workerman/webman-framework/src/support/Response.php create mode 100644 vendor/workerman/webman-framework/src/support/Translation.php create mode 100644 vendor/workerman/webman-framework/src/support/View.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/DisableDefaultRoute.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/Middleware.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Any.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Delete.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/DisableDefaultRoute.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Get.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Head.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Options.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Patch.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Post.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Put.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/Route.php create mode 100644 vendor/workerman/webman-framework/src/support/annotation/route/RouteGroup.php create mode 100644 vendor/workerman/webman-framework/src/support/bootstrap.php create mode 100644 vendor/workerman/webman-framework/src/support/bootstrap/Session.php create mode 100644 vendor/workerman/webman-framework/src/support/exception/BusinessException.php create mode 100644 vendor/workerman/webman-framework/src/support/exception/Handler.php create mode 100644 vendor/workerman/webman-framework/src/support/exception/InputTypeException.php create mode 100644 vendor/workerman/webman-framework/src/support/exception/InputValueException.php create mode 100644 vendor/workerman/webman-framework/src/support/exception/MissingInputException.php create mode 100644 vendor/workerman/webman-framework/src/support/exception/NotFoundException.php create mode 100644 vendor/workerman/webman-framework/src/support/exception/PageNotFoundException.php create mode 100644 vendor/workerman/webman-framework/src/support/helpers.php create mode 100644 vendor/workerman/webman-framework/src/support/view/Blade.php create mode 100644 vendor/workerman/webman-framework/src/support/view/Raw.php create mode 100644 vendor/workerman/webman-framework/src/support/view/ThinkPHP.php create mode 100644 vendor/workerman/webman-framework/src/support/view/Twig.php create mode 100644 vendor/workerman/webman-framework/src/windows.php create mode 100644 vendor/workerman/webman-framework/tests/CoroutineControllerLoadTest.php create mode 100644 vendor/workerman/workerman/MIT-LICENSE.txt create mode 100644 vendor/workerman/workerman/README.md create mode 100644 vendor/workerman/workerman/SECURITY.md create mode 100644 vendor/workerman/workerman/composer.json create mode 100644 vendor/workerman/workerman/src/Connection/AsyncTcpConnection.php create mode 100644 vendor/workerman/workerman/src/Connection/AsyncUdpConnection.php create mode 100644 vendor/workerman/workerman/src/Connection/ConnectionInterface.php create mode 100644 vendor/workerman/workerman/src/Connection/TcpConnection.php create mode 100644 vendor/workerman/workerman/src/Connection/UdpConnection.php create mode 100644 vendor/workerman/workerman/src/Events/Ev.php create mode 100644 vendor/workerman/workerman/src/Events/Event.php create mode 100644 vendor/workerman/workerman/src/Events/EventInterface.php create mode 100644 vendor/workerman/workerman/src/Events/Fiber.php create mode 100644 vendor/workerman/workerman/src/Events/Select.php create mode 100644 vendor/workerman/workerman/src/Events/Swoole.php create mode 100644 vendor/workerman/workerman/src/Events/Swow.php create mode 100644 vendor/workerman/workerman/src/Protocols/Frame.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/Chunk.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/Request.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/Response.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/ServerSentEvents.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/Session.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/Session/FileSessionHandler.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/Session/RedisClusterSessionHandler.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/Session/RedisSessionHandler.php create mode 100644 vendor/workerman/workerman/src/Protocols/Http/Session/SessionHandlerInterface.php create mode 100644 vendor/workerman/workerman/src/Protocols/ProtocolInterface.php create mode 100644 vendor/workerman/workerman/src/Protocols/Text.php create mode 100644 vendor/workerman/workerman/src/Protocols/Websocket.php create mode 100644 vendor/workerman/workerman/src/Protocols/Ws.php create mode 100644 vendor/workerman/workerman/src/Timer.php create mode 100644 vendor/workerman/workerman/src/Worker.php diff --git a/.env b/.env new file mode 100644 index 0000000..b8d1a15 --- /dev/null +++ b/.env @@ -0,0 +1,14 @@ +# 站点对外地址。上线时改为实际域名。 +LAYSITE_SITE_URL=https://laysense.cn +# HTTPS 部署时取消注释。 +# LAYSITE_SECURE_COOKIES=1 + +# 有需要时覆盖默认值。相对路径以项目根目录为基准。 +LAYSITE_LISTEN=http://127.0.0.1:8990 +# LAYSITE_WORKERS=2 +# LAYSITE_DB=storage/laysite.sqlite +# LAYSITE_MEDIA_DIR=storage/media +# LAYSITE_TRUSTED_PROXIES=127.0.0.1,::1 + +# 启用 MCP 时填写至少 32 字符的令牌。 +# LAYSITE_MCP_TOKEN= diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 62f9980..0000000 --- a/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -/vendor/ -/runtime/ -/storage/* -!/storage/.gitignore -/.env -/.taste-skill/ -/shots/ diff --git a/runtime/cache/framework/finder/php_files_91921f4982732bde0f9f40e4b3f846f7389ec7ea7b18c365741889027e0d3be5.php b/runtime/cache/framework/finder/php_files_91921f4982732bde0f9f40e4b3f846f7389ec7ea7b18c365741889027e0d3be5.php new file mode 100644 index 0000000..9a78beb --- /dev/null +++ b/runtime/cache/framework/finder/php_files_91921f4982732bde0f9f40e4b3f846f7389ec7ea7b18c365741889027e0d3be5.php @@ -0,0 +1,67 @@ + + array ( + 'mtime' => 1795624085, + 'hasAttributes' => false, + 'class' => 'App\\Controller\\MediaController', + 'type' => 'class', + 'psr4' => true, + ), + '/www/laysense.cn/app/Controller/StudioController.php' => + array ( + 'mtime' => 1795624085, + 'hasAttributes' => false, + 'class' => 'App\\Controller\\StudioController', + 'type' => 'class', + 'psr4' => true, + ), + '/www/laysense.cn/app/Controller/AdminController.php' => + array ( + 'mtime' => 1795624085, + 'hasAttributes' => false, + 'class' => 'App\\Controller\\AdminController', + 'type' => 'class', + 'psr4' => true, + ), + '/www/laysense.cn/app/Controller/DesignController.php' => + array ( + 'mtime' => 1795624085, + 'hasAttributes' => false, + 'class' => 'App\\Controller\\DesignController', + 'type' => 'class', + 'psr4' => true, + ), + '/www/laysense.cn/app/Controller/SiteController.php' => + array ( + 'mtime' => 1795624085, + 'hasAttributes' => false, + 'class' => 'App\\Controller\\SiteController', + 'type' => 'class', + 'psr4' => true, + ), + '/www/laysense.cn/app/Controller/BackupController.php' => + array ( + 'mtime' => 1795624085, + 'hasAttributes' => false, + 'class' => 'App\\Controller\\BackupController', + 'type' => 'class', + 'psr4' => true, + ), + '/www/laysense.cn/app/Controller/McpController.php' => + array ( + 'mtime' => 1795624085, + 'hasAttributes' => false, + 'class' => 'App\\Controller\\McpController', + 'type' => 'class', + 'psr4' => true, + ), + '/www/laysense.cn/app/Controller/AccountController.php' => + array ( + 'mtime' => 1795624085, + 'hasAttributes' => false, + 'class' => 'App\\Controller\\AccountController', + 'type' => 'class', + 'psr4' => true, + ), +); diff --git a/runtime/logs/stdout.log b/runtime/logs/stdout.log new file mode 100644 index 0000000..e69de29 diff --git a/runtime/logs/webman-2026-11-26.log b/runtime/logs/webman-2026-11-26.log new file mode 100644 index 0000000..039d35b --- /dev/null +++ b/runtime/logs/webman-2026-11-26.log @@ -0,0 +1,6 @@ +[2026-11-26T00:30:57.577992+08:00] default.ERROR: 116.237.17.224 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(931): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(167): Webman\App::findRoute() #7 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #8 [internal function]: Workerman\Connection\TcpConnection->baseRead() #9 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #13 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #14 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #15 /www/laysense.cn/start.php(15): support\App::run() #16 {main} [] [] +[2026-11-26T00:30:58.458939+08:00] default.ERROR: 116.237.17.224 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] [] +[2026-11-26T00:31:00.354322+08:00] default.ERROR: 116.237.17.224 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] [] +[2026-11-26T00:32:05.591458+08:00] default.ERROR: 116.237.17.224 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(735): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] [] +[2026-11-26T00:33:08.485804+08:00] default.ERROR: 90.96.186.30 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] [] +[2026-11-26T00:35:58.780386+08:00] default.ERROR: 90.96.186.33 GET laysense.cn/admin/login Error: Undefined constant App\Content\Assets::DEFAULT_ICON in /www/laysense.cn/app/view/admin-layout.php:20 Stack trace: #0 /www/laysense.cn/app/Content/View.php(45): require() #1 /www/laysense.cn/app/Content/View.php(16): App\Content\View::fragment() #2 /www/laysense.cn/app/Controller/AdminController.php(657): App\Content\View::render() #3 /www/laysense.cn/app/Controller/AdminController.php(30): App\Controller\AdminController->render() #4 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(428): App\Controller\AdminController->login() #5 /www/laysense.cn/vendor/workerman/webman-framework/src/App.php(159): Webman\App::{closure:Webman\App::getCallback():426}() #6 /www/laysense.cn/vendor/workerman/workerman/src/Connection/TcpConnection.php(829): Webman\App->onMessage() #7 [internal function]: Workerman\Connection\TcpConnection->baseRead() #8 /www/laysense.cn/vendor/workerman/workerman/src/Events/Event.php(250): EventBase->loop() #9 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1797): Workerman\Events\Event->run() #10 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1593): Workerman\Worker::forkOneWorkerForLinux() #11 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(1573): Workerman\Worker::forkWorkersForLinux() #12 /www/laysense.cn/vendor/workerman/workerman/src/Worker.php(625): Workerman\Worker::forkWorkers() #13 /www/laysense.cn/vendor/workerman/webman-framework/src/support/App.php(147): Workerman\Worker::runAll() #14 /www/laysense.cn/start.php(15): support\App::run() #15 {main} [] [] diff --git a/runtime/logs/workerman.log b/runtime/logs/workerman.log new file mode 100644 index 0000000..9ee7d07 --- /dev/null +++ b/runtime/logs/workerman.log @@ -0,0 +1,4 @@ +2026-11-26 00:36:21 pid:4048938 Workerman[start.php] received signal SIGINT +2026-11-26 00:36:21 pid:4048938 Workerman[start.php] stopping +2026-11-26 00:36:21 pid:4048938 Workerman[start.php] has been stopped +2026-11-26 00:36:21 pid:4055911 Workerman[start.php] start in DAEMON mode diff --git a/runtime/release-update.lock b/runtime/release-update.lock new file mode 100644 index 0000000..e69de29 diff --git a/runtime/sessions/session_4642ca1e97f07570602f6a23b52f53a8 b/runtime/sessions/session_4642ca1e97f07570602f6a23b52f53a8 new file mode 100644 index 0000000..d27b89e --- /dev/null +++ b/runtime/sessions/session_4642ca1e97f07570602f6a23b52f53a8 @@ -0,0 +1 @@ +a:4:{s:8:"admin_id";i:1;s:12:"auth_version";s:64:"3e9123d0802768a210b9b7abb63b0fa3ec25073d7dcc13ba3fde95eaf0dbdc2e";s:11:"admin_since";i:1795626237;s:4:"csrf";s:64:"f1fbaee11f2744c721526d053a32609a6a0ea87ecef7f4c775dc0696b58e38c4";} \ No newline at end of file diff --git a/runtime/sessions/session_5d4813b2ce9ef52ca809292e2ca0a39d b/runtime/sessions/session_5d4813b2ce9ef52ca809292e2ca0a39d new file mode 100644 index 0000000..b7fb699 --- /dev/null +++ b/runtime/sessions/session_5d4813b2ce9ef52ca809292e2ca0a39d @@ -0,0 +1 @@ +a:1:{s:4:"csrf";s:64:"637ad0173f728beb95e405ee6c319895caa3e2710bebe052faba8c007ff9d84b";} \ No newline at end of file diff --git a/runtime/sessions/session_9866b4738ae5a72c352c798a74a5bd67 b/runtime/sessions/session_9866b4738ae5a72c352c798a74a5bd67 new file mode 100644 index 0000000..beb1fce --- /dev/null +++ b/runtime/sessions/session_9866b4738ae5a72c352c798a74a5bd67 @@ -0,0 +1 @@ +a:1:{s:4:"csrf";s:64:"b6fec2c3e8890229d727f5d13be3cd3203af1bb7bd4cd85e2ec36b4a98e164ba";} \ No newline at end of file diff --git a/runtime/sessions/session_be3a99224d70dba62cfccfd756a26382 b/runtime/sessions/session_be3a99224d70dba62cfccfd756a26382 new file mode 100644 index 0000000..538db33 --- /dev/null +++ b/runtime/sessions/session_be3a99224d70dba62cfccfd756a26382 @@ -0,0 +1 @@ +a:1:{s:4:"csrf";s:64:"1193d7e41d462adc94a1f107c1ef17575624fce84d8163eb2518469826596725";} \ No newline at end of file diff --git a/runtime/sessions/session_f393e9966092010277f6c9a34d76b55a b/runtime/sessions/session_f393e9966092010277f6c9a34d76b55a new file mode 100644 index 0000000..ea1d525 --- /dev/null +++ b/runtime/sessions/session_f393e9966092010277f6c9a34d76b55a @@ -0,0 +1 @@ +a:4:{s:8:"admin_id";i:1;s:12:"auth_version";s:64:"3e9123d0802768a210b9b7abb63b0fa3ec25073d7dcc13ba3fde95eaf0dbdc2e";s:11:"admin_since";i:1795624593;s:4:"csrf";s:64:"f62286ba57ef213e9288b43e3e2869d5eb8268e0486b95d99296653089f9b1b2";} \ No newline at end of file diff --git a/runtime/webman.pid b/runtime/webman.pid new file mode 100644 index 0000000..a15079c --- /dev/null +++ b/runtime/webman.pid @@ -0,0 +1 @@ +4055919 \ No newline at end of file diff --git a/storage/laysite.sqlite b/storage/laysite.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..410750521a18c753ea3444ddacbb665de1d98720 GIT binary patch literal 212992 zcmeFa3vg6dnkFbA2_zs%Q!a{fsc5G~(Kg0HFCK;hx+qN9bYV;tcDZZZ9yXPEC1sJy zlrvLc%Ihwrgg_7UG7ljTmV|lPfFukCy*1W zA|Mfv2uK7Z0uljqlPa(V*fBD(hW7+;qC#0VNm|wcS!L zOnx%a#MOQ>(HuMRLG<+P*xeEB+^N{mnfM1M)sth9k+W*sdF^6X?EX+`S&7GIbc4R|W6LMZm}`;G%uPG4n})8p8yH`B4l$2M)$ix^dizZD^4KR6CnF+7OpSGA_Iv8!Qx!Oz&x{pk5)fKxluq+aNc-tGTwT|Kqg zjZVE);77YX)V-=us3y3zs3;ghhh6Kf2)|8O9QFj!dNlDZezfG7f(pMM%`Vtlf&wV- zuMHh^D;3UKZ%7oYQk-saJ5jO}CHe9}j~fpfcf_yKw@LnAVEZ33mih1@|0Dtu0f~S_ zKq4R!kO)WwBmxoviGW1l_X2_N;|p>#9$S-NpO?#WqS`kW9jJ>Bd=xu&-sSh!R{Mew zCH>VkexKqaiSf09@_^Il7Q*nGA^hX@_znf>U!~INEqEPY{FQ!)s<^}@#n+I6!r~j3 zkC;LS>y}`l~Azgh(F-2b_NcuKcbY^SXyrC23YrjJ9BpAwSpoPiC;Yn0P!X0 z_dzVj@lIr{-E3=0jaHb^7?!5X-4Kv%MW_P@0EeuKf0 zU6%+*1SA3y0f~S_Kq4R!kO)WwBmxoviNHf5up}!#)2D=xnBdUTZ)X)|a_YXqLQd0A zSh~b|kuxI{mMmVFwLJ4kbsjyehxg|$&03Xd4L07gt zYjtK7awG<86z3r&kVQpmoRvzA)3;zz){49;f3-sP|7G?u>dyxIKidCq`+tS(AGQCD z{Xg0NgZ~e{P@V0uR|~SzIC@5s(N-1SA3y0f~S_Kq4R!kO)WwBmxqF&jW$7 zwWy`^DSQ+^j*p`6<755z@KLxDAL|~)$J5L4@zgSWJeh}&Kg`9)nuYlI0ZIO=v&sIy zZs|uEwsxD(zS#cCvcI-(U-ozQHTM7A{%>u+uBk!>^;kx zmYrJmXUqO#+2FFiWp6B-w7s|NPi=o~`+sf!a@kLo6)an3i`zz)ZL*cvmfM~{G= zAQ6xVNCYGT5&?;TL_i`S5s(Oc76cy6&NuC;x>g>X`GwiCmot3PoNO=ErQW?X{ znp|eBJ$v~oSY2_RoZEj`2|T6$4k#}AdGyIgvzM>I{R&SY7%FsCDXv4oKYS#6MSdn( zQ}xEIS(&|Jt+-I71pI|=51tPB14n=Gcy@l7VawG`x`m#^L3OLYoxLjGwC~o|xSb)S zix(FSJFm+bav~@H6U(#nR~q(Sagd#3S$00GzH9-m^gnLT&VSVSS>b%+4+LiV?I0TC zQG%-;$-g%7IOVClp+{G+DUpWXR zYgzV+mExB;R$zf0q$&*mI0e96>k3i+zoiRe8TOK;+Twr6^W^?u(aQ_Z=4d(Fvfs?Q zj~nt&BJedpAiURR&v<;b&9w||Yaps28tDlEb8=xaoje|Wc<=105q2oln&T@r{ z#0ID1-GhAYC@$CdgC0IJW%Jvwy)KSi4OS^`oO`;du%x80wDjfTOl4 z#v>=W0~`1G_c=okXui+ybA}3OAE@^HT5%gEz05KWqV#&DcD+APIj=$3Fuy)LnTI~C zqCxm+avwIlh;{|`ddeTrjcO|9^^~u#@ueZ7`H)N5{90O=ie$DgbPs56#gW2tr_ZMZ<|gloBkP?m z9BMo-x+s}n>t9@m)~_Sl&P#56$qQg24zN3(nX&=$^IQD4m+(%I3%4F_J>_liTkbv1grFE%+8>+0qckhazAh+n*RG0Ikgdaw0eiT1W~ z8@02e+CUR-;smRJ^B^zR=1*gB#)ZU!Tvm*eo59mof`LD1l+gMI)C;%t)1Kx9V#AVb zfLLM+uUpY@Fd4)$KCFrHi;TY)?K}?rw2scm)CER}FXFIi?P8~PwnrTt(E3LrBkhri zbLz>nxQ^4P>8$FBI<=#VPo~zc4`>&s=Lf2Jn07L#DTBqm)jHl$FH8X;#;z#n!gmuE z0kxG7Ol*zfEDo5Llb^Iwi#b$@p(sr^6e+DNnBQo4voIR#Z1r!gXm~YwG)hzEC=JEg z;mAlG20`l?i#1Hr%yr<5t>}0k@QqA_BO~Y4cTPsex)>t$%yG2?bbcjzEsRsZF+w;U zTs_{1-9FxMJv#XzohCloM`gxNYBvXX*l>}DT)ligdaX}ux=-WUF{CyfkDso?+;JRm zIuAIKCJWkDQe3>off}?i9Npd)yE{6+A-60Pg|(j97M2t!9MQo65NGtvNlfkp30Uf~ z(n9;C=-o>WOBLpz&u7||q#J9!pW;|M9{2eT_puiiV7QBH$8uI2%S;~b5}jXisKXuc z_uj=>ZvYiX*lW$_&|9tbtkycIj*sDZc=i4jwGo3-kJIfPuk3N)xOkj=AH6k&Q{OQ> zcv!vN8XKI74PtG$6hGIeHJ^&t^0pDn50(>o>!ah zp(-XLZFnRy+Q>8!ZEnIT_jvFZd-gl{hlaOIwmUw)vUy99I(m10RHO5Pg^Jq)6~b&( zVB<*z?pR<WGiT#i5|K9!=_A&d-uYu?%yC4ye2uK7Z0uljvHjLEgxQZ6i6l5%13;*<+{c_|lib5kxXT9k5O;lh*)IXNj8 zva?ezWM!pXSg_!UoX5-Z^30~E2?wC~|AlsUhCOcokMQ`vi41@4-`}Bo?zHc*{}4Ci zpF}_+AQ6xVNCYGT5&?;TL_i`S5s(N-1ionqEM1zFxyoh;;Y*j`*AnB`cNS-5mMoqr zlYb`<*Yna`&&BoJnb(&tLamF;S{I_!!Zf9FP%6g|^_OPjSGM^p3%|0=UkmVSf$__p znU%N3D*to-zXFo~|2O-;v43p8gUJ6@d%*rn`;Y7;_JVKP5X=5b1SA3y0f~S_Kq4R! zkO)WwBmxoviNH4%fo0j5t1=TpzxZiN{Y$=^omrBZM(kfKZlsa>^Tdrbf`6{4*_8Yj ziE?Q~|AnHQDf{P$pQiAiEqMDh zzY+n7fJ8tdAQ6xVNCYGT5&?;TL_i`S5%^{yK=ywr|9`W_T=rHXAQ6xVNCYGT5&?;T zL_i`S5s(N-1ipC)*mCVX{snjT_7acZ7c~CO z-SzX`J73=IczNfK_wIHWR~=6+cHpnZS*aWhdTT2kFYo@7mmT|F!v9~{yVvpa-9Op= z^WFP)?LHui1fQZZYaK7`b3C_u?{3t#Yv+MoJD=PAjHu<1ay0pQz8vy|yh^$oUd8E7 zcRd(7n)(3V_miEk?0wnsWR2J9@jb~kS11Zsz(1W{Po<9z_6a7}nt1rFxAiA$0szPt zauP%jEL`q)r|npcKj;w^?AiD7?&o*^+{BHWa~NkGQT3^J&E^zyx&1%i^Wx5*|I+c( z-M@4^Wsbx%4#2r~@!F+-mr?Riqp`RPMG=#er)9cUzftRP9rAj7hf?U5K?qgh(5mFeOiFrEC+owWpr_me4l{*b z69vr~Km(x!4tm@s5|+u1LBv!#C}v40_>{-JmfKL__lF+(p&Gy)0?+$!ukt#N`fEcE z`H+}Bp`$gk;zR|WbnJRz_pYDnb4`@qv(NF=lj7bpjwh?Jz=RZ^6Q_hdiJv}ysIUTO zhPj_ytD_Lax>1`lMhS$?v&PN$=;g&r+yQ4rh^kE#GpenvaXUkb`=FC)ml1#PBC>ex z+Jy^OZeKZ@fFUOOL7cvZbzl)zl3ZF%!f$3TTDg6DWRB6^(O z;B41(l9rO$O6jZ1%#pOLGS)3-Ce_Wh(*zWv^wg!B5mS7wz|k545}RB=Nm&RMuic-u zaOJvnnZM*+lEty0@S zS~?EEa=W8MpSEcmy?CuHZ%M{?vhQWs|H?LMYqGt%G_v%yrQccn4~suoY|r~e-lMr& za{pq{#|!`4qV9z&7f$EcbN&{E<)1`AA|Mg?(hzuc6?UnZ01(}C`HTaPayoJwC8zA*H$|6ioj0{Ul_P@97XZ-EK&nI?p%*C8OFI zZRd_FZ`MFH93;jtwR4Nt{_uMXSH84%Hs&w6F$YVMf3FIEccmEYdb{XkEn@0|;^TWs zT@sh(+;H`Vf^|+AZHG>OyI$J6m(&mYUV_R%*B8_{gTW*Ifcs#TGgy^OBp9mi&NWn` zMF&g7Kl!!aS+sIvQD*p2F&PYnx?6$RK^hRq5HqelruUDh#f;k|c3^JIxbAq$xCD_X zy!6|PRuWteuz;g)W#v>LM(NNVaUb}O}e9R1H>kgI}wV9W` zi`7g>2M=knNK|DSF}@w%^eq8SeSQ)+W&z{n=7mSof@9wPOyF3B4E@DIsGTWZEM6P_ z?(#(||7c5Qcy|&txv=z9`U4(JL$BX|sFuQEh22KKarB@N+`pBUu4X)JC9dQO98a0Q zi4dMKX%GbW(?=GrJh)}Hsh++;iLo*36%Acp|9$(Sm0PxCHZTvK{^|5rA4xk@$@LrS zo{mx)ik<(U=*vHkz|jZjDN~w^0b`{lS7KRut#kPqhuM0e;at3S*Rq8xUoDv@)EJ=3 zgK+7M2-?!ou2INBv1kKpG@fyoN(|bYp4)w3*E0@`G<{iHv}EDRU8^1dVDMn6@%E)f zi|6%#fpc)lu}AZS!u!NgE4o3W!o}&3H1M;~qlF}xMiL9K0ieE#@$FePpTXMdYG)ut z^TyB2ra`9b2P^!6YF+1J@-zu`5~@7p_8;+?+9c~ULc}*qK*+BOReMdj9wVEoA28ME zrXDcltV~g5=_sUAa_M3<4?ma@Xw7tmRvLX)5^<1Sfh$f?bD3S{yI!Tz={kC_#u?H% z0_Gq1=6rMuMY(g4kzw~ZSYmw3qx1hV?f*3c|H(gzfJ8tdAQ6xVNCYGT5&?;TL_i`S z5s(N-1imf^*fO&o&-5uFm>v!lZeB|9|C#pxGXww0KZ$@uKq4R!kO)WwBmxoviGV~v zA|Mfv2uK9JJ_sz$dOXim0I>Z3j~VuV{Q7iI_Cz8e5s(N-1SA3y0f~S_Kq4R!kO)Ww zBmxov6M^ik%)F)S|9>OHe#5*jzeofm0uljsuBsm)WffBR29@EYhNgSdGjxwTiok^RsFM{7CB%3 z`KH>bVVDj+VdpvloL~UU3(>b{4%{{mW9e|NoZ^`+xcJIws#N z5s(N-1SA3y0f~S_Kq4R!kO)WwBmxoviNNQDz>2JryqUTKvj1m1@_D^O)*}&+2uK7Z z0uljUO%ef#fJ8tdAQ6xVNCYGT5&?;T zL_i`S5%~NNkoN!24@+5-L_i`S5s(N-1SA3y0f~S_Kq4R!kO)WwzN!dF`~O#UWMsP} z0uljaEp1 z?6YsZ{np#Bz5d$kZ@pdPtW;`h%e|gpmEx{nurPnsx}Swtth0qz%;-~42^{vglpwbw zGSaT~wy7-xDL>QnEOz1pt@&JZa6la&i{9u#pVWyuZLCx48H+VcI-c8iz=7IglS7g5 zd$F$W$Yif}u^}@4UbOQ#zXH8YdCTWfni?>p6=r^(bIQgL-#+St`S8z z#N+&6{Ng3Gvnw*o;~<3;WVk8|GRI@r-s5*^XGgVxCL)^Vx_ED$cCk}COL)ibjz&*k z2gqvE1<(_%P{{UAW85vVg97k0}&R|dp1&jOvPo>A_^cIPss!{^}^+%NQn%NLe=>P*O zh~u?_)inW+%j2soc&32o7z4yO7rg!qN>uuBQ+?-pZ0HjAqTuz{U&HlkXGjTnoZcXA z>)jK>!A~XXompdr^9`zU1Y;A9cMrxdowL4aYA`ZA!0*GGQf6@D6WObluL&=zU$t&c z_~=hx1N9yN@gC%LsVpz(Vsd2EQ+jTla)MHcdJK%)xetly&4kQjol;S>XFN7IYz#3L zzNCuyC({FiO*C_QNIMx;JDV{3u{x+7UHm@WN}>?41XB&$M#4EddN zyhrPJN4+pbi!+f?f>88DULc^gT)_l+NJ?X{jYo-gABxfnXeJeG4FzhIXYk$WRszPa z3cnx3&cBkkl+xnTO@$>Tg{7sAk_}r+O1Ew-Zv17|s@3a$Q~&zvC&O=eent!Ii{aYD z0$T;Bf;EcskP>(SUk~tC+9s?&<2TN!?+wR>Zh=x~Y$wq>CRZ^74^(d0bJ^K%D!atFbTiV$ZD6Mw3sU0nj5=ZpfJC2uM-b;kToBLR2v_CA0w#FtWsroa= zBO~XT_)*N#L9>6#YY=6&XBIk@X2TpN=y?3$W&A0%vPB1wg zL$PbeLA%UAsrRp_jo2Lx7EqvOZGRB4^J@T7XG zO&vR}PIM6A5F4gbrNex83qhq#oQ_@|BO(>(;EUSW1_pxrPJHMDNd3Gj_MzC_TanRW zz=dj2p-qseSuqNKV6YKa)Z>lX@JM8|k^6yW&LD1m zR0jHWY%B@?*Yf5hkYJKeN{TX0JyKwc1ZG8}0)C{b_@ZlzlA6qe!O z$1TLoG(a4kD3x0MjEZTsw=~TpWFEkojKr}uncrXW%AxSvYaS2R{*=UXaDQl>eEqG@VJ|P; zytQO=7RmoPi>ES{jV`^q)Ul)oU*(@fKq4R!kO)WwBmxoviGW1lD~dq)PnJHGzw6cD zE*t(J<0MQtWw|~jbi^Mx#9Ea2z-aWsATj(xLm8RqiA>y`?V_T6~1Av#n*v#q?n;DOD^TAZ#KdDdpIF0ru0e6@P{ z?rh)FH{(IAIQB^1_m@BU!|=|vo5Ke&(k09HgkQ}!rP(9ZuPWu$PTz}8AIxEaq#u@% zY-xc`9y$zYAGG)CAi7ra~wWf+5&6ef}e)*MQJ_t(9AEsNFn)V5rblrMM1} z>P>BIf@ul*v)FVG^y+8;D<}er%YRr293{Cmd`Z3BMl(tv$oH$9J~tH*GArQ;GlDvK z1}{16^o1}s2K9XwC3I=o*0SOS_0Q$z=dbx`c;gydc%zv79*h0f<;Uw>A=0wm0pw(| zvwlwyg=xO!+w)Oi5bVNS#6ml1WJzf<#M54DI?Kxe#=`o_FQR^3DO>IIctifJ!VK*C zQ9|)bnoy`(;&tJ8{UFqctU5^6@00wWz2Ki`EO{>Pzt79T7x^a<_Ifa?_QIetE+-Z2WwTK)1(cbS5IK6t%GuzRp_k4rU~5sjyl#sJNe*wwdo#f-SG$( zW!P}lwmbNuPSNs8^#*C)ZPQ&u94;@+*4qo{MqvQ!>yB-1&*2^0s>*iY{c7VCu54Qo zE^MpWp`PfE_Dn^uwVCgTjGcy^DgI6$7oYjoZACRZwiSs=4}08--$9F8!0*LN3mnz8 zA;nE!YG~ejd|r=F5kLJwSoF3R%uq<`_@q~rqndz1+VAZJKEF>X*s*w9&|e#HDUM*k zm8LRxz*$-7@fDKs1?7FA;QH#C4F!(S(HgWuw6=&Yp#5AADl8J0aYYAk$2^eafl5Jg z__o^6q4r+K9*jNHje*tr?*qR0`3`K({K!l+>B@%#*lHu=Zq)#4{k zQssi>gn12Cadmi7YiNv3U%*qm2og^`J&0laY7dyX^b{&yr5a1nr&xh%vurC?tg)>O zKLG(UGnZ^O>qEvy`W+D0^5p}crUiD<2&=jdxgnIZM+j1 zgX;^it>S{%aB6nwQs}uMm{gflwYsa3G}G1|8R>=5o~&oWhmAJ351ZoW?vUyER+o7Z zCDpcW>*LW|&Fbazpb2;`kZ+c7e#5MVmkwx!dD__h>$ruV5I`Wgz^MzCWEM||-92$v zZMi@#7bd%C>&j81D0Y{mE?Az4C`Znl=00|eFs*P@X5@p&*ce;?xEN{{tFh64 z^EGTJpTodMBrKdRu}+bX-EqLGdtR`7svCg2FGTA{quuY|6D8q~mfoItG8`Sh#ax8i z@&UT4x2$CY<2#S#igDD5AjPhStG`lQA!Z=3qZ`bFe!UPvn(GjD%M{*1 zziqGRZ1yN7SRnIdhM$D7)|tK$ys7YmJnBI8ph0<4=P7T>=OB4U{s z&Iy<$pQq zwWz=$sLtZ}BRq_(zD1vg;)L%PPhwsrEJT;`E`#LYI7`g`_p+^0 z15W1whv_h&uWTj7#cLd-+Zlu71$pZj)G|-Pund7o92OX?gKiGD7=DufGqYPW@SpsX z2uK7Z0$&yaX9GF5{8gI;JACu)JVTRXIL%pE1k-Ph*>Y0H%!4U<(^*~PRfNNmkK&%x_Ab~XHy zm-l}%LAn!y1j7IMW7zx=K@e>w7j@Kzum*gA+im<(7jYAe*YP=5C6znos4Bamm zl$qQBk{X34H(+Mn7<{)eM1RIQt}g~a7bM?Li61*coAQWBd4_ZH{STw#V9wjf*Li#( zcJB_99zw6w2gM#lXYh2yq6-F|RK3E5nn>(qqt<$p{8}4tL*Rj03ZJl;;&Ep0p&@|} zGU)n+P_@^5KPy4h#(SoNc4X?J)_rZJZWt9sPoIySxTEup6JQs6_P?+n?|@R#;OJ)6 zdww>Gb-8_?67O9vQ4qwg=k}RMbNkidj0`kXIUEsYG#>AoxY)7t&ewq5Iqfps;*!CVrVbu2`SainokMG0e%{y zLj3d~;{V{&ZURFBCSpNPqPyqxa_Bx6g_Quf@dICU2NnOP?A%VT*HPgQI1cQ7$?O!q zLqkK+2_3EQpQf48(vRWdannxUg9SHU*QbtM{h~>@`qM7CtfS+Z{?x7)53Dsi2W@C< za7;Tl#9_F!d^UB*24J;^vh2J%cnM#yUPf>9*GS>rEF>&=g0kE2?gYQP$hoiU0 zBNG$QcHw=Xa%^&tu4&;B-XFAtfMIyi88}34`)Y@wyM>ze1m?hPwdsV`hPT&aB}4O2 z2~pDIaeR;6YmD7%5m&y@c~TjGo`*E1pN>P&MmiDl5o`W1Hr#+uE0aL;WaO$|z_?3& z6*d8jDj>(S1Jnd=GbZeSQR)ILV+ zm98RM550I1DY6T8#0IAkg=+G->fkxdY}N?W>|pu-YDV_eFN^J$@0AEh1SA4;A#nE9 zg|>WHSRR9g<>t>a4b^}iTb&Xt2m392B817zqH9k`-1L+(A9e4oe#6mNRw~1wa zTa6*ibGgG#Z!K2akFOLvwgs!5UN1R4=>KA!uJywA!RsN93NntA6=OeOV=VInTI)pY zy+&P&4KE2%G*Lc!c`7<}8C)50Vj>W9)}mxlIX%UjY&86lc6VGIX;5#ICnNThSsydF z*b`Bh%*d^<4lENxoAivO6RhcmHXPb*?fQUraXP6adVyX)q-`UO*@C<*dB2*Myf9+pzf%`3?(~*c1`Px%HFjD_exU#!*;WOm-XA(9bf~o3|K)O+|}1c>Fa7;wQ;J zbmE-W(C>I1pv+1KWUcS%{K^u-tW;p7Wh?hhF_@6_1|bvby-Fd81WBt+$Ut&kz5gNm zy)psm6fP3Y%=#oq6|M~U)Gak)R*zO!=*Z6ablRPYm%JYzb?o)S zUE4=4(7T)=$KH^84r2Sk#`P9j>%|^8`=TavoV4Pqq@KJEYK&fJNtu(0b%1Q2oL>sE z4|^}cW*;5D3;9_cY@TaZOxXD++sNY_veQf~fLv})HZ$2kxgYxoRs>3g!Rmg>M$mMR%3z5b zy<1vb{5U010I9C{Xz z{J$WlA!CUhAM#HkAQ6xVNCbYD2(;$q!ta5V8)wQ)<%W^%CneR-gR~oDMTB4BeDoVe zQC-799NFT(=eO*reGAAe7(iQA$BHJeNSKQ%>xoAuY(00*8x zor1ER5`FE5CLhWc?0CF&vdIAq1~r6}I|-|eUJh?$k9ykdTQ2-f-D&(6g+L2!2x2#{ zHKXwe{=_HoBDXH13%aMC*~6#Jtr$IHax& zn@OYq4NA}w8^AWSM?`N+5YR5;p9@ek_lGZ64~X5BQ^ z@Tggnq=6#_lN%YoNzV*k0)s`hbe%)UaBR3q40N;B`aU-aWndXp-)+Tpb@U!Nbc{_i zu?q_$4Xm~D5@<3?m}jHGM2pE2WDp($eOh~StaB19D;!_AXX>e|!fPYVKqG1xo=u)N zJ-+pCydkVVhblboqC*v~^3BSI(v1}r#mbhA6{Ter7;sAlI1Xh^3^*Z5gU&M+mVF01 zJ#oG`t@#F$)aj~15d^z+u_Mi&nDe?Dcq&c8$sNg+EeQgBMQ&%vSyTa^n<5(SLlrdO ze^j!$cuQGvaoLuQ8@FuH{hc0WVbbZo@QC87a)y|Ogc1i`oJrC`pvrFcEwbf5zDxL^ zy`z|Gu@@R+AEN6jt#gmaqIneVNG#eUT+tBaH+hN{q~7bs6xJg*n$FG?yqIht1z^x4 zBd1~S#Bfvc%2Q!T6GUCY_gsh=S4h1!_%5`HCXMss`XXa(9!i)p7Y#?!(!>%6SJ{aU7xb6 zKTqW=dP&+XYpdqM?+3-}p?uXXI7M2Dq6-8&*3LCrk^IGe;X?I`7eVg(oS{Pgy_cLn z#kFYj`w;$3(H;O=C$)Gby-Iuc9wLv@z$gUv&ly9p;EDWynOTQ2@SpsX2uK9JI0SmW zm1kSMsz~q_x3?oqFp($Q@Nu_9Cb4I9f~iQmt$cdtaiM-E5AuiMsIZd+ka++p2Xu~H zWH}J0K)?bFJ~wtBUdWVc+vKLPQ6NeSi>8^BTkI-G!_WpE!MsS^#OdpZmNFc`=q@g@ zsXID;3aQ1*XyUK-jVYiR*d~#Rd_(e=&L$`GD$T)07%~&;Bo~%jF0|t*xUc7NG`6Ll3oiqQ4;LA?O|`zc&1xF}mRYNhasG1Q9;Zk9=7j zIpP%36Q%BevLt@)L+#e3=iL6FwF^8D=t#7W@>s>Y?~-rp<@4ag<0oLlf@k7=?RLE& zL4CM}!_liEIk{P(c6uB-m@liFt}2`m;`Sr;kKj$Uv5vPQbZ zibx4k<={kyME84datJReeQIJI zo4!bMx%VcHM4`}*@m^f#{eeBi!IH(AhdAov%c7YIXHeJFiR}yi|B(@LNQC7d)0qeH zX%ikydP-Iz?v-pnNeaUk&XL%jIf`PZ`}tagOTGY4cyt$z9K@Min2h&8X?2e(9=^+m zPmzc{gCYzsdw>!dZN+j-kQoQph$Moor!W;`Q=?I6o&_VUBbV?FwK`^4yFoStk>LeX z6_F$A;AN&>ykdqL->X{!*28rNxgFP2gj3O$Et|@n8(k$^+)D9=;!UMnN=nO%U1ghG z&u%QIAEe5v{ zM(KEVeKF>>Sm+&_*5T`mN5K<0p2b&oX|c%251U%W2%nkP(M2$Xf&V=b?Xcr{PskA&KP5Om z@Yqt@>L&_?KmR}9oz(WkIZng?!M+QBI_z*b$SFN_eO4X&yZ|UfHZXsB3}$qW#IB^& zEBKw*4N_tSN?_VDmCaD3KcyciCXU-g6r)9VZw3$;ra9p`&Ko{hb>ZiSn#^@dOsrwM}m<>9AYFeivP+$R7DsJ?wS$~u?UqpYr;hit zFA$`22Y~4Cm;9oH(^;~$nz5RFeA6^2Hr)%6&yZ7+hFN&C&d(JfH4?*GD>usV6qy@u z4m<$R5(}V=Sklx$X1Gs>soo$<`sUeD!p_HT$utXuTQa_Iasc`wBB)cI{tQsDLo~ne zp=d94MM(jQoUNe)(a-ap=-@XP6k?52GNy9J2b`utckea)h_U48>9+=_w6l{bJ+~}5 zl(byH1_h$C3tr1s2S2`D-;atb~dMoZ@+NwGgJXj#2@+3Ngt^_j%-bX6n0 zVnW|egb8atM>j#M$u>@Q@_^MIl8|Mr|Y6W>&`Ob6ChMO&3zrtV@;|w8kM%mVF1_ zR>IR-_nH?u$^ZlVQo#`>VaXKf@YAkcEE=(CfRxA=y0rFd%mB_l=I}z$?ek(&V=wU8 zi<_#UB+{@DB5C$OwN|a)>d)&c?>c|Dl@p`ClIBs6B>_%+@$eOhy|b4Fhj~D8%}xZ= zUBk!Cc^Fyto#h^{CxpN-5|5A`rTscg0eb!5_6_$qX45S!37qaKAqE8tIrL^5DpEuu zj_s5!7GWEFyTHmg3egHM%u&Hbf{PCy;@RjTb&=u{<~zz;)7P$!K$Mzom}!c!qE+Z%XDh}BTR^6wx?(P_lxNdIx{bu~Z^>-la644YZ+Yn=uGA@=?c~kMM zL}jHBrl~S2JS$BlQAzaH+2|Sg*it_K2T>F!98Mx6L#X-uDF}42-|tS!xsoRR8kKtK zxd#wXaWVlFB^>C0cf#w-lq7iOeBAHAf8dx+ce@f$B7%hUt)IfvjqY0piV~v=v6MD{ zk$sD$M^+xsKER(^dc;)dC6glwlb|VZQup7T{WY_%O*6@;1f+?Kzq1lj(i6fV`}3xw z89PMCS?*N|gD#xw;Klg~*l2ui1q(QqZ(PD*3Z&D)+13u6aqTP=tN-?b*w9r<+CG4! z+!I*aMI9Kr5FN-w|H97|KO8|EV2>JHelOA!AlrPXYUXtd!;!wgkI|ql>2K}w2Nbc| zrK?z92yrX5DLRRh!?D;&o+37bmOdgt{Y^!p4`{L8qjJCd=**spV>fh{R^hE^w9~Cu z4M#;0%MTNpHOVe)X^GdNZ0L7bo>qU$ghPu{8n6Ykn+gj+QcO=C+~g4!IOtND z?uNrd;@)8}Id}_b;-P-eC{FKAB`)#mWWIj3SCe$58$gZLq`71%lC}Xe$Xm1^nM+L5 z0;&u0tTkn`2|cNtJKjO=MsXz-riW++88P9^J=(l;{~pvOrrS)&=V%5hpmP`m`{Dg4*Wsm?$^b=&}$6 zl{t*!36xk73kxQ6vA~Bq{G8u~Bj!kJWmwYjoy`_>n}elTX(Kj!p}OcCLY@!34d`Q< zY5^9~nNs4+A(5w)WA{-ZSEVa|F1KkHA!DElK^bZ4FgX7 zC{DP-2?pXWAt1;jwTs5SBU&{3+9pz{rh-deGi_(!nGm~1?ov3f@A+2*O~K% zteii{u;t`EhkxXsL_i`S5s(N71e#XkOxb)62km%0GnXW3akwrSgHIes1{PM!BIi8< zfLVd`0GqVoCrruzA+ygFNo^G6;D!0eP6w61VFav_s+Ufi5~?OJTd-?Wt{#y-9VyrJ z^QrX%`EXN&V+wy^7^~nX2+s{LC~O)78_3RT?1ZU~3?jZ&>wFht4jez=U4kHea%e-) zE7B^#a?ED?(|0Ila{N66zpc|Qc4}vPD9&|gVx2lTfCGlvXi9a%7(RVtQ?YvaeXVtx zy+-t$w~0{a)xw-y0?>qpfUAv)S0t(K$nA#Wdrfux7m2Z%=iUT3GI1UZ9<{C?+AE8f zuQ+##4nsUUp>`g_2?{t5G1@>FGc>TxAk-QWvL@J!D2>L=0a!F}^jLhdlXJ53BPdB( z?dxH&gm)jm&YA{*AuBZ?Ba7PfHHOSoC;Se<(tSNF1gW06!skW;HGDw=|Hv33=M$*G zddyHl|7Z4DkEXsbEqY#u1WAy1IR77vsj$sJ7X%K}IufWH1|bj^>M<#n3}31AMMe^) zFLHLf4{{csT)I*!1uV8SpV;w;ZTX{{g*Q|ClX+Mrj#M4R*zti6`r05|Js;%4WX$-7 zUL3^aZf?Z^YBI1Fr z3>1oh6d1zw3bG*|Yk;g9C__QxC!6E%P*4+WzW_O2M-cl}ze&x`YJKgH}N5X3nRXH9oEUL+vtBrqB8 zfL}RfweL6!S6+A-aXt{5O79IvuMO*d4mkOD_|)Ij^}>BztGn_ybrINhc|NmhksaXx+Ri;pxfV#euOdQ>q{P8^^GPC73xtPG!i1>q|-5b;)6?+^{ButRV*ahy#7q!S^+l=e15T4of`EQG2Vj%+`q7g)E5MG2cX^b{uHHbD| z!%?4L1~9)t-k9$2-R1B61R^!CL|C8xtnDc)M$%mNP#~V7t=ni$yyr6I=7GCDya$oC z$2ew3duJH?vUrT5Aw+Ho{dp{$$ITNWKMmg?01{J>b+#Z!#ILTSFsxDJi^OOm)dkTp ze1WdkBbF5n!$2{CGVSt%G=D5@hAxeiMWgqkw{R}Pht`t(3ZRJ2rt}mP58oP`bHVR7 zr(DXyDo9`C|I7M*M&43<$UljIM8HI#wfa%payl0p4ust+GV_A23PlNG*TOcXook1S zL)!KKcV)`uhOiiC=x>vay_6yJ4(aUE7<@Ttjec)VGpl=tz7>mnPeO6antSn^nd#_- z5pigBE1E-cjF9ybMZqF$C@z8&Bh>iJON&oaC5-hrHa*NcKZ~4n3wmPkTd`Kk?FHUQ z>-~Va5zf)2OQd3Fr-k#@WoG5zsfbO$6mWFb-Bjvi3>3A| z%0Xc_P^WNgp($aTOjJ_qd3YFvl%`mC%fusdG=+E$!Fpkj0w=DsBX>s=4-0!dkwd!o zae1AD1iPKk6(p)ijMB&{oG7mQyI;5j@q(2L1 zlL9PB0vv-5QU`%`7hqtbWBPH~jG2{XV^fehyV9&0rLzKW)n#DC0hOE5Iz%gT@+Z%F zG@GV=db?6~+Z*44wr{hO9LCQVk+x6w6X$8ju}G%3cx0p*Ivl=8tIuhQ={D)!l*YiJ zJxJ>3Fo}7{{9I6oX1c>CL^V=~fx+a(N*^uZq_6Xxh65`javcRFcA(Xwgn06(|89tuv{lr4U{7 z%bGN3l~@q_yy=FkM>AOYsP4E^^6O0r?-qq1NIKm(;W)^2vW`JTJ z;Vj%9lT$D}5|U=3^`S3eq4@I1LWuvum*NBxCL_u=GSx~;{jK*%KPpnbU=u@p1MSb_ z9h9P==`zBiFvlrlK~EzqY$M}B&)(5(RcrFX%(gLdEfOnx?Cy2MrqWMnK02>5mxZy! zxeC#{{p#dxxM`zuQVhO(4BDdT_(cl*ZH7Gv>6Uc0FoG(u__>u3qA`Lb1q z+0h*{H(*jwTUL6t6Sk^8tYP{Cl&_O^JiHbqNuMG#^`?4~xoc7cTb2vR8PEu$@XXf% z648&i9V%GPGj~ZXDym|Q51+3=pdwkY$Vts)YAs{ka&#m}y^j?fXPc@g z`jP%4q46FYGuc`0iU`p9fR(Kzr-{UBEGbzk!_lMM8GagRv{~JW*3dB<1B2i`$!8n~ ztxWdD>KZ{6+;j}6P))UgmsZDUd}DV9q9+I8nXDfFNH7mLee7KXaD%|m&p341I4A`U zc;mN-y4qpap#qVyW@G};TVzJM8{<1;pn1G_89}}qYR)LKhl~6_vkb95C>LR$!%@9t z+AvXLlOt6!c3C@j3Z00I4kOUl0+9YRQg;hGCy$a&ER%+jY7`X@)A$RWD2t9--9_ZZ zLv~!X=>l2tdWVt21yRLV=a64_=l=aga7}|U6Yl~I5a%OA6Fx%=_OJMbd%W?Zc`WTC z^$*IRJV4M#3Hn5+%&)g%1dusU9XkWxIi9uiMwB&^`tV=A9lLu)t81qd%UfWeNHb#? z5KJ1d@ysD}GbsamV-t*(ta!$lK#ffuHKTKYf~I8|n7B6i{~W-~IsGZ<(aEKC?$t$!5h1No2{eL@MtilyJY?&=_( z8xp%Vs0aoo1lf_VrJ(9oJZ<)vU&WdC#OX^-ogf;bCoBS2>!EKU7>$(Y+-z$ju{fiA zVwtflc8m|0F|4^}0%=w}KWORZJsk@Jy?Nq1+iID4NK1d*Wu7K@ih2h__{4ciW-`^y zW;k<#b77w5=%{|6jxaQ(l;kq7I{`qPRj%IZG@qh=h=rH82$7tLQJ}%@L{k687$xgI zi}!=sA+ze4VH|G^?LC%gj00^W%|r05!0y5A)mJQJi5F@tMwS*w5k73)Q`zI1K$@ge zsA#%dbOY8Gf#&GdI1CGVpEFH3dy8L%j$B zZ1EiyM{XSv^Y{cpDrs5`9fNv>X@joA5w`s}Wz@e+xe>9dIiS)*LSy{kMGIYn;R9Hb z>J+5kJErvvSz1D8UyJd8HG@2vPb04SGz|khX_4V->@+w(EUu`Jo5x?`J#>OMd~mTb zajS^;K;7>iL#J77sBJ86J8z7MZj};bOeeAYs=qye^D=2i#K= zCGLzhA>(;#k*@|`014ycY@7$zrO$Ncta$5$7l}BqfI2AjY1W=v`Gd#^W$FPz(fk$Z z*f|3nHaYEFKhrmw#SDkJBST>eGZCP$RzvedPSJ?z~NV`tD798CL zsh8qkPhfkaa_}D(4Ipe!+@(<#aA9W9-N{qYV|wHDJoJX;SKq70u3`nI^@Uvk1ZzmW z7N>$(=n+KcIPk*0R~%rNKyhX}69z?bVvNjj(<1K)2Zn}wB=U7`OyMO8Dm5BzR7^sfgFobjoh_*~D z8mUM%w_zW|JOwUH7_{1TonufaTC{FLY>o+2>;t!q@j5UlkSB~Sy$=J+!wW|X^CImj zu(@J$6y?+ICJ=gJ*TVdWzAeMEs`aKm8?by|8%D!v%|#BK4x9vl-Vgy|Qu0=h@nOTb z={&>yjWOKtq9J!Unl1x3NK1hr%4^4BCmT=$?-1~=i46^*9)f{}3jwq^EG}%FpgOMs zA!(!$xAe^!ELUecb2`z!3(*TxSYfTSEIMcP)1e{9!6NKV0@2*`8W^}v&Ed^R@GB{e z75yecN45`_Z~DK|p0@7Bo$-GhB<iE|+(q@9h#qWlZ7mvjeZa0AXpm#SM3RJB%^ZEYWNye`DzjO zTdw$&3Qs7QvL!J80lH*%$jZeM+aNele#FXN(LN})08j=IdT$>V8ZbZ12w9hC5J$p> zjnhHI)^F}6{B~k#FZc1@K^!)}RBTkV4MB<)Poa_KgE-@e{51s!%6UhL3SsK9I_IF3 zNSlL20K`l4_1qBh{4tB2YEPgY5NiV^`%LCb$s{&-{^=z3eUec@U*Y&c>^rxvf@1`9 z>ZNy?mBqdzmWK0W)SbQkSYZX8%P6mXXX1qt>iBS-NcD8UV(MOT-5Nb6}IKew+koU#y#ZhQR&w;cUC_K zu`$kK(9=)eL-@LaNP9!EIP*L)K0An;MU&veK9n)GT+)J=`#PYu+8(K`q!yoFav~$8 z<&l|3gSnhVF6R-KTPbyKEZ?wcbA_^DBkYLU{c*SvSWgFITa#eJX3vRYQjhhhEzXUi z556F3?uoT_1bQOFI82N)lPHSaY2k;jejA?E?12+GM08l;e1kbPR_K_-XFYZaWe9#l zb!cdM_3dA83oKT|JE~W(xE)K&5vDALscSEM2xlz6w2VQ2KGDI2)f2a{Y+}?%fMwSG zBKTx+Zt!3Oc@ML=ZRMH8f<`RZoPsv5_AG9bhKf=^3tpk43m1Vpzr|FE@{1g4#ByW= z#zKM@@+u~{_yHn7i?~jFFEYWC)AAHLlq9{=qAuco`2=EPA&34dAqbe=0d-;FqL&Hn z0so}xSj-oD7Vhe+v~}kKS0!A4c!qNt<0M(0B+6|_dg}L8?y!h$R*!!`gy{zU5$ggr zHQqa{?KCBHuEtRJfaS&J1VM~rQykkJ6v5qcUDSP?4FS+nK$DGKfu?fb6>|hqh)C$U z+ffx|vuk=E`6$dilM=hPlV><8WOpha0yLRvM~4|(y1C(FZ!O8K zf*TCPN{Y5;Z9P)A3jT>@M^oJlinAJ*SP23+6GAoAXi&jeOi8TJApt}fR1gafsftz~ zam+byq3Z3r-`2In#7W>#lcnu1v^ikiep}Z{Lppe#UMgB>?F;w9?1IsFB7d>2-L`g+ zT>RmaOx`l&I8K~Wa~sWbxI=dyi%o+SyX7b=c92K+IGO%{0;mf|Av!kk)$>@Qh4abS zWzsD-TxaZc;-Iep1YsO!_MI5x-H26<^Ctt~L6BXT)VVNm zkN|_ok~Ga@@Mt*UuKNmNEjATXW~uwMKXS|lE!q_50`({jt*#ak#06TQ>c^UB0qq&5 zEXJ^dLfton^L1{jT`iU&X0vmwt{a`vRRgAt0?gz%#NG}lp-~^-O=22J-$5ZMd;|oq zT^J7HLdWm1hMLVKuvGC~YS(ys83iT&*%o}B#}_mg=2R?iG_5eaSak1UscS(lLl}h6 zTgotWwLUV2lO{3I!Zh{9Xv5RaT|pTT6T~p)YB7$?|4TKEVdtC%bg12TQEy%D=0OTaXh;EV1dWbZmv}XxN6Pib8K4}rp4e|KL zrXlD)BjW$F{~^Pck+&89$UljIL_i|&bw{A-N8hvM>w*29HVBrig_F_!cX3GJmlEAy zqz{3N@_*Miozt55X3mV`4t}WjT{YUN&W&~vXzcW-Du%>}P8g0^d3#Udy0iwsX%lQA_^Z5S- zS2A+{JABALiNIG8f!1fgZ_C#M@y|YCvRX14|573jSG8KHzp!Y0BVt{+9q2DljuvNQ z3GEXyrk>-l)5W;6(SWf^j3HagNoQ}#jKl#*WHXU5^|O;*5}-1s9^}Hr#dfj;i6K3} z?=q%7r(;z<6m1++-}|n54q&r7w|qSU>-DVIA74Rm{SL&~!$S-4iX1TQ*tE$S zaxc8gVd{q4EW80CV>gh%;GY_0g&EgR?r@S$xviVw%Qd zZl3N`ro!k;j>k`;FofnOQCR7-iQ{D9B|RS!lkxkYEx5TDiBx8xq%ST|`wJtihm7M- zA}oaTClS`>E^D!qAAy?INTidI3} zwnp&1ofNmnY*sMj4|tTII*26f_c`uvmJl{)z+Fg*C>d_aqF>%;-DI? zNMxPk->>W7HoSA|^9OQ{WbSOEcAMXKm;1+z)qwVh_xd0re zb;UX-X&F1t+lp{&zl>s9Zxclfh|_FP53X|niq?CB^BqK|+VLNS`?QZkt!fP%Rj*J| zhWLptE=f_Z&8@m;_WY7GTJd{X@y`>ykm65|9I8mb21pRP16OLr*ctZ7odE6o|#ADWwCJBP>bam-+t?KLnr=j)9R#F~YI=4S^I^ z4K(7PIqc80$-y^9H@L|Be=`4{%>O6z|MBun5q~oOpE%L$fytZ%6F^bOGXI~<{|Bx| z=KllBj1)T*M=JCG$^3sZ|6giK7Z#Hc(rjc$lllLKW&S^z|8L&;{}z$`KQHUwWGwy7 z((f#3%Db2Q$f9ElcjO$zCHW^2kO=&~A<(eoDckZ@>}i2KcDYBYtDHW!|F9CEqYc`x zP==MsGimdtB^_M2W1IMif2tIx8~+68t0RbHZ_4%pmmeAKpxG5U2ywh%>MeeYNL7L) zg;ao|1n3)AR_=En)$7DrcN6u<8N^vpgs1X0oZ7`{VTtucV%hd#Buiach>``VlK@z~wI*xmQQZ<{qh z7Nz{FB5w?(xfj= z>r-^z`Un|Ca3)1` zyqEKI>2BHrf3q+po2=jUhqmQwc8L=*kFChfJ5pWY2?Rsj;-K#1hO-ZDAurBJKEsN0 zMkdI0uss zn+W9_Y>vIxXuL64>-IZ5zF^4d#ha@g#hW*7bgV}mj-uLNps3vA!}pnWbPj>&jHB$) zaFj1B#K;FdeqW+=k>9%`oVUidf|5~$*DPO-WE55YYGi{AQQk&AsfyDR5v_=9Uy+HP z$i!WSu)qbxDusEkVC!oI!P=S{e;}l|3u^-YUn#Cou;7`38d&dqcyYn&&lFVq-AcjM z0=;_N^uqWSD%e_9{PtV;Usl8FAJ|r`-E4aT>1i8Z%*>;g&px|1O}y3 z$OWforlfNrnm!OkydK}7Ak|_`#+dvtM%7GSNz(w2C=RpgLa(zNsWTl_0i^;4!=Ms4 zj05gK3MuatSt*@Hu^MNkf}ESETDb1+-}(IR{X6&Rj^4UcE66=|?Kl$BAsb!vMh|XQ zV>B^Kag>@_Q57G=if997Xt}$E#8Yn$Sy3l(@cLP`?Ywre3#Z?dmX#o9dMVCnK(u(7db_@?^jUQf zXS5<|qv+B$x491JtDYPAkbNHN1FZ$_5Kf_`!#LvggD@)Mp%5-&129If8V5p!{99{k z%e@}gj}prP=wjwIJ*_DoM>S-6>uf;tkcf0EU1mnue5xvM!u-if-uZz_Vf*sC;7SD!37>d`q;&n1@(uoL;{kv_si;4L%}u5i;g& zV!hEHO}s~6Z;t<&!*v3#D>O^@*l*HKpo;B z`cFsS$3ZD{UJlY>>sdL)TPP3Y*lC#6krtT~!EtyGT@lI~oEU_C6u2a1Y3kUxi(tt8YU?#{^@)1 z3&&BI`pbbvVj}BF>cqjh#9H&`&#zFHoeAf~sK0Vh8@LTCF1i zXN|QO)N6VvDmm9*LjMK*o*QRYA94geP*gm|)Qp`YDwb>_}}jsVPLqQ*X@mds}&JDCGB5PgR@8DPlru%tUmzZPK{&J5OX$*DkrlB%6e($gz#YEL_E5g9e9PYWgpYC3w z0s3^{e+tnhq472s7^jOAoaVHjwOtQ2An96UTw`tHVkmCKI=O@7{{@+`j0H9LkbhrW z1j0G%C=ZivW6I6d4M6%orh$n~OE_0{R^9GrG%#JTJ#B8=AFWAj+ZBF4l)iS=``KPa-{d@Ma6EA}k_8Rkl== zLMuJ^Timq%3!gWcnVrl`!fp;LUN)QE$-MLN&difM&*VkHLJ9@A(OO&6H>26>JJYZ2l){V;ChjCwU zbNIFqz%1D(R?_e@k;0EWy(BqxZ!-0fXWUqbOzMt4g)*&6K>y_m5kUYim*{(gxF>8U zBp&h-DIJia0c$cM@Kx$w@bWxyT`~PUCTm>^{Xa{`>q+X)X(p&{xypW%eE!0^s|w*; zx=AkRCR|6C*0#of()>3+4k0B0DqmFdS81nOZ3#Ud#A$I$qz@Z$?O-s-bytZS;28<7 z+r|d!e>EnwJ2!0Q_F^0|gRY40vYL}{LOKh5;&5Gechd290#LXMLIuH0Q+zkd%hrlr+l6i!`H84UcZzg&!h_FuK9uU!BD literal 0 HcmV?d00001 diff --git a/storage/laysite.sqlite-shm b/storage/laysite.sqlite-shm new file mode 100644 index 0000000000000000000000000000000000000000..9d67236ba092210c3a0f63d0f02918d5f98dc893 GIT binary patch literal 32768 zcmeI*yG;W@5CG7%!Fh5+l^9tA-e_oc1?Z{p!qvKd_BcG;&*Sm|RxqoRMrte?3oklL!^VnZUMo;tJc4FO)Jd4bCH<8(A?iU$bL4W`O0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBly&?$ku^+FIJK!5-N0t5&UAV7cs0RjXF)FqHNiFPBly3wXCJ0y^I=!&`o zdS#=ofmSxnaAlR3UHD+x1*@&sFPqiQwyuL6uIu2f=iY05!T|yV2oUJHz@Y4xqcSS_ lZxum+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV44megIc1CAk0q literal 0 HcmV?d00001 diff --git a/storage/laysite.sqlite-wal b/storage/laysite.sqlite-wal new file mode 100644 index 0000000000000000000000000000000000000000..6f2f62397f06c86b5d064c3f2ef44a52877d167a GIT binary patch literal 70072 zcmeHQe{d7mo%as`HdtO9;!xsHly#k8K$az0#yG|YN86NXnx;oNGM8|fWMeEFjP3B#*aQqVHUZlt7;Gf}n91DSwD-q#+Fa+ZGrhZMt6fPm?c{nlcWtlj z+&gM2LH&9AV3fx2oMAa0t5kq06~BtKoB4Z z5CjMU1c5&k0{hcf?0t4a=AUKR%GuJbHr8t2R$<#(TT`>O*1CTAV3fx2oMAa0t5kq06~BtKoB4Z5CjMUe`E+e zo4Ggpel!VCtOR?3+mEQDP>Du_tce} z&6e`g(z0^1?KO+7{55l_1v%sO{MS8fUHb0v#0C8_w5E?2^dGUk!1QAu{L}uI-tZuM zfedN_>;>RLegpx606~BtKoB4Z5CjMU1Ob8oL4Y7Y5FiMA8W7l+xi|fOR1p~;!(MH4+H^%06~BtKoB4Z5ClHe z2(-MB^;AL8m;JUPy?>QnpOu&AUzVqT4dpq1gEiaExdp~9ME$2Cw?fi|;mD0X?Y-gs zDFb#jyrAq3#jnHDozm?o{3<*@DETKMBfV0mPa5cm_4SBtH^lDg4`+^xZ;eJLE{B67 z;z|EceSX=)gmh{`I_{SOXT+XBcy{2Yz7}ng;pr1npf?@9>X{>QM?K{++ttEChy@eLLdt*L-tYthLx&x0q=W;seEwzk`XZP=i@N_-v z<>*Sm+sJN#d&a?f)u&pH6V#_e9@rr(C&1UUj`)&VxdFDumQ_?*%>I{i))nm9$M4d^ z4}j0h)8{F;XSrFSiSvE~LlGOi8|fd1f@46!GkxKi$$Pw7s1@mUcXT9xs{sdyoIfJY z_@rPDj#PZ>xHeM2`X2EfJOtPQ0F&G*2#RhLjkDOoXUQJoWUapKo86TOA%$2FKk*&=Ju0W$Xp0qeL zxzv5?YZHs|g3?<-KdSb9^#KDMTTaeswzLxb@qJZNgN zvs0X&j+`2W3Y4z+q>IDQU&Q{mV?H0$VK_J>ofwwJhGXvx#rltir^m#=&G0lr6}pCW z=5BayUhKadJ9km^%|yD#q_cOzv-1!eR5(u1pd>HO1;R7uV*PEXOU(t8pqiPgl||wpO4~i+hDG1#3o0qk72Uu@2c#-^<#i1_L zqhti}`+COhKpx;d#xpv8Q=B~wi5y^H6s%*_*7txt-(oPARa&f-*3t~<3eTgiPJW*h z0SiPBKVM*lKKH{Py;WbK&%TqEonDcab2#UTRe|)1tko-yEU#YnTITmYX>xzs;oF`l z)E8Kb^lQ`d@;Y{Ask6T#1Q?y}S`PX)>Y&PueCDn=)9rCFPB$7Fs~pY)2D^*l`Rz0> zG&-D|Q3*;{qj%L+_15b9kqoL#;IYc1_=WKzIyoJkI30WExOg0fn=@k9dFeuLbZWw4 zHH+O-7P0HJ*w$(l-)*s4D#Y=jDwC(W$|R@ga3$r)!PYw6PCUp!u7v8ysoUaM51#HJ zkN}R3>MF)i?`3PZ-$PKSUMxIRnHZEV1czwEw$VsWD`YQn$-g*Wfpt}GHkX%g+Xl8c zHmilM-fT8(gy&)dxEPQVip^j$#Iqs?sjyjWTT9KB3R^h@fhPlcG@xfW^%}2|1Kz{9 zlZws@%`Vp1#5(Kh1!E28a?sV`8Gm^Cyf`-wLRysxg{iJWQ8*jw47}IAoi;&jvI1{v z^td?2!JFRwz zdFye*Y}=il)zqL4*4mLeWkVF08Ynbx_i`>5#3?_*A2jX5A1JC&Z{Y2mhuu!wIq(q< z9)lU9$|Te;dWGi$@o1Yku6Qt^2*4|jtcG(mD{(ri#hDhEuwkN&ot*?PC^6)SCNDH| zclSn4+!VVz@l1rh!32nX%F)VsgCO1Kr2d5%q>hp3;PL2uI}+qNM?pS@nKlwSDZPyZ z<;B6HlNY0tSHi*ILLPcfL_%ZY&=E9^2ZKlgoNE(1-^K+`jKn11GMNQeY=X((#-4h_w;NWsWlu#gggr|qX)9*xP zdn2KN$l!Q%d`J;JWJw_I+0^K&ZrSyWKCft(JPIDk&&qCU&oOQQLsNsHUJyKdrO8z1 z6iODpOSlFT>*nnBrltmymvylW&+;Y**W^Zh$y8cmF0sHX;{o}u#8c0B@ffH8fKn94 zJEB+G)D-zf2WN1)L9lW`$_)lM{l{h~fjA7NM&4_xak}AtaU4Ap(C9v#fdLJV(BR)_ z1euA4Ibp%KiE~x^vy1fk1%RTz2tI7mv+B79_M^XQFod)n5Ub<7P8I~gS7^S`qc4ZI_JaXH=J;FD*!#K2Iij5>-T0TP0+ zhIrIQ7gNK!Xk|Vz@vQfN(+&lLkp_MC#?zFCZ*|%+$sZMr8={s6<(GCo|Am)!zNik- zd;?S)3=I>}k)z`AGh!$hx!wmaW#`0*>S46!JuCxaxf#fT`crx2Xt^AseyVsk>2Ob&Dhxx zv=H1SV2F`?{**%j<92h6ZaWKOi2(iF%{IwnftPbM+6B!}0P_`kp^O6+@-R^Mbk6z$ zkRcArc~Scz3^k04tHZ4l)GYADmojD5za|kS=t4TmcyshkgT7$xR(S&HT9=;1*Si}* z0s+lX10U}U(aF0oS4Af#rE@26f{@9-76WfZg7cBS*=Wam;n0+HX(l`!RP;AvS3sbE z&suTljMUu|p6gd;F!fs=O@M*U@Z2#72osugt#2U`n6!}EZ4}L@fji;=Bn+SKH$W*D zIdu_95SLCxuHAuq6tHC!X1M58KTajmKP?7NMJN1_(GO<=;?)*$>?-&~E})|uy9%Ns z%&Q;Hbf8cAo~vS@Ps#8=hjgJ;I`&p1bRirXj!q2Y5{W&%kc74fkSNUj;E3nZxK9v^ zAWj?`8thtU!!zflQ+Ghc0iIEL<(yyzBhFiR`XmUnNW!{183~TSO|0)S=q@39kcuqZ zf_y6t_{90^<)z}#H4x{*)5oANaiF797p1Oo5V6ELpExuUYwwl@0{|;%8$n|MsYXKG z=u;#xB%K*UWp0}aL+)isPwYM$=>UaWD^kJCw?^*z#reL-=rIw*6%e#!pNi&fd=Ru0 zvGa5AD(X89!VH35*06?ySHsg?P}9=bkmx@zwg*8vf*fiJunA{!&zD}@3vwh#gmUHg zLq`Hg#K6($#1SMOU1}HGk0L20)Q!qBc2&AGC_=&)hrvG{w*gnE9FQZS{5Vv2?gEq_ z62qf54uxeV)E3%qNv&<-QCYDR=mkA)a$Z9q4xLWO@up2;&k+#6lnek6V^^VCq9f2? zK}FLg_8fnh$z{Vhn~ug>)m~t<>BsNx-@0k-p0B;&6j%fPiZxh)%^)KqZHK`CUNhmp z4gRY?q>0t35AYYow_Nj_>NYd2FI z&T`~Sv9?);0`hhpm06gsv4P7(UKHcHj1`&rvMnIwJqzVuwHJ8u#>TgForjmBwS0=Y zjb7QP-%$Te{Q@)s5$Y$@zraa^A5i}Qnt{Ki=BXg|g1nI*L4Y7Y5FiK;1PB5I0fGQQ zfFM8+AP5iy2m+4^fwC=-k``ESgH%d=?D zz%xh*P=u`fKZm~j3z7Xla*yi;uI+ftUVL%B1lbFeV3*hjZv*sUv41xWbT`}-_9M+y_oyW+*$pV z+*kEK)c;QZ_qkuprE_!jG5vIIx!$bLgRP3>M-U(g5CjMU1Ob8oL4Y7Y5FiNrNh7d9 zS6q~|YFY;is7|+0;2Q1qB~R;$lUG&YXb-!y)(J-upkwolPwI*bl44MnU$?B$6~xzH zm1Wq?g*s#LqIFnhT^6mj!YK=z68xykvWb3*DP7)rSfy1DW!k7btH%O8yGEB+1n;%y z=sdGpmtT;sITfa8tuDV2=Rt{=- zI!{-yR$U*KPh&9T>Iz_$7@yBj$8Df=1#8sDTIQRdl`&IZ^KecK97wZ%wXPsP?uTXh zr?j3tUZ)+7wkpuNaUQvDp43L(RNuTVUstd}jR;OvW4%r|V)QeQ>k42&8|SD7PRyxw z3jEp}T^?i{pCIu>wk{8?Y}ax5D|LC0T|4CT@m0D!$d$boGPEXFmj}z>b|o*5DUV7v z@{~Z3gVn2bd5{BpJaKA`u5gWZwH#Vs?o+zLBCVU3t%FmWymEunKdCExTKm$@HNe3< zPM&k;tko4l{Vtq7qnzTiD%oAh=E~3L3fF7>*RqVz=w0L-1utXFp$h#UH)46iK&6JN;4>EsCGwKz7yGaAHjSY^;_zf)PGPvr=rwPseh$@Nd2R1C-7bBJ17+S z5d;VV1Ob8oL4Y7Y5FiK;1PB5I0fGQQfFSS(L_n9Bmaa#aoMoBm=^3kZnc3+p(Q`Js zWTDFnbXkrr%g{xKE}7_(k(nvm3MB9pwm$ZyukOiuejnl~T)v`R!&3+kjl+5FLotLUs_?ftu_ zBSS�_+`df-xM?jn1f+59G#lc5u*hbo_F3a!hO+7Q3&YW1TxY@!9w2r0vkrXlF}w z{5@&9O&UgrK8p_&r%KGiHv_XogNbK=XM!zhVrx7~?&MhEFlu1vfh@!M)riCZ(Pb%% z7;tPkItO~-SmeFAn6Cqe0>>o2yMzDX%0bgDz;VC3Mg@_FjlOLi!C9_20v(%xrX;}>AhE8}27pN*R zU820)i3l$f_$U`h8wpQg|2Pcggr|`36h3@uqzpx=+6(;G=d*VG)fb<)>A@{CtsyPL zlOBaXzu#ZW8(Z|ni2nqUAW>OK0*@jTXeanMD@h7oKi=bV3I>JbPZcOq(8ev6P84#u z1R+HhPm+1z6v{wPGP4q04Rju2;H=ow6&blHlTIOatHJBy(LNT)Kp_e zL@e3J3{04RP`>(?ZPphQ03nRbg_WhU`zlsg@i`37ZBVWyIcPp15mvu`lipZdBonvY zF3MU&#hYl=B@O|BNO$by98k;RH!=+t=IvE$g$F_nh02#UI30*YPiBm!t5+J}r)@e- zUdE$1C%;m-fa|=#w2T8HALyrzK=CEp7`dC1JYw&QuM5;%N^r36;nX@bL2CrFD@@U~ zoyPPlaVl#=?CKd{(7i`Oi+K{kMy$^1W?UvEHDGaeAo*67%$2sElniZXayo?i?X=li z3K^5>8Mo6`>!J=JBbr=7)YekI(0Yt>X(|LWOE7Yy*1ssOD#qaeGb|q1ILE~P*^QXM zvlv)8Bd6X4VovGY$&bg)sm7~@%CgXUuaI~K9P5GaZMwH?ju>o<%Aq)lRX6#LXRTlCe~ih2%3~JaVgXk`qEUp z(Z?+|@QeaCZ9;oV<>Y4Kl=%MICJC~ z5YeEPVo>D|R6MKMN%gl1(RqGkL9`)LRJ``}N8LYQy&)pJ?rGrEd}P&CC>yrYKvH}w z90X#<;m8f(k4%Ywd_q?^pA-Gw3z0t-_@lRvNI{^vd}Q!1#qmm4zrZx}V9U%Jo_7kV z>q8CO)YK&N!*V4KRt~p^iwAh*l~QGb(Q%=tCH0~dG8{~gOw#xWGRphc40~V?L0vuL zToA%`FR+dqz77+Bn*#~1*|3W%F}xr+N(`VZEHfgFA)1@-S@IOZ4e}o!#2OfAst#N@phG_W+@ zK!nZLfg*5BAsas12Vx0$51%rmB&S;P7H_&4vES6ywDS!98JohVuIJ*83|2FokMs* zN5&PEP61YlK)e|gCqN^s04H5)mu`(>M^rIgr^B;dO9TxEk=L0-3=d?})UG;P-fb1;^O=ZgIX<>hMW7 z-V+CIMsK!CrzbzY`8qadWgKwM4_$eXw!0XfXL-7k27_{MqZ{tPxLqytt8Q?WZO`Ln z2M0x1;)P}xYvi5ZVvRPNYQ&~Ex)`tkadX}V#+CS{Nw&)|)^IL|9Iu>0stDz`NiZwf z*?(vY?P3|n()oWF_3^6v0qR4BYyY87^9F%~G&&fJt`xkD>=w9Z9IRJ;!gdh&=@2q> zPPLD~T4^Tx2;i`+9bnBTuQJ0z7Sy}g-5UeDNcmF%brQ}6R(M-voALc%MgOs2m)A}c z?90myrLcdaqS9jaznrtKVAno=mmYqw{U$F@k9Xf}u&Nf3_b}?e$1B78QwD6pAl>ec zjs%o@)!0g$@xk&wwz7l`INF^8FnZl1Ub2q>?HJND0kV%EBn6{nz7@L_DYx-Y6V)^ zqQwiqZ|CNkQ16`ai6h6tv-4oJ411-}1}^O}ipWP>K)N(7PTY;o!%BGvWB_lvQcqt5 zFOvT?3&i5@~{7;H$f@ zKU3c#{s8L*rnGv2sfV95iIE^c5FiK;1RfFs?b-KI3nU%mOwIH6T1Ce`z06~BtKoI!UAkeN~ zS|_la`?_b%TKBBk`>TqQG%^AK0t^fcvaF1R8Vn3<*W2d?;D@)PO9(6f+uJ)= zHEA)Js!5{5w+6sUR8bTLrZx`o$pr4L4RVsvafN}waQlC+ck7mKt4YJL&YqowaTdc+C?j>~4R!*kuv%mXI(sb#%YJq|UuEw;FLUnEzsH!$$!e*d*@WjXx* ze5)@Ul~ma8?%cchBCb&&&J))P%RxAh)3`f(2-g25ZIAx{{rG>q*0Y};&qprJ>Ja6F zVf*qiEm_aq3WwHb1qc2w$Xmau_HVZVU2bbtB@J9O+(L}o?ckM^pJvG1%76d;udT~i z39FMGrQQV8W~|iIJ)GpSIog0O=OUABp7#gz0d4R9|CjXt`sX(Dzvc%_OHbAP>~KuI z6>vSA#E?`{GWV9$fuob9|DAN&9-!}NdH8+Sb@OiTYFWAD)r55TKbNDIAngC}G-SUQ z8GGzO^ikMzV!yp)an7|h)Izo_GV)@S0lTbhuB1c*{9}xB#_y@G>c#KuX7G9?(1k=~ z;F56f%+B=RkzmzKrKxggS$b$^fZi4{>q3eq9c6dCiNQME!b za8*@VS&5j11s_9s5_o_*wAGqoWP4beU5mx=Qg@rzJ&(oz?lGhDzu}&0zV$D1z2i~7 zsTMXl$>rg>6xOflsb4Bm6lkk3>bBQ6c3Mny1VDoS%Qnh#F*J# zX(nB?wr9rUwO?+|{Z+njs;EP~m8<7*f}iot$m`lf;mLoh(YEq{Jpc~=e*g|72`b)y zjm>J!^Ze7>S81(w*!Ps*aRJTuqoScL*6-f-v^(7k@j%YFv6f`@r<4j@Tg7pUmX$N| zI}4jai1XgK`6)d9A1IJo^#+rQpdiH6V_5Ay>|o>K;G|%E@2JBH-5sryNI2O_;QZL_ zI8zq*(dUrxosp1Geca8H*9&9ZeYx)yzR4h~-rzscE{g`;tE>wArCF}C+s)TDeXa=_ zeuOXn8hNQpOHY4ZFe|c(%Z85~2cr1ixdxadFtvZLS^Y@GWIj-oEpMlvf>dSH4Ss(* zwvkj*y=3&@zWu)efd5HoHQz5lx2lwq?fKwrcTxDu_IC2YsFS9$QTa95WGt0ix5n+6 zO2=cXa+ufTs?L3-t8hs7bMF6Q^zDaUR+qoz6-eUae`F{x8%-*-IFgS01}jv=`q6f| z;Shd#;i>R&+MrtU0P}D3cB)^h5{}pTrPcokW{&Q)^_8wyEhYCgqWu9@GQl8zuhnvD z{Nehz8(kfwi$rwy5;xSTH>KBFU>}!2DKhu}NwxegY35DV0cLtyL$?e#C)r3}|AY|B zd2J>~kM%Y%BlW*i!C~iF+-j1rA7R$hYXeota-U}?mgG_F66-&x{-Z+h@$7G2>uE)m znSxz+QF{zm+{J$g>TFN3orvu}C;X2E|KH@jMQ)Gy&^^iiZ--pZk1#K_rq6NNxIPZV zJZ=a5P5-6Wj@^6Os_Gz6d*P#Li}S&wn1TvzOXl zIO8Vhz9+l>^7Ag+H)haIz?jRWPpJUCyqSQIN$;bk=Xza0=ZTfaiNncs)uY$8hk+C! z_i2&UjcT*c+RNBYwSR6i`zxNK#V_OFpGg6Po+s()SvhC9dKzhum!V^x$T1TWii*U- z)ml@R_Rp*Th(h4(lk0YDfxU88JEzaj3u5u(Uypa3r`vyY@x%zbw7T6hQ=S#N=A3o8 z%rWxjFNS8-i6_@|g(e=?mEvlK{i{?_r<9`ne~Spv)0->l>JHnLQh60A5DCT{C6FWJ zWRRoeFeoDCuqc7jb5c%@bF!QU`N%!uT(1hUQEo##7dQU?ZD?^?vzVFe!{JAqSNJTj zUivx|BIkT#QA(psrL(k<)J1&xQ@XS5XKk(g$L@;{(zgaEK~wy`!av#e{egMnLF|=yNyN`I~<%0F1!2Du=7XD z(W4+-WJd5&b8qANsL_GLYbi{0PsFIf^QyahmHFZC*HY_|UUdtKtvP+~$%e#}-`1m9 z7x-m@;}YnW-_d3pvo*mmsO}`Ij2D}l>F}we`c-E~eqKqq#u;U3>ZK=50>45Wl*^fB z{QSV=mNTbIN3i4cQ+*Y`E6VUg@e4_G4)4!?&$->Uq~SGB!waK)^g~H|a&w72D~mD9 zM9G*AjlEZtI2TdMYMI{*?<)?=7WDNFVd7-u>nb2mX0T9vyz(fbzoCL&v|1%;Wu%ekF)cKf6qbL>1f z(V0}IKN|!?{cNnOTnKvI`6JnrzaLAcCWAbaVM#1p6qv!ry0RaNaAy6> zd_iE@=4AXUFB(f6OA|}0}Chq>q#rK79SAOCMC&s?_szrh814b#V;a>v3mln-M@M6RUqucMWc zP689NNLr0YMzOE71#Wn6nf@J9y#!QU?#?~`*Oil}e2otqbuQr0jpy?f;x;4_$*C@6 zSJl@_E3SfpH12k3#a5q7!bj-@>0)_FQP)eC87ulrxnfN$Xmb3qMmlOLhnRybk0?)6 zxir0rCjHPA2A^fhFk1+ip0bAH3B#lDppvEU{OUK7V$^|I;4HpAXR8wHj|Hrm0EB~W z?ZYPcU!4(hH91m4P^rvf%vhldi%^!skr9tA6T?AV7DxQffcDB*V@uM9)y1c!kFcp$ zlYq{^30j+{!*bz`mhrR#Y1G}0O~><<3R!0ww4F<{rTO4K2Z zpoS~i6Z6k~7wJ4RJIaj6dPU0aY&l$X_m$>f|9hF0k>zFU6C@_l!fer#oj2a=X2GMM zobJRjMRCP(Vrgmvvc)OF@GGVV6$6&>0UN~@XnQ16-xth#LUKH3Q(|C55Dj?R9?R>7 z%F6wtJ7e>j+eqMC6dTcUMmtkti@CyyZ42cS1XuW|U-BmGbH7o3{FA=a2Q}%TW&XhP zW9pXmg&Oe6=I&y{yR1K5zbAN{VA<4&@np1aDei;RqPv$njrmtP3f-D~wOE1hUa=o`xLAZ6?M?%e6~MhuLe z&*hmphM3vOw$j@0A6PPJp6}|EP0wtdvv>so$OH}L%DEz_O8-<~xgtv8w>K|t zMX#Oks`82b(0UzjoxH+b3j}as#>@MppRY+}V7h8LX>0~nRUI9$hQ1or*r==$*2wc8 z>3)(G*Mkn%Tyo36U#mtRx(3BlE4a`AcTCR8@*QV6jM(i-bfd(Kbz3Uwh#$qaSM!<1 z8OauLY^O)h`LjRqh45!?3WPVg9@H*DR+k#GC5N+QtFt9#vUMs%|NiM+=;ZoFNdM9) zJiwA1v-46m6;v%9gmiY#(Xu!Da*36eB7Z(f9f3Rj66w0BnFd<0v#!mgqt--odhI{w zZZGCJt(+?Q#0GQuZwcXTNWgP){?$`u4olXsm)as!uB?h;*G7G0Q~q`o3|1+fgRB=T zJJXj}s9E78Mf!>5+BG`gKFPI@Eu^DBr{?$_->#5$QZ-KRS zWQ!v)`b75qMacPGu6ixn!iYW zqB_1qiRu=Q;%WcODajGf!tK8e61M$ zkRkN6_BT@&!wA#_dPWe;>KpKZ@R@mTGgUFlI9uvh7Ls&Y;mXMlFHhN1Lt!_IKtilg zl_(o|%Js+d?1xNrqc}nQqW$U9RiqXSzieP{>^)>nkdFw|qqH=~)CBJNnv<)W6t{GL z@1%@rk@4_Be_E&hXWk30|I&=J@mkKpng7#KVFY#E71;J; zb>aR}D7N9_h~4u;jIC+I>6Zjwr-Qiqof-4n-xUbBO*kw;?v{o$MYuHy;16;WGiDil z9d;SPmSs?lLM-*M{xr$&*~%@?DTejn!X9^ba+2~fvi#ApF*1!(r-BaP2BwNo$t-Au zGm=Z4#4@D@bBD|JZ{2-6iAI<%F0}wiQC%x+&FbOmuT{_3k*b8n^s{2Qw4ad65*@2Q z(YwXucEuHyan!WXRgV8eBx45KlhbkJjPNOPf10h(`sJ(+sj5P{)2|91_QV-HFaY`v$73kLHL#ba;jQd@q~;wAYktb0?19jk9;}= zXyJ;{3H-FRG{o84!B9X176RrDCGD_y-cRmA`s&=qS4_;&VFREfN^!y=z1B z(lMw%aAxRZC4}=RG=c?ogB_q6rMm+wRv%iK8b8mKV7Eiqx-b5T2;6_u^kJ9*Hb**4Vd*@%HmS}AsvviTqzi5oH>!bx@#E!)f%u~ z8p;P5BWn4%jZ`!XigQKm2N<&7B+ED#a>1MIN&=Z!2Q__Sq;v3&5qG@wRbxjPzDH*F zXiaYFedQ2yiY|lo<>X-3V;Pw9Ted>i%NCuCq4J%c?~HI7)g70kqps0hXpBF(_;kO3rav<{KwxH}Mfbs zi^GlfvBF;uS#+yJxOwgVFj@O>kk`z#a*cxr_||QFT(`U*3NnDvdD{1owY4SAT!*^o_Ip>|=0m z{CiO7LvTa{WflG*{%qu8i7iSNV*QqcJL@n_geA068zr0r1Sk|!V3rNC`id7WSHERc z1<^JL;s|CcNd_45B#p6%;i{;D7EavKRm*xbu*g@ z^w4o6{5^AXV~-TrSyziUu{JKOgcoPDCCNUwwo`CsQi@LQl))yl?Ef2+W@X4RTNg<+@iBDIT= zv~X74@i1>(N!mAcPIH~f0XtoB9CGzb@}b|T;9?I)YEr5CM5US!ol}v}1@S6CGwPSXUORfun|l|^u0RwcTArcQ&0~e3 z@y+7|mXLZ01j1GT51*aLRg}1?++_bZt*J(QN1?A>lY#;Nib4)Zfc&U?x$ELvfiPt> z{+Cy0SMeU@p6$?I@GCFBP zF!gBpTnX8enB+_)*;S(VB?H6Xk_x;bQ1V70wXrU2Q0h5jJc5bXd3I7Vpk4vJf^*g+ zmzo?>WLBmTZOs8K3Fbzg-LXznic_9KGy9;0zJ_DM;GdCip zEFL`WR(H=Tm&vd47gJ#0K$|Ypq23&W>!HS?$G~fg>VK1GsGQ+;aNYWI^4ao?9d)YB zYOKxxLzoLuarY0?emVBqI#NYbfliGfu^O&bXck2t>9 z!P%*XX)?vsI+kec0&5P*p&b%y#_moYD}q<(6vZT`K?EkjFKT*dWMhR#vx+PhXUG~Qm+4@?~e~bAaBm}G1}#MlXS|D z&kTAwjPfXiVpaAIG;1{DyL855EW4SkgV0sCES5=0mr#U4FvJkn5nr}Bl6mCQ8FN*M zgtj;6W?!CNF9CRbg{S>vs5h*}wm>F?+hjpk^c?)dGy{^6Betjr38#36Xg;DXslAp$ zJrML{N2Im4?Pkrcl$^3@u0tPNKI)`l5F1kFLiGJiE7?@J6+_^VTTc$LwyOcAJo56~ zKolj27tz&)gFPnGlQE1j#F76!Z>J|gQ0k^_u5QdaU=iKt6vNa+zVU0p%2%WwQ-ui? zLAV7|Lv0OqCr}0JvHAsGnk^GgJ`P^L6A&EIz@{tzX7(l&<2nM?rHBp z_y}CY9V>GR%MmD2+h!xbgBSa2c!UByPq|RDqhsxpJE}`GWg4IA(+@s&d+1nwD{}KS z7Ol6&rfua98WqV-24{I<<4G{##}4qc2L_#CJg|$+d}#drG;vlrIY89_V>o{UV0*>n za+^kzs56b(rdJCt96aM+f{&8sKi-fE^>H>-J;dVW*T|umm1q|@)qTk=D=D8 zWt46g>I;T)mC+(jG@f!`=Z=vN5|DwuU(=hQsHne3AMd@oH^cZYMByut#BPU6h?vA} zMJFl3`ta|aQciTIH;2C39{C%=Dg!IO?%Dvy7!njpV#sAgDoUX5eL|)$l@$rg)7nvrXB*^pIxH-$__jYS!Z4QpAc)gP)OZWZ@_V69Y^C6I9Rv zumH|Lfj2=2`uL6qse{O8o9}8_YN$8E=AQQhPFzmUg)Gs@H}zJ`g(9mR<1z}uvkRsc zbT@;YtEgaorIOS>*^Iwfoxch?SGnL5kYH<(Zp84j)UD;?mMkoLg@vgX4h|Y;6+bAD z$Zy0g1aBN(YBt40E9#~jXiyb75=xk+AKZ<|%ZuE7M{l1Vv<0CW{a+O`bvz#Eo?4B+ zgN9MNAWo6oh5;~GObSE7C#nNFpSX0m&=X;w0BWf!MigniQpm!Y+vV|?XY-pQ&x(_i zx2=4h#n9hzT!SjqK(SB_-eUPJii94;6e(T>8mvK+6e^Nq&Kakacw&9sXmeSU9HEs_0#e^aGw27UxW?;l*;H7Jw5;$madk(|83@OT-Mh zj9i$zonS@2*&D!U0P2;bgS`|CAJi!dOr#op5@GhSKt=MdY>GLEo;o=1GE7pxk15$u zUcHFiMFP7ZhKyg4QVuzI(fte(e_Y`al1~O5_w97Z!cXSjuZv}2ndLa@hXH=iUDo;apWZtic}^z)J&vqnRiNSl$1kbAcmCavziKe zppzeJyu&}PUNE4gNb1;jvJGz(GB%X|+Z0-jAP+i21P!>lUb0h$Y_jIZ#mR3VJk*u}77#9K<9a$F@yAj%jTR-~A109sg-P^M9gvShb9&BX8CD1I z(^#g+J2;-|_&U3Tsy!s(;e)F&gBIu|-}x>t7mgaIido!YW3r){lM`=uoP8(1KM`-}s6+n5ZXtD?Tx@18j zc@5tqVT7@bA7v{XuiU&Yz#9HKJ~6(uLuQeV>*=7iypZJ5HI?!zD;yIY*xt$4-5R zUIY=`JGaHcf|G}>BP938pdvgwgcvsYrF(!ln-W9b6K)mqzu7{Eoms$k6uVeQ24XD^ zVl7jCtw#+Xe>uz0rR(Y8b(Rh9>Eb6GD>%y=~+IOMKVKD$yi<$z~vy&!JP5j{>f}n&>JA?N3n{b zwv~|tyPu@NixBFBMr~R~hav!)ij#{}Q5d$Ur(~D|)6w!4Czm?0vm$O3(VEJcVnt(+ z^a(P9a9r5OLF*|HT><=eDJo}7>c(vvVLEE`f-PVyU^2ke3TnsgxAfHu1*yYrB`EoQ zH4s)4bQ%@&R1^i;)>vMSkgUl!YmAT$KJ4R76OsGkAB@LI#dk+jju+)BS4&p_;8f!@ zzGOqE0T_NmgLPyhwnE$bcz~{OHtP&8+|&QX$>Au(whn7{rhZH6?isEVq7SX2e9yXO zsRs{RZ5CN{BkPv+mBPpIL6TfmjBP5+HmhRw_u}cXffRpi{-4Ee?u`~tRzbgi76jEC zuZNw+tzA)pccJ(o>(Np>4K=FJPvb=&WK1Nz8ph*$^iv|K(<$ySwdFOEOEi-68uGD5 z%Mi@L;4K@E4|@X`UZBn<=dVr?xKL_Q;6lH~VsTLqKQlU~q_PteB{u!;039W7Jw5V? zsRKSX7)Zwgl@hCRSKu8SknEx34$4e@o7pB~F_WVv($m;AW)uxR(`LsOI@*k5Uu=tr zc$U&v=c26v^0=U&)S5{a>=QaGS07L}#PD5^b`ROqjeJcrrn)3#!^$R8sz+Hd++B?T z-q?&MI|$|&gBI#1OM+vSvZ)8RrIiMkNe5-kTz7g!A3qa*|5Et@GRU(lMzRjtQYmzKi49%?3f z*VR}|z1PPLo@#sV+67{guK%m7a3no?+T6ep3(Q@f7+r;jKJX6LMi-o^+Z^0GEu!1ZD*K`yNffK` zctoTA4cH5+aI^dCHvYFErqCW%C^Z9Yafo?6Y<%P6`7qBt?FYY6d4B%Sy+0j^SJun> z?=Q29Cr(JI*Xz+E%Zd5{<5cWKiz3aKf|cfK+GCKkQP6CDTb`0-hvjHtLA-($(eN-jwQ{5wzW zEAyf0qL4RIeTfV(ryt5pk9>BuJ_#`t2yQ`!*QD>&QUVrjtI4pbvkWSGFUhEBQIs_x z+3u<-P#-9znwy11REB-}PIb=jdc2R}2bzpMgcz}(%Iop0^%&AoUtwI}J2f^I>K390 zfVw=cvcwU{`9zU2!$GT9VY0$k-eChKO>DSh9N@Iv6x8-%b3D$w2XsGwlAhtmcQmu} z)3mUdXJMw}m1J-Apums}8#6cJ89l+%+Yl}?yfII(xtKpj2x~I=#~cFbAw20JH1Q#9 z#?V4K+@`of3(X<_YBvHJWBII3*HnzX|0zE9{m}5eo^LBa@Z~4HRMI}x_!oZ!ak9P~ z%ffeh&iq7@e-|^UMQ!kdz+jL&e&)JLm?@h6kH^ zHF;^)5&9sRd3c^e0JEyKaO+Q8`ldh5$)5OW(fu$%U9t#1Mhqd2!A)1sX#FF+cgq72 zWD!N%0d(Ptek|kL=HQ}cF%q}>G}`ZuyT@%m{{CmVrJP;lemwu0S#y10K6EbO2u&Gf zW=ABc#o!&ntV`UjL9;ZL(m*EcJ3B_(jhM^(}+(kcjl4=9&Z{)`=Grm zkgjEmiVl@DN3yfFeK|*G$``MdPKuaQgL35IzS#}nWZ?LCZ}U%OW30b0dsoi0rlD!# z({9uyy0!~D?k2WJGmq^N>RSx5c^Le=hc&|~P&t-Kg0ZU~FtD^`f z9t0JoJa&zt5>RI^3L1Un!L-YFH6WS(tR1m&xyf*E6+xQMKW)7jVZ#>sjJ;yceYvsB zssScQzXZu}&T0`_Xf6BLgElkML>CJOXIY7U#ZUr=Mq3jM+iBhG;tqL9?{2?~cx6f< z;NWs0J$F%>uoyvXo;ob;+9*x)S_}znQ>GEkO}e}%6-}NlS#rAKy6d1fFFJopoQ`(W z@^cDudCp8c!+jyW9YpK>+D1xmYRt(p`}tt;a~V>XCP>T%p*M+*C@0!^L5%&k0t{2< zHXEfds)Mr*+uyj}JHo9ruaHe&W}CMSi)+H3M(eD!JcF*vq9 z9W?IOj7fP1mKszbH7Ot1VlW3W_og0;!#Z*Kk8d++`wr1w-!5{!_MwW{RXopkUH>Pu zV}9n(eL6wD+I~r{9Z0bd7At5nrD$x7n=S@YjG8)|UQ+ZIs2CPl6J0l%;7(JMf~Om8 zLsAMl{VGheVZ}%+7-TKOrO>x+jD;Wf6?JKK0see!M9L5h$G|XFnjA67I`|MCXF`kz z_*N4RY13$-`nr{sgiySr!HeMsM=`PMYft5(J+jNDCBr634iW10R4PK-FbA<`Hj%in z7s<`AGYTQkQkjZz5)3@mOo@p_UxV2{j{^kcWNz!a#eO|1KKB~ zyvl#tVh%C*>FSjkAgu)?!X9e}JK6CUL8wemcG05w4^c1Me**6HTcl*!?>(>v4Uh-! zY)y!~mQJ0o+MH8^*)Hs024~E8^5~tSrh?V=KlndmJ4H~}3{A6ZrFOAaC~rN+$FfHz zcR4D%Y+ST>5CchR8Ely~fqjn8S2 zK@)umuD5nLXa6v(`ph7u)T+QlyN8)r};@<7v(KPdz`D2QcFgyX=YdBt-$4+U&{pk`R4ZX9a>R z5=8O{9B7t9CPn~r!9Yz%>X*MF@TNP?j@rHh#`D`uz%y!04{^4zn2S0?l)<#9UOZoR zpxNYFUj%1BnwJnPN&<#M(js5V`J)6%_-9yOF5-{JW{Ri4PLH?}q|Pg!b|C*c9oz}2 zMb9XsuCQ@$6ZiEIw|(I=PWP|>K)KwH_kI{TNYP6_iA)tCT$^4rHXcv0B?`AUYg2$) z7$s^Z(b-5x#tHns(5`cxBMJ5#-4eRSi1gtdIU6uAdPKCA4VCIHOfX1w+Dri{rst#e z-w3PApjP=hFqxJ?tojH*dP5}|C8i(JB5_8=(d@-ev~(4OMQ#THY?uc-CL-ZjGqm2EY^aw2jmQcQg&CH4~oV^PPr%`Wv zKV#VqgE4!;dOj?MH?KBBnyL{63$Ce`c)~k zANq~Q=>ww$j}Uz~s9M6ujD2Vc3P9}ztf9tpp=8m*%I8A3(au&O>=#(i7f$?WMF5M1 zA$+Hp5r}#NY;4@Flb_56;k-1&7`A#7z4KNa)+Y%s7`_3y*bFHZ`au4ih(=#YqX;jV7ZZ#5aX-H>1(mQRWqN51&0WR-Z66;w z3N6R(a7EddjPGAv7|PJ}w4?uso3fpK*kV2>A6)f~mc7mAJ6A&Sjjp{F+j^5XEtfi# z$@xcSt)K(M*Ks=qm0%fircP7# ziwIIFQdCIKM>vm{Qan#~BD2X*V=i~BAkXost7`#8ps+jYhoNWoBLy_OvtlSS4Plis zup4z(pSWPhDI$N0J~B4B#}-%ik9-e~#57NIEHf9eChATaM)vzC!di+DZvoty<~!F3 z&xcdwe~4uNPeNeTlJ`!1RI|VDsfb5gZbG9gqE7|OzI}kP-%e2_86Ek|;aAwnxF1dd z!zm*eP=*vaU^d1#m?1a`*2SGVb_kLEo@Hx706|JP&g9?{hzUz- zqCYGi4FnCfJl@vQlcQg7VCOYw=?#!8>Vzf#{EN3m7%huxx+U{xSMCcIS^)DmV9#Gu z-hs$XB3g*LKEEBXY!K?^!-De2@k7RpvNQRukUYTCuu0O;_#UySr&~&ctPa{4xgyB~ zO~fh#a~hPJp71;eID;z;1WkBi*$BsqSY(XFn{~K*r~&FrO>I2N2kv&u@NXQW*Zx_o zxQPc~bUbuoietKn5nx{c?9_-Fx{7*FzR0eCG|PyZce`y6ErN-3Eby1D^#RQc)Qr@D z)LNjtF_eaR+Y-xrgxZO$vI;~{vgmDwj?#Y zy1=seqCSwCV|+o4!gjKttT}O&QJ}rTK*IMkvo`uwQ}|qeh){9TWY5)`n$2}%M>@N$ z;UHYu)D(BXJ|FJp2QbtmWEO)%h13-43Mqu{ij(Iht&6b1nFXRir%4^neov97xg-bh zZAy9lF`Fy(#q+0tDTq^zgEyw?)q15RJs`d8!}{aJD{V2&N|jy{m*`y3iISkUSYL{4 zXZYtm!^eRj0x9HVD2)VcxeD}epI@3mv>ZO0?X3QTX7{gDj=inN;{#@;gVI~Y;MVng zfbzV_22IYKQPM%5du`DNyLP&fZ^w!Kp?#@Thse)LcR3!oe(Ui-kD_CchYTP%TTOY$ zppF@(-CS7TbIgyZvG5T$%R^qM{J2HW=Ac2Vs(5XHFj*&@(`QmJ%Ubx@DTVfUoN@`* zl4Rs6eS$kP!}arI0+aIml62kb9?9fU#q+c$PY&*-Zgodmar2XDZ$&aLqM()`i(u<- zmps&ChNDr&P(4jUmUDe)`i(3@Ju8uoV}3nD508nH7{62 z^uA9rpQ*LlgdS>8@4Cf}#Mirtoi@Z0GI1GF=zrfnIr$lO`Y;pNwO+yVLwsSoOmIqZibBV%{#d9GIN3 zsRs^QMZi{)uVZIc>(A5ZDdLKJpAT%CN{Z=N z#_+MHczbY0G!0GtOps>Ur+0JH051n|2yj$_dCQjAGgk9xCr$J>q}RkKS_o6_Gfv;G zDo(Ff@76+2kL~N1bHcnYWcs3;g;V?K%VE=hL)oHnd!R;Yf~LoXxi6O{#U#s)k9z6d zoPO6h1D+%gicd^yppX z$XDW+$}lReRChV^wFHPm^!`}oGRSESd1IZ=i|ChyLQd4!y#NSOOy9=+uKd&)K@k~ z1&5PXZDU%q*}}VZ2Ex0z2RCA2CZ{VM^F&=n^Y_N_HuHJ$k%Sr=w@wGu@(2FQlqSg; zVYWV86*J*YIpLHV?;F~8)ramE&cwqX-X3tNIB&)6a(-!MTpE#kofQPPUvbsgp1Ezk z*gV!yg~}^@Ai_H!K?HdNCh6#z3U<>jc;QxNc4Zi~oEdpFO665$Bm5I{;~byF*e+bi zq&B`nAuC&Wf3U-90}}8s@nW`wQQ4^3kgN(_k}!Soea1$CV_)ghc1R)U0P_`iYbUC^ zI?O?UT}Ce^)Ql^+X`UUaLu_%jb`e8gktE7QdB}yG61Q-5*ny8>l<_-D^^68M6oLCa zJF%4o{srS4ujILV6c+S}eCu21&^I>+FhG>+T|#B#`8e=wHeuDu>2YOQ;#uu@*l6MA z9d|Gqk?1tatKyr(omX1Zof|2O+xOjdlLsmG&TKWEEt(f60$ut&u_v*^M|t3d?;>9KT0P%us;ycKvFha!gx{kL>GMgOtpD!lo&D5$ z&v@Y(T)qB88{^(3%eHV&^EZAHDuEw_`^z7vlRNYeaK7-Dq7rc}@6SpWso)`BgzG_O z<$*iw?lZvr8=!;ZqrR309R4_}nxAuWUnV(aIp*@X;>&QrVw~WK?Bx%2SLfHdJaSM9 zAE;kTM3Jw;&`kHxVkPcnF)?c=u48UmDdgxyc@T*BuD7-fO-IuTirW&!0Mt$Zh9awSLd>} zq0NfhV9-Zt_D`8_PI;V%)+?)BzsJBpu+SJQ)((b`XmjI%KmDEQ^)HHwHr=GQ2RW1M zm*5AACAac^r!nHfsg!m(yItMU#-{VNUA;;7<_*@hZLJr%m)Dn-C$H}D^C4sRlU`$P zln<}4>jb^cZRq-xaZ)8lkGBWeQ!<2^sQVLoOY;_kPdEM#(Z;VxYPecE54SaNnb-Oq z`PHC&iQQmY1R#ZEjenBVu>AH5{@POlFg6auiJcR7AQ`;MfMVz1Xl((fG*FB&4Ex=a z8_ sQ)e#upy9#clroZ@I-1lSNW)og&tD^H61kk5}%Qw2eBqM!8`CL{dPv(lK``i z#!MbxhprV&nMwN?A*aWv$&b@c7ku}goGD)d(8>FhL=zsYGA5NhHuq*XYtGaL*~)^k zHQfAu*zKUjqW)k2el2Ayd|sS>AqFP&|e^?6_L{@+{yg}I^ zEP2mMVblBQR1ozDpr)ZS8}D9RFZ`MD&QITr7m0JBlQ?w1+7U`IiogM4Hfaa@kp`XJ zdkLqQ(J*nq^CzTY(nOOhcf`VNm(esO#{|MTA}yjhWUBBas56 z1W;I^gC#PVWa0oJZe#o<>qY|;`6Ww?x&Wi(Y8L;z3o}55*61bR`CgI_u0{7iR!r~? zFJb!pDcSDBL{Nr`$)qRdonS^sf3;*#(cr=7vu-VB_3RPR&oYe+6cN^7_O%=W8VYsM z#VSFW!SIlCAi3QlSMZ~=Hc5K43V#j)&sf^IUKK?|`5c`(_^yITyoIngBdM0S;6MmJpnz(1-}W)nWh~g*RttH#IJt)=>jqn@+4|AW9tu3sC|3#o z<7h*uaNe2w;gRg9lS`ok50w4h5bvgdRq7clLRI$)MWo~q=x{tHRQ>oq`7F~QE>usO zCaVwI3CZldkTe5e^v<976xf!*0W zzTg=A!{G-%AAx6o|7knJjfqZJ+GpFY{lHY6~`842VB^hHnJ;s1BOgBz)1VpGRrhGO&J;ptqK>Ad9WApfrEU+3 zoqYFqk(e^9CN1-m=#bU5IT2+8)FQUjg z!Sj2e(M%oK@as!Tthin#TQIAArT8K4`z9YK=kDH|S|u=NYCdChnvv{$Sq%>IlfD^~ z?f0#F0S156cN?aZorFYA=4E z9ddXqZBfw0b9?yc8OKKSX`{fGBCQU6>yhLCN78oyv;F`7*WSBIZB?{YLhZeZmZG%@ zLebjPF0ofztF0QPc8yxGsSzR{6jiZj5~(6)f*|%k-{1c(=aM__@1rP5ydBfWJrZ}nR=ppo`fg%eywJd-iM}Hyn`fR zdauc(zd|{;j%#C<9ICzO(DS^dth;J&i5aAj5jqI_t;^Uw6B&tLYa1bTL|fi+b@iC@ z%hNb@H0a)qZHaimT>r05fm5V^SI0)hlIRag5OWVHURWrrsV`W+kJRbowi9ssG|R`- zs&7mplt^>Ng;&eQ6&o`dUHfkTUC+uYZ>1y-@B*!PYz|4~@%>{TcZRI3?L9LNshRKA z?A{@^bZr{oIGK%j=^b(kzq|SlEJO2NY`Olj7LOtt9owX1>D7s0U~G;%{ot z_UU8xX8dzc*?!+~ZAfQ_t&_!mY^eKc*q1k`{t8~qJ6NIkJ)o6N^j(rG`}!n?CpV!- z=8@WONo~iU^qiiaiS(xrI7=BmG$=kL&slNJO&-}i{1t1NKpv7{({>Q+qjV|s5~zba zT=6pMSTlq;|GJb1moLAuN&XJs@}TQlCXka$^LjAd!Lw`Bcp0}c+{K&K(LqTQId8Ar zGZkLCo*tC+JkIFXQ8HPqb#yPwOim3fs`Hv6vZqRgpmIr}K{8rU`oidyl2}o6-N(X& zc-h<)qjT5R9!R2J40n1|P%W8<^v@#t(FQ&n$7jE#ZTwx0;Ys}YUe}D>mKe;r9cC2M zULn%Eno}uIEeRH{GfA1=t2cSsB;zpd4F_N&ZHac?pSlt6^%>vIE`3+@CRtHQPkU@S z>38uaO|&*{I|(->Fj`oyUTaq_h1q^99PKP04pIg~IGuNoN^=SW4kH%)Yr+T>Kv6@| z!=?qZEK6|lbwJEWXMc_vwADzH^{KKHKUn9w-)>wKBC^Gc>%us5eaTzF$6Pfrj>pLI zYTxxLi*cYud|-o4V?-&h8!7+7TXJh}B97{rK4 z&O2!|+~KN>;fmk}2`Rb-@0;0X->d)Iw~*1dKY~})WYESvVuo6g>;s7~1)U}TPC*kT z#qp$=GtP#I%W^@Lsg#6A`kH>-rQK7H zeM=&t*lcsz3n{jrQ|;(Z{aj>qm)tyTUe^zzOY^2{*kbpjO0WTj^T*d8K@1_45H{e0 z-+99AoqQp;l|0ZEUj3Cb>M9yObwAo-32HNTKEjANzoh#Wg;;pY#bK%zlhT{|yofB~ESxs3icm-%ZmK#PK^P^E(2Ro=2=Zt2 zvaVZUed-~eoX zv9U4WS{7zxj4`rY^x=deuxVoo!?%)9p;S@KuiQ9g3d z`i%-1wvAv2P2ThuTp}{Z0n+*)1|edS)4x^&Zm>F|J|)_#G^ncOFk(Qo+=fjXp&BZ< z>NnW`?S=>cpKR3UzN8zTV?sQG6)X)LFu66vsLA{t3ldWKjCwSJ@Fv#GhSJdKZ_$Tg z4La$=_wmMB4$c9)SH2W+QPMm{BXW}5w;s;39M^;i zDvFYxY*bm!>?@Rj6{2+e5WF8r|2`$^hVV`|cZ{sFAx`}`=($DBn?P@DMjuU{CY_&Y z7!evpY)W^`vlnqq1$|<-1rjG+g4@1jZc@MTlw650>&n+m9kXf_hUMtux^95lJmaZ* zZikhvMBFh@K6$)5dsW9kY-)Y$ArY~QFR%Y;bzx@i7sadK@N#wRv(5j7hbCq9EvvE< zW0EY@n8kzT(>N$M+QdF!TFYM*lO3GU5m#5ca`PLt_C4YEl3jWT7x6+{wCR6?N^A*k zZd#&bR&_dLu#?B7H#1GBba2n^>D$u|{Yp8J`TIdo-;pWqsyvzd32R741PjJinJ?V7 z^pIY9Oq>rsPVMs9`p$3KqFdgS@(IS`LX?vcP4_7nYZSZ*77UKmFBCox>p%M$;QxJ& zLtyM;%IO(Vo?ryK3!1gyK4owYH%+*|TqU7f%*T9nyM=|y+3~~hi%seGpJ4~ux4iph zHxI|+bZr!zi}pxWHV&K21hexmin3vIuWM};wOO3J;)d1$)%(2yGt&NkaMD}3C?}ly z&n&kU*NJu+5BaPb6rYrh59CMn6-7`w!~u9GX3z$Bq!BG@TW_gLdVV9(dAcN`yQF)JkO>V4+#?wXm zX4XHxA0FWiTxif6|NrN@ml|4@EjsM^Xw7-&z_r~D9%^h?aG@o)B((Dsua}1DvQ@L| zszEdHvbCYah9j*>);{lN>baOQZCpMTsD3EWrMJvwT42wpvJLMLqM`ZOm*#CDpbtcb zZk_w^BL4+Ctv!pRcX@z8oJ;kEf?~o6&DcozicyC3^cm=lkC&o+>9|61m-D8lMio6i=QZri@CIQ#>E$D`nN(I!0Ygn8?uYTW!{yDX zxx*LKEUl;=$x6($R$4{WnjR4r&z?H(8fd1{hOH;`+$Zxe9o@_4(5a+kuccTcgj4NY ztSvujboN-WjNN{Lh74-fI0a7PGB^aLU=8nRy}s+ z(}Uv6MK(EG9}2o2O5=J0pK3+r(cH9tSLrN7Vu zCV8qRd4YsaG>+Rhm3)nyZheoL80#>*T&qlP-&3s5Ic9+aIRv25OkjiNy4MFr<29}} zq?xX6(42qv`~8LCfJKK{C9!S2!qylZLmkqqM?UgaGAfi3Y99T2{(vDItwk*SNWPboH}41^3g4 zq@TLXe|6%%;ETh&rf~L$2~u#Gl#-1iZvf#&b(YE1r#`-)pBFJ5MK>H)!l7 z-_{t;<^M|4{?1-Sj7r#!dQ|HSriT-DT5~!z@+ta}h6A)7PfQOcYdvc{C|{i}omj#z4G-|2k`HpLw#5Vff{3d zT)nb=Rkr+X<(x6xixIR?Thw&&Tj`rj_$=n3`mFMf+2BsVfI)NQI^WnxohY~wZ{e7> z9^1=+FF$X}tHn3$>wh}cPeQ500=n$q{MfL9n8E&Zm519$8XdKvCHcpste@RLHBWUt z#9G2~#)^=FRq1N}xH)Vc9e9ECC6cR`=S5S0CYkG6GDOqYs6ED})$)UD{2zTTI>6_+ zecPyaRInBh2&A|A@{{s)|NFG2ris~=pm`20ehRvPuSu$>IBEL3vMp=(lV=cMo)Bdj)*>CV;0Bg)jSy-wDNtTuK z(rJ%mPx|-;E)_4S%9c_<9B7NXp`ad18q;Dmd3(NZ&}Q04(!N0vbQ9ZV8FLBC<`!mk zKP4|4?(hNG!};$t)6NZZM`OjPP0*>nB9&!s09m;mHTt6^-j&R@vnsT+5)`XU#-F_8 z{BgZRlxJ_e$_FK+B|JrRZCR&VnWM% zw4OOTL#^iXO4=*%t;>Xs9Md*bUj1u_G!zfqntimm2D!$d*C0{Wc z_zj+@EnFiBetq$!C#jCQ1i2e1d*W~PTF1}TXT_*)qH3ci*)Ixlz(B=?Z4*Bl{9tsd z4RQL9%L{U=hj8*1UdLWU0yljl_6{VYelVm+v*Hf!qv29Oduu$Bt152*0pukLF#dSw zhM3tq2n|$fdFi~n0{n5Id=qjJunfM6zLNJ?ZQP#?UA^4VZK}4%v4QCdyz^qIR7A zTV*sXvhP(-cx_9@rzz&Q8@{{yPe#oyoFlA<7V78`lrPXFo^1Y(JWk>h<@;UtNB@xv zDhS50@Dc{Z)6Pnwny=jFy>IZy^S(QOr;8VfEKDaDCBz&H7q7l; zV}z25R)pcuVEPb-T6oFG1TT6~n96z52yAX}?8(rWyZRa?aiExpdz$31JL<`&U}vdF}*a^BZ&P4JTf##@s8V=G*n*C}?4KrcV(x zoUL$pae695=(bu8J1xIRlmKwv+op%sKsYDSYk-_I#gwepcu3RiH9cH-9&(}Mvofk5 z!Ln>V>`8~_1vGEiZ`p39@hP22YYzIe9uQ$xbLo3$P*eanTy({ zhboJX^)p|^BRY1UgC|V5jF*^on`gt_C+u>(4%?6la&i7EN(rLO-2u z)O#h$>+q#)hBum$;_C%Lr)+t4Y3gK}8XC779d)prl9V>z$sSX{^2G7%zslDJ5nlA@ z9Bo|l*TB2yI>syKW5f2pH9wtC5^Dm9g@AViHEW_ypprV|W{4QRVwMU#=Lm=@;WVgj zj>V55fDFW0Px<%gS2=!f#~q+Y>;+TxUb*N6xqd0Cw3Dkk`(}0p3o($8Lt&q&-WVddsH zm|wO63Z9W^Jzv!~>apF7oOc&hA0qi8Bo`t{>%vrYM4dBv^+ccBvEQp?Rgm!Fq7Y*Dji*n(Y^D9YSr$i3!9_{O$W85dhm3Z2xbu+D0 zD4jgJN-We{ylXP7>af9MG^=G5@rZ#w{#n&-45o-h0&P!Tep8B2n9kV7SijS;_iM%9 zoEm0)rot{|>r*vL>A0OA)UDXs-r8E4u@Rox5S4lSMxMzfnl|}LU+@8$bqXl5zaD1Q z**lh^Rjb`7g$ezo5AaQxKLE3T+haeVgEA9ZomyX)L(3YPs zdAi4w5UQPnBGBo^!u}i$1%*X5XT1-k>R8aNQm0>bHwl<{MC!q^LyvOS7bZ}7eW8OTwK+QTq^MGg&?12@C!n*OCK6K;%Gd*Vdmm%TMIw(g zE@qjbdVt`PoM1&mYEpnstMrtxnNu0ZsY*(I@zy7&w-KX)KIU-tFJLig=`KB)G$H5te=ajtBY_$s`R43)qUAmf- z8OhG`Q6U}<{kRe>&l@u=a2A^Wl}aZ@aatC2f11@z(|_fUl}8@PoAZA@NNM~}f?Ah0 zRE#T=4yrTuC9$iPpfSDm$xPMv?orMn`@d>0c%6yXO1J18{3J`ol371rZQ#9&p_8ocE!H8!xMeUD-mU)Ujcy;_#Ddap=`Iz#y|E`Kr{J2Ck3}}HT zthkI9r?zPa#+EiYVv>uW9!4ds$6^(nH7fYPH*#X`^p}&HDAImSctUM2vDa~zhhXMY zm@RN^c{@hFwZf$pYQoxMg7490g^E=`Y;Q6uoM}h*a3wX~XGyTXl%zzDIVK>xxH|_@ zw#JN;xpkBTI)}N$#9z{_m?^PGEzo)AO#&Dw9mrxAV^Kq~#{j1x!`9-Z_0WIPy;4>g z%VFE$$!t>IH|wmpn*8}EDz7d*3M$+HyF5X#>T`{rTajLAo9Iyz#13QlyPO2(P}Pb! z$x2$uw+keS&0s$_a#(%${UHkWl3Vodwz@0r0MW)7We}k&i#-o#mnL1jaylUx718Y$ltXv)VRwgKz2C9P2L`29N9R3&!u%N|O!AZZziEgh7G z4oc}1uY2<23b7DMv&ww-_hlS;x%V!J6udS&oN2DUp{Xs zodZt<32AsL^QrsH_ML*szeNVpWz)|)R6-Vl&teDH|4c?Sdr;0Y_A;U^@_7mIIO}p3 z@h}pSV8;=%@C3ryWn47$U1Wk16wL_S9x#535dFtoR(B<)1F%fa63#Ua79wtW69!1x z*4gwtxYMY&d-=1c;jdfLJ7%}TZFgz=6fCGg3~^mlk-u|&qJ$j=-*Qh0zQ1g+|6_*C3eSK1TsGD#fr!;lmup{l` zv8Ds@a1CzjiT`iNv*~JANkC06j_qg7EQq>$@nl@m!(UIFH{lE3*u2;_q8nGv^KdjL zMg`v4C|@s_JGd!95r$L@@GVI_o~zd1BAxbP<>7NU8iGd^BZ{$t?@d__G}`YcB9 z&%h-)N#~1uROHU6&P^{H2N^4{U<#-6^d`*adFqCNeOt@EFF(02LH6f^XGGfb&_pM& zJf~Q@nRG1P8cX<0wP|+IKCC6@Ssq_e7c@~@u3^Ut);#TI$qVMAH`<_@kHFuR zLgM@1ZmlCVo#WnfX!u>pYxqv{r!8%jJdGIZM$gtImpGTj61zt!89{go`#o1Jf5nW3 zJUSRB`37ekfPeg^ij@R;xg=bAX8k%#1HH|-ZJ`okRa0}vw`FcCk1{iZgx^=(z}Ed_ zK&Clz>mX*9{v|r|%AX`RO);ewKJvr(mW zziekab~?@T8E%1s`9P3DlLFJXD;S{SZRlMO5|*#J-t~nic>5|IbKAJok8 z_u1_GK+@ynvLnTg)zV#!)_6d~!yf%ZzU>DBny%hIWWX$Lv%^7YwnMVvq!bZ!US0v8 zrUL&ML92e+)oVTozzomPp-CMx!IKI!R?YlL)i>+X&1+KNSnu*Omeh|6?AK*(@)-0> z0HztCeVBXGTdr0bfKS8QQrLM=>d*Cmk~IPN@r2BF@;{E0VxTsCNeS)u4Wm-^ed~Xl zMBBYD+;W5N3&4+&8`(=d&>Tb;;G-cPNy1M}@kl|fqk$ENP?-RTriprX+2gu`t>+~5 zb7Ya$Niu70;}7Q0gao@YXMbH2w<@>5=X8xbZ6QHToy*v&Hqt@V8};&N`1vsIQjh#> z&4L?b3cDKziT4v5tnW^(=y~|O_f52%kNV9q+WIlz=IWGw9P0o=| znPGbOYw3z!DNbTLutdltOZP@LG~IgPu$I!b`iS!k++pYhR*Q{?>^3IRl?GzoQiMh{pi+x*9@WF`woRazM>R7;~R^?D-!&`*) zCf8R%0gWBE#^KLbPcBRk#a9O&HSPam2{pw|<6_`B&5+2YEANqN(}cCrYugvC1P-UC zBLAWf-@a-vNU71B4=QT@^BuRckKAVNQv+{{k*2XUgLbjnCy#2Gz&`-NW@!`D7Ab&wPZ>R%7d0v)!g zp;WC`udg||7${p4ah<$W05#+4^pzB!&@98Y5J*TnME;y&gwcxvO(9&Z^3_Toi!?VU z7QWL-t4P~_dwMbIIx4RVTT3`kPk03b+>}gnWn$r zSS@bf&?bT>`UX1aGI8uM4)bYmps1 zck1+uN08BOjj3ns#OW%K-r1Tu*^8k5U8M=a;Iq5AZNUUO4t6UWd1W!R{V3Pb(&?Zi z_lsi)a9-0`VftbstdX`e%`0H4WcxQ(w665KmxjS<9?OfpQ{fLeVCtFDvzQH9cJgS$#8i#@A}CI4um)Ny`Rx%l}!^4{SBP?V*a|!T|oM= z<;8q&4T;zsfmMBZ2%Ym=Wjgae;{E>P>Olo9tVQx9i$Eu_bk`p|YbYoPo~5}AHuhiI z7NA)^7@@DS2y)#rtdf}DePm(jQR(*mowJ9cprG7lN`@V_`04qCJ1Sf$uZ=IxG@nWT z@QPWwV%%B_(RMtVygFvD1R7rv@{P3Af0qS2D7Bbk$g`X9sYxOHWDBbE@Ot~=F(*6@ z3H?v&p(s(T-)U8y(RR2mf{S8yGGvUO(IJvoB`81mmz~bO-5C$00wirk;zGhTpDDA^ z4AoGgYRrr`y|%PY7H%>wNe~#QX4dH=`8T1ro#+4Y#QRaFvWUAz`}77%UVe4|aay+j z@@u&`kx+U$w+;);b1*zV&P@F~P-JGvN8N8&-A18;PSDW@5k3?;OMdaX5Q% z?$96B#e#7gAD#Me_oxl z{qiuvOXDx_McL7>qMR~k&UMlW7_O@B1v_4YvXuiB6qj2zDm4zd{IEyWCiLNAMY+Dc zGVrS;>4E#wT*r~3MRjQ<52x;Iu5hE5x#g(XD6t}0v z7~$oeh{(-x<4A6OT7k9{0rXl%Nj?RwD~hPJk zy?HiXc;v6l^ zX|geeiF(SMQxl+s`gQll)V`x--&xZ)e~IK%DyoN4h}}cVi141Hw`XeOm9V(I{HY;3 z`@0XPhVuDDs%lyK5I8>_KThXRPVLYv#ULy6z{i<(T3EaEMR>z{P}V_ zi=C|~Bja*n*+l`SrdbH}Jk)ve7SfMBGKfp;-hx|7&Hn`5)=X#_dHd0J6>sGhJ6LG& zBEw~7=Y$I8M&{9-X-eoTKt~9!*?F|k)+h5GhzyJ&8oBU?JmqR)uyjYa{n5c5)y}-b zl{^!i{W^2Gsi0Q5IFQ4=9sywhJ;-Lfy#*h4(#lPiR4aann36v-vwf3Kc4Ci$w z0Z6+*C6HEo`1`8EQo!2CQ57a#QhxxBpZ-A;Z=pdG{{TF%0`2w0Le9BIM+eYe9hYDj{UU-5Y^okBrA^X)&4NZ6sVoCc7To| zW*x0pWCs!tO76YDfcY-hqVL|wG|_&!f+>32HPWBe9zL!HWNVi?cc!n+sS7VkY#k#XDZVJ_$KkIyL_lyW7BaS;^nm;Ai5}zX;52QoMOw$&LwmO0G!W z0B?O3_nP`QK!Uc9pe&0m6rVR=@G)Ana}fGgnB#n4N{4V*Whij7cGe>DAFE?Re{xYn zgl+(OV__10FZ;GsvAv5aE8B@=Xyjn=T03_24sDmtyrT;uYXZPdfM+&%MSs0~sf`=b zj{tmd)^#(Ns6Yf(5bVlU8&7+Xx4}!({u(8y-iS5<#H-7W!obh3T2dc4P8XY980U9i z>K8GgCCmZS+)%H{ zFG&FZ;aB9iJQ8TpX4rNN2~h-aDj+eOa4wVDh>qQ-l{}7Lci-+4g%6+aR;ak2?TDt> z{-4>R`RA)Zx19S?ZSp+#*sIrPEzg$+HDS=B`8%R5+2q>TG86XW^bt)L&eYIN<> zutG%{;yIAJJdy3t#T|zhbk&YKPU_#nE-UnJZXbL9 zS&}%Fy$Fp3(4hSOinQiDTtAb7h4#~zI7_ZDl+E;O7Fa*UrqyBI`K3j3H@1e=)fhyQ zMC?CDY+VXMN0&XjO36!3{*eU9iIoSA+%dt@e}Su~d%a_%Xd4||8j*xhK}~_x%e&?w z?;L&@N6^ZTM4_Ah;3&Z&HCsF5<4ddx^vBL~^=Ea+N`TC}aDpqOv*`{%M5K&}FcoLn z#-<9sfS_KFVdZy<-fai{mwM1RRw5J!ksd&$tQa+LE`L^&1X9diiD6E%bN4FY=>pAe zM(M~;F3bBvh=rZ_65fTUmXx5qgP)7O!bG#=7r}~DPIx;%Mo=_GgwB6Y9#m=hJ{8p& zNX!jY=Ly$Le95P}u;nYohr8Louh0B@T-5pRl@KE^iuqD4q_}IrEa=X&HeUC{wjS{k zgD`679Np;xq=!tK>fJW%fzYYLD8vgGp$@P*~zn9-}BQK~mCX-o$r1cP;_W<@$U zkajH-+J|i_E$9;WsYv!trbc~h&yCn@tV-W42Wr*Q<}10Nf(BL+a>tH}{%_uL&Zz}Q z_Rv)J8O`p($b;;=&wrbdmj0)rlqu)e!!S7?kgL-&Q!Iz3=A>nrpZMnKQ zReDf1orJkLX$syFyy6g6B{PXfkv1ImR9Ichc{N+!2`j({qiXKctf+tBDf+SZMhKpq zj6*X(y?yrw^F0JY?qOY17_crebpWM@AsHCnRAAfnh7iF z&+k!=oSGDg=`5;`!&96mdzu|@*5l^bjVhHdH`js{G|hP9{Ag)FLtVBB_N1(p))cUk zH7F}-{0rW)a1XOyDF#?(+lZ6 zz_^jG*U)<}c~_YYV;%UYU|~RxJCGNsXOFRz!CH zIh2Bj{_0lhAyJuux5KY*;T@#xZCr@;#-nat1QLC8{j%Gnqag`jml@sJh7?mLbYe!g z`pInU%35RSdK%Th*N%9%h5za72Z1BYb4(!S-YB-*+sbw?2r0|zMnHNw}`)=p-pomD@# z955N4diM6oGq(OeZw0PSo+`?D)+Z0{>IXLX>fd zmYzQ+>tty(I3YX6&JNw;KeuB~@|kcZS`egxWCdRhq@C*k-YlYhM_*|5fx0rTo5loj zBC` z`pmv0^iMS`b287#vUh;SlBPJRyrtebM`_b?RPR&u_mu}d)8NTON3X*=V*q+MbWxV|7Eyqow>WBaV?T4C@))2rU|cvM)yuSzj| zLDT-)?A~P=Ymo8<)R)+~<3cjR?nVE!6k2Av=Sm8wD7@Q`LELsSz~^%03t`^qvZ-wx zv^EGokxVHhk)@T!hdV7EbEerF^W zl-W^m&{l-Mb)T4Hl%(z4?c^;1nsNl;d_MTrQZD*N8c&o9Zr=>r^GY}A8JlQSB+Fg= zL)YZ$hc+&Rx5M|}ApcTU`^2(`rj3?E> z|K=IPA1A~&S?-RNN7Rzg#4980cE=8NP_}*Y-nVArqNl7KV~GCcvB>_@Ls%6$h*iU< zBL2)68C|Tv-x-4+o+dTT+`u69hV_izzC(>nHg%s zIMvqUKrrYvN{`4~ScC|~UxclZ8vBQo=uG)U$o^u>hGY3C$y41p-04Yx@_|7iyC}_+ zqc%dK!qWGVITlj3dDNcM!Ah+QU_tkagKbHQ;hpZywnx}tczb8Wlt&o(4 z{#-QcCd=T0v52058DMPlp`iuc1l{{L>3^nPwfLc-Yq>Hm^O~zYA3n+YR>xn8I)7NL zdpHjg-El1M^==JbF(j@TMhk;VdcQ;1zWKWL;cfVmSiv;)-SH(}Bw_U;FWlWU(-1)D|0~@9wV&MFjD?8xUJp zS(m@AEV;eoR~PTIPC)un&<1xWJh1-3Dry?!`m=rqz{p_-YLBC4@t(UW1nE)pz~ zP}UUa$G5xusgN4OQm)$VNZOuoIG1?cTaFdgsPgBK3cS2s=JE2Xw4=mL5?&G1Wwp(5 z?O5ARa_BFJy^loVgV!D~gimCmh-~OyMX>GsH}qJ$(cA?m9tm$F321^uWuyK(;s5oC z!#c=pQr6@Qm7#{JM)nCWCW9+ zC7<7MeGs5DU)sc2b+5ecm1XkC104YG(b}Guei8?JrjUPbY=*{mY|>cpM8~cTSet~A z3cuOFOf)phkY- z#4Ekq-9pYr^5I@|poIoM4w9{mSJTMP`LjS*N8+($A#eNuU7R8r^dX0J#o#P0)VmY@ z0CTOXy6j$n)frnkKkzz%KAV5)*QR>+2ZRe66w!N;SkJ77HD1GT7~}uf z0~uxY{G#)VxE!S-WtM}7j@{Lp6C88me)Cbw4JaC9p1WX_<>`EY^-9oCiuZqtym2** zU7M`-^-{>*XVGk$q@`|c$8$Fu)UrNI@W#mmedS83C%}v4q1+9#T$i(FP6%qvy?#!( z!s*L*8=Qn7bTV_&==0u6rbXt0BxTLB)l^EQ0_tyJX4J`9nq|hCye(UDY)ELKPL=3y zvxVdKT|`Qo#W6Ud-!ETa(ET(^*bc1BHr87jQk0ObE?(vXG7q}*Bud^Q29n%WTp25} z80C{XzVOty?uZTwS1wlYk!2K&TBPt!xxm-N~v>jf* zwlaPHe6`+M2rA(IE`#St7j7kj*E`=Q>M)>h?Gh&1hFpXAo%H5gMQ=2FFt-Jvc?!spo>Vvv{!k^u#+Wwm|8;^fmQ$qX_bN;jjLu^^)1~0ntX?Q4p zd+r@GPTQVF+m*J+j$KN-doh`*Ss?%L|W#tKZr0sX^Agysh zIhgZL`plMm75SnGHM^8OQ*)wizFU;0sDWb#pZ|%T>DdNu+8UNkPOcggbqVK6W7U32%3 zc;E29n;WBk@JH-aGtO2{N=HRf2HoNavnH0D@c0pyurvi@vCB_=C~^uPht8$BD>{?e zG5g=mHPKEn$)rtok$H8-yc703#)T5?Lf1FQ>%r~a$(Tl$zS}GJH)g3&ySxV)(Qqvwj-a`gP+yk$nwaZ=jd{IT6@Ija*b zhwgHla_nQBsdrj3bh{ig5seVGl2CFewl7BIrt#vIM>eP|G7_aP$VB3cq8M}}U~Oz& ztOofn66_Q{_{3!Jo(x56Tzy#NzxF|JTvwwhjx^5LuYKkjnC!L?+qA#<^-Hx$T$NWr zss7P~8VisZ6!K&0iI<{O?fEL1SV?_8SFjNRalZ)76DP;O!L!ACgVHCU6 z^Bn&M{mVLcf8J-LL<=M!1%j??hTRQTd`?93XPxwOTeLHrO|Y^dJW1T+$xwOWxi?gU z9T0fJCa=t!K`~#|S6eFK-jZS+b#Ql}Y0zBYN`;!7r#5jdTZuRQ)h=D{7)>ecHRxsa z(4BXau6*7#)iLzU&|V7?hO-u1_?>nj;8|mVHhwqJG>=(dR-q@Zc;QRKh`t>#gg;&( zVd+-Fve+(NBjuvLPteaORJJ8c8eP{IZMm`gsJg!3(if-EF}?K)w}zuQ575s3Y*4L_ z{v_1kZ}TnP{a$KyM1!p#Bey3x1I%8@1V}AWnTX&O*J}QwyN}ja$7`>WaWXCO`~%Ov zBCb~WBn$Y=dG|F@3m&Tw-df8p#MoBKT=~-{)pZ|sT;hL1c3yHo?%-~Mi@q+AgitdM zUkH_DccQ;2x~2OCi`AN_Tfo^sY7v}@Wx;=SNh(eCD?_Q8vr@L5k0GyU+tBx)MsnhV zk(KYJp)Im<7jxeo3KLaasqaaBroCP<)q&*??JeYpLVOB zLNI4t>milqaDK=u7$$(426WDlM=!++1{l))_y6C#^N^_UQPIamr$!|>B3n_2>%B+R zUAua7GU!r0Qy{5*B->R@)6OB$4%^mA*ku>?#gn{*SID7K=k_*Z1WW37*24TZEbR@<3^-Dgzed6xR!UzOMS>?LZ|wZNWxSZt z&*j5}SV@U;pD1N%^HY8I`K2h$5e*D#;OXp~Z!x=2*WT@4@K7#0oQgcDu@Jele2 zFRAP;y0h{qzAhF>2iR?|tm>;z{M?}ZZP&m)=X)lc#aj5u{Klt;ys;%24R7YOxu3DG ztPV!XUe6VyPsj6_@@HGJqKdLXEWWdC&Vc4|UZx{YW&iL!geccR5L7v;tEX_A`%HGf z`Z}xR&p~}(XkUNFEF~ILa-xSZY8Oeqg7LHgK4XkNn?Rr9`P&WWn+N|VnF`loEKzKw z#@98E{+ZRIT$-X$+WCxoGk-s8<~I08v;r~~(N#`jfTNUji;*+`v*)#rTA{nomiE4M z_?%dsP2UGoT!kej!=Y6mUgBiipZ`bGS4PFzG{GkL;u0K!E$$&Wgy0Y~xVt;SJ-E9p zF2UVBEDpilWwGE6fyM8>-@W%7e(mAUJkwLtU0q%ChPitaX4$v@PPh_pgqPTp9Hvo5 z2OpTP!rb>e?+9sc+Yo|oj_L&IcSfZG=s(852=Z1Ar=jn+>A&IZ9|iKQ3B{X^KYb+c zQ20u3^K_m(-BL=`>-Nb$7Nu!uUB-48tl_lbiP1?>QUCWl{vFQGZs7+MKe}=0H4B6i(AtPdyhH!;PJD3j)rNy6&@VyU+f?+}Sq3Glao8BDP%qE?B#?y2yex9v9qwU>afd zB~4^sb1%&;K~Mke{F2Ls7rOFA+X)gD*(l%St+7we<~C*uTeiP7#$)|S9kB1r4y)h$ zp4gpjcElNlyHagyY7<_%tueoe6M3C#5-r*c+$-->7${sQpkqNg&^oaPc`j!21p;dW z9uUtQ0(hU`)DpQVuGDv(oQ`x|RCx0Q{?wU+khES?oJO`)EQC1i2p?DxS|pQhni!A%lbHA7Y}eA@+s)O&X*V$2h! z%{nL(rqy>YbL<3a=5W%E-44-(_tt}CIF04Y{UJZAi#j3dm{5_e9@SJlG-W7Bk% zVj8rfHoX-?MrNQ@3mgtLEQ0)1fWRi%=-v>BqLWj0Y|-9l%y>Jh@KH$3#h8YV(OC9O z8ZDJ199L&M^rEzDy6%C)AyaHuqp6z*rl8r5S+slj4DS#%XnFf=+4S<8);QhZM$*>% zqQx$wInip`mw}|2JZ5_+POHP8-k;A8AU&x+JV`OtW4`#!^}(C$^~u@N_gP!BO0S!6 zu$aWRvVtk!gnqj|`MP4+JdK;k!ZTh$Q7NO@=->Un7HTP+Mr)Y^!=6=RjhhxA< zhSI&zEFu^GA`dMVFq{beH}l!oz8f#EnIf1cN2+i`6Jgz;1m+R`X&dyI%BkbVTR>8P zp=)zmIdTXsrVPQGwNQ?S-cgVk;KQ-jGE?1 zV%&7Yw`)!SounLn&g4>j*uG}~@SW}F;wKuiMWYZSZYfj^XL8A@_=cr*3v%ODG9(^| zD8vSUjxy^_cQa$2PrK~9I#hi-T@}lgnsdqnm*=|~ZnQ~ZyLk4sTm?-A$-_aI+^?0|@Li|#+AM9D{uk`!g+Qau! z+tGK{427hbtatmqpB*XRT3UbHumdyR6fZG3FFvW^Q%V}BuuKAwL5*fP36TgO7jHV@ z`9N5^xxbkeD^sb4&rrHlzVNrKOxe0p)XQ95-CEvGCI4w2vE`OEfYq|HJMK5vWlmmQ zY00JeSgN&$Y9SFz6tAx;o6(is@@;HnrHYH~J3}i?m$u7>OKv|&+xtZ~A_j7gksurX zou^V&ob>=@37AH<>J)+ZtY$L`rhVh4f|4xag6miHUmWg`Q-~K)!M(?S2(<-brv#IF zALUkc&!d)&{iwL6_J81H2TTTS*$LQ9MpN<82li_dBX3&HjM)TmW^rUAzIc_+q)@Jv z+{j?IvU;Z%m}9ZJc7HBuI5TT{8^u2BR4P*ZD!tlr_UR+WT8vm_Al&%+-{=jhZ+4ih z{b`p!>@G)wcGI$^T~^--_kN4{p%s;*O{Z z-9~P0ouDW+Tv5(i6er_w<`UKiH<(TFH-k&V~2|;vv2w`#;ZUf@*Dc!UZg{RM- zHjcah>{or>xHI{Zt!RmBM_b1)eM$RHaN6DnNgrvGYn653j^!oPo0Wo2_o5)D_w(m- zK7#5Fl3)Kc>C{>t;W~q0uQ;wLdPi-#8^%emIhao0jRDqg!_$J#3JzMxZ|3TKJe_Y_lJ- zx2Fcf@JKG6iNH0RF{z+RrV4gzbd>*#<@o)z=5oWSy6s>!tJXb^x!~SxV*Ba91x7duK~{V2 zhmD%Aova>gwN*}?J{;fBj0f0n^6I;6^zN&T;&r;LIDN^HtV@MCclNkZo@&5mTUT=u zdyc+gp2pGU=j~$7U)Y80=g>J9{v-e(SSSgN;DxIBY4<9Ht~=R?|# z4lSQqJ4o4wppJ2UH%ZuQVq^7mWhf^Xggc#;m3)y}$$I%(5rN{Lr!k;Y9&F zh#gcLcg1^Heh@)`a6g0&wwEf<&cd;pap!~ePvIwYZu_DxmI~_XBKm1s!H%i>eFW=g zs4bh0{Kicwmz9C#paASgtelv)-w=$8fORxsZ>65N4e7+xu<}754%KbJWxH~}M9Aur zInBJt5#r}*{_QoLBu=R!L zb%jnrE+`}&op*l1dJ*N9<{3=_+=u4dwnh3A+vZ!gEuw0rUmG{+WSckBK3d;Iy*sT_ z6{t+Re3=vBvTIu0MGl3H?EPgkaAr73%{{!Es6Ty=rnm=X;Y-x5ynk5hySJz}+MO`@ z`=8V!WJ~Ae`qF1*yE@}Qmj;TI(ml<7|MWa&v0yX6+Xja$KHpx8+l}4{v#ImWjVK!z z#t+qe97D+NBE*Q)3yt2GC#S4{i9+17&4yc%80{!TF91$aO|`>N1(^8+93|#zX^~r zL$BM0#W* zc{t;KIIwcKx}@iVtHTWMFbdyU$j9TorA6j*v#ZC2Q2SE>D1bTCIv zBT}sIu;xX2Cf`}fSGk*X(T?xuZy}8Ag^-!+DBKjy)UU6DlodDN7`hcloj1mt(oEWjab}H;C5##Lzk5dWuB^#SfBV57C^ z-QhmJ?Q$%8pt*D}QQVR{)8BxFO$N?Wlb_{l$BTtJZ=CJhN;lj4drfja-dAhn@o1lO ztU^(k>D_|w0O-+vNA9JE{MCNeDp)ddv=tsKc0}Bc#61ZEhx%!8Ke%zl=dmp3Av^<|h zi>n?-?O|P&otW%a$Df1XG8fF!4>n74?bz9g{b>r$l(z!8CQz8maexW}vOQwytdZY0 zgwkmKx+hLVVFjLi*@F?Q1#6a7U-Ov7jo6w0N(Ddjh_sE^Y2%;V-m%$Xy;5ierY-0K zbP(qSuBVRzQgSoS`S6);y!}?7Gc9L+j4Zh5x=~&%+n1aA!vlnvEI*@{^>hO}Pv#{+(x|f+cV-KzLPO2|oGKf=0KslU46Z}SvSQQ{X zRm~JpNpo2_Q17G{+ao#&TDMPTWiO{s8ffNZ6fk1LB=}xI(2t6q9y$J_NT5u%qLz6C zEi_Htdb{#HOKYYCB9(^1&%Zs@y_b#!PtOgBM(+F;`6-y!23qqI&Qd{Fw`T#i2Tx$G z%j&@j%qn*8b`zdYRox6n3B5bOIxxni`Aq`M6fd>w8#EIf)a(-gZ@6p+>hsQ0vuMx9Yq*t3ImT{3!4cM#O*%^Z*oR$SP$ z$NO8;E;k0eb+tE0Nnw=ZiX>ALyWf!=%%5C+?eDnzLmK#!z4!@krOZ*k2Ne6NQS=d& z<{k19dRaK^eGwWagkhQr-&~Io6PW*xbC`gmoh_KgwQ?8W1wJ_vf~$pdhjpI<@67~Y z9qG|6UH$N6>$<|#yosQ(ayue_AAEc7HD^_%WgAS^Hhl7!>6%(vFv)({tKH{CGXN5v zH*%(@Nx}%~VWvtfsDO~Fg}k6uyK^RFkCAA*A^G)(?7-tsF;DM<-6z5J^Z+KD6tWH;R#NWIK(reYDz?B4k}fmsE9M*>Vqov^-kfN(Owkz2jc2 z-iXUS)x(Tmuxzv58XJ|;RY%Z)=@?1S5JH6qX7NdJ@X3e$P=sSq`|N0K`MYwJb<0aW z9pYNt+*~J?|M?k}HCIXePu*pX(4Y9qyw?1u1+%;p#h9=r#@g`=QWJ zoAf^A$*2Xw9uStPyb7-X;0mTHtc)>8tUHm%RhvjJx z=Am1!hV9v|Q3wjZs0_Z?FJ=Ai04}^Os6JSP8SVriZJ&93LxP2qe&d83u`con^z|qT zb85e}5ZoNdezL8saOA#MFdc;!F20Z(F0R(-@6)~m8y(NBlI~|-B8x4%!uH8w9Huwe5cMbrgUdpuwEbJmccCBx-QG)Pp zK}Sbqd}pzeQ?kr6ZOJ$~t|aj-UGg*Ehu?P%O-KeLn-dw`kt3zE41V1mB(iHF5(oSi zk4?+J|8ryoSqthUa~_^do(|IgSG5K_)T-?X%KK>2>_L^bK05r1lt0}^3V~}%_t3r# zi5#hIckF%KA@?7EFpLax)hkzAU+vaM#`Sz!%a;=&bv?F^j1va@MmV`M%=}r+G1IXo zAuv>LwPFm^X`+ZLnIE!~`(wW-6@MvbKjDBEvPPV5eNq73Ydk;P?0-i%X{+g#uT~Dz znnAWe+bP0d8JRVysIRGTlT?&7G=?xfRIb1Xux}ceHMiaxJVA2mbHioor<@ozd0*Zt zU-wPh8xpq+r!HRXnE_q+>gfCU>#nHvEP`%xxrMnG3y$j=Ptw~k&s8`>o(g^|gWnBo zTVn!tGwchsY@+w}p|#sO#wW1xUYFJGyXs?>03<_=PV(-QOSE3ajxJRaiF?0OZuP}~ zw9)!^V}{kPetRVs5%Fkke{A6wOISP)+RH{#aAxcUuI z+4Pr4dA_`&Zi#r#EnMI7xM4u|sz5!f@PSjxrJU|lAueCe_`qAU2f^icgQGQzR>=9C zVWCV!Ctm-rfmlzm2<)s3vmGiebfv^CmEX!mR%`a4QTK8?xln?NX|cdx&V(!u_xITz z7L?P|)PZ5=?d}&4{@TfL3!bjWz265#7nMH)&O4PUa^5M-8O2=745e?8X@yVp9@hEB z(9JYsW*|Oo3B?ri#pk{6>^b6a#TMOQ(bAHg_>;1?1bk-$%=!i_DHOM$F+VdNr$5Sh z+E(9tK0qybt|Y0ijPH~D{gGfYgM*kDxpBrsYem-BJntQv4`AGWmt#F`V2O@IYB6z| zg8Y3KPU3WPOh~Rdg6p_gfoxK>Vo;4#ZK1^>h8w(6*>U1?(rE?f(ZY}Ljx_lY^?%u% z^8J`fU+g0Q#v{;&J#A4tM>Su^h+2973}^#qPfS`G!RODP^V{1qVr#qj?Y0T5QzaSj z8c%%q-CNuB-F>85cF6FYc=igigg-BN9s3@6$f{b)I7r9z##LhRRpLj&Pt=bY}BluEXG#B+?B^jQ-N;NcFRbUA>!{M9gWz? zWc}^oOZu&<5RUuB5pWiG0b%b)YCp=>Rpio#9eef8a^X4OKzg%z$E7PT5$ZGFh z%}UQfb^mTCj4d!jfhlI9(AWVVjXB9^jFUQDH=1KTGtv>^RytH1Vncn)@=M0IFyEfw zy<0LsnfoIaexXqr$s_7cC3QqCa%63%yl=Vsf_rEbo95cSbHqSABK(yB+~oIYP}wCcyQYCZJ_w4w zD8z+ej1`Ipny0|&M{73Jsvw5cl)6I9y%w?(`U=RO-CfM zXBpoY7h|PsTWR8>9Kg%W%rxcp0uLaO)kmI_<0?ECOsdA6V{AkdWH^K=zk0{@W3#5O z$%9nJzt(uRk{i30A2Uz(iIeUUF8VFBaL&qG+j%wf1U}oBrTDnIReNZ_mfI; z>NC2|P{A|@YG9@@_8^uG(k2jWC%~nYq_31@sIAt#kw0Dm?z=>`6ncoksgm;CZeD`m z4vVEh>MH82(Z^ z^4RHYZ{YVDdl6A9rS#MNXTt{8^QCBks+^y&;|Z_$Hc9%NXr5u{`SN=V^oiIjOT0>} zs(Pg9rOdLYL-iLD&P{^kuAicWI!8l*NvCw@MW!hsIk#gE_>ZCT*I7-a=+>QR+c_TZ zN?sr8t}{Y8-@6#^@@5r*29{udyzyeQCwVjxwf07sRqM0)T-3NEL%q`+#8|9zS3s~o z2lw^Q!~(&{Qsl5qDI@tq+yPc0iSDn_iL%|kvzVW0&Z?z=V4c{AW=OB!>KCn0_OM)C zf~G1}nV+;ApJRg~oj=4V^chK**aO!Ei8`d-Pjg-drve(RPDz=ISinESQ(UKX7#WWiA7%1>*jbGxyH#*aI7d69jsO2(fV z_Vf7w2%{9Wztq-^zqf0acNq+m`Bj=v*ZY;U3knBp3S=OH!@j+oj7h~p8 z)hXrtXXJr=%w-O|Eo7zcCI=u$A$e_d0)i(^GUQncw*SgAo{d{z&hy?TEO43!5X2T) z8(5DeTfy$SJZj_ZPgF&U(#1J)nPMmPJW3-2(T&>UC8c~=asxh}FyR^&2K3l{!R&5- z3l#6;(L(yrV`hhWD_tVC#u67I0Jqw&-OP)S3GB)Qwr6(aD$m`7G=K@iz6TJ=wtUj< z&`J)`oWmH^sUa#kgTu!)bk9u-q|ep-C^;-e!|aGtV_^GX;Cp(8Xu9;h##QP+d@lBN zdB@pR!uA(8?~-6vSJ9)AF9L#P_TsIVb-IK)BVky6F3*KpNAq7F*`D?9QV$`pZx0gf z%X+gKxYrAn^Dp4ge%Yl4gKzzxnsz#W-PZiwGB}dnSxfj`e6f$MkpQk%$*!+1$%tkr zgn;oOi!Xls0c@rRrOI>L$YZHiyWj^o;At zi&PeWjf+mpB}Pw{5^q=Wf!#XMMf$h7E!pC?nHSi6_kMiE=R;)?3miAOXu`uI(NL`up?PUu?od!Wg9*Zlam3YEzJ7Xw1dan8L1NQ~s3x8_x@S}-m ze~t`9$DZ3-cY^jm(0LN`U4jgwW8T9>UcgW&+tAoPhZE>}M>x0JqDBzuZb(qkChvgf zk?^h&l|6ag9@zEah-b9~_*-6#CBz@cF_qR!8b7HOL}_$~%z>qYBF9eGq7Cc>_U`U0 zTgPmn&R0_zYG2jb}z<8;?%%8J{$64PUEv#)cZ>CLYY+`f(sG;n_E6 zj$SH{&bW}C!O-1DG2ik$_U^yp+gJn;q@(@OXJoI0Glz_Zo9iA~K^sk_RfD-_=_tp$ z%?>&3r(+5$K4e0Oh>R~*Gr7)_wQ63?u?M}ums!rZko#o{Rz1<+ zIp#Gh+_O|^{qdK$v*59SMD2X?UK&jzwfUL5jUnB3G3=iBhPXm|bcVwy+4tCKOSSm} zCpXzJIKzWY%3D4Vqj_=HA{qMW{bb3W(R`a;l3|)q%vDw-XA@+d5nm_myD}$gV23ef zQw)5*?VfZZhR-zTU3gd^R!XxFr`jC6jW>9jf+oys%a>2aqlfoGKZN}S*O^r5>+dt6 z0l{d>6$6B;MKK9Sq3FwI5!1ekJnY}6L~sNFXm5z&+q?&+&^<8L#nDBd%jkPgvuC`T zk*95zO{A=R$?2x3ehz!~GHZTO{Uw<4op_2dzK4?5RDLQmdNtEq)IZ||b!W_i?uqs4 zEO8C7nRn&C?Yf9=@~E$HDI{TxUACH9{s*4b+r*#A z=+cN*O-gG`+MT7`pV6*@^1|0fN1w=B41nF6{6t4N3dXExSsS8@aa8YHu13N_T}W=L zeiayx?=4a2d?3d)vX4sp{?3)*^gTB#t`WC_Ci-`mA<8pnen;JnW; zE+^N~@~T>KIBvR8GM+LLt{x1H`p^uiQ&toBDX17O$f1f)^g?rYJ=zWUJUHxq)K;AG zLYDp0U&xQ?3Y1N;+N}A-^nF;=+;TYOhXL^6>Ee(clBYXxWE#QB2jdNS&(K7K_;_do z_ywhR`uGTYrXXC`nsD5jJoLS?L`^s$RT@ij8DOn=T8LV zRZUO6SWoKSTc3!N2Dz|vyx;UMGDViXEDomv&x^F&cb*S+1{}7Xn1lEO-c=Mzi{K|c zIo6xmKPbtv^SaU7l?UI_;;v5IM!R!GUdX{@Ss~h%{WKnusu0S&ggstZJhdN@~ic)criDa!!v~tz|Nlvu-&BI%J25>yfxaU|98fcr~L#4R^SNr z`=lAFYnXK!_WydpBMGfsgbO{h_aH1YKE*6^-mhbh77Iq!x@@jk;BJc7G!#caoyxwx zN+^rY93$gEE@`nW&o?`%EbPne*Q1NQ>TSn(6E8oSMC$6gKh_L*_<12lUQpp~E?kk0 z-V9`YqZr8xrwCybwAKIQvAD0~U%Zd~_qHq2@hs8W=NJ=ZjNqaM&+?)g%*mE>bE*Am zQ1}Vp1k|nY{3|_yEbEOmGCS|fyYsX|&nms>KkNSU@qyicoveL(ZpdH%Xx;0>>ROz8 zl!xy|b8yl9^j)oB=7oW;AhUbGnp?zx2e3XFsDXC6U zi#|+93>>MJfO~Qw0n}0U&V%fePdC#fsEQ*XYN!BRQh!@+Y69|Lg#o1WxEv(818ZPA zSBREZ!n@>Woy1!mucQPODIdk~=6l!WqPGF) z$HZ~Lfq{hRjNXsCGC{+l;!9Zr^JwDSLL6HC#KGLdsKgb2QD|8$84`bE&iv>zO8P6B zc}nJiKI7Vtjge%5L5N?$VlvLHekam4E?*y{qr-l0aDb|!4o-s2Q!zyd3W!L=muL$9GTm)!>20ZGwo#k z^*{{{#2UWz0ZxF)ia-P2#wQct<(vY^=IWf^uu*vCzJJ|;>;XheBh;fQ!= zb%^*?VTpo7z<;{P%IXQV8r#0*4Bjor*)3m0^nknZB=x{9v)zCdCls_Ld7?Esu{CPcV_-K4(krkBSpNZo zCZLQI`Ku}sLGJ(`O6KEysns!}X!LC3!hEr5N8pDJ4bYxudUJ2|j;zWUL5)#m%LWO4 z6cbvqDY+)YQ3r~tpE|eQ)qJuJ(E(0We;x&_#x6)$Su?*OnCTKe^{Bw5ieK~EL z1a)_-t8f%t?Z})4@XU$xvZZM1{mE=(i3j5`HPj-7-wgMDwDY07(!YiU)?X(+vPsjJ z%vYibfXkOWcCY#>wT}AtvbL3s>N0w|!69x7Dc?{d*_y=`$7mpFbyc)S`nq8QZnR?Q zEc6Z)QUkv)j3`XX`+OKQdL>DRid2AHI5gfQ!zJqvxW*pZEW!SOlC{;IL*Ha9B3#b^%kAz zQ6=y@K8X#Esv%5qll68J4mp|)JL(wK;mHm(^Gt7HVOssDyzrxRF?Il??w=!@nZqG5 zf;%Nr8$Ul!rZyTbl%R;ZYv~hJLfO&M) z|I1um6?lEw23;UZ0^4Smb^t4_!Tnyh2!tPyxQ_hZT?w;x=i8kD(_XVJj!E}$ri;H22K930uyD#n7$rdIeLMEY%_ z7t}Dpg!$DH<04fgsg6%a6G5S9XtL~pdKlWZnk^U;CK)W*;X=q_T&IR)csmxonB-4q zjX9V;dhaJrb7p)^B9;F{`p(U-J1a4|ma==uU_R-Rq(gN*-)8GQzOZB2v6rYM1b)=} z{Kt`7NgIk^0i68oSc$Ug4Df2fYz&r+^)La4N4;xYtMPKltWe0|ZL18s^%JzhF1OO_ zUVJV@l;{7Z)u*p`&WGO{eE{R#G z&&EdE;gn|kED@oA6|Y7?PYJiH{^O1${TAy=FwVJ)v0bt#ZniA-7!b7cIaH@b!Pt); z*Qk_5Ylf2w*e@R>-SHQd+U~E|F!`*pLk>z|BK4uRgy|aVpYgXQ%I#i0Zg>s+ zJDQb$fl-0Hp=O{W%}`;K(y;;1o<^mOZq&NvRBbj(ha6 zO296@RL1{o_;LG>CIn??d1He$q87ILq$Phwu)L?E0&iAAx|RKfo#5qWfMIj98!7AC zf8QcyOEOfW7xB|k7X=KsHP&k>Y<6J>Oz~~&!XeSNOVUNDn_b_%OTS@X0BE<|mnl|M z#UedB$|R$yjw-9gYHLn))x`>^l=1)jB5_Qg3@oj!72AnIyBrgWNPJ~Bwh|#9Y9X#8 z$^tN#jsUynEmafv6@JN=$QS#~g|t{2rqlLuqZO_)US2P}}FB;;l&##ijN1 zFkwEz7(QC6Mb2pK5}CPAS?{X1cMHq~KCaUBPE&GfERaf5pRkgyQldL2NJQ9206sQdVkah=F-9L#5_J@fF76F>C+-Z<*8@+FHd7Q@eI!Gx~A zL91Oko4!A)ru7G9V2e_4yFKc-T{1^@k!PC%+_*iEgA@;0ILR2F+z@^4jzB_#u4_|y z_PUo+T~mm6{{0ksOK)Rv_0_Yo54x&p;}_4b3Tw$a>{NE{C~kfpLZzSKDs*VBb{@&C zY;17$zH^4bFv)xj`962ktku%HbH8`46FMu1zv&~Zu77qs;gdG288me==2e7HSKlS? zO;NO?tGvukH-7LxT>d!>C9K}vfB7xl(D0aPrXY+f>z)isqjI+9-vOyp8uJ5K&*Zcw z9~;gPl6E##Ba8k5!5>DhZ6Y)l#T!a6%TEj12I+AUo(ZJ9Ykz|EKbkYekjeaH+&86H zE$NBTX_@GIjg=)=WEyJ};>!Qf*JHIN7!5;(1 zkAb77#_a__|GX@g~(sdZQJ2 z%bD;`H{E+GDsHS2n&EBjq_u;vxUi^9uFtYb8PJLZC=;o-aa{?`NIl~0oW;&;D77f1 zU^>)Y<%uYQJ!@MOrDJAxVd3QpB;spyL9oyErsKqS9|8$NGiiAj>U-k>&{MM-E8;E7 zSElQ_hm~25mQ)myv>~BS;`A;Y-Ri_6PlW`YnY3DW?nQFsGTRwlMDq6oIY-A=k>YmxNEgd zgl-?oauB7$nVx(|Pin)Y59C%Ka7e=D(oNFu9N}oB0TA>_WE5pg66)Y?ZQofFIe@;c zF~ahot~=T3)=UO9&v2`H^Emx-r5U%uxzWYx#>;{1AUEjMfuXYM($D=x9z91JvG20P zuQwxvGC4_Dtnkv$yNr0~>J7nRmp{oOYZI|jFn)8&EQE!4epsyW2gELsm|w5`Yg6<6 zt8VCuO5+#*>iJ0OY_o~*C~#>#!FM0?78DI)n0UQmKf5&4@*I9}eIfiHg~Zz7%3$@K zD*g6L1T^frz6*AH^|vd%p5ru47z$J#iaU$?by}%&?|}5hc7A-^ z7c-`b6VW#kM>y&%uxg7{XN|sbHqy?}UXd%p*@4#rK#gqqskf^QB# zTm-nZmrwB;d{hj-Ox_Q35eB4l`q1k3LElEexMY(XGBY=@M1DZVrK+ow&dFz+l zL?Ez}CFu4`KD5Ec5qd3V{xIgk2m6LDj%7l-WuL!1p&uw^s?NLtc?T z!!@?cLdRQm{5Gsm&fTaGxE;Y)MgoQLm0Ys5f??KPqO$$s*jn9JBYY2X1(bdp`d@8r z=~q`*XErzE;^MNnJ~ky&`d>e2%H#@>cF@%Tdk8!gM{`A}!PezR3#N)j zQ{7{q_#cqH7~5o-@NwRc6(=DU{{_g^it0Jx?}YwKV5#`}yd#FYMm>=Hdx#yFsQ*Wz zCF-%^F0IZlYW+vd0O*{S_DVrdPw@rUMlP}A7jCk~B9)sn#*W2nP|v)$6UrI@?E;QS zz)~E-7QDwxj0Efpqro*25)0aH@fM~j|uCi+5`JCKgBERg!h0vv3zH{!%$vO_{v zAY^DPLz08#Y&=IGOO<^hi-Q>KfJaEE|Ayj5I@VJ*UZL4A$op4PWlSMxE@}e(-wR5o z>Bg%kJ*S~1CLxTqXpa@OVam6trWuMKUz4nYBg%*&)Rg~3oFcsuP2n{A*G=EYkY5{F zaUq5ksv3VzVzt7-f{y}YGmbb5jnpGZ0fz+o#W`a_G&5MGdNs^wzLQs(iC^1>YTu** zuzqp=ahXxXT~`$Ru(LL^64X*7l?1U!KtemRGAp$Ju}dgFWJh(pZj!hPi-PX!uKku^i_gWikoGa%U~CzO2oAimC!xI^X!+O zw(BRb&y)tR=)d zfPSR9zok=Xhq*b43EO|RBz;L4?9SEcNQ-Z10@L5V|8eBCIU%{cW=7uHr|JFrH<9Sl zL*X!E)#P7Ctd&g%Q+7C;Kx1B%;}iq*ZdesETzYUF#SUBhhaJ*}qBgJRSux!QxgY;w z#~g22Ilna$tO3WG;j<%sh4wec8I6r54T1MO^wYo;vv}WcCg5K3?S66_`0LJ?j&Uav zZWJ{1SWxO(EL8~DTctA&)ImAZRi+D(<*a0)PjHnZ)DLaiLM@7xO+d2>5N)U2N_rr~ z;k`%ybsa}#vT7V+{z}+ej*OEI#e4?772UbTU>G2(Cp)2QxD0S8@G{uK3aUBsH&1uI zb-!QEds%sVtHXPs5X}S$ZQ2xJ=)%P8poOTFG;(o{nbvnIdk5=5ERh`1#dUL{Ds#-_ znYiVfRa+Q0kr6k`e+wBF_stlE&m(_0cTsv{5P7_Mle}ZyayriqX9Wk{vaylT2k^r# zp>3zfly0JxkRwGIKYAsh)=PU@%N>R$CuF+`Io7&*;N+|+ImRW=Ydyw+mlj>7ezSC4&+WGt9X!LsA480)Cn|(Px z{DtW?2&y@ggq?=2k#g#;oB-aVGXs`Wmrpu6Ypal_t;PV%8IH!Zw`cxrpB>|9$IB$K zmLi`2)!SI{+wMoO>37U-Y~Ie(Ux%T#*c07wS9(da{J>w0wm2f4agS~Z^o@U*BzmQuV0CreF z+lb8xY?SXy?$a8!m{bT2id#M=r|HoXvxn(VBMFtBM~PJMLO*x_8kS|R*H#8YwC{|x1oibaRD+``zBPR| zEIiR}PFMH2=-PSWpsqAwW?K2s@)J?kxAnQV<_g$gJ z*Yo~gO>M>Dk!?+!bayn`mJv$0vp??^xzGLeb5@ZX!N_ryO_Jg9R85eT18t-O;sCJc zS39ulh5=Y_V&fyV46&^^@^#N+5{UnI^ySn*Os0g<#619&l&%1!l1Pp*5;&-mWTLIh zh~8=BXLuFBG0uS${F$tv;_o{QR*$kHs1c>T2)7+DdqWbs6xeUo*7woM)YQ*>wt~Z$ zXJKXHTb-EyU$}9EjGSqBaFBn=XUSwgcC8$@kr={v^HG7Q#ADu<$pUPeM z?uW#2A#--xrVnzk6cxr7$Uw7-Z?Y4OkMh`}Mmn8%+!a}O_7|xf+!+B*II`?=fJi5N zVB<;Xw>m3KJk2ES#Yy9{jUp0fmx>Su1gM3K|3Sj@WNPS0Gj-K0nUYF2N2^{$$|DP| zfJo#XFVhX*I2kI3@&v^rtUzb#ZUVr>v~V$N3~qiF^_sW<^VkX15k--qV1AkwSJ`m4MCE+{zx(7O4clkmWO3B2+=i;Y)SQHk$ZrTfg?k~rNE z#XyQYHjoBji!@=M9V<#|miG_!>-uv*k&!j)VTrnxuIcrv*&V z5a*19iOqi%!+G>T5%lM3idT;ceQ0?Yj?eR{zEttDmUTv~ zF|Y<|tNmfe+ngkYTYnn_Vb~jC?KaQ)m>Mq_tXNvZmhOAM@diFV;@^z(Z}BDJQq0@R zGAujouA8P!7`g20^TmZ2T7KV7F%k&Jviz_1Q|umIbq@P(b=~{imOW=_Vxi$7J<$}M-Z8GpTg_;dC0HUUTPjIlX$$1K$P)lY=z8s~&+xXbN+m&vVyf;aCMPSw{wpi+S z`u=zNx|oDKe{?!yC<@3wma`_hpz1FgtvPa;b*I=$4>=Q3?lcEcxbbn^0rIoD<#kV> zP6sKEoyRk@kfu^Ghvkd9n%06>dqJYa_dAZ|i2|(Cz!*jaBn;=n zSM_&!Vk2&0n6kK7~6rBQG2)Ok@jqYueyo)^u~QYyID7M zfFaL1Ha;O;cjU7(BLrKNM`srOJj>$tUrklzUTkY$Y`f~~5#Me;{cn*lQlr59L&=HA z)z{g9TRi05hS8HjE;ezAB<4}3aK7k0u4psvtbr6+drVnt%r!dgGj49|8D|_o4L0sU zuJID;@QQHy>1KklWcRnWxaJ)_p3`4&FjwvgR_WUmm5|a@N}+b_`V2zsj7Q;9_`9!j zEXB5E9j3_*nc^88VZ+9(InG&4u3dep|9*#!i0u3<5LZxJs#?Q;xFQ_B`zYd9zUM2; zZ&Pa^Zc7RPav9zkZWr*xYg)`$yHN@!*_RKlg2Te zEOm+5Q5DRYTOCx{`st*-SEhxCu?jIg_Y32`vDM|%QPQ>6kUg!IJh20m+6)@G+xbr+ zrG!*51H3{H)N~fv(q@lJmneRXb7m6mvhh3 z-*evQeeP{sU+LpgN*EpydPKm_TzkB~vC-NC$qFYDdu@<(O0+(EJk59hQ_2GS7issE z{-H?@HCzRwO)9J%XTm=M-;Jg)?}iMPY)F$!w!7P`vR8QTqwc|$%FEjb

%`hpgQp zOS9rmi12@w;|n^G9|^+uIck5jZF%_GRI!09+^bWhgljQw(64bTv zWL|4&<<8_rY$GZW5F8)cdEK;vIy~*@Tz~X@PbHq}HJ>-Q5G#Kk2b(f6&@m>0q_%1C+ zfh!H=wwDX|2~wj580Z6HnyA0wrN~2BOGXZI|Kb{nC)vsBRAFUEsaNxAx-(tQX@T{V zjRA&eov4j7?|J?CMNGG>#HO5XdUb?FME|}~6)0y3C>*-oq~F;v!5&)ZGFC>ZM-ZeADOsS99IwV=LpFG0P0jOI6{WaY#-Q+b`=4R!KUMJ|UyJ6(PVYPktn!YcTe;pH+ZVu<7q4Ph?4z+Tj?hW_TC608OUzJjQE$)_ou%#btM+%2Z zX#};@H@>NF`Wserb``Hwdoe>Kqm&JE>+YP`q-{|5nrDIa3@kr-(ci!NjJd4EdlxFh zUN7iDD^IWG={3CV-pz*mu?*)z&VJ^2k#Vp@ZnlzWvO<8aE6w}5|HDAr)ghJ`@My~R zh=^Jq8v(lIlGtzh8l+LC?VHe^NYzV`)K96Va5K2?YC)BPjJttFq2KCno0q>z?YT9| zJ_>_7>j{7j*rAUVME|jiP~@Ff98h58x6eN(s=n(I7tsEmZ-nA*RRV}?7+lyd(-q8# zG3_K%8rP?la)mX1E-$geF1fPHkm3wW2Kv2D39iK!_qm*ywEdwQbcX>3fsLdw<(?{E zr6t4*2MyJlodw6>pUtW?8ei68Fys>Y=>Gt|<-33k5vuls2mSWMrD>rU<7VHah&mIk z1GcVpL_190|dD3JPn3snL%2JV4OX{vHbJA>_#Js)u;UPmoHU)^6By7t}TjzRqR z&YPFMf-5R+f8S)_cBx3`s?8~}lsF#ghL}wd$q9wy<}u<0`XuG=oe1w(;0Do{zKKDK z{5QsT8?gxQ#V1UCoJpZ+S2tJNB5i>bjs3MYII+7$!w3JmIKPQyxTdB)=(tglRwtpn zgpf19Aoyo8RkW#^g1%XEb?tST1u0z~fT>gyYjBDB;Ev#Vc{|NxvJvULK!SJetG#ZS z-z*~o0J(6ksj~KInn7ldWzbFgM|Bc~iGLACs$*3$MKUIz74-(`xF%=a9}-i`c2O^5 zK`p^<>Im?IIzf#BpvtA;p^AdwnxW*sQn)`M(z*{py;Temgt`pxhjRF^%gpuaY^$)1 z2M44Rxb@UY3TC?7!>L;vp@_(4ox*7G%J7@hnVAs@x@nhB(bFA)pxJ5}OVX%Y*R~c7#OrC;*N*Qv=5IET& zVsN>*?3V9EEJ}LK$W0sB4QnrSz{7`#@YP8hO?h|z;6Ukb+Cn~zI+AWob6H*S8DBWxb`EN@hHv5LYlpj58R<_Cbh1UQtx439~Sg(m!Wp zs9F$D*8Z{+Bc>5=imy3mtdmCcCp;N)0=M=cz`Ce06#+m z5vZqj`DhdmUh+L~4N~*6nm9AIw6f}A z38m_k@`QnxEjnTi-iCIct5130;r6KLb@8>Gj-+);*45C1A^b$4_);@9cU2DcI~v|f18+-do=iJvFdMW&7D>7(G`@L(ce*ITFajIPebI+g z)ZCTlauRP~ytfe3%mNf+W^p8V;zP(y1{=xBdVOMX=6HTI?-B0vfYP%%!XDjrt7o6| z)HZ#S@Zt;ab*=54cwsa9!`;;ma;#6J?&k#sdmSf~sA0E}xi0Ud*ACmo%*_4?O8D-- zR(P^Z$-J^ann{xXReK#Y8f^)OTXq$+%_=}Nw}%S@*+)SdR}*YX#1l55-#xqVhGkyx&fGCH!Og&<1+6?w1X@y0NmLQ zGQDI)rM&do9&ViRtdRvE(Tlxzonw^g||1{xu2V9&YnJ4+@dD@W)#YCjk{^(>)L z=LCl5J)c4%HJLd&SI=uqD#G~HH@;ZK>)Yo}JcYPzZ%-ZLpC30BF`eWHasL<%;JBE7 zMe%O3i<0NS;l?NzMr(az;M-BCrr++Dx94MJ*i9Hfg^hjwfO8j2+k7es!3h`&kvH`{&8YG3?85)5Tir8k9 z=F+(>Z%B3QFTMr6lW4pt7UIFhc`z4r`)jcU{Yl=ZPX|D)#pO3X(PcjgT5pxyI8U;S zO|2+~)7iPqth*emgL*Tblf(kn8U5#9PD7?c7kh-cgpPl#9!=98&kVvL=X0n_zUG?= z#5lwFY-!EF)dlw4kmJGez1Bn8_E9d7Mms)v8iICT2b^}CtoI9DZtEz)kjYhYr?v9h zUXxmDW`Td=N@DH@XwU3j4?MDx$HWhmv+dyT%dQ zZNrjo=0?byD4%Dk$u<+bI2$sF6`+DB3!~zv>IFHwNmTHVh-M2xMYE;!(p}6O z4dm?7{3egY%2V-pdk$8};fwW%zUdv#AbM_&gQq9TpK_(=UnjrbbR`Y>i73&+ld07( z7LMBpu7+!!x5Fjq>vWD`ILK0eP65*uc--Sz?=gK;zFzpKLZWnv`f#_~5A8FGoXD;8 z=qYLGQTyT3rxgbOdDAf1(=y>;}jLj?puNczPUEHKhz@kbTc7|BlSG3Obcs zKjsx0Ju53T+U`{bKLkiLxB*xa`uqKAFXSVguYVP$_Y=`dOPKJf^k07cYw1AXy%*$G u%bccLV@eJtzeHL8`TYNtpAJZzN_EwdH>J*KF|9e&-)&)`s&tP=lq-(^9yqj+H&%^ z-f@V91%g<>e-N_=(uQE{?CaUtVC&bf-vEPc;MmH+v1t>B0QVNIt-=B#!a@Q<+qUnN z+Pz(LkLWfbvHjwE_DRdi$%^b&P(C1|EF~i=v-%+{unikHHgfQDaPZ6Q5ZWR0fBK90 z0pi)PZg?G&m1Q@yj)#SnhlN=Q!NGH~v#fnVKfYMjv9htRhi%xni37YLZws`Jg_U(3 z8!J0I8yk4H7x+2E#>2jK*8#2dyk{=Mc02Pa_=dmSAa*qCBmdbJqPXIfTlY3@5)j-b zBrLHT**Up+`33I_i^?l1tEy{0)z-DPwRd#lzjSpE z5r#)bzmAPhd?U@xFDx!ClUFFK>tcaezb^~?|NFxJSQigi*E%*fRyNq`x>(k^ffp+e z8~d&U>$hs1fn9dy-L2ref$wPe%dC$Z#T3sH`LEn+*(4yYG$cVL^&QTm9XyrfBg^H1L@}^r!bo0;AK0s?%Rhf9=O^D1wGsi z6|bs8)kFABA2l`U&zK<$O@Rr$e1Rcu9%e$JElh}m2@OTlIVYKrj~kqJ!{>-_@O(TO z$%Hs@w6|Nd>d2Fgvi&JkhU5V8r)ICghUd!k0+LlF$9@Vg*-(F&xD{E1i24R z#4&_0&7W~(m@^Zq9%pTNgH>fheoTm1&+vC;LLUx?F;sME@=VAdxuA$;u=HX`MbLu7 z|CC3wx{q?c)usTb^q@bErGJ(bE zuEST=B&y7GUcmL#Eg07G;H17E-(Q%2cL)LBcN6jdsW%O;nHYj16#c`*?AzBPGw`8{f?nGlNu6XH?lwS6_-obms(;3*Goknl z;Lz)U^M~Sb-DK(W0fUO}%5ekKQxk^Q-mA_PMDE-^d}yrIN8=C^dN5gqTTq%rlHtIc z`H`m?4W4Dm>16H;vFF<5u%iaY5=$EzrT49zxXHm=v!^7DA>>jMKR=%cB8WZ{A{8ym z`wnpDg#}pg;o4l^%39rhSfM6j&ym>|T=E2_dQMX`T8Gbw<;M&5g657ZY180D8Q&3f z>9(l8)FrcZTc3;irJ(?^dpc+@uwFb^ul>*Uwv#i4%z-=6l-d`#4h-toC-G<><~NKw z@A8CYDkTp+1_E5+aMQ|43yvrOf?F`O4DX_zDechMVq)na=+bYY)W#|^r}Rkkv2U$7 z{#&swsbX+8kg=PbS#hT2b=$Cie}nnE!pQIfC!0Zb z^~-(`diu5dK$TNkSDJgg={5VuTbzVJ-x2R+O2}v(Ot( z>7xZ9pKiWUsA>W?FvB4=k`tXv4bOnpGodQuHe8M<_AN?uU59P^B1hWFxieB& z7sZnw(XS4%2MvqkBQX_n?(+=qTqJEHhOxV}eh^bJZ9Rm4FuTxaqi-ttzC>k%<14x1 zJNxENY#%j%JS~3-o}z9f0%i6T`9Ox{7t1Dl7oq!Cn@?D~HjwW7Z-2CrpEOI8)Q|;9 zD#Z-sixmtxm1;~V@N=S}h;8SZl?r_2lYUQ6&%?CzUIxY9bin^Qx^gUdMVrAJFTjMFTQV?%XdLZ=R~WJ8 zqgniY1|K#+S+W4tGB*11R_*)~U2)cd))H2RkXwxh6AD{%4e`}%$kOXw?>U3b&?jJ~ z4bCnbZFz{4pH|E*R{T095>$N?vCGPwgsfsnWRbH7(kSGXZ}~(W_quQ$kKOwo9fG!R zTE_UoIh1Gpv6(M!nD0g8vWXgZy|S%tQdF%A@gh<18$oLBnyl84B>SdMUQ`i2+uh%* zloe#_dWrkZ20PZj$UFobj{`}Y(FV?eY z^#yo#lLv@ymGL}i)5~w|+U!XcPByY%Eb2b>6cpcF7q`FMN8?T_&5=;39IK4sMR8`R zt>apF#q%DMhdjk-Q_D|EqA9h_DAiNbHpX5E<&0|0y>49l*YG~AYR%#9lI)tLE2PH! zB*(*jc2!p*EeJ#NK3a^?yKetcSUdJlSiAqHo8!sn+?>6L@f8KeF7?jp`3_AonU;Ue z*Gfhp4*?q`0~@{l-A2n|iR=B`hQb0U2Opwalsh7es&)lE+$+}nSc)}qE%2`f|6nQB zA?^_PoJolR6GCDwEbqi`LyTm($1-qM?~5R*`RKp?tQ9XJ!?F~!rxsn3Lu=jZn zr~lF)D^`qHQLRkK7P}%B!`%vwUvC7fgw?0V;YNz=5c*+s$tOM{pDlE|+0IApxzHKC7%A4LKO2&%qa(d%Mj zcX`i=HYa822OVPJiFv-sHxu`2UE$*md8{}i#afLUdR?}Y2{jq0fRu=#EG|f-ge;nt zvA_inYt!G-pDz16SW)p4N0&V}{sbpxmN+t@qjzvj=w26&97D;jInf@mWTke_ep&ww z6S|_u-Nh-hr~izP$hMEBeJfz$nMxQeDT%Mf?O;=4t-G9rUzPvLNYx6=I9Ji$^lb z$*!|`V)jzt?TSSKjpq-O(FT{rB9^QTHjxx#0 z4KXac`*5#ys0*9VwP%__;@s6mhTX{WxLx=XkK|r^;ms*;wM3u4X*Dy`Q%Li8vVCj9 z;NYVp^|6m2rJ_vY2=VR8T0zYek{g;ST2A||dmXU7g7iUx?XcaHSPomySu#1KXixM_=R2qJ)tSgUZV5!uax#AdZk_+aQ82XC#S zdGDI*^Bx{^S;cmTK5teWM~w}TjYR=)e5q0iC(Fh%p`ZkAEX`|J_FM&q?G;HUD1fTt zIDM79?Us#hhzk6;@;siVgs+6JOuPn|5r9mq(i#w--h6}SgcLbO#k;zq9j`w%*XB@v zl^!l20yRO~N!48F6ehH3vU*@a5(Qx0&wqv?KyJE7ax1?^+Wh*mN=?&O@ot>hmP0h@ zF&x=GJ`nzokB5CU5Ifsiwm#YaWlEo^6?ZNZN^0WJm6Z9iasn2!V#wgfhvI&5a!vSY zG%NW90Un6Oa=B*2POa;$8mY>eU5U+ULfkaYHg3XYF9#@>t~2C)VXOPYrcuA!^a4M` zcSZ-||2nXp=9-R15Rb&AC2nJHz)xK7zkRp5Vta`DV%?^N7!oL3%yl}H2mCt)x{t?t zytUZ#c6%s)I+wH`&qs*?4GDzsEk~#^sy~PlO&P zy{sL4J0c8Cj{j0uk+p|mv?zIA41N+XXqi&Yy&_|^2iO8WQ_e>tll~Mp5(lc3C0+z& zpW3n+5! z-^hgWa1`uD`VH`5p%A*uDw=u(Q+vDFI~qm~tXH3{WKocsdCVvH)N^xC6n@l=?6O zJfQGV{&+@n$Lt?}sr2V>S@83*^fRIV#Am_v7)=PC5>rsb1sZn>FXbuI(>?`S!_%36{$+%=DbSVh4a9epX54wfn!;D0@r!YQ7Fro4FWgD=i3@Ij5 zyN6^*zb^>@G8dXhlifSO9m&wy0cVuFWI`<{WSsIJl`Q1Y0;1MMWKdo%alkK6*5QQk zkc@2qV0A|Bd!y5eJ;@Hndr9EvRe}*yA^;@VvDPAnGL&X1{Bk&=EQTDj2nPko)}7>M zL)6l9KMkA7`BW%Nj_eNT{Wi{Yv$xc=idR{O-S_BS#uhX*(&5i zfdP&PeN^Z^OI_-*I#{$+m`!6`!q{OZbaEa?Mj5Cu{PeLj4kTkwnl~Q)4K2x79ALCy zW5!u$!}!VH;2daWj9~4RfyDc z0i=qsjAfKeVHU0`llma972FlpY43*o4K{TZ-&#MN8j(Pb6lVF*+Ro$FfdzIC(b@1Kq^G)G0;I5V=@#P8x~O?W@{ z0qPqlCcyT0u6iDD^_DZu>|TaTDQydVW;2y!tFPK9#d7m$2NlOFilJp4?dSvKA$yX1 z<+8Anuy`jIdy=J)sPoR9YI42o@PVcw|>_*ae za6w*a-}T?XDR&9EL2!WptX=rfMzwO-YyU~D~12lhu`p5dA~t!*c*f{@CLTEwKf=|V2U z#kln;WE@R1BzM^pn~-^}GfJj;>kIP*cc1vWfluIC^#(*A9n~&9%H3VSI4KG&{St80 zq^k*=i||VsZJF3z1)}^#=cH3vmy(Ai;eA*`ay)4>w||^aL8qM3ihS$cygZ&)z8fTV z6d2#y|518z#!}m zVss#HmG{;**DurEUGhV`8=e*LHC=+ z&WqH(FYz3GCpz2ICHz`LdrU&;0}kK3x6y9qfuwvlRG4eC zIse3euip0ieY&GafPTwo$)Vq)AQeQzAgl*H6|h}V_5(|T51G)hMx=N%43s1sI0Ays zWsF>|#Lx`j#A1dRrnv*yHd=Spw%K(cH{2h8+49FP-8^sfjUzDe^=>x-miOqP! z8u8y&$7P|<5$N0>JuN)L0_FWeUu6dhXp7WF?|ipS(@@8$E zXaqC(yX8>-qvcSH;+U4M(hv=v`%;5>?Z9&bsi2sDUL&>Q<-%^9A5Ww$B}QD(Io89Qci03M84>5(^f4~D4l8pdv-s82qe82fN* z&NGerr8F^@wi~p|B2E_;nuaWFX);beWifEZMgX!xjrab|IoAoVWcnaX+UkU0HDo#u>@?y?nl6-tiaF4*X2pA zEA@YIExB7ZGv3z8_QtEo;0={_8z+4r{wsjc$P_UlHx2G!H7;yjltr8On-xAXVbm)+ zUhdho0pXkZwQLKy0$`_r%7H}+AOd_eiin_Z!_DfRVsT%$CGVpf#<{ref%&P}{I}Ni zJ6ZiCBP=t}hQH!3uPjaWE98_a3jE%}`$hN`B!`IJwJkFKDiLy8m-hR_1rJ0z8V7lI zAm{XN&r&(60QR#<*c|(_a|8m@TIc9ar(m~nF!~7pXx1YpbgF%KZ`oDb>u+xnKHJf>k&YJcj_o1YGc7M35l>u?myUSex$LWMOsu!U+vF23wfQGTO^e6d zw8iw5WYlptoVlgKKdccKNeT!?j5v2{?rMKFawTK%gcp0F z0@_Z&H)3)zw5U>D#(OQWJ5{#^I4~m_?&gg0JHW%YC2*HXCEnK*D%(j~A3fx_*~{9r zNFYjpimpAWINkeEchkminiCerG$q(-C+fAV zhspTdW?Out?m@u%Q#NDSL=}ad%bq|auh$!n$)nW)BCM z9T-hmlRX0a&FM z+7+F~o`R9|XeF(Tk~bxkpv@`rF%8|21(v4k(S92 zj}vO?>y5HOZ3_}#6rWC0bMs#~B07|*)F@*3?pd_8p5yiK0~Yu1oo8L``q+POKf*Vl zFM(sNA~;d#o`lIfv3U&2g{0yJyQLaD^~&RIZhfvPGJR8@Fdw83vx6>`o}>F=s)jrUmPKK^(ae}?DP zP~tZ-p;9*{l#3dttW+!k#`4?{Vmb4BIf!2^2SI#x`L!Ng2K&KnhG&`3yJI+t znlPo?M->r_0Lc6tFuK}RWR7Gr1_<_#dMaTZPP;_@*KnPOZ4#z$CgNzpY6!ZAHt_aN zA7#{Y63#al6DTaBb}>IEFIO?6Zbjkx;qvT9Ui-fmsY$VZ!VNtugJYUx^#Q8HQ934K z)(6=RVY$1;J6WodpI(u=pZ~S{h@odo<~c$b?THf~6Z)cnp+n8Eb6@3`qvunMzm9q# zse8dL9bN@?;sDs)W|?_vB$dE@gyi-Sv4PxEd3MsX#La*1!g*^xs^F&mhiVd1&E%)3 zgI+L;?2hy#oZ!WCG9fGi-b`GWX6!fu(n2b@!A*6>i;xSXa(3Mh}Jk z-67TF|4}D-U;@2a-Nh=cc9nK4vX@aUNBm9iSWH{iG+PHRZX)XrbN}EVfZuAu&yw{A z!|s>B33n}B^vs*`yJzQU^`VpVyR^f@jw??nlT@Zwz**LRw~ff9Mu`8j`@n~8L?xHN z4rz1K?rx#ZQS`HeJBCbkHU4t3+`-2(f+RK!aO1|Jl0n6Vq&qA$vTElL2Lh%RP!OTD z?f{=wkBg&dN~vATn&*fbcv02d*E1ob_r))q8t_|{un$YP8g9AQyv-P3MeibFeOwFk zEV*v@HFSRMD(Rwqe3zXyyyMorGFg%#EtFD2_Xg+_#N3*xw_#*6Ghm3I>9m?;3f(IP zQ|{C3395Oem#n<9FPwMUH+*I2IBeSjzpgf!WzZ6436AO_p!`?Q%Biq!=3IFABTr*r zZ-ANS%<{M?Lomie{(7_=@c5h|C+fx?03kkV!qLF*Si%T6j){H+V#jB{)F6Wwo#h0{ z?g8n5?ez1;FEAB~XbmP5XBN$1$1JAd?GiW*H;@fa5e)-&wJ7;Y<@i0rH+oG+sjAZr z99saBHOkmU<{Av+A^R_z-~@4~lE?LO^)J%iQ#hTiULrTpF8>T;4iF`}9La_j0ce)j zY_jM?iD3TAO7CmcqbrYJeyT|lZXw~y5u9kvj!W&Xl|}Z`Lvvdy4t^|fzVX+hHBz3@ zgq*X;m0x3Lkk^f15n9xP?(6yqs!0#e42Zxi`rKd|kv;A`-%nWf`w3Uo1z!E)=67v7 z<#OZg+eWbPKbF^~#I?Dp!U~?O>0vW)4!9MGn4cKjxK`=!Kx+(mg`8+wxaH4OkG}l> zw&KXrK-gdpiAP`Y=pdw^*X_^&HW5aXju!!JLM))D1%NwM0teVMRt+Ncp4DCkdk%)A zyu1kB$o=2_#(CIO#}IShXr7_wtN$gdBygFn)_|W#Ho**W;vH;a z&3@lS4pZ6Aqs8|G&MH2lqpS)C0)_oLBZy;_!hRu*>>U{oTB~*sOMTqPX4~(h&dU&z z2kGr)HUQQvVB>5GHNu83}`SO5Ir0K zje~PuWyTf^r=|&wE>(<8?O508PcRCU^MlI=srE~E*nyB)ujHIaQPt7s=nWftVlngjpr zqY<{6p&QB$&?F1Vi7{$D-?HohyH$Oq|EkXNY*!nbwFts&4$%Hr8}%9f#fCICC&s>_ zfo|Puh8Xd>)piYdheTUrn}tWe+1r7F`kr>t*sw7xeo&EC{9qww5R5%O8r`kwpI;=I zn&bo=Y!;XB`QVtk9&@t5%AO=ySyUE8TxaQKSbEp%l)2fV_eLDo`uEqcSw99W>odfV z`zmko^7R;lUIVPI8P?lw{EW7fB!?x)-IoaC92NMHYCe*5|h zefX>`5$pO2`vPYd78tjWhzV8dk%gH=mG`4qq!af&FZgR%{r(s3IvS6Z+3sS(nJn6o>XPz(!BJ*1hr`}5&eOUv!?eRGjYQALJ?ka1uM0QW?R4#n+m1F6m zgxi5b)c!?0O`HsOBeqo)s8v#W)$SSEbe5TETJL-&c6}s*-r%h~1Z=lDEbz{%IVO;l z>$JJrvl0V`hqNEV`mj3mIBzlc98gkhaY|R7c0f^07P|JB^lgC%CO+ycU14LIJ7ARq zU5t4G?9mNZvMX8UiQTXkZ%?$CgYWYh(a4A)L{|*8!h3(KYYIuWwA_CAOs~?>j;HT0 z!l0SqWG}Ao{57BPMpBYxdx;7$!ldK&!-AYLpK`Hhkc8W*V9$GMTM@!5#;d#N1a^@L z&93eV?8*jW9&hCi z*LKp5(pn=OB%6x%&lZ}=<=SNFwghoU^c%NrkFyJSN zz93-<;@!#V3hs#$Ngm-Q9?t)HGs{*tO~eJM??@ZZYS`&@v{T>paps`k(~x1D8M)?9 z1DqdLU%aD9#)pE8T_hK&|{>Az{ z)~v6px`3TxXtR`fXi!Q^F7){mOd$oI)uQ>om77qCmq1j0;sMH!FQ-7TeKXmID#u-u zUy+Q#(H}H1f*+N3`l#PuifnPUygQWVml^)r%E5SJs;-!hJ?p8VV`uMGN=XXswCy#n z2bzRTbr7eIIt3zrs1qA zyAp zm>@Z7rd$7R{FZMy75kpLkCcQ*wlA{r-jf#g+4M)Lic?4ZDei$f5`zc5_tTD+kWoV% zmRIWPIBF$J_0L9ZAd>^CJCVIb36ArrPdu*iFmNpMacV zm0+C*3B?)<;94Q*Yz@>(kH@o3&XH3-3ZE`i-^*6eEYrCCYUJ6woXs$hREY`Rd%#<> zF+_y{CiKX-8J9D5-*uLatavty#2)bFhE18`ZjZNn&edx@e<}7xd2-vU1n!W$Szjd2 zth(-7iypFLoKR+RxXAQPt~!gy9+;C0hF!};0U_%A!_;ZrN@3Nk+-L*$t=i6f&s=0q zt>+0E&zP>V1zohfJ%uSKR)JW}I3J+ATL_QN$sBqrpzUl4~HWo3Yi8cVX zdl~m*^SXr%h8@&oBj?{7FZ7kzr?#$cGs3J;Q`C_dR$kQP@6Gi(AgxQp@|aiB{%1Ul z`GW(`^tO+y(k-W+uQSvT=g@k5XXyugBu$VEp!t!!aIe=rCO{9j z;f{w)jW>Pev)4iH&!tAq>x`S?a|J8p1>Jk9Jzbelz`}hmN3KA>UPC^2%z@AQr?`(I z)F_)v+=d0KU+52EgRUhX z1Jr9ch$ns+n}D%{Z$OnPkulaO?%p2;EUVts9Ih5WLABYqr!2D7;{^ zX8(>hpD3N9$HKxRf+_cWG*4#B2SuvBMDf#>BLzYE?l#u9)+`+ z=cQjhyKd%lKiwsGA*P0OCr{F!CX_a5R2iXn86{C(J+`Up{Nv3UPgzKKniM=JenBRl z##sP#r;!WtQ_F*WcRy-ywx^@DE-#5Z!-jl{bI^M_*K8|w;v1JoG)>tb2V(r!SSEx) z(okO*o6))@v%UPTn;&f#KAk%&k<8Dwk)8Kc>}$Fq2Cvz-sn*{FdDdnc}?g|Ir13$;secOk-(f~9XN>|qc8!@xG5r94s zhL$k*yoEbTB#1@zdY#i6wO)KViaKAV2Nj>Fp4Bz0PTNLWDkjNWb}02hy{49ZN{?%o-U!}`Bipih?=H*3z9?~` z>P}h-kjl~$&Bre)>RPM%UG>;5z*<-ZU7-n+b%x_PXvVFsp|;uwqXY;}3dr1Ys@u_T zhm0lPvL-uuH)FWe&4-af6Zn33tHEN4z-~c|#vvlZ`uXL*L?2v;_s8UJ&KiynRKo;h zE|^Q(-Kb1X4*iln75dy-V=}C|bjC+Rrmc(>ee(Xfyck2y?CJ=y15`^Kw8fB?`=2rF z6btTZc%U(ct7I1{-PBaeLwxzI!&#es(1A}~!?;ffHE0Ehq`4~xC<35H{1Ky2MEr@e zW^Z9TGpl4+*Q}%CMb*S!5fmrs@d<=4cHLSOz=0run;phCGdAMCk__)Dy}03icB4~9 zr_CdUlW&js+p&7CjghTHo6z4XHy$=C%?_)e+|9_H-I^6XcQi`~5qSp*^FH`39zt!pGL1`@;u-?pw=Xv$CSIQ8Pzi!mN*k^9W!*%X_X}fy*3da6La@TX)?^<{v8W@BP*^3FO=gHGH0X->L3}+*e%J6VN zlKGiXX9D*lJ8ahPjCcF*1l=3f;TY*DC$f!Gz`%SxK*%4kj6C@7EGo2*nO9 z)8^W7L}|c6>(UfeDrQ$k-(m)V5t#XCsQy3tJpV%5U{(Iy4C6FYGu_LVooqLw)7(47 zdvD!LV2Q8uk;L-SQ_mNa_Z@-^X$Hd+pp#*Py`E`X6L+N5d&juZx9$cv1@p$6`E|0* zhi~j_I3(`;0Fex#H;&cP)sZZvA0t`89jQwy&fkPxOGmUG zxbdXF*>-8jM-1`8BwdM1h*)E-3i9+lK~ z+*&lSqZ;2Oe!4#-ey#uwf!Ohs3H3SEm8H|4lF4rAm@fvnRqfBJe8Pi$d0Kuj6k$}D z6Vqd?&{Nl<(Q{jD--$zq>1mh`NTCvC60c>fUdvFs*n9uJOq1SYsm0p+;C5bnLNoL;9iNmEA|`eaJSjh%{z^n<_~H4oY-OFhE-Z~ z1vrh0T62Y4K1w)SISmeg4i`y48KnFz^8R3xAef~hwyS-88j+md@F~%C)5^K~A0%4~ z-ayy~jQ!H_AsTzipJ;UVl|?RJ<6|KiPm$9#4vl-9)i8fFurMp(^;RD=Lz z*FGD8WTnIsF&WY^9oayhuPHLDDBZNf-1N~meUD6mE}d+cW0k4DmRQIxx)kdm5)=aO z2O_R491tB;xnS=8UJ^Dm_rto=C8hd+?U&0w%r;(#hWO{4?)ut4=bm1a0*fV@*82PDwJEqMJ)!~G*4`Z{Z z_*FgcEUJlh5<5n9Yz}$5b9ihi^Zp0S>Ol*x9(2ObgRXo74*L0)n&_-v+S!6W{KxkJTuZMqU6vSFaN&1-uFl$*r6TagN@(QS( zezdg0R$E%&^M0nK|Mn;PU9Wr>|9ck7NAD%7d}MHuWb=!Ybv@-BwF4UpM54bQ4G`bkA93=YMMgr-04lVa3J{7E z0st_{aFn!Yb)9sJKhYtRCuQvzCh=-QAy*n|FH1Gl-c_;~4Qx4qoYLTqmk6hlIW+b=o+DHI!~d2|Q}ABD8n*b+URgQ{EY zo|wG28v5bdHC0aTqukD?fizs#HB_kYUTVmb(~xN1XH0nw5kcQ<1#07uPZ59^x&8Fw zjc|eiccrM?(!rdRZ{Ek%2eK_*^;@}w_UKjLbdJ})Ag}H+B&#-Ou0OzMmtU|yziU?v zL;SXepZ-;0s4p=K_`a~axiRihy#Yxs%*##gj+WD1z9$D+BsZn&ePCnoA50@)x$RUo zI;Bl^+r%nnEIb<4r=o6=w*v|QBP2s#BYKkB7&$QME0{q^H>oJn|y{Q^VE@`7U z#p_!k0l8^BPQK0h9X^*lJ8k{+R95kRmJd5cHvnOF0ymI>ZmM7y@ZhG9(O{&?VH`K4 zO9Msf%Zoh>hTiHdrk=*b1p6|sSl##j{dle5u9s1&S9`W<-+wP4=^HW+s`%(0d3KXN+GrlsBg z(4iX82*U*db>@vu#1DbfA0mjdCL(fZx}&{7k!;hg_xje%S3QM>(|Xj7l%Xatz)O7e zYMCMs%H`J{zRm2IoA}F};k8HF0lC|D#-uwe1brZ>KQAtYaAZ&U1SHGVIOTkZ?dsO_ z5A7Gr4iiHcdoSk4?Q4;f+jA+ril26Rrp5>2dSaN6z`dEC!Gt>84JX}JwI5&W=xij! zJ$2P#<$Tedt%P>=*Rzs$_jeVGluhio6IS;QF?0gGwsZLJJ7)wtvnnX~C%-qIi5ojb zoC(Rc>@&CT_DYrUzB(5;9O{07{jb40+hb}$`5rcip=>WfFroWWfZBt)eiM$YG$9i^ z)gC>=PP`sAEX{Afp3E8Nn47j+<%-JQ-S2^$orP~kj9&nS0qzL~FnptkYy@RM08?xa z$fL9gwGYG^Uz*Bb+buLASto^#b$T(HvxDkVpep%#c%=>de`K!MrwE6E6{#4Y%>NDx zPTDh+i1}E|j;L6Ir6^^_V(MN$Wv}@4b*K4FB78PdHl-1e0df2!uLZZ5rBE(<<(a_n z5gYdNTb)1dsHKgw4wgzYv=1T|`w$DekV(oPtB8g}y$Y|g$W|Se+Y}zp-PAQCWX^%P zus4~R8B>lDMa6N_ciqpIJgFPv;k%_L=>vP4u+c8li6NkJ4>5iVs0JCFFF|3GX0C@< zdg0kO)~c*8dvaTkwVu7&snjo@H=flzBo++OK*6L-3+?`{a(Ed7z~Q-H#}X!^%Y?`R z%gfw%orl72w;qUX=(u3+?R`B=@&5D9S>IeIf3-UWN@bg3b-eU4>ORRhJ(wN6arV~B z&+7-D4`)iTex2>sX6T;=PhtTW?UpNrNI%@%#S)N3FCRiI96*|qE40Xl7=oTH>1y{@ zhbq1kaatCVi&a|MFi5CYfvtxDRD?;Cj*L5cDFtBWRwsHsi*DaS2P9xac z7Sry6z+409m}}^jic|CRqh6V#y9R!Xa7Z@5PYx$w2J7IAeLkvT-MowwHl>RNKwlX+ zNpPUUNar;~+G!Fuer1TVq!RmRt11E^WP; zTKOC@Y`)kBtuN7CN(Hd$Z+X~V*Q@RkUJmhBB z*bA>d;$6mxS%1uAE#?{cWnvOzJEl1eRKBZB3?VJM6>xHb`UP#d;{yGyUF&qVJ~{ek zx)Cy8g%I-nC``=Zh^?9KR7`y41Q z;$m;ih?(9PGcn3y^J5QO6AJjqwO9=NnKUn!f1{u#;NA6a%<^B1J}c|ogOt29l202J zU8#aB{z?7yzodTYwbcK9%`5pFLnU5K{+;@djDOGl|88pPRy-dLbPSSy%m@_~HIhUh z3I@^?-;C#+BvxT=EKTo*Otsf3C<3tmneww?1u6)@4v)Y2RzOqm_62q9{%!zWfzugq%Ih~nuH?^-z&+&$A`O#o4k!LwgQ~<)` zeig{JcoI>_F5{#5CBe=F*<*h_KO}1AazAD{29o||Rve_p7Mt&;1OFG(*~_-d1J4)z z81Vwd;P;6^koq}aBw(6r05l(Xh1Dmch=iu0*M6?AO_7FocQk%{FR$RE)t&YT(U-8f z4$z0(AqYDrv?A*nM!$IGs+QAnNd|R`ixAfVaC#b5AQnzDQctZ1;B<1$n%hG&$QS?4h1v%rn`?p+5TrY z3Q<60cU{$xV!lgA*Jgvv8A69ahye>kF3%u{znoEW*Y9U^7@f;Pf&&Tt4}{5yPxr2i z|8*)ws~vZ(l=p1MjoJ80wR_49O$W|wy(DnOnSwVU;s^bo5%HDL!c}n@Zg<6(G91oc zy#NUwZ`#4oT4{#)e3v&aa#NPSpS!mp1{^y8!_(m5E@9uOdl5PGNXrjx@tKRUJ$kQ? zX>UJ~e7u7d*P5fQN>#Ee+fF(do1u+GHp=>yTgW&GvtLQyyxM_jWPoYGpTg#OORsto zVn`>TioK0}DcRYY{`}hBk<|QYs^W9Xb@+>$aAIvYjLr$9!<3UyAGw$b?I~2Ddwcn_HW;1%&|tQQ zHyv;Eoc_1n^xY^{F>MC1%1geItM zA^>NLv)2@D`$h1p6WpHK?HV)DZJGQ;)ivL57pLdrRoPX}cRf0K7b$?DFBpWITx3GY zUISK&1Z)>hhh!X_$8~Gi0(Z}R;#9_V=YJdjmP$R~-(z0?TFlG)5%Ut+9Y599ZeO^L z&opAOlB8b10NEtwyKJ&FyAU3P;J(ffC*R@{U0S*;l~81!Kzt+q_|f~Zg3p+J5LvFQ z{2iDD)p4Q<0!qJG_#JNOsX8bfv_(Om!Fw1e4i^upbD&`5^Mm1T2l5WeS}%ogQBR27 zQL~MK$iijs)@E8)1K!rv5owS&IA08{PJFBy0Gw=`Oj9Pi*b>{07PU@cQ%WCw9qbi+ zrnz(aLJfST8FuaGoaLY2Eov&$o~1Jc$xjH~_B-Qb)!ZJP_>v~Zc4+4#t<1Q0C5}nG zQQokmrSk*{PbeZ)QzCi>8Z5 zj(%gDZ$ByB+t8YgeHs8|sb7tm!;-HxiDH^M9|G0}LU<6OdcY-RARtwJ=Wm1o(a;&zi;cwarRrgQED=o3~rQ4H~r^Eshyz}_veiV zT<0!CPt^>^S|0CrD{2X@+E-XrG2-JwucLJSeI>}xt3g)3tIrRY(!V|9$lQS>cCTsXJ1FYAluY5oJNgu18Z0{&VQ_7 z2~h!O`{uowe6~!aJ+5n3H$KX*Uh=cv_Q%|qlSJ zexG)oKpC>z*5i)t=g%ss*DvKJ!dG{=D!j_IQCx=dGT~tA~slUU7y$-vp73|2(B5)C1orQCWjK&N>(j$6TUHr4$EtNP(28|soHFT@ zhIB{b!^)yc=j4&P)PhzY$i-*+*l0ExwDxyLXQnsN5 zB}MU2Xl!ldlmkgc+>lO@|EJ2Te7nCE}bP*2bE`+k4F>)&;` zQdi{jxzBy>bDwkGuS1kG3cB3m!9p@U|D;DXDIxB(ciW?Y+DF4Fep49*8w#W$BU}N? zH|Km;-sakvR75BvYwaU)vUl$IaA-A}i>yK{_?eU4ocYB?DX9NoVO(;Np!oI2S7?l-HKtFJ%lZE8yCIb|cKf~VMVvxC`|k0V`zzId6<~j3>>SC)1Q2>g`U9EV zu4jY;-+Lo$4C;)W;zWJ~7@k#sH!i+$gfs&stpje{enSe)Vs(JU`ZFAuodp)#@KqtX_JfHby3 z96YM~s{DzujtGRE!53Q<9bCFvV}~;+l6{Kq+rc3{)1iR3d;VffTZ6QT2qFSG&@vv% zP5KLRwI|zIF}6;m3otz1ZddEnoQsk*mQk}-Vvboj=WPcWaVb(c8zmUTb45uSgS!3q6DzaKL z)YIQQJrQ!xZta!300ZMa(P=k4s=AdEG=5u!q`x-IY+$H(R^;j?E$%$nT+c%c;h|g1 zO~9jgzhqy1P2=IU0UjRkUYl>%?N*+57l=Yfa?!3C@b6|#eQEX`G+5%{%UiI-_ZXSH z&1YmcM3#lYs=2&by6K4$e@y_)1FW%m$kY%glG`C|qQktwm2Dl=81F{p>+FBAhvTFx zh;~222+3YWl#pbQx1d$*-_5!N^Lz3SF_Bf>Jk^T$x%#BlK9qR6#nM<~fB661;DQv1 z>-2}TIg{l{7)C7~R zL<;FSm>-w^@zpg>{2wI9ApnA;Jx6+z^5ot6v9E_NiiF?MR2yrU)`ae*b|(yh4#Vy4 z1WW;i=lcL0d5|#H+_f-ZD4VFzD4lRiZQI5xdFM2f|Ale+n@f-HSfmoe$kHRk&W6 z;G5C3e%~W%ZddSgWWFF>fP}4>-y8bgH-C_94sL%gJvQ_Z21O!9S|6JCL}z}vAuE$> zey}!vBZW353jt9)CeZCq0EU zg0rTK8ZsX^$jVAQH!g2DaXZw`a?#>xY*m{bX%!1QK)>*Dn zfE3fy!Q|{L*_o+38pcwVcM1Zzdv1w`4n&G%#a4i7n$7?P2M`5XSKx;YqdhPWHTGb; zJnHY~?yWc~6)RR<)TliPbX!vYZael<0{1YV!k}UGOG9QI^X|Rqi%0UlSG9eVixc?F zN=K`=h&BEZ>M{xw5p_b*LH+`crE^bj@E2x4WxggQ{CvLWho1mYR1-R3dr;%KNq{kc z-Sk=K$7dw@y(0_u%;fh=M@*Mo5Z+r9mi7b$up?Kv?$E)4k>KjcjBkMcEf7+qTT!l_ z=X3NwPI9u#nVRLc){}WtFY&F|bg%0Y?*J~5OxLl@COpC$nUZPacHKR;$z1qZq7>w_ z?g2A;>$t6B+Dqquqm9iiFDlQWOLWa< z{vH0X;;x*RF;=R!F>jB{`f@Sm`1!#Z9MJ4!$HaoyMM2AB#?P5-GA}@cLr?a@ecFDJ zQ~&%OyfnKyq0k_ILC3_o_#6E38JvP~%5u$z_kCWMr?!V?_=Bu@s}*(IQE7V62CL&6 zCM2bts}6;x{J6W%j%&GapA)~~_2ttWiQye6<~0_;yaVCYKX_Phq%1K$XLSBSFG#TJ+{+^r60W;}nJqP4_E*(`fy%MnlWZEVd5tR*_GUHt=vZ z@~NJD1k)B;P9SE;wNKr^J2z;>n((tI6&BW#_j*dmE=3lJDd<4T}0>CM2lL}d)9nCxj7kSx1#KCA8>bV*hkymmD}4}ax#(c?TU8GkMp*i)diJi z$@T1hS3qaq0)G{Tft0CB`tsU(%37#<#>wXDYOCu_8Q0uvk6Aw+q?fo)!r}5Erio-X zVoM%49jaD*av!$kH1!2q$S11fuSaRC`HV667=xS4tn{m?()k($i<9_;@~&L&D^c3v z9lM@?dYI1e(8%DJW-F+>3xbH@IVl+6`SQ2%d|fCGkH%ImvRb=GvgXUO^1`b(<#W3S z{1_cc(f?zy;P&LhA4)qbc}PATD}4xyXHLAfA+`r6ytimy|Mro14OuVrMS@F>=w+*p zM5XeAqcg`Om)FwIoTSp)?5Hk4Zf%z80;r4oYtsq!WdFBK2Yztoaq6a<2Gz4)thP!% zQll}^<&!&=)rP>2|ENzg{c(do`ctJhc-m*Qrv)%Va4nn0m5}*5lw_rcZR}3*`2=Hbnq$p?R_n@}z=Q*$+)mk{`O z7*Ig43vFshN-hg%Ii?VO(b|e=SXC+8rE!=PGS~R2ulsvG?sj`K+k@OF^({0Z`M}?3 z!izKd$!$-+jA>B~CjyC>NxZ{Yo=K>n zJL0=ujd@*U+6}+Ofvb8Vh-V_dZ0p>H9_eze%4$@8StL}eYx$r}=O@MZ_?QcC2W?*b zLK8lxq6z(6vn)y}-bR9r4BIX))w_@qsN#YqUtr;_tmh1>jBglG+9K7NMo^8rNMwcuy0 zco%iVXY9Yy#g)`_u{kweOwAk0YeFrM#-uzKLWyEwaYuR=D*r;N_uYppw|l49-LOj- zRbY(&09iQ}{Rv$KXcvuDqFvMo0aK$x4Ek2lq{qXxnQY5ERBmgeY*Y9b#Gv~Jme7;v zvdQcTC-Gs)`tC#gs2{ikfEJ<3u_?%g^wxy>lEfQay>L~hYl&v+X-+>!86V59F^Ou< zN1tDSlMw2Elg&y|0ibf`@&wgCM0wCn<&t3u??%5D)$w(ot&BaAyqP@4{qwxU5EgZT z?$PZ{MBDVw)?VnQON4(sdc(XjHkAR?-)LCbY%JHb!w8ne(WmQi{$ytVxjQ#Z`YaE} zK3bVHkNb)Qxw{y>QS`j|@lnUj4v-@^zMO(A`D4~qJpI``?e z9N#d#NNB(ZXVzl5E$s>Rv1W>Vk?ywMwE+PW#Z~lw6R*DiLA-(iQT5-%E1IZ!9Lwu3 zV}U%PFPp2F6r}Zjt9I zrcFV|+kw^1JK%nxrL+dbS1#nkq#`Hc*@BBM+my3KNiLTmYzCzMxPQS!+#-A?no?AU z)id18fu9E{N;naQznNL1?vK+eZodUYx!)|q#9!<+x|$#W&TY?SjM1+?0npyZPi-I6 z6!pN&T4Y*TpLSN0cF!=q@}<=JnCoWW`Yx=BB6^J#Bx!N(AYT*gAJIm4)nBrwle&cq zvi2e#yf6A=3wMDnoIpiOpuQcaktJeK|JuPY77EzG%3ufY?M&HE?D)cbV&J{rRB z-H6aSmL_HMcn73x)aF7ef8sw}A9zQtWj51h)DDe)*EqJ5|FmB)$J z{eT>BjaC*xt#7(aYC^TWSXP4bh`30Za#i;G>Ms&*oRahnsJ{0arvEy3z+dS#@ihJ> z2E4FNJ@nZmBSg~mI}+zUF$h0*4dhrwnXdtzEckZgFHvQn00MZAmp4p+4>;Wcn-PF5 z-F`}k>!Wm+dUXFd%EA2oP+YgdN&$@#hXTu&j{1D7ky4gPc_6)XBY?S)cqBhXm{6FR zbB-xlal_#Vt5#tGa~fX#V|Z7t;nusOVmUz8Pg9ZZUmM>i8Z<t_`k>>^ z$15_!#_6kG)AfZKqM5)>{Mi3?n5nCO~Bx-dAK$S{^dsWiojoH!Ie?+!nu4 zu*Bx??f_d5%md(Wh^72^lV*2U|r_7OHMJHiCz7e z=lNn+-u@Vla)s}p5hwoPOF7)BZ4@m?8$2{vMLA6JBhjc6RuIRVwxRv3v$8`2{zAJK zKlsKzMU5oyi!tk)!0S>v65aJ&q; zWXX2OQ6!51Fhq{mn&f$!kX+aLu%}m1&sFH_hyJy^`z6M^sxo2nmacW)Sh9>^0Q!3y zmY@snla7Tbd-&SE#QBXLP!zc+io6J9j+J}5%9V0RH>A-lvU%-4?5>!}Hp#~@u`Te5 zF7_wFNm}LL_&ik^0j_i(|FY-Q=dT#j)D0MP~Cf2381NlM&mt!d!Qbh{0V%gOXj* zuMvTB6uf7`p2FwKPL~?uHC1-_;1F=`KjEOjXG8K5;gn;gvs5WDfB&L(cFnuZjy{Si@^9H zxn3u>4{J$UW9M@Xm>0uIe1F!`U8uNJpV|}_LVibn3<;s*Edr=h2g7do#N6vnR<7|8 zi@u8!a*oXW*7DWpi_7gNd6%@r57Plu|2LClT9S%R=if`s^n0mIP~^RpoM1OtoCSB8 z-GHh-_$uI7L9?4KAv83-Tj^>~!-f3a*`vp=1-w5?cZIv_epRmOFZLU5oBgJsg)IqqL6n56KOS~Sh` zjQ#C-TGtNxzil&VByvDy`bclu#OL7bju2UL&v3$p4 zzV5xs>LO|R?&ua~v68L>^+WmQUl1#BytD=TnQkLswriOIDlW8vPN)ex=+30dW z8qh8^&Ldd0_5ph?^Mcx#b1cUcPe{ZB-_=&AhcS~$7;1;?nxgh!kUW3*Cf%DIawM~% z?YB;~!)9QII5jB7ewAO0g)gv93fN%|Tj?Km$hBSKbR1gYrkSB{GDypdxICoDdWnBB z?@BZ%%8AgMh`ah~L$NiWMm+A6if^}-9Nw;G*3P7$Q%3ESWO-TK^$^&Hma^|rkT05y z8X1*NTkS!P(B*k5%;+mw7M$S!h8fXvt6y&F?(?>F$`XpVnP8MGU!?G_)@%(DqB{a+ zRe73Y$@k^3+o}%0aRgvV_#QQReC$0n)vSm`yZ6lxZKH3^%x+96Bxh!(-xb?OY^bhK zt>rIFTmaoyk3U};Z|*QR9U77yd$D;J(fSv}7PXuryKat}bzFcwf-jhn^}!H{9C9$k z@7#!-5K^MM+z??maz8!NTA!lxBt2j56W2F4frhWb*aA2a7hWkm;gi3|>oZ7#IC-6} zTS-=@Lhp1~Io}@>euQg6e{2P4YL?A@>Np5My#p9ZNw5&xJX;R^piyX5$&nknyCQym z40zUVCfbWfOGhC()c#jQC(U-0sJ7DyJSXomeAXDK&KINxV1e!~T>5sSFEdbx!_wzgBIPsv(va8_kss?-yG1z~P`l&`riHCU z9H4!dFN8UbO|l7lKNz_)XjI*b3@5<*U=%$Q;2*3BsEIrvIvHA%)&K$V`(!NT5f9x8 zESh|FSe@=RM`T?X_Zs@&%tI$~Bal_b<+>xDJJt7a5l70yn32Z6){gza6Cwc^7Cn@QtPb z*4&aLCJOMYL4gUWMQDgJpYd|L44%-YcYIV(ytho%fBn%o!hI=MuU12abTZQ`WTn$m z$Z#d?SX{}XdwksLYUAz}!%BVcad5{dt3%KAQLUE70;WpD;TTQmWiP#YG?NF4yRX;l znggnz%Vj|=Qud|)p7@$)^%_Rsr&goLri3A_?%CP$TZ)T*68lCs3{r4xV{_txRFe%~ z3;oB?ktysy!YuVu91r0;eiTRU6Ou}7+F_%8$1MdmmcTnvd5GvAJe+exU8k0Rw7%o& z1EzhEKN{n1(eGxO$XPS3QZXclWMijGQ4^;s-)+9d{s9%%6orxH=KmNiH;pG6M9Mvg z4(lL@idZCJ^4DA_Z&>5|Bfm3VxP?`lp3#Sa=6g^C+v>iD^nxDH%|B<=S(yeSZ>DLIZgjm*P%XigyCJmdL`{GXCmhYY96FQv4^=7Pv;igRe=P18iz0Lja7)tPC6@rg zEjab*z8a_NK|%dF)}XQ;K@mjLw2E6Q6|06oHHKGYjgHLDe5GWkImyKVeaXc#d+Xw* zi&g-aKO|3A?LnSAoi(AgE<|4Vqp6yPj?1B<@aRIKeOvhhfyYQ42kN!#*8 z@vBz17k4@pRGP9M^?xhf0_2?(05lZclJ;~@ih(@l6CLm;%t6!=oq6&EJ@+RK?oK54 z$hUlbiSsfew>-EiR~ki9{4)xRG6B-?ZQqt84`l5pB(Wza=$9TIOQAB>6mS#>NxC+1 z^Jkua!q2&t(=ug8j_2YhvGD(jnfh!5X_ru=uE!wqSR*68(g?`he!OykuCPMakDrIE=c}Mc;VsGVWFb>>$n7mN#Gaji zyjAImMPTerOZ6vg5WXy0N9z0Ty|1pG@qX9+6?qZ7M*ZJ8lM`6dEo>-!pbJJ&0J2o8 z*8Am5FG=+0iaYc79W6?6Q72C#Yrs-t&+-z)X#93VFgYRTH@}^+*abc>H*R2RGNFZO zg>nPrcR#pSQ<>kwrrDIQp_C)>X|O3yDN0mGfJVWQ)ZzDx)8~Flf%k@aw3YQT|J@{6 z37X}8C%vxGV6)+ndLle{X$0V!#5RA7Si%3lz< zmc{g;Rb{6J5x+$<6%a;38N6cQf};LSs>1)fl?DCti7RF0DbOw|x0Nx3$@ z?`NFoL`A{(vFCOJ*ke2=1(s|~kuHST8t5JmJ-^eIdKtw<4>Usr3)xDfoS?no#lghClWCj1$H^WAL?_)dKJ|2J8LUB)OnSJTA$zuw1fz(o| z_jp7l6G^9jaDReDH@+P4#rWc*%QLjy8JJ~{{Wu?}D0;Wi*{WU-Kg*yc~kNVhjM-OgC{JoJp1_wJ|7u`S%=?oo3v_;Qsa0<+Bh4khdWc>BUtxo?b0tiY9$MZ zeE*1EOt+#JaDu%rM^U2}Ea!v>^rs1ZPuc!q>CDaB}5r8iR zs5dsj=Q&!Q9(AVS9ceppI~7UWh|j=jl9>fkOt$B!==D^NyF^qqoRNg9bwij}m2cR- zeKTlWU-#(^{Uc*h?qSCJ?xOd=Lh}zfet2#d;ny=pgRO=WpnWIC@!BAq*%q~+sG=5X zLpn{=q6xj}wK!4~TDcF1?t6wKxPC$<;c{D|`&Y$7R9|DA7)sd%z@3k&imEOzD*b4T z4T%F6YM<4hd^D%mfpWPw-q_w8k&DSOPDt%5nC9h+)_&mKbra@0f%mGyQVLW@=gEmb zhL*=|z{BjLMjuNYpD64dNU0I6ky*Ls4aiXRG5zMn7(-YX1_li9HpyeNAKc_wK&9pq znF)k0J`t2b>~`cLM+d|<<25~46-Y7Ed4W8y;-WC;+#hvfqy9beGyz&gksz}D%zKkF zS++$FeJur$uZ!4T=sc-t62!;_@4iq057%gb2Z*2kh+&`xD*+Ye8pi)57ILdrl1XuW?Knr=%nTmc-R@kffuj)q+Q2J!qC2LyV0@88L0S15~$ z3nn&Yt}th!;VN5lwv~; z+1TUhx{7z+seDQ|_ZLKf!fi>us4rpxaFIiR7K!})C~0+OGEhDeo#PEA>fTBRO@&q% z$_{0~(t;bbYw{|-6VJ5oF}X0(oX^B`?WnNheRN08rFP9dgPP8_?E;Q>%G`dw^tlcR z?tH8XS>Vo%1NImYNtJ7McHIb2D;pmFq>2u1&Q3};mp#3qdy2pDVMcS(`i~dX-0ADH z$Oxjs=y+5p)FiI?fi7f9dn9{?~)?W!fHz1 z>8)=X-YC_z7jsEyAJsT(c`bIcZw>x8hVM7j@uMXX1)z@2G^nHWBA42IE#rkYe1K}K zrieDpQls*Geg31Rsw@IabuRdAsjgKhHDF((m%aF(K4rE!r#CV zE_RI2P^bD`P8)aYFRdq=vFcs%N; zs9t~$O9~iVCHkKvSpV1GA;JCBus3&u273HPKId{f;Wy~9EOC8DID~)+g??X?s)e8Czkge2ZqNtx~I|n8ltU4 zxli{>)hl0$25ET}Y3n>H-YcFvumgr&H*H+^tZ#i7>sXiv3!A$tW_zj95*b(%T?ThH zVr+sFz5p==+dV94_Ym3GS08&{GHAG$pjD~;bh6cE1tT-tcu2T#d?*8v4|HSTR0;tk zgNfS(;J5-=tI>Bje@^5H^hjpNykg0+!1At=Qf0ahaRK-fQvqNr_sZ6RUi7=^iW%UC z-k|bB`{dnJoA_t4?}glOO{Vfg#Yv)6eke|*X^S7aLgR-fXt$h$4QwL5O{8*gke+YA ztieFMRTZ)dnNLsAH8ps)@kxPZizmnVF9h^VGin4Y;Goi#a-ay5h2G4uB5r@Rl%{_K z2%y)IuB4ZEz_z|p*|Fs0W z`Vr%$Va`urib5ILhGghQ)K(XDS~km{pTWz!921w^+)&?5tsag6;pLxi&jXzw8cEg} z{#k7x5wonpPrYwHG8kCxogOR)0w5YTI2WXjwy?pkkubFcYvIl#l6Myx9k|QH zexyqDL_%Cq9AqZtK#DLXKK%V`ZpbMiCbffDHN99M^Osq7`SzM%i-t?9=e{W+i z(;2g#)D+{VvQH}rP#XJG9{_Y|>{E+ld_%%gR$J`TgIfSye`!K!q&ooUUQGl5UCw_3 zbi=3sUEqyQZv%9XseR67*7+=f`UuRM&Ws}44z2a)=+3wQxkr67Eq)Zxn&Sbjc{vZb z?iz5iJkLV4;Sj$L77Tem$puy;$2RETHYGpB=H~89pLTOcWO#A4)JDP37JdF72^q6JoEB2BdBENAS*=1pTul-0%5@?iZ)L?D`;CmN@R6F?B-GT4 zF%viEUXQYgeCyN8__9OSE^Oha*)vvY?smg5_*qcJktg3Kox`K}$VL_2`TBdle{1A9 z|6wzO=gSocp@rk(q?s5U=>U=CEGabA(UT%}w9g!VTCv0L?XJG?;n;v5De4S3TBT5Z7L>CN&`OIZyOzax{IyadXVpyPA_H?!8ggB9RIR`X44pn0w z_@5wP>mtR?dfXKpt~*OE9@w}bSLA-=b?{xE$10{>PfeqcH%OgXNF}0De8SCi^T7kn zZ;FpyXxgpX>)NpKDnLCdd@ZnbB@34;H+;WbJ<}=v?1eC>xD@XUOu&DiH3*A?bMtQA zWcU#~n4WbmjF~R7U(Iuk5depm-3B!}k1V4@6DdiVHRFR;-Rq$Kb!Yf!^C!AlasyhPby zcTH262)EL0Mn%=W4KyQfojI2F+)#Gc-3L*rxNNX;0@Fh~D#ZuAqA!&c5&G2>tn~IP z_YDg_E!n$3iJL%woUefjcu9{kY%hN!ZTZ75l*CKY@2*|Cyk^>d-rd?>E-t49EQ_C~Y4+n?|R!^x*GgiSEH17;;_=s*8r(q~>$&gns`q;ht7~z*>7CjSA+yWb(Yq-frMQP=yEOZc_Q&_s zp*%&)bYo85WUb;-7y_}?@$iNDNGR_-ML_b=ZTEg({F~=RYfUw`nxECH1K%+QC-i_U z#3l>q%-QsTtS5$Nr41f`{ral)hX;sfTsK~)%B13#-?{%Y#b+5EPB}zUtxk$H?MbzG ztgvE_@|D|MC~3flFZj8wU^+){>2uU94%p0n@z|@08kRDqye<=Wf z&xE#@NdH?|s2Y9H{pTr{5x2Af?s(P#8nv$~4c~8OkuUEI7<4fA>sVzLsZ(j8PX#J7$&bOa;hGGLN&KbI@Gcv1=FHF&mdlVhR`|u0--3O97 zvFr*d7SEC+wt6oAV>pXcDF=)EjWbVjPtGm^*x3nmB$^57G&&TnT$&s9O1SaRjbM|D zu3WZnAzrr_-z;TwK*-#rpjYHGZA$8=YnmC7)0Y(VrTS8x9_BKgU_XcNs4NHhRK1l5 z0%KUY8#FXDRI$eYc5_2=*z4$9^U^Lu*I&%4t4r4c8Y;Cw^EVB(|EbZgd-q*rGeZ>{ z9dNeq`|5;q-9mQLiTL(J-UaBvtFFT?p?%R0ot$2mCbre`9TEsuO}p|Vdi7m3Y$RI= z6fgM|hc-42K>XC-oLQVKlGj#Ndvfee%Q4-(rgbnvYNaHq?ZePE!g2}~YOPXA%&ajc zDmAAa{|HrGm5(v~A;E5_{tovMKj~W9Nb<)hMZ7Nhme}tz@g7g?O(7i zNo8~L^~!Q^^Ht^rY~T)ou#MJ-m zwdl~q;=Mte8MGmV?le%@{1&LJ7=X&m7M;fI(N3kDaS|d(N_U$V2VO3uazEmugNmX` zpyg?2oQ(7JD^@S#45>^xp!Yyg+X-7>1s~$0KY8t3^z5X3!!@T^q6b{QVs%0H0v04O zKEHeovaDc&xr|Br4HCA_M2wkG(SyxOo40c`I&uFrtZ8Hy-CmFDgXOIhp@=Hd7sPk1s{#lmcc~-CR)w7jF-R4tYFY|;PO zLN6M?Ff*wnImcEai|(g!$^r0WYghR4KhRL~GOPzzsy4;XN{Z#BgGQ~)hmmhAe}qcC zO6m4(zzP5g{j_OOr^ho7CaK~F1|fY1Jo<|<67R-^- z43&Hi#XEuIa}Wk5N0}FGW+K_#+<2G}*`aZtSo<@M8NjgCpZuTFtzp5sSu9}6{5gmO z-x}ER4{Q_84(+3$$wKoN+l)C4%4iG1$)>p|?v-ERg!YwT{P<*@3yA}-{Cnvhc<$*h zXcT@J$8Uf0@@JbCOaFYjMf9vt_K=Vg>kgeKjNtIQK%JoWB(x6Aa?=b|+rmCH8@^st z4;LXz55u{dUrxPuH1uE=&kN+Stzmt{HN2z|cly-kE3)9IsDFdb$D;1|pX=^{;u5=g z6hv4bj{{Zg!_AzyNB-P>Oh4x{H}fz_YFRMAWb=RAt|{m*@Q=d9(`|3cW6Dib9liCO z&=2A`$CBFh;3{bcM~-7h=lpnVZQFLCACWy?dU5EegcRM&qkqC9-SkoU6$XXT8mzoZ zoS$VJMe&|HP?#WYUy5-3z`cQk&caAH%2(?&4tJN^j-BnYp^>QF`1l`o}Bus^Ac^F; zPsnfR7wf|}YK%#setKQEgwPz$O*WExsR&3)mgd3KwMwC)JnyPW&x*Xv4P)kEs1XxLWn@xa z+BiC#6FYLGM+0QFqkGFxou{oa8;7$1`Y%dLu;aiqsQZJFp!T4XZ4vdqQ5cQcSipg5 z_t0ZQRIFvl!~#$lcRzZ(*Qn{vvC}ChQ#nji+d(A*Gs_5yp~}|lAniMO#)GI6{}+Vn zLAA(Mqe&bLBL6FBP@8_-Uw!xe$Jt%@8fR#ZE342lX8X$@4 zf?DS`ZK%9LbHkeD!gw~-1`VN5%Z?8B{O8Yk3|_(y*NOxfX6Cs34A8i}8S^9_&S%S6 zmkH1AUP|U2^WVSu5(yoN=Cq!`_4IwT>^*3OJZKlpt8wMX-P0*weU0bE$TvWaI>&lQzvntO#`mE{TgH}8JbAt4N*kl! zS+6ndtm?3D(z8@Ot7~exdv1M~k8#~xpGSJ*ze|k_2D9g6H+UQ<$Fbag)k|MEnq9N^ zN&TKSMtw_69mkpkP{h7}Z*+r&$fm{LIx=G$D^vReU16RgOmZ8M+wFJ^KA|FW zod439>kgbRVjcwQNUUB2RD6A!>%TQc5pP%1*ss!(mpK`TT!SM@bUpEc{l$;);+b!< zhe&1=U{WvtMj55D+tEm$g1={5CSn1MOZXhoI!F?orNv80cIORuR<+zAXrQ$WS0%t)sa1}>9y-0ke) zcfM7>2+(hfE@$hS1)d75WgX^@w$bE=j3!&+0EmhnB)k8{H=2C?2Z_qRNAfazb$8LY zz-r6E9b>%BprxvTptH$t&bUp7Gd+iMr_$ltm$&F}UmR4L{-(o`=h%F{IXR|s{= zDwxEW__`3-lm?cPjw4xs4p+n{(3}OraQq02q)2VLYOjB=#Q0yPChch4H<&p!~O?v^@5#)Lb&`7ztfA>|$rmJOt-5+BVDXw!6M;57tC4o9zxxO4np)XRgZted_T9|%A1 zd%v6FdYE$?e@vA-DjBjW1@S`+1KFons}blF%k@ZFg_Wz`h=9plj0%??fH}Gd=>{1R zg43Sq?3kNp#K87LyRq}=^J^ahpsdF%4IY1rl=yJe*jP};P*Zwp{s9a!gH&~L$sxVk zJ+EX(hc9$3Rdu-#6^zxg#LjdQI)uMK>l4%HI{4+kiLKjDaNyoo2nx7Cq6O{fgDk=IIbYtEpR;Vjj1xIvTh`)gZU)Eo-7sFw?M ziz>4Cs!k|-yNQ=bmz+<@);V?7j3`yp%1o+U2gMHU5Xz_kInDDHgXymw>HuF5{P=5! zu48DtJ&O#`WJ8@nw}EWjWO6gNjA>GC&NAoMTN3jEBUD_cE3=( zwLYu`O)AI>kvVoR9^a`*N8t7ACwNkH$G13qxq1{%mjKuzaRg2l21x}Gj9!Orn>&iB zTJpJ@-L7D#T@xASs_*ZI)|J0-S_Mti}Ro*U=A;7SX)qr*ezA3lDQ6g>R-rdK-gUXaMcx~sw$AMlF55%=7c>tHQI zm@9MdDb>cNPnqrx0Yb*PlP?bL<=c1e#20!Eus3!7*S)!nexxY(plDDc5yhvMnvwhU zm6o^v`!D$%35PB3H8{S0<>fh?Tv=grJQ5btk`XIz{!r6=?ZhYbPk!Ks#tEnZQBQpb3zRG{Wp%03DSgKd$hd zb^*ymPF(HsI_Ky^Q2JS?OLj9Lboaw&LYwtWMInT95Kkw9_MznSXxphnxbd5y7 zP}mZ{F>b^#-`haZEkuJjYaG~0NQIFJG-!sbY%@}PjgZt^`8c~?!R~0HdMyAq8X{M7 zzCxr&ppRe+W@;cc0mp1g&rRVy;15z5dX_CB^)3=-E9%A?pC5=zuD-XtZJA&K=F+xh zn$j$jn=hk5 zHwN~crXci#&U!1~rYvlw!0(VXicm8m8(Oogt2rv&&2RJ7eva||xy?z$M?UkgI3EVu zqfi;-hUA#{GAO+#gueEWN6@PU)gL7!4%PO0EihE9U3-tg<5%G&p! zZ{y5w#uaKLmJFjl9H^OZF|Ksg*bp3_@WW5M6)c4L@;0>Fu?{<(8!jwrLg@j-@R!sN z1o>xmjIkrJRJ!ipU%rG5!LrLxgzQbtt>Ttev)t}Dvoxjdx%Uij$QGzGNS z-?8U}PxMUDOGlOT?nP42MeUO3KM#vv*wJL5;)~NG^bbc-sd2H>eC7q;f5i3`WJTE; zL5@VGsFH&Kc-erelNslriI!+XGb$07l1eG^!S|%p(i=mL%G*T9tnb)cZfO0WMOsUX zK^ttsrV9(^@QqOMW#~1Y{OI+CP$25!%`(oPR_e@ew2-(v?ZkXaV0oXW;O60G@aiuP zXf!$qi11zlcQ}yJYAIX?-c#9`QG#0^zd-Snu zKMN+nAW%SR`tw6AX(f`7?*oFdFZ1mRp0A5bA_K;+fBLNPY%eI4o<$ z*J))87X6+9F~@cdYa?o$us7KxETRiY@iVPa$l|9*P-6DkEk?m{$r_*M3N(p#Zs~tqF-*h! zyWtCZAaTl42h^aqFiyFrM@?(`4a2O3gLEn?62G1}5bMorP;#O) z>Kj&$65&_{j(S6|F1B5$`2mlq$0VU1Xz+NowD+MxDswGx*Jc`LnW#cD1j#|o9HJHs zmO%p-8t7t-X4IL1Q-0lJsCZOvwrm_Uk*^djx&PXv*LZm1E zf{2lKbd>vzt}Sm=+*;_k`eaWXkNp)VBNcSIotNi|Lp$>1sGqWVs5LfGUtkKcN_^u8GH1OUPS z>f0cI$_FbLI=vB1K1lC5x=K!50>cm{ZNNib$3#ufV|cvyaCI{bnF;LF9v zFc)4ED(E0ikuupvSsPP;HJx7q*3>|?rnm9f54k}IPuA&C*|U!fMCgS8o^%Nf$bK@E z173HBfPtmZ3{34XlZ5zo1ww-blP3fF(QZMhTSF~bm~i}Z=ro^)xe`=W_#P>z!Neac zeECKX%)U=~c5mdj$rO9~VRN8!1rGX;k&RRYt|xF1zubm(0-qYo9t5a&xb3fEUP&@X;_=TLe2Oi2gv66Q#+gGCkXi+ZcVh>j-8{U-MN( zQ?oSP*vl#zLlJaK`8$fBTLWrw`4!Mu0ShPc&cW#`p$I5@`5{!s^fB`<>UAT%v)ai zF;8AP5%qKIhtZ(B_=y|ZcMLUtW=+FC!XlU1e2vOO#&tL?EzccxF1~Z8Nw@V2E^*F( zH&T!&SA!9@cI<2FL&h(fseg!YxZ3X;b6k)?M*s}H_1w@TW!4J8>sdCeU{+l-vpu_+ z>lg-}q)Hw&fSkxhj9?xi4ZVq{YfNw&;@z2nR@ytgepEb(ds@76kHt>YY_b)Je-tA^ zK3j%!&syrrPdxbK%;K?1V~E;Ljg*40VN7ply}uZ-CoJ3A(m~eA#+$eH)yaW8<7)-5 ze#3MW6YN3;Gqf(ZDK^}fJMu_dL6z4q{)$@+ojT77<^>R$~mC_PdozpcRJ{@h56sSSPn z1%-G43Hr8mQzuaAyG(@F4NANx<%#%17}5^b8}LBY{-|a+8}Y; z_(`D19-X~7eKUWh_Bo{1uoFV}qkYfM^%e`SrU${SUp2o#hHcvzKMieTxWww)DnQdseRT8*?j~owd1_knJpGzl8Wm-ixPS#vKv9q&8w}f`0@hCt_%o6SeZjnU}6ysmiZh=;vjy;BVWYe zER&Z&HDTrPM+K3X^Q1tuxRz);vLeyA0v!oV(wCO9 zx-AR9BJXwmJC2~M0_{-X1mjR+UR`-BY*hBx!hHO3w$_1%OAu&nIH~_4G2!8|)maQi zsch{CQwt#GgbbxJ0;o*(=4&;m?`U-BA-7EJPD=-c&9vIrGQ`<^?^T~XM$yAXI9qmC z^Uy5~&CC-KmvKrugcPj%>fJSMJ=HLF%h`?34Oo$&8N`GSNq8jTVQ8?w#6)RX%>KYT zAD(R13tKGNz>(tFPu{)Wr7gHqB=8`e{V&+qC_0>Sgm@sjE}GNAoD^zY6ewMIB})1W zr;!hY9fB!%_Y)4Kv}(u`LC3M3d0ufxe9y{A`XfEnch}YfLIL<#4s1hzuniUMe{VzN z?`;U^d?@A(=1MoxWrA>B3NtAo1F`;M-KNhx?DRv)Tc|`StpFqTY*k$QQ`)<{=3^>P zlpICCf++_|3KMmuA`Fr{062Ev?mJo{L00P5NjRMnBIA9J9I@ut+u&F(9)&~n67&rK zl}soCzD*YRw#;9?ZQXOlw!1*qrpi2fJ>{hb>agPh-nm;2W^!BL*sU|h7o0JxuTaBh z&}8R|#$i;=CVT|~zaXL(e-~toLkw_H6MNVRq)I zqagumt1AISYitJ63Y-5P=b@_V5yG`Ua89?4Tc8y(S`r;9c9bYPPVIv2w(fxzdf)mmv9;Es!tFd-U+@2M_U6%0zyBZipeRC;eXEcPDQnq= zN|J;YikKwpgzST1ln}C{P-IIYVzQTI#;(XNvNOoejCC;Pb6;aAeZHUjcb{|r(J`H4 zdB3mab-k|F@_1^z4LGPRB|4%*6SjYuKQHL7{SOY9js5>02Tb4Q0b}&jNNWRU+4OY- zXUXYs28RLu&?c!C$XRWk^Khiz7S7VzoeAJ9N1C5jTip9FR~zD>qVy6RFxVaE3-%uf z59m=KQl%PC#P4}vo5xTWROc6W*DUV5V3^P$2e*ymMPU1QS=0x|OXTM95`OlOi*iKw zW(^4Jv{$Q_V0$i#fBfNiVRfPj>v-AUR7i9RyaICu$x9HZv}3u$5nU3E4aoD;drd{VdTmb+v-~mu(2<<==z^~mRIu9zW%iRwDG5Wb! zDltE-aQf%gHW_!?5xdxqVNkxZ`3wackE-DL3$~ezEY3Ye5gJ^4t9pyTzqA2}KQ2TF z1@U+CH{$QSH)Qz57^svLAX>#gh0eEL0lo_i)CposE>JWnugLWHzWl+zVC|4=4N%lg&hnjn`>NO$vrWsnV8qLH=P0*_Sg=Mt-LuDj@ zY$fUdNNM@&j)^DAWXBAhiE0Q!^~@~|#VHfe+~BGbO$1?kCFw2f**mW`Wxn=BV)5zq z(4_teFV(_%uWt|LA2db;cdKsbLBW(!<%NWT9iT`{npyD!6Pmp=SBql!A1pP0C313^ zfqDk{Vo|w@tYT%3mbVeyXAiWnnVCF(cj&8NR>lbk8l_-p)xr8+u7*{9w2c}*3?*8H zf??^{8WvB-v?Pspy>E}3Ti$`tYA9$SIVg;?YEZ&*l=8s4fxfXc)xu~gGyrpm7}!PZ zi0;IcihozWUY`iaGFRjpkn<;S|dt1_uu~<(o7RB*-)VLc} zKTnu&f5|dF$gQcVarCC$>4u$rL1X35Z8iyR($nFWQ|;kD!^K`d)2JpVKU*rFpWWh_prcl;0wJjz3a-wZvG&QfL91#u6!P z#=nM8W}$JaF>#`c`H_sKr>SO1tGTC2VT~(I`FD)LKJU`|n~cxxqjsC`N%=Zw*Tq^& zNe@uPo~z|sjSIWd?92O&Yi)7`qTbqvkwLde(opZ&#lJ^}uv~-ol_Wy%czS4h=Let; zi`>O^ohOMj@z>xJ_G$YFuqG3oac@s*DhDIa8C9R{9zV3qHQMIIwv-Vuou6#VIPzxP z-bS7-rFneH_j8-J<6vh`u4O<=f?QK>)G9I?h|t``Br_s6@3+y|2zM__vs50 zBx)kDOe8MZ97Qju?>HVy$56?0duhfXLTmJpNq8^;T*CJeY3pNjOEl0=zw4bkW%Xw1 zE16{mvD)#qaJgE5m+0pfJygl@Q0@3Xkn0cnuB9&UJhUfv$Rt@6cnK4PBV$;lqx9!L zs=gWyui-lCtsF+wz)A3vE)k#01zHq(K=*a~1!SN`UOxFyer!hd5Xj_nFZ7}YnIDlf zq;vW$Whd>A*J;t-bMQnAL4ECrrWNhRZ1~=|;FRhEeLtw5?Xy+-x%Q&ox{2<)m(u#H zOtFlSHbnu%vZ`ctH43A?#@G~ZY6LBX2KIN!5)dMlw3nQNR7~@&Zup!?J$rtvmTIz% z*xZy z7|BVMo#5KVO(R*uRst4w5M^O23sDw!3|QDLn+w|;!b?%WLjnWMC`F(nyN_du44_yH z?Mh@F>V@N&pExtB-?8NO@MxuWqo8XAomR8ZAhQr2rGIDdfpgt=%)ST`aii ze;JvsQS=-#mfCm}2C|10mPik+E)iWyz|Rz*D+Zq@SuU@}huIeQXB#SZOO2SiG}*u5 zwP@;SMBy`wZ9q-13wVvkodD(nS);2VOa4%l!(W9R{KJn?-XN_q`fia{uWXZ6Yd_JJ9QCGOam6v$^m7v(aqM|X<8!xy zG({r=PYYvyl`fwBg?Wn(0#Fv7szU!N*#6#51k9i?KbjDIHt|zLb4}{q&qur!z@d-j zMVbsr1aukurYQyF6dri3m?~RP$NH(PF)eWQD(2hK$G@Zz~;XvJ;wEBRscI|pgKPtutO z)sBgsdu$(0>sbXs08(lPAf=AK2k{pWu`$LZ5yS`T7T;oRU75s{g zykoHO2bI0X!nppft2O0u;%&Ld73J(5mRLEjq&pnkWUT$zLAPorpYv7@zza+>SPY@L ze-d2;n6=H9DR8~8G8aJr*IWCHzK;%sT3}aB8ZfUF2&`%gd!o0hId@iq|LgP3JaPF} z{Z@lzGy0)o4@L2-0;iL zB2tPq_rZ;qO8SCXRS-`P0>{#0{PL51`P>>>7B^upKWe?Y2c14O;psnatY*5VgJ|hn zNiNE7okuC@n} ze;9M_ec9}M)b5-PAPQa#gsfg&TgqgVd>=bl;{9p&j70-oCL}XxDYWHeu?9XyyZr%G zqyks?#LcTHmoZhqN+7brg!NlNW5uaX*!X^gTxI-ZGcxA(Yle3~y}NYaQ4b-sjpi3O zaE3bz%I7Dc2M_U)prw8*kHR{M@Vrn{%i)%HcV7BBv*oY?bEW+oGR2AX!|&38=S#61a8 zYe7me{4xyC8ZPC3nvmwRD5g!KEs3fopK2{;7&HvFyKXw7{^SCzL^QrIX)^RH_loNU zym}y65rLVlbPZl&l-H1rd98XPO%_LZZQgvnaqzczpGV&gV}pM-4xW zRv(m{3yK?l-r6d&pzY^Hjo_*HB=Y)w@U>wk^J0ZL&!}W~Hoq9Nf!o?q!K5JkBrT%v2Fi`+Vko{{pa@{7A0Qp`n~;h*x^uw z1-bYIs49nV)VP5%%-^6|V2W(0af<^N98cWYMd#o*c4M{O!VhJY&U^roqSbu8LQZx% z^^Wl8mp$pb#7ZrA+$Jfe2=&c++Y)VLhZ=nWvWAi#Iz}_=ek`Gh?(9%Md({AJw=ppg zez7>Dse0duH3qxq*E5-ybBxadPk_Q|OmPMwPdMd(aNQuT?dw4Gf&36fmC_xu)?dc2 z5LAt!<`)U9n%=*H{cJ@e5ca%{iMW6U_H@&r{kHNcL`EQQwIZ-yf*RAJ7^5BmdW?8C zQrG5&;kYD-!S?APzg>t~o*nn5bXmKz0J=D!V_`PwSgTi>s6j||BkrUJ3&_jG_xt9F zTMbyXl=sf;v+maP-8H0CsF(aleJ}?kP_|&RTHsQ7ZSwyIY}SI3f!+iM|3xm|nj@+k zGTj-nHQQi54v%QZcm}f4Ry7&9! z^&Y_umECKdI(}BetKQP4<9iqLiJJ}&_21~1Ml7PHKn6*O0)qV%gBnX6qiMg7*Y`D# zc=w{hK%pr7d%Y=(P~5xNJd3ONKL4biyz19UR!dTnFC`5Pg|6HPdwBT~CAyKDny?Sp zb$TM|W)ZyP{JB<%leZw|aV=+gA2pdhlHtSpAf>Dv`Kk*1onDCq_|yow*ry9JJ=rhG zXrrrgP)3PCqy35L&6cS=Dt06`w={gJK`OX(=!`&w4se4w%ApIQmRKScxVEwyw(0EF z%#f^JzDjNc3KpMp4(m_NRigP1K2EaY9HJ4p{2lxRPdREqbgci+Prw;v>ooHWjg(s$ z6r6>gCIp+RXd6SQKQ@C1M5yzi0ApXThNJ7?^a-5X)zNUnGrg}?!!K$*&{g5m12>4J z7?&s)d8XG^j{Gi~yWd$(KKJpX5qzv>h5(ATPmpY>=S^{pcW(963%m&!);y{&WO3}B zGw3Y42|GrSIn+Zf2K>d(uF7 zDtzUT*)@k+Iz3nehKB&%scRemm#(ce)#Be(=9@`Afp{VpZv3%m5?-XtjvXaQ-KuR^mvHkI>XSTnu%^T_DHVZI|6zONbDMO!=r@p| z(-*>vJ&Ql5&gOaJgs%>S2Ex=v^^2d5xOWh`$4y_3eMqnEdc5+8LmH~{st=*wH5%mB-{XWzb2`QB-%~WrC{+y_ne2{813QO(9*MHh{kT_`C$Hj-rus~IuMJo0ettpR= zFZorugKsLmg=8Xnq=bDN{Aq5|^nD84bJ%{4NApL#tr{7Rwn+{*-K9!j6Q4;Z;~og1 z+__h-FU8_7$U~os6>FKXf6bG;_nH0->oK6QayWi%xFgImPMkpJ&m*s#<6+w1QgxhO zyKq5fNuVa4u@PtYB>IW$r`MSudr#t2&MGk1hkE*^<0MaAT1a3{By*BBl=F!4IOXR(qEN}r%#*}uz)r`{De zb%*$b^?Hw&K59Jzf^c25H*%Ny3lFX>J?w9Ejo$qGy!Obs}b z6u{=syxfAUypXPzJsAT}Z7#i42~29DDrJ+|FsD?b9Z)_m-rK$PHqZdwqrTs5v1V@u zAC>WnWWW)II9DGMJWV47fx2xt`8iRl_}<>@d$?}A$$s<$prQOo+W$ZVU9v#kSq^H< zyu@PZ2FPTmd_es?0$b-}gm|EyAx-fq7YRb`aVLyUP1L5{-+;=}KmKCR)yO$}LmJ9Y z;w$50b+(g6X?0kecxGP?3Rop%u-f<&MVhb zt6{mST^_x;Pd5LeWjX})c49Ohz0#JqSWukj$eXnuY2H|D1h z>_C+~5P+p5f!Fudfr5Tl0g`PIoMBqDN|`@!?q?0^y)}z1Oj0WUhH_d(;=&QE0(@rH zr+-czc^cdqHAtY46IA^$Q22|v+x$gw3V+e^|KKlfTf@J;-f+%1(gABiJH<5pYF}c1 ztmDs^=f}isn+LY|oCMJv<=;PFrwf)Snw;m#zX#7AgkRJA+`1qWd-ropqrLPd^9qs~ z83?gm5U7O8>(sjM_wvIk7E>0T*Vdx5G0s{$F+^sMOrBhSzKJi(-N2XiH2=nz&Hg3v zx*_$ssqji!K(k;0K`w!2Xr*z?J(MR(ejfEN%~r_z;a&VsxV0t$*=h1Ch6eSm1l*|X zV3bA^C#uy8eA)!&hOk1k9t{Bhl`=nK7NKMGIDR3JtN<$Ot~ zwC)M{iC(Vh!MXia&`8PbcQ zXcslJ4!j=lELltAj?B=4=cn^Wv^J*w4t?YOHKqrO7SU=bD4LI|7twf+VVqy z-*kO6EF|XDoO^WtR$_I-c7Im{zom>{kg$6uD^+~9YgS0IZlq`0s0J{k7FL1frXxiP zP%Jml{)Mb2m7{hcc?M<=bi<=B_XTz9;H1Q>7gxd(zt$viFSrxqH>te|>l?iAHNbm6 zrvmVRxp_EPo<1pj$INt*wq~Zc9tfeM$d{HW1=!FGh|5b5XmnEooQ?s7wUt?sP+iHM zOD&j_pX5$|o1TEXmI>@p6bH9A!>~?k1p^GI}44|JV z!f|JvGwv9zXWzVGchWP+my_4DC3Or1QDjV*%s0pj@ApirHH#DPQ1BZ$%f&ftUd*rr za{S>x0K$Ef;%GQ%M~XmGNZuO|$Nq!5stJ%VT8+~8D*@|^q{(`apvnaD_pfy8#2CW5Jut&?| zX^;W~{a{oJuNiNQ>JGqSDkxI?MY138;t?)8IqAQ)OVGioY zOh7~Y!j(2E4>DK!V8^mE^9EB)9~@*Ca`2=6Q@Nf{RHxVwi&{y6Z1aRi#~%vqj=|rV z3j43m$nJEn+SQO`(CsA=D4xV2Ra~Z(exT^p8_!wyDP68#?U}?+;%^HPsvnCKoV@shq3skv57B#l z?;!IK{3z%lo0)&1hxD7;Hd3#25(I&AN#bOwyuZImk)~YHX`IEmL6@)SCYE&|hcNgr zq7FxOu824I_kAOyI-<`F0<^q{Py2Q; zC^8m)ZJ-Z1Kocepk=IYup^GB%5Y-*=Ulx7r)74T@mQPjY29M{MlfQ_Z?O)Xwpn#2* zDPSX+KVT#4Ti~kwu-=nO4T8|Gi0}M0UmB;}N>Y<}dbcE`>GD3&2Rix0PWc&VU*n)b zKZn=eUgQ;!?)X5P#}t>}{VzSS$%Xz12$K?63T`+Uma}|>GM&`WLN$X z05&>nce>h*?vp?SvGs^r=}bX=cU#0JGP{Q?C83P${ls?tl3 z3AWEdxx)6dba3uMp@5uNNeT&043bTOAB;Ozc;D^jEzY6g1JF)%fhEl^3F7?{b+TWb z9f`({d;;T*H})p8;f*5_HRO9ro=~%%$ZR6chWscB9Q8V6&0(Mo1c|KKrKCCZ@>w+x z20csKCBzc%4jD^D`(Xi*^&)T%(`L!*;1sLuXolrrgJc>xh$7cYI`X(AW{zM_3w}Mw z1`}sGL-R$NYSKx+${m!Eg+7%92$zfjg3@<;HRlsYo(`?t*hFN(03u6{g26auWzVhzkyMck$9`tA1Y%i_7&N%9 zyj&S2)zu5DIM|$hbeoVh)4$1bGy2VP>$`tZYi-G?jI+A2y|{wRC8`UCBfDdpN0efj zKp$DV-&DqV0%c`W(=TfSjupd8~xNSW&J#9_Iu3#Yt<3i35q zzLy`(H$TSwV1^5wV41*7PqbfC>?5+)bfKOm6ZUaD?+lQl?|vy>D0{UibUBBpU)a1s z(%Mhb9{`Dbt9J3SJE<`ut?B^;QndWW|kEd?5=HFL$UHv2frC_wz5HPSFRe%qLpvPNWv7{MAj(EaZ<0z22d;VAH8D^YvC4PhY@{Ct7a5Bl)c z7rw`oPd$gdzvx&1EUrFD(l`k`+fH&HZ&ZZ@t>%CLjiDv0vG8P>Q0T9>2k9JHn_f&B z+32<1M>rLIFty1HD>}Y#_$q}gWh}q~4Au^?)Qq)gIhI0*dQt6wc!uz~8Ktv!D1Q!F zrJLg#QUz(iMi*dMgeAbQfi-Wd7bN z2}q8?Wr}l^L9gli#beK|qc@Eb3H^NOL)zQ?Eo%_}+u(1(C;R;j@@Br^>r~tFxazA$ z>eGs|!>C*qhXNrJsXP2IiZAx}zbq0gLvyf^)_S$=v{1`W1C57SUk;tVDMS;R40)gn z69dHHTj0{NAU=*=p1ZuH?Gw*3t1L`3U%pw9-k zJ=0dRvlSgHJO+7pFc+MiZm!j#fy)58#d=Xz-ll}mcBPy2%OuDAyD2|7{4N8Pb2#5N zA`9YSSFO!F5qF$;J>7Cu2HiC~b4B@%;SV{R*PL^el*`{-Kj|2AK>UJOJZWD60Juaf zMZQ3Eg#?+o*Ro{Z)d1+&Y@g8f3>`Weymp0q!4opat#SF@lun7ak>-fvDkQCg`iV>9 zvqtN};-G&7ra&B8dfr|vIuvYpzMyGJB(U0%{_D(O3||8y#FJ$Q*JZq*j~{SdirJ5F zpp=g-VPB1My3i%EnGU8*(|tsY;+SFwCo|Zq+j+23PFV_(Mp-$}?hg^|jaO6z*nT4E zh%abA*oeh(pLkyTv1U4Q6tZ8Nl#9-z1kXoFp6`1n1(+7sWy=MWXJ)D`O+p_UHGEa! z5~6C%Z~`IjN*F%D>nOO#XQS|vz;_JMZ|ct(^>LovjgZjIBJB46X={#=I^y=>==D0) zH;IC&G7}3rbkzp4rRb;2eS&Sa8Gt9YYnvyQwMCR#E(iQhghx-sm?=Q&@pK$_I$uRq+SyWNcV3$VEz49QcT}^p(5`5!^Shxb#r~LOMwFeM>sm zJ>YML(N_$Q`&m#TlvN z;RzQk7s$;lz(KjJxW&2{pPYvE*4VZPemTbFEoAPk9Q^iC%ho!tSM@lXmmT+zhBL_m zvRqn^ECa!JQ#8Qgq@enNbkT=Yv?x)WU=5-dK9i!J@4IgSgSzLkn^-;8i?rE4W)Tch z#C#Uz7`Y!#XQV~<;;1HN(T@sDC>0-ZK~u|3EP&iM0X?$&J5 z%zVy3J%e%QLH**6X19vvrW^j8vDsbb_WBW>$H_C(bL3pADJT89B~+eXiL>YKFZh`^ zZ*Q~hJpko8gHGMlf1|X=Zu~12`7=ngE!mn?p`h>w*=-S%fI$M20_41AO1+xuU^gcr}Z~g)RTG@sqVVld*-1f z&6xYj?2-@B0yoP|Y`u!XFNN4;Bxda|3c!Uj2{}GfplJ%s+jwgdcb?I!A|sZP zk!2QZHzo`8+n1&Xr_WxjFeyX=qw@_7>3%ZI!=&W!cq5>ioXDkG^aX z*E0P8IwgpFkh!vPm7ND9C8j~)+lVK_nleHThS&Cy5oO*#{;L`XACf#AA=CqklScOP z-Jr14cC*dPqStgM3tb94%>?{&mqWVTj_64$U(yp4naivL4np;`HcmTeCfB3)XiLKx zvFI^HvC43vVEab9co6%v*qoxGO$46rI0b>%N1Ql%m+W||b0-4N4-3-BGazAr;`dfg ze)~C|2Qe{P-oICf;9T-fsz*$A?y1q!D__Un-FK{B1sBjihE798K->CsahFk>Zg2y> zFm+Lgo0y8EBEGr`9ptjxvTTcT6f zmVm-HG5#)4)tP?gdjIY+fv4zuVE33)b`SjAnpS=mxncj*-0c{ze;`s@pergB0dW#H zQEe!m0SP2ogDuX%H5u&XULXJLyENn5_Apap_)$wCa~H#4d{D8?5Ky?S=u*WLJg!s| zTp{d0VTsl#pGI1>VYrFWbyu=mGVHG5n(jzlnR>@J^?9hEPKBQ@g#;`nQ;Lmr9Jkqp zh})rE17{%5K##sB&6+CWyb%HIEtWgW{F7($bKb$&p#wq))q`nQ?>ze9KWc1d1(sWf z99{(pO*v6_B=Ly)*Kbvx%7C&2CF(#~p<}mxk1x>sJF=!qv`QRze@WZ7)ZS?teWWbE z;Jqq{K^H#%)1~@fS6a4O5;)|;wQ(RR()bS~fqNn~fw}%4$Vu%P>* z8N8(I0^WJ?lH3;C)K1 zkW_df$crs7Oy48ihr>Dfak`wl15>}13V{v_*xO=@zqwtr#k&b~mxw`00NWw$s#|7v zw!p;U5syn#4}?;o%%{dS%z@3Vc`Utt?l-y0W{X_4lmYG_By-S#s^wxMa?xKW1jpm@ z#nkb@+o^qN56|;EfTnl*^`x7j)v@aIs5aGZ^6S7~${ZK_@%f4p5q2wkRlC=-V0y&H zp?F^;1MYUNk{+YROyUI>%flD1ocdaJlKK4j=48ZCCL>6}^VXgIt6>-KKceXI2VK|4 zKnZTDnC(!T^qR-l^LsLn+}1f&Rsp$)l8^H~VckEsy9AI5K)^8}nlwJwzXs%3#-=Ol zY;444!=E2^4EanWGla#rdC~j>i8lgX92H2FhUm}3oOhEI|2IpwH(s<7TFI_f|zmtLi^=a4Cq0bXfX|g>p=xk=+J_-b67RYOpBU0 zr4}!~F`bF7@2=Mj>mTOViiauKo%nu6$o`2mRjcksot*jrbY-a>yFnjvPw{u|hOr`C zwvbAPcOaFLHxh*uT-oV?AjXSe(v9wZvlF~fWz+QdU%0YXD?pmt!j-++z?D7boR1R7 zfFMWK)CJ>%4Fc#d%^ezpj=#z@9CWe+VSdx{;iS9PF6-Fw1avymjL=$+p(TiQ@u$7QkC-SA)yv_>EiVZ<900Jy_9(m=Or{IL)=R!F;%u8 z-0Z=h2#NA#gQfQ`N|G~6C#n4$zm)HzR+*?Maf>3!2!Mu}(N+U+PXzHbz+LiCV)Gej z11~Yn^97^m%8Z zP4ZC(nc5QnKM*EvGfZlft7_Kc-301eoGFX+rD8WPUZoO@Q?jI9XB!gOTEJSA1w2IY-un>@IQCEi zkNW4fT+7U%$9<^7Ro_i0cHnN@sd8^+K7yhHs@y1j&``i8reIxKW}-j4P?B`5&Gond z;aC(1y}obiXwTJw$Wx3fG{lPyFR@`nS%7hsH1WH*_o2JM<-|mYn%TFflbhj9KJ(K?bb zqsrqDR&o!fo*N@;)8J6ChWm^rT5D6I8sCF!h<7sx;nhO22p(iDce~YvEKnvF)=`5o z+%(bLSw*2btCfp%&0^a>VSoj~vrn2yCgvc__9J;wKAhN6L zcE9kEbEA9@Y2h^}U`pt=Oo<4HVkR(YFKOuAM&AB%>1*yJkTgpl=N?iPKwfL|63S1I zzJxZFM}*d|U9o=MU&L9#yIyhUAIMXzr5zo@qEf$5e1SXZPUj^GuPXxZx`qHSDowu@ zmUqjPz9gP(UGcWM7=lu2BO}~Wq!F}^}Z69^p>zR}ZK06Fn z?fb360JQ;elt&Sq$FdL|S7HXo3E{~#OLueOy~%VjpQtZY+sDb9d&_f+R#OIGr!5sN z`8Rp%S8rAAE}QQ252+MQd?C)#|0+HHpA%ePL84NER#mD(E-06CBsj28IcblX;Nv~w zW$EtvL5gS5MlzYt(c|tB<%gfY%`FPCpx?9m>9s9scram>K+Z(m{g2cS*tmbReon*8 z!2)L>@!&j-wXWZ8N+>RQe$znTb(i-k`Tg=YZ4`hD>b($rwOc0(Ka$Jgk}Z~X34Qoj z=`g=xySIYDRz=kbYwR5DpF?33-NI$6@fPup=XsePe?kXX5cJT&nsxeoaGTdApYT>p zSpw&bA+A3;h1`x#7Nx1+r^WaCXf@->5$y3xB^cMp@2=AgeeV`}Q1Z^BA;rQeeVSGt zxLEe~U+mpNQn1Pp|E3QQd{lUH^^V35X){UFJwUGeg6rBP!{r*11+Ub~-k7EywjV~o` ztpS#yvLY59oQaTO!Ac_KE%fN0z*qn_y{{m-5@Z}ZjMP?bQJUZ;V z%QA_0V;|KDKt*2%r%agm?D|90`mT;qC9lwiBXBo%#*cu-#f{1Dj}4qICR=8w%NG9vl*SoBRyOiF3~Qsh^`Kw%Mj%$ug&wP5E!6%}{R z`9|6s?9Cf(s3{f+pxRa9uv{TP{SN!tqb_tG!~5sYx);^-`r~5+zYmPc6b;yL42HyH z)=4}bX@=>-U2g9V#>bK}YOmfnTiV0%#<>cD?A<6|hW}MG_!}uP3FWke?X?4a9AvR5 zRiis;0lP<5D~>iP-}zwQ&6gGuFxdFmWp(jcmvkSG{2Rwjnv!Cvmr?pJ-Zw+fbm%@% zV!XfN|BXiy$+UF03y^lp%`pCPa>}Cn*STTu?pvqEHsYP(+XG~{H9!DiljBc%4kXfx z8Ug8n(LLc~FI~l|zMu5VR%y6&PIhpR*d-0fix+J#+H+I?0K4RV1G~HqAUF&+fnE6k z*d>9veY=Ol&X@=EYIjV{14LKjIUw@@PH>Ik%%r7Eu&Mmtp?;o1jdhBSiL(w`JT8{| zcs^~Mdv{6l0#EUm=RFZU$=cV{dTDQe>9%Q2@gf%C@AiP+D6(Bpiaj~K%3%lN*L z#%KoWMabv3i4#d|e{&fZ=@dl<-e4EKcdR3@Y?H4^4qk$Yqu7# ztYZf*7&EGCVxJ~jzU$|0{!~_Re3+#N;L;}1V7Z$~tcVz3*PnD#iW`jzNXJ0SoWO#p zA*%lyl$bV-lo=FfE?bi99Fuo)VV~FdRe1Ow*C$#xkxvJya)2{SR}IbeCq>4d-&O&~ zGN6Vt5L+tXnEDPfCqkiewP?b%&VlG>Lp^nX!0Osk>gXUFvOwLmxx> zZT4I5n75Ay#i*sv6!3_|G8pxxU}Ogjz_0Pz{>c0J6|fdu+wMeD=2zckZL4RVICnu$ zjDmZJI_V4uN9%Qv$r^x;qeFM|@6v%AnJ04_nJsaKMd>yQ+IecB^>Mnq_91Ml=4bf) zWq^@o;3$JGoEZ}!O8Ntfo4^=sNLDGpE`spe0xRsz;;Jb8!?;1;%Vj;+rKol$E(6P> zw*?P9tZ;Z^-vF?ulDsmw<_?Tq8;TpTCK7p8yJ`ue#o@+{4A zPf;~dBf)W%dr~_Oyf|~B%;@H+4FIB7Q>z~*6vrPm(2QED=(hnWDQdX zvAp@df0MbU|7UvjH3!jqEsdG8A{$j(lRgzhYs)lqJvA@o8jdT~p{@Ge2M2C3|M6KM zjvp-Z=h$1o;qSx(-9G^1iJ!Z%_!o>PgIV{-NpyUr{9_pado#lq80zcoH60qXVOI~l8Jte3L^GBp^%>Wj@ycmB3HhEs@Q2D(xP}G3 z8R>cdK2%3I%3$7(2)c2YLFB#W1F9dS-szW643_(ehUJA`{&rH0Y)_7`Julr?>Ut)D z(R$sIJOU;Yi-!64avw72A%cD1ts;Hg&5TS3HoKp;_q*TO2sM%yqsG}azx?x zNLd2!YE@*qvzyRThV``@Hz6Ds8~Mnp07>v3oDAD&hW|ai@06ajIr=C-_ryUVm#d)RPWw61x%!{_BBwkw4sE$Ag;b-*p$b2ZDLh>|HQFn zDa9&1>8)2o$`TJJlVk|O)mdigMtvGe=>{)fAA~R@S%8?-Az<}KXE&;$l77qZ+4=U* z=@pBE@)QNsI;ZFaGX>Oy^u%>8PL`N2wOBphUvuENZl22Q!pD9luX=6~e?_enxXxt9 zyr#*+sJ%SZk8Y*Y_<+2Z$Ibs(<+~A4JH!lOK+JHdYgk!`q?AK^F<9rxzqI6WCb7^k z0iP-q7V>$tpaFFPLOcmBgJ2B`xl$nO@$JRkWG-k0FoCD7Vaqd6JlXl)5hON3~SV z%_=vJzaU8ojQt?CFlPsB`6k0THhmUN3(!$zUbOt2`Nh${sD6=G)u=EI8sp>9bB#nZ zMjEo8k~(=^T?KfCfNj^$?nzxjKNnkzP-LW2qZ+7Q+0l}Bi zxlC9UEXO4nhi03QA6}haIMDyy+_FXb#JiwN55pCDZ@s3J^An88@Dj2hkvM|Dyk$-L#er%x7 zFj43PXE;j-@6t-+h>F1Oj^2MDbf60*ga}$m!vDw*)((|*S(9uy!-EtHN*oy+r4swID1GXdJ?Bu!4NbDP<@I8Km3tsNH5W9`mc&yb+ z4PXjfO`MgIzne3@P(2*nAyv%;P!~cVwLVG`F$NFy2RO23h%4BDDYf2clFkP(rSFFO zrf$-9>NZ^31;R)e2T&Ms2mIJNXm2aM=@I%QmL& z{YPzX%Vp(5c-g$9&fI_Dzd%f0`QXO8?BsuGdu{T+7`FLe7dH4`yEi89*^8Bq2vo&M z#3b2kL7TJ}cvrz4Uy#g1&vcSJK9(Hw@f%!dnZs{TE7!Nfw#rz8h7yH~AZZNQv8mxQ z^v;kp)87jBq@@+Kctac@+x#!bTf~Sh{uecc|AiYF(J8l7+2()2p*iZod3^5VC7ujk zHG6xZRPMoTIty%<7bEC>?V!+E?){;&)c>ZlD0S^Px9JO$a^01N5>M38gsGO%S)qX` z8azv|SZCz!Ak)=RR2us`@Ocffj<&Cu#jf}$Nvg8V!Tz;ekI{TykId^eGq%&UOOwU!RM=Sb~Bs~Hu;G>r)F|ehzQa+=kSpV6FgZkkoQir^$NpLNCTFCp9t6OBq9MPOX^82S@=?{E>@A>_yKQFr z-R)&HrJiuXdwciPzVP{4@97IWi#$$b!C`kJFSp7}U-djaHGLtmk~Iff&zewrf=-Wb za;)oL)fZd+7;8((9nLoF5)9x1F%cEXZ(j(C;T6=d{CZNk&xS)M%_DHSKDp9f5k{9;&Fu8qeY~R>mqknC%`-tT-gOmU-28}^YjshdqjOn+G zq7k8|i_N}3;sWif02O27&or*AfIlM)Le_zhCDdd2*rg=Au!NnR?a54R3)WNm<7|bj z@;%2Y3OC}n&620stQw-pK!$c%KmCh}=oj62WAk$+4&Ua()rDyKTZ(BY$h-JI$h$(w z49YCSRlofmLFI>xVek1`b_}e`!p+5^zCn)l*?`x%;sRVj5J}U70ISr?k30OsW_qaj z?sGM_BWcf=Aav9v-2>|7^&W%ilPQLgwc68Ekf5m+sUeHkZ$>UE6W8HS2*Amn9}-|C z{sXz){?S%C84Q(VwQy_&1aQ`%4c=$ty~&~krW8WFS}q1Khl;G&Jqg;bf=T!21W#OL zKE%C7i*W#aCxNQCy~Kzed?yQ+O}>+>NgpP7v&`*Fd;rJwPULBVa8+)Ls-l6@O!&pB z+k4JG-ZRWHX(Y3acgo8+vW0iTN%9^uzeanh0bmV8!9aHGH2!g0#-HiKU&fzdEh;0ogAYzDf$993rEfpd@+}`G~ht;}WXP&RP43 zEQf(_&vF!_bXoES1?kK;q3DI$K`$1f-dbrt)3lS4o}opN-)*DdqM0jF;ioRqB`#$4 zH-xU0dker0lJp6#0bNo>2%r-Vt#4z# zMktsse~KlDul7D0>P-kgsw2a81< zuU#1{1#A1&%HPsk2(Qp5@CW8c2i0Q0B%q1`x0uOqNe>8ZtvamEWL}H zlrNckh}I3tSKe>R7fx~~ZJk#3XH3z{vTO!Kv<44r^;I@i5eO?$A2g+9D%ykK zt=&^7-cW8s2NQ-ACq$;>`kw^h__Pw?^P|JnF+i$ILcp7%xc6T9FsjiAd?yuZb#Vr^ z+bLM{GVx#}w_m)onHxER9I7bJ`zFV966a9ZrXnRUzsFD^wFu0W`W@B9 z?e$AkcEc;DAFPqhr{)`b*h)#~iR(i!M&$YSTyXADS(!OBt6};b@0xySlxZT@_3?Hn zLPY}pf#f^coWC+(g^pONv+)036BAqH-5@Cys%s1*=$H1LY{Q5m{O0P)yMFx0?Rd~! z&-f%W44i04w}+UV!($TJzdWAu1n|v-Uf%?&W5TLsWxO6ubTTGu8pPF6-TX%*t@#=! zlJ0f9VfE=NX&s6WaSjFAGN6Fb_c`>E*kn>ABus=;`CtH6HLXnrh6qr|VfFQXnQ zE45<|5!H3toU0$D6qKA2dBI;+a8FJfD3C+RY>mO7C_)RcV;CsqE%5R9&iL~`as{ZZ zBUdp|9`C=eK63txmgSjBQ>Id(5G^c*q5(>Z;N`+bb<>Ye8w3tYm_`990qpYVz1%&wuIO?0gbV5cIMYx)D? z4iTNAshZ+Cz4~kwXXV9LIyWdZ^TuFX{0+oWUr$9UWK0r>rfWRvZ8Fe9y>8h1`EJF< zE4O-cc`fL;7G&m^Nuu#Q-~u0u2K1ABJ2IdXVF=65^6Z#M`%wpfN(){y^tkOX{zXc# znrCG7^u{Li0-Ml=vI*6Rz*p62kr6)+5R+GOC={A{K%u#1Vi6@Oq~=#D6-L#_d$*$& zi_b(-_PH%~8+Nn0JZJ&_2nX^g2o3}@zyzR2rMs|#`_GU>N6}mKGc9nNq0rBw%CtnT zwP1GFn50@Q>*@PUpDl=E54n0fYc7mgW-jG_Um%9Ko1jn$WifMPGR?C@P ziOFe%KGe_FZ|u*W^_MB3)@J<&@?fkBNE8IYM5kREnO}#>DY#O-xo^S$7V{{9hPqgA z2wm04N>V0x`o+FgN-I+ei>+*$RR}6vYO9Lg?#g}9=fi}Kdddmu z$jI<3X?^$occmWUWvMBFIO+-H#)oFg@L2L2DLe>I<26_kVm6=%v!wy%%xB3=0H2f`QBnDz=ql+v^{(G?>-iLY_Y{u&86aNo;aj0#>t)7(t%qHAUqE&FR}}VP1$_U3WaWCEzdpy<5woOe z5mUE=4hKb*e<5K1MTcXb(Ojp|E{@^1smgW0(9+&kJwuw9HYYmB`ImRyxR#`T#Nfim zkEd=t;o9XQldQrv`^&>q_Ln6AbLMr2a>4=8VF1nBpuZCcjR6 zcyM31OPuIHJW=0RmU1G1v$5MXc^1!rbA9S{Bp)L)ns4_h$dUO4dn5LjZKL9P z^Bv|&iBOCTzQ0l&e(_UysX^zRT-^ZiWxk}g(daR#*(~Fv`z`>Ds}2RwxQG7>jr*>A z0s&A+p;dM)Mx6*l3JPg@3x&k%$MEUMOKwds-vYOcP5 z$T2zQVrS81w_CA9Qiz%wA0d@c zDY8yQQ7RQuw$WlwQX=b|7G=qnZDJT9L@2_EGL}$TCi^x_b}D;Jh%qFxWX3vX#`Js5 zpi`aCb$!3T>vmn&U)QkiLo`s>ia95d;FzVEmBF2&Da?xSan znPr-*Ct!0&EoJLq>nO#BOv-b)EVsRhai^8Cmi+N;Whdr03vyiGLXqNz;~oN;5lpwO z(DYz#lsv4SoE=*v4w$$dkF2Mj2p+@Nz#vEYhS9)C%^*r&l=|(Bmv-F+v`KHc!6)|jF)`sNFvFq00?237kUu)^f^DgjV1U6muwL0>qW+yAyLUp6*i*O8TGjQ63R zPx3!^F#c0l9EetGVSi#$sDst!5&r8<(lSMD3Ps6z)Z zftlj~L}b9w>COhB26nD?!!}M!y@m8Qo$mJK0;IwZ;SO@uS1hHQj9CmXOc0dC@QNSR z3OKvM@M@fWz{b|@;+IMT#yZF_VDTZUuwpNFMqvV$hoQ%SLU0u*(T$DSuurThO_&wU zJ*9t}_3ED#3Dj=UIyZQ;63Bi5ehfEu2@IyJ;Kv3EQA_LKC_ENT-H2%cHW?_QNnN>9 z=%LqPKKm?{Y0B?fpB{&i_M6)um-Zcjet>P+|E}W&`{F8TCyi z=HpLv3E#5FUWj`)uJGn_SI^Dt)%XL}&VI|;h^B@``!QkqC_tAeS_7z8CwO8zs7KW~ zttoNl20Rq=OWiN-XXvZ->IG~o>L40DyH%|FG3U}y96bsS%734Z4Fiu7dA2X;6_SzX z3dzVTvKlC-HD6<#CGUudO^MAQFZEl`!DkpCa=u z_~nBHQfO{t!N%#t?OMmu-U71PiTch7(?p@=^eh#fq34Pk20Rw#mC3GRWsQz8{sMo= zg=2>mzMu+F^w?~zm5y_FDf~X}mwiheie&D5Er{8=c7$M+=fIx$c8o;9(SS{r)qP)# zCIXfx89Rnoe~MKelP9V`mj0;Ob9n-_EFDoP1?Xy6zTrl!!{F{A#BK3*z64s(qoYe3 z#nh)Gb!XrddsSt|ePuMA8_w8QhGL4_ezqwJ*cKM6F<~Br?dF#SsOQQ&7o0<$&pc3^ zCXD?PFTwX!%wO4DMBEwrJzji4ykOVj1-EmR76AOa!tWmqNv(B-q~=HTsBi7G znE<0~w#W+MOdg_7&aXg--M*suGMU zu#0Insf)Q|rpz-e`fD6jWZcqCj9Po~51*ktD(_9fpHWTdL0Kz}37n?#1&DMK*pPrt z=SHSYr{xcb7lAe8t&34uPKJF6n!rt)Go3r#*vJZ|ovAv7dfG26ne&D7oI!Sl=4;#> zX7FuiTOiQ)LxW*+2Y}#-a0f*;LRCMaxPt%mQ}(nF3K_%^wdnvr^|P~Y2zDkdV(U*u zSb48ByFbu|NRUPu_t&%`TEDzAQ^zn3rYqxto(*_r^OGWLCPbFGG=i$X>g(*jyY=s= zp#3_c(fy}DmcEJFw~z^rOw)7_@>a6Il^7YV4n}EOmt?F2RHxF??(wgy^zFT5UFBjJL5!c}LneH*qrTGwxY^uyh*u;bXwrLaz7026Zb*n z4V$v(b&Plnb1T0JAY37Y1xOrN+;)(!C~yuCs5=hhR?Y#wAn3MTl!PS9@mQ)`yjPz^ z!kx%JNQ^L`|6eu3Sy|dYPoZB=Ffbg4W)8=3cWT;;9q*;l&VGQl+!Q%}yZ-0|mT`Gp zVK#Wmg^^heXQCf~u7}huytvE_dfId^rjz+J@I{}dQRWAYE^t+{=KBb9hiwUq) zzro|iEIM)1!}xn(V*w`u&(+mwsfJXBaE%oR9oO?<{5;Z%Qv>2XN>>ODfsI)*U(n9{ zyF+|bK{wW$Ke@nF!F+Q>0ONkYGJ~NCz7273YA1WHynG{gIpKfb%kiD@`onfghhiqA zHB0a9JD{}g9WTs`K89(V=Kj?x{KEP)S1YA%?A~M>=YGWdNnB5>b8f>z!X@WQTVsh$ zJKlH%jfz(mcHmcikfv9CkdnCJq})n&FB>#vFN&dHm5^F_KL>HKr=amrM*Csn^2gIW zxhl7cW7P+#Tj7b97d@+{mn0H}K$}z&%y@ybnMJ=bX@{}sHw6X#68h~)2)Aanj%q1~ z$=J3m-R6fk?z2nXGXcO5$x6z7k`mA9A(^UFpVuc%Z}z7uiw!>NQ8SS``L!6!J=7ZH zwNS259I*cRa!Tx!B>HA&d_Ok(9q*NtFOK``eN<(Jen7x6(>R><1A?CeY|x{bz`oO9 z=>QYQ2_T_N9B21OK$_t7tV>iQwcfj*OcqZ+$ocgLMCwS>zU7ks#qGl)!EiJ11tN-m z3_P~yC=xF?w8HTTzTH0{<47sSJYgoN(msi=t=YWJ>~JvAb?A`h+^IBV)0t5$~uI~c-U90vSa-mcHkd($TFZMGuMe>ATrNdml9#k2ZIhnGgsEB~Gd>DU2%s z)+XOtR~rlkBKHm(1eW0*Ox?yFk;hFvP+St%jBUeh(7XEKI#k+`(e>F*O}yRxL9By; z)|<*0LA#3PJngr)PH^5Ej)sde%_%MBplK^=qPF!rNm_wj0kT2ze`)Os+gSoMk@g-@ zv3{G9b1ZF(%sA(}^CXmR98vDSo4fR2qxnJNzJOpcZqzvpw+qHIdhWYmN!wQ z7!c5DuI*ml&UW$rx!ley-@5D84z_l3w7;(zo%f5+l zO$a4E`y1>R8{k*QbLb@=Qxx6}g!p}k??YzBHQNvYv*o!}JpiUoWqdZ(BPMShJs2tB z4`f4Gd=$GMkS$<_6&$MsJVudH15`C(Ohpu-qofQ%3m6=&H77i<+F8*hoAp;-RPSV8 z;Qa?29L7K$VUlbT#4=qg1h-fw@wcMIPet!vr!?H$_jmbPlnr|p#T5L1{&DDCtUzuh zfe-AbkagM%BI8dU4XqRzQ>xv9Xr;lX^3=s;3%*S`4_FPY-=O)n(NWHF3YknZ26vvb z9jHlR9QC*^WbTvN9wc|vkbIy`rTvkO;XA5Y5ToxfCLas3l}(DxeRQjPfnW5Ha!9NO zkH1_H$1RT8X?UU%$fa(tuuq9^NFpo93QC7c@3%{jkebO&j#51a<1Z%ry)pmVqnHD~0;_WjBKpj)zI z^-x~nF=^pjpoI-o%*JI$rXmx9#G6}fVOfJ9FWD#AMy|86bdqK|gCwt5Pi2|S;g~AL z^nf|=&34?C2B;ENdvun$C4!xlTn78YIs}6OS=ysDy9%aZ6{xI=r2hFbD#!|#xc~g> z|M@q2IN!>2Sc1067J9!Am+ZSzJ=-Yp{QVBY=zDKm>+b6NkjYvM9mP=8q>u~PxtfuD z>YTp82slH72g<;LXViWTr(!>+Tn%(h(l($#G{VOS+s^jNf)Js?mx`dB4c5b}Oy{3* zF6REy^k#a~yOVP@@!x*Y_kqK#UG4%WfpQZQ>>D4+-~{iH*@;z6F{QZHbepN6ag(tw zAt?iW5iEp}JK#roGqk7I_)!JmIWzfD6NB8#nnN>#@TZQFws65KA`hCT%qurgw1@_f ziDVfJ6Pmg6Q5OS%s5o@Qca5<&1-6sFlKAql-lV=7!d8K|_SJ)7>%PkFbCR8&>Q6jL zODUPA+{6W=K7WLf!0w-If%=sQCSJfs<;tNb>yQQgMXIU6&zIxd>x6pt;cKmR>4eKW z-lA$0kjjkj;G@2WTDDVT9@${aw(@{cj|)>~{9vcByNUXs;Uo%x!zxv`xaBZ^)A|nH zxl4`jIkrosjN$$T&W8HO+TDhI?w+N2D*N0?j69j^EsPTpT`L%0pDaeR9MHCYlGf7I zG`DjIJG!7vW2|y%b^TN(0JI9b3av8oOj*Dq9=>-e^}Qi|=jd2{g#hTFCcQC?Qm3|C zNinN12Rm`ARTx#w2ZL$Ms8M0|fld}EueqKH%Cig)V1n|lH~YHdKgB|4Y+AwRz7aLI zK8XWlzqS<5<^D6EGYV3su6~5b+jyy(<$c5F+XAaMew`(>#NF*LkcFp&QZ}vJ#1p|r zyui=2yM-*u9))3X&kvLppXO`BkH$R!1qH`$*u;XC&XnZlt56m#|kCE$v@hdWtF@T%f zhl!MCp9?&e7zj;HW0HK)^NB0UXzF>tO+>mAxRXJ*xZC?^nd{}NV%1LHmAfr+$3Q|n z%f19~z+(A&^4}g`-1_0Mo$~Ns6A6ifqa77D9;Hg&n@?lHmYH%n!WwH?91lo;_}L7T zuOmK$6@VIS1)vu56~~-7=wH3(R~-1)+1JKZ+r_-gKkABG_B2@Da9Owb1xQNmRxVuN zN4N%5LVQn=D4GhTp_T#bb}ttR-|v9QF}u=j`uWJE@pa<%pcKYZF3`tTRbrJ`@FR3G zt*NfFtf`uxc-;tEn^nGSJyU=RlZa!nJkzvt_N{0YmHYcB1pEc$~a4VP@=GX3KS z14zDG{{Y!c1^{w^Zx|JrxRVl)dFthaty^bb%@?WY<5k6ya}Alo-@#9?FL>cLiKn9W zQiFJk_TH_NKlG_R`NcP06<53R~Z^TDm>4HgBy56D9HHz27PPs~p7xYa;9s zxKCiVc@&o*`?se9H-0Roa^2bxg4fy*!vBP@3_szEhmK>V=F34zO<~T5Wvu*~gzlaO zcl$Q3X7_I>7BO=TnHX=9#$d@dS8`i*=IkoJ#+j|6*IeOkJWF-Z37p zji0N~C2nbKH?wSzyU($%c0a4TU|fidp&dXqu{74q0iVjkBwmxDNP3jhT5(Pzo+4gJ z`6ETB1OYOtsd6vnJYF;4 zLZpF>tnpYQIgW$Fy`Bw9XeC;9fea5wbXR~$#f)`|Oczjfifm0Q(SXy|YkM5`orNtM z&b=-_GhC@`JhB3lopsEl9kf%5&G$xDN*6w~Xqn|ap5^iVn#*Fv1cstTQko@ZgdHvn z3wPw6OKhGxYs+?equcE-(aV6vr3|OElh=3Fdc|PHrAi~DbJETlilPn#@8T=}W)((L zp=*(Eg)w#!uGsf}#4qH2!yKz0^W)l9%Qnc%oUR&Elk#m{1YS=SEjV5rXH>JOONiCy zQW2xgqt0_#sErI34bL|wyJ^VWw$q?2VzBnmQ@#6txjg^umIaG|ZdbWQM1{unT7~Dd z-m(_GkXIWLxb6afm(GO6qMzCk3V@7-6PJ}}wVwRFmQ2W4fs5a`#kv!4UC5%-L)6Ca zzS21nhvu&ofJAHfsM@cTu?B{aoFNFS*Lcuv7GaL}WiC7-H-ykdpuv2>^Ex1_E=+i= z82j3DYNlwOD}8tge;x7FAIBp&=h+KOm6KKn=#iV_0=r|oqnfM zq$%a-Jvl$k)V6MZ`U=&Cw+EM4@X|Vy_DX1?9-7BC`oqXbY`2t$YLmK7_9n;>L!7eB ziGzLuzF7|$cZW}TaYD#&Hp=V9Tr;AWe(WZw_n)!MSbgNWcE?ndtUu;H&v~r8e{Pqk z3BdN0GbF%8pws;a@Y@Dgs5Y(+0+-r03;JP)zdqZw+rfJGh*er>swODTH=S$&XGMh? zR(8RW-0(ofS}LR=M8VXZ&E^mmebnf7|JU#Jkck4{%io^>5jk>-b{2V-Y!X1XP4BT$ zsx1pqjWoS+?4vOkOz9%lnj9v8L9qs57VYlrA!_ z4;+ZZsCg(=cnU?@ile-qpALlaj8bk9%bO1m8%BbXU#heCiFceL zJ6!w?7VU9$V97XUGZ#PvYXKB#ls^Bu$>B=O=i1?EZ#f*aZ~A5@X8kFpm} zkbEza0uj~Q!sVxY6bu`TQDsJ2BVgNAtcmE*xH4uKTU(1BSqL-m7XnJ#?BjvKGN)yx-wwnvxSOKBCB!{&J>hUoPnZ)%jjLZ3}1q* z(*-X_*mD3;I}9{gggJ$N6aggq!19MWJERq8O(ys$@bT7o#NM&m+4!`r#4<`|j>Ek# zvK}h~$YB>j_~&%4hCk*KC3;97uCa_B!Mjb27JsZOObxpac_S-%HBv$}2=*NL9u#D7 zLyF5hCMYn4z?5_3QhWw=u>2$<^5~%%%SM%H!V7Dy7M*X2Js41@4LbMnSAJbL^SxD8j21nENNHIC#PA|3oYO_jf ze>{A6!-k26>tHyliKhkx*#MSZ%u7^Tj{{hC;8z{KO?)$nMlq@KGQPjJ`d2_>DFE94 zw{jBubMBEQ`JR6PjncvM5RqU7W6+rT0bvLz`oqTVkiefdgQR!pCCJ#q2P3JXSlACp zfHaEonzHWy#9ySM7GlY_g53#0y*{h+<93f%kF2e_+*@8eyKxWg0zU#S9PVgt*e~;d zix_`30o2M2`5@Rc>O4{WYKIZi8kDCP+cM9PoI{gSIlU)Rt_<(q?lI!34z)6bAD|0R zGKS&Xkmeoo*>HH`Og(_{aPNWiUG)&#E}jIfu6&)et^^*2=G({OX$te4R#i=^Fi(}J zxA@7^^aQ2j4}Z{0jl?txh{r)heBrb6{Nvg9*OONZn6I)<48s7ZW92huaaAdx+R3O+gN#!UB1mqDhgurl1- z#x<(?OT}Hh|Bq||6NO_|Q_Vm%buY7;3TP5+f6T4J+3^JEcGQ<>L_SF+<6y5h;fgc4b1kSB> zl@bG#NW;=%QlARH#d}GIg_89nhqX`0ezOXusnL&;gZ;56pO=&Xt>ee@zG2pB-wHif z8oQ5uL+u=}bod?YhH-b`KLfySb(>zK3~g^Rf{y6!vHz-u^+iJ1RSv0yK&F3!2&CyeWgM9pmuP{D7UfUpgPePe&d)^dg+}i=KPv@njj6jh^_+52&ncE~|=9Vdj)Y8ZKnJIEkidshgf^m@tuE zSDDP;nr^AF^YhHvcc~|ucHM*T;PZp=>om|Mc);a17R-;_sq6en6E?Tcf<50RR0Z}o3l9i=Zc4GIof>DHqy%Ijye2gA z3WKIU^h-L{#ofM5zts=g*$ws3a3ypNoWI95*6ecH7f%8Ik;I#Sof>$5FLKd_y=D&V zm8fmWAE&INYpf0T8ed;{@9MWfiZU^!wB*&f@EV`vH0Ve1K7Tn@ys@+LGE;^xbWF3cfV|eN7V6s4aGPbjJ{EwGrn8uB5mqrstwb3^){k z6RK)q@-GO)1|a8Hqqs3aJ;UgomGa{#9u87^EagRUuhWXFRt>ay=*o-O%_DZ?! z@FS*-F5&r>WDbB1xRbTQ?RzBijmnyPk!eQR7%c5Bo2G#d64g-5>#|AZoBWSc;vI|* z?($ppV;K*%!vh}2sE7k;#8Q)n_e~5r)1b4kd_tNbOu0N`%TCNZk(}q9MC#cs`9Q+rjuJBn`2M!RyinVZJlla}AAbLQeJ61-=x}n- ziO)KR;)9f*@V9w)!vfU~e;be_Cq7PTB~4Vf)uBAa${S-tP0t(=5)!jvuNuQ-tI1FF z^3`y(hezJSp7e6(KR&J2w7x&#=tEwRG%!)5RtvDXb95=N=rS4G*}iNyAqc|)=`z5k z-6Rij>8w`iy}bvDw*KXK!DZ2Be44&%0BC8F;hI1r!!!_q(5We)4T~i?1x{t%dWJC9 zxW4`NpvcZQ&T`AWODKk5VdOGDY!hm556DL#F27{}72HE6Rgq9I2UOU9Nxw~a=-u~k zFM@u-^J!9c4?UL}+S{G2lE~dA|7tFpy=HHA%KGfepzzs z>8CB8dBYKeLlAGV9W%?AsmmA(LKPcn;aTRv(7*>!KyCcUyuDth;LPG`5;u3vzr3cC z_NE|;D1n^1_F9`utR#siRAvNCvFBTBX*9|7sPQ5-D?t8{(0_iRo?EJ@{5Wy^*i*~X0i7i;WRaWqv_liR9r<8GQ4d~zPNG&)aFEr9F?SiaU7b)mlSc!QB*D6q6s zaD4q6P6t9CWsYpD{$lU@GY2S~F`0Y?-cJwY<0}Ks)Na3%@KD%{4)zi#Gro^p7O)@m zq7DD6(%`pgnU{p4hYG`%@16nG?mAxt{*P2an*AcyVByt80=HXRQuH!L(11Fu;BD=y z_6s?w%=>PRK#xWlmqVRtFbC5nU5#@Fl-v@XmQ4E5Tp;scS)s*I@gg93SfQ+;n3T1$ zxhq)vv}V#ArRm}*?TDGe_l|((Pf1b7M}>yFSu`aW@s$dAgP&wNnaUNK((y=_S2pea zTAbKFX-X!KtQZ}P4R1akKKQk$Tcz)=nN*)6n2_Ou!U~;$4Xa{M^I4M}vQqWXlF^4~?%!k2_;xFN1O9&X~B&X(dG zlK~fgA#6dBzJ>Lu8bbs>!$$!}U(Z4oYSlnzq{miT1b#9XlXA-=en1S0v4KY-h7@Ah zH;W$OxHbC<(1}t@o*v3hdp?^ddHB5AA#iA1fpAuxji()WDRiq#0+eXj+ z0fC11eKNsA`6~C1!M2%S5SBE_1!-o;2b^vACFRBIJFlZlP`Yo)f>Yds)0+_yiyD>1 zUBct<&TJ2o-ttPKEe_mhM<=N-kgjby94;;&QJq+(^vtfA%%}ZU5_J=E3QXqSz+59m zHlQ~mI_m`D*FRmK9_Q)3AVkzKh!JYhcI`2+o2x8fTk3j|in`rH&t_C8qY7lkF}+Cw z6!VO~_(4|{QHH_`W%kKDC67kBp@Y4)D;4F7eTbd4;IE8m^OK`;u!x)hkDr|?Gczf)PWe)TX)bD+$TYiOo zoK2oBgQ-Lx&3G{EGSm+rx$RTrNSJHS?7~@FTT?P#30#B?88RW)`pKAV8_+JDbrPbx zl8Wyk^^OMv#}+5|O%l2O+i%otj?fEeqh99WTX;xv3Q?emiMQZQ%oDzKZ20hK*M$$x z$Ic|41mEtJRE2u_DN1rO^0@Hb?jh_WyY;68ds0p6n@d}+ppYhlAjCDm!<%0L36??n zSehz(f;mf;wtwaYW7zldBDij=*ry}x-%bsce=K!Sy&ifoch|9Nr;`zqyg72scY#I) zdJi^=Hv`-C4R9+QTZg*G&NxbjO-+OJ)Q&=X7st4Z`(i&my$R8GjvN`N6*Bj+#9ZPl zGGE$cX(N}P_SA%xJ8QYY!S{k9u>xrXb|c0;p)MgN_&qQ+#oJMJOK`!2?FF(A4!z_N zkog2g(C9eD-#D7TKR=tU`XE0Urutvb~(|_k47Uv$>qUv_LBl%{PZRqXy)+XHdT`lx9|aU$2;UYK9|djwd^Rtg z7!U+`$Z%JMT>9a#kLE_xQ2xNAG614qosd2q(zS7f^9um(vx_P4_>%8sSS^mO-;N6;K;Ngs$u= zU;o)vL|55-X89oVS;r!BqM2wu=mxqMK=Y{>0yN(vJ6lgr+||S#MoSk;n|Q&@r3u!X z99DzoEe!KfG!4EGr#x+0KiI_j;qYfsOkH{I1umICTi|dclNA&76OIRGZ)1Ze4}h)i z@fj_kHIqioUBR>p|B*~U>`Z`~?Kc{cLssNAgvnX5Z-Q7*MMeYaH=3H(usSr+eL*ak z9uF$fpK!7azpi$$AFRqrGgc{jX(|dYw1@%3uDnw({^rRoYU&$#>|fgA1?C4w?*nDT zepHh(xWi5EBY^(s6cC;w6~U*thLmD4hsLb7{72>xSCy6YFG!)Qm@BN0Z+z|Jv!c0@ z;KZr^kHvD7YrQ%*uYIrAIriba4y`MLhznNRMhZ&Z%LquRx#}*dDezdRNm^U-j)6Py zk8%45Qb$%)y&|D$coa>u(jL2Bpwr}sTH;`3+_?8tK1XR{Hg!pZ>&5A)G8}a zZ72BFv{pZEHnSMrp^0;(?-6^;%ZfS+Xhv7)eGksM)MF3$e{fdj)xUwNZXm&a;TJ+~ zgQoEe2T1vIwxP!M;gn?Nj5{xN6lU+unZ!)VW{DnqI{5U)!+SNzcPYJ#X`eLe7yCqy zM%*!tgm^`(3(K1*fWtzh3OaYvW|c9P?I2~*;XZMzq(ebZRd;9Kbsbx!53fJ9Y`my` zLL$-&g41x#qpOo{^Q&B>6rYaJ{*;+Ie#HNU^C^)M1t(o*0k$u_utQ;4*099rn7nbZ z%RAyJNbV+`dTpUafUwh=0^jZ4OwjVn*@7C&wZK#pR?XL*;}}6QlK?Cb9Dp>))Oj_b zv{|q?kJC7&r)t+`-ay_M^YfH5gQ`*&i$5MjDmrj>6@(qUC{t;8uTiBq8**2cWk$Xt z3sS(3$v&WOCAJD>za+1Z6G%G5z0)(FCn2}|`(q}z5e=?@EUe+0GFx4Av95JVp$WHQ zM1BS?h9C2NMa-5kBTd*S-H)=ceHaqd|A0Gi*UQ0C|J0cr^ELA0YBal|fktDXlQ96q zBtTc7Y%=EfnAk5;W5(7|(5F3F@R9f2sfad_y%9RCt^?Rs##Sdk=qwp{mWhBaD1gc; zFK7c=!YV)X#Y8xXHwF~Y^%Y0ocGwzxy^FG^aehMY?9cZQ%IzX|s!)xyMpb8I;cI-oiN#GtUR|VH2gUdEDNgUOaxY@x0DCZhUkha8Ii<&WX;kRhlnvePI{t_2g(#eN>10)62Qfw!QFk))Jp% zBLVpNKPr$+#yi~1Wrd$yG@la6Q4;n0SMvvSIS0wSQqSv>XgU5U-+5b#6R|arzWZep zDrxM^Crh2J_g`q<(cQKY=<2lqj!1?9w&NMILOv>yixCE>@`u1e$|VBjcpqrJU#rX~ zN8BgH(`utyhnnUjyF#TOS=n)KPH>qS(R=7JWh8IFi`*VynHQ&7LK?QSJy!TK_>#$^ zCUl(LQn1vCw{;L_R3VOvTh*o^``~vGi@GF%^dk0#W41QAaWvV!@3lfL{j@vp(Zp7( zt_D=KEQy=ps{;0_0Bb;Ke!})G@z*oStULRb0wX%b#<1VO+txa*O87u4$aM~g9-x02 z=Gw)3w=t^~hyy^uyBp*(I}ty*uOxLXSR595o`yoE0u$oF6O|{g#v)}mt_*P(bZmj z)iO|ivsR+5+xqV9%pH?6_R^ExZ<1SlEqjL3?M5RCoPy$Gvz?^Et=l`6u5xdwtk?pJ zE13gf>&Xn;2l9W0?GXeVgstY!ur*o@TdNi2=`X;Yb$|Z(xAutr7B>#@bH5~>Qq>ldX8-GF9BzEjXRM1cZkh3W)Y7AW+UI0cnU>1CS*q@oA=DM;Rb!YGkQG z;K4w?!zlew5{@B+YHPt!xLknXd5pdNB?b(yfEEhrJtGKQs@^I`G8DDwU@HoO&&gpJ zY@bo&GRU0Wf9qRQR0BCi)4sJd6?1Q50tZDpP<*oJD)_lRzAagcaZGy=l=XAZ^4*Xd zN$k-Bm1qB(3Xoq4MQa5k=I`vyFlGtV?5CaM#2jCP+O}dcKEMg7?C!cZOEE~bqn^$B z)A+E^@arLLFhfWgT=kNpK}`v#qb`DD!?7fFE8DgGG@6sLjYV-2TBW!xuqbYWE(6$n z0Gk7=DLIn)Qt&Q1A;!irfiA_ z%BEHzT+T$*NR2_~jscY3H<=EGF!E#`aOJSHjWy{UNNcVtkv-;jsy8zN)(_4Ax*;Ge z2Ic->St-|8<^!i%bmRhZKMz)M=Qogw;6tE5U2v+YGWy z?eLy?26o-)C;ua$5~#Mp^$+)j`)BoVsU4n*zrdZTll|#YUg~a%B2AepusWjW_^3Mp z9CHCpR2PEf!KkeQk@f(MY^6mGX6Om7IvV@HNj1ddXi`O?-1S!$;B>YL30N9Wz1d8u zSM@}{D@AW-H22DeVlTh6j}soDv*3EeX8~MKD2b1kHO*K$249_KWOSitF3f?=i8;;a z6?YGJs~P%s;AkG1C#TTIT_New!HX%J4r7h35njjbwLnGLQf|nq)c)1Lc(I3pgX5v< z)1jx>p60nS$Vq$;3m$`-Ql>2RJDR!$(;iClcIq)dU4#uKA~jw{^9QrPKkw{nMONp$ zgZ{1gX<}L_(SD5#4RRL~u(jHWnHuPSq0TLBz3VYL8{+F}0xk-9arEeHIHTHuIjHcO zKx*pcTHXu>R%j6wvP4Wx7%V8Br#sHtM|IrdGhk^;bBMhzVLHEv#V|WgJ6Sqea|P(i znfRVLdL32xb5@&*YQRAX&`?B~kMFc8wlMa_*`sGejT|i8VY)4((aFvfgljF;v2c9_ zO1{je+Tx&-u*0<%TX@x;ur)J4yW*!zZr0N0Jz1Hk5nMap$+?i~YQ6mY>yw!s=cj0L zSd&z+&9CI(0qlf!;4J4d=D&~92KFtC%bx!Vfl5ue$i$aTE{0ihQuQCQjKZs%H+uUcR?+TfP z`Rwr{oRlP;7*-fTlbWb29~?E3F3m2*1iYILwXy*3690?}0O3&O8_HEud<`+c?qoa%5rs6e%wSFeS=O@f-ip8X#jIx=3NH*< zdL8N+BSoKedKY=XVCgF%26FuW&KGcJm}k~+B0?)8^lUS5=HdCR4*;(25sXfyqSREn zeCK!h_q0r*gv;TZV>=3No4osbFlN{AE|*D}Pnj)hiWF{R%7eiKeJRbTuEV==da;U! z4Lw4>T=HidJq!cbd3FXrS^$(m+OtuEZaDg7pKMa%_z;b#80_dc8as5?VMn5=MR{)1 zm*^(UGcY!QybB1-N{Xzpfvs?T3j66YQbWzMh(@JN?|A)Zjol$pFCtH?5BVt_ScO}v zX)GrJM|B?AVb0|obk4Yk#{>uGHUID0ZTvf>AfhG;q`rE!eOM6pncnEFcAYhcQ`f27 z8EAa>&f>-vbB=2jz;Ns>ZU4$hLR;iw+U7&1A`G(mlXSH>HA5)+_DPYzXr!zOUF z4)7iAe`Qsk&j3P``}>)&%6Q7%r6Z*`mOib(D%n^XXTnbs<{GSW;v(f2Sfw1cT<+_r z$b))k*lze~d?bAX#T0`)?&CIbr$=WwY1h`@V3ppSkR7vvQ;I{XPMYNJF}zQ+;GfP? zojvsI<3jkqmNaeBQrSfHz$y<1SG8`XYmhC2GExmP8h9%HE_QL1kq{VYuHQ}$0*P+U z)8R+~HH=O6kdJjty85ZgC;p0j3z^^0y|;`%x}k#Ned?d0+^@^oQVCcMYK+=iHoOC|~(jaTsS0WPuKFh%e(YCYZ%>!F2 z9hO>rCICAs4(SQP)oe9fLCMc{F#9~zuXzyfjhd23YqBmmIa3_7OLX`IlfbF?uO|cu zobg3zSqLs8^rer7r$_WP9$S6A8S~_>HX!IVu()Zy%AgNYAqZqNpbs$Y{vF1l2DOLs zBKM-w?T?x1sMZln&N%FL?==*B_Hy)q4f_ZvvEl2EP%@1pWVelzQ>@Ot&h(LnaGiiS zV$Lr=#p>kPL$?)j`xuyhlufogptbe$XY6Z{mcSe9rJnJ(R$KfA4BwNKzRBti@KyP$@cS;3!#vPzxFpeV-9w#)%u1SgXa{p_qc}0l_qo;p;r{;ckKJ(_{^~n;Y`gmha)AFy z(QPurtza#Jsj@Sg%(d9Dx)$M^;FLaMP6n8R;_&p;JQS|H!ywjZWe^JU45U!8bmqhM z0wYa2tZTt%*sZD4vzI8atL`XI)sY&5Bga~IKW^N%WxavIx0qVw9#T-+pi{6%yuj=3 zY4^=}VBfyu+xHyrwUN~&4bLvEca4nwaLycJOV_M5Yh zt>c+{v9$zM2-o*zZQ@9UwN2b8Tv*T6?6}OAcP=p!5AQV;-nEXKtQ$_S)a>;vZx7Wv zP+C_r3K^xvfX;{rmYpdp)lZL3ZL$}uRs43Re&pSLL(wq5KbDI-hRzqqTrOD$-SxgM z$C?{@_XSlls$);xvA%wIFg&RL+2{Zk&Jgl!z|E3VQLMqS9n;+dn?4dLTacoy4$Cjx zGV%sQm&|*#TU?&Gep82vg2J!+Q0p&iF#~l|6@IZBx$$-Lt8qb-ne-$>=2G#SX=9Rx z?cag3LuKvxG=b+c@wt+VuGYm6Ljb`EAPpBpfq4xj5nJw@{!nZb*U3xj;&Fc*-JF*C zPvyhvjSsx%UO~p*gZ+yb+g8|uc3JnAeD1N$b4?s3O)x+4g)_X3%Y}Am zqPH?%Ds=s;*H(n3)A;wab5j8MTgpQIHkz~*4inb-3fL2P(3VP{i!P#UHgLdiK1PeE zd>B1&bg^N=ss@;B)zS1Rk!J05@3flq3E}&J1{qv8ib@erisOeR_lph!bntTwFNH{Q ztwjM-`RlK2I=_*toNgZaWbv-CuQ=c3KGR(Y`7IsMS9j5F!H%)7TgdDNhsZZ=31^^i zs*GPwcX!azq}XSCwvAgfmOK7RSe|vhH$53Xpe4i}X*cs;wkNFNcv*PCv}fw}h|8{F z!7Xg9i!yx-MFbac=Vl)IT2bA~Ax<45;qRYZOgSkC@w@vzvfED$-2YaNqMz90E2egy zt+az;8W=}m8f}w~T8FihqHoQtV~gu_JQ+o?CWr$FUwt@Ok03>8Tp+&j1b$+Bv!Xv+3AOc|bnnYGiBe~7qa9#-me`Zs?6#xJL literal 0 HcmV?d00001 diff --git a/update.php b/update.php new file mode 100644 index 0000000..414a0d6 --- /dev/null +++ b/update.php @@ -0,0 +1,575 @@ +#!/usr/bin/env php + [ + 'bin/update.sh' => 'a1cc96a5ecc3db3074563877dec07f0ebf8689e90e0e9aece838071df4793e26', + 'bin/update.php' => 'b13d3e925b59589f4d599d6deebb1fb27fa81ad0b98e5d0c67199279c3de9635', + ], + '1.4.1' => [ + 'public/assets/vendor/codemirror/xml.min.js' => 'c0c38a5cf20549c4e20d90428edd830cbbf6a631245a1ac2fb8e88676d4c0b7a', + ], + ]; + private const LEGACY_BASES = ['1.3.0' => 'd5bedabaa1d0187e29060c41fb030e9587a8692f']; + private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|updatescript_map\.json|composer\.(?:json|lock)|start\.php)$/D'; + private const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024; + private const MAX_EXPANDED_BYTES = 256 * 1024 * 1024; + + public function __construct(private readonly string $root) + { + } + + public function execute(?string $target, ?string $backup): void + { + $current = $this->version(); + $map = self::remoteJson(self::MAP_PATH, 65536, 10000); + $rule = is_object($map) ? ($map->{self::UPDATESCRIPT_VERSION} ?? null) : null; + if (!is_object($rule)) { + throw new RuntimeException('当前更新器未列入兼容表,请下载新版 update.php。'); + } + $from = self::parseRange($rule->from ?? null); + $to = self::parseRange($rule->to ?? null); + $releases = self::releases(); + $latest = array_key_first($releases); + $latestVersion = $latest === null ? null : substr($latest, 1); + if (!self::inRange($current, $from, $latestVersion)) { + throw new RuntimeException("当前站点 v$current 超出此更新器的起始版本范围 {$rule->from}。"); + } + $eligible = array_filter($releases, static function (string $tag) use ($current, $to, $latestVersion): bool { + $version = substr($tag, 1); + + return version_compare($version, $current, '>') && self::inRange($version, $to, $latestVersion); + }, ARRAY_FILTER_USE_KEY); + printf("更新器 v%s,当前站点 v%s\n兼容起始版本 %s,目标范围 %s\n", + self::UPDATESCRIPT_VERSION, $current, $rule->from, $rule->to); + + if ($target === 'check') { + if ($latest !== null) { + printf("上游最新正式发布 %s\n", $latest); + } + echo $eligible === [] ? "暂无可升级的正式发布版本。\n" + : '可升级至 ' . implode('、', array_keys($eligible)) . PHP_EOL; + return; + } + if ($target === null) { + $target = self::chooseRelease($eligible); + if ($target === null) { + return; + } + } elseif ($target === 'v' . $current) { + printf("当前已安装 %s。\n", $target); + return; + } + + if (!isset($eligible[$target])) { + throw new RuntimeException("无法从 v$current 升级到 {$target}。可选版本为 " + . ($eligible === [] ? '无。' : implode('、', array_keys($eligible)) . '。')); + } + $this->update($current, $target, $backup); + } + + private static function parseRange(mixed $value): array + { + if (!is_string($value) || !preg_match('/^v(\d+\.\d+\.\d+)-(?:v(\d+\.\d+\.\d+)|latest)$/D', $value, $parts) + || (isset($parts[2]) && version_compare($parts[1], $parts[2], '>'))) { + throw new RuntimeException('更新器兼容表中的版本范围无效。'); + } + + return [$parts[1], $parts[2] ?? null]; + } + + private static function inRange(string $version, array $range, ?string $latest): bool + { + [$minimum, $maximum] = $range; + $maximum ??= $latest; + + return version_compare($version, $minimum, '>=') && ($maximum === null || version_compare($version, $maximum, '<=')); + } + + private static function releases(): array + { + $result = []; + $deadline = hrtime(true) + 10_000_000_000; + for ($page = 1; ; $page++) { + $timeout = (int) (($deadline - hrtime(true)) / 1_000_000); + if ($timeout <= 0) { + throw new RuntimeException('查询 LaySite 发布列表超时。'); + } + $entries = self::remoteJson(self::RELEASES_PATH . "?limit=50&page=$page", 1024 * 1024, $timeout); + if (!is_array($entries)) { + throw new RuntimeException('LaySite 发布列表格式无效。'); + } + foreach ($entries as $entry) { + if (!is_string($entry->tag_name ?? null) || !is_bool($entry->draft ?? null) || !is_bool($entry->prerelease ?? null)) { + throw new RuntimeException('LaySite 发布列表格式无效。'); + } + if (!$entry->draft && !$entry->prerelease && preg_match(self::TAG, $entry->tag_name)) { + $result[$entry->tag_name] = $entry; + } + } + if (count($entries) < 50) { + break; + } + } + uksort($result, static fn (string $a, string $b): int => version_compare(substr($b, 1), substr($a, 1))); + + return $result; + } + + private static function remoteJson(string $path, int $limit, int $timeout): mixed + { + $stream = fopen('php://temp', 'w+b'); + if ($stream === false) { + throw new RuntimeException('无法创建更新查询缓冲区。'); + } + try { + self::download($path, $stream, $limit, $timeout); + rewind($stream); + + return json_decode((string) stream_get_contents($stream), flags: JSON_THROW_ON_ERROR); + } finally { + fclose($stream); + } + } + + private static function chooseRelease(array $releases): ?string + { + if ($releases === []) { + echo "暂无可升级的正式发布版本。\n"; + return null; + } + $tags = array_keys($releases); + foreach ($tags as $index => $tag) { + $release = $releases[$tag]; + $title = self::terminalText($release->name ?? ''); + $details = self::terminalText($release->body ?? ''); + printf("\n%d. %s%s\n", $index + 1, $tag, $title === '' || $title === $tag ? '' : ' · ' . str_replace("\n", ' ', $title)); + echo ' ' . str_replace("\n", "\n ", $details === '' ? '暂无发布说明。' : $details) . PHP_EOL; + } + + while (true) { + echo "\n请选择版本编号或输入标签,回车取消\n> "; + $selection = trim((string) fgets(STDIN)); + if ($selection === '' || strtolower($selection) === 'q') { + return null; + } + if (isset($releases[$selection])) { + return $selection; + } + if (ctype_digit($selection) && isset($tags[(int) $selection - 1])) { + return $tags[(int) $selection - 1]; + } + echo "请输入列表中的编号或版本。\n"; + } + } + + private static function terminalText(mixed $value): string + { + if (!is_string($value)) { + return ''; + } + + return trim(preg_replace('/[^\P{C}\n\t]/u', '', str_replace(["\r\n", "\r"], "\n", $value)) ?? ''); + } + + private function update(string $current, string $target, ?string $backup): void + { + $runtime = $this->root . '/runtime'; + self::makeDirectory($runtime); + $lock = fopen($runtime . '/release-update.lock', 'c'); + if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) { + throw new RuntimeException('无法取得 LaySite 更新锁。'); + } + $pending = $runtime . '/release-update-pending'; + $work = $this->root . '/.laysite-update-' . bin2hex(random_bytes(8)); + try { + if (file_exists($pending) || is_link($pending)) { + throw new RuntimeException('上次更新尚未完成。请保留该次更新的备份,并检查 ' . trim((string) file_get_contents($pending))); + } + if ($this->version() !== $current) { + throw new RuntimeException('站点版本已经变更,请重新选择更新目标。'); + } + $backup = $this->backupPath($backup, $current, $target); + + if (!mkdir($work, 0700)) { + throw new RuntimeException('无法建立更新暂存目录。'); + } + $base = $this->archive(self::LEGACY_BASES[$current] ?? ('v' . $current), $current, $work . '/base.zip'); + // Accept the VERSION file already identified above, including the old release numbering. + $base['VERSION']['hash'] = hash_file('sha256', $this->root . '/VERSION'); + $release = $this->archive($target, substr($target, 1), $work . '/release.zip'); + $plan = $this->plan($base, $release, $backup); + $php = getenv('LAYSITE_PHP') ?: PHP_BINARY; + self::run([$php, 'bin/backup.php', 'export', $backup], $this->root); + $vendor = $this->stageDependencies($work, $plan, $release); + if ($plan !== $this->plan($base, $release, $backup)) { + throw new RuntimeException('准备更新期间,站点文件发生了变化。'); + } + $this->apply($work, $pending, $plan, $release, $vendor, $php); + printf("已更新至 %s,可使用原站点配置启动 Webman。\n", $target); + } finally { + if (is_dir($work) && !is_file($pending)) { + self::removeDirectory($work); + } + fclose($lock); + } + } + + private function backupPath(?string $path, string $current, string $target): string + { + if ($path === null) { + $directory = $this->root . '/storage/backups'; + self::makeDirectory($directory); + $path = sprintf('%s/laysite-v%s-%s-%s-%s.tar', $directory, $current, $target, gmdate('Ymd-His'), bin2hex(random_bytes(4))); + } elseif (!str_starts_with($path, '/')) { + $path = $this->root . '/' . $path; + } + $directory = realpath(dirname($path)); + if ($directory === false || !str_ends_with($path, '.tar') || file_exists($path) || is_link($path)) { + throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。'); + } + $path = $directory . '/' . basename($path); + printf("站点备份将写入 %s\n", $path); + + return $path; + } + + private function version(): string + { + $version = trim((string) @file_get_contents($this->root . '/VERSION')); + if (!preg_match('/^\d+\.\d+\.\d+$/D', $version)) { + throw new RuntimeException('请从已安装 LaySite 的目录运行更新器。'); + } + + if ($version === '1.4.0') { + foreach (self::LEGACY_VERSIONS as $tag => $files) { + foreach ($files as $path => $hash) { + if (@hash_file('sha256', $this->root . '/' . $path) === $hash) { + return $tag; + } + } + } + } + + return $version; + } + + private static function download(string $path, $stream, int $limit, int $timeout): void + { + $curl = curl_init(self::HOST . $path); + $bytes = 0; + curl_setopt_array($curl, [ + CURLOPT_USERAGENT => 'LaySite release updater', + CURLOPT_CONNECTTIMEOUT_MS => min(3500, $timeout), + CURLOPT_TIMEOUT_MS => $timeout, + CURLOPT_FOLLOWLOCATION => false, + CURLOPT_WRITEFUNCTION => static function (CurlHandle $curl, string $chunk) use ($stream, $limit, &$bytes): int { + $bytes += strlen($chunk); + + return $bytes > $limit ? 0 : (int) fwrite($stream, $chunk); + }, + ]); + if (curl_exec($curl) === false) { + throw new RuntimeException('下载 LaySite 发布文件失败。' . ($bytes > $limit ? '文件超过大小限制。' : curl_error($curl))); + } + $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE); + if ($status !== 200) { + throw new RuntimeException("无法读取 LaySite 发布文件 {$path}(HTTP $status)。"); + } + } + + private function archive(string $ref, string $version, string $path): array + { + $stream = fopen($path, 'xb'); + if ($stream === false) { + throw new RuntimeException('无法写入发布 ZIP。'); + } + try { + self::download(self::PROJECT . "/archive/$ref.zip", $stream, self::MAX_ARCHIVE_BYTES, 60_000); + } finally { + fclose($stream); + } + $archive = new PharData($path); + $files = []; + $size = 0; + $prefix = 'phar://' . $path . '/laysite/'; + foreach (new RecursiveIteratorIterator($archive) as $entry) { + $uri = $entry->getPathname(); + if (!str_starts_with($uri, $prefix)) { + throw new RuntimeException('发布 ZIP 的目录结构无效。'); + } + $name = substr($uri, strlen($prefix)); + if ($entry->isLink() || !$entry->isFile() || str_contains($name, '\\') + || preg_match('~(?:^|/)\.{0,2}(?:/|$)|[\x00-\x1f\x7f]~', $name)) { + throw new RuntimeException('发布 ZIP 包含无效的文件路径。'); + } + $size += $entry->getSize(); + if ($size > self::MAX_EXPANDED_BYTES) { + throw new RuntimeException('发布 ZIP 解压后的大小超过限制。'); + } + if (!preg_match(self::MANAGED, $name)) { + continue; + } + $hash = hash_file('sha256', $uri); + if ($hash === false || isset($files[$name])) { + throw new RuntimeException('发布 ZIP 文件损坏。'); + } + $files[$name] = ['uri' => $uri, 'hash' => $hash, 'mode' => $entry->getPerms() & 0777]; + } + foreach (['VERSION', 'start.php', 'bin/install.php', 'composer.json', 'composer.lock', 'resources/schema.sql'] as $required) { + if (!isset($files[$required])) { + throw new RuntimeException('发布 ZIP 缺少 ' . $required); + } + } + $embedded = trim((string) file_get_contents($files['VERSION']['uri'])); + if ($embedded !== $version) { + if ($embedded !== '1.4.0' || !isset(self::LEGACY_VERSIONS[$version])) { + throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。'); + } + $canonical = $path . '.version'; + $contents = $version . "\n"; + if (file_put_contents($canonical, $contents) !== strlen($contents)) { + throw new RuntimeException('无法暂存发布版本号。'); + } + $files['VERSION'] = ['uri' => $canonical, 'hash' => hash('sha256', $contents), 'mode' => 0644]; + } + + return $files; + } + + private function plan(array $base, array $release, string $backup): array + { + clearstatcache(); + require_once $this->root . '/vendor/autoload.php'; + $database = App\Content\Database::path(); + $media = App\Content\Media::directory(); + $protected = array_unique([ + $database, realpath($database) ?: $database, $media, realpath($media) ?: $media, $backup, + ]); + $plan = []; + $conflicts = []; + foreach (array_keys($base + $release) as $name) { + $old = $base[$name]['hash'] ?? null; + $next = $release[$name]['hash'] ?? null; + if ($old === $next) { + continue; + } + try { + $path = $this->managedPath($name); + foreach ($protected as $reserved) { + if ($path === $reserved || str_starts_with($path, rtrim($reserved, '/') . '/') + || str_starts_with($reserved, $path . '/') || in_array($path, [$database . '.key', $database . '-wal', $database . '-shm'], true)) { + throw new RuntimeException('更新路径与站点数据重叠。'); + } + } + $local = is_file($path) ? hash_file('sha256', $path) : null; + if ($local === $next) { + continue; + } + if ($local !== $old) { + $conflicts[] = $name; + continue; + } + $plan[] = $name; + } catch (RuntimeException) { + $conflicts[] = $name; + } + } + if ($conflicts !== []) { + sort($conflicts); + throw new RuntimeException("以下路径与站点定制或数据冲突,尚未替换任何文件:\n" . implode("\n", $conflicts)); + } + if (array_intersect(['composer.json', 'composer.lock'], $plan)) { + $vendor = $this->root . '/vendor'; + foreach ($protected as $reserved) { + if ($reserved === $vendor || str_starts_with($reserved, $vendor . '/')) { + throw new RuntimeException('站点数据或备份路径位于 vendor 目录,请先调整该路径。'); + } + } + } + + return $plan; + } + + private function managedPath(string $name): string + { + $path = $this->root; + $parts = explode('/', $name); + $leaf = array_pop($parts); + foreach ($parts as $part) { + $path .= '/' . $part; + if (is_link($path) || (file_exists($path) && !is_dir($path))) { + throw new RuntimeException('更新路径不可写:' . $name); + } + } + $path .= '/' . $leaf; + if (is_link($path) || (file_exists($path) && !is_file($path))) { + throw new RuntimeException('更新路径不可写:' . $name); + } + + return $path; + } + + private function stageDependencies(string $work, array $plan, array $release): ?string + { + if (!array_intersect(['composer.json', 'composer.lock'], $plan)) { + return null; + } + $dependencies = $work . '/dependencies'; + self::makeDirectory($dependencies); + foreach (['composer.json', 'composer.lock'] as $name) { + $source = in_array($name, $plan, true) ? $release[$name]['uri'] : $this->root . '/' . $name; + if (!copy($source, $dependencies . '/' . $name)) { + throw new RuntimeException('无法准备 Composer 依赖。'); + } + } + $vendor = $dependencies . '/vendor'; + self::run([ + getenv('LAYSITE_COMPOSER') ?: 'composer', 'install', '--no-dev', '--prefer-dist', + '--no-interaction', '--no-scripts', '--no-plugins', + ], $dependencies, array_replace(getenv(), ['COMPOSER' => 'composer.json', 'COMPOSER_VENDOR_DIR' => $vendor])); + if (!is_file($vendor . '/autoload.php')) { + throw new RuntimeException('Composer 没有在暂存目录生成依赖。'); + } + + return $vendor; + } + + private function apply(string $work, string $pending, array $plan, array $release, ?string $vendor, string $php): void + { + $staged = []; + foreach ($plan as $name) { + $staged[$name] = null; + if (isset($release[$name])) { + $file = $work . '/files/' . $name; + self::makeDirectory(dirname($file)); + $mode = $release[$name]['mode'] & 0755; + if ($name === 'bin/update.sh') { + $mode |= 0100; + } + if (!copy($release[$name]['uri'], $file) || !chmod($file, $mode ?: 0644)) { + throw new RuntimeException('无法暂存文件 ' . $name); + } + $staged[$name] = $file; + } + } + if ($vendor !== null) { + if (is_link($this->root . '/vendor') || !is_dir($this->root . '/vendor')) { + throw new RuntimeException('站点的 vendor 目录需要手动更新。'); + } + $staged['vendor'] = $vendor; + } + $marker = fopen($pending, 'x'); + if ($marker === false) { + throw new RuntimeException('无法写入更新记录。'); + } + $record = $work . PHP_EOL; + $written = fwrite($marker, $record); + fclose($marker); + if ($written !== strlen($record)) { + unlink($pending); + throw new RuntimeException('无法写入完整的更新记录。'); + } + $applied = []; + try { + foreach ($staged as $name => $source) { + $destination = $this->root . '/' . $name; + $previous = $work . '/previous/' . $name; + if (file_exists($destination)) { + self::makeDirectory(dirname($previous)); + self::move($destination, $previous); + } + $applied[] = $name; + if ($source !== null) { + self::makeDirectory(dirname($destination)); + self::move($source, $destination); + } + } + self::run([$php, 'bin/install.php'], $this->root); + } catch (Throwable $error) { + try { + foreach (array_reverse($applied) as $name) { + $path = $this->root . '/' . $name; + if (file_exists($path)) { + $discard = $work . '/discard/' . $name; + self::makeDirectory(dirname($discard)); + self::move($path, $discard); + } + $previous = $work . '/previous/' . $name; + if (file_exists($previous)) { + self::move($previous, $path); + } + } + unlink($pending); + } catch (Throwable $rollback) { + throw new RuntimeException('更新回退未完成。原文件保存在 ' . $work . '。' . $rollback->getMessage(), previous: $error); + } + throw new RuntimeException('更新失败,原程序文件已恢复。' . $error->getMessage(), previous: $error); + } + unlink($pending); + } + + private static function move(string $from, string $to): void + { + if (!rename($from, $to)) { + throw new RuntimeException('无法移动 ' . $from . ' 到 ' . $to); + } + } + + private static function run(array $command, string $directory, ?array $environment = null): void + { + $process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes, $directory, $environment); + if (!is_resource($process) || proc_close($process) !== 0) { + throw new RuntimeException('命令执行失败:' . implode(' ', array_slice($command, 0, 2))); + } + } + + private static function makeDirectory(string $path): void + { + if (!is_dir($path) && !mkdir($path, 0755, true) && !is_dir($path)) { + throw new RuntimeException('无法建立目录 ' . $path); + } + } + + private static function removeDirectory(string $path): void + { + $entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST); + foreach ($entries as $entry) { + if ($entry->isDir() && !$entry->isLink()) { + rmdir($entry->getPathname()); + } else { + unlink($entry->getPathname()); + } + } + rmdir($path); + } +} + +$target = $argv[1] ?? null; +$backup = $argv[2] ?? null; +if ($argc > 3 || ($target === 'check' && $backup !== null) + || ($target !== null && $target !== 'check' && !preg_match('/^v\d+\.\d+\.\d+$/D', $target))) { + fwrite(STDERR, "用法:php bin/update.php [check | vX.Y.Z [备份路径.tar]]\n"); + exit(2); +} + +umask(0027); +try { + (new LaySiteUpdater(getcwd()))->execute($target, $backup); +} catch (Throwable $error) { + fwrite(STDERR, $error->getMessage() . PHP_EOL); + exit(1); +} diff --git a/vendor/autoload.php b/vendor/autoload.php new file mode 100644 index 0000000..537fee6 --- /dev/null +++ b/vendor/autoload.php @@ -0,0 +1,25 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var string|null */ + private $vendorDir; + + // PSR-4 + /** + * @var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var list + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * List of PSR-0 prefixes + * + * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) + * + * @var array>> + */ + private $prefixesPsr0 = array(); + /** + * @var list + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var array + */ + private $missingClasses = array(); + + /** @var string|null */ + private $apcuPrefix; + + /** + * @var array + */ + private static $registeredLoaders = array(); + + /** + * @param string|null $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return array> + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return list + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return list + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return array Array of classname => path + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders keyed by their corresponding vendor directories. + * + * @return array + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..51e734a --- /dev/null +++ b/vendor/composer/InstalledVersions.php @@ -0,0 +1,359 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..e7b5f7b --- /dev/null +++ b/vendor/composer/autoload_classmap.php @@ -0,0 +1,99 @@ + $vendorDir . '/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php', + 'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'Nette\\ArgumentOutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\DeprecatedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\DirectoryNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\FileNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\HtmlStringable' => $vendorDir . '/nette/utils/src/HtmlStringable.php', + 'Nette\\IOException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\InvalidArgumentException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\InvalidStateException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\Iterators\\CachingIterator' => $vendorDir . '/nette/utils/src/Iterators/CachingIterator.php', + 'Nette\\Iterators\\Mapper' => $vendorDir . '/nette/utils/src/Iterators/Mapper.php', + 'Nette\\Localization\\ITranslator' => $vendorDir . '/nette/utils/src/compatibility.php', + 'Nette\\Localization\\Translator' => $vendorDir . '/nette/utils/src/Translator.php', + 'Nette\\MemberAccessException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\NotImplementedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\NotSupportedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\OutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\Schema\\Context' => $vendorDir . '/nette/schema/src/Schema/Context.php', + 'Nette\\Schema\\DynamicParameter' => $vendorDir . '/nette/schema/src/Schema/DynamicParameter.php', + 'Nette\\Schema\\Elements\\AnyOf' => $vendorDir . '/nette/schema/src/Schema/Elements/AnyOf.php', + 'Nette\\Schema\\Elements\\ArrayType' => $vendorDir . '/nette/schema/src/Schema/Elements/ArrayType.php', + 'Nette\\Schema\\Elements\\Base' => $vendorDir . '/nette/schema/src/Schema/Elements/Base.php', + 'Nette\\Schema\\Elements\\EnumType' => $vendorDir . '/nette/schema/src/Schema/Elements/EnumType.php', + 'Nette\\Schema\\Elements\\NumberType' => $vendorDir . '/nette/schema/src/Schema/Elements/NumberType.php', + 'Nette\\Schema\\Elements\\StringType' => $vendorDir . '/nette/schema/src/Schema/Elements/StringType.php', + 'Nette\\Schema\\Elements\\Structure' => $vendorDir . '/nette/schema/src/Schema/Elements/Structure.php', + 'Nette\\Schema\\Elements\\TupleType' => $vendorDir . '/nette/schema/src/Schema/Elements/TupleType.php', + 'Nette\\Schema\\Elements\\Type' => $vendorDir . '/nette/schema/src/Schema/Elements/Type.php', + 'Nette\\Schema\\Expect' => $vendorDir . '/nette/schema/src/Schema/Expect.php', + 'Nette\\Schema\\Helpers' => $vendorDir . '/nette/schema/src/Schema/Helpers.php', + 'Nette\\Schema\\JsonSchema' => $vendorDir . '/nette/schema/src/Schema/JsonSchema.php', + 'Nette\\Schema\\Kind' => $vendorDir . '/nette/schema/src/Schema/enums.php', + 'Nette\\Schema\\MergeMode' => $vendorDir . '/nette/schema/src/Schema/enums.php', + 'Nette\\Schema\\Message' => $vendorDir . '/nette/schema/src/Schema/Message.php', + 'Nette\\Schema\\Processor' => $vendorDir . '/nette/schema/src/Schema/Processor.php', + 'Nette\\Schema\\Schema' => $vendorDir . '/nette/schema/src/Schema/Schema.php', + 'Nette\\Schema\\TypeExpression' => $vendorDir . '/nette/schema/src/Schema/TypeExpression.php', + 'Nette\\Schema\\ValidationException' => $vendorDir . '/nette/schema/src/Schema/ValidationException.php', + 'Nette\\ShouldNotHappenException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\SmartObject' => $vendorDir . '/nette/utils/src/SmartObject.php', + 'Nette\\StaticClass' => $vendorDir . '/nette/utils/src/StaticClass.php', + 'Nette\\UnexpectedValueException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'Nette\\Utils\\ArrayHash' => $vendorDir . '/nette/utils/src/Utils/ArrayHash.php', + 'Nette\\Utils\\ArrayList' => $vendorDir . '/nette/utils/src/Utils/ArrayList.php', + 'Nette\\Utils\\Arrays' => $vendorDir . '/nette/utils/src/Utils/Arrays.php', + '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', + 'Nette\\Utils\\Floats' => $vendorDir . '/nette/utils/src/Utils/Floats.php', + 'Nette\\Utils\\Helpers' => $vendorDir . '/nette/utils/src/Utils/Helpers.php', + 'Nette\\Utils\\Html' => $vendorDir . '/nette/utils/src/Utils/Html.php', + 'Nette\\Utils\\IHtmlString' => $vendorDir . '/nette/utils/src/compatibility.php', + 'Nette\\Utils\\Image' => $vendorDir . '/nette/utils/src/Utils/Image.php', + 'Nette\\Utils\\ImageColor' => $vendorDir . '/nette/utils/src/Utils/ImageColor.php', + 'Nette\\Utils\\ImageException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\ImageType' => $vendorDir . '/nette/utils/src/Utils/ImageType.php', + 'Nette\\Utils\\Iterables' => $vendorDir . '/nette/utils/src/Utils/Iterables.php', + 'Nette\\Utils\\Json' => $vendorDir . '/nette/utils/src/Utils/Json.php', + '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', + 'Nette\\Utils\\RegexpException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Strings' => $vendorDir . '/nette/utils/src/Utils/Strings.php', + 'Nette\\Utils\\Type' => $vendorDir . '/nette/utils/src/Utils/Type.php', + 'Nette\\Utils\\UnknownImageFileException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Validators' => $vendorDir . '/nette/utils/src/Utils/Validators.php', + 'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'Random\\BrokenRandomEngineError' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php', + 'Random\\CryptoSafeEngine' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php', + 'Random\\Engine' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/Engine.php', + 'Random\\Engine\\Secure' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php', + 'Random\\RandomError' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php', + 'Random\\RandomException' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php', + 'SensitiveParameter' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php', + 'SensitiveParameterValue' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php', + 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', +); diff --git a/vendor/composer/autoload_files.php b/vendor/composer/autoload_files.php new file mode 100644 index 0000000..1b18837 --- /dev/null +++ b/vendor/composer/autoload_files.php @@ -0,0 +1,16 @@ + $vendorDir . '/symfony/deprecation-contracts/function.php', + 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', + '5897ea0ac4cccf14d323035e65887801' => $vendorDir . '/symfony/polyfill-php82/bootstrap.php', + '253c157292f75eb38082b5acb06f3f01' => $vendorDir . '/nikic/fast-route/src/functions.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', + 'd2136ff22b54ac75cd96a40e0022218e' => $vendorDir . '/workerman/webman-framework/src/support/helpers.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..15a2ff3 --- /dev/null +++ b/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/workerman/webman-framework/src/support'), + 'Workerman\\Coroutine\\' => array($vendorDir . '/workerman/coroutine/src'), + 'Workerman\\' => array($vendorDir . '/workerman/coroutine/src', $vendorDir . '/workerman/workerman/src'), + 'Webman\\' => array($vendorDir . '/workerman/webman-framework/src'), + 'Symfony\\Polyfill\\Php82\\' => array($vendorDir . '/symfony/polyfill-php82'), + 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), + 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), + 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), + 'Support\\View\\' => array($vendorDir . '/workerman/webman-framework/src/support/view'), + 'Support\\Exception\\' => array($vendorDir . '/workerman/webman-framework/src/support/exception'), + 'Support\\Bootstrap\\' => array($vendorDir . '/workerman/webman-framework/src/support/bootstrap'), + 'Support\\' => array($vendorDir . '/workerman/webman-framework/src/support'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'), + 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), + 'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'), + 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'), + 'Nette\\' => array($vendorDir . '/nette/schema/src', $vendorDir . '/nette/utils/src'), + 'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'), + 'League\\OAuth2\\Client\\' => array($vendorDir . '/league/oauth2-client/src'), + 'League\\Config\\' => array($vendorDir . '/league/config/src'), + 'League\\CommonMark\\' => array($vendorDir . '/league/commonmark/src'), + 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), + 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), + 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), + 'GrahamCampbell\\ResultType\\' => array($vendorDir . '/graham-campbell/result-type/src'), + 'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'), + 'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'), + 'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'), + 'Dflydev\\DotAccessData\\' => array($vendorDir . '/dflydev/dot-access-data/src'), + 'App\\' => array($baseDir . '/app'), +); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php new file mode 100644 index 0000000..301b0c6 --- /dev/null +++ b/vendor/composer/autoload_real.php @@ -0,0 +1,50 @@ +register(true); + + $filesToLoad = \Composer\Autoload\ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$files; + $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + + require $file; + } + }, null, null); + foreach ($filesToLoad as $fileIdentifier => $file) { + $requireFile($fileIdentifier, $file); + } + + return $loader; + } +} diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 0000000..b476d8c --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,323 @@ + __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', + '5897ea0ac4cccf14d323035e65887801' => __DIR__ . '/..' . '/symfony/polyfill-php82/bootstrap.php', + '253c157292f75eb38082b5acb06f3f01' => __DIR__ . '/..' . '/nikic/fast-route/src/functions.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', + 'd2136ff22b54ac75cd96a40e0022218e' => __DIR__ . '/..' . '/workerman/webman-framework/src/support/helpers.php', + ); + + public static $prefixLengthsPsr4 = array ( + 's' => + array ( + 'support\\' => 8, + ), + 'W' => + array ( + 'Workerman\\Coroutine\\' => 20, + 'Workerman\\' => 10, + 'Webman\\' => 7, + ), + 'S' => + array ( + 'Symfony\\Polyfill\\Php82\\' => 23, + 'Symfony\\Polyfill\\Php80\\' => 23, + 'Symfony\\Polyfill\\Mbstring\\' => 26, + 'Symfony\\Polyfill\\Ctype\\' => 23, + 'Support\\View\\' => 13, + 'Support\\Exception\\' => 18, + 'Support\\Bootstrap\\' => 18, + 'Support\\' => 8, + ), + 'P' => + array ( + 'Psr\\Log\\' => 8, + 'Psr\\Http\\Message\\' => 17, + 'Psr\\Http\\Client\\' => 16, + 'Psr\\EventDispatcher\\' => 20, + 'Psr\\Container\\' => 14, + 'PhpOption\\' => 10, + ), + 'N' => + array ( + 'Nette\\' => 6, + ), + 'M' => + array ( + 'Monolog\\' => 8, + ), + 'L' => + array ( + 'League\\OAuth2\\Client\\' => 21, + 'League\\Config\\' => 14, + 'League\\CommonMark\\' => 18, + ), + 'G' => + array ( + 'GuzzleHttp\\Psr7\\' => 16, + 'GuzzleHttp\\Promise\\' => 19, + 'GuzzleHttp\\' => 11, + 'GrahamCampbell\\ResultType\\' => 26, + ), + 'F' => + array ( + 'Firebase\\JWT\\' => 13, + 'FastRoute\\' => 10, + ), + 'D' => + array ( + 'Dotenv\\' => 7, + 'Dflydev\\DotAccessData\\' => 22, + ), + 'A' => + array ( + 'App\\' => 4, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'support\\' => + array ( + 0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support', + ), + 'Workerman\\Coroutine\\' => + array ( + 0 => __DIR__ . '/..' . '/workerman/coroutine/src', + ), + 'Workerman\\' => + array ( + 0 => __DIR__ . '/..' . '/workerman/coroutine/src', + 1 => __DIR__ . '/..' . '/workerman/workerman/src', + ), + 'Webman\\' => + array ( + 0 => __DIR__ . '/..' . '/workerman/webman-framework/src', + ), + 'Symfony\\Polyfill\\Php82\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php82', + ), + 'Symfony\\Polyfill\\Php80\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', + ), + 'Symfony\\Polyfill\\Mbstring\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', + ), + 'Symfony\\Polyfill\\Ctype\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', + ), + 'Support\\View\\' => + array ( + 0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/view', + ), + 'Support\\Exception\\' => + array ( + 0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/exception', + ), + 'Support\\Bootstrap\\' => + array ( + 0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/bootstrap', + ), + 'Support\\' => + array ( + 0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support', + ), + 'Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/src', + ), + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-message/src', + 1 => __DIR__ . '/..' . '/psr/http-factory/src', + ), + 'Psr\\Http\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-client/src', + ), + 'Psr\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/event-dispatcher/src', + ), + 'Psr\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/container/src', + ), + 'PhpOption\\' => + array ( + 0 => __DIR__ . '/..' . '/phpoption/phpoption/src/PhpOption', + ), + 'Nette\\' => + array ( + 0 => __DIR__ . '/..' . '/nette/schema/src', + 1 => __DIR__ . '/..' . '/nette/utils/src', + ), + 'Monolog\\' => + array ( + 0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog', + ), + 'League\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/league/oauth2-client/src', + ), + 'League\\Config\\' => + array ( + 0 => __DIR__ . '/..' . '/league/config/src', + ), + 'League\\CommonMark\\' => + array ( + 0 => __DIR__ . '/..' . '/league/commonmark/src', + ), + 'GuzzleHttp\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + ), + 'GuzzleHttp\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', + ), + 'GuzzleHttp\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', + ), + 'GrahamCampbell\\ResultType\\' => + array ( + 0 => __DIR__ . '/..' . '/graham-campbell/result-type/src', + ), + 'Firebase\\JWT\\' => + array ( + 0 => __DIR__ . '/..' . '/firebase/php-jwt/src', + ), + 'FastRoute\\' => + array ( + 0 => __DIR__ . '/..' . '/nikic/fast-route/src', + ), + 'Dotenv\\' => + array ( + 0 => __DIR__ . '/..' . '/vlucas/phpdotenv/src', + ), + 'Dflydev\\DotAccessData\\' => + array ( + 0 => __DIR__ . '/..' . '/dflydev/dot-access-data/src', + ), + 'App\\' => + array ( + 0 => __DIR__ . '/../..' . '/app', + ), + ); + + public static $classMap = array ( + 'AllowDynamicProperties' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php', + 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'Nette\\ArgumentOutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\DeprecatedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\DirectoryNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\FileNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\HtmlStringable' => __DIR__ . '/..' . '/nette/utils/src/HtmlStringable.php', + 'Nette\\IOException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\InvalidArgumentException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\InvalidStateException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\Iterators\\CachingIterator' => __DIR__ . '/..' . '/nette/utils/src/Iterators/CachingIterator.php', + 'Nette\\Iterators\\Mapper' => __DIR__ . '/..' . '/nette/utils/src/Iterators/Mapper.php', + 'Nette\\Localization\\ITranslator' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php', + 'Nette\\Localization\\Translator' => __DIR__ . '/..' . '/nette/utils/src/Translator.php', + 'Nette\\MemberAccessException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\NotImplementedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\NotSupportedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\OutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\Schema\\Context' => __DIR__ . '/..' . '/nette/schema/src/Schema/Context.php', + 'Nette\\Schema\\DynamicParameter' => __DIR__ . '/..' . '/nette/schema/src/Schema/DynamicParameter.php', + 'Nette\\Schema\\Elements\\AnyOf' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/AnyOf.php', + 'Nette\\Schema\\Elements\\ArrayType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/ArrayType.php', + 'Nette\\Schema\\Elements\\Base' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Base.php', + 'Nette\\Schema\\Elements\\EnumType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/EnumType.php', + 'Nette\\Schema\\Elements\\NumberType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/NumberType.php', + 'Nette\\Schema\\Elements\\StringType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/StringType.php', + 'Nette\\Schema\\Elements\\Structure' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Structure.php', + 'Nette\\Schema\\Elements\\TupleType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/TupleType.php', + 'Nette\\Schema\\Elements\\Type' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Type.php', + 'Nette\\Schema\\Expect' => __DIR__ . '/..' . '/nette/schema/src/Schema/Expect.php', + 'Nette\\Schema\\Helpers' => __DIR__ . '/..' . '/nette/schema/src/Schema/Helpers.php', + 'Nette\\Schema\\JsonSchema' => __DIR__ . '/..' . '/nette/schema/src/Schema/JsonSchema.php', + 'Nette\\Schema\\Kind' => __DIR__ . '/..' . '/nette/schema/src/Schema/enums.php', + 'Nette\\Schema\\MergeMode' => __DIR__ . '/..' . '/nette/schema/src/Schema/enums.php', + 'Nette\\Schema\\Message' => __DIR__ . '/..' . '/nette/schema/src/Schema/Message.php', + 'Nette\\Schema\\Processor' => __DIR__ . '/..' . '/nette/schema/src/Schema/Processor.php', + 'Nette\\Schema\\Schema' => __DIR__ . '/..' . '/nette/schema/src/Schema/Schema.php', + 'Nette\\Schema\\TypeExpression' => __DIR__ . '/..' . '/nette/schema/src/Schema/TypeExpression.php', + 'Nette\\Schema\\ValidationException' => __DIR__ . '/..' . '/nette/schema/src/Schema/ValidationException.php', + 'Nette\\ShouldNotHappenException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\SmartObject' => __DIR__ . '/..' . '/nette/utils/src/SmartObject.php', + 'Nette\\StaticClass' => __DIR__ . '/..' . '/nette/utils/src/StaticClass.php', + 'Nette\\UnexpectedValueException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'Nette\\Utils\\ArrayHash' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayHash.php', + 'Nette\\Utils\\ArrayList' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayList.php', + 'Nette\\Utils\\Arrays' => __DIR__ . '/..' . '/nette/utils/src/Utils/Arrays.php', + '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', + 'Nette\\Utils\\Floats' => __DIR__ . '/..' . '/nette/utils/src/Utils/Floats.php', + 'Nette\\Utils\\Helpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/Helpers.php', + 'Nette\\Utils\\Html' => __DIR__ . '/..' . '/nette/utils/src/Utils/Html.php', + 'Nette\\Utils\\IHtmlString' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php', + 'Nette\\Utils\\Image' => __DIR__ . '/..' . '/nette/utils/src/Utils/Image.php', + 'Nette\\Utils\\ImageColor' => __DIR__ . '/..' . '/nette/utils/src/Utils/ImageColor.php', + 'Nette\\Utils\\ImageException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\ImageType' => __DIR__ . '/..' . '/nette/utils/src/Utils/ImageType.php', + 'Nette\\Utils\\Iterables' => __DIR__ . '/..' . '/nette/utils/src/Utils/Iterables.php', + 'Nette\\Utils\\Json' => __DIR__ . '/..' . '/nette/utils/src/Utils/Json.php', + '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', + 'Nette\\Utils\\RegexpException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Strings' => __DIR__ . '/..' . '/nette/utils/src/Utils/Strings.php', + 'Nette\\Utils\\Type' => __DIR__ . '/..' . '/nette/utils/src/Utils/Type.php', + 'Nette\\Utils\\UnknownImageFileException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'Nette\\Utils\\Validators' => __DIR__ . '/..' . '/nette/utils/src/Utils/Validators.php', + 'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'Random\\BrokenRandomEngineError' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php', + 'Random\\CryptoSafeEngine' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php', + 'Random\\Engine' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/Engine.php', + 'Random\\Engine\\Secure' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php', + 'Random\\RandomError' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php', + 'Random\\RandomException' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php', + 'SensitiveParameter' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php', + 'SensitiveParameterValue' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php', + 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json new file mode 100644 index 0000000..de1c9a1 --- /dev/null +++ b/vendor/composer/installed.json @@ -0,0 +1,2266 @@ +{ + "packages": [ + { + "name": "dflydev/dot-access-data", + "version": "v3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/dflydev/dflydev-dot-access-data.git", + "reference": "a23a2bf4f31d3518f3ecb38660c95715dfead60f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dflydev/dflydev-dot-access-data/zipball/a23a2bf4f31d3518f3ecb38660c95715dfead60f", + "reference": "a23a2bf4f31d3518f3ecb38660c95715dfead60f", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.42", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.3", + "scrutinizer/ocular": "1.6.0", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.0.0" + }, + "time": "2024-07-08T12:26:09+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Dflydev\\DotAccessData\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dragonfly Development Inc.", + "email": "info@dflydev.com", + "homepage": "http://dflydev.com" + }, + { + "name": "Beau Simensen", + "email": "beau@dflydev.com", + "homepage": "http://beausimensen.com" + }, + { + "name": "Carlos Frutos", + "email": "carlos@kiwing.it", + "homepage": "https://github.com/cfrutos" + }, + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com" + } + ], + "description": "Given a deep data structure, access data by dot notation.", + "homepage": "https://github.com/dflydev/dflydev-dot-access-data", + "keywords": [ + "access", + "data", + "dot", + "notation" + ], + "support": { + "issues": "https://github.com/dflydev/dflydev-dot-access-data/issues", + "source": "https://github.com/dflydev/dflydev-dot-access-data/tree/v3.0.3" + }, + "install-path": "../dflydev/dot-access-data" + }, + { + "name": "firebase/php-jwt", + "version": "v7.2.2", + "version_normalized": "7.2.2.0", + "source": { + "type": "git", + "url": "https://github.com/googleapis/php-jwt.git", + "reference": "99efeb17d6def8c0295777f2d45b07ff4fdb4e40" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/googleapis/php-jwt/zipball/99efeb17d6def8c0295777f2d45b07ff4fdb4e40", + "reference": "99efeb17d6def8c0295777f2d45b07ff4fdb4e40", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "require-dev": { + "guzzlehttp/guzzle": "^7.4||^8.0", + "phpfastcache/phpfastcache": "^9.2", + "phpseclib/phpseclib": "~3.0", + "phpspec/prophecy-phpunit": "^2.2", + "phpunit/phpunit": "^9.5", + "psr/cache": "^2.0||^3.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0" + }, + "suggest": { + "ext-sodium": "Support EdDSA (Ed25519) signatures", + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present", + "phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures" + }, + "time": "2026-11-17T00:25:19+00:00", + "type": "library", + "extra": { + "component": { + "id": "jwt", + "path": "Jwt", + "entry": "README.md", + "target": "googleapis/php-jwt.git" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/googleapis/php-jwt", + "keywords": [ + "jwt", + "php" + ], + "support": { + "issues": "https://github.com/googleapis/php-jwt/issues", + "source": "https://github.com/googleapis/php-jwt/tree/v7.2.2" + }, + "install-path": "../firebase/php-jwt" + }, + { + "name": "graham-campbell/result-type", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/GrahamCampbell/Result-Type.git", + "reference": "adccca3324eece92ca35463648c12b9e6293c05b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/adccca3324eece92ca35463648c12b9e6293c05b", + "reference": "adccca3324eece92ca35463648c12b9e6293c05b", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.10" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.52 || ^9.6.34 || ^10.5.63 || ^11.5.55 || ^12.5.14" + }, + "time": "2026-08-24T09:06:52+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "GrahamCampbell\\ResultType\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "An Implementation Of The Result Type", + "keywords": [ + "Graham Campbell", + "GrahamCampbell", + "Result Type", + "Result-Type", + "result" + ], + "support": { + "issues": "https://github.com/GrahamCampbell/Result-Type/issues", + "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type", + "type": "tidelift" + } + ], + "install-path": "../graham-campbell/result-type" + }, + { + "name": "guzzlehttp/guzzle", + "version": "8.5.5", + "version_normalized": "8.5.5.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "d1a26e6ce24268e740af501de8748d1c945e6f4b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/d1a26e6ce24268e740af501de8748d1c945e6f4b", + "reference": "d1a26e6ce24268e740af501de8748d1c945e6f4b", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^3.1.1", + "guzzlehttp/psr7": "^3.5.1", + "php": "^7.4 || ^8.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0", + "symfony/polyfill-php80": "^1.25", + "symfony/polyfill-php82": "^1.27" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-curl": "*", + "guzzle/client-integration-tests": "4.0.1", + "guzzlehttp/test-server": "^1.1", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^9.6.34", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "time": "2026-11-21T21:14:02+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/8.5.5" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/guzzle" + }, + { + "name": "guzzlehttp/promises", + "version": "3.2.0", + "version_normalized": "3.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "a201cc78db93065f891278f86eaeaa1c97c5a158" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/a201cc78db93065f891278f86eaeaa1c97c5a158", + "reference": "a201cc78db93065f891278f86eaeaa1c97c5a158", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^9.6.34" + }, + "time": "2026-11-21T03:48:02+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/3.2.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/promises" + }, + { + "name": "guzzlehttp/psr7", + "version": "3.6.0", + "version_normalized": "3.6.0.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "1fa0f8319c046b7dec80030460254283d851388e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/1fa0f8319c046b7dec80030460254283d851388e", + "reference": "1fa0f8319c046b7dec80030460254283d851388e", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^2.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0", + "symfony/polyfill-php80": "^1.25", + "symfony/polyfill-php82": "^1.27" + }, + "provide": { + "psr/http-factory-implementation": "1.1", + "psr/http-message-implementation": "2.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "1.1.0", + "jshttp/mime-db": "1.54.0.1", + "php-http/psr7-integration-tests": "^1.5.1", + "phpunit/phpunit": "^9.6.34" + }, + "suggest": { + "ext-intl": "Convert internationalized hosts with Idna", + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "time": "2026-11-22T00:00:35+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/3.6.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/psr7" + }, + { + "name": "league/commonmark", + "version": "2.10.7", + "version_normalized": "2.10.7.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/commonmark.git", + "reference": "8eb53e906fd60c67038d22f1f1cab420ed58b8be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/8eb53e906fd60c67038d22f1f1cab420ed58b8be", + "reference": "8eb53e906fd60c67038d22f1f1cab420ed58b8be", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "league/config": "^1.1.1", + "php": "^7.4 || ^8.0", + "psr/event-dispatcher": "^1.0", + "symfony/deprecation-contracts": "^2.1 || ^3.0", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "cebe/markdown": "^1.0", + "commonmark/cmark": "0.31.1", + "commonmark/commonmark.js": "0.31.1", + "composer/package-versions-deprecated": "^1.8", + "embed/embed": "^4.4", + "erusev/parsedown": "^1.0", + "ext-json": "*", + "github/gfm": "0.29.0", + "michelf/php-markdown": "^1.4 || ^2.0", + "nyholm/psr7": "^1.5", + "phpstan/phpstan": "^2.0.0", + "phpunit/phpunit": "^9.5.21 || ^10.5.9 || ^11.0.0 || ^12.0.0 || ^13.0.0", + "scrutinizer/ocular": "^1.8.1", + "symfony/finder": "^5.3 | ^6.0 | ^7.0 || ^8.0", + "symfony/process": "^5.4 | ^6.0 | ^7.0 || ^8.0", + "symfony/yaml": "^2.3 | ^3.0 | ^4.0 | ^5.0 | ^6.0 | ^7.0 || ^8.0", + "unleashedtech/php-coding-standard": "^3.1.1", + "vimeo/psalm": "^4.24.0 || ^5.0.0 || ^6.0.0" + }, + "suggest": { + "symfony/yaml": "v2.3+ required if using the Front Matter extension" + }, + "time": "2026-10-31T13:35:37+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.11-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\CommonMark\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "description": "Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)", + "homepage": "https://commonmark.thephpleague.com", + "keywords": [ + "commonmark", + "flavored", + "gfm", + "github", + "github-flavored", + "markdown", + "md", + "parser" + ], + "support": { + "docs": "https://commonmark.thephpleague.com/", + "forum": "https://github.com/thephpleague/commonmark/discussions", + "issues": "https://github.com/thephpleague/commonmark/issues", + "rss": "https://github.com/thephpleague/commonmark/releases.atom", + "source": "https://github.com/thephpleague/commonmark" + }, + "funding": [ + { + "url": "https://www.colinodell.com/sponsor", + "type": "custom" + }, + { + "url": "https://www.paypal.me/colinpodell/10.00", + "type": "custom" + }, + { + "url": "https://github.com/colinodell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/league/commonmark", + "type": "tidelift" + } + ], + "install-path": "../league/commonmark" + }, + { + "name": "league/config", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/config.git", + "reference": "754b3604fb2984c71f4af4a9cbe7b57f346ec1f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/config/zipball/754b3604fb2984c71f4af4a9cbe7b57f346ec1f3", + "reference": "754b3604fb2984c71f4af4a9cbe7b57f346ec1f3", + "shasum": "" + }, + "require": { + "dflydev/dot-access-data": "^3.0.1", + "nette/schema": "^1.2", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.8.2", + "phpunit/phpunit": "^9.5.5", + "scrutinizer/ocular": "^1.8.1", + "unleashedtech/php-coding-standard": "^3.1", + "vimeo/psalm": "^4.7.3" + }, + "time": "2022-12-11T20:36:23+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\Config\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "description": "Define configuration arrays with strict schemas and access values with dot notation", + "homepage": "https://config.thephpleague.com", + "keywords": [ + "array", + "config", + "configuration", + "dot", + "dot-access", + "nested", + "schema" + ], + "support": { + "docs": "https://config.thephpleague.com/", + "issues": "https://github.com/thephpleague/config/issues", + "rss": "https://github.com/thephpleague/config/releases.atom", + "source": "https://github.com/thephpleague/config" + }, + "funding": [ + { + "url": "https://www.colinodell.com/sponsor", + "type": "custom" + }, + { + "url": "https://www.paypal.me/colinpodell/10.00", + "type": "custom" + }, + { + "url": "https://github.com/colinodell", + "type": "github" + } + ], + "install-path": "../league/config" + }, + { + "name": "league/oauth2-client", + "version": "2.10.0", + "version_normalized": "2.10.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-client.git", + "reference": "25d240c6804f975909f8cdd131345949d8642535" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-client/zipball/25d240c6804f975909f8cdd131345949d8642535", + "reference": "25d240c6804f975909f8cdd131345949d8642535", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/guzzle": "^8.5.2", + "guzzlehttp/psr7": "^3.5.1", + "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" + }, + "require-dev": { + "mockery/mockery": "^1.6.15", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpunit/phpunit": "^11.5.58", + "squizlabs/php_codesniffer": "^4.0.4" + }, + "time": "2026-11-20T19:11:07+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Woody Gilk", + "homepage": "https://github.com/shadowhand", + "role": "Contributor" + }, + { + "name": "Andrew Millington", + "homepage": "https://github.com/sephster", + "role": "Developer" + } + ], + "description": "OAuth 2.0 Client Library", + "keywords": [ + "Authentication", + "SSO", + "authorization", + "identity", + "idp", + "oauth", + "oauth2", + "single sign on" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-client/issues", + "source": "https://github.com/thephpleague/oauth2-client/tree/2.10.0" + }, + "install-path": "../league/oauth2-client" + }, + { + "name": "monolog/monolog", + "version": "3.13.0", + "version_normalized": "3.13.0.0", + "source": { + "type": "git", + "url": "https://github.com/Seldaek/monolog.git", + "reference": "1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac", + "reference": "1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/log": "^2.0 || ^3.0" + }, + "provide": { + "psr/log-implementation": "3.0.0" + }, + "require-dev": { + "aws/aws-sdk-php": "^3.0", + "doctrine/couchdb": "~1.0@dev", + "elasticsearch/elasticsearch": "^7 || ^8", + "ext-json": "*", + "graylog2/gelf-php": "^1.4.2 || ^2.0", + "guzzlehttp/guzzle": "^7.4.5", + "guzzlehttp/psr7": "^2.2", + "mongodb/mongodb": "^1.8 || ^2.0", + "php-amqplib/php-amqplib": "~2.4 || ^3", + "php-console/php-console": "^3.1.8", + "phpstan/phpstan": "^2", + "phpstan/phpstan-deprecation-rules": "^2", + "phpstan/phpstan-strict-rules": "^2", + "phpunit/phpunit": "^10.5.17 || ^11.0.7", + "predis/predis": "^1.1 || ^2", + "psr/clock": "^1.0", + "rollbar/rollbar": "^4.0", + "ruflin/elastica": "^7 || ^8", + "symfony/mailer": "^5.4 || ^6", + "symfony/mime": "^5.4 || ^6" + }, + "suggest": { + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "elasticsearch/elasticsearch": "Allow sending log messages to an Elasticsearch server via official client", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-curl": "Required to send log messages using the IFTTTHandler, the LogglyHandler, the SendGridHandler, the SlackWebhookHandler or the TelegramBotHandler", + "ext-mbstring": "Allow to work properly with unicode symbols", + "ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)", + "ext-openssl": "Required to send log messages using SSL", + "ext-sockets": "Allow sending log messages to a Syslog server (via UDP driver)", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "psr/clock": "Required to pass a clock to the Logger and control the timestamp of log records", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server" + }, + "time": "2026-11-16T10:43:05+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "https://seld.be" + } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "https://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ], + "support": { + "issues": "https://github.com/Seldaek/monolog/issues", + "source": "https://github.com/Seldaek/monolog/tree/3.13.0" + }, + "funding": [ + { + "url": "https://github.com/Seldaek", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/monolog/monolog", + "type": "tidelift" + } + ], + "install-path": "../monolog/monolog" + }, + { + "name": "nette/schema", + "version": "v1.4.0", + "version_normalized": "1.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/nette/schema.git", + "reference": "af9fa8a86bfca9b02b10346220db26e62ef942ec" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/schema/zipball/af9fa8a86bfca9b02b10346220db26e62ef942ec", + "reference": "af9fa8a86bfca9b02b10346220db26e62ef942ec", + "shasum": "" + }, + "require": { + "nette/utils": "^4.0", + "php": "8.1 - 8.6" + }, + "require-dev": { + "nette/phpstan-rules": "^1.0.7", + "nette/tester": "^2.6", + "phpstan/extension-installer": "^1.4@stable", + "phpstan/phpstan": "^2.3@stable", + "tracy/tracy": "^2.8" + }, + "time": "2026-10-22T02:12:50+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Nette\\": "src" + }, + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + } + ], + "description": "📐 Nette Schema: validates and normalizes data such as configuration or API input against a schema described in a few readable lines of PHP, with precise error messages.", + "homepage": "https://doc.nette.org/schema", + "keywords": [ + "configuration", + "data validation", + "nette", + "normalization", + "schema", + "validation" + ], + "support": { + "issues": "https://github.com/nette/schema/issues", + "source": "https://github.com/nette/schema/tree/v1.4.0" + }, + "install-path": "../nette/schema" + }, + { + "name": "nette/utils", + "version": "v4.1.6", + "version_normalized": "4.1.6.0", + "source": { + "type": "git", + "url": "https://github.com/nette/utils.git", + "reference": "6bf24518accf32cf845bca305e0b92078700fd01" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/utils/zipball/6bf24518accf32cf845bca305e0b92078700fd01", + "reference": "6bf24518accf32cf845bca305e0b92078700fd01", + "shasum": "" + }, + "require": { + "php": "8.2 - 8.6" + }, + "conflict": { + "nette/finder": "<3", + "nette/schema": "<1.2.2" + }, + "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", + "tracy/tracy": "^2.9" + }, + "suggest": { + "ext-gd": "to use Image", + "ext-iconv": "to use Strings::chr(), ord() 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-10-20T17:07:56+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.1-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Nette\\": "src" + }, + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.", + "homepage": "https://nette.org", + "keywords": [ + "array", + "core", + "datetime", + "images", + "json", + "nette", + "paginator", + "password", + "slugify", + "string", + "unicode", + "utf-8", + "utility", + "validation" + ], + "support": { + "issues": "https://github.com/nette/utils/issues", + "source": "https://github.com/nette/utils/tree/v4.1.6" + }, + "install-path": "../nette/utils" + }, + { + "name": "nikic/fast-route", + "version": "1.3.1", + "version_normalized": "1.3.1.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/FastRoute.git", + "reference": "7476684f39bb9124b3be69ed3d84b66723920298" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/7476684f39bb9124b3be69ed3d84b66723920298", + "reference": "7476684f39bb9124b3be69ed3d84b66723920298", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35|~5.7" + }, + "time": "2026-07-09T19:38:47+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "FastRoute\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Fast request router for PHP", + "keywords": [ + "router", + "routing" + ], + "support": { + "issues": "https://github.com/nikic/FastRoute/issues", + "source": "https://github.com/nikic/FastRoute/tree/1.3.1" + }, + "install-path": "../nikic/fast-route" + }, + { + "name": "phpoption/phpoption", + "version": "1.10.0", + "version_normalized": "1.10.0.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-option.git", + "reference": "67b192b6a42ec03944b972d6e633ddec78ad2c6d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/67b192b6a42ec03944b972d6e633ddec78ad2c6d", + "reference": "67b192b6a42ec03944b972d6e633ddec78ad2c6d", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.54 || ^9.6.36 || ^10.5.64 || ^11.5.56 || ^12.5.33" + }, + "time": "2026-08-24T00:54:40+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "1.9-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "PhpOption\\": "src/PhpOption/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "https://github.com/schmittjoh" + }, + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "description": "Option Type for PHP", + "keywords": [ + "language", + "option", + "php", + "type" + ], + "support": { + "issues": "https://github.com/schmittjoh/php-option/issues", + "source": "https://github.com/schmittjoh/php-option/tree/1.10.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption", + "type": "tidelift" + } + ], + "install-path": "../phpoption/phpoption" + }, + { + "name": "psr/container", + "version": "2.0.2", + "version_normalized": "2.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "time": "2021-11-05T16:47:00+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "install-path": "../psr/container" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "time": "2019-01-08T18:20:26+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "install-path": "../psr/event-dispatcher" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "version_normalized": "1.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "time": "2023-09-23T14:17:50+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "install-path": "../psr/http-client" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "version_normalized": "1.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "time": "2024-04-15T12:06:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "install-path": "../psr/http-factory" + }, + { + "name": "psr/http-message", + "version": "2.0", + "version_normalized": "2.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "time": "2023-04-04T09:54:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "install-path": "../psr/http-message" + }, + { + "name": "psr/log", + "version": "3.0.2", + "version_normalized": "3.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2024-09-11T13:17:53+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "install-path": "../psr/log" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.8.1", + "version_normalized": "3.8.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/feb1edf4e546af3b85c5caebe8359a20db230ca3", + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "time": "2026-09-16T14:15:10+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.8-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.8.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "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" + } + ], + "install-path": "../symfony/deprecation-contracts" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.37.0", + "version_normalized": "1.37.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "141046a8f9477948ff284fa65be2095baafb94f2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/141046a8f9477948ff284fa65be2095baafb94f2", + "reference": "141046a8f9477948ff284fa65be2095baafb94f2", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "time": "2026-04-10T16:19:22+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.37.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "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" + } + ], + "install-path": "../symfony/polyfill-ctype" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.43.3", + "version_normalized": "1.43.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "122889ed24dc000165bcbfd77ec412f15cbdfc6a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/122889ed24dc000165bcbfd77ec412f15cbdfc6a", + "reference": "122889ed24dc000165bcbfd77ec412f15cbdfc6a", + "shasum": "" + }, + "require": { + "ext-iconv": "*", + "php": ">=7.2" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "time": "2026-10-28T09:35:49+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.43.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "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" + } + ], + "install-path": "../symfony/polyfill-mbstring" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.43.0", + "version_normalized": "1.43.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74", + "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "time": "2026-09-25T15:50:05+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.43.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "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" + } + ], + "install-path": "../symfony/polyfill-php80" + }, + { + "name": "symfony/polyfill-php82", + "version": "v1.43.0", + "version_normalized": "1.43.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php82.git", + "reference": "843bbe8b2a7934307b749751eede0f111f5d1cfc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/843bbe8b2a7934307b749751eede0f111f5d1cfc", + "reference": "843bbe8b2a7934307b749751eede0f111f5d1cfc", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "time": "2026-09-25T15:50:05+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php82\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php82/tree/v1.43.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "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" + } + ], + "install-path": "../symfony/polyfill-php82" + }, + { + "name": "vlucas/phpdotenv", + "version": "v5.8.1", + "version_normalized": "5.8.1.0", + "source": { + "type": "git", + "url": "https://github.com/phpdotenv/phpdotenv.git", + "reference": "ba37876e98122ca15151247ce1187d20ee8bf4e0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpdotenv/phpdotenv/zipball/ba37876e98122ca15151247ce1187d20ee8bf4e0", + "reference": "ba37876e98122ca15151247ce1187d20ee8bf4e0", + "shasum": "" + }, + "require": { + "ext-pcre": "*", + "graham-campbell/result-type": "^1.2", + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.10", + "symfony/polyfill-ctype": "^1.26", + "symfony/polyfill-mbstring": "^1.26", + "symfony/polyfill-php80": "^1.26" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-filter": "*", + "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "suggest": { + "ext-filter": "Required to use the boolean validator." + }, + "time": "2026-11-23T00:53:11+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "5.8-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Dotenv\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Vance Lucas", + "email": "vance@vancelucas.com", + "homepage": "https://github.com/vlucas" + } + ], + "description": "Loads environment variables from `.env` to `$_ENV` and `$_SERVER` automagically, and optionally to `getenv()`.", + "keywords": [ + "dotenv", + "env", + "environment" + ], + "support": { + "issues": "https://github.com/phpdotenv/phpdotenv/issues", + "source": "https://github.com/phpdotenv/phpdotenv/tree/v5.8.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv", + "type": "tidelift" + } + ], + "install-path": "../vlucas/phpdotenv" + }, + { + "name": "workerman/coroutine", + "version": "v1.1.7", + "version_normalized": "1.1.7.0", + "source": { + "type": "git", + "url": "https://github.com/workerman-php/coroutine.git", + "reference": "68a905d50f7ec1efcedc1ec317a75dcc3dea3f0f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/workerman-php/coroutine/zipball/68a905d50f7ec1efcedc1ec317a75dcc3dea3f0f", + "reference": "68a905d50f7ec1efcedc1ec317a75dcc3dea3f0f", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "workerman/workerman": "^5.1" + }, + "require-dev": { + "phpunit/phpunit": "^11.0", + "psr/log": "*" + }, + "time": "2026-10-24T05:06:43+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Workerman\\": "src", + "Workerman\\Coroutine\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Workerman coroutine", + "support": { + "issues": "https://github.com/workerman-php/coroutine/issues", + "source": "https://github.com/workerman-php/coroutine/tree/v1.1.7" + }, + "install-path": "../workerman/coroutine" + }, + { + "name": "workerman/webman-framework", + "version": "v2.2.5", + "version_normalized": "2.2.5.0", + "source": { + "type": "git", + "url": "https://github.com/walkor/webman-framework.git", + "reference": "263ef955d8ba6a0cb6fbc1bd0912589ed67c0c8d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/walkor/webman-framework/zipball/263ef955d8ba6a0cb6fbc1bd0912589ed67c0c8d", + "reference": "263ef955d8ba6a0cb6fbc1bd0912589ed67c0c8d", + "shasum": "" + }, + "require": { + "ext-json": "*", + "nikic/fast-route": "^1.3", + "php": ">=8.1", + "psr/container": ">=1.0", + "psr/log": "^2.0 || ^3.0", + "workerman/workerman": "^5.1 || dev-master" + }, + "suggest": { + "ext-event": "For better performance. " + }, + "time": "2026-10-25T09:46:46+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "./src/support/helpers.php" + ], + "psr-4": { + "Webman\\": "./src", + "Support\\": "./src/support", + "support\\": "./src/support", + "Support\\View\\": "./src/support/view", + "Support\\Bootstrap\\": "./src/support/bootstrap", + "Support\\Exception\\": "./src/support/exception" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "walkor", + "email": "walkor@workerman.net", + "homepage": "https://www.workerman.net", + "role": "Developer" + } + ], + "description": "High performance HTTP Service Framework.", + "homepage": "https://www.workerman.net", + "keywords": [ + "High Performance", + "http service" + ], + "support": { + "email": "walkor@workerman.net", + "forum": "https://wenda.workerman.net/", + "issues": "https://github.com/walkor/webman/issues", + "source": "https://github.com/walkor/webman-framework", + "wiki": "https://doc.workerman.net/" + }, + "install-path": "../workerman/webman-framework" + }, + { + "name": "workerman/workerman", + "version": "v5.2.4", + "version_normalized": "5.2.4.0", + "source": { + "type": "git", + "url": "https://github.com/walkor/workerman.git", + "reference": "4c817dec82c9ea223879b019600db58f62199abc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/walkor/workerman/zipball/4c817dec82c9ea223879b019600db58f62199abc", + "reference": "4c817dec82c9ea223879b019600db58f62199abc", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": ">=8.1", + "workerman/coroutine": "^1.1 || dev-main" + }, + "conflict": { + "ext-swow": " array( + 'name' => 'laysense/laysite', + 'pretty_version' => 'dev-main', + 'version' => 'dev-main', + 'reference' => '89f363186becd5bb733f30901af79903f47c9627', + 'type' => 'project', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + 'dflydev/dot-access-data' => array( + 'pretty_version' => 'v3.0.3', + 'version' => '3.0.3.0', + 'reference' => 'a23a2bf4f31d3518f3ecb38660c95715dfead60f', + 'type' => 'library', + 'install_path' => __DIR__ . '/../dflydev/dot-access-data', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'firebase/php-jwt' => array( + 'pretty_version' => 'v7.2.2', + 'version' => '7.2.2.0', + 'reference' => '99efeb17d6def8c0295777f2d45b07ff4fdb4e40', + 'type' => 'library', + 'install_path' => __DIR__ . '/../firebase/php-jwt', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'graham-campbell/result-type' => array( + 'pretty_version' => 'v1.2.0', + 'version' => '1.2.0.0', + 'reference' => 'adccca3324eece92ca35463648c12b9e6293c05b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../graham-campbell/result-type', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/guzzle' => array( + 'pretty_version' => '8.5.5', + 'version' => '8.5.5.0', + 'reference' => 'd1a26e6ce24268e740af501de8748d1c945e6f4b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/guzzle', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/promises' => array( + 'pretty_version' => '3.2.0', + 'version' => '3.2.0.0', + 'reference' => 'a201cc78db93065f891278f86eaeaa1c97c5a158', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/promises', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/psr7' => array( + 'pretty_version' => '3.6.0', + 'version' => '3.6.0.0', + 'reference' => '1fa0f8319c046b7dec80030460254283d851388e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/psr7', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'laysense/laysite' => array( + 'pretty_version' => 'dev-main', + 'version' => 'dev-main', + 'reference' => '89f363186becd5bb733f30901af79903f47c9627', + 'type' => 'project', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/commonmark' => array( + 'pretty_version' => '2.10.7', + 'version' => '2.10.7.0', + 'reference' => '8eb53e906fd60c67038d22f1f1cab420ed58b8be', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/commonmark', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/config' => array( + 'pretty_version' => 'v1.2.0', + 'version' => '1.2.0.0', + 'reference' => '754b3604fb2984c71f4af4a9cbe7b57f346ec1f3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/config', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/oauth2-client' => array( + 'pretty_version' => '2.10.0', + 'version' => '2.10.0.0', + 'reference' => '25d240c6804f975909f8cdd131345949d8642535', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/oauth2-client', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'monolog/monolog' => array( + 'pretty_version' => '3.13.0', + 'version' => '3.13.0.0', + 'reference' => '1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac', + 'type' => 'library', + 'install_path' => __DIR__ . '/../monolog/monolog', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'nette/schema' => array( + 'pretty_version' => 'v1.4.0', + 'version' => '1.4.0.0', + 'reference' => 'af9fa8a86bfca9b02b10346220db26e62ef942ec', + 'type' => 'library', + 'install_path' => __DIR__ . '/../nette/schema', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'nette/utils' => array( + 'pretty_version' => 'v4.1.6', + 'version' => '4.1.6.0', + 'reference' => '6bf24518accf32cf845bca305e0b92078700fd01', + 'type' => 'library', + 'install_path' => __DIR__ . '/../nette/utils', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'nikic/fast-route' => array( + 'pretty_version' => '1.3.1', + 'version' => '1.3.1.0', + 'reference' => '7476684f39bb9124b3be69ed3d84b66723920298', + 'type' => 'library', + 'install_path' => __DIR__ . '/../nikic/fast-route', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'phpoption/phpoption' => array( + 'pretty_version' => '1.10.0', + 'version' => '1.10.0.0', + 'reference' => '67b192b6a42ec03944b972d6e633ddec78ad2c6d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../phpoption/phpoption', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/container' => array( + 'pretty_version' => '2.0.2', + 'version' => '2.0.2.0', + 'reference' => 'c71ecc56dfe541dbd90c5360474fbc405f8d5963', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/container', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/event-dispatcher' => array( + 'pretty_version' => '1.0.0', + 'version' => '1.0.0.0', + 'reference' => 'dbefd12671e8a14ec7f180cab83036ed26714bb0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/event-dispatcher', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-client' => array( + 'pretty_version' => '1.0.3', + 'version' => '1.0.3.0', + 'reference' => 'bb5906edc1c324c9a05aa0873d40117941e5fa90', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-client', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-client-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-factory' => array( + 'pretty_version' => '1.1.0', + 'version' => '1.1.0.0', + 'reference' => '2b4765fddfe3b508ac62f829e852b1501d3f6e8a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-factory', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-factory-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.1', + ), + ), + 'psr/http-message' => array( + 'pretty_version' => '2.0', + 'version' => '2.0.0.0', + 'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-message', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-message-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '2.0', + ), + ), + 'psr/log' => array( + 'pretty_version' => '3.0.2', + 'version' => '3.0.2.0', + 'reference' => 'f16e1d5863e37f8d8c2a01719f5b34baa2b714d3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/log', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/log-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '3.0.0', + ), + ), + 'symfony/deprecation-contracts' => array( + 'pretty_version' => 'v3.8.1', + 'version' => '3.8.1.0', + 'reference' => 'feb1edf4e546af3b85c5caebe8359a20db230ca3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-ctype' => array( + 'pretty_version' => 'v1.37.0', + 'version' => '1.37.0.0', + 'reference' => '141046a8f9477948ff284fa65be2095baafb94f2', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-ctype', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-mbstring' => array( + 'pretty_version' => 'v1.43.3', + 'version' => '1.43.3.0', + 'reference' => '122889ed24dc000165bcbfd77ec412f15cbdfc6a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-mbstring', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-php80' => array( + 'pretty_version' => 'v1.43.0', + 'version' => '1.43.0.0', + 'reference' => '9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php80', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-php82' => array( + 'pretty_version' => 'v1.43.0', + 'version' => '1.43.0.0', + 'reference' => '843bbe8b2a7934307b749751eede0f111f5d1cfc', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php82', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'vlucas/phpdotenv' => array( + 'pretty_version' => 'v5.8.1', + 'version' => '5.8.1.0', + 'reference' => 'ba37876e98122ca15151247ce1187d20ee8bf4e0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../vlucas/phpdotenv', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'workerman/coroutine' => array( + 'pretty_version' => 'v1.1.7', + 'version' => '1.1.7.0', + 'reference' => '68a905d50f7ec1efcedc1ec317a75dcc3dea3f0f', + 'type' => 'library', + 'install_path' => __DIR__ . '/../workerman/coroutine', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'workerman/webman-framework' => array( + 'pretty_version' => 'v2.2.5', + 'version' => '2.2.5.0', + 'reference' => '263ef955d8ba6a0cb6fbc1bd0912589ed67c0c8d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../workerman/webman-framework', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'workerman/workerman' => array( + 'pretty_version' => 'v5.2.4', + 'version' => '5.2.4.0', + 'reference' => '4c817dec82c9ea223879b019600db58f62199abc', + 'type' => 'library', + 'install_path' => __DIR__ . '/../workerman/workerman', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/vendor/composer/platform_check.php b/vendor/composer/platform_check.php new file mode 100644 index 0000000..d32d90c --- /dev/null +++ b/vendor/composer/platform_check.php @@ -0,0 +1,26 @@ += 80200)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.2.0". You are running ' . PHP_VERSION . '.'; +} + +if ($issues) { + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); + } elseif (!headers_sent()) { + echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + } + } + trigger_error( + 'Composer detected issues in your platform: ' . implode(' ', $issues), + E_USER_ERROR + ); +} diff --git a/vendor/dflydev/dot-access-data/CHANGELOG.md b/vendor/dflydev/dot-access-data/CHANGELOG.md new file mode 100644 index 0000000..b8b468d --- /dev/null +++ b/vendor/dflydev/dot-access-data/CHANGELOG.md @@ -0,0 +1,74 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [3.0.3] - 2024-07-08 + +### Fixed + + - Fixed PHP 8.4 deprecation notices (#47) + +## [3.0.2] - 2022-10-27 + +### Fixed + + - Added missing return types to docblocks (#44, #45) + +## [3.0.1] - 2021-08-13 + +### Added + + - Adds ReturnTypeWillChange to suppress PHP 8.1 warnings (#40) + +## [3.0.0] - 2021-01-01 + +### Added + - Added support for both `.` and `/`-delimited key paths (#24) + - Added parameter and return types to everything; enabled strict type checks (#18) + - Added new exception classes to better identify certain types of errors (#20) + - `Data` now implements `ArrayAccess` (#17) + - Added ability to merge non-associative array values (#31, #32) + +### Changed + - All thrown exceptions are now instances or subclasses of `DataException` (#20) + - Calling `get()` on a missing key path without providing a default will throw a `MissingPathException` instead of returning `null` (#29) + - Bumped supported PHP versions to 7.1 - 8.x (#18) + +### Fixed + - Fixed incorrect merging of array values into string values (#32) + - Fixed `get()` method behaving as if keys with `null` values didn't exist + +## [2.0.0] - 2017-12-21 + +### Changed + - Bumped supported PHP versions to 7.0 - 7.4 (#12) + - Switched to PSR-4 autoloading + +## [1.1.0] - 2017-01-20 + +### Added + - Added new `has()` method to check for the existence of the given key (#4, #7) + +## [1.0.1] - 2015-08-12 + +### Added + - Added new optional `$default` parameter to the `get()` method (#2) + +## [1.0.0] - 2012-07-17 + +**Initial release!** + +[Unreleased]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.3...main +[3.0.3]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.2...v3.0.3 +[3.0.2]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.1...v3.0.2 +[3.0.1]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.0...v3.0.1 +[3.0.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v2.0.0...v3.0.0 +[2.0.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.1.0...v2.0.0 +[1.1.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.0.1...v1.1.0 +[1.0.1]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.0.0...v1.0.1 +[1.0.0]: https://github.com/dflydev/dflydev-dot-access-data/releases/tag/v1.0.0 diff --git a/vendor/dflydev/dot-access-data/LICENSE b/vendor/dflydev/dot-access-data/LICENSE new file mode 100644 index 0000000..b6880d4 --- /dev/null +++ b/vendor/dflydev/dot-access-data/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Dragonfly Development Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/dflydev/dot-access-data/README.md b/vendor/dflydev/dot-access-data/README.md new file mode 100644 index 0000000..775fbdf --- /dev/null +++ b/vendor/dflydev/dot-access-data/README.md @@ -0,0 +1,158 @@ +Dot Access Data +=============== + +[![Latest Version](https://img.shields.io/packagist/v/dflydev/dot-access-data.svg?style=flat-square)](https://packagist.org/packages/dflydev/dot-access-data) +[![Total Downloads](https://img.shields.io/packagist/dt/dflydev/dot-access-data.svg?style=flat-square)](https://packagist.org/packages/dflydev/dot-access-data) +[![Software License](https://img.shields.io/badge/License-MIT-brightgreen.svg?style=flat-square)](LICENSE) +[![Build Status](https://img.shields.io/github/workflow/status/dflydev/dflydev-dot-access-data/Tests/main.svg?style=flat-square)](https://github.com/dflydev/dflydev-dot-access-data/actions?query=workflow%3ATests+branch%3Amain) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/dflydev/dflydev-dot-access-data.svg?style=flat-square)](https://scrutinizer-ci.com/g/dflydev/dflydev-dot-access-data/code-structure/) +[![Quality Score](https://img.shields.io/scrutinizer/g/dflydev/dflydev-dot-access-data.svg?style=flat-square)](https://scrutinizer-ci.com/g/dflydev/dflydev-dot-access-data) + +Given a deep data structure, access data by dot notation. + + +Requirements +------------ + + * PHP (7.1+) + +> For PHP (5.3+) please refer to version `1.0`. + + +Usage +----- + +Abstract example: + +```php +use Dflydev\DotAccessData\Data; + +$data = new Data; + +$data->set('a.b.c', 'C'); +$data->set('a.b.d', 'D1'); +$data->append('a.b.d', 'D2'); +$data->set('a.b.e', ['E0', 'E1', 'E2']); + +// C +$data->get('a.b.c'); + +// ['D1', 'D2'] +$data->get('a.b.d'); + +// ['E0', 'E1', 'E2'] +$data->get('a.b.e'); + +// true +$data->has('a.b.c'); + +// false +$data->has('a.b.d.j'); + + +// 'some-default-value' +$data->get('some.path.that.does.not.exist', 'some-default-value'); + +// throws a MissingPathException because no default was given +$data->get('some.path.that.does.not.exist'); +``` + +A more concrete example: + +```php +use Dflydev\DotAccessData\Data; + +$data = new Data([ + 'hosts' => [ + 'hewey' => [ + 'username' => 'hman', + 'password' => 'HPASS', + 'roles' => ['web'], + ], + 'dewey' => [ + 'username' => 'dman', + 'password' => 'D---S', + 'roles' => ['web', 'db'], + 'nick' => 'dewey dman', + ], + 'lewey' => [ + 'username' => 'lman', + 'password' => 'LP@$$', + 'roles' => ['db'], + ], + ], +]); + +// hman +$username = $data->get('hosts.hewey.username'); +// HPASS +$password = $data->get('hosts.hewey.password'); +// ['web'] +$roles = $data->get('hosts.hewey.roles'); +// dewey dman +$nick = $data->get('hosts.dewey.nick'); +// Unknown +$nick = $data->get('hosts.lewey.nick', 'Unknown'); + +// DataInterface instance +$dewey = $data->getData('hosts.dewey'); +// dman +$username = $dewey->get('username'); +// D---S +$password = $dewey->get('password'); +// ['web', 'db'] +$roles = $dewey->get('roles'); + +// No more lewey +$data->remove('hosts.lewey'); + +// Add DB to hewey's roles +$data->append('hosts.hewey.roles', 'db'); + +$data->set('hosts.april', [ + 'username' => 'aman', + 'password' => '@---S', + 'roles' => ['web'], +]); + +// Check if a key exists (true to this case) +$hasKey = $data->has('hosts.dewey.username'); +``` + +`Data` may be used as an array, since it implements `ArrayAccess` interface: + +```php +// Get +$data->get('name') === $data['name']; // true + +$data['name'] = 'Dewey'; +// is equivalent to +$data->set($name, 'Dewey'); + +isset($data['name']) === $data->has('name'); + +// Remove key +unset($data['name']); +``` + +`/` can also be used as a path delimiter: + +```php +$data->set('a/b/c', 'd'); +echo $data->get('a/b/c'); // "d" + +$data->get('a/b/c') === $data->get('a.b.c'); // true +``` + +License +------- + +This library is licensed under the MIT License - see the LICENSE file +for details. + + +Community +--------- + +If you have questions or want to help out, join us in the +[#dflydev](irc://irc.freenode.net/#dflydev) channel on irc.freenode.net. diff --git a/vendor/dflydev/dot-access-data/composer.json b/vendor/dflydev/dot-access-data/composer.json new file mode 100644 index 0000000..44dc5ed --- /dev/null +++ b/vendor/dflydev/dot-access-data/composer.json @@ -0,0 +1,67 @@ +{ + "name": "dflydev/dot-access-data", + "type": "library", + "description": "Given a deep data structure, access data by dot notation.", + "homepage": "https://github.com/dflydev/dflydev-dot-access-data", + "keywords": ["dot", "access", "data", "notation"], + "license": "MIT", + "authors": [ + { + "name": "Dragonfly Development Inc.", + "email": "info@dflydev.com", + "homepage": "http://dflydev.com" + }, + { + "name": "Beau Simensen", + "email": "beau@dflydev.com", + "homepage": "http://beausimensen.com" + }, + { + "name": "Carlos Frutos", + "email": "carlos@kiwing.it", + "homepage": "https://github.com/cfrutos" + }, + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com" + } + ], + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.42", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.3", + "scrutinizer/ocular": "1.6.0", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.0.0" + }, + "autoload": { + "psr-4": { + "Dflydev\\DotAccessData\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Dflydev\\DotAccessData\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "scripts": { + "phpcs": "phpcs", + "phpstan": "phpstan analyse", + "phpunit": "phpunit --no-coverage", + "psalm": "psalm", + "test": [ + "@phpcs", + "@phpstan", + "@psalm", + "@phpunit" + ] + } +} diff --git a/vendor/dflydev/dot-access-data/src/Data.php b/vendor/dflydev/dot-access-data/src/Data.php new file mode 100644 index 0000000..3409b8e --- /dev/null +++ b/vendor/dflydev/dot-access-data/src/Data.php @@ -0,0 +1,286 @@ + + */ +class Data implements DataInterface, ArrayAccess +{ + private const DELIMITERS = ['.', '/']; + + /** + * Internal representation of data data + * + * @var array + */ + protected $data; + + /** + * Constructor + * + * @param array $data + */ + public function __construct(array $data = []) + { + $this->data = $data; + } + + /** + * {@inheritdoc} + */ + public function append(string $key, $value = null): void + { + $currentValue =& $this->data; + $keyPath = self::keyToPathArray($key); + + $endKey = array_pop($keyPath); + foreach ($keyPath as $currentKey) { + if (! isset($currentValue[$currentKey])) { + $currentValue[$currentKey] = []; + } + $currentValue =& $currentValue[$currentKey]; + } + + if (!isset($currentValue[$endKey])) { + $currentValue[$endKey] = []; + } + + if (!is_array($currentValue[$endKey])) { + // Promote this key to an array. + // TODO: Is this really what we want to do? + $currentValue[$endKey] = [$currentValue[$endKey]]; + } + + $currentValue[$endKey][] = $value; + } + + /** + * {@inheritdoc} + */ + public function set(string $key, $value = null): void + { + $currentValue =& $this->data; + $keyPath = self::keyToPathArray($key); + + $endKey = array_pop($keyPath); + foreach ($keyPath as $currentKey) { + if (!isset($currentValue[$currentKey])) { + $currentValue[$currentKey] = []; + } + if (!is_array($currentValue[$currentKey])) { + throw new DataException(sprintf('Key path "%s" within "%s" cannot be indexed into (is not an array)', $currentKey, self::formatPath($key))); + } + $currentValue =& $currentValue[$currentKey]; + } + $currentValue[$endKey] = $value; + } + + /** + * {@inheritdoc} + */ + public function remove(string $key): void + { + $currentValue =& $this->data; + $keyPath = self::keyToPathArray($key); + + $endKey = array_pop($keyPath); + foreach ($keyPath as $currentKey) { + if (!isset($currentValue[$currentKey])) { + return; + } + $currentValue =& $currentValue[$currentKey]; + } + unset($currentValue[$endKey]); + } + + /** + * {@inheritdoc} + * + * @psalm-mutation-free + */ + public function get(string $key, $default = null) + { + /** @psalm-suppress ImpureFunctionCall */ + $hasDefault = \func_num_args() > 1; + + $currentValue = $this->data; + $keyPath = self::keyToPathArray($key); + + foreach ($keyPath as $currentKey) { + if (!is_array($currentValue) || !array_key_exists($currentKey, $currentValue)) { + if ($hasDefault) { + return $default; + } + + throw new MissingPathException($key, sprintf('No data exists at the given path: "%s"', self::formatPath($keyPath))); + } + + $currentValue = $currentValue[$currentKey]; + } + + return $currentValue === null ? $default : $currentValue; + } + + /** + * {@inheritdoc} + * + * @psalm-mutation-free + */ + public function has(string $key): bool + { + $currentValue = $this->data; + + foreach (self::keyToPathArray($key) as $currentKey) { + if ( + !is_array($currentValue) || + !array_key_exists($currentKey, $currentValue) + ) { + return false; + } + $currentValue = $currentValue[$currentKey]; + } + + return true; + } + + /** + * {@inheritdoc} + * + * @psalm-mutation-free + */ + public function getData(string $key): DataInterface + { + $value = $this->get($key); + if (is_array($value) && Util::isAssoc($value)) { + return new Data($value); + } + + throw new DataException(sprintf('Value at "%s" could not be represented as a DataInterface', self::formatPath($key))); + } + + /** + * {@inheritdoc} + */ + public function import(array $data, int $mode = self::REPLACE): void + { + $this->data = Util::mergeAssocArray($this->data, $data, $mode); + } + + /** + * {@inheritdoc} + */ + public function importData(DataInterface $data, int $mode = self::REPLACE): void + { + $this->import($data->export(), $mode); + } + + /** + * {@inheritdoc} + * + * @psalm-mutation-free + */ + public function export(): array + { + return $this->data; + } + + /** + * {@inheritdoc} + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return $this->has($key); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->get($key, null); + } + + /** + * {@inheritdoc} + * + * @param string $key + * @param mixed $value + * + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->set($key, $value); + } + + /** + * {@inheritdoc} + * + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + $this->remove($key); + } + + /** + * @param string $path + * + * @return string[] + * + * @psalm-return non-empty-list + * + * @psalm-pure + */ + protected static function keyToPathArray(string $path): array + { + if (\strlen($path) === 0) { + throw new InvalidPathException('Path cannot be an empty string'); + } + + $path = \str_replace(self::DELIMITERS, '.', $path); + + return \explode('.', $path); + } + + /** + * @param string|string[] $path + * + * @return string + * + * @psalm-pure + */ + protected static function formatPath($path): string + { + if (is_string($path)) { + $path = self::keyToPathArray($path); + } + + return implode(' » ', $path); + } +} diff --git a/vendor/dflydev/dot-access-data/src/DataInterface.php b/vendor/dflydev/dot-access-data/src/DataInterface.php new file mode 100644 index 0000000..5909a8c --- /dev/null +++ b/vendor/dflydev/dot-access-data/src/DataInterface.php @@ -0,0 +1,131 @@ + $data + * @param self::PRESERVE|self::REPLACE|self::MERGE $mode + */ + public function import(array $data, int $mode = self::REPLACE): void; + + /** + * Import data from an external data into existing data + * + * @param DataInterface $data + * @param self::PRESERVE|self::REPLACE|self::MERGE $mode + */ + public function importData(DataInterface $data, int $mode = self::REPLACE): void; + + /** + * Export data as raw data + * + * @return array + * + * @psalm-mutation-free + */ + public function export(): array; +} diff --git a/vendor/dflydev/dot-access-data/src/Exception/DataException.php b/vendor/dflydev/dot-access-data/src/Exception/DataException.php new file mode 100644 index 0000000..2faf9f5 --- /dev/null +++ b/vendor/dflydev/dot-access-data/src/Exception/DataException.php @@ -0,0 +1,21 @@ +path = $path; + + parent::__construct($message, $code, $previous); + } + + public function getPath(): string + { + return $this->path; + } +} diff --git a/vendor/dflydev/dot-access-data/src/Util.php b/vendor/dflydev/dot-access-data/src/Util.php new file mode 100644 index 0000000..5634c51 --- /dev/null +++ b/vendor/dflydev/dot-access-data/src/Util.php @@ -0,0 +1,78 @@ + $arr + * + * @return bool + * + * @psalm-pure + */ + public static function isAssoc(array $arr): bool + { + return !count($arr) || count(array_filter(array_keys($arr), 'is_string')) == count($arr); + } + + /** + * Merge contents from one associtative array to another + * + * @param mixed $to + * @param mixed $from + * @param DataInterface::PRESERVE|DataInterface::REPLACE|DataInterface::MERGE $mode + * + * @return mixed + * + * @psalm-pure + */ + public static function mergeAssocArray($to, $from, int $mode = DataInterface::REPLACE) + { + if ($mode === DataInterface::MERGE && self::isList($to) && self::isList($from)) { + return array_merge($to, $from); + } + + if (is_array($from) && is_array($to)) { + foreach ($from as $k => $v) { + if (!isset($to[$k])) { + $to[$k] = $v; + } else { + $to[$k] = self::mergeAssocArray($to[$k], $v, $mode); + } + } + + return $to; + } + + return $mode === DataInterface::PRESERVE ? $to : $from; + } + + /** + * @param mixed $value + * + * @return bool + * + * @psalm-pure + */ + private static function isList($value): bool + { + return is_array($value) && array_values($value) === $value; + } +} diff --git a/vendor/firebase/php-jwt/CHANGELOG.md b/vendor/firebase/php-jwt/CHANGELOG.md new file mode 100644 index 0000000..8597266 --- /dev/null +++ b/vendor/firebase/php-jwt/CHANGELOG.md @@ -0,0 +1,272 @@ +# Changelog + +## [7.1.1](https://github.com/googleapis/php-jwt/compare/v7.1.0...v7.1.1) (2026-09-02) + + +### Bug Fixes + +* Limit the number of segments a JWT can be exploded into ([#639](https://github.com/googleapis/php-jwt/issues/639)) ([93d248c](https://github.com/googleapis/php-jwt/commit/93d248c650aea615d74a5ffa20c91c7a818e9b8d)) + +## [7.1.0](https://github.com/googleapis/php-jwt/compare/v7.0.5...v7.1.0) (2026-06-11) + + +### Features + +* Add support for PS256 ([#637](https://github.com/googleapis/php-jwt/issues/637)) ([aa0b447](https://github.com/googleapis/php-jwt/commit/aa0b4472c137255545b177a1840891304eac55f1)) + + +### Bug Fixes + +* Skip parsing valid unsupported curves ([#638](https://github.com/googleapis/php-jwt/issues/638)) ([8a6c2a7](https://github.com/googleapis/php-jwt/commit/8a6c2a75d7f45e781c93d618939f8a045fe69f53)) +* Update homepage URL in composer.json ([#635](https://github.com/googleapis/php-jwt/issues/635)) ([f7ae571](https://github.com/googleapis/php-jwt/commit/f7ae571efe255aed89c8f8d0f2cb7f71c5835664)) +* Validate numeric type of iat, nbf and exp claims in encode ([#634](https://github.com/googleapis/php-jwt/issues/634)) ([958e422](https://github.com/googleapis/php-jwt/commit/958e422961e874843a7fcc339e55a0101a66201d)) + +## [7.0.5](https://github.com/firebase/php-jwt/compare/v7.0.4...v7.0.5) (2026-03-31) + + +### Bug Fixes + +* RSA from JWK sometimes returns empty Instance ([#628](https://github.com/firebase/php-jwt/issues/628)) ([b4c78aa](https://github.com/firebase/php-jwt/commit/b4c78aa731664122198ad36c0033aa29e807397a)) + +## [7.0.4](https://github.com/firebase/php-jwt/compare/v7.0.3...v7.0.4) (2026-03-27) + + +### Bug Fixes + +* readme examples, add tests for all examples ([#626](https://github.com/firebase/php-jwt/issues/626)) ([510a00c](https://github.com/firebase/php-jwt/commit/510a00c0e6353bc7d68412fab67e57a13954cb46)) +* use urlsafeB64Decode everywhere ([#627](https://github.com/firebase/php-jwt/issues/627)) ([b889495](https://github.com/firebase/php-jwt/commit/b889495c83ddc3f3885ca3f0b65b41b1cb37a3b1)) + +## [7.0.3](https://github.com/firebase/php-jwt/compare/v7.0.2...v7.0.3) (2026-02-18) + + +### Miscellaneous Chores + +* add environment for Release Please job ([#619](https://github.com/firebase/php-jwt/issues/619)) ([300fd02](https://github.com/firebase/php-jwt/commit/300fd02c883f096c9067df652dbd23f62cb5e2a7)) + +## [7.0.2](https://github.com/firebase/php-jwt/compare/v7.0.1...v7.0.2) (2025-12-16) + + +### Bug Fixes + +* add key length validation for ec keys ([#615](https://github.com/firebase/php-jwt/issues/615)) ([7044f9a](https://github.com/firebase/php-jwt/commit/7044f9ae7e7d175d28cca71714feb236f1c0e252)) + +## [7.0.0](https://github.com/firebase/php-jwt/compare/v6.11.1...v7.0.0) (2025-12-15) + + +### ⚠️ ⚠️ ⚠️ Security Fixes ⚠️ ⚠️ ⚠️ + * add key size validation ([#613](https://github.com/firebase/php-jwt/issues/613)) ([6b80341](https://github.com/firebase/php-jwt/commit/6b80341bf57838ea2d011487917337901cd71576)) + **NOTE**: This fix will cause keys with a size below the minimally allowed size to break. + +### Features + +* add SensitiveParameter attribute to security-critical parameters ([#603](https://github.com/firebase/php-jwt/issues/603)) ([4dbfac0](https://github.com/firebase/php-jwt/commit/4dbfac0260eeb0e9e643063c99998e3219cc539b)) +* store timestamp in `ExpiredException` ([#604](https://github.com/firebase/php-jwt/issues/604)) ([f174826](https://github.com/firebase/php-jwt/commit/f1748260d218a856b6a0c23715ac7fae1d7ca95b)) + + +### Bug Fixes + +* validate iat and nbf on payload ([#568](https://github.com/firebase/php-jwt/issues/568)) ([953b2c8](https://github.com/firebase/php-jwt/commit/953b2c88bb445b7e3bb82a5141928f13d7343afd)) + +## [6.11.1](https://github.com/firebase/php-jwt/compare/v6.11.0...v6.11.1) (2025-04-09) + + +### Bug Fixes + +* update error text for consistency ([#528](https://github.com/firebase/php-jwt/issues/528)) ([c11113a](https://github.com/firebase/php-jwt/commit/c11113afa13265e016a669e75494b9203b8a7775)) + +## [6.11.0](https://github.com/firebase/php-jwt/compare/v6.10.2...v6.11.0) (2025-01-23) + + +### Features + +* support octet typed JWK ([#587](https://github.com/firebase/php-jwt/issues/587)) ([7cb8a26](https://github.com/firebase/php-jwt/commit/7cb8a265fa81edf2fa6ef8098f5bc5ae573c33ad)) + + +### Bug Fixes + +* refactor constructor Key to use PHP 8.0 syntax ([#577](https://github.com/firebase/php-jwt/issues/577)) ([29fa2ce](https://github.com/firebase/php-jwt/commit/29fa2ce9e0582cd397711eec1e80c05ce20fabca)) + +## [6.10.2](https://github.com/firebase/php-jwt/compare/v6.10.1...v6.10.2) (2024-11-24) + + +### Bug Fixes + +* Mitigate PHP8.4 deprecation warnings ([#570](https://github.com/firebase/php-jwt/issues/570)) ([76808fa](https://github.com/firebase/php-jwt/commit/76808fa227f3811aa5cdb3bf81233714b799a5b5)) +* support php 8.4 ([#583](https://github.com/firebase/php-jwt/issues/583)) ([e3d68b0](https://github.com/firebase/php-jwt/commit/e3d68b044421339443c74199edd020e03fb1887e)) + +## [6.10.1](https://github.com/firebase/php-jwt/compare/v6.10.0...v6.10.1) (2024-05-18) + + +### Bug Fixes + +* ensure ratelimit expiry is set every time ([#556](https://github.com/firebase/php-jwt/issues/556)) ([09cb208](https://github.com/firebase/php-jwt/commit/09cb2081c2c3bc0f61e2f2a5fbea5741f7498648)) +* ratelimit cache expiration ([#550](https://github.com/firebase/php-jwt/issues/550)) ([dda7250](https://github.com/firebase/php-jwt/commit/dda725033585ece30ff8cae8937320d7e9f18bae)) + +## [6.10.0](https://github.com/firebase/php-jwt/compare/v6.9.0...v6.10.0) (2023-11-28) + + +### Features + +* allow typ header override ([#546](https://github.com/firebase/php-jwt/issues/546)) ([79cb30b](https://github.com/firebase/php-jwt/commit/79cb30b729a22931b2fbd6b53f20629a83031ba9)) + +## [6.9.0](https://github.com/firebase/php-jwt/compare/v6.8.1...v6.9.0) (2023-10-04) + + +### Features + +* add payload to jwt exception ([#521](https://github.com/firebase/php-jwt/issues/521)) ([175edf9](https://github.com/firebase/php-jwt/commit/175edf958bb61922ec135b2333acf5622f2238a2)) + +## [6.8.1](https://github.com/firebase/php-jwt/compare/v6.8.0...v6.8.1) (2023-07-14) + + +### Bug Fixes + +* accept float claims but round down to ignore them ([#492](https://github.com/firebase/php-jwt/issues/492)) ([3936842](https://github.com/firebase/php-jwt/commit/39368423beeaacb3002afa7dcb75baebf204fe7e)) +* different BeforeValidException messages for nbf and iat ([#526](https://github.com/firebase/php-jwt/issues/526)) ([0a53cf2](https://github.com/firebase/php-jwt/commit/0a53cf2986e45c2bcbf1a269f313ebf56a154ee4)) + +## [6.8.0](https://github.com/firebase/php-jwt/compare/v6.7.0...v6.8.0) (2023-06-14) + + +### Features + +* add support for P-384 curve ([#515](https://github.com/firebase/php-jwt/issues/515)) ([5de4323](https://github.com/firebase/php-jwt/commit/5de4323f4baf4d70bca8663bd87682a69c656c3d)) + + +### Bug Fixes + +* handle invalid http responses ([#508](https://github.com/firebase/php-jwt/issues/508)) ([91c39c7](https://github.com/firebase/php-jwt/commit/91c39c72b22fc3e1191e574089552c1f2041c718)) + +## [6.7.0](https://github.com/firebase/php-jwt/compare/v6.6.0...v6.7.0) (2023-06-14) + + +### Features + +* add ed25519 support to JWK (public keys) ([#452](https://github.com/firebase/php-jwt/issues/452)) ([e53979a](https://github.com/firebase/php-jwt/commit/e53979abae927de916a75b9d239cfda8ce32be2a)) + +## [6.6.0](https://github.com/firebase/php-jwt/compare/v6.5.0...v6.6.0) (2023-06-13) + + +### Features + +* allow get headers when decoding token ([#442](https://github.com/firebase/php-jwt/issues/442)) ([fb85f47](https://github.com/firebase/php-jwt/commit/fb85f47cfaeffdd94faf8defdf07164abcdad6c3)) + + +### Bug Fixes + +* only check iat if nbf is not used ([#493](https://github.com/firebase/php-jwt/issues/493)) ([398ccd2](https://github.com/firebase/php-jwt/commit/398ccd25ea12fa84b9e4f1085d5ff448c21ec797)) + +## [6.5.0](https://github.com/firebase/php-jwt/compare/v6.4.0...v6.5.0) (2023-05-12) + + +### Bug Fixes + +* allow KID of '0' ([#505](https://github.com/firebase/php-jwt/issues/505)) ([9dc46a9](https://github.com/firebase/php-jwt/commit/9dc46a9c3e5801294249cfd2554c5363c9f9326a)) + + +### Miscellaneous Chores + +* drop support for PHP 7.3 ([#495](https://github.com/firebase/php-jwt/issues/495)) + +## [6.4.0](https://github.com/firebase/php-jwt/compare/v6.3.2...v6.4.0) (2023-02-08) + + +### Features + +* add support for W3C ES256K ([#462](https://github.com/firebase/php-jwt/issues/462)) ([213924f](https://github.com/firebase/php-jwt/commit/213924f51936291fbbca99158b11bd4ae56c2c95)) +* improve caching by only decoding jwks when necessary ([#486](https://github.com/firebase/php-jwt/issues/486)) ([78d3ed1](https://github.com/firebase/php-jwt/commit/78d3ed1073553f7d0bbffa6c2010009a0d483d5c)) + +## [6.3.2](https://github.com/firebase/php-jwt/compare/v6.3.1...v6.3.2) (2022-11-01) + + +### Bug Fixes + +* check kid before using as array index ([bad1b04](https://github.com/firebase/php-jwt/commit/bad1b040d0c736bbf86814c6b5ae614f517cf7bd)) + +## [6.3.1](https://github.com/firebase/php-jwt/compare/v6.3.0...v6.3.1) (2022-11-01) + + +### Bug Fixes + +* casing of GET for PSR compat ([#451](https://github.com/firebase/php-jwt/issues/451)) ([60b52b7](https://github.com/firebase/php-jwt/commit/60b52b71978790eafcf3b95cfbd83db0439e8d22)) +* string interpolation format for php 8.2 ([#446](https://github.com/firebase/php-jwt/issues/446)) ([2e07d8a](https://github.com/firebase/php-jwt/commit/2e07d8a1524d12b69b110ad649f17461d068b8f2)) + +## 6.3.0 / 2022-07-15 + + - Added ES256 support to JWK parsing ([#399](https://github.com/firebase/php-jwt/pull/399)) + - Fixed potential caching error in `CachedKeySet` by caching jwks as strings ([#435](https://github.com/firebase/php-jwt/pull/435)) + +## 6.2.0 / 2022-05-14 + + - Added `CachedKeySet` ([#397](https://github.com/firebase/php-jwt/pull/397)) + - Added `$defaultAlg` parameter to `JWT::parseKey` and `JWT::parseKeySet` ([#426](https://github.com/firebase/php-jwt/pull/426)). + +## 6.1.0 / 2022-03-23 + + - Drop support for PHP 5.3, 5.4, 5.5, 5.6, and 7.0 + - Add parameter typing and return types where possible + +## 6.0.0 / 2022-01-24 + + - **Backwards-Compatibility Breaking Changes**: See the [Release Notes](https://github.com/firebase/php-jwt/releases/tag/v6.0.0) for more information. + - New Key object to prevent key/algorithm type confusion (#365) + - Add JWK support (#273) + - Add ES256 support (#256) + - Add ES384 support (#324) + - Add Ed25519 support (#343) + +## 5.0.0 / 2017-06-26 +- Support RS384 and RS512. + See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)! +- Add an example for RS256 openssl. + See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)! +- Detect invalid Base64 encoding in signature. + See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)! +- Update `JWT::verify` to handle OpenSSL errors. + See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)! +- Add `array` type hinting to `decode` method + See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)! +- Add all JSON error types. + See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)! +- Bugfix 'kid' not in given key list. + See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)! +- Miscellaneous cleanup, documentation and test fixes. + See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115), + [#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and + [#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman), + [@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)! + +## 4.0.0 / 2016-07-17 +- Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)! +- Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)! +- Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)! +- Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)! + +## 3.0.0 / 2015-07-22 +- Minimum PHP version updated from `5.2.0` to `5.3.0`. +- Add `\Firebase\JWT` namespace. See +[#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to +[@Dashron](https://github.com/Dashron)! +- Require a non-empty key to decode and verify a JWT. See +[#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to +[@sjones608](https://github.com/sjones608)! +- Cleaner documentation blocks in the code. See +[#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to +[@johanderuijter](https://github.com/johanderuijter)! + +## 2.2.0 / 2015-06-22 +- Add support for adding custom, optional JWT headers to `JWT::encode()`. See +[#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to +[@mcocaro](https://github.com/mcocaro)! + +## 2.1.0 / 2015-05-20 +- Add support for adding a leeway to `JWT:decode()` that accounts for clock skew +between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)! +- Add support for passing an object implementing the `ArrayAccess` interface for +`$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)! + +## 2.0.0 / 2015-04-01 +- **Note**: It is strongly recommended that you update to > v2.0.0 to address + known security vulnerabilities in prior versions when both symmetric and + asymmetric keys are used together. +- Update signature for `JWT::decode(...)` to require an array of supported + algorithms to use when verifying token signatures. diff --git a/vendor/firebase/php-jwt/LICENSE b/vendor/firebase/php-jwt/LICENSE new file mode 100644 index 0000000..11c0146 --- /dev/null +++ b/vendor/firebase/php-jwt/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2011, Neuman Vong + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the copyright holder nor the names of other + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/firebase/php-jwt/README.md b/vendor/firebase/php-jwt/README.md new file mode 100644 index 0000000..9d4ff3e --- /dev/null +++ b/vendor/firebase/php-jwt/README.md @@ -0,0 +1,469 @@ +![Build Status](https://github.com/firebase/php-jwt/actions/workflows/tests.yml/badge.svg) +[![Latest Stable Version](https://poser.pugx.org/firebase/php-jwt/v/stable)](https://packagist.org/packages/firebase/php-jwt) +[![Total Downloads](https://poser.pugx.org/firebase/php-jwt/downloads)](https://packagist.org/packages/firebase/php-jwt) +[![License](https://poser.pugx.org/firebase/php-jwt/license)](https://packagist.org/packages/firebase/php-jwt) + +PHP-JWT +======= +A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519). + +Supported Specifications +------------------------ + +- [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) — JSON Web Token (JWT) +- [RFC 7515](https://datatracker.ietf.org/doc/html/rfc7515) — JSON Web Signature (JWS) +- [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517) — JSON Web Key (JWK) +- [RFC 7518](https://datatracker.ietf.org/doc/html/rfc7518) — JSON Web Algorithms (JWA) (`HS256`, `HS384`, `HS512`, `RS256`, `RS384`, `RS512`, `ES256`, `ES384`, `PS256`) +- [RFC 8037](https://datatracker.ietf.org/doc/html/rfc8037) — CFRG Elliptic Curve Diffie-Hellman (ECDH) and Signatures in JOSE (`EdDSA` / `Ed25519` and `OKP` JWKs) +- [RFC 8812](https://datatracker.ietf.org/doc/html/rfc8812) — CBOR Object Signing and Encryption (COSE) and JSON Object Signing and Encryption (JOSE) Registrations for Web Authentication (WebAuthn) Algorithms (`ES256K` / `secp256k1`) + +> **Note:** This library only supports signed JWTs (JWS, [RFC 7515](https://datatracker.ietf.org/doc/html/rfc7515)). Encrypted JWTs (JWE, [RFC 7516](https://datatracker.ietf.org/doc/html/rfc7516)) are not supported. + +Installation +------------ + +Use composer to manage your dependencies and download PHP-JWT: + +```bash +composer require firebase/php-jwt +``` + +Optionally, install the `paragonie/sodium_compat` package from composer if your +php env does not have libsodium installed: + +```bash +composer require paragonie/sodium_compat +``` + +## Example + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$key = 'example_key_of_sufficient_length'; +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +/** + * IMPORTANT: + * You must specify supported algorithms for your application. See + * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 + * for a list of spec-compliant algorithms. + */ +$jwt = JWT::encode($payload, $key, 'HS256'); +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); +print_r($decoded); + +// Pass a stdClass in as the third parameter to get the decoded header values +$headers = new stdClass(); +$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers); +print_r($headers); + +/* + NOTE: This will now be an object instead of an associative array. To get + an associative array, you will need to cast it as such: +*/ + +$decoded_array = (array) $decoded; + +/** + * You can add a leeway to account for when there is a clock skew times between + * the signing and verifying servers. It is recommended that this leeway should + * not be bigger than a few minutes. + * + * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef + */ +JWT::$leeway = 60; // $leeway in seconds +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); +``` + +## Example encode/decode headers + +Decoding the JWT headers without verifying the JWT first is NOT recommended, and is not supported by +this library. This is because without verifying the JWT, the header values could have been tampered with. +Any value pulled from an unverified header should be treated as if it could be any string sent in from an +attacker. If this is something you still want to do in your application for whatever reason, it's possible to +decode the header values manually simply by calling `json_decode` and `base64_decode` on the JWT +header part: +```php +use Firebase\JWT\JWT; + +$key = 'example_key_of_sufficient_length'; +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$headers = [ + 'x-forwarded-for' => 'www.google.com' +]; + +// Encode headers in the JWT string +$jwt = JWT::encode($payload, $key, 'HS256', null, $headers); + +// Decode headers from the JWT string WITHOUT validation +// **IMPORTANT**: This operation is vulnerable to attacks, as the JWT has not yet been verified. +// These headers could be any value sent by an attacker. +list($headersB64, $payloadB64, $sig) = explode('.', $jwt); +$decoded = json_decode(base64_decode($headersB64), true); + +print_r($decoded); +``` + +## Example with RS256 (openssl) + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$privateKey = << 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'RS256'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); + +/* + NOTE: This will now be an object instead of an associative array. To get + an associative array, you will need to cast it as such: +*/ + +$decoded_array = (array) $decoded; +echo "Decode:\n" . print_r($decoded_array, true) . "\n"; +``` + +## Example with a passphrase + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Your passphrase +$passphrase = '[YOUR_PASSPHRASE]'; + +// Your private key file with passphrase +// Can be generated with "ssh-keygen -t rsa -m pem" +$privateKeyFile = '/path/to/key-with-passphrase.pem'; + +/** @var OpenSSLAsymmetricKey $privateKey */ +$privateKey = openssl_pkey_get_private( + file_get_contents($privateKeyFile), + $passphrase +); + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'RS256'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +// Get public key from the private key, or pull from from a file. +$publicKey = openssl_pkey_get_details($privateKey)['key']; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +``` + +## Example with EdDSA (libsodium and Ed25519 signature) + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Public and private keys are expected to be Base64 encoded. The last +// non-empty line is used so that keys can be generated with +// sodium_crypto_sign_keypair(). The secret keys generated by other tools may +// need to be adjusted to match the input expected by libsodium. + +$keyPair = sodium_crypto_sign_keypair(); + +$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair)); + +$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair)); + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'EdDSA'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +``` + +## Example with multiple keys + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Example RSA keys from previous example +// $privateRsKey = '...'; +// $publicRsKey = '...'; + +// Example EdDSA keys from previous example +// $privateEcKey = '...'; +// $publicEcKey = '...'; + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt1 = JWT::encode($payload, $privateRsKey, 'RS256', 'kid1'); +$jwt2 = JWT::encode($payload, $privateEcKey, 'EdDSA', 'kid2'); +echo "Encode 1:\n" . print_r($jwt1, true) . "\n"; +echo "Encode 2:\n" . print_r($jwt2, true) . "\n"; + +$keys = [ + 'kid1' => new Key($publicRsKey, 'RS256'), + 'kid2' => new Key($publicEcKey, 'EdDSA'), +]; + +$decoded1 = JWT::decode($jwt1, $keys); +$decoded2 = JWT::decode($jwt2, $keys); + +echo "Decode 1:\n" . print_r((array) $decoded1, true) . "\n"; +echo "Decode 2:\n" . print_r((array) $decoded2, true) . "\n"; +``` + +## Example with PS256 + +### Note +PHP's OpenSSL extension does not support RSASSA-PSS signatures (PS256) by default, so we provide support via a soft dependency on the [phpseclib/phpseclib](https://github.com/phpseclib/phpseclib) library. It is necessary to install this library in your project if you plan to use PS256. +```bash +composer install phpseclib/phpseclib:^3.0 +``` + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$privateRsKey = '-----BEGIN RSA PRIVATE KEY----- ...'; +$publicKey = '-----BEGIN PUBLIC KEY----- ...'; + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +/** +* PS256 support requires phpseclib/phpseclib +*/ +$jwt = JWT::encode($payload, $privateRsKey, 'PS256', 'keyid'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'PS256')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +``` + +## Using JWKs + +```php +use Firebase\JWT\JWK; +use Firebase\JWT\JWT; + +// Set of keys. The "keys" key is required. For example, the JSON response to +// this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk +$jwks = ['keys' => []]; + +// JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\JWT\Key +// objects. Pass this as the second parameter to JWT::decode. +$decoded = JWT::decode($jwt, JWK::parseKeySet($jwks)); +print_r($decoded); +``` + +## Using Cached Key Sets + +The `CachedKeySet` class can be used to fetch and cache JWKS (JSON Web Key Sets) from a public URI. +This has the following advantages: + +1. The results are cached for performance. +2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation. +3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second. + +```php +use Firebase\JWT\CachedKeySet; +use Firebase\JWT\JWT; + +// The URI for the JWKS you wish to cache the results from +$jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk'; + +// Create an HTTP client (can be any PSR-7 compatible HTTP client) +$httpClient = new GuzzleHttp\Client(); + +// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory) +$httpFactory = new GuzzleHttp\Psr7\HttpFactory(); + +// Create a cache item pool (can be any PSR-6 compatible cache item pool) +$cacheItemPool = Phpfastcache\CacheManager::getInstance('files'); + +$keySet = new CachedKeySet( + $jwksUri, + $httpClient, + $httpFactory, + $cacheItemPool, + null, // $expiresAfter int seconds to set the JWKS to expire + true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys +); + +$jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above +$decoded = JWT::decode($jwt, $keySet); +``` + +Miscellaneous +------------- + +#### Exception Handling + +When a call to `JWT::decode` is invalid, it will throw one of the following exceptions: + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\SignatureInvalidException; +use Firebase\JWT\BeforeValidException; +use Firebase\JWT\ExpiredException; +use DomainException; +use InvalidArgumentException; +use UnexpectedValueException; + +try { + $decoded = JWT::decode($jwt, $keys); +} catch (InvalidArgumentException $e) { + // provided key/key-array is empty or malformed. +} catch (DomainException $e) { + // provided algorithm is unsupported OR + // provided key is invalid OR + // unknown error thrown in openSSL or libsodium OR + // libsodium is required but not available. +} catch (SignatureInvalidException $e) { + // provided JWT signature verification failed. +} catch (BeforeValidException $e) { + // provided JWT is trying to be used before "nbf" claim OR + // provided JWT is trying to be used before "iat" claim. +} catch (ExpiredException $e) { + // provided JWT is trying to be used after "exp" claim. +} catch (UnexpectedValueException $e) { + // provided JWT is malformed OR + // provided JWT is missing an algorithm / using an unsupported algorithm OR + // provided JWT algorithm does not match provided key OR + // provided key ID in key/key-array is empty or invalid. +} +``` + +All exceptions in the `Firebase\JWT` namespace extend `UnexpectedValueException`, and can be simplified +like this: + +```php +use Firebase\JWT\JWT; +use UnexpectedValueException; +try { + $decoded = JWT::decode($jwt, $keys); +} catch (LogicException $e) { + // errors having to do with environmental setup or malformed JWT Keys +} catch (UnexpectedValueException $e) { + // errors having to do with JWT signature and claims +} +``` + +#### Casting to array + +The return value of `JWT::decode` is the generic PHP object `stdClass`. If you'd like to handle with arrays +instead, you can do the following: + +```php +// return type is stdClass +$decoded = JWT::decode($jwt, $keys); + +// cast to array +$decoded = json_decode(json_encode($decoded), true); +``` + +Tests +----- +Run the tests using phpunit: + +```bash +$ composer update +$ vendor/bin/phpunit -c phpunit.xml.dist +PHPUnit 3.7.10 by Sebastian Bergmann. +..... +Time: 0 seconds, Memory: 2.50Mb +OK (5 tests, 5 assertions) +``` + +New Lines in private keys +----- + +If your private key contains `\n` characters, be sure to wrap it in double quotes `""` +and not single quotes `''` in order to properly interpret the escaped characters. + +License +------- +[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause). diff --git a/vendor/firebase/php-jwt/VERSION b/vendor/firebase/php-jwt/VERSION new file mode 100644 index 0000000..77f5bec --- /dev/null +++ b/vendor/firebase/php-jwt/VERSION @@ -0,0 +1 @@ +7.2.2 diff --git a/vendor/firebase/php-jwt/composer.json b/vendor/firebase/php-jwt/composer.json new file mode 100644 index 0000000..89c8c70 --- /dev/null +++ b/vendor/firebase/php-jwt/composer.json @@ -0,0 +1,53 @@ +{ + "name": "firebase/php-jwt", + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/googleapis/php-jwt", + "keywords": [ + "php", + "jwt" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "license": "BSD-3-Clause", + "require": { + "php": "^8.0" + }, + "suggest": { + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present", + "ext-sodium": "Support EdDSA (Ed25519) signatures", + "phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures" + }, + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "require-dev": { + "guzzlehttp/guzzle": "^7.4||^8.0", + "phpspec/prophecy-phpunit": "^2.2", + "phpunit/phpunit": "^9.5", + "psr/cache": "^2.0||^3.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0", + "phpfastcache/phpfastcache": "^9.2", + "phpseclib/phpseclib": "~3.0" + }, + "extra": { + "component": { + "id": "jwt", + "target": "googleapis/php-jwt.git", + "path": "Jwt", + "entry": "README.md" + } + } +} diff --git a/vendor/firebase/php-jwt/src/BeforeValidException.php b/vendor/firebase/php-jwt/src/BeforeValidException.php new file mode 100644 index 0000000..595164b --- /dev/null +++ b/vendor/firebase/php-jwt/src/BeforeValidException.php @@ -0,0 +1,18 @@ +payload = $payload; + } + + public function getPayload(): object + { + return $this->payload; + } +} diff --git a/vendor/firebase/php-jwt/src/CachedKeySet.php b/vendor/firebase/php-jwt/src/CachedKeySet.php new file mode 100644 index 0000000..37c3f94 --- /dev/null +++ b/vendor/firebase/php-jwt/src/CachedKeySet.php @@ -0,0 +1,275 @@ + + */ +class CachedKeySet implements ArrayAccess +{ + /** + * @var string + */ + private $jwksUri; + /** + * @var ClientInterface + */ + private $httpClient; + /** + * @var RequestFactoryInterface + */ + private $httpFactory; + /** + * @var CacheItemPoolInterface + */ + private $cache; + /** + * @var ?int + */ + private $expiresAfter; + /** + * @var ?CacheItemInterface + */ + private $cacheItem; + /** + * @var array> + */ + private $keySet; + /** + * @var string + */ + private $cacheKey; + /** + * @var string + */ + private $cacheKeyPrefix = 'jwks'; + /** + * @var int + */ + private $maxKeyLength = 64; + /** + * @var bool + */ + private $rateLimit; + /** + * @var string + */ + private $rateLimitCacheKey; + /** + * @var int + */ + private $maxCallsPerMinute = 10; + /** + * @var string|null + */ + private $defaultAlg; + + public function __construct( + string $jwksUri, + ClientInterface $httpClient, + RequestFactoryInterface $httpFactory, + CacheItemPoolInterface $cache, + ?int $expiresAfter = null, + bool $rateLimit = false, + ?string $defaultAlg = null + ) { + $this->jwksUri = $jwksUri; + $this->httpClient = $httpClient; + $this->httpFactory = $httpFactory; + $this->cache = $cache; + $this->expiresAfter = $expiresAfter; + $this->rateLimit = $rateLimit; + $this->defaultAlg = $defaultAlg; + $this->setCacheKeys(); + } + + /** + * @param string $keyId + * @return Key + */ + public function offsetGet($keyId): Key + { + if (!$this->keyIdExists($keyId)) { + throw new OutOfBoundsException('Key ID not found'); + } + return JWK::parseKey($this->keySet[$keyId], $this->defaultAlg); + } + + /** + * @param string $keyId + * @return bool + */ + public function offsetExists($keyId): bool + { + return $this->keyIdExists($keyId); + } + + /** + * @param string $offset + * @param Key $value + */ + public function offsetSet($offset, $value): void + { + throw new LogicException('Method not implemented'); + } + + /** + * @param string $offset + */ + public function offsetUnset($offset): void + { + throw new LogicException('Method not implemented'); + } + + /** + * @return array + */ + private function formatJwksForCache(string $jwks): array + { + $jwks = json_decode($jwks, true); + + if (!isset($jwks['keys'])) { + throw new UnexpectedValueException('"keys" member must exist in the JWK Set'); + } + + if (empty($jwks['keys'])) { + throw new InvalidArgumentException('JWK Set did not contain any keys'); + } + + $keys = []; + foreach ($jwks['keys'] as $k => $v) { + $kid = isset($v['kid']) ? $v['kid'] : $k; + $keys[(string) $kid] = $v; + } + + return $keys; + } + + private function keyIdExists(string $keyId): bool + { + if (null === $this->keySet) { + $item = $this->getCacheItem(); + // Try to load keys from cache + if ($item->isHit()) { + // item found! retrieve it + $this->keySet = $item->get(); + // If the cached item is a string, the JWKS response was cached (previous behavior). + // Parse this into expected format array instead. + if (\is_string($this->keySet)) { + $this->keySet = $this->formatJwksForCache($this->keySet); + } + } + } + + if (!isset($this->keySet[$keyId])) { + if ($this->rateLimitExceeded()) { + return false; + } + $request = $this->httpFactory->createRequest('GET', $this->jwksUri); + $jwksResponse = $this->httpClient->sendRequest($request); + if ($jwksResponse->getStatusCode() !== 200) { + throw new UnexpectedValueException( + \sprintf( + 'HTTP Error: %d %s for URI "%s"', + $jwksResponse->getStatusCode(), + $jwksResponse->getReasonPhrase(), + $this->jwksUri, + ), + $jwksResponse->getStatusCode() + ); + } + $this->keySet = $this->formatJwksForCache((string) $jwksResponse->getBody()); + + if (!isset($this->keySet[$keyId])) { + return false; + } + + $item = $this->getCacheItem(); + $item->set($this->keySet); + if ($this->expiresAfter) { + $item->expiresAfter($this->expiresAfter); + } + $this->cache->save($item); + } + + return true; + } + + private function rateLimitExceeded(): bool + { + if (!$this->rateLimit) { + return false; + } + + $cacheItem = $this->cache->getItem($this->rateLimitCacheKey); + + $cacheItemData = []; + if ($cacheItem->isHit() && \is_array($data = $cacheItem->get())) { + $cacheItemData = $data; + } + + $callsPerMinute = $cacheItemData['callsPerMinute'] ?? 0; + $expiry = $cacheItemData['expiry'] ?? new \DateTime('+60 seconds', new \DateTimeZone('UTC')); + + if (++$callsPerMinute > $this->maxCallsPerMinute) { + return true; + } + + $cacheItem->set(['expiry' => $expiry, 'callsPerMinute' => $callsPerMinute]); + $cacheItem->expiresAt($expiry); + $this->cache->save($cacheItem); + return false; + } + + private function getCacheItem(): CacheItemInterface + { + if (\is_null($this->cacheItem)) { + $this->cacheItem = $this->cache->getItem($this->cacheKey); + } + + return $this->cacheItem; + } + + private function setCacheKeys(): void + { + if (empty($this->jwksUri)) { + throw new RuntimeException('JWKS URI is empty'); + } + + // ensure we do not have illegal characters + $key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $this->jwksUri); + + // add prefix + $key = $this->cacheKeyPrefix . $key; + + // Hash keys if they exceed $maxKeyLength of 64 + if (\strlen($key) > $this->maxKeyLength) { + $key = substr(hash('sha256', $key), 0, $this->maxKeyLength); + } + + $this->cacheKey = $key; + + if ($this->rateLimit) { + // add prefix + $rateLimitKey = $this->cacheKeyPrefix . 'ratelimit' . $key; + + // Hash keys if they exceed $maxKeyLength of 64 + if (\strlen($rateLimitKey) > $this->maxKeyLength) { + $rateLimitKey = substr(hash('sha256', $rateLimitKey), 0, $this->maxKeyLength); + } + + $this->rateLimitCacheKey = $rateLimitKey; + } + } +} diff --git a/vendor/firebase/php-jwt/src/ExpiredException.php b/vendor/firebase/php-jwt/src/ExpiredException.php new file mode 100644 index 0000000..25f4451 --- /dev/null +++ b/vendor/firebase/php-jwt/src/ExpiredException.php @@ -0,0 +1,30 @@ +payload = $payload; + } + + public function getPayload(): object + { + return $this->payload; + } + + public function setTimestamp(int $timestamp): void + { + $this->timestamp = $timestamp; + } + + public function getTimestamp(): ?int + { + return $this->timestamp; + } +} diff --git a/vendor/firebase/php-jwt/src/JWK.php b/vendor/firebase/php-jwt/src/JWK.php new file mode 100644 index 0000000..1870c6f --- /dev/null +++ b/vendor/firebase/php-jwt/src/JWK.php @@ -0,0 +1,376 @@ + + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWK +{ + private const OID = '1.2.840.10045.2.1'; + private const ASN1_OBJECT_IDENTIFIER = 0x06; + private const ASN1_SEQUENCE = 0x10; // also defined in JWT + private const ASN1_BIT_STRING = 0x03; + private const EC_CURVES = [ + 'P-256' => '1.2.840.10045.3.1.7', // Len: 64 + 'secp256k1' => '1.3.132.0.10', // Len: 64 + 'P-384' => '1.3.132.0.34', // Len: 96 + // 'P-521' => '1.3.132.0.35', // Len: 132 (not supported) + ]; + + // Known standard curves from the IANA JOSE registry which are not supported + private const KNOWN_UNSUPPORTED_EC_CURVES = [ + 'P-521', // RFC 7518 + 'Ed25519', // RFC 8037 + 'Ed448', // RFC 8037 + 'X25519', // RFC 8037 + 'X448' // RFC 8037 + ]; + + // For keys with "kty" equal to "OKP" (Octet Key Pair), the "crv" parameter must contain the key subtype. + // This library supports the following subtypes: + private const OKP_SUBTYPES = [ + 'Ed25519' => true, // RFC 8037 + ]; + + /** + * Parse a set of JWK keys + * + * @param array $jwks The JSON Web Key Set as an associative array + * @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the + * JSON Web Key Set + * + * @return array An associative array of key IDs (kid) to Key objects + * + * @throws InvalidArgumentException Provided JWK Set is empty + * @throws UnexpectedValueException Provided JWK Set was invalid + * @throws DomainException OpenSSL failure + * + * @uses parseKey + */ + public static function parseKeySet(#[\SensitiveParameter] array $jwks, ?string $defaultAlg = null): array + { + $keys = []; + + if (!isset($jwks['keys'])) { + throw new UnexpectedValueException('"keys" member must exist in the JWK Set'); + } + + if (empty($jwks['keys'])) { + throw new InvalidArgumentException('JWK Set did not contain any keys'); + } + + foreach ($jwks['keys'] as $k => $v) { + $kid = isset($v['kid']) ? $v['kid'] : $k; + if ($key = self::parseKey($v, $defaultAlg)) { + $keys[(string) $kid] = $key; + } + } + + if (0 === \count($keys)) { + throw new UnexpectedValueException('No supported algorithms found in JWK Set'); + } + + return $keys; + } + + /** + * Parse a JWK key + * + * @param array $jwk An individual JWK + * @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the + * JSON Web Key Set + * + * @return Key The key object for the JWK + * + * @throws InvalidArgumentException Provided JWK is empty + * @throws UnexpectedValueException Provided JWK was invalid + * @throws DomainException OpenSSL failure + * + * @uses createPemFromModulusAndExponent + */ + public static function parseKey(#[\SensitiveParameter] array $jwk, ?string $defaultAlg = null): ?Key + { + if (empty($jwk)) { + throw new InvalidArgumentException('JWK must not be empty'); + } + + if (!isset($jwk['kty'])) { + throw new UnexpectedValueException('JWK must contain a "kty" parameter'); + } + + if (!isset($jwk['alg'])) { + if (\is_null($defaultAlg)) { + // The "alg" parameter is optional in a KTY, but an algorithm is required + // for parsing in this library. Use the $defaultAlg parameter when parsing the + // key set in order to prevent this error. + // @see https://datatracker.ietf.org/doc/html/rfc7517#section-4.4 + throw new UnexpectedValueException('JWK must contain an "alg" parameter'); + } + $jwk['alg'] = $defaultAlg; + } + + switch ($jwk['kty']) { + case 'RSA': + if (!empty($jwk['d'])) { + throw new UnexpectedValueException('RSA private keys are not supported'); + } + if (!isset($jwk['n']) || !isset($jwk['e'])) { + throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"'); + } + + $pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']); + $publicKey = \openssl_pkey_get_public($pem); + if (false === $publicKey) { + throw new DomainException( + 'OpenSSL error: ' . \openssl_error_string() + ); + } + return new Key($publicKey, $jwk['alg']); + case 'EC': + if (isset($jwk['d'])) { + // The key is actually a private key + throw new UnexpectedValueException('Key data must be for a public key'); + } + + if (empty($jwk['crv'])) { + throw new UnexpectedValueException('crv not set'); + } + + if (!isset(self::EC_CURVES[$jwk['crv']])) { + if (!\in_array($jwk['crv'], self::KNOWN_UNSUPPORTED_EC_CURVES)) { + throw new DomainException('Unrecognised EC curve'); + } + return null; + } + + if (empty($jwk['x']) || empty($jwk['y'])) { + throw new UnexpectedValueException('x and y not set'); + } + + $publicKey = self::createPemFromCrvAndXYCoordinates($jwk['crv'], $jwk['x'], $jwk['y']); + return new Key($publicKey, $jwk['alg']); + case 'OKP': + if (isset($jwk['d'])) { + // The key is actually a private key + throw new UnexpectedValueException('Key data must be for a public key'); + } + + if (!isset($jwk['crv'])) { + throw new UnexpectedValueException('crv not set'); + } + + if (empty(self::OKP_SUBTYPES[$jwk['crv']])) { + throw new DomainException('Unrecognised or unsupported OKP key subtype'); + } + + if (empty($jwk['x'])) { + throw new UnexpectedValueException('x not set'); + } + + // This library works internally with EdDSA keys (Ed25519) encoded in standard base64. + $publicKey = JWT::convertBase64urlToBase64($jwk['x']); + return new Key($publicKey, $jwk['alg']); + case 'oct': + if (!isset($jwk['k'])) { + throw new UnexpectedValueException('k not set'); + } + + return new Key(JWT::urlsafeB64Decode($jwk['k']), $jwk['alg']); + default: + break; + } + + return null; + } + + /** + * Converts the EC JWK values to pem format. + * + * @param string $crv The EC curve (only P-256 & P-384 is supported) + * @param string $x The EC x-coordinate + * @param string $y The EC y-coordinate + * + * @return string + */ + private static function createPemFromCrvAndXYCoordinates(string $crv, string $x, string $y): string + { + $pem = + self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER( + self::ASN1_OBJECT_IDENTIFIER, + self::encodeOID(self::OID) + ) + . self::encodeDER( + self::ASN1_OBJECT_IDENTIFIER, + self::encodeOID(self::EC_CURVES[$crv]) + ) + ) . + self::encodeDER( + self::ASN1_BIT_STRING, + \chr(0x00) . \chr(0x04) + . JWT::urlsafeB64Decode($x) + . JWT::urlsafeB64Decode($y) + ) + ); + + return \sprintf( + "-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", + wordwrap(base64_encode($pem), 64, "\n", true) + ); + } + + /** + * Create a public key represented in PEM format from RSA modulus and exponent information + * + * @param string $n The RSA modulus encoded in Base64 + * @param string $e The RSA exponent encoded in Base64 + * + * @return string The RSA public key represented in PEM format + * + * @uses encodeLength + */ + private static function createPemFromModulusAndExponent( + string $n, + string $e + ): string { + $mod = JWT::urlsafeB64Decode($n); + $exp = JWT::urlsafeB64Decode($e); + // Correct encoding for ASN1, as ints are represented as unsigned in jwk + // but signed in ASN1. Prepending null byte makes it unsigned. + if (\strlen($mod) > 0 && \ord($mod[0]) >= 128) { + $mod = \chr(0) . $mod; + } + if (\strlen($exp) > 0 && \ord($exp[0]) >= 128) { + $exp = \chr(0) . $exp; + } + + $modulus = \pack('Ca*a*', 2, self::encodeLength(\strlen($mod)), $mod); + $publicExponent = \pack('Ca*a*', 2, self::encodeLength(\strlen($exp)), $exp); + + $rsaPublicKey = \pack( + 'Ca*a*a*', + 48, + self::encodeLength(\strlen($modulus) + \strlen($publicExponent)), + $modulus, + $publicExponent + ); + + // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. + $rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA + $rsaPublicKey = \chr(0) . $rsaPublicKey; + $rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey; + + $rsaPublicKey = \pack( + 'Ca*a*', + 48, + self::encodeLength(\strlen($rsaOID . $rsaPublicKey)), + $rsaOID . $rsaPublicKey + ); + + return "-----BEGIN PUBLIC KEY-----\r\n" . + \chunk_split(\base64_encode($rsaPublicKey), 64) . + '-----END PUBLIC KEY-----'; + } + + /** + * DER-encode the length + * + * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See + * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} + * for more information. + * + * @param int $length + * @return string + */ + private static function encodeLength(int $length): string + { + if ($length <= 0x7F) { + return \chr($length); + } + + $temp = \ltrim(\pack('N', $length), \chr(0)); + + return \pack('Ca*', 0x80 | \strlen($temp), $temp); + } + + /** + * Encodes a value into a DER object. + * Also defined in Firebase\JWT\JWT + * + * @param int $type DER tag + * @param string $value the value to encode + * @return string the encoded object + */ + private static function encodeDER(int $type, string $value): string + { + $tag_header = 0; + if ($type === self::ASN1_SEQUENCE) { + $tag_header |= 0x20; + } + + // Type + $der = \chr($tag_header | $type); + + // Length + $der .= \chr(\strlen($value)); + + return $der . $value; + } + + /** + * Encodes a string into a DER-encoded OID. + * + * @param string $oid the OID string + * @return string the binary DER-encoded OID + */ + private static function encodeOID(string $oid): string + { + $octets = explode('.', $oid); + + // Get the first octet + $first = (int) array_shift($octets); + $second = (int) array_shift($octets); + $oid = \chr($first * 40 + $second); + + // Iterate over subsequent octets + foreach ($octets as $octet) { + if ($octet == 0) { + $oid .= \chr(0x00); + continue; + } + $bin = ''; + + while ($octet) { + $bin .= \chr(0x80 | ($octet & 0x7f)); + $octet >>= 7; + } + $bin[0] = $bin[0] & \chr(0x7f); + + // Convert to big endian if necessary + if (pack('V', 65534) == pack('L', 65534)) { + $oid .= strrev($bin); + } else { + $oid .= $bin; + } + } + + return $oid; + } +} diff --git a/vendor/firebase/php-jwt/src/JWT.php b/vendor/firebase/php-jwt/src/JWT.php new file mode 100644 index 0000000..f9a21e2 --- /dev/null +++ b/vendor/firebase/php-jwt/src/JWT.php @@ -0,0 +1,835 @@ + + * @author Anant Narayanan + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWT +{ + private const ASN1_INTEGER = 0x02; + private const ASN1_SEQUENCE = 0x10; + private const ASN1_BIT_STRING = 0x03; + + private const RSA_KEY_MIN_LENGTH = 2048; + + /** + * When checking nbf, iat or expiration times, + * we want to provide some extra leeway time to + * account for clock skew. + * + * @var int + */ + public static $leeway = 0; + + /** + * Allow the current timestamp to be specified. + * Useful for fixing a value within unit testing. + * Will default to PHP time() value if null. + * + * @var ?int + */ + public static $timestamp = null; + + /** + * @var array + */ + public static $supported_algs = [ + 'ES384' => ['openssl', 'SHA384'], + 'ES256' => ['openssl', 'SHA256'], + 'ES256K' => ['openssl', 'SHA256'], + 'HS256' => ['hash_hmac', 'SHA256'], + 'HS384' => ['hash_hmac', 'SHA384'], + 'HS512' => ['hash_hmac', 'SHA512'], + 'RS256' => ['openssl', 'SHA256'], + 'RS384' => ['openssl', 'SHA384'], + 'RS512' => ['openssl', 'SHA512'], + 'PS256' => ['openssl', 'SHA256'], + 'EdDSA' => ['sodium_crypto', 'EdDSA'] + ]; + + /** + * Decodes a JWT string into a PHP object. + * + * @param string $jwt The JWT + * @param Key|ArrayAccess|array $keyOrKeyArray The Key or associative array of key IDs + * (kid) to Key objects. + * If the algorithm used is asymmetric, this is + * the public key. + * Each Key object contains an algorithm and + * matching key. + * Supported algorithms are 'ES384','ES256', + * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384' + * and 'RS512'. + * @param stdClass $headers Optional. Populates stdClass with headers. + * + * @return stdClass The JWT's payload as a PHP object + * + * @throws InvalidArgumentException Provided key/key-array was empty or malformed + * @throws DomainException Provided JWT is malformed + * @throws UnexpectedValueException Provided JWT was invalid + * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed + * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' + * @throws BeforeValidException Provided JWT is trying to be used before it's + * been created as defined by 'iat' + * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim + * + * @uses jsonDecode + * @uses urlsafeB64Decode + */ + public static function decode( + string $jwt, + #[\SensitiveParameter] $keyOrKeyArray, + ?stdClass &$headers = null + ): stdClass { + // Validate JWT + $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp; + + if (empty($keyOrKeyArray)) { + throw new InvalidArgumentException('Key may not be empty'); + } + $tks = \explode('.', $jwt, 4); + if (\count($tks) !== 3) { + throw new UnexpectedValueException('Wrong number of segments'); + } + list($headb64, $bodyb64, $cryptob64) = $tks; + $headerRaw = static::urlsafeB64Decode($headb64); + if (null === ($header = static::jsonDecode($headerRaw))) { + throw new UnexpectedValueException('Invalid header encoding'); + } + if ($headers !== null) { + $headers = $header; + } + $payloadRaw = static::urlsafeB64Decode($bodyb64); + if (null === ($payload = static::jsonDecode($payloadRaw))) { + throw new UnexpectedValueException('Invalid claims encoding'); + } + if (\is_array($payload)) { + // prevent PHP Fatal Error in edge-cases when payload is empty array + $payload = (object) $payload; + } + if (!$payload instanceof stdClass) { + throw new UnexpectedValueException('Payload must be a JSON object'); + } + if (isset($payload->iat) && !\is_numeric($payload->iat)) { + throw new UnexpectedValueException('Payload iat must be a number'); + } + if (isset($payload->nbf) && !\is_numeric($payload->nbf)) { + throw new UnexpectedValueException('Payload nbf must be a number'); + } + if (isset($payload->exp) && !\is_numeric($payload->exp)) { + throw new UnexpectedValueException('Payload exp must be a number'); + } + + $sig = static::urlsafeB64Decode($cryptob64); + if (empty($header->alg)) { + throw new UnexpectedValueException('Empty algorithm'); + } + if (empty(static::$supported_algs[$header->alg])) { + throw new UnexpectedValueException('Algorithm not supported'); + } + + $key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null); + + // Check the algorithm + if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) { + // See issue #351 + throw new UnexpectedValueException('Incorrect key for this algorithm'); + } + if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) { + // OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures + $sig = self::signatureToDER($sig); + } + if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) { + throw new SignatureInvalidException('Signature verification failed'); + } + + // Check the nbf if it is defined. This is the time that the + // token can actually be used. If it's not yet that time, abort. + if (isset($payload->nbf) && floor($payload->nbf) > ($timestamp + static::$leeway)) { + $ex = new BeforeValidException( + 'Cannot handle token with nbf prior to ' . \date(DateTime::ATOM, (int) floor($payload->nbf)) + ); + $ex->setPayload($payload); + throw $ex; + } + + // Check that this token has been created before 'now'. This prevents + // using tokens that have been created for later use (and haven't + // correctly used the nbf claim). + if (!isset($payload->nbf) && isset($payload->iat) && floor($payload->iat) > ($timestamp + static::$leeway)) { + $ex = new BeforeValidException( + 'Cannot handle token with iat prior to ' . \date(DateTime::ATOM, (int) floor($payload->iat)) + ); + $ex->setPayload($payload); + throw $ex; + } + + // Check if this token has expired. + if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { + $ex = new ExpiredException('Expired token'); + $ex->setPayload($payload); + $ex->setTimestamp($timestamp); + throw $ex; + } + + return $payload; + } + + /** + * Converts and signs a PHP array into a JWT string. + * + * @param array $payload PHP array + * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. + * @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256', + * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' + * @param string $keyId + * @param array $head An array with header elements to attach + * + * @return string A signed JWT + * + * @uses jsonEncode + * @uses urlsafeB64Encode + */ + public static function encode( + array $payload, + #[\SensitiveParameter] $key, + string $alg, + ?string $keyId = null, + ?array $head = null + ): string { + $header = ['typ' => 'JWT']; + if (isset($head)) { + $header = \array_merge($header, $head); + } + $header['alg'] = $alg; + if ($keyId !== null) { + $header['kid'] = $keyId; + } + if (isset($payload['nbf']) && !\is_numeric($payload['nbf'])) { + throw new UnexpectedValueException('Payload nbf must be a number'); + } + if (isset($payload['iat']) && !\is_numeric($payload['iat'])) { + throw new UnexpectedValueException('Payload iat must be a number'); + } + if (isset($payload['exp']) && !\is_numeric($payload['exp'])) { + throw new UnexpectedValueException('Payload exp must be a number'); + } + $segments = []; + $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header)); + $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload)); + $signing_input = \implode('.', $segments); + + $signature = static::sign($signing_input, $key, $alg); + $segments[] = static::urlsafeB64Encode($signature); + + return \implode('.', $segments); + } + + /** + * Sign a string with a given key and algorithm. + * + * @param string $msg The message to sign + * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. + * @param string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256', + * 'HS384', 'HS512', 'RS256', 'RS384', 'PS256' and 'RS512' + * + * @return string An encrypted message + * + * @throws DomainException Unsupported algorithm or bad key was specified + */ + public static function sign( + string $msg, + #[\SensitiveParameter] $key, + string $alg + ): string { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + list($function, $algorithm) = static::$supported_algs[$alg]; + switch ($function) { + case 'hash_hmac': + if (!\is_string($key)) { + throw new InvalidArgumentException('key must be a string when using hmac'); + } + self::validateHmacKeyLength($key, $algorithm); + return \hash_hmac($algorithm, $msg, $key, true); + case 'openssl': + if ($alg === 'PS256') { + return self::signPS256($key, $msg); + } + $signature = ''; + if (!$key = openssl_pkey_get_private($key)) { + throw new DomainException('OpenSSL unable to validate key'); + } + if (str_starts_with($alg, 'RS')) { + self::validateRsaKeyLength($key); + } elseif (str_starts_with($alg, 'ES')) { + self::validateEcKeyLength($key, $alg); + } + $success = \openssl_sign($msg, $signature, $key, $algorithm); + if (!$success) { + throw new DomainException('OpenSSL unable to sign data'); + } + if ($alg === 'ES256' || $alg === 'ES256K') { + $signature = self::signatureFromDER($signature, 256); + } elseif ($alg === 'ES384') { + $signature = self::signatureFromDER($signature, 384); + } + return $signature; + case 'sodium_crypto': + try { + return sodium_crypto_sign_detached($msg, self::validateEdDSAKey($key)); + } catch (Exception $e) { + throw new DomainException($e->getMessage(), 0, $e); + } + } + + throw new DomainException('Algorithm not supported'); + } + + /** + * Verify a signature with the message, key and method. Not all methods + * are symmetric, so we must have a separate verify and sign method. + * + * @param string $msg The original message (header and body) + * @param string $signature The original signature + * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For Ed*, ES*, HS*, a string key works. + * for RS*, must be an instance of OpenSSLAsymmetricKey + * @param string $alg The algorithm + * + * @return bool + * + * @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure + */ + private static function verify( + string $msg, + string $signature, + #[\SensitiveParameter] $keyMaterial, + string $alg + ): bool { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + + list($function, $algorithm) = static::$supported_algs[$alg]; + switch ($function) { + case 'openssl': + if ($alg === 'PS256') { + return self::verifyPS256($keyMaterial, $msg, $signature); + } + if (!$key = openssl_pkey_get_public($keyMaterial)) { + throw new DomainException('OpenSSL unable to validate key'); + } + if (str_starts_with($alg, 'RS')) { + self::validateRsaKeyLength($key); + } elseif (str_starts_with($alg, 'ES')) { + self::validateEcKeyLength($key, $alg); + } + $success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm); + if ($success === 1) { + return true; + } + if ($success === 0) { + return false; + } + // returns 1 on success, 0 on failure, -1 on error. + throw new DomainException( + 'OpenSSL error: ' . \openssl_error_string() + ); + case 'sodium_crypto': + try { + $key = self::validateEdDSAKey($keyMaterial); + if (\strlen($signature) === 0) { + throw new DomainException('Signature cannot be empty string'); + } + return sodium_crypto_sign_verify_detached($signature, $msg, $key); + } catch (Exception $e) { + throw new DomainException($e->getMessage(), 0, $e); + } + case 'hash_hmac': + default: + if (!\is_string($keyMaterial)) { + throw new InvalidArgumentException('key must be a string when using hmac'); + } + self::validateHmacKeyLength($keyMaterial, $algorithm); + $hash = \hash_hmac($algorithm, $msg, $keyMaterial, true); + return self::constantTimeEquals($hash, $signature); + } + } + + /** + * Decode a JSON string into a PHP object. + * + * @param string $input JSON string + * + * @return mixed The decoded JSON string + * + * @throws DomainException Provided string was invalid JSON + */ + public static function jsonDecode(string $input) + { + $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING); + + if ($errno = \json_last_error()) { + self::handleJsonError($errno); + } elseif ($obj === null && $input !== 'null') { + throw new DomainException('Null result with non-null input'); + } + return $obj; + } + + /** + * Encode a PHP array into a JSON string. + * + * @param array $input A PHP array + * + * @return string JSON representation of the PHP array + * + * @throws DomainException Provided object could not be encoded to valid JSON + */ + public static function jsonEncode(array $input): string + { + $json = \json_encode($input, \JSON_UNESCAPED_SLASHES); + if ($errno = \json_last_error()) { + self::handleJsonError($errno); + } elseif ($json === 'null') { + throw new DomainException('Null result with non-null input'); + } + if ($json === false) { + throw new DomainException('Provided object could not be encoded to valid JSON'); + } + return $json; + } + + /** + * Decode a string with URL-safe Base64. + * + * @param string $input A Base64 encoded string + * + * @return string A decoded string + * + * @throws InvalidArgumentException invalid base64 characters + */ + public static function urlsafeB64Decode(string $input): string + { + return \base64_decode(self::convertBase64UrlToBase64($input)); + } + + /** + * Convert a string in the base64url (URL-safe Base64) encoding to standard base64. + * + * @param string $input A Base64 encoded string with URL-safe characters (-_ and no padding) + * + * @return string A Base64 encoded string with standard characters (+/) and padding (=), when + * needed. + * + * @see https://www.rfc-editor.org/rfc/rfc4648 + */ + public static function convertBase64UrlToBase64(string $input): string + { + $remainder = \strlen($input) % 4; + if ($remainder) { + $padlen = 4 - $remainder; + $input .= \str_repeat('=', $padlen); + } + return \strtr($input, '-_', '+/'); + } + + /** + * Encode a string with URL-safe Base64. + * + * @param string $input The string you want encoded + * + * @return string The base64 encode of what you passed in + */ + public static function urlsafeB64Encode(string $input): string + { + return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_')); + } + + /** + * Determine if an algorithm has been provided for each Key + * + * @param Key|ArrayAccess|array $keyOrKeyArray + * @param string|null $kid + * + * @throws UnexpectedValueException + * + * @return Key + */ + private static function getKey( + #[\SensitiveParameter] $keyOrKeyArray, + ?string $kid + ): Key { + if ($keyOrKeyArray instanceof Key) { + return $keyOrKeyArray; + } + + if (empty($kid) && $kid !== '0') { + throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); + } + + if ($keyOrKeyArray instanceof CachedKeySet) { + // Skip "isset" check, as this will automatically refresh if not set + return $keyOrKeyArray[$kid]; + } + + if (!isset($keyOrKeyArray[$kid])) { + throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); + } + + return $keyOrKeyArray[$kid]; + } + + /** + * @param string $left The string of known length to compare against + * @param string $right The user-supplied string + * @return bool + */ + public static function constantTimeEquals(string $left, string $right): bool + { + if (\function_exists('hash_equals')) { + return \hash_equals($left, $right); + } + $len = \min(self::safeStrlen($left), self::safeStrlen($right)); + + $status = 0; + for ($i = 0; $i < $len; $i++) { + $status |= (\ord($left[$i]) ^ \ord($right[$i])); + } + $status |= (self::safeStrlen($left) ^ self::safeStrlen($right)); + + return ($status === 0); + } + + /** + * Helper method to create a JSON error. + * + * @param int $errno An error number from json_last_error() + * + * @throws DomainException + * + * @return void + */ + private static function handleJsonError(int $errno): void + { + $messages = [ + JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON', + JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', + JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3 + ]; + throw new DomainException( + isset($messages[$errno]) + ? $messages[$errno] + : 'Unknown JSON error: ' . $errno + ); + } + + /** + * Get the number of bytes in cryptographic strings. + * + * @param string $str + * + * @return int + */ + private static function safeStrlen(string $str): int + { + if (\function_exists('mb_strlen')) { + return \mb_strlen($str, '8bit'); + } + return \strlen($str); + } + + /** + * Convert an ECDSA signature to an ASN.1 DER sequence + * + * @param string $sig The ECDSA signature to convert + * @return string The encoded DER object + */ + private static function signatureToDER(string $sig): string + { + // Separate the signature into r-value and s-value + $length = max(1, (int) (\strlen($sig) / 2)); + list($r, $s) = \str_split($sig, $length); + + // Trim leading zeros + $r = \ltrim($r, "\x00"); + $s = \ltrim($s, "\x00"); + + // Convert r-value and s-value from unsigned big-endian integers to + // signed two's complement + if (\ord($r[0]) > 0x7f) { + $r = "\x00" . $r; + } + if (\ord($s[0]) > 0x7f) { + $s = "\x00" . $s; + } + + return self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER(self::ASN1_INTEGER, $r) . + self::encodeDER(self::ASN1_INTEGER, $s) + ); + } + + /** + * Encodes a value into a DER object. + * + * @param int $type DER tag + * @param string $value the value to encode + * + * @return string the encoded object + */ + private static function encodeDER(int $type, string $value): string + { + $tag_header = 0; + if ($type === self::ASN1_SEQUENCE) { + $tag_header |= 0x20; + } + + // Type + $der = \chr($tag_header | $type); + + // Length + $der .= \chr(\strlen($value)); + + return $der . $value; + } + + /** + * Encodes signature from a DER object. + * + * @param string $der binary signature in DER format + * @param int $keySize the number of bits in the key + * + * @return string the signature + */ + private static function signatureFromDER(string $der, int $keySize): string + { + // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE + list($offset, $_) = self::readDER($der); + list($offset, $r) = self::readDER($der, $offset); + list($offset, $s) = self::readDER($der, $offset); + + // Convert r-value and s-value from signed two's compliment to unsigned + // big-endian integers + $r = \ltrim($r, "\x00"); + $s = \ltrim($s, "\x00"); + + // Pad out r and s so that they are $keySize bits long + $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT); + $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT); + + return $r . $s; + } + + /** + * Reads binary DER-encoded data and decodes into a single object + * + * @param string $der the binary data in DER format + * @param int $offset the offset of the data stream containing the object + * to decode + * + * @return array{int, string|null} the new offset and the decoded object + */ + private static function readDER(string $der, int $offset = 0): array + { + $pos = $offset; + $size = \strlen($der); + $constructed = (\ord($der[$pos]) >> 5) & 0x01; + $type = \ord($der[$pos++]) & 0x1f; + + // Length + $len = \ord($der[$pos++]); + if ($len & 0x80) { + $n = $len & 0x1f; + $len = 0; + while ($n-- && $pos < $size) { + $len = ($len << 8) | \ord($der[$pos++]); + } + } + + // Value + if ($type === self::ASN1_BIT_STRING) { + $pos++; // Skip the first contents octet (padding indicator) + $data = \substr($der, $pos, $len - 1); + $pos += $len - 1; + } elseif (!$constructed) { + $data = \substr($der, $pos, $len); + $pos += $len; + } else { + $data = null; + } + + return [$pos, $data]; + } + + /** + * Validate HMAC key length + * + * @param string $key HMAC key material + * @param string $algorithm The algorithm + * + * @throws DomainException Provided key is too short + */ + private static function validateHmacKeyLength(string $key, string $algorithm): void + { + $keyLength = \strlen($key) * 8; + $minKeyLength = (int) \str_replace('SHA', '', $algorithm); + if ($keyLength < $minKeyLength) { + throw new DomainException('Provided key is too short'); + } + } + + /** + * Validate RSA key length + * + * @param OpenSSLAsymmetricKey $key RSA key material + * @throws DomainException Provided key is too short + */ + private static function validateRsaKeyLength(#[\SensitiveParameter] OpenSSLAsymmetricKey $key): void + { + if (!$keyDetails = openssl_pkey_get_details($key)) { + throw new DomainException('Unable to validate key'); + } + if ($keyDetails['bits'] < self::RSA_KEY_MIN_LENGTH) { + throw new DomainException('Provided key is too short'); + } + } + + /** + * Validate RSA key length + * + * @param OpenSSLAsymmetricKey $key RSA key material + * @param string $algorithm The algorithm + * @throws DomainException Provided key is too short + */ + private static function validateEcKeyLength( + #[\SensitiveParameter] OpenSSLAsymmetricKey $key, + string $algorithm + ): void { + if (!$keyDetails = openssl_pkey_get_details($key)) { + throw new DomainException('Unable to validate key'); + } + $minKeyLength = (int) \str_replace('ES', '', $algorithm); + if ($keyDetails['bits'] < $minKeyLength) { + throw new DomainException('Provided key is too short'); + } + } + + /** + * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial + * @return non-empty-string + */ + private static function validateEdDSAKey(#[\SensitiveParameter] $keyMaterial): string + { + if (!\function_exists('sodium_crypto_sign_verify_detached')) { + throw new DomainException('libsodium is not available'); + } + if (!\is_string($keyMaterial)) { + throw new InvalidArgumentException('key must be a string when using EdDSA'); + } + // The last non-empty line is used as the key. + $lines = array_filter(explode("\n", $keyMaterial)); + $key = self::urlsafeB64Decode((string) end($lines)); + if (\strlen($key) === 0) { + throw new DomainException('Key cannot be empty string'); + } + return $key; + } + + /** + * Signs a message with a PS256 algorithm + * + * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key + * @param string $message + * @throws DomainException Provided key is invalid + */ + private static function signPS256( + #[\SensitiveParameter] string|OpenSSLAsymmetricKey|OpenSSLCertificate $key, + string $message + ): string { + if (!class_exists('\phpseclib3\Crypt\RSA')) { + throw new DomainException('phpseclib/phpseclib is required for PS256 support'); + } + + if ($key instanceof OpenSSLCertificate) { + throw new DomainException('Cannot sign with an X.509 certificate. A private key is required.'); + } + + if ($key instanceof OpenSSLAsymmetricKey) { + if (!openssl_pkey_export($key, $pem)) { + throw new DomainException('OpenSSL unable to export the AsymmetricKey'); + } + $key = $pem; + } + + /** @var \phpseclib3\Crypt\RSA\PrivateKey $rsa */ + $rsa = \phpseclib3\Crypt\PublicKeyLoader::load($key); + + return $rsa->withPadding(\phpseclib3\Crypt\RSA::SIGNATURE_PSS) + ->withHash('sha256') + ->sign($message); + } + + /** + * Validates a PS256 algorithm signature. + * + * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key + * @param string $message + * @param string $signature + * @throws DomainException Provided key is invalid + */ + private static function verifyPS256( + #[\SensitiveParameter] string|OpenSSLAsymmetricKey|OpenSSLCertificate $key, + string $message, + string $signature + ): bool { + if (!class_exists('\phpseclib3\Crypt\RSA')) { + throw new DomainException('phpseclib/phpseclib is required for PS256 support'); + } + + if ($key instanceof OpenSSLAsymmetricKey) { + $details = openssl_pkey_get_details($key); + if (!$details || !isset($details['key'])) { + throw new DomainException('OpenSSL unable to extract public key'); + } + $key = $details['key']; + } elseif ($key instanceof OpenSSLCertificate) { + if (!openssl_x509_export($key, $pem)) { + throw new DomainException('OpenSSL unable to export certificate'); + } + $key = $pem; + } + + /** @var \phpseclib3\Crypt\RSA\PublicKey $rsa */ + $rsa = \phpseclib3\Crypt\PublicKeyLoader::load($key); + + return $rsa->withPadding(\phpseclib3\Crypt\RSA::SIGNATURE_PSS) + ->withHash('sha256') + ->verify($message, $signature); + } +} diff --git a/vendor/firebase/php-jwt/src/JWTExceptionWithPayloadInterface.php b/vendor/firebase/php-jwt/src/JWTExceptionWithPayloadInterface.php new file mode 100644 index 0000000..7933ed6 --- /dev/null +++ b/vendor/firebase/php-jwt/src/JWTExceptionWithPayloadInterface.php @@ -0,0 +1,20 @@ +algorithm; + } + + /** + * @return string|OpenSSLAsymmetricKey|OpenSSLCertificate + */ + public function getKeyMaterial() + { + return $this->keyMaterial; + } +} diff --git a/vendor/firebase/php-jwt/src/SignatureInvalidException.php b/vendor/firebase/php-jwt/src/SignatureInvalidException.php new file mode 100644 index 0000000..d35dee9 --- /dev/null +++ b/vendor/firebase/php-jwt/src/SignatureInvalidException.php @@ -0,0 +1,7 @@ + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/graham-campbell/result-type/composer.json b/vendor/graham-campbell/result-type/composer.json new file mode 100644 index 0000000..ff99240 --- /dev/null +++ b/vendor/graham-campbell/result-type/composer.json @@ -0,0 +1,33 @@ +{ + "name": "graham-campbell/result-type", + "description": "An Implementation Of The Result Type", + "keywords": ["result", "result-type", "Result", "Result Type", "Result-Type", "Graham Campbell", "GrahamCampbell"], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "phpoption/phpoption": "^1.10" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.52 || ^9.6.34 || ^10.5.63 || ^11.5.55 || ^12.5.14" + }, + "autoload": { + "psr-4": { + "GrahamCampbell\\ResultType\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GrahamCampbell\\Tests\\ResultType\\": "tests/" + } + }, + "config": { + "preferred-install": "dist" + } +} diff --git a/vendor/graham-campbell/result-type/src/Error.php b/vendor/graham-campbell/result-type/src/Error.php new file mode 100644 index 0000000..1a547e2 --- /dev/null +++ b/vendor/graham-campbell/result-type/src/Error.php @@ -0,0 +1,119 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace GrahamCampbell\ResultType; + +use PhpOption\None; +use PhpOption\Some; + +/** + * @template-covariant E + * + * @extends \GrahamCampbell\ResultType\Result + */ +final class Error extends Result +{ + /** + * @var E + */ + private $value; + + /** + * Internal constructor for an error value. + * + * @param E $value + * + * @return void + */ + private function __construct($value) + { + $this->value = $value; + } + + /** + * Create a new error value. + * + * @template F + * + * @param F $value + * + * @return \GrahamCampbell\ResultType\Error + */ + public static function create($value) + { + return new self($value); + } + + /** + * Get the success option value. + * + * @return \PhpOption\Option + */ + public function success() + { + return None::create(); + } + + /** + * Map over the success value. + * + * @template S + * + * @param callable(never):S $f + * + * @return \GrahamCampbell\ResultType\Error + */ + public function map(callable $f) + { + return self::create($this->value); + } + + /** + * Flat map over the success value. + * + * @template S + * @template F + * + * @param callable(never):\GrahamCampbell\ResultType\Result $f + * + * @return \GrahamCampbell\ResultType\Error + */ + public function flatMap(callable $f) + { + return self::create($this->value); + } + + /** + * Get the error option value. + * + * @return \PhpOption\Option + */ + public function error() + { + return Some::create($this->value); + } + + /** + * Map over the error value. + * + * @template F + * + * @param callable(E):F $f + * + * @return \GrahamCampbell\ResultType\Error + */ + public function mapError(callable $f) + { + return self::create($f($this->value)); + } +} diff --git a/vendor/graham-campbell/result-type/src/Result.php b/vendor/graham-campbell/result-type/src/Result.php new file mode 100644 index 0000000..8545067 --- /dev/null +++ b/vendor/graham-campbell/result-type/src/Result.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace GrahamCampbell\ResultType; + +/** + * @template-covariant T + * @template-covariant E + */ +abstract class Result +{ + /** + * Get the success option value. + * + * @return \PhpOption\Option + */ + abstract public function success(); + + /** + * Map over the success value. + * + * @template S + * + * @param callable(T):S $f + * + * @return \GrahamCampbell\ResultType\Result + */ + abstract public function map(callable $f); + + /** + * Flat map over the success value. + * + * @template S + * @template F + * + * @param callable(T):\GrahamCampbell\ResultType\Result $f + * + * @return \GrahamCampbell\ResultType\Result + */ + abstract public function flatMap(callable $f); + + /** + * Get the error option value. + * + * @return \PhpOption\Option + */ + abstract public function error(); + + /** + * Map over the error value. + * + * @template F + * + * @param callable(E):F $f + * + * @return \GrahamCampbell\ResultType\Result + */ + abstract public function mapError(callable $f); +} diff --git a/vendor/graham-campbell/result-type/src/Success.php b/vendor/graham-campbell/result-type/src/Success.php new file mode 100644 index 0000000..4dfb7d2 --- /dev/null +++ b/vendor/graham-campbell/result-type/src/Success.php @@ -0,0 +1,119 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace GrahamCampbell\ResultType; + +use PhpOption\None; +use PhpOption\Some; + +/** + * @template-covariant T + * + * @extends \GrahamCampbell\ResultType\Result + */ +final class Success extends Result +{ + /** + * @var T + */ + private $value; + + /** + * Internal constructor for a success value. + * + * @param T $value + * + * @return void + */ + private function __construct($value) + { + $this->value = $value; + } + + /** + * Create a new success value. + * + * @template S + * + * @param S $value + * + * @return \GrahamCampbell\ResultType\Success + */ + public static function create($value) + { + return new self($value); + } + + /** + * Get the success option value. + * + * @return \PhpOption\Option + */ + public function success() + { + return Some::create($this->value); + } + + /** + * Map over the success value. + * + * @template S + * + * @param callable(T):S $f + * + * @return \GrahamCampbell\ResultType\Success + */ + public function map(callable $f) + { + return self::create($f($this->value)); + } + + /** + * Flat map over the success value. + * + * @template S + * @template F + * + * @param callable(T):\GrahamCampbell\ResultType\Result $f + * + * @return \GrahamCampbell\ResultType\Result + */ + public function flatMap(callable $f) + { + return $f($this->value); + } + + /** + * Get the error option value. + * + * @return \PhpOption\Option + */ + public function error() + { + return None::create(); + } + + /** + * Map over the error value. + * + * @template F + * + * @param callable(never):F $f + * + * @return \GrahamCampbell\ResultType\Success + */ + public function mapError(callable $f) + { + return self::create($this->value); + } +} diff --git a/vendor/guzzlehttp/guzzle/AGENTS.md b/vendor/guzzlehttp/guzzle/AGENTS.md new file mode 100644 index 0000000..564546f --- /dev/null +++ b/vendor/guzzlehttp/guzzle/AGENTS.md @@ -0,0 +1,76 @@ +# Agent Guidelines + +## Code and tooling + +- All code must remain compatible with PHP 7.4. Run PHPStan and PHP-CS-Fixer + only under a PHP 7.4.x runtime; never run either tool under any other PHP + major.minor version. +- Use fully qualified `#[\SensitiveParameter]` on concrete executable + parameters when their established role normally carries a secret, + credential-bearing aggregate, or confidential Guzzle-owned container, and + the active frame can throw or invoke throwing code. +- Repeat the attribute on every qualifying owned caller, callee, concrete trait + method, and closure parameter. Do not add it to interfaces, abstract-only + declarations, pure/no-realistic-throw helpers, assignment-only sites, + arbitrary generic payloads, or completed non-recoverable derivatives. +- For PHP 7.4 compatibility, put `#[\SensitiveParameter]` on its own line and + the parameter on the following line, expand the complete parameter list, and + never add a comma after the final parameter. Native trace redaction starts on + PHP 8.2 and does not redact logs, messages, properties, wire traffic, captured + variables, return values, or the separate backtrace `$this`/`object`. +- Always pass an explicit character list to `trim()`, `ltrim()`, and `rtrim()`; + never rely on the default characters. +- Handle `preg_*` engine failures: when the result is used as data, test for + `false` or `null` and throw a `\RuntimeException` including + `preg_last_error_msg()`; boolean validation guards must compare strictly, such + as `=== 1`, so an engine failure can only ever fail closed. Diagnostic + escaping is the narrow exception: use a deterministic bytewise fallback rather + than throwing, so it cannot obscure the original exception. +- Anchor validation patterns to the true end of input with the `D` modifier or + `\z`; a bare `$` accepts a trailing newline. +- Never embed raw control bytes in exception messages and other diagnostics; + escape or redact the offending value first. +- Helper classes that expose only public static methods are `final` and have a + private constructor. +- Resist native PHP serialization when a class holds live state (streams, + resources, handles, callbacks, credentials) or when magic methods such as + `__destruct()` have side effects that untrusted unserialized data could + redirect, as with the file and session write fixes in Guzzle's persisting + cookie jars. Plain data holders, such as Guzzle's in-memory cookie jar, remain + serializable. +- To resist, `__serialize()` and `__unserialize()` both throw + `\LogicException(static::class.' should never be serialized')` and its + unserialized counterpart, usually via the `@internal` `NonSerializableTrait`. + Where a `__destruct()` has such a side effect, it is enabled only by the + constructor and disabled in `__wakeup()` and `__unserialize()` before + throwing, so the protection holds even if the exception is swallowed. +- In general, numeric inputs should not accept non-finite floats. In situations + where they are accepted and we need to cast to a string, we should branch on + `\is_finite($value)`, using `(string) $value` for the finite case and + `\is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')` otherwise. +- Never call `strtolower()`, `strtoupper()`, `strcasecmp()`, `stripos()`, or + other locale-sensitive case functions; use the locale-independent + `GuzzleHttp\Psr7\Utils::asciiToLower()`, `asciiToUpper()`, + `caselessEquals()`, and `caselessContains()` helpers instead. +- Changes in behavior need a `CHANGELOG.md` entry in the unreleased section of + the target branch and an `UPGRADING.md` note when the behavior differs between + major versions. + +## Contributor references + +- Read the [exception guidelines](docs/contributing/exception-guidelines.md) + before deciding which exception a change should throw. +- Read the + [cURL connection reuse reference](docs/contributing/curl-connection-reuse.md) + before working on the cURL handlers or connection reuse and sharing behavior. + +## Documentation + +- Wrap markdown prose and PHPDoc text to 80 columns using greedy wrapping. Never + split a markdown link or an inline code span across a line break; a line that + cannot be broken may exceed the limit. Avoid em dashes. +- Keep PHPDoc and the corresponding `docs/` pages in sync: shared prose is + deliberately word-for-word identical, including boilerplate copied verbatim + between related functions, so apply the same edit to every copy. Only + formatting and linking may differ, such as a docs link becoming a PHPDoc + `@see` tag; the wording must never drift. diff --git a/vendor/guzzlehttp/guzzle/CHANGELOG.md b/vendor/guzzlehttp/guzzle/CHANGELOG.md new file mode 100644 index 0000000..15ae95b --- /dev/null +++ b/vendor/guzzlehttp/guzzle/CHANGELOG.md @@ -0,0 +1,2403 @@ +# Change Log + +Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. + + +## 8.5.5 - 2026-11-21 + +### Security + +- Reject hosts that `idn_conversion` converts to an invalid host (GHSA-2g6w-c7gx-fxj8) +- Reject invalid hosts before parsing a URI string again (GHSA-2g6w-c7gx-fxj8) + + +## 8.5.4 - 2026-11-20 + +### Security + +- Reject proxy credentials with percent-encoded control characters in the cURL handlers (GHSA-q8h8-pjjq-cq2h) +- Reject malformed proxy URLs that older libcurl silently skips or misreads (GHSA-q8h8-pjjq-cq2h) + + +## 8.5.3 - 2026-11-20 + +### Fixed + +- Reject hosts longer than 4096 bytes when `idn_conversion` is enabled +- Fix `idn_conversion` failures escaping as `IntlException` or a PSR-7 exception +- Stop servers from raising the `guzzlehttp/psr7` host deprecation + +### Changed + +- Adjusted `guzzlehttp/promises` version constraint to `^3.1.1` +- Adjusted `guzzlehttp/psr7` version constraint to `^3.5.1` + + +## 8.5.2 - 2026-11-17 + +### Security + +- Exclude URI fragments from stream handler request targets (GHSA-gqx6-m769-3x35) + + +## 8.5.1 - 2026-11-17 + +### Fixed + +- Cancel cURL multi transfers whose synchronous wait throws instead of leaving them running +- Reject CR, LF, and NUL in request header fields in the built-in handlers +- Reject CR, LF, and NUL in request methods in the built-in handlers + + +## 8.5.0 - 2026-11-13 + +### Added + +- Add `Utils::setDefaultHandlerFactory()` to replace the default handler + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^3.4` + +### Deprecated + +- Deprecated `Utils::defaultUserAgent()` in favor of `ClientInterface::MAJOR_VERSION` +- Deprecated `Utils::headersFromLines()`, `Utils::normalizeHeaderKeys()`, `Utils::debugResource()`, and `Utils::normalizeProtocols()` + + +## 8.4.0 - 2026-11-12 + +### Added + +- Add `max_idle_handles` client and cURL handler option to limit idle handles + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^3.3` +- Send longer-path cookies first in the `Cookie` header, like browsers and libcurl +- Replace stored cookies in place so a refreshed cookie keeps its position in the `Cookie` header + +### Fixed + +- Fix overlapping stream handler transfers swallowing and mixing up PHP errors +- Fix the stream handler sending an empty `From` header with no `from` ini set + + +## 8.3.2 - 2026-11-12 + +### Fixed + +- Fix overlapping stream handler transfers leaving the `from` ini setting blank + + +## 8.3.1 - 2026-10-25 + +### Fixed + +- Fix `CookieJar` storing already expired cookies instead of removing the stored cookie +- Fix `CookieJar` ignoring a same-value cookie that changes its expiry or its `Discard`, `Secure`, or `HttpOnly` flag +- Fix `SetCookie` renewing the lifetime of `Max-Age` cookies rebuilt from an array, so persisted cookies never expired + + +## 8.3.0 - 2026-10-18 + +### Changed + +- Adjusted `guzzlehttp/promises` version constraint to `^3.1` +- Adjusted `guzzlehttp/psr7` version constraint to `^3.2` +- Replace the deprecated `Promise\Is` with `Promise\State` for PHP 8.6 +- Decode chunked stream handler bodies as they arrive, ending at the last chunk +- Reject truncated and malformed chunked stream handler bodies, like libcurl +- Reject unsupported response transfer codings, like libcurl 8.14+ +- End stream handler bodies at their declared `Content-Length`, including `0` +- Throw when a streamed body ends before its declared `Content-Length` +- Classify cURL errors 8 and 23 with a response as `ResponseTransferException` +- Reject stream handler gzip and deflate bodies with trailing data, like libcurl +- Accept raw deflate stream handler bodies, like libcurl + +### Fixed + +- Fix streamed stream handler bodies delaying bytes that arrived with the headers + + +## 8.2.1 - 2026-10-18 + +### Fixed + +- Fix PHP 8.6 notices for oversized numeric hosts +- Fix `delay` values over 71 minutes +- Fix `CurlMultiHandler` delays over 71 minutes +- Fix overlapping stream handler requests sharing a deadline +- Fix stream handler responses in Swoole coroutines on PHP 8.4+ +- Fix reads of streamed gzip and deflate responses waiting for 8 KiB of decoded data +- Fix stream handler accepting corrupt gzip and deflate response bodies + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^3.1.1` + + +## 8.2.0 - 2026-09-06 + +### Changed + +- Allow connection caps to be combined with persistent transport sharing on libcurl 8.22.0+ + + +## 8.1.0 - 2026-08-24 + +### Added + +- Add PHP 8.6+ stream TLS session sharing, while persistent sharing remains cURL-only +- Add support for PHP 8.6 +- Add in-transfer resends of seekable streamed uploads when PHP exposes `CURLOPT_SEEKFUNCTION` + +### Changed + +- Adjusted `guzzlehttp/promises` version constraint to `^3.0.2` +- Adjusted `guzzlehttp/psr7` version constraint to `^3.1` +- Classify stream handler transport failures using PHP 8.6+ structured stream error codes +- Hide URI credentials, queries, and fragments in automatic exception messages +- Match `no_proxy` rules against IPv4 hosts written in the shorthand a transport reads as an address +- Hold the cURL easy handle out of the reuse pool until a silent retry has been dispatched +- Treat a deferred resolved with a pending retry promise as progress when waiting on cURL transfers + + +## 8.0.3 - 2026-08-24 + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^3.0.1` + + +## 8.0.2 - 2026-08-05 + +### Changed + +- Adjusted `guzzlehttp/promises` version constraint to `^3.0.1` + +### Fixed + +- Fail a cURL multi handler wait with an attributable error when the transfer is no longer tracked +- Fix `StreamHandler` resolving numeric IPv4 hosts differently from cURL handlers on macOS and Windows +- Fix `StreamHandler` TLS peer names and proxy authorities for numeric IPv4 hosts on all platforms +- Settle a cURL multi handler transfer displaced by a request reusing its native handle ID + + +## 8.0.1 - 2026-07-26 + +### Security + +- Reject request URI hosts and `Host` header values that are not printable ASCII (GHSA-v5mv-p594-2x33) +- Reject URI hosts with a percent escape or that are not valid RFC 3986 hosts (GHSA-v5mv-p594-2x33) +- Reject numeric-looking URI hosts with trailing dots, read as IPv4 addresses (GHSA-v5mv-p594-2x33) +- Treat percent-escaped cookie domains as exact-match-only (GHSA-f7vp-7xgx-4w4r) +- Regenerate a derived `Host` header after client URI rewrites (GHSA-v5mv-p594-2x33) + + +## 8.0.0 - 2026-07-20 + +### Added + +- Add `SensitiveParameter` metadata to credential-bearing parameters so PHP 8.2+ redacts their values in exception traces +- Add HTTP/3 request support to the built-in cURL handlers when PHP 8.4+ and libcurl provide HTTP/3 support +- Add `Multiplexing::NONE` support as a client, cURL multi handler, and conditional request option +- Add generic and structured PHPDoc annotations to client request/config option, async promise, handler, middleware, pool, and mock handler APIs +- Add `ConnectTimeoutException` for connect-phase timeouts, extending `ConnectException` +- Add `NetworkException` for no-response network failures +- Add `NetworkTimeoutException` for no-response transport timeouts +- Add `ResponseTransferException`, with `ResponseTimeoutException` for response-transfer timeouts +- Add PSR-17 `request_factory`, `response_factory`, `stream_factory`, and `uri_factory` request options +- Add explicit `close()` lifecycle methods to the built-in cURL handlers and concrete cURL factory +- Add `HandlerClosedException` for pending transfers rejected by `CurlMultiHandler::close()` +- Add persistent transport sharing modes (`TransportSharing::PERSISTENT_PREFER` and `TransportSharing::PERSISTENT_REQUIRE`) +- Add `ProxyOptions` for proxy option resolution +- Add `ResponseException` for request failures with responses +- Add auth middleware for built-in Basic and Digest authentication + +### Changed + +- Canonicalize IPv6 hosts in Digest challenge cache keys +- Canonicalize IPv6 hosts in cookie domains, host-only identities, and domain matching +- Restrict cookie domain suffix matching to valid non-literal, nonnumeric host names +- Reject Secure cookies and insecure overlays received over insecure connections +- Enforce the `__Secure-` and `__Host-` prefix requirements on response cookies +- Hardened `FileCookieJar` and `SessionCookieJar` persistence against unsafe unserialization +- Reject native PHP serialization of runtime objects +- Restrict persisted `FileCookieJar` cookie files to owner-only permissions +- Require persisted cookie data to use JSON lists and construct all records before changing the jar +- Normalize persistent cookie JSON failures as `RuntimeException` +- Moved the internal `Utils` time, timeout, IDN, and environment helpers to dedicated internal classes +- Adjusted `guzzlehttp/promises` version constraint to `^3.0` +- Adjusted `guzzlehttp/psr7` version constraint to `^3.0` +- Quote multipart `Content-Type` boundary parameters when required +- Added parameter and return types to `SetCookie` methods +- Added native property types to supported public cURL handler state properties +- Added a `string` return type to `SetCookie::__toString()` +- Validate proxy and no-proxy option types strictly across handlers +- Match leading-dot no-proxy entries against the bare domain and split string no-proxy lists on whitespace +- Validate `force_ip_resolve`, protocols, and `delay` ranges at the client boundary +- Treat a matching proxy `no` entry as final even without a scheme-specific proxy entry +- Validate proxy URLs in the built-in handlers and reject malformed or unsupported ones up front +- Default a port-less proxy to 1080 in the stream handler, matching libcurl +- Downgrade HTTP/3 requests to HTTP/2 or HTTP/1.1 when the proxy is resolved from environment variables +- Throw `RequestException`, not `InvalidArgumentException`, for an unavailable proxy or TLS feature +- Resolve proxy environment variables in the stream handler, consistent with the cURL handlers +- Honor `no_proxy`/`NO_PROXY` from the environment in the stream handler, including `*` to disable proxying +- Reject an environment-resolved `https://` or SOCKS proxy in the stream handler, matching its `proxy` option behavior +- Require cURL proxy header separation for first-class `Proxy-Authorization` on every route +- Reject every first-class `Proxy-Authorization` field, including empty, on stream proxies +- Reject raw `CURLOPT_PROXYHEADER` without proxy header separation support +- Pass the request as the second argument to `on_headers` callbacks +- Pass the `Pool` iterable key as a trailing argument to per-request observer callbacks +- Declare strict types across remaining source files +- Reject request option values that do not match their documented types +- Reject invalid `idn_conversion`, `retries`, and built-in handler `on_stats` option values before use +- Reject non-finite floats in the `query` and `form_params` options +- Reject non-string scalar values in the `body` option +- Apply automatic `Expect: 100-Continue` injection to HTTP/1.1 requests only +- Reject invalid `SetCookie` constructor field types instead of coercing them +- Validate and normalize request framing across the built-in cURL and stream handlers +- Reject raw cURL request options outside the built-in cURL handlers' allow-list +- Reject non-string raw cURL header-list entries before applying them +- Reject proxy tunnels that require fresh connections when persistent transport sharing requires reuse +- Reject PHP stream context options outside the built-in stream handler allow-list +- Reject selected request options ignored by incompatible built-in handlers +- Treat only `null` as an omitted path or name when clearing cookies +- Validate malformed `auth` request option arrays +- Reject colons in built-in Basic usernames and ASCII control characters in Basic credentials +- Move built-in Basic and Digest authentication handling to the default auth middleware +- Reject unchallenged Digest probes for body-bearing requests instead of replaying the request unauthenticated +- Reject malformed Digest challenge parameter lists that libcurl's Digest parser may have tolerated +- Reuse Digest challenges to authorize subsequent body-less requests preemptively +- Advance the Digest nonce count when a stale challenge repeats the same nonce during the initial handshake +- Remove first-class NTLM authentication from the `auth` request option +- Stop forwarding the generic `auth` request option when following cross-origin redirects +- Limit the `Referer` header to the origin on cross-origin redirects +- Follow only redirect status codes 301, 302, 303, 307, and 308 +- Reject invalid `HandlerStack::remove()` arguments +- Require `Pool` request collections to be iterable +- Raised the built-in cURL handler floor to libcurl 7.34.0 with SSL support +- Store response cookies without a `Domain` attribute as host-only cookies +- Prefer cookie `Max-Age` over `Expires` when both attributes are present +- Match cookie names case-sensitively in `CookieJar::getCookieByName()` +- Ignore float-like or exponent `Max-Age` cookie values instead of truncating them +- Tighten invalid response handling and avoid exposing response-derived cURL stats +- Reject malformed response protocol versions and reason phrases +- Escape controls and malformed UTF-8 when copying raw values into exception messages +- Reject malformed or conflicting response `Content-Length` and combinations with `Transfer-Encoding` +- Expose raw stream-handler `Transfer-Encoding` metadata and coalesced framing in `progress` on newer PHP +- Wrap malformed redirect `Location` values in `BadResponseException` +- Default HTTPS requests sent by the built-in cURL and stream handlers to TLS 1.2 or newer +- Apply the stream handler `crypto_method` option through the SSL context so it consistently controls the minimum TLS version +- Validate built-in handler timeout options before applying them +- Require a request when constructing `TransferException` and its subclasses +- Classify empty, malformed, or handler-unsupported request protocol versions as request exceptions +- Classify additional cURL transport failures without a response as `NetworkException` +- Classify stream connect failures as `ConnectException`, with connect timeouts as `ConnectTimeoutException` +- Classify stream transport failures without a response as `NetworkException`, with timeouts as `NetworkTimeoutException` +- Classify generic response-aware request failures as `ResponseException` +- Classify response-aware transfer failures as `ResponseTransferException` +- The stream handler returns an empty body and releases the connection at the end of the headers for HEAD and CONNECT-2xx exchanges and 1xx, 204, and 304 responses +- The stream handler no longer writes to the `sink` option or reads trailing bytes for responses that cannot carry a body +- Reject short buffered stream-handler bodies against `Content-Length`, including decoded gzip/deflate +- Normalize duplicate `Content-Length` casings and preserve encoded values on decoded responses +- Reject unrepresentable byte counts and response sizes requiring integer bounds as `ResponseException` +- Ignore cURL informational responses other than `101 Switching Protocols` before the final response +- Treat response sink rewind failures as `ResponseException` and skip non-seekable sink rewinds +- Classify redirect request-body rewind failures as `ResponseException` +- Ignore stream source close failures after a complete response body transfer +- Throw `GuzzleHttp\Exception\InvalidArgumentException` for invalid built-in handler options +- Classify built-in cURL handle, `sink`, and HTTP/3 setup failures as `RequestException` +- Throw `ConnectTimeoutException` for connect timeouts +- Throw `NetworkTimeoutException` for cURL no-response timeout errors +- Throw `ResponseTimeoutException` for response-aware transfer timeouts +- Enforce the `timeout` option as a total transfer deadline in the stream handler when it buffers the response +- Reject stream handler responses whose header block arrives after the `timeout` deadline +- Stop consulting the `default_socket_timeout` ini setting in the stream handler +- Treat stream handler `read_timeout` as an idle timeout for every request stage, defaulting to 60 seconds +- Default the cURL connect timeout to 60 seconds, with `connect_timeout` set to `0` disabling it +- Stop the stream handler from injecting `User-Agent` and `From` header values from the `user_agent` and `from` ini settings +- Classify request-body stream size detection, read, stringification, and rewind failures as `RequestException` or `ResponseException` by phase +- Classify cURL response sink write failures, including timeouts, as `ResponseException` or `RequestException` by phase +- Treat request method names case-sensitively in built-in handler and redirect method-specific behavior +- Treat PHP resources passed as `sink` as caller-owned in the built-in cURL and stream handlers +- Use the configured PSR-17 URI factory when parsing redirect `Location` headers +- Allow built-in cURL handler `progress` callbacks to abort transfers with truthy return values +- Normalize built-in handler `progress` callback arguments to integer byte counts +- Reject built-in cURL `progress` throwables with `ResponseException` when a response exists, otherwise `RequestException` +- Release built-in cURL easy handles before invoking `on_stats` +- Prefer `CURLOPT_XFERINFOFUNCTION` for built-in cURL progress callbacks when available +- Made `MessageFormatter` final and required `Middleware::log()` formatters to implement `MessageFormatterInterface` +- Made `CurlFactory`, `CurlHandler`, `CurlMultiHandler`, `MockHandler`, and `StreamHandler` final +- Made static utility classes non-instantiable and declared `GuzzleHttp\Handler\Proxy` final +- Pass the request to `on_trailers` callbacks, reject non-callable `on_trailers` values, and wrap `on_trailers` callback exceptions in `ResponseException` +- Wait for in-progress HTTP/2-capable connections by default (`multiplex` defaults to `Multiplexing::WAIT`) +- Require libcurl 7.65.2 or newer for HTTP/2 requests so multiplex waiting is never silently unavailable +- Require libcurl 7.54.0 for HTTPS proxies and requests tunneled through HTTP proxies +- Suppress proxy CONNECT response headers for tunneled requests +- Point rejections of the raw `CURLOPT_PIPEWAIT` cURL option at the `multiplex` request option +- Reject raw `CURLMOPT_PIPELINING` in favour of the `multiplex` cURL multi handler option +- Reject required multiplexing when the final `CURLOPT_HTTPAUTH` mask permits NTLM +- Reject cURL multi options that the runtime libcurl cannot apply +- Reject unknown handler constructor options +- Reject invalid `select_timeout` cURL multi handler option values +- Reject raw cURL multi connection cap options in favour of the named options +- Parse `Set-Cookie` strings with RFC 6265 whitespace trimming +- Ignore valueless `Set-Cookie` attributes that require a value when parsing +- Trim only the trailing CRLF from the stream handler header block +- Fail streamed uploads immediately when the body cannot be resent for an auth challenge + +### Removed + +- Dropped support for PHP 7.2 and 7.3 +- Removed `Client::__call()`; use the typed HTTP verb methods or `request()`/`requestAsync()` +- Removed `ClientInterface::getConfig()`; the concrete `Client::getConfig()` remains available +- Removed support for the `GUZZLE_CURL_SELECT_TIMEOUT` environment variable; use `CurlMultiHandler`'s `select_timeout` option +- Removed support for the `handler` request option; configure the handler on the client +- Removed direct access to `CurlMultiHandler::$_mh`; pass `CURLMOPT_*` values through constructor `options` instead +- Removed `RedirectMiddleware::$defaultSettings`; use `RedirectMiddleware::DEFAULT_SETTINGS` +- Removed the deprecated `RetryMiddleware::exponentialDelay()` method +- Removed the deprecated `RequestException::wrapException()` method +- Removed the deprecated `Utils::describeType()` method +- Removed `Utils::jsonDecode()` and `Utils::jsonEncode()` in favor of native JSON functions +- Removed deprecated `GuzzleHttp` namespace functions in favor of native or class equivalents +- Removed `Utils::defaultCaBundle()`; rely on the system trust store or pass a bundle path via the `verify` option +- Removed `HandlerStack::__toString()` +- Removed `RequestException::getHandlerContext()` and `ConnectException::getHandlerContext()` +- Removed response access from `RequestException`; use `ResponseException` +- Removed `Utils::isHostInNoProxy()`; use `ProxyOptions` helpers for Guzzle 8 no-proxy matching +- Removed `Utils::isUriInNoProxy()`; use `ProxyOptions::isUriInNoProxy()` +- Removed `Handler\Proxy::wrapTlsFallback()`; the default handler stack selects the cURL or stream handler by TLS support automatically + + +## 7.15.1 - 2026-07-18 + +### Security + +- Preserve host-only cookie scope and require explicit persistence markers (GHSA-wm3w-8rrp-j577) +- Bound response cookie admission and generated `Cookie` headers (GHSA-f283-ghqc-fg79) +- Exclude URI fragments from `Referer` headers generated for redirects (GHSA-h95v-h523-3mw8) + + +## 7.15.0 - 2026-07-17 + +### Added + +- Added `Multiplexing::NONE` support as a client, cURL multi handler, and conditional request option + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^2.13` +- Use locale-independent ASCII folding for all case normalization and comparison +- Bound cURL upload reads to the declared `Content-Length` +- Sanitize the cURL error text exposed through exception handler context +- Fail closed when a named cURL multi connection cap cannot be applied +- Reject the request-level `CURLOPT_SHARE` cURL option when named connection caps are configured +- Strengthen old-libcurl SOCKS isolation for raw `CURLOPT_PRE_PROXY` and opaque share handles +- Isolate HTTP proxy tunnels from opaque shared connection caches +- Trigger runtime deprecations for previously deprecated functionality in 7.1.0 + +### Deprecated + +- Deprecated `Utils::jsonDecode()` and `Utils::jsonEncode()` in favor of native JSON functions +- Deprecated passing `CURLMOPT_PIPELINING` in the cURL multi handler `options` array +- Deprecated passing `CURLOPT_PROXYHEADER` without cURL proxy header separation support + +### Fixed + +- Defer cURL requests created from multi callbacks until native execution unwinds +- Fail synchronous waits from native cURL callbacks promptly instead of self-deadlocking +- Guard cURL multi handle removal against progress callbacks re-entering the handler +- Scope promise waits on the cURL multi handler to the awaited transfer +- Strip `Content-Length` and `Transfer-Encoding` when redirects discard the request body +- Stop re-applying the `delay` request option to followed redirects + + +## 7.14.2 - 2026-07-14 + +### Security + +- Prevent first-class and proxy URL credentials from reaching origins (GHSA-94pj-82f3-465w) + + +## 7.14.1 - 2026-07-13 + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^2.12.5` + +### Fixed + +- Fail closed when a proxy tunnel isolation cURL option cannot be applied +- Normalize Stringable proxy credential values before computing connection-reuse section signatures +- Restore conservative credential redaction for unparseable proxies with multiple `@` separators +- Redact request URI credentials from the stream handler connection error message +- Reject enabled response streaming (`stream => true`) on cap-configured stream handlers +- Distinguish CurlMultiHandler and StreamHandler outcomes in connection-cap custom-handler guidance +- Reject raw cURL options that conflict with explicit multiplexing guarantees +- Stop explicit multiplexing conflict checks faulting on non-array cURL multi `options` values +- Reject required multiplexing when the final `CURLOPT_HTTPAUTH` mask permits NTLM +- Require an integer `CURLMOPT_PIPELINING` when combined with explicit multiplexing +- Check the required multiplexing cleartext proxy rule against the final cURL configuration +- Bound cURL multi handler blocking selects by the earliest pending request delay +- Stop synchronous cURL multi handler waits blocking on other transfers once the target has settled +- Stop cURL multi completion processing double-settling promises canceled from completion callbacks +- Run ready promise queue tasks before sleeping for delayed cURL multi requests +- Avoid integer overflow in cURL multi delay timing on 32-bit platforms +- Roll back failed cURL multi handle attachment instead of leaving requests pending +- Release the cURL easy handle when the `on_stats` callback throws +- Normalize response trailer field names to lowercase with values in wire order +- Retain response trailers only when an `on_trailers` callback is configured +- Validate the `on_trailers` callback before starting a cURL transfer +- Reject the `on_trailers` request option on the stream handler, which cannot observe trailers +- Match cookies, proxy schemes, auth types, and header names with locale-independent ASCII folding +- Reject proxy option values that Guzzle cannot classify identically to ext-curl + + +## 7.14.0 - 2026-07-08 + +### Added + +- Added the `on_trailers` request option to expose parsed HTTP response trailers +- Added the `multiplex` request option with `Multiplexing::*` modes to control or require HTTP/2 multiplexing +- Added rejection of explicit `multiplex` requests when `CURLMOPT_PIPELINING` disables multiplexing +- Added the `max_host_connections` and `max_total_connections` client and cURL multi handler options + +### Changed + +- Redirects that discard the request body no longer require it to be rewindable +- Synchronous cURL multi handler requests no longer wait for other queued transfers +- Section SOCKS proxy connections by credentials on libcurl before 7.69.0 +- Reject request-level `CURLOPT_SHARE` when combined with authenticated SOCKS proxy configuration +- Redact proxy userinfo containing raw control bytes in cURL errors +- Check linked curl/libcurl NTLM support before applying NTLM auth +- Clarify that NTLM is deprecated by both Guzzle and curl/libcurl +- Remove deprecation for the raw cURL `CURLOPT_CERTINFO` option +- Warn when a cURL multi option cannot be applied + +### Deprecated + +- Deprecate the raw `CURLOPT_PIPEWAIT` cURL option in favour of the `multiplex` request option +- Deprecate unknown handler constructor options +- Deprecate invalid `select_timeout` cURL multi handler option values +- Deprecate raw cURL multi connection cap options in favour of the named options + + +## 7.13.3 - 2026-07-08 + +### Changed + +- Adjusted `guzzlehttp/promises` version constraint to `^2.5.1` +- Adjusted `guzzlehttp/psr7` version constraint to `^2.12.4` +- Pass explicit trim characters ahead of the PHP 8.6 trim default change + +### Fixed + +- Stop matching cookie domains against hosts with a trailing newline +- Reject HTTP status codes and certificate type extensions with a trailing newline +- Treat PCRE engine failures as invalid cookie names during cookie validation +- Report PCRE engine failures when formatting log messages +- Report PCRE engine failures when splitting `no_proxy` values + + +## 7.13.2 - 2026-07-05 + +### Fixed + +- Stop the cURL multi handler busy-waiting on request delays shorter than one second +- Stop cURL HEAD requests with request bodies hanging on responses that declare a content length +- The cURL handler no longer transmits request bodies on HEAD requests +- Preserve response headers when a response includes HTTP trailers +- Harden cURL response header block detection when HTTP trailers are received +- Corrected the PSR-7 class names in the Pool iterator exception +- Redirect body rewind failures no longer leak a bare `RuntimeException` + + +## 7.13.1 - 2026-06-29 + +### Fixed + +- Allow middleware to rewrite partial URIs before transports validate them + + +## 7.13.0 - 2026-06-29 + +### Added + +- Added the `crypto_method_max` request option to cap the maximum TLS protocol version +- Added HTTP QUERY redirect support, preserving method and body on 301 and 302 + +### Changed + +- Section proxy tunnel connection reuse by credential so distinct credentials never share a tunnel +- Isolate concurrent foreign cURL proxy tunnels added while another owner's tunnel is active +- Route credentialed HTTP(S) proxy Proxy-Authorization headers through cURL proxy header handling +- Reject request-level `CURLOPT_SHARE` when combined with authenticated HTTP/HTTPS proxy tunnel configuration +- Remove deprecation for raw cURL `CURLOPT_PREREQFUNCTION` callbacks when defined by PHP cURL +- Route TLS 1.2 `crypto_method` requests to the stream handler when cURL cannot select TLS 1.2 +- Reject final request URIs missing a scheme or host before transfer + +### Deprecated + +- Deprecate invalid protocols, force_ip_resolve, delay, cookies, and allow_redirects values + + +## 7.12.3 - 2026-06-23 + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^2.12.3` + +### Security + +- Treat IP and numeric cookie domains as exact-match-only (GHSA-g446-98w2-8p5w) + + +## 7.12.2 - 2026-06-23 + +### Fixed + +- Clamp out-of-range `Max-Age` so a very large value no longer overflows to an already-expired timestamp +- Use strict comparison in `CookieJar` conflict resolution so distinct numeric-string names don't overwrite +- Store a cookie whose `Domain` has a trailing dot on the origin host instead of silently discarding it +- Fix `StreamHandler` hard-failing on bracketed IPv6 literal hosts when `force_ip_resolve` is set +- Use strict cookie `Path` comparison so `CookieJar::clear()` with a numeric path keeps a distinct-path cookie +- Fixed cookie handling for falsey `Domain`, `Max-Age`, path, and name values +- Fixed `decode_content` handling for falsey string values +- Fixed deprecated request option values reaching built-in handlers before normalization + + +## 7.12.1 - 2026-06-18 + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^2.12.1` + +### Fixed + +- Reject proxy URLs with a malformed scheme in the cURL handlers instead of letting libcurl mishandle them + +### Security + +- Reject HTTPS proxies when the installed libcurl lacks HTTPS-proxy support (GHSA-wpwq-4j6v-78m3) +- Reject dot-only cookie `Domain` attributes as match-all (GHSA-cwxw-98qj-8qjx) + + +## 7.12.0 - 2026-06-16 + +### Added + +- Added `RequestOptions` constants for `curl`, `retries`, and `stream_context` + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^2.12` +- Constrain cURL transport sharing to safe libcurl DNS and SSL session support +- Resolve proxy environment variables in the cURL handlers; libcurl no longer reads the environment itself +- Ignore proxy environment variables when the `proxy` request option makes a decision +- Disable proxy environment variables on Windows SAPIs other than CLI (httpoxy hardening) +- Redact proxy credentials from cURL handler error messages, following `Psr7\Utils::redactUserInfo()` +- Normalize no-proxy domain and IP literal matching across the cURL and stream handlers + +### Deprecated + +- Deprecated the request-level `handler` option, which will be ignored in 8.0 +- Deprecated raw cURL request options outside the built-in cURL handlers' allow-list +- Deprecated the `CURLOPT_PROXYTYPE` cURL request option; set the proxy type via a scheme-prefixed proxy URL +- Deprecated PHP stream context options outside the built-in stream handler allow-list +- Deprecated passing `ntlm` as a built-in `auth` type +- Deprecated `Utils::describeType()` +- Deprecated non-finite floats in the `query` and `form_params` options; 8.0 rejects them +- Deprecated non-string scalar values in the `body` option; 8.0 rejects them + +### Fixed + +- Fix cURL TLS and HTTP/2 capability detection using libcurl feature checks +- Fix proxy `no` list matches being re-proxied through environment-configured proxies by libcurl +- Fix `no` list and `NO_PROXY` matching to support IP CIDR ranges, matching libcurl +- Fix the stream handler not applying scheme-less proxies and their credentials + + +## 7.11.2 - 2026-06-12 + +### Fixed + +- Fixed non-finite float values emitting coercion warnings on PHP 8.5 + + +## 7.11.1 - 2026-06-07 + +### Fixed + +- Ignore request-level `transport_sharing`, matching other unknown request options + + +## 7.11.0 - 2026-06-02 + +### Added + +- Added support for providing the `proxy` request option's `no` value as a comma-delimited string +- Added the `protocols` request option to restrict allowed URI schemes for request transfers +- Added `cert_type` and `ssl_key_type` request options for TLS certificate and private-key file types +- Added PHP stream handler support for the `ssl_key` request option +- Added transport sharing via the `transport_sharing` client and cURL handler options + +### Changed + +- Adjusted `guzzlehttp/promises` version constraint to `^2.5` +- Adjusted `guzzlehttp/psr7` version constraint to `^2.11` +- Allowed domainless `SetCookie` instances to be stored without wildcard request matching +- Changed no-proxy matching to respect request ports for host-and-port rules +- Prevented `CurlMultiHandler` destructors from throwing during cleanup +- Improved invalid response handling across handlers + +### Deprecated + +- Deprecated non-iterable `Pool` request collections, which will be rejected in 8.0 +- Deprecated non-uppercase easy request methods; 8.0 preserves method casing +- Deprecated non-string `headers` request option values, which will be rejected in 8.0 +- Deprecated empty `headers` request option value arrays, which will be rejected in 8.0 +- Deprecated empty and malformed request protocol versions, which will be rejected in 8.0 +- Deprecated conflicting raw cURL request options, including `CURLOPT_SHARE`, which will be rejected in 8.0 +- Deprecated scalar-coerced `idn_conversion` request option values, which will be rejected in 8.0 +- Deprecated invalid documented request option value types, which will be rejected in 8.0 +- Deprecated selected request options ignored by incompatible built-in handlers, which will be rejected in 8.0 +- Deprecated `RequestException::wrapException()`, which will be removed in 8.0 +- Deprecated `RetryMiddleware::exponentialDelay()`, which will be removed in 8.0 + + +## 7.10.6 - 2026-06-01 + +### Fixed + +- `CurlMultiHandler` now rejects the promise when `CurlFactory::finish()` throws, preserving sibling transfers +- `SetCookie` now normalizes unparseable `Expires` values to `null` instead of `false` +- Fix stream handler decoded `gzip`/`deflate` truncation by dropping invalid `Content-Length` + + +## 7.10.5 - 2026-05-27 + +### Fixed + +- Defer cURL multi cancellation cleanup until after progress callbacks return +- Classify additional stream handler connection failures as `ConnectException` + + +## 7.10.4 - 2026-05-22 + +### Fixed + +- Fix IPv6 literal matching in no-proxy rules +- Handle cURL multi completion messages without handles after cancelled transfers +- Fix magic client request methods such as `options()` to uppercase inferred HTTP methods + + +## 7.10.3 - 2026-05-20 + +### Fixed + +- Fail clearly when an HTTP response header line is invalid +- Remove middleware by name when the name is also a callable string +- Treat empty request protocol versions as HTTP/1.1 + + +## 7.10.2 - 2026-05-20 + +### Fixed + +- Normalize HTTP version request options before applying them to PSR-7 requests +- Use string values for headers generated by request preparation and response decoding + + +## 7.10.1 - 2026-05-19 + +### Fixed + +- Fail clearly when cURL options cannot be applied +- Fail clearly when the certificate option is malformed +- Fail clearly when JSON decode depth is invalid +- Fail clearly when session cookie data is malformed +- Fail clearly when the stream progress option is not callable +- Prevent response creation failures from exposing stale cURL responses + + +## 7.10.0 - 2025-08-23 + +### Added + +- Support for PHP 8.5 + +### Changed + +- Adjusted `guzzlehttp/promises` version constraint to `^2.3` +- Adjusted `guzzlehttp/psr7` version constraint to `^2.8` + + +## 7.9.3 - 2025-03-27 + +### Changed + +- Remove explicit content-length header for GET requests +- Improve compatibility with bad servers for boolean cookie values + + +## 7.9.2 - 2024-07-24 + +### Fixed + +- Adjusted handler selection to use cURL if its version is 7.21.2 or higher, rather than 7.34.0 + + +## 7.9.1 - 2024-07-19 + +### Fixed + +- Fix TLS 1.3 check for HTTP/2 requests + + +## 7.9.0 - 2024-07-18 + +### Changed + +- Improve protocol version checks to provide feedback around unsupported protocols +- Only select the cURL handler by default if 7.34.0 or higher is linked +- Improved `CurlMultiHandler` to avoid busy wait if possible +- Dropped support for EOL `guzzlehttp/psr7` v1 +- Improved URI user info redaction in errors + +## 7.8.2 - 2024-07-18 + +### Added + +- Support for PHP 8.4 + + +## 7.8.1 - 2023-12-03 + +### Changed + +- Updated links in docs to their canonical versions +- Replaced `call_user_func*` with native calls + + +## 7.8.0 - 2023-08-27 + +### Added + +- Support for PHP 8.3 +- Added automatic closing of handles on `CurlFactory` object destruction + + +## 7.7.1 - 2023-08-27 + +### Changed + +- Remove the need for `AllowDynamicProperties` in `CurlMultiHandler` + + +## 7.7.0 - 2023-05-21 + +### Added + +- Support `guzzlehttp/promises` v2 + + +## 7.6.1 - 2023-05-15 + +### Fixed + +- Fix `SetCookie::fromString` MaxAge deprecation warning and skip invalid MaxAge values + + +## 7.6.0 - 2023-05-14 + +### Added + +- Support for setting the minimum TLS version in a unified way +- Apply on request the version set in options parameters + + +## 7.5.2 - 2023-05-14 + +### Fixed + +- Fixed set cookie constructor validation +- Fixed handling of files with `'0'` body + +### Changed + +- Corrected docs and default connect timeout value to 300 seconds + + +## 7.5.1 - 2023-04-17 + +### Fixed + +- Fixed `NO_PROXY` settings so that setting the `proxy` option to `no` overrides the env variable + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^1.9.1 || ^2.4.5` + + +## 7.5.0 - 2022-08-28 + +### Added + +- Support PHP 8.2 +- Add request to delay closure params + + +## 7.4.5 - 2022-06-20 + +### Fixed + +* Fix change in port should be considered a change in origin +* Fix `CURLOPT_HTTPAUTH` option not cleared on change of origin + + +## 7.4.4 - 2022-06-09 + +### Fixed + +* Fix failure to strip Authorization header on HTTP downgrade +* Fix failure to strip the Cookie header on change in host or HTTP downgrade + + +## 7.4.3 - 2022-05-25 + +### Fixed + +* Fix cross-domain cookie leakage + + +## 7.4.2 - 2022-03-20 + +### Fixed + +- Remove curl auth on cross-domain redirects to align with the Authorization HTTP header +- Reject non-HTTP schemes in StreamHandler +- Set a default ssl.peer_name context in StreamHandler to allow `force_ip_resolve` + + +## 7.4.1 - 2021-12-06 + +### Changed + +- Replaced implicit URI to string coercion [#2946](https://github.com/guzzle/guzzle/pull/2946) +- Allow `symfony/deprecation-contracts` version 3 [#2961](https://github.com/guzzle/guzzle/pull/2961) + +### Fixed + +- Only close curl handle if it's done [#2950](https://github.com/guzzle/guzzle/pull/2950) + + +## 7.4.0 - 2021-10-18 + +### Added + +- Support PHP 8.1 [#2929](https://github.com/guzzle/guzzle/pull/2929), [#2939](https://github.com/guzzle/guzzle/pull/2939) +- Support `psr/log` version 2 and 3 [#2943](https://github.com/guzzle/guzzle/pull/2943) + +### Fixed + +- Make sure we always call `restore_error_handler()` [#2915](https://github.com/guzzle/guzzle/pull/2915) +- Fix progress parameter type compatibility between the cURL and stream handlers [#2936](https://github.com/guzzle/guzzle/pull/2936) +- Throw `InvalidArgumentException` when an incorrect `headers` array is provided [#2916](https://github.com/guzzle/guzzle/pull/2916), [#2942](https://github.com/guzzle/guzzle/pull/2942) + +### Changed + +- Be more strict with types [#2914](https://github.com/guzzle/guzzle/pull/2914), [#2917](https://github.com/guzzle/guzzle/pull/2917), [#2919](https://github.com/guzzle/guzzle/pull/2919), [#2945](https://github.com/guzzle/guzzle/pull/2945) + + +## 7.3.0 - 2021-03-23 + +### Added + +- Support for DER and P12 certificates [#2413](https://github.com/guzzle/guzzle/pull/2413) +- Support the cURL (http://) scheme for StreamHandler proxies [#2850](https://github.com/guzzle/guzzle/pull/2850) +- Support for `guzzlehttp/psr7:^2.0` [#2878](https://github.com/guzzle/guzzle/pull/2878) + +### Fixed + +- Handle exceptions on invalid header consistently between PHP versions and handlers [#2872](https://github.com/guzzle/guzzle/pull/2872) + + +## 7.2.0 - 2020-10-10 + +### Added + +- Support for PHP 8 [#2712](https://github.com/guzzle/guzzle/pull/2712), [#2715](https://github.com/guzzle/guzzle/pull/2715), [#2789](https://github.com/guzzle/guzzle/pull/2789) +- Support passing a body summarizer to the http errors middleware [#2795](https://github.com/guzzle/guzzle/pull/2795) + +### Fixed + +- Handle exceptions during response creation [#2591](https://github.com/guzzle/guzzle/pull/2591) +- Fix CURLOPT_ENCODING not to be overwritten [#2595](https://github.com/guzzle/guzzle/pull/2595) +- Make sure the Request always has a body object [#2804](https://github.com/guzzle/guzzle/pull/2804) + +### Changed + +- The `TooManyRedirectsException` has a response [#2660](https://github.com/guzzle/guzzle/pull/2660) +- Avoid "functions" from dependencies [#2712](https://github.com/guzzle/guzzle/pull/2712) + +### Deprecated + +- Using environment variable GUZZLE_CURL_SELECT_TIMEOUT [#2786](https://github.com/guzzle/guzzle/pull/2786) + + +## 7.1.1 - 2020-09-30 + +### Fixed + +- Incorrect EOF detection for response body streams on Windows. + +### Changed + +- We dont connect curl `sink` on HEAD requests. +- Removed some PHP 5 workarounds + + +## 7.1.0 - 2020-09-22 + +### Added + +- `GuzzleHttp\MessageFormatterInterface` + +### Fixed + +- Fixed issue that caused cookies with no value not to be stored. +- On redirects, we allow all safe methods like GET, HEAD and OPTIONS. +- Fixed logging on empty responses. +- Make sure MessageFormatter::format returns string + +### Deprecated + +- All functions in `GuzzleHttp` has been deprecated. Use static methods on `Utils` instead. +- `ClientInterface::getConfig()` +- `Client::getConfig()` +- `Client::__call()` +- `Utils::defaultCaBundle()` +- `CurlFactory::LOW_CURL_VERSION_NUMBER` + + +## 7.0.1 - 2020-06-27 + +* Fix multiply defined functions fatal error [#2699](https://github.com/guzzle/guzzle/pull/2699) + + +## 7.0.0 - 2020-06-27 + +No changes since 7.0.0-rc1. + + +## 7.0.0-rc1 - 2020-06-15 + +### Changed + +* Use error level for logging errors in Middleware [#2629](https://github.com/guzzle/guzzle/pull/2629) +* Disabled IDN support by default and require ext-intl to use it [#2675](https://github.com/guzzle/guzzle/pull/2675) + + +## 7.0.0-beta2 - 2020-05-25 + +### Added + +* Using `Utils` class instead of functions in the `GuzzleHttp` namespace. [#2546](https://github.com/guzzle/guzzle/pull/2546) +* `ClientInterface::MAJOR_VERSION` [#2583](https://github.com/guzzle/guzzle/pull/2583) + +### Changed + +* Avoid the `getenv` function when unsafe [#2531](https://github.com/guzzle/guzzle/pull/2531) +* Added real client methods [#2529](https://github.com/guzzle/guzzle/pull/2529) +* Avoid functions due to global install conflicts [#2546](https://github.com/guzzle/guzzle/pull/2546) +* Use Symfony intl-idn polyfill [#2550](https://github.com/guzzle/guzzle/pull/2550) +* Adding methods for HTTP verbs like `Client::get()`, `Client::head()`, `Client::patch()` etc [#2529](https://github.com/guzzle/guzzle/pull/2529) +* `ConnectException` extends `TransferException` [#2541](https://github.com/guzzle/guzzle/pull/2541) +* Updated the default User Agent to "GuzzleHttp/7" [#2654](https://github.com/guzzle/guzzle/pull/2654) + +### Fixed + +* Various intl icu issues [#2626](https://github.com/guzzle/guzzle/pull/2626) + +### Removed + +* Pool option `pool_size` [#2528](https://github.com/guzzle/guzzle/pull/2528) + + +## 7.0.0-beta1 - 2019-12-30 + +The diff might look very big but 95% of Guzzle users will be able to upgrade without modification. +Please see [the upgrade document](UPGRADING.md) that describes all BC breaking changes. + +### Added + +* Implement PSR-18 and dropped PHP 5 support [#2421](https://github.com/guzzle/guzzle/pull/2421) [#2474](https://github.com/guzzle/guzzle/pull/2474) +* PHP 7 types [#2442](https://github.com/guzzle/guzzle/pull/2442) [#2449](https://github.com/guzzle/guzzle/pull/2449) [#2466](https://github.com/guzzle/guzzle/pull/2466) [#2497](https://github.com/guzzle/guzzle/pull/2497) [#2499](https://github.com/guzzle/guzzle/pull/2499) +* IDN support for redirects [2424](https://github.com/guzzle/guzzle/pull/2424) + +### Changed + +* Dont allow passing null as third argument to `BadResponseException::__construct()` [#2427](https://github.com/guzzle/guzzle/pull/2427) +* Use SAPI constant instead of method call [#2450](https://github.com/guzzle/guzzle/pull/2450) +* Use native function invocation [#2444](https://github.com/guzzle/guzzle/pull/2444) +* Better defaults for PHP installations with old ICU lib [2454](https://github.com/guzzle/guzzle/pull/2454) +* Added visibility to all constants [#2462](https://github.com/guzzle/guzzle/pull/2462) +* Dont allow passing `null` as URI to `Client::request()` and `Client::requestAsync()` [#2461](https://github.com/guzzle/guzzle/pull/2461) +* Widen the exception argument to throwable [#2495](https://github.com/guzzle/guzzle/pull/2495) + +### Fixed + +* Logging when Promise rejected with a string [#2311](https://github.com/guzzle/guzzle/pull/2311) + +### Removed + +* Class `SeekException` [#2162](https://github.com/guzzle/guzzle/pull/2162) +* `RequestException::getResponseBodySummary()` [#2425](https://github.com/guzzle/guzzle/pull/2425) +* `CookieJar::getCookieValue()` [#2433](https://github.com/guzzle/guzzle/pull/2433) +* `uri_template()` and `UriTemplate` [#2440](https://github.com/guzzle/guzzle/pull/2440) +* Request options `save_to` and `exceptions` [#2464](https://github.com/guzzle/guzzle/pull/2464) + + +## 6.5.2 - 2019-12-23 + +* idn_to_ascii() fix for old PHP versions [#2489](https://github.com/guzzle/guzzle/pull/2489) + + +## 6.5.1 - 2019-12-21 + +* Better defaults for PHP installations with old ICU lib [#2454](https://github.com/guzzle/guzzle/pull/2454) +* IDN support for redirects [#2424](https://github.com/guzzle/guzzle/pull/2424) + + +## 6.5.0 - 2019-12-07 + +* Improvement: Added support for reset internal queue in MockHandler. [#2143](https://github.com/guzzle/guzzle/pull/2143) +* Improvement: Added support to pass arbitrary options to `curl_multi_init`. [#2287](https://github.com/guzzle/guzzle/pull/2287) +* Fix: Gracefully handle passing `null` to the `header` option. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: `RetryMiddleware` did not do exponential delay between retires due unit mismatch. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: Prevent undefined offset when using array for ssl_key options. [#2348](https://github.com/guzzle/guzzle/pull/2348) +* Deprecated `ClientInterface::VERSION` + + +## 6.4.1 - 2019-10-23 + +* No `guzzle.phar` was created in 6.4.0 due expired API token. This release will fix that +* Added `parent::__construct()` to `FileCookieJar` and `SessionCookieJar` + + +## 6.4.0 - 2019-10-23 + +* Improvement: Improved error messages when using curl < 7.21.2 [#2108](https://github.com/guzzle/guzzle/pull/2108) +* Fix: Test if response is readable before returning a summary in `RequestException::getResponseBodySummary()` [#2081](https://github.com/guzzle/guzzle/pull/2081) +* Fix: Add support for GUZZLE_CURL_SELECT_TIMEOUT environment variable [#2161](https://github.com/guzzle/guzzle/pull/2161) +* Improvement: Added `GuzzleHttp\Exception\InvalidArgumentException` [#2163](https://github.com/guzzle/guzzle/pull/2163) +* Improvement: Added `GuzzleHttp\_current_time()` to use `hrtime()` if that function exists. [#2242](https://github.com/guzzle/guzzle/pull/2242) +* Improvement: Added curl's `appconnect_time` in `TransferStats` [#2284](https://github.com/guzzle/guzzle/pull/2284) +* Improvement: Make GuzzleException extend Throwable wherever it's available [#2273](https://github.com/guzzle/guzzle/pull/2273) +* Fix: Prevent concurrent writes to file when saving `CookieJar` [#2335](https://github.com/guzzle/guzzle/pull/2335) +* Improvement: Update `MockHandler` so we can test transfer time [#2362](https://github.com/guzzle/guzzle/pull/2362) + + +## 6.3.3 - 2018-04-22 + +* Fix: Default headers when decode_content is specified + + +## 6.3.2 - 2018-03-26 + +* Fix: Release process + + +## 6.3.1 - 2018-03-26 + +* Bug fix: Parsing 0 epoch expiry times in cookies [#2014](https://github.com/guzzle/guzzle/pull/2014) +* Improvement: Better ConnectException detection [#2012](https://github.com/guzzle/guzzle/pull/2012) +* Bug fix: Malformed domain that contains a "/" [#1999](https://github.com/guzzle/guzzle/pull/1999) +* Bug fix: Undefined offset when a cookie has no first key-value pair [#1998](https://github.com/guzzle/guzzle/pull/1998) +* Improvement: Support PHPUnit 6 [#1953](https://github.com/guzzle/guzzle/pull/1953) +* Bug fix: Support empty headers [#1915](https://github.com/guzzle/guzzle/pull/1915) +* Bug fix: Ignore case during header modifications [#1916](https://github.com/guzzle/guzzle/pull/1916) + ++ Minor code cleanups, documentation fixes and clarifications. + + +## 6.3.0 - 2017-06-22 + +* Feature: force IP resolution (ipv4 or ipv6) [#1608](https://github.com/guzzle/guzzle/pull/1608), [#1659](https://github.com/guzzle/guzzle/pull/1659) +* Improvement: Don't include summary in exception message when body is empty [#1621](https://github.com/guzzle/guzzle/pull/1621) +* Improvement: Handle `on_headers` option in MockHandler [#1580](https://github.com/guzzle/guzzle/pull/1580) +* Improvement: Added SUSE Linux CA path [#1609](https://github.com/guzzle/guzzle/issues/1609) +* Improvement: Use class reference for getting the name of the class instead of using hardcoded strings [#1641](https://github.com/guzzle/guzzle/pull/1641) +* Feature: Added `read_timeout` option [#1611](https://github.com/guzzle/guzzle/pull/1611) +* Bug fix: PHP 7.x fixes [#1685](https://github.com/guzzle/guzzle/pull/1685), [#1686](https://github.com/guzzle/guzzle/pull/1686), [#1811](https://github.com/guzzle/guzzle/pull/1811) +* Deprecation: BadResponseException instantiation without a response [#1642](https://github.com/guzzle/guzzle/pull/1642) +* Feature: Added NTLM auth [#1569](https://github.com/guzzle/guzzle/pull/1569) +* Feature: Track redirect HTTP status codes [#1711](https://github.com/guzzle/guzzle/pull/1711) +* Improvement: Check handler type during construction [#1745](https://github.com/guzzle/guzzle/pull/1745) +* Improvement: Always include the Content-Length if there's a body [#1721](https://github.com/guzzle/guzzle/pull/1721) +* Feature: Added convenience method to access a cookie by name [#1318](https://github.com/guzzle/guzzle/pull/1318) +* Bug fix: Fill `CURLOPT_CAPATH` and `CURLOPT_CAINFO` properly [#1684](https://github.com/guzzle/guzzle/pull/1684) +* Improvement: Use `\GuzzleHttp\Promise\rejection_for` function instead of object init [#1827](https://github.com/guzzle/guzzle/pull/1827) + ++ Minor code cleanups, documentation fixes and clarifications. + + +## 6.2.3 - 2017-02-28 + +* Fix deprecations with guzzle/psr7 version 1.4 + + +## 6.2.2 - 2016-10-08 + +* Allow to pass nullable Response to delay callable +* Only add scheme when host is present +* Fix drain case where content-length is the literal string zero +* Obfuscate in-URL credentials in exceptions + + +## 6.2.1 - 2016-07-18 + +* Address HTTP_PROXY security vulnerability, CVE-2016-5385: + https://httpoxy.org/ +* Fixing timeout bug with StreamHandler: + https://github.com/guzzle/guzzle/pull/1488 +* Only read up to `Content-Length` in PHP StreamHandler to avoid timeouts when + a server does not honor `Connection: close`. +* Ignore URI fragment when sending requests. + + +## 6.2.0 - 2016-03-21 + +* Feature: added `GuzzleHttp\json_encode` and `GuzzleHttp\json_decode`. + https://github.com/guzzle/guzzle/pull/1389 +* Bug fix: Fix sleep calculation when waiting for delayed requests. + https://github.com/guzzle/guzzle/pull/1324 +* Feature: More flexible history containers. + https://github.com/guzzle/guzzle/pull/1373 +* Bug fix: defer sink stream opening in StreamHandler. + https://github.com/guzzle/guzzle/pull/1377 +* Bug fix: do not attempt to escape cookie values. + https://github.com/guzzle/guzzle/pull/1406 +* Feature: report original content encoding and length on decoded responses. + https://github.com/guzzle/guzzle/pull/1409 +* Bug fix: rewind seekable request bodies before dispatching to cURL. + https://github.com/guzzle/guzzle/pull/1422 +* Bug fix: provide an empty string to `http_build_query` for HHVM workaround. + https://github.com/guzzle/guzzle/pull/1367 + + +## 6.1.1 - 2015-11-22 + +* Bug fix: Proxy::wrapSync() now correctly proxies to the appropriate handler + https://github.com/guzzle/guzzle/commit/911bcbc8b434adce64e223a6d1d14e9a8f63e4e4 +* Feature: HandlerStack is now more generic. + https://github.com/guzzle/guzzle/commit/f2102941331cda544745eedd97fc8fd46e1ee33e +* Bug fix: setting verify to false in the StreamHandler now disables peer + verification. https://github.com/guzzle/guzzle/issues/1256 +* Feature: Middleware now uses an exception factory, including more error + context. https://github.com/guzzle/guzzle/pull/1282 +* Feature: better support for disabled functions. + https://github.com/guzzle/guzzle/pull/1287 +* Bug fix: fixed regression where MockHandler was not using `sink`. + https://github.com/guzzle/guzzle/pull/1292 + + +## 6.1.0 - 2015-09-08 + +* Feature: Added the `on_stats` request option to provide access to transfer + statistics for requests. https://github.com/guzzle/guzzle/pull/1202 +* Feature: Added the ability to persist session cookies in CookieJars. + https://github.com/guzzle/guzzle/pull/1195 +* Feature: Some compatibility updates for Google APP Engine + https://github.com/guzzle/guzzle/pull/1216 +* Feature: Added support for NO_PROXY to prevent the use of a proxy based on + a simple set of rules. https://github.com/guzzle/guzzle/pull/1197 +* Feature: Cookies can now contain square brackets. + https://github.com/guzzle/guzzle/pull/1237 +* Bug fix: Now correctly parsing `=` inside of quotes in Cookies. + https://github.com/guzzle/guzzle/pull/1232 +* Bug fix: Cusotm cURL options now correctly override curl options of the + same name. https://github.com/guzzle/guzzle/pull/1221 +* Bug fix: Content-Type header is now added when using an explicitly provided + multipart body. https://github.com/guzzle/guzzle/pull/1218 +* Bug fix: Now ignoring Set-Cookie headers that have no name. +* Bug fix: Reason phrase is no longer cast to an int in some cases in the + cURL handler. https://github.com/guzzle/guzzle/pull/1187 +* Bug fix: Remove the Authorization header when redirecting if the Host + header changes. https://github.com/guzzle/guzzle/pull/1207 +* Bug fix: Cookie path matching fixes + https://github.com/guzzle/guzzle/issues/1129 +* Bug fix: Fixing the cURL `body_as_string` setting + https://github.com/guzzle/guzzle/pull/1201 +* Bug fix: quotes are no longer stripped when parsing cookies. + https://github.com/guzzle/guzzle/issues/1172 +* Bug fix: `form_params` and `query` now always uses the `&` separator. + https://github.com/guzzle/guzzle/pull/1163 +* Bug fix: Adding a Content-Length to PHP stream wrapper requests if not set. + https://github.com/guzzle/guzzle/pull/1189 + + +## 6.0.2 - 2015-07-04 + +* Fixed a memory leak in the curl handlers in which references to callbacks + were not being removed by `curl_reset`. +* Cookies are now extracted properly before redirects. +* Cookies now allow more character ranges. +* Decoded Content-Encoding responses are now modified to correctly reflect + their state if the encoding was automatically removed by a handler. This + means that the `Content-Encoding` header may be removed an the + `Content-Length` modified to reflect the message size after removing the + encoding. +* Added a more explicit error message when trying to use `form_params` and + `multipart` in the same request. +* Several fixes for HHVM support. +* Functions are now conditionally required using an additional level of + indirection to help with global Composer installations. + + +## 6.0.1 - 2015-05-27 + +* Fixed a bug with serializing the `query` request option where the `&` + separator was missing. +* Added a better error message for when `body` is provided as an array. Please + use `form_params` or `multipart` instead. +* Various doc fixes. + + +## 6.0.0 - 2015-05-26 + +* See the UPGRADING.md document for more information. +* Added `multipart` and `form_params` request options. +* Added `synchronous` request option. +* Added the `on_headers` request option. +* Fixed `expect` handling. +* No longer adding default middlewares in the client ctor. These need to be + present on the provided handler in order to work. +* Requests are no longer initiated when sending async requests with the + CurlMultiHandler. This prevents unexpected recursion from requests completing + while ticking the cURL loop. +* Removed the semantics of setting `default` to `true`. This is no longer + required now that the cURL loop is not ticked for async requests. +* Added request and response logging middleware. +* No longer allowing self signed certificates when using the StreamHandler. +* Ensuring that `sink` is valid if saving to a file. +* Request exceptions now include a "handler context" which provides handler + specific contextual information. +* Added `GuzzleHttp\RequestOptions` to allow request options to be applied + using constants. +* `$maxHandles` has been removed from CurlMultiHandler. +* `MultipartPostBody` is now part of the `guzzlehttp/psr7` package. + + +## 5.3.0 - 2015-05-19 + +* Mock now supports `save_to` +* Marked `AbstractRequestEvent::getTransaction()` as public. +* Fixed a bug in which multiple headers using different casing would overwrite + previous headers in the associative array. +* Added `Utils::getDefaultHandler()` +* Marked `GuzzleHttp\Client::getDefaultUserAgent` as deprecated. +* URL scheme is now always lowercased. + + +## 6.0.0-beta.1 + +* Requires PHP >= 5.5 +* Updated to use PSR-7 + * Requires immutable messages, which basically means an event based system + owned by a request instance is no longer possible. + * Utilizing the [Guzzle PSR-7 package](https://github.com/guzzle/psr7). + * Removed the dependency on `guzzlehttp/streams`. These stream abstractions + are available in the `guzzlehttp/psr7` package under the `GuzzleHttp\Psr7` + namespace. +* Added middleware and handler system + * Replaced the Guzzle event and subscriber system with a middleware system. + * No longer depends on RingPHP, but rather places the HTTP handlers directly + in Guzzle, operating on PSR-7 messages. + * Retry logic is now encapsulated in `GuzzleHttp\Middleware::retry`, which + means the `guzzlehttp/retry-subscriber` is now obsolete. + * Mocking responses is now handled using `GuzzleHttp\Handler\MockHandler`. +* Asynchronous responses + * No longer supports the `future` request option to send an async request. + Instead, use one of the `*Async` methods of a client (e.g., `requestAsync`, + `getAsync`, etc.). + * Utilizing `GuzzleHttp\Promise` instead of React's promise library to avoid + recursion required by chaining and forwarding react promises. See + https://github.com/guzzle/promises + * Added `requestAsync` and `sendAsync` to send request asynchronously. + * Added magic methods for `getAsync()`, `postAsync()`, etc. to send requests + asynchronously. +* Request options + * POST and form updates + * Added the `form_fields` and `form_files` request options. + * Removed the `GuzzleHttp\Post` namespace. + * The `body` request option no longer accepts an array for POST requests. + * The `exceptions` request option has been deprecated in favor of the + `http_errors` request options. + * The `save_to` request option has been deprecated in favor of `sink` request + option. +* Clients no longer accept an array of URI template string and variables for + URI variables. You will need to expand URI templates before passing them + into a client constructor or request method. +* Client methods `get()`, `post()`, `put()`, `patch()`, `options()`, etc. are + now magic methods that will send synchronous requests. +* Replaced `Utils.php` with plain functions in `functions.php`. +* Removed `GuzzleHttp\Collection`. +* Removed `GuzzleHttp\BatchResults`. Batched pool results are now returned as + an array. +* Removed `GuzzleHttp\Query`. Query string handling is now handled using an + associative array passed into the `query` request option. The query string + is serialized using PHP's `http_build_query`. If you need more control, you + can pass the query string in as a string. +* `GuzzleHttp\QueryParser` has been replaced with the + `GuzzleHttp\Psr7\parse_query`. + + +## 5.2.0 - 2015-01-27 + +* Added `AppliesHeadersInterface` to make applying headers to a request based + on the body more generic and not specific to `PostBodyInterface`. +* Reduced the number of stack frames needed to send requests. +* Nested futures are now resolved in the client rather than the RequestFsm +* Finishing state transitions is now handled in the RequestFsm rather than the + RingBridge. +* Added a guard in the Pool class to not use recursion for request retries. + + +## 5.1.0 - 2014-12-19 + +* Pool class no longer uses recursion when a request is intercepted. +* The size of a Pool can now be dynamically adjusted using a callback. + See https://github.com/guzzle/guzzle/pull/943. +* Setting a request option to `null` when creating a request with a client will + ensure that the option is not set. This allows you to overwrite default + request options on a per-request basis. + See https://github.com/guzzle/guzzle/pull/937. +* Added the ability to limit which protocols are allowed for redirects by + specifying a `protocols` array in the `allow_redirects` request option. +* Nested futures due to retries are now resolved when waiting for synchronous + responses. See https://github.com/guzzle/guzzle/pull/947. +* `"0"` is now an allowed URI path. See + https://github.com/guzzle/guzzle/pull/935. +* `Query` no longer typehints on the `$query` argument in the constructor, + allowing for strings and arrays. +* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle + specific exceptions if necessary. + + +## 5.0.3 - 2014-11-03 + +This change updates query strings so that they are treated as un-encoded values +by default where the value represents an un-encoded value to send over the +wire. A Query object then encodes the value before sending over the wire. This +means that even value query string values (e.g., ":") are url encoded. This +makes the Query class match PHP's http_build_query function. However, if you +want to send requests over the wire using valid query string characters that do +not need to be encoded, then you can provide a string to Url::setQuery() and +pass true as the second argument to specify that the query string is a raw +string that should not be parsed or encoded (unless a call to getQuery() is +subsequently made, forcing the query-string to be converted into a Query +object). + + +## 5.0.2 - 2014-10-30 + +* Added a trailing `\r\n` to multipart/form-data payloads. See + https://github.com/guzzle/guzzle/pull/871 +* Added a `GuzzleHttp\Pool::send()` convenience method to match the docs. +* Status codes are now returned as integers. See + https://github.com/guzzle/guzzle/issues/881 +* No longer overwriting an existing `application/x-www-form-urlencoded` header + when sending POST requests, allowing for customized headers. See + https://github.com/guzzle/guzzle/issues/877 +* Improved path URL serialization. + + * No longer double percent-encoding characters in the path or query string if + they are already encoded. + * Now properly encoding the supplied path to a URL object, instead of only + encoding ' ' and '?'. + * Note: This has been changed in 5.0.3 to now encode query string values by + default unless the `rawString` argument is provided when setting the query + string on a URL: Now allowing many more characters to be present in the + query string without being percent encoded. See + https://datatracker.ietf.org/doc/html/rfc3986#appendix-A + + +## 5.0.1 - 2014-10-16 + +Bugfix release. + +* Fixed an issue where connection errors still returned response object in + error and end events event though the response is unusable. This has been + corrected so that a response is not returned in the `getResponse` method of + these events if the response did not complete. https://github.com/guzzle/guzzle/issues/867 +* Fixed an issue where transfer statistics were not being populated in the + RingBridge. https://github.com/guzzle/guzzle/issues/866 + + +## 5.0.0 - 2014-10-12 + +Adding support for non-blocking responses and some minor API cleanup. + +### New Features + +* Added support for non-blocking responses based on `guzzlehttp/guzzle-ring`. +* Added a public API for creating a default HTTP adapter. +* Updated the redirect plugin to be non-blocking so that redirects are sent + concurrently. Other plugins like this can now be updated to be non-blocking. +* Added a "progress" event so that you can get upload and download progress + events. +* Added `GuzzleHttp\Pool` which implements FutureInterface and transfers + requests concurrently using a capped pool size as efficiently as possible. +* Added `hasListeners()` to EmitterInterface. +* Removed `GuzzleHttp\ClientInterface::sendAll` and marked + `GuzzleHttp\Client::sendAll` as deprecated (it's still there, just not the + recommended way). + +### Breaking changes + +The breaking changes in this release are relatively minor. The biggest thing to +look out for is that request and response objects no longer implement fluent +interfaces. + +* Removed the fluent interfaces (i.e., `return $this`) from requests, + responses, `GuzzleHttp\Collection`, `GuzzleHttp\Url`, + `GuzzleHttp\Query`, `GuzzleHttp\Post\PostBody`, and + `GuzzleHttp\Cookie\SetCookie`. This blog post provides a good outline of + why I did this: https://ocramius.github.io/blog/fluent-interfaces-are-evil/. + This also makes the Guzzle message interfaces compatible with the current + PSR-7 message proposal. +* Removed "functions.php", so that Guzzle is truly PSR-4 compliant. Except + for the HTTP request functions from function.php, these functions are now + implemented in `GuzzleHttp\Utils` using camelCase. `GuzzleHttp\json_decode` + moved to `GuzzleHttp\Utils::jsonDecode`. `GuzzleHttp\get_path` moved to + `GuzzleHttp\Utils::getPath`. `GuzzleHttp\set_path` moved to + `GuzzleHttp\Utils::setPath`. `GuzzleHttp\batch` should now be + `GuzzleHttp\Pool::batch`, which returns an `objectStorage`. Using functions.php + caused problems for many users: they aren't PSR-4 compliant, require an + explicit include, and needed an if-guard to ensure that the functions are not + declared multiple times. +* Rewrote adapter layer. + * Removing all classes from `GuzzleHttp\Adapter`, these are now + implemented as callables that are stored in `GuzzleHttp\Ring\Client`. + * Removed the concept of "parallel adapters". Sending requests serially or + concurrently is now handled using a single adapter. + * Moved `GuzzleHttp\Adapter\Transaction` to `GuzzleHttp\Transaction`. The + Transaction object now exposes the request, response, and client as public + properties. The getters and setters have been removed. +* Removed the "headers" event. This event was only useful for changing the + body a response once the headers of the response were known. You can implement + a similar behavior in a number of ways. One example might be to use a + FnStream that has access to the transaction being sent. For example, when the + first byte is written, you could check if the response headers match your + expectations, and if so, change the actual stream body that is being + written to. +* Removed the `asArray` parameter from + `GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header + value as an array, then use the newly added `getHeaderAsArray()` method of + `MessageInterface`. This change makes the Guzzle interfaces compatible with + the PSR-7 interfaces. +* `GuzzleHttp\Message\MessageFactory` no longer allows subclasses to add + custom request options using double-dispatch (this was an implementation + detail). Instead, you should now provide an associative array to the + constructor which is a mapping of the request option name mapping to a + function that applies the option value to a request. +* Removed the concept of "throwImmediately" from exceptions and error events. + This control mechanism was used to stop a transfer of concurrent requests + from completing. This can now be handled by throwing the exception or by + cancelling a pool of requests or each outstanding future request individually. +* Updated to "GuzzleHttp\Streams" 3.0. + * `GuzzleHttp\Stream\StreamInterface::getContents()` no longer accepts a + `maxLen` parameter. This update makes the Guzzle streams project + compatible with the current PSR-7 proposal. + * `GuzzleHttp\Stream\Stream::__construct`, + `GuzzleHttp\Stream\Stream::factory`, and + `GuzzleHttp\Stream\Utils::create` no longer accept a size in the second + argument. They now accept an associative array of options, including the + "size" key and "metadata" key which can be used to provide custom metadata. + + +## 4.2.2 - 2014-09-08 + +* Fixed a memory leak in the CurlAdapter when reusing cURL handles. +* No longer using `request_fulluri` in stream adapter proxies. +* Relative redirects are now based on the last response, not the first response. + +## 4.2.1 - 2014-08-19 + +* Ensuring that the StreamAdapter does not always add a Content-Type header +* Adding automated github releases with a phar and zip + +## 4.2.0 - 2014-08-17 + +* Now merging in default options using a case-insensitive comparison. + Closes https://github.com/guzzle/guzzle/issues/767 +* Added the ability to automatically decode `Content-Encoding` response bodies + using the `decode_content` request option. This is set to `true` by default + to decode the response body if it comes over the wire with a + `Content-Encoding`. Set this value to `false` to disable decoding the + response content, and pass a string to provide a request `Accept-Encoding` + header and turn on automatic response decoding. This feature now allows you + to pass an `Accept-Encoding` header in the headers of a request but still + disable automatic response decoding. + Closes https://github.com/guzzle/guzzle/issues/764 +* Added the ability to throw an exception immediately when transferring + requests in parallel. Closes https://github.com/guzzle/guzzle/issues/760 +* Updating guzzlehttp/streams dependency to ~2.1 +* No longer utilizing the now deprecated namespaced methods from the stream + package. + +## 4.1.8 - 2014-08-14 + +* Fixed an issue in the CurlFactory that caused setting the `stream=false` + request option to throw an exception. + See: https://github.com/guzzle/guzzle/issues/769 +* TransactionIterator now calls rewind on the inner iterator. + See: https://github.com/guzzle/guzzle/pull/765 +* You can now set the `Content-Type` header to `multipart/form-data` + when creating POST requests to force multipart bodies. + See https://github.com/guzzle/guzzle/issues/768 + +## 4.1.7 - 2014-08-07 + +* Fixed an error in the HistoryPlugin that caused the same request and response + to be logged multiple times when an HTTP protocol error occurs. +* Ensuring that cURL does not add a default Content-Type when no Content-Type + has been supplied by the user. This prevents the adapter layer from modifying + the request that is sent over the wire after any listeners may have already + put the request in a desired state (e.g., signed the request). +* Throwing an exception when you attempt to send requests that have the + "stream" set to true in parallel using the MultiAdapter. +* Only calling curl_multi_select when there are active cURL handles. This was + previously changed and caused performance problems on some systems due to PHP + always selecting until the maximum select timeout. +* Fixed a bug where multipart/form-data POST fields were not correctly + aggregated (e.g., values with "&"). + +## 4.1.6 - 2014-08-03 + +* Added helper methods to make it easier to represent messages as strings, + including getting the start line and getting headers as a string. + +## 4.1.5 - 2014-08-02 + +* Automatically retrying cURL "Connection died, retrying a fresh connect" + errors when possible. +* cURL implementation cleanup +* Allowing multiple event subscriber listeners to be registered per event by + passing an array of arrays of listener configuration. + +## 4.1.4 - 2014-07-22 + +* Fixed a bug that caused multi-part POST requests with more than one field to + serialize incorrectly. +* Paths can now be set to "0" +* `ResponseInterface::xml` now accepts a `libxml_options` option and added a + missing default argument that was required when parsing XML response bodies. +* A `save_to` stream is now created lazily, which means that files are not + created on disk unless a request succeeds. + +## 4.1.3 - 2014-07-15 + +* Various fixes to multipart/form-data POST uploads +* Wrapping function.php in an if-statement to ensure Guzzle can be used + globally and in a Composer install +* Fixed an issue with generating and merging in events to an event array +* POST headers are only applied before sending a request to allow you to change + the query aggregator used before uploading +* Added much more robust query string parsing +* Fixed various parsing and normalization issues with URLs +* Fixing an issue where multi-valued headers were not being utilized correctly + in the StreamAdapter + +## 4.1.2 - 2014-06-18 + +* Added support for sending payloads with GET requests + +## 4.1.1 - 2014-06-08 + +* Fixed an issue related to using custom message factory options in subclasses +* Fixed an issue with nested form fields in a multi-part POST +* Fixed an issue with using the `json` request option for POST requests +* Added `ToArrayInterface` to `GuzzleHttp\Cookie\CookieJar` + +## 4.1.0 - 2014-05-27 + +* Added a `json` request option to easily serialize JSON payloads. +* Added a `GuzzleHttp\json_decode()` wrapper to safely parse JSON. +* Added `setPort()` and `getPort()` to `GuzzleHttp\Message\RequestInterface`. +* Added the ability to provide an emitter to a client in the client constructor. +* Added the ability to persist a cookie session using $_SESSION. +* Added a trait that can be used to add event listeners to an iterator. +* Removed request method constants from RequestInterface. +* Fixed warning when invalid request start-lines are received. +* Updated MessageFactory to work with custom request option methods. +* Updated cacert bundle to latest build. + +4.0.2 (2014-04-16) +------------------ + +* Proxy requests using the StreamAdapter now properly use request_fulluri (#632) +* Added the ability to set scalars as POST fields (#628) + +## 4.0.1 - 2014-04-04 + +* The HTTP status code of a response is now set as the exception code of + RequestException objects. +* 303 redirects will now correctly switch from POST to GET requests. +* The default parallel adapter of a client now correctly uses the MultiAdapter. +* HasDataTrait now initializes the internal data array as an empty array so + that the toArray() method always returns an array. + +## 4.0.0 - 2014-03-29 + +* For information on changes and upgrading, see: + https://github.com/guzzle/guzzle/blob/4.x/UPGRADING.md#3x-to-40 +* Added `GuzzleHttp\batch()` as a convenience function for sending requests in + parallel without needing to write asynchronous code. +* Restructured how events are added to `GuzzleHttp\ClientInterface::sendAll()`. + You can now pass a callable or an array of associative arrays where each + associative array contains the "fn", "priority", and "once" keys. + +## 4.0.0.rc-2 - 2014-03-25 + +* Removed `getConfig()` and `setConfig()` from clients to avoid confusion + around whether things like base_url, message_factory, etc. should be able to + be retrieved or modified. +* Added `getDefaultOption()` and `setDefaultOption()` to ClientInterface +* functions.php functions were renamed using snake_case to match PHP idioms +* Added support for `HTTP_PROXY`, `HTTPS_PROXY`, and + `GUZZLE_CURL_SELECT_TIMEOUT` environment variables +* Added the ability to specify custom `sendAll()` event priorities +* Added the ability to specify custom stream context options to the stream + adapter. +* Added a functions.php function for `get_path()` and `set_path()` +* CurlAdapter and MultiAdapter now use a callable to generate curl resources +* MockAdapter now properly reads a body and emits a `headers` event +* Updated Url class to check if a scheme and host are set before adding ":" + and "//". This allows empty Url (e.g., "") to be serialized as "". +* Parsing invalid XML no longer emits warnings +* Curl classes now properly throw AdapterExceptions +* Various performance optimizations +* Streams are created with the faster `Stream\create()` function +* Marked deprecation_proxy() as internal +* Test server is now a collection of static methods on a class + +## 4.0.0-rc.1 - 2014-03-15 + +* See https://github.com/guzzle/guzzle/blob/4.x/UPGRADING.md#3x-to-40 + +## 3.8.1 - 2014-01-28 + +* Bug: Always using GET requests when redirecting from a 303 response +* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in + `Guzzle\Http\ClientInterface::setSslVerification()` +* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL +* Bug: The body of a request can now be set to `"0"` +* Sending PHP stream requests no longer forces `HTTP/1.0` +* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of + each sub-exception +* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than + clobbering everything). +* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) +* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. + For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. +* Now properly escaping the regular expression delimiter when matching Cookie domains. +* Network access is now disabled when loading XML documents + +## 3.8.0 - 2013-12-05 + +* Added the ability to define a POST name for a file +* JSON response parsing now properly walks additionalProperties +* cURL error code 18 is now retried automatically in the BackoffPlugin +* Fixed a cURL error when URLs contain fragments +* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were + CurlExceptions +* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) +* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` +* Fixed a bug that was encountered when parsing empty header parameters +* UriTemplate now has a `setRegex()` method to match the docs +* The `debug` request parameter now checks if it is truthy rather than if it exists +* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin +* Added the ability to combine URLs using strict RFC 3986 compliance +* Command objects can now return the validation errors encountered by the command +* Various fixes to cache revalidation (#437 and 29797e5) +* Various fixes to the AsyncPlugin +* Cleaned up build scripts + +## 3.7.4 - 2013-10-02 + +* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) +* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp + (see https://github.com/aws/aws-sdk-php/issues/147) +* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots +* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) +* Updated the bundled cacert.pem (#419) +* OauthPlugin now supports adding authentication to headers or query string (#425) + +## 3.7.3 - 2013-09-08 + +* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and + `CommandTransferException`. +* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description +* Schemas are only injected into response models when explicitly configured. +* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of + an EntityBody. +* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. +* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. +* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() +* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin +* Bug fix: Visiting XML attributes first before visiting XML children when serializing requests +* Bug fix: Properly parsing headers that contain commas contained in quotes +* Bug fix: mimetype guessing based on a filename is now case-insensitive + +## 3.7.2 - 2013-08-02 + +* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander + See https://github.com/guzzle/guzzle/issues/371 +* Bug fix: Cookie domains are now matched correctly according to RFC 6265 + See https://github.com/guzzle/guzzle/issues/377 +* Bug fix: GET parameters are now used when calculating an OAuth signature +* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted +* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched +* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. + See https://github.com/guzzle/guzzle/issues/379 +* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See + https://github.com/guzzle/guzzle/pull/380 +* cURL multi cleanup and optimizations + +## 3.7.1 - 2013-07-05 + +* Bug fix: Setting default options on a client now works +* Bug fix: Setting options on HEAD requests now works. See #352 +* Bug fix: Moving stream factory before send event to before building the stream. See #353 +* Bug fix: Cookies no longer match on IP addresses per RFC 6265 +* Bug fix: Correctly parsing header parameters that are in `<>` and quotes +* Added `cert` and `ssl_key` as request options +* `Host` header can now diverge from the host part of a URL if the header is set manually +* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter +* OAuth parameters are only added via the plugin if they aren't already set +* Exceptions are now thrown when a URL cannot be parsed +* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails +* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin + +## 3.7.0 - 2013-06-10 + +* See UPGRADING.md for more information on how to upgrade. +* Requests now support the ability to specify an array of $options when creating a request to more easily modify a + request. You can pass a 'request.options' configuration setting to a client to apply default request options to + every request created by a client (e.g. default query string variables, headers, curl options, etc.). +* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. + See `Guzzle\Http\StaticClient::mount`. +* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests + created by a command (e.g. custom headers, query string variables, timeout settings, etc.). +* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the + headers of a response +* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key + (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) +* ServiceBuilders now support storing and retrieving arbitrary data +* CachePlugin can now purge all resources for a given URI +* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource +* CachePlugin now uses the Vary header to determine if a resource is a cache hit +* `Guzzle\Http\Message\Response` now implements `\Serializable` +* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters +* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable +* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` +* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size +* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message +* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older + Symfony users can still use the old version of Monolog. +* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. + Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. +* Several performance improvements to `Guzzle\Common\Collection` +* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +* Added `Guzzle\Stream\StreamInterface::isRepeatable` +* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. +* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. +* Removed `Guzzle\Http\ClientInterface::expandTemplate()` +* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` +* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` +* Removed `Guzzle\Http\Message\RequestInterface::canCache` +* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` +* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` +* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. +* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting + `Guzzle\Common\Version::$emitWarnings` to true. +* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use + `$request->getResponseBody()->isRepeatable()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. + These will work through Guzzle 4.0 +* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. +* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. +* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. +* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +* Marked `Guzzle\Common\Collection::inject()` as deprecated. +* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` +* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +* Always setting X-cache headers on cached responses +* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +* Added `CacheStorageInterface::purge($url)` +* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +## 3.6.0 - 2013-05-29 + +* ServiceDescription now implements ToArrayInterface +* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters +* Guzzle can now correctly parse incomplete URLs +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess +* Added the ability to cast Model objects to a string to view debug information. + +## 3.5.0 - 2013-05-13 + +* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times +* Bug: Better cleanup of one-time events across the board (when an event is meant to fire once, it will now remove + itself from the EventDispatcher) +* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values +* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too +* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a + non-existent key +* Bug: All __call() method arguments are now required (helps with mocking frameworks) +* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference + to help with refcount based garbage collection of resources created by sending a request +* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. +* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it's deprecated). Use the + HistoryPlugin for a history. +* Added a `responseBody` alias for the `response_body` location +* Refactored internals to no longer rely on Response::getRequest() +* HistoryPlugin can now be cast to a string +* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests + and responses that are sent over the wire +* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects + +## 3.4.3 - 2013-04-30 + +* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response +* Added a check to re-extract the temp cacert bundle from the phar before sending each request + +## 3.4.2 - 2013-04-29 + +* Bug fix: Stream objects now work correctly with "a" and "a+" modes +* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present +* Bug fix: AsyncPlugin no longer forces HEAD requests +* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter +* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails +* Setting a response on a request will write to the custom request body from the response body if one is specified +* LogPlugin now writes to php://output when STDERR is undefined +* Added the ability to set multiple POST files for the same key in a single call +* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default +* Added the ability to queue CurlExceptions to the MockPlugin +* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) +* Configuration loading now allows remote files + +## 3.4.1 - 2013-04-16 + +* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti + handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. +* Exceptions are now properly grouped when sending requests in parallel +* Redirects are now properly aggregated when a multi transaction fails +* Redirects now set the response on the original object even in the event of a failure +* Bug fix: Model names are now properly set even when using $refs +* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax +* Added support for oauth_callback in OAuth signatures +* Added support for oauth_verifier in OAuth signatures +* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection + +## 3.4.0 - 2013-04-11 + +* Bug fix: URLs are now resolved correctly based on https://datatracker.ietf.org/doc/html/rfc3986#section-5.2. #289 +* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 +* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 +* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. +* Bug fix: Added `number` type to service descriptions. +* Bug fix: empty parameters are removed from an OAuth signature +* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header +* Bug fix: Fixed "array to string" error when validating a union of types in a service description +* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream +* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. +* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. +* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. +* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if + the Content-Type can be determined based on the entity body or the path of the request. +* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. +* Added support for a PSR-3 LogAdapter. +* Added a `command.after_prepare` event +* Added `oauth_callback` parameter to the OauthPlugin +* Added the ability to create a custom stream class when using a stream factory +* Added a CachingEntityBody decorator +* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. +* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. +* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies +* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This + means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use + POST fields or files (the latter is only used when emulating a form POST in the browser). +* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest + +## 3.3.1 - 2013-03-10 + +* Added the ability to create PHP streaming responses from HTTP requests +* Bug fix: Running any filters when parsing response headers with service descriptions +* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing +* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across + response location visitors. +* Bug fix: Removed the possibility of creating configuration files with circular dependencies +* RequestFactory::create() now uses the key of a POST file when setting the POST file name +* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set + +## 3.3.0 - 2013-03-03 + +* A large number of performance optimizations have been made +* Bug fix: Added 'wb' as a valid write mode for streams +* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned +* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` +* BC: Removed `Guzzle\Http\Utils` class +* BC: Setting a service description on a client will no longer modify the client's command factories. +* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using + the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' +* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to + lowercase +* Operation parameter objects are now lazy loaded internally +* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses +* Added support for instantiating responseType=class responseClass classes. Classes must implement + `Guzzle\Service\Command\ResponseClassInterface` +* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These + additional properties also support locations and can be used to parse JSON responses where the outermost part of the + JSON is an array +* Added support for nested renaming of JSON models (rename sentAs to name) +* CachePlugin + * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error + * Debug headers can now added to cached response in the CachePlugin + +## 3.2.0 - 2013-02-14 + +* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. +* URLs with no path no longer contain a "/" by default +* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. +* BadResponseException no longer includes the full request and response message +* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface +* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface +* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription +* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list +* xmlEncoding can now be customized for the XML declaration of a XML service description operation +* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value + aggregation and no longer uses callbacks +* The URL encoding implementation of Guzzle\Http\QueryString can now be customized +* Bug fix: Filters were not always invoked for array service description parameters +* Bug fix: Redirects now use a target response body rather than a temporary response body +* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded +* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives + +## 3.1.2 - 2013-01-27 + +* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the + response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. +* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent +* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) +* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() +* Setting default headers on a client after setting the user-agent will not erase the user-agent setting + +## 3.1.1 - 2013-01-20 + +* Adding wildcard support to Guzzle\Common\Collection::getPath() +* Adding alias support to ServiceBuilder configs +* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface + +## 3.1.0 - 2013-01-12 + +* BC: CurlException now extends from RequestException rather than BadResponseException +* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() +* Added getData to ServiceDescriptionInterface +* Added context array to RequestInterface::setState() +* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http +* Bug: Adding required content-type when JSON request visitor adds JSON to a command +* Bug: Fixing the serialization of a service description with custom data +* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing + an array of successful and failed responses +* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection +* Added Guzzle\Http\IoEmittingEntityBody +* Moved command filtration from validators to location visitors +* Added `extends` attributes to service description parameters +* Added getModels to ServiceDescriptionInterface + +## 3.0.7 - 2012-12-19 + +* Fixing phar detection when forcing a cacert to system if null or true +* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` +* Cleaning up `Guzzle\Common\Collection::inject` method +* Adding a response_body location to service descriptions + +## 3.0.6 - 2012-12-09 + +* CurlMulti performance improvements +* Adding setErrorResponses() to Operation +* composer.json tweaks + +## 3.0.5 - 2012-11-18 + +* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin +* Bug: Response body can now be a string containing "0" +* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert +* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs +* Added support for XML attributes in service description responses +* DefaultRequestSerializer now supports array URI parameter values for URI template expansion +* Added better mimetype guessing to requests and post files + +## 3.0.4 - 2012-11-11 + +* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value +* Bug: Cookies can now be added that have a name, domain, or value set to "0" +* Bug: Using the system cacert bundle when using the Phar +* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures +* Enhanced cookie jar de-duplication +* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added +* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies +* Added the ability to create any sort of hash for a stream rather than just an MD5 hash + +## 3.0.3 - 2012-11-04 + +* Implementing redirects in PHP rather than cURL +* Added PECL URI template extension and using as default parser if available +* Bug: Fixed Content-Length parsing of Response factory +* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. +* Adding ToArrayInterface throughout library +* Fixing OauthPlugin to create unique nonce values per request + +## 3.0.2 - 2012-10-25 + +* Magic methods are enabled by default on clients +* Magic methods return the result of a command +* Service clients no longer require a base_url option in the factory +* Bug: Fixed an issue with URI templates where null template variables were being expanded + +## 3.0.1 - 2012-10-22 + +* Models can now be used like regular collection objects by calling filter, map, etc. +* Models no longer require a Parameter structure or initial data in the constructor +* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` + +## 3.0.0 - 2012-10-15 + +* Rewrote service description format to be based on Swagger + * Now based on JSON schema + * Added nested input structures and nested response models + * Support for JSON and XML input and output models + * Renamed `commands` to `operations` + * Removed dot class notation + * Removed custom types +* Broke the project into smaller top-level namespaces to be more component friendly +* Removed support for XML configs and descriptions. Use arrays or JSON files. +* Removed the Validation component and Inspector +* Moved all cookie code to Guzzle\Plugin\Cookie +* Magic methods on a Guzzle\Service\Client now return the command un-executed. +* Calling getResult() or getResponse() on a command will lazily execute the command if needed. +* Now shipping with cURL's CA certs and using it by default +* Added previousResponse() method to response objects +* No longer sending Accept and Accept-Encoding headers on every request +* Only sending an Expect header by default when a payload is greater than 1MB +* Added/moved client options: + * curl.blacklist to curl.option.blacklist + * Added ssl.certificate_authority +* Added a Guzzle\Iterator component +* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin +* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) +* Added a more robust caching plugin +* Added setBody to response objects +* Updating LogPlugin to use a more flexible MessageFormatter +* Added a completely revamped build process +* Cleaning up Collection class and removing default values from the get method +* Fixed ZF2 cache adapters + +## 2.8.8 - 2012-10-15 + +* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did + +## 2.8.7 - 2012-09-30 + +* Bug: Fixed config file aliases for JSON includes +* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests +* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload +* Bug: Hardening request and response parsing to account for missing parts +* Bug: Fixed PEAR packaging +* Bug: Fixed Request::getInfo +* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail +* Adding the ability for the namespace Iterator factory to look in multiple directories +* Added more getters/setters/removers from service descriptions +* Added the ability to remove POST fields from OAuth signatures +* OAuth plugin now supports 2-legged OAuth + +## 2.8.6 - 2012-09-05 + +* Added the ability to modify and build service descriptions +* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command +* Added a `json` parameter location +* Now allowing dot notation for classes in the CacheAdapterFactory +* Using the union of two arrays rather than an array_merge when extending service builder services and service params +* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references + in service builder config files. +* Services defined in two different config files that include one another will by default replace the previously + defined service, but you can now create services that extend themselves and merge their settings over the previous +* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like + '_default' with a default JSON configuration file. + +## 2.8.5 - 2012-08-29 + +* Bug: Suppressed empty arrays from URI templates +* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching +* Added support for HTTP responses that do not contain a reason phrase in the start-line +* AbstractCommand commands are now invokable +* Added a way to get the data used when signing an Oauth request before a request is sent + +## 2.8.4 - 2012-08-15 + +* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin +* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. +* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream +* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream +* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) +* Added additional response status codes +* Removed SSL information from the default User-Agent header +* DELETE requests can now send an entity body +* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries +* Added the ability of the MockPlugin to consume mocked request bodies +* LogPlugin now exposes request and response objects in the extras array + +## 2.8.3 - 2012-07-30 + +* Bug: Fixed a case where empty POST requests were sent as GET requests +* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body +* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new +* Added multiple inheritance to service description commands +* Added an ApiCommandInterface and added `getParamNames()` and `hasParam()` +* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything +* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles + +## 2.8.2 - 2012-07-24 + +* Bug: Query string values set to 0 are no longer dropped from the query string +* Bug: A Collection object is no longer created each time a call is made to `Guzzle\Service\Command\AbstractCommand::getRequestHeaders()` +* Bug: `+` is now treated as an encoded space when parsing query strings +* QueryString and Collection performance improvements +* Allowing dot notation for class paths in filters attribute of a service descriptions + +## 2.8.1 - 2012-07-16 + +* Loosening Event Dispatcher dependency +* POST redirects can now be customized using CURLOPT_POSTREDIR + +## 2.8.0 - 2012-07-15 + +* BC: Guzzle\Http\Query + * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) + * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() + * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) + * Changed the aggregation functions of QueryString to be static methods + * Can now use fromString() with querystrings that have a leading ? +* cURL configuration values can be specified in service descriptions using `curl.` prefixed parameters +* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body +* Cookies are no longer URL decoded by default +* Bug: URI template variables set to null are no longer expanded + +## 2.7.2 - 2012-07-02 + +* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. +* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() +* CachePlugin now allows for a custom request parameter function to check if a request can be cached +* Bug fix: CachePlugin now only caches GET and HEAD requests by default +* Bug fix: Using header glue when transferring headers over the wire +* Allowing deeply nested arrays for composite variables in URI templates +* Batch divisors can now return iterators or arrays + +## 2.7.1 - 2012-06-26 + +* Minor patch to update version number in UA string +* Updating build process + +## 2.7.0 - 2012-06-25 + +* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. +* BC: Removed magic setX methods from commands +* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method +* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. +* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) +* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace +* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin +* Added the ability to set POST fields and files in a service description +* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method +* Adding a command.before_prepare event to clients +* Added BatchClosureTransfer and BatchClosureDivisor +* BatchTransferException now includes references to the batch divisor and transfer strategies +* Fixed some tests so that they pass more reliably +* Added Guzzle\Common\Log\ArrayLogAdapter + +## 2.6.6 - 2012-06-10 + +* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin +* BC: Removing Guzzle\Service\Command\CommandSet +* Adding generic batching system (replaces the batch queue plugin and command set) +* Updating ZF cache and log adapters and now using ZF's composer repository +* Bug: Setting the name of each ApiParam when creating through an ApiCommand +* Adding result_type, result_doc, deprecated, and doc_url to service descriptions +* Bug: Changed the default cookie header casing back to 'Cookie' + +## 2.6.5 - 2012-06-03 + +* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() +* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from +* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data +* BC: Renaming methods in the CookieJarInterface +* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations +* Making the default glue for HTTP headers ';' instead of ',' +* Adding a removeValue to Guzzle\Http\Message\Header +* Adding getCookies() to request interface. +* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() + +## 2.6.4 - 2012-05-30 + +* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. +* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand +* Bug: Fixing magic method command calls on clients +* Bug: Email constraint only validates strings +* Bug: Aggregate POST fields when POST files are present in curl handle +* Bug: Fixing default User-Agent header +* Bug: Only appending or prepending parameters in commands if they are specified +* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes +* Allowing the use of dot notation for class namespaces when using instance_of constraint +* Added any_match validation constraint +* Added an AsyncPlugin +* Passing request object to the calculateWait method of the ExponentialBackoffPlugin +* Allowing the result of a command object to be changed +* Parsing location and type sub values when instantiating a service description rather than over and over at runtime + +## 2.6.3 - 2012-05-23 + +* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. +* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. +* You can now use an array of data when creating PUT request bodies in the request factory. +* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. +* [Http] Adding support for Content-Type in multipart POST uploads per upload +* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) +* Adding more POST data operations for easier manipulation of POST data. +* You can now set empty POST fields. +* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. +* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. +* CS updates + +## 2.6.2 - 2012-05-19 + +* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. + +## 2.6.1 - 2012-05-19 + +* [BC] Removing 'path' support in service descriptions. Use 'uri'. +* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. +* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. +* [BC] Removing Guzzle\Common\XmlElement. +* All commands, both dynamic and concrete, have ApiCommand objects. +* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. +* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. +* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. + +## 2.6.0 - 2012-05-15 + +* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder +* [BC] Executing a Command returns the result of the command rather than the command +* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. +* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. +* [BC] Moving ResourceIterator* to Guzzle\Service\Resource +* [BC] Completely refactored ResourceIterators to iterate over a cloned command object +* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate +* [BC] Guzzle\Guzzle is now deprecated +* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject +* Adding Guzzle\Version class to give version information about Guzzle +* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() +* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data +* ServiceDescription and ServiceBuilder are now cacheable using similar configs +* Changing the format of XML and JSON service builder configs. Backwards compatible. +* Cleaned up Cookie parsing +* Trimming the default Guzzle User-Agent header +* Adding a setOnComplete() method to Commands that is called when a command completes +* Keeping track of requests that were mocked in the MockPlugin +* Fixed a caching bug in the CacheAdapterFactory +* Inspector objects can be injected into a Command object +* Refactoring a lot of code and tests to be case insensitive when dealing with headers +* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL +* Adding the ability to set global option overrides to service builder configs +* Adding the ability to include other service builder config files from within XML and JSON files +* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. + +## 2.5.0 - 2012-05-08 + +* Major performance improvements +* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. +* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. +* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" +* Added the ability to passed parameters to all requests created by a client +* Added callback functionality to the ExponentialBackoffPlugin +* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. +* Rewinding request stream bodies when retrying requests +* Exception is thrown when JSON response body cannot be decoded +* Added configurable magic method calls to clients and commands. This is off by default. +* Fixed a defect that added a hash to every parsed URL part +* Fixed duplicate none generation for OauthPlugin. +* Emitting an event each time a client is generated by a ServiceBuilder +* Using an ApiParams object instead of a Collection for parameters of an ApiCommand +* cache.* request parameters should be renamed to params.cache.* +* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc.). See CurlHandle. +* Added the ability to disable type validation of service descriptions +* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/vendor/guzzlehttp/guzzle/CLAUDE.md b/vendor/guzzlehttp/guzzle/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/vendor/guzzlehttp/guzzle/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/vendor/guzzlehttp/guzzle/LICENSE b/vendor/guzzlehttp/guzzle/LICENSE new file mode 100644 index 0000000..fd2375d --- /dev/null +++ b/vendor/guzzlehttp/guzzle/LICENSE @@ -0,0 +1,27 @@ +The MIT License (MIT) + +Copyright (c) 2011 Michael Dowling +Copyright (c) 2012 Jeremy Lindblom +Copyright (c) 2014 Graham Campbell +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Tobias Schultze +Copyright (c) 2016 Tobias Nyholm +Copyright (c) 2016 George Mponos + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/guzzlehttp/guzzle/README.md b/vendor/guzzlehttp/guzzle/README.md new file mode 100644 index 0000000..bd907e5 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/README.md @@ -0,0 +1,95 @@ +![Guzzle](.github/logo.png?raw=true) + +# Guzzle, PHP HTTP Client + +Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and +trivial to integrate with web services. + +- Simple interface for building query strings, POST requests, streaming large + uploads, streaming large downloads, using HTTP cookies, uploading JSON data, + etc... +- Can send both synchronous and asynchronous requests using the same interface. +- Uses PSR-7 interfaces for requests, responses, and streams. This allows you + to utilize other PSR-7 compatible libraries with Guzzle. +- Supports PSR-18, allowing interoperability with other PSR-18 HTTP clients. +- Abstracts away the underlying HTTP transport, allowing you to write + environment and transport agnostic code; i.e., no hard dependency on cURL, + PHP streams, sockets, or non-blocking event loops. +- Middleware system allows you to augment and compose client behavior. + +## Installation + +The recommended way to install Guzzle is through +[Composer](https://getcomposer.org/). + +```bash +composer require guzzlehttp/guzzle +``` + +## Version Guidance + +| Version | Status | PHP Version | +|---------|--------------|--------------| +| 8.5 | Latest | >=7.4,<8.7 | +| 7.16 | Maintenance | >=7.2.5,<8.7 | +| 6.5 | End of Life | >=5.5,<8.0 | + +## Quick Start + +```php +$client = new \GuzzleHttp\Client(); +$response = $client->request('GET', 'https://api.example.com/users/123'); + +echo $response->getStatusCode(); // 200 +echo $response->getHeaderLine('content-type'); // 'application/json' +echo $response->getBody(); // '{"id": 123, "name": "Ada"}' +``` + +For more examples, see the [Quick Start](docs/quick-start.md). + +## Documentation + +- [Quick Start](docs/quick-start.md) +- [Overview](docs/overview.md) +- [Request Options](docs/request-options.md) +- [Uploading Data](docs/uploading-data.md) +- [Cookies](docs/cookies.md) +- [Exceptions](docs/exceptions.md) +- [Guzzle and PSR-7](docs/guzzle-and-psr-7.md) +- [Handlers](docs/handlers.md) +- [Middleware](docs/middleware.md) +- [Testing Guzzle Clients](docs/testing-guzzle-clients.md) +- [FAQ](docs/faq.md) +- [Package Ecosystem](docs/package-ecosystem.md) +- [Upgrade Guide](UPGRADING.md) +- [Changelog](CHANGELOG.md) + +We use GitHub issues only to discuss bugs and new features. For support, use +[Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle), the +[#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on +[PHP-HTTP Slack](https://slack.httplug.io/), or +[Gitter](https://gitter.im/guzzle/guzzle). + +## Security + +If you discover a security vulnerability within this package, please send an +email to security@tidelift.com. All security vulnerabilities will be promptly +addressed by the security maintainers listed in the +[Security Policy](https://github.com/guzzle/guzzle/security/policy). Please do +not disclose security-related issues publicly until a fix has been announced. + +## License + +Guzzle is made available under the MIT License (MIT). Please see +[License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with +Tidelift to deliver commercial support and maintenance for the open source +dependencies you use to build your applications. Save time, reduce risk, and +improve code health, while paying the maintainers of the exact dependencies you +use. +[Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/vendor/guzzlehttp/guzzle/UPGRADING.md b/vendor/guzzlehttp/guzzle/UPGRADING.md new file mode 100644 index 0000000..65bc707 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/UPGRADING.md @@ -0,0 +1,2785 @@ +Guzzle Upgrade Guide +==================== + +7.0 to 8.0 +---------- + +Guzzle 8 is a major release that raises the minimum PHP version, updates the +Guzzle dependency stack, adopts stricter PSR-7 header and request method +behavior, changes some network exception classification, and tightens validation +for request options, protocols, transport settings, cookies, and native method +signatures. It also adds generic PHPDoc types to async APIs for static analysis. + +#### PHP Version and Dependencies + +Guzzle 8 requires PHP `^7.4 || ^8.0`. Guzzle 7 supported PHP +`^7.2.5 || ^8.0`. + +Guzzle 8 also requires Guzzle Promises 3.x and Guzzle PSR-7 3.x. If your +application pins either package directly, update those constraints to allow the +new major versions. + +Read the [Guzzle PSR-7 3.x upgrade guide][psr7-upgrade-guide] as part of every +Guzzle 8 upgrade. Guzzle's normal request and response APIs use Guzzle PSR-7, so +PSR-7 changes can affect applications even when they do not instantiate PSR-7 +classes directly. This guide calls out the most common inherited PSR-7 changes, +but it does not repeat every PSR-7 behavior change. + +Pay particular attention to [that PSR-7 upgrade guide][psr7-upgrade-guide] if +your application constructs requests, modifies responses, sets headers, uploads +files, builds multipart requests, works with URIs, or inspects streams. + +Also read the [Guzzle Promises 3.x upgrade guide][promises-upgrade-guide] if you +use async requests, custom handlers, middleware, pools, or promise helpers. + +Guzzle 8 now requires `psr/http-factory:^1.0` directly. + +[psr7-upgrade-guide]: https://github.com/guzzle/psr7/blob/3.0/UPGRADING.md +[promises-upgrade-guide]: https://github.com/guzzle/promises/blob/3.0/UPGRADING.md + +#### IPv6 Origin Canonicalization + +Guzzle PSR-7 3.x serializes IPv6 hosts in native URIs in their RFC 5952 +canonical form, and its `UriComparator::isCrossOrigin()` canonicalizes +bracketed IPv6 literals from any PSR-7 implementation before comparing +origins. Redirects between equivalent spellings of one IPv6 address are +therefore same-origin in Guzzle 8: `Authorization` and `Cookie` headers, the +`auth` option, cURL authentication options, and the same-scheme `Referer` path +and query may be retained where Guzzle 7 stripped or reduced them, and absolute +Digest `domain` protection spaces can cover an equivalent spelling of the same +address. + +Guzzle 8 also keys its own host-scoped state, the Digest challenge cache and +the cookie jar, on the canonical IPv6 form, so equivalent spellings share one +entry instead of fragmenting state. A cached Digest challenge may be reused +preemptively across spellings instead of causing another 401 probe. Host-only +cookies extracted from one spelling match requests using another, persisted +cookie domain text is canonical, and equivalent cookie entries coalesce. Bare +IPv6 cookie domains, which the cookie API permissively accepts, canonicalize +without gaining brackets, and bare and bracketed forms remain distinct +identities. Cookie-domain matching remains exact-only for IP literals and IP +addresses, and DNS suffix matching now requires both the cookie domain and the +request host to be valid non-literal, nonnumeric host names. A host counts as +numeric on its rightmost label alone, so a cookie domain such as +`svc.0xdeadbeef` is exact-only in Guzzle 8 although Guzzle 7 reads it as a name +and matches its subdomains. + +Configured proxy endpoints are not canonicalized, no-proxy matching was +already representation-independent, and the URI text sent to the transport is +not rewritten: a foreign `UriInterface` that reports a noncanonical IPv6 +spelling is serialized as supplied. IPvFuture literals, zone-bearing values, +and invalid bracketed text keep their ASCII-case-folded textual identity in +these Digest and cookie comparisons. + +#### PSR-7 Header Values + +Guzzle 8 uses Guzzle PSR-7 3.x, and several of its behavior changes surface +through normal Guzzle client usage. This section summarizes the inherited PSR-7 +changes most likely to affect Guzzle users; read the +[Guzzle PSR-7 3.x upgrade guide][psr7-upgrade-guide] for the complete list. + +Header values passed through the `headers` request option or PSR-7 request APIs +must now be strings or non-empty arrays of strings. Empty strings remain valid +explicit header values, but empty arrays, `null`, `false`, integers, floats, and +other non-string values are no longer cast or accepted. + +If your application builds headers from configuration, user input, or typed +domain values, normalize them before creating or sending requests: + +```php +// 7.x, no longer accepted in 8.0 +$client->request('GET', '/', [ + 'headers' => ['Api-Version' => 1], +]); + +// 8.0 +$client->request('GET', '/', [ + 'headers' => ['Api-Version' => '1'], +]); +``` + +#### Request Method Casing + +Guzzle 8 preserves explicitly provided request method casing. HTTP method names +are case-sensitive, so Guzzle now sends the method exactly as provided and +applies built-in method-specific behavior only to exact standard method names +such as `GET`, `HEAD`, `POST`, and `PUT`. + +If you previously relied on `new Request('get', ...)` or +`$client->request('get', ...)` being sent or treated as `GET`, normalize the +method before constructing or sending the request: + +```php +$client->request('GET', 'https://example.com'); +``` + +The convenience methods such as `$client->get()`, `$client->post()`, and their +async variants continue to use uppercase standard methods. + +#### Auth Request Option Changes + +Digest authentication is no longer implemented with cURL `CURLOPT_HTTPAUTH` and +`CURLOPT_USERPWD`. Guzzle supports legacy non-session Digest challenges without +`qop` and challenges with `qop=auth`; session algorithms require `qop`. +`auth-int` is not supported. To use libcurl's native Digest implementation +instead, omit `auth` and configure cURL options directly with a cURL handler, +including `CURLOPT_HTTPAUTH => CURLAUTH_DIGEST` and `CURLOPT_USERPWD`. + +Guzzle 8 no longer treats `ntlm` as a built-in `auth` type. If an existing +NTLM-only integration must be kept temporarily, configure cURL options directly +with a cURL handler and a libcurl build that still supports NTLM: + +```php +$client->request('GET', '/', [ + 'curl' => [ + CURLOPT_HTTPAUTH => CURLAUTH_NTLM, + CURLOPT_USERPWD => 'username:password', + ], +]); +``` + +This is not a long-term migration path. curl/libcurl has deprecated NTLM +because it is weak, deprecated by Microsoft, and does not work over HTTP/2 or +HTTP/3. curl made NTLM opt-in in curl 8.20.0 and plans to remove support in +September 2026. + +Digest requests that carry a body send the initial unauthenticated probe with an +empty body and `Content-Length: 0`, as libcurl does. The body is sent on +authenticated attempts: once in the normal one-challenge handshake, and again if +a stale-nonce challenge must be retried. Because of this, non-seekable request +bodies work with Digest authentication unless a stale-nonce retry forces a +rewind. Followed redirects also rewind the body under the normal redirect rules, +independently of Digest. If the server answers the probe with anything other +than a 401 response, a 407 proxy challenge, or a followable redirect, the request +fails with a `GuzzleHttp\Exception\ResponseException` carrying that response, +because the probe did not represent the original request; remove the `auth` +option for endpoints that do not require authentication. See "Differences from +libcurl's Digest implementation" below. + +#### Differences from libcurl's Digest implementation + +Guzzle 8's Digest middleware deliberately diverges from libcurl, which +implemented the `auth` option's Digest support in Guzzle 7, in the following +ways: + +- **Unchallenged probes fail loudly.** Body-bearing requests are probed with an + empty body. If the server answers the probe with anything other than a 401 + response, a 407 proxy challenge, or a followable redirect, Guzzle throws + `GuzzleHttp\Exception\ResponseException` with that response attached. This + exception pre-empts the `ClientException` or `ServerException` that + `http_errors` would otherwise raise for such a response; `catch + (RequestException $e)` catches both. For unchallenged sub-300 probe responses + libcurl instead re-issues the request unauthenticated, which can cause the + server to process both the empty probe and the replay; for other statuses it + surfaces the probe response. If a server does not require authentication, + remove the `auth` option. +- **Probe payload headers.** The probe strips the payload-describing headers: + `Expect`, `Transfer-Encoding`, `Trailer`, `Content-Range`, + `Content-Encoding`, `Content-MD5`, `Digest`, `Content-Digest`, and + `Repr-Digest`, and forces `Content-Length: 0`. `Content-Type` is kept, as + libcurl does. libcurl's probe is bodyless but not header-identical: it keeps a + caller-supplied `Expect`, keeps HTTP/1.1 `Transfer-Encoding`, sending a + chunked probe with a zero chunk and no `Content-Length`, and forwards other + caller headers untouched. Guzzle's stripping is deliberately stricter. +- **`auth-int` is rejected.** Challenges offering only `qop=auth-int` are + ignored. libcurl selects `auth-int` when `auth` is absent but hashes an empty + entity body, providing no actual body integrity. +- **Challenge selection.** With multiple Digest challenges, Guzzle picks the + strongest supported algorithm. libcurl decodes the first Digest + `WWW-Authenticate` header field and ignores later Digest fields. Multiple + Digest challenges inside one field are parser-dependent in curl. +- **Strict challenge parsing.** Challenges with duplicated or malformed + parameters are rejected. When another usable Digest challenge is present, it + is used instead, always across separate `WWW-Authenticate` header fields and + in some same-field shapes. The 401 is returned untouched only when no usable + Digest challenge remains. libcurl is lenient: later duplicate values overwrite + earlier ones, `stale` and `userhash` flags are sticky once set, and malformed + tails are tolerated after enough valid material has been parsed. +- **Challenge reuse.** Cached challenges authorize later body-less requests + preemptively with incremented nonce counts; body-bearing requests always + re-probe, and only challenges that produced an authenticated success are + cached. libcurl kept Digest state per easy handle, which Guzzle 7 reset between + requests, so 7.x re-handshook every request. Guzzle honors the RFC 7616 + `domain` parameter when scoping reuse, and curl's Digest state has no `domain` + handling. Guzzle generates a fresh cnonce per Authorization header, where + curl's non-SSPI implementation reuses one cnonce per nonce while incrementing + `nc`. When `domain` is absent the cached challenge covers the whole origin, so + on origins that host multiple realms or trust boundaries a preemptive request + can disclose the username or userhash and password-derived response material + for one realm to another same-origin endpoint before it challenges; use + separate origins, a server-side `domain`, or disable reuse by replacing the + default auth middleware with `GuzzleHttp\Middleware::auth(false)` as shown in + the `auth` request option documentation. +- **Per-leg observability.** Each handshake leg is a separate transfer: + `on_stats`, `on_headers`, and `progress` fire per leg, and `delay` applies + once, before the first Digest leg: the probe, or a preemptive request when + challenge reuse applies. libcurl performed the whole handshake inside one + transfer with one stats callback. +- **Streaming sinks.** With `stream => true` plus a configured `sink`, a Digest + request drains the final body into the sink, protecting sinks from challenge + bodies on handlers that ignore `stream`. A non-digest request on the stream + handler leaves the sink untouched. +- **Proxy Digest (407) is not implemented.** The response passes through. The + built-in cURL handlers allow proxy credentials but not `CURLOPT_PROXYAUTH`, + and libcurl defaults proxy auth to Basic, so proxy Digest requires a custom + handler. + +Non-seekable request bodies work for the normal handshake because the probe never +consumes them. A stale-nonce retry after the body has been consumed still +requires a seekable body, the same limit libcurl has. + +Built-in Basic and Digest authentication continue to work for clients using +Guzzle's default handler or `GuzzleHttp\HandlerStack::create($handler)`, but +they are now applied by the default auth middleware instead of while the client +constructs the request. If you pass a raw custom handler directly to `Client`, +remove default middleware, or build a handler stack manually, Basic and Digest +authentication will only be applied when your stack includes +`GuzzleHttp\Middleware::auth()`. Unknown auth type strings are left in the +request options for custom middleware or custom handlers. + +Guzzle also validates non-empty auth arrays before applying them: indexes `0` +and `1` must be username and password strings, and index `2`, when present, must +be a string or `null`. Invalid auth arrays that previously emitted warnings, +coerced values, or did nothing now throw +`GuzzleHttp\Exception\InvalidArgumentException`. + +```php +// Valid: +$client->request('GET', '/', [ + 'auth' => ['username', 'password', 'basic'], +]); + +// Invalid in 8.0: +$client->request('GET', '/', [ + 'auth' => ['username'], +]); +``` + +Guzzle 8's built-in authentication middleware rejects Basic `auth` credentials +when the username contains a colon or either the username or password contains +an ASCII control character. Guzzle 7 encoded and sent these values. Colons +remain valid in passwords. + +Guzzle 8 also no longer forwards the generic `auth` request option when +automatic redirects cross origin. Guzzle already removed the `Authorization` and +`Cookie` headers and cURL HTTP authentication options on cross-origin redirects; +this now also applies to handler-visible `auth` state. + +Same-origin redirects continue to preserve `auth`. If an application or custom +handler intentionally reused `auth` across redirected origins, disable automatic +redirects or handle redirects manually so each origin receives explicit +credentials. + +#### Exception Hierarchy and Classification + +Some Guzzle 8.0 exception changes add intermediate classes, while others +intentionally reclassify specific failures. Broad `TransferException` and +`GuzzleException` catch blocks still catch all Guzzle transfer failures, and +`RequestException` still catches response-aware and other non-network request +failures. More specific catch blocks need auditing: Guzzle 8.0 splits timeout +failures into connect-phase, no-response network, and response-aware timeout +classes, and the built-in cURL and stream handlers classify more transport +failures by transfer phase. This section covers upgrading from Guzzle 7.x to +Guzzle 8.0. The `ConnectException` inheritance change happened earlier, in +Guzzle 7.0.0, when it moved out from under `RequestException`; see the 6.0 to +7.0 notes for that migration. The hierarchy changes are easiest to compare in +the two trees below. + +Guzzle 7.x uses this hierarchy: + +```text +. \RuntimeException +└── TransferException (implements GuzzleException) + ├── ConnectException (implements NetworkExceptionInterface) + └── RequestException (implements RequestExceptionInterface) + ├── BadResponseException + │ ├── ClientException + │ └── ServerException + └── TooManyRedirectsException +``` + +Guzzle 8.0 uses this hierarchy: + +```text +. \RuntimeException +└── TransferException (implements GuzzleException) + ├── HandlerClosedException + ├── NetworkException (implements NetworkExceptionInterface) + │ ├── ConnectException + │ │ └── ConnectTimeoutException + │ └── NetworkTimeoutException + └── RequestException (implements RequestExceptionInterface) + └── ResponseException + ├── BadResponseException + │ ├── ClientException + │ └── ServerException + ├── ResponseTransferException + │ └── ResponseTimeoutException + └── TooManyRedirectsException +``` + +`NetworkException` is new in Guzzle 8.0 as the base class for no-response +network failures. Throughout Guzzle 7.x, `ConnectException` implements +`Psr\Http\Client\NetworkExceptionInterface` directly and there is no +Guzzle-specific network base class. Reusable packages that support both Guzzle +7.x and 8.0 should catch `Psr\Http\Client\NetworkExceptionInterface` for +no-response network failures. Applications or packages that require Guzzle 8.0 +may catch `GuzzleHttp\Exception\NetworkException` for all no-response network +failures. Keep catching `ConnectException` only when handling connection +establishment failures specifically. + +Guzzle 8.0 also makes response-aware request failures explicit. Guzzle 7.x does +not have `ResponseException`, and response-aware request failures remain under +`RequestException` throughout Guzzle 7.x. In Guzzle 8.0, `ResponseException` is +the base class for request failures where response headers were received and a +response object is available. `ResponseTransferException` is used for +transfer-level failures after headers, including response-aware network, +protocol, content-decoding, partial-body, and response-body transfer failures. +`BadResponseException` and `TooManyRedirectsException` also extend +`ResponseException`; custom subclasses of those existing classes, or of +`ClientException` and `ServerException`, must not override the now-final +`ResponseException::__construct()`. + +Only this branch exposes response access: `RequestException` no longer stores +responses, no longer accepts a response constructor argument, and no longer has +`getResponse()` or `hasResponse()` methods. Catch `ResponseException`, or test +with `instanceof ResponseException`, before calling `getResponse()`. + +Timeout exception classes are now split by the transport phase the handler can +determine. `ConnectTimeoutException` is thrown for detected connect timeouts +(DNS resolution, TCP connect, proxy CONNECT, or TLS handshake). It extends +`ConnectException`, so code that catches `ConnectException` will also catch +connect timeouts. `NetworkTimeoutException` is thrown for other detected +transport timeouts before response headers are received. It extends +`NetworkException`, but not `ConnectException`. `ResponseTimeoutException` is +thrown for response transfer timeouts after response headers are received. It +extends `ResponseTransferException` and exposes the response. + +Timeouts that originate from caller-supplied PSR-7 streams are not transport +timeouts. Reading the request body stream, including size detection, +stringification, rewind, and upload reads, is a `RequestException` before a +response and a `ResponseException` after response headers. A slow response +`sink` write is a `ResponseException` once a response exists, or a +`RequestException` otherwise. + +If a handler throws `Error`, `TypeError`, or another non-`Exception` `Throwable` +before returning a promise, `Client::sendAsync()` returns a rejected promise. +Waiting on it rethrows the original throwable. During request and response body +handling outside native cURL callbacks, Guzzle still wraps `\Exception` failures +as `RequestException` or `ResponseException` where appropriate, while +non-`Exception` throwables propagate unchanged. Native cURL callbacks remain +different. A throwable from a cURL `sink` write is wrapped as +`ResponseException` when a response was received, or `RequestException` +otherwise, and the cURL handlers continue to report `CURLE_WRITE_ERROR` as +`on_stats` handler error data. + +`HandlerClosedException` is new in Guzzle 8.0. It extends `TransferException` +and is used when an explicitly closed `CurlMultiHandler` rejects transfers that +are still pending, including delayed transfers. Existing Guzzle 7.x code should +not normally see this exception just by upgrading. Guzzle 7.x did not have this +exception or a public cURL handler `close()` method, and destructor cleanup did +not reject pending promises. If you add deterministic cleanup with +`CurlMultiHandler::close()`, wait for or cancel outstanding transfers first, or +handle `HandlerClosedException` or `TransferException` for pending promises you +may still observe. + +When updating catch blocks for Guzzle 8.0, catch the more specific no-response +and response-aware failures before `RequestException`: + +```php +use GuzzleHttp\Exception\NetworkException; +use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\Exception\ResponseException; +use GuzzleHttp\Exception\ResponseTransferException; + +try { + $client->request('GET', $uri); +} catch (NetworkException $e) { + // No-response network failures, including reclassified cURL and stream + // handler failures. +} catch (ResponseTransferException $e) { + $response = $e->getResponse(); + + // Transfer-level failures after response headers were received. +} catch (ResponseException $e) { + $response = $e->getResponse(); + + // Other request failures after response headers were received. +} catch (RequestException $e) { + // Request failures where Guzzle does not expose a response object. +} +``` + +The built-in handlers also reclassify several failures that Guzzle 7.x reported +as `RequestException` or `ConnectException`: + +- Connection-establishment failures (DNS and proxy resolution, TCP connect, TLS + setup, and QUIC connect) are `ConnectException`. +- Other failures with no response, such as send and receive errors and + no-response HTTP/2 and HTTP/3 protocol errors, are `NetworkException`. +- Response-transfer failures after response headers were received are + `ResponseTransferException`. This includes response-aware cURL connection, + network, protocol, content-decoding, partial-body, and response body transfer + failures. Response-body network stalls are `ResponseTimeoutException`, while + `sink` write failures, progress callback failures, deterministic response + size/platform-limit failures, or request-body stalls after headers are plain + `ResponseException` instances. +- Post-transfer response finalization failures are also plain + `ResponseException`. A seekable response sink that fails to rewind does not + become a `ResponseTransferException`. Non-seekable sinks are not rewound, and + source close cleanup after a complete stream-handler download is best effort. +- Other non-transfer or local failures that occur after a response was received + are `ResponseException`. + +This applies to both the cURL and stream handlers; the exact error codes and +messages each one maps onto these classes are an implementation detail. + +The cURL handler no longer treats non-`101` informational responses such as +`100 Continue`, `102 Processing`, or `103 Early Hints` as the final response. If +a cURL transfer fails after receiving only one of those interim responses, +Guzzle now reports a no-response failure such as `NetworkException` instead of a +`ResponseTransferException` carrying the interim `1xx` response. Code that +previously caught this path with `RequestException` or +`RequestExceptionInterface` should catch `NetworkExceptionInterface` or +`TransferException` instead. `101 Switching Protocols` is unchanged and is still +surfaced as a response. + +The built-in cURL and stream handlers now reject a response subject to body +framing when its `Content-Length` is malformed, conflicting, or present with +`Transfer-Encoding`. Equivalent decimal duplicates remain valid, including +leading zeros. Like libcurl 8.14 and newer, both handlers also reject a +`Transfer-Encoding` that names a coding other than `chunked` or `identity`, or +names `chunked` before another coding on the same header line. Framing failures +detected from a complete header block occur before `on_headers` sees that +response or any of its body bytes are delivered, and raise +`ResponseTransferException`. A transport that rejects the block first can +instead report its existing transfer failure. When a handler needs the length as +a PHP integer, a valid value above `PHP_INT_MAX` raises plain +`ResponseException` with the underlying `OverflowException` available through +`getPrevious()`. The stream handler does not impose this platform limit on +`stream => true` responses. Framing validation does not apply to responses to +`HEAD`, any `1xx`, `204`, `304`, or successful `CONNECT`. `205 Reset Content` +remains subject to framing validation. + +The stream handler also raises `ResponseTransferException` after draining a +non-streamed response when a valid, positive `Content-Length` declares more +bytes than it receives. For decoded gzip and deflate, the length applies to +encoded bytes before decompression, and the original values remain in +`x-encoded-content-length`. It raises the same exception when a chunked body +ends before its last chunk or has malformed chunk framing, or when a decoded +gzip or deflate body has data after the compressed stream; reading such a body +with `stream => true` throws a `\RuntimeException` once the bytes before the +fault have been returned. Valid `stream => true` responses remain lazy after +header validation, but end at a valid `Content-Length` that fits in a PHP +integer, and a read that reaches the end of the connection first throws a +`\RuntimeException`. A `Content-Length` of `0` gives an empty body; Guzzle 7 +read such a body until the connection closed. + +For chunked responses through the stream handler, the transport resource's +`wrapper_data` can now retain the original `Transfer-Encoding`. This is visible +on streamed bodies and to custom stream factories. On PHP 8.1.20+, 8.2.7+, and +8.3+, `progress` also counts raw chunk framing coalesced with the response +headers. Later socket reads were already counted before decoding. Guzzle's +response continues to expose the decoded body without that consumed header. A +streamed chunked body detached after it has been partly read is a Guzzle stream +resource that keeps decoding it, rather than the transport resource. + +The deprecated `RequestException::wrapException()` method was removed. Create a +`RequestException` directly for request failures where Guzzle does not expose a +response object. Its third constructor argument is now the exception code, +followed by the previous exception. For failures with a response, create +`ResponseException`, `ResponseTransferException`, `ResponseTimeoutException`, +`BadResponseException`, `ClientException`, `ServerException`, or +`TooManyRedirectsException` instead. If you used the removed +`getHandlerContext()` methods to classify failures, use the more granular +exception classes above instead, or use `on_stats` when you need handler timing +or statistics. `GuzzleHttp\Exception\InvalidArgumentException` remains outside +the transfer exception hierarchy and is still used for invalid configuration or +request option values that can be rejected before a transfer starts. + +`RequestException::create()` no longer accepts a handler-context array. Its +fourth argument is now the optional `BodySummarizerInterface`; remove any +handler-context argument and use the new exception classes or `on_stats` when you +need transport details. + +`TransferException` itself now also requires the failing request as its second +constructor argument, and its message argument is no longer optional; +`getRequest()` is available on the entire transfer exception hierarchy. The +subclasses' own constructors, such as `RequestException` and +`ConnectException`, already required a request in Guzzle 7, so only code +constructing the base class changes: replace `new TransferException('msg')` +with `new TransferException('msg', $request)`. + +#### Request Body Framing + +Before sending a body, the built-in cURL and stream handlers now finalize the +request framing. Each `Content-Length` value must be a non-negative decimal +integer that the selected transport can represent. Multiple values are allowed +only when they agree. Guzzle emits a single canonical value, and it must match +the available body size when that size is known. A request cannot include both +`Content-Length` and `Transfer-Encoding`. The only request transfer coding +Guzzle supports is a single `chunked` value on HTTP/1.1. Guzzle removes that +marker and adds an exact length when one is available. Otherwise, it lets the +transport choose valid wire framing. Other codings, coding chains, repeated +`chunked` values, unknown-length HTTP/1.0 bodies, and `chunked` on other HTTP +versions are rejected. + +A `Transfer-Encoding: chunked` header is only a provisional framing marker: +Guzzle treats the request body as content, never as pre-encoded chunks. Callers +that pre-encoded bodies for Guzzle 7's stream handler must remove the chunk +framing before upgrading, or the server receives it as literal content. + +For an unknown-size body with an explicit `Content-Length`, the stream handler +treats that length as the body boundary and does not read beyond it. Both +handlers reject premature EOF and request-body streams that return more bytes +than requested. The stream handler captures an otherwise unknown body once and +sends it with its exact length. Violations raise `RequestException` before a +response, or plain `ResponseException` if a cURL request-body read fails after +response headers. Omit both framing headers and let Guzzle choose. + +`PrepareBodyMiddleware` now adds a provisional `Transfer-Encoding: chunked` +marker only to unknown-size HTTP/1.1 bodies. For other protocol versions, custom +handlers receive no provisional framing header. + +A retry that reuses a consumed non-seekable body now fails if its known +remaining size no longer matches an explicit `Content-Length`. Use a seekable or +otherwise repeatable body for requests that may be retried. + +#### Request Option Validation + +Guzzle 8 rejects additional malformed request option values at the client +boundary. `force_ip_resolve` must be `v4` or `v6`; `protocols` and +`allow_redirects.protocols` may contain only `http` and `https`; and `delay` +must be finite and non-negative. Per-request `cookies` values must be `false` +or a `CookieJarInterface`; the `true` shorthand is only valid in the client +constructor. + +The following 33 options are now validated against their documented types +before a transfer starts. + +The boolean flags `http_errors`, `stream`, and `synchronous` must be `bool`. +`decode_content` and `verify` accept `bool` or `string`, `expect` accepts +`bool` or `int`, and `debug` accepts `bool` or a stream resource. +`allow_redirects` accepts `bool` or an array in which `max` is an `int`; +`strict`, `referer`, and `track_redirects` are `bool`; `on_redirect` is a +callable; and `protocols` is a non-empty array of `http` and `https` strings. + +`crypto_method`, `crypto_method_max`, and `retries` must be `int`. +`connect_timeout`, `read_timeout`, and `timeout` must be `int` or `float`, +`delay` must be a finite, non-negative `int` or `float`, and `version` accepts +`string`, `int`, or `float`. `cert_type` and `ssl_key_type` must be `string`. + +`cert` and `ssl_key` accept a `string` path or a `[path, password]` array +whose optional password may be a `string` or `null`. `auth` accepts `false`, a +`string`, or a `[username, password]` array of strings with an optional third +element that may be a `string` or `null`. + +`headers` must be an array whose values are strings or non-empty arrays of +strings. `form_params` must be an array of strings, numbers, booleans, `null`, +or nested arrays of the same, and its floats must be finite. `multipart` must +be an array of part arrays, each with a `string` or `int` `name`, a `contents` +entry, optional `string` header values, and an optional `string` `filename`. +`protocols` must be a non-empty array containing only `http` and `https`. +`curl` and `stream_context` must be arrays. + +`on_headers`, `on_stats`, `on_trailers`, and `progress` must be callables. +`sink` accepts a `string` path, a stream resource, or a `StreamInterface`, and +per-request `cookies` values must be `false` or a `CookieJarInterface` as +described above. Invalid values throw +`GuzzleHttp\Exception\InvalidArgumentException` naming the option and the +expected types. + +A few build- or version-specific rejections that previously threw +`InvalidArgumentException` now throw `RequestException`, matching how the +HTTP-version capability checks already behave: requesting `crypto_method` TLS +1.3 on a libcurl built without it, and a stream-handler proxy whose raw +transport this PHP build's `stream_get_transports()` does not provide (for +example `tls://` on a build without OpenSSL). The same input works on another +build, so it is a request failure rather than a caller error; a scheme invalid +on every build (such as `udp://` or `ftp://` for a proxy) still throws +`InvalidArgumentException`. Only code catching the specific exception type for +these build-misses needs to change. + +#### Per-request Handler Option + +Guzzle 7 deprecated the `handler` request option with a warning that Guzzle 8 +would ignore request-level handlers. Guzzle 8 rejects the option instead: +passing `handler` in per-request options throws +`GuzzleHttp\Exception\InvalidArgumentException` before a transfer starts. +Silently ignoring the option would fail open — a test that supplied a +per-request `MockHandler` would fall through to the client's real handler and +hit the network. Configure the handler when creating the client, or use a +separate client instance for requests that need a different handler: + +```php +// Guzzle 7 (deprecated, used the request-level handler) +$client->request('GET', '/status', ['handler' => $mockHandler]); + +// Guzzle 8 +$client = new Client(['handler' => HandlerStack::create($mockHandler)]); +$client->request('GET', '/status'); +``` + +#### Body Summaries In HTTP Error Exceptions + +Guzzle's default `http_errors` middleware uses `BodySummarizer` to include a +short response body summary in response-aware exception messages. In Guzzle 7, +creating that summary rewound seekable response bodies to the beginning. In +Guzzle 8, `BodySummarizer` still summarizes from the beginning of the body, but +then restores the body cursor to its previous position. + +Most applications do not need changes. Check only code that catches +response-aware exceptions from `http_errors` and then reads the response body +while relying on exception creation to leave that body rewound. If you need to +read the body from the beginning after catching the exception, call +`Message::rewindBody()` explicitly. + +#### Request Protocol Versions + +Invalid request protocol versions are no longer treated as omitted. Passing +`'version' => ''`, `'version' => 'HTTP/1.1'`, or sending a PSR-7 request whose +protocol version is empty or malformed now fails before the request is sent. + +Omit the `version` request option to use Guzzle's default HTTP/1.1 behavior, or +pass an explicit supported protocol version such as `'1.1'`. Do not include the +`HTTP/` prefix. + +Invalid `version` request option values are still rejected with +`GuzzleHttp\Exception\InvalidArgumentException` before a request is sent. +Empty or malformed protocol versions returned by a `RequestInterface`, and +well-formed but unsupported protocol versions such as HTTP/3 with the stream +handler, now fail with `GuzzleHttp\Exception\RequestException`. If you +previously caught `InvalidArgumentException` or `ConnectException` for request +protocol version failures, catch `RequestException` or `GuzzleException` +instead. + +#### Callback Semantics + +If you use the `progress` request option with the built-in cURL handlers, audit +callbacks for return values. Any truthy return value now aborts the transfer and +rejects the request with `ResponseException` when a response is available, or +`RequestException` otherwise. Return `0`, `false`, or nothing to keep the +transfer running. + +If a cURL `progress` callback throws, catch `ResponseException` for +response-aware failures or `RequestException` for broader request failures, and +inspect `getPrevious()` for the original throwable. The throwable no longer +escapes directly from the native cURL callback. + +The stream handler still ignores `progress` return values. + +Exceptions thrown by `on_stats` remain unwrapped, so existing catch logic for +`on_stats` exceptions does not need to change. The built-in cURL handlers now +release native easy handles before invoking `on_stats`. Built-in handlers now +reject non-callable `on_stats` values before starting the transfer, and the +built-in cURL handlers reject non-callable `on_trailers` values the same way. +Raw callbacks passed through the `curl` request option remain low-level cURL +callbacks and are not normalized by Guzzle. + +The `on_headers` request option callback now receives the request as its second +argument. Existing userland callbacks that accept only the response continue to +work, but callbacks that inspect all arguments, for example with +`func_get_args()` or a variadic parameter, will observe the additional +`Psr\Http\Message\RequestInterface` argument. + +The `on_trailers` request option callback now receives the request as its third +argument, after the trailer array and the response; callbacks that accept only +the first two arguments continue to work. Exceptions thrown by `on_trailers` +now reject the request with `ResponseException` instead of `RequestException`, +and the callback now runs before `on_stats` instead of after it, so `on_stats` +observes an `on_trailers` failure as the transfer's outcome. + +When requests are sent through `GuzzleHttp\Pool`, the pool now appends the +request's iterable key as one extra trailing argument to any `on_headers`, +`on_trailers`, `on_stats`, `progress`, and `allow_redirects.on_redirect` +callbacks provided via its "options" configuration; callable requests yielded +to the pool likewise receive the wrapped callbacks in their options argument. +Existing userland callbacks that do not declare the extra parameter continue +to work unchanged, but callbacks that inspect all arguments, for example with +`func_get_args()` or a variadic parameter, will observe the additional +argument, and arity-strict PHP internal callables used directly may reject the +extra argument and should be wrapped in a userland callback. `progress` return +values are still honoured, and requests sent directly through a client are +unaffected. + +The built-in handlers invoke `on_headers` for the final response headers and for +`101 Switching Protocols`, but not for other informational `1xx` responses such +as `100 Continue` or `103 Early Hints`. Guzzle does not expose a separate Early +Hints API; a dedicated interim-response hook may be added in a future minor +release. + +#### No-Content Response Bodies + +The stream handler never reads the response body of a HEAD request, of a 1xx, +204, or 304 response, or of a 2xx response to a CONNECT request. Such responses +now always carry an empty body created by the configured `stream_factory`; the +transport connection is closed as soon as the headers (and the `on_headers` +callback) complete successfully; the `sink` option is not opened or written +(string path sinks create no file); and `stream => true` yields the empty stream +rather than the live transport stream. In particular, `stream => true` no longer +exposes the live transport for a 2xx CONNECT response. Per RFC 9110 these +responses cannot carry content, so any bytes a misbehaving server sends after +the header section are never read. The cURL handler already behaved this way via +libcurl. + +#### HTTP/2 Multiplexing + +The `multiplex` request option defaults to `Multiplexing::WAIT`: +HTTP/2 requests on the cURL handlers set libcurl's `CURLOPT_PIPEWAIT`, so a +concurrent burst waits for an in-progress connection it may be able to share +instead of dialing one connection per request. Guzzle 7 leaves this to libcurl, +which never waits by default. Pass +`'multiplex' => Multiplexing::EAGER` to restore the old dialing +behaviour, or `Multiplexing::REQUIRE_EAGER`/`Multiplexing::REQUIRE_WAIT` to +fail loudly unless a multiplexed protocol is guaranteed. + +HTTP/2 requests also now require libcurl 7.65.2 or newer, so waiting is never +silently unavailable where HTTP/2 works. + +#### Sink Resource Ownership + +PHP resources passed as the `sink` request option are no longer closed when the +response body is closed or garbage-collected by the built-in cURL and stream +handlers. Applications that relied on Guzzle closing a raw resource sink should +close the resource explicitly or pass a string path instead. + +#### Stream Handler Header Serialization + +The stream handler now trims only the trailing CRLF pair from the serialized +header block it passes to the PHP stream context. Guzzle 7 also removed other +trailing whitespace there, which could drop trailing spaces or horizontal tabs +from the final header value when a request came from a PSR-7 implementation +that does not trim header values. + +#### TLS Minimum Version + +The built-in cURL and stream handlers now default HTTPS requests to TLS 1.2 or +newer. Applications that must connect to legacy TLS 1.0 or TLS 1.1 endpoints can +explicitly lower the minimum version with the `crypto_method` request option: + +```php +$client->request('GET', 'https://legacy.example.com', [ + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT, +]); +``` + +#### cURL Minimum Version + +Guzzle 8 requires libcurl 7.34.0 or higher with SSL/TLS support when using the +built-in cURL handlers. If this requirement is not met, the default handler +stack will not select cURL automatically, and manually configured cURL handlers +reject requests. + +`GuzzleHttp\Handler\Proxy::wrapTlsFallback()` has been removed. Custom handler +stacks no longer need it; the default handler stack selects the cURL or stream +handler based on this TLS support automatically. + +#### cURL Handler Lifecycle + +Applications that manage built-in cURL handlers or factories directly should +treat closed instances as unusable. Reusing a closed `CurlHandler`, +`CurlMultiHandler`, or `CurlFactory` throws `BadMethodCallException`; create a +new instance instead. + +If `CurlMultiHandler::close()` is called while transfers are pending, those +promises are rejected with `GuzzleHttp\Exception\HandlerClosedException`. +Destructor cleanup remains best-effort and does not reject pending promises. + +A custom `handle_factory` passed to a built-in cURL handler remains +caller-owned. Closing the handler does not close an injected factory. + +#### Timeout Option Validation + +Built-in handlers validate timeout option values when they apply those options. +`timeout` is applied by both built-in transports. `connect_timeout` is applied +by cURL handlers and accepted without effect by the stream handler. +`read_timeout` is applied by the stream handler and accepted without effect by +cURL handlers. When a built-in handler applies a timeout option, positive +values below `0.001` seconds now throw `InvalidArgumentException` instead of +being converted to no timeout. + +#### Stream Handler Timeout Enforcement + +The stream handler now enforces the `timeout` request option as a total +transfer deadline when it buffers the response, matching the cURL handlers' +treatment of the option as the total time of the request. Once the deadline +passes while the response body is being buffered, the transfer is aborted and +the request is rejected with `ResponseTimeoutException`. Each body read is +bounded by the shorter of the `read_timeout` idle timeout and the remaining +total timeout. A response whose header block arrives in small pieces past the +deadline is rejected once the headers are complete, because PHP's HTTP stream +wrapper can only bound the time between packets while waiting for response +headers. In Guzzle 7, the stream handler applies `timeout` only while +connecting and as the idle time between packets, so a server that keeps +sending small pieces of data can extend a request past the configured timeout +indefinitely and still produce a successful response. + +With the `stream` request option enabled, a response whose header block +completes past the deadline is rejected in the same way, and the response +carried by the exception has a closed body. The deadline does not apply to the +streamed response body, which is governed by the `read_timeout` idle timeout. + +#### Stream Handler Timeout Model + +The stream handler now treats `timeout` and `read_timeout` as orthogonal +controls. `timeout` is the total deadline for completing a buffered request or +obtaining a streamed response, with no deadline by default. `read_timeout` is +an idle timeout bounding how long the connection may sit silent at any stage, +while connecting, waiting for response headers, and between reads on the body, +defaulting to 60 seconds; `0` disables it. Any received data resets the idle +clock; nothing resets the deadline. + +In Guzzle 7, both behaviours fall back to the `default_socket_timeout` ini +setting (60 seconds by default), `timeout` also acts as the idle cap, and +`read_timeout` only governs streamed reads. Set `read_timeout` explicitly to +tune or disable idle protection; `default_socket_timeout` no longer has any +effect on the stream handler. + +#### Connect Timeout Default + +The built-in cURL handlers now default the connect timeout to 60 seconds +instead of libcurl's 300, and `connect_timeout` set to `0` now disables the +connect timeout instead of selecting the 300-second libcurl default, matching +how `0` disables the `timeout` and `read_timeout` options. The stream handler +still accepts `connect_timeout` without effect; its connect phase is bounded +by the `read_timeout` idle timeout, which shares the 60-second default. + +#### Stream Handler Header Injection + +The stream handler no longer lets PHP's HTTP stream wrapper inject header +values from ini configuration. A request without a User-Agent header no longer +sends the `user_agent` ini value, and the `from` ini value is no longer sent: +the wrapper offers no way to omit the From header entirely, so deployments +that configure the ini send an empty From header instead of the configured +address. Both now match the cURL handlers, which ignore those ini settings. +Set the headers explicitly on the request or client to send them. + +#### Proxy Option Validation + +The `proxy` request option is validated more strictly. Proxy values must be +strings, and the `proxy['no']` value may be either an array of strings or a +comma- or whitespace-delimited string such as the value from the `NO_PROXY` +environment variable. Other values now throw `InvalidArgumentException`. +Guzzle 7 skips invalid `no` entries instead of rejecting them. + +When a request uses HTTP/3 and a proxy is resolved from the environment, the +request is now downgraded to HTTP/2 or HTTP/1.1 in the same way as for proxies +configured through the `proxy` request option, since current libcurl releases +cannot carry HTTP/3 over an HTTP proxy. A request excluded by the environment +`no_proxy` list stays direct and keeps HTTP/3. + +#### No-Proxy Interpretation + +No-proxy lists are interpreted identically everywhere they appear — the option's +`no` list, the client-mapped `NO_PROXY` environment variable, and the +environment `no_proxy` consulted by the built-in handlers — and the shared +interpretation follows libcurl's. Compared to Guzzle 7, this changes how string +lists are tokenized, how leading-dot entries match, and what a match means. + +String `no` lists are split on whitespace as well as commas, and a leading-dot +entry such as `.example.com` now matches `example.com` as well as its +subdomains, exactly like the bare `example.com` entry. Both changes align the +option's matching with libcurl's interpretation of `no_proxy`, which the +environment path already followed. In Guzzle 7, the client mapping removes +spaces from `NO_PROXY` values, while the option form treats space-joined +values as a single entry that never matches and limits leading-dot entries to +subdomains. + +A matching `no` entry now applies even when the array does not configure a proxy +for the request scheme: the request goes direct, and the built-in handlers do +not fall back to an environment proxy for it. The `no` list is also validated in +that case. Guzzle 7 ignores the `no` list entirely unless the array selects a +proxy for the request scheme. + +#### Proxy URL Validation + +The stream handler now throws `InvalidArgumentException` for any proxy URL +whose scheme it cannot execute: `https://`, SOCKS (`socks4://`, `socks4a://`, +`socks5://`, `socks5h://`), and anything other than `http://` or a raw PHP +transport such as `tcp://`, `ssl://`, or `tls://`. Guzzle 7 passed these to +PHP, which failed later with an "unable to find the socket transport" error. +The cURL handlers reject a `proxy` URL whose scheme libcurl cannot use as a +proxy with the same exception. Raw PHP transport values still pass through the +stream wrapper unchanged. + +Both handlers also reject a malformed proxy URL (an invalid host, an +out-of-range port, or leading junk before the scheme) up front with the same +`InvalidArgumentException`, instead of passing it to libcurl or PHP to fail on +later. + +An `http://` or scheme-less proxy that omits the port now defaults to 1080, +libcurl's default HTTP proxy port, so `proxy.example.com` resolves to +`tcp://proxy.example.com:1080`. Guzzle 7 passed a port-less proxy through +unchanged, which PHP's stream wrapper could not use because it requires an +explicit port. + +#### Proxy Tunnels and HTTPS Proxies + +Requests tunneled through an HTTP proxy, meaning an `https://` target sent +through an `http://` or `https://` proxy, or a tunnel forced with raw `curl` +options, now require libcurl 7.54.0 or newer. HTTPS proxies (an `https://` +proxy URL, where the connection to the proxy itself is encrypted) also now +require libcurl 7.54.0 built with HTTPS-proxy support, raised from the 7.52.0 +floor used in Guzzle 7. The built-in cURL handlers reject such requests on +older libcurl with a `RequestException` before they are sent, matching the +other build- and version-specific capability checks. + +On supported libcurl, the proxy's CONNECT reply is suppressed with +`CURLOPT_SUPPRESS_CONNECT_HEADERS`. Guzzle 7 delivered the interim +`200 Connection established` header block to the `on_headers` callback and +could attach it to exceptions as a response. In Guzzle 8, `on_headers` +observes only origin responses, and a tunneled transfer failure is classified +by its transport phase instead of as a response failure carrying the proxy's +interim reply. + +#### Proxy-Authorization Headers + +In Guzzle 8, every first-class `Proxy-Authorization` field handled by a built-in +cURL handler requires libcurl 7.37.0 or newer with proxy header separation +support, regardless of Guzzle's predicted route. This includes an empty field, +which keeps its cURL header-control meaning in the proxy-only list, and requests +predicted to be direct, no-proxy-bypassed, or sent through SOCKS. A request is +rejected with a `RequestException` before network I/O when separation is not +available. Guzzle 7 instead omits the field on those known non-HTTP-proxy routes +and requires separation only when it cannot safely discard the field. + +Guzzle 8 also rejects a raw `CURLOPT_PROXYHEADER` list when proxy header +separation is unavailable. Guzzle 7.15 only deprecates the raw option and passes +it through to the installed PHP cURL extension and libcurl. + +When the stream handler selects a proxy, Guzzle 8 rejects any first-class +`Proxy-Authorization` field, including an empty value, because PHP streams have +no proxy-only header channel. Guzzle 7 instead accepts exactly one value, +rejects carriage returns and line feeds, and adds one canonical proxy +authorization line after selecting the proxy. That first-class value, including +an empty one, takes precedence over Basic credentials in proxy URL userinfo; +multiple values are rejected. Direct and no-proxy-bypassed stream requests omit +the field in both versions. Configure Basic proxy credentials in the proxy URI +or use a cURL handler for a first-class proxy authorization field. + +#### Proxy Tunnels Under Shared Connection Caches + +From libcurl 7.57.0, a cURL share handle passed directly to `CurlFactory` and +Guzzle's worker-global persistent sharing pools are treated as opaque +connection caches: anonymous HTTP and HTTPS proxy tunnels are forced onto +fresh, non-reusable connections, and `TransportSharing::PERSISTENT_REQUIRE` +rejects them. Guzzle 7 applies the same policy to its configured share handles +and additionally rejects the deprecated request-level `CURLOPT_SHARE` option +for proxy tunnels there; Guzzle 8 rejects that raw option outright, so only +the configured and persistent surfaces exist. Handler-lifetime +`transport_sharing` keeps ordinary tunnel reuse because its shares never lock +connections. + +#### Proxy Environment Variable Resolution + +The stream handler now resolves proxies from the environment the same way the +cURL handlers do. When the `proxy` request option makes no decision for a +request, it reads `http_proxy` (lowercase only), `https_proxy`/`HTTPS_PROXY`, +and `all_proxy`/`ALL_PROXY`, and consults `no_proxy`/`NO_PROXY` — including `*` +to disable proxying entirely. The uppercase `HTTP_PROXY` is never read (an +httpoxy defense), empty values are treated as unset, and on Windows proxy +environment variables are resolved only under the CLI SAPI. Guzzle 7's stream +handler never consulted the environment; it honored only the explicit `proxy` +option. + +Because the stream handler cannot tunnel or speak TLS to a proxy, an +`https_proxy` or `all_proxy` set to an `https://` or SOCKS URL now throws +`InvalidArgumentException`, exactly as the same value passed through the `proxy` +option already does, instead of connecting directly. An environment `http://` +proxy used for an "https" request still fails at connect time, because the +handler cannot open a CONNECT tunnel. + +To ignore the proxy environment variables for a request or client, set the +`proxy` option to `''`: an explicit option decision is final, so this forces a +direct connection with no environment fallback. To send only selected hosts +directly, add them to the `proxy` option's `no` list, or list them in +`no_proxy`/`NO_PROXY` (`*` bypasses every host). These work identically on both +built-in handlers. + +#### Handler-Specific Option Overrides + +Handler-specific overrides remain available for finer transport control when +they do not conflict with Guzzle-managed behavior. The built-in cURL handlers +now reject raw cURL options that override request method, URI, body, headers, +timeouts, redirects, proxy URLs and types, TLS verification or client +credentials, progress/debug callbacks, sink handling, cookies, protocols, +connection coalescing, or cURL share handles. Use first-class Guzzle request +options for those settings. Allowed raw cURL header-list options, such as +`CURLOPT_PROXYHEADER`, now accept only strings or stringable objects as entries. + +The cURL handlers also reject stream-only `stream_context` options, but accept +`read_timeout` without effect. The stream handler rejects cURL-only options it +cannot honor, but accepts `connect_timeout` without effect. These timeout options +are intentionally best-effort so shared request configuration can be reused +across transports. + +#### Expect: 100-Continue Injection + +Automatic `Expect: 100-Continue` injection now applies only to HTTP/1.1 requests. +HTTP/1.0, HTTP/2, and HTTP/3 requests do not receive the header from Guzzle's +body-preparation middleware. + +The stream handler rejects an explicit `expect` option when it results in an +`Expect` header, because PHP streams do not support the `100-Continue` workflow. +Set `expect => false` for stream-handler requests that must avoid this rejection. + +#### Native Type Declarations + +Guzzle 8 adds native parameter and return types where PHP 7.4 allows. Code +overriding affected methods must update method signatures accordingly. + +`SetCookie::__toString()` now returns `string`. + +`HandlerStack::remove()` now throws `TypeError` when passed a value that is +neither a callable nor a middleware name string. + +`Pool::__construct()` and `Pool::batch()` now require iterable request collections. + +`SetCookie::setSecure()`, `SetCookie::setDiscard()`, and +`SetCookie::setHttpOnly()` now require boolean parameters. Calls from files that +declare strict types will throw `TypeError` for non-boolean values. + +`SetCookie::getExpires()` now returns `int|null`. Invalid textual expiration +dates are treated as `null`. + +#### IDN Conversion Option Types + +The `idn_conversion` request option must be `true`, `false`, `null`, or an +integer `IDNA_*` bitmask. Numeric strings and floats that previously worked +through PHP scalar coercion are no longer accepted. + +Integer `0` remains a valid option bitmask. Use `false` or `null` to disable IDN +conversion. + +#### Generic Promise and Structured PHPDoc Types + +Guzzle's async client APIs, handlers, and middleware callable annotations now use +generic `PromiseInterface` PHPDoc types. This is a +static-analysis-only change at runtime, but projects with stricter static +analysis may see new or different diagnostics. + +Code using unparameterized promise types continues to work. If your project +implements Guzzle client interfaces, provides custom handlers or middleware, or +uses stricter static analysis, you may need to update your PHPDoc annotations to +include promise fulfillment and rejection types. + +Public client config, request option, pool option, handler, middleware, mock +handler, and history middleware PHPDoc now uses structured array and callable +shapes. This does not change runtime behavior, but stricter static analysis may +now report invalid option keys, invalid option value types, or lower-arity +callback annotations that were previously hidden behind loose `array` or +`callable` PHPDoc. + +If your project implements `ClientInterface`, extends client behavior through +traits, builds custom handlers or middleware, or documents reusable request +option arrays, update those PHPDoc annotations to match the supported request +option and callback shapes. + +#### Multipart Request Serialization + +Guzzle 8 uses Guzzle PSR-7 3.x for multipart request bodies. Multipart parts +created through the `multipart` request option no longer include generated +per-part `Content-Length` headers by default. If your tests compare raw +multipart payloads, remove those generated part headers from expected strings. + +Generated multipart `Content-Disposition` header `name` and `filename` +parameters now escape double quotes, carriage returns, and line feeds as `%22`, +`%0D`, and `%0A`. Literal backslashes and other characters are serialized +unchanged, matching browser multipart form submission behavior. Custom multipart +part header names and values, and explicit PSR-7 multipart boundaries, are also +validated by PSR-7. + +Custom multipart part header values also preserve trailing spaces and tabs in the +serialized request body, so raw body snapshots or signatures may need updated +expectations. + +Guzzle now quotes the `boundary` parameter in generated +`Content-Type: multipart/form-data` headers when an explicit PSR-7 +`MultipartStream` boundary contains characters that require quoting. +Automatically generated boundaries are unchanged. + +You can still pass an explicit `Content-Length` header in a multipart element's +`headers` array if a non-standard peer requires it. + +#### Cross-Origin Redirect Referer Header + +With the optional `referer` redirect setting enabled (off by default), Guzzle +now sends only the request origin (scheme, host, and port) in the `Referer` +header on a cross-origin redirect. It previously sent the referring URI, +including the path, query string, and fragment, which could leak secrets such +as reset tokens or signed query parameters to the new origin. + +Same-origin redirects still send the path and query, with any user information +and fragment removed. The `Referer` header is omitted entirely when the scheme +changes, including an `https` to `http` downgrade. This matches the +`strict-origin-when-cross-origin` policy that modern browsers use by default. + +If you relied on the full URL crossing origins, collect it with the +`on_redirect` setting, or disable automatic redirects and follow them manually. + +#### Automatic Redirects + +Guzzle now follows only the redirect status codes 301, 302, 303, 307, and 308 +when `allow_redirects` is enabled. Other 3xx responses, including 300, 304, 305, +and 306, are returned to the caller unchanged even when they carry a Location +header, in line with RFC 9110 section 15.4. Code that relied on Guzzle following +one of those responses should handle it directly or inspect it with an +on_redirect callback. + +#### Secure Cookie Integrity + +Guzzle 8 ignores `Secure` cookies received over non-HTTPS requests. It also +ignores an insecure cookie received over a non-HTTPS request when its name and +domain overlap an existing `Secure` cookie and its path falls within the +existing cookie's protected path. This includes deletions sent with +`Max-Age=0`. + +Guzzle 7 accepted these cookies. Applications using plain HTTP development +servers that send `Secure` cookies must use HTTPS or remove the attribute. +Cookies inserted directly through `CookieJar::setCookie()` or restored from +persistence are not rejected because they have no response origin. Existing +`Secure` records still protect against later cookies received over HTTP. + +#### Cookie Name Prefixes + +`CookieJar::extractCookies()` now recognizes the `__Secure-` and `__Host-` +prefixes case-insensitively. `__Secure-` response cookies must be `Secure`. +`__Host-` response cookies must also be host-only, include a `Path` attribute, +and use the root path. A bare `Path` without `=` remains ignored. Invalid +prefixed response cookies are ignored. + +Cookie names remain case-sensitive, so differently cased names remain distinct. +Correct the attributes or rename a legacy response cookie that used a reserved +prefix without satisfying its requirements. Cookies inserted directly through +`CookieJar::setCookie()` and restored persisted records are unchanged. + +#### Host-Only Cookies + +Cookies extracted from responses without a `Domain` attribute are now stored as +host-only cookies. They are sent only to the exact host that set them. + +Previously, Guzzle stored these cookies with the request host as a normal domain +cookie, so they could also be sent to subdomains. Applications relying on that +behavior should use an explicit `Domain` attribute. + +`SetCookie::toArray()` may include `HostOnly => true` for host-only cookies. + +#### Cookie Domain Normalization + +Cookie domains with multiple leading dots, such as `Domain=..example.com`, are +no longer normalized twice during matching. Such malformed domains are rejected +instead of matching `example.com` or its subdomains. + +#### Cookie Max-Age Expiration + +Cookies with `Max-Age=0` or a negative `Max-Age` are now treated as immediately +expired. When such a cookie is added to a `CookieJar`, it removes a matching +stored cookie instead of being retained as a normal cookie. + +#### SetCookie Constructor Field Validation + +`SetCookie` constructor arrays no longer coerce invalid field values. Cookie +names, values, domains, paths, max-age values, expiry values, and boolean flags +must use the documented types. Invalid constructor values now throw +`InvalidArgumentException`. + +```php +// Valid: +new SetCookie([ + 'Name' => 'foo', + 'Value' => 'bar', + 'Domain' => 'example.com', + 'Secure' => true, +]); + +// Invalid in 8.0: +new SetCookie([ + 'Name' => false, + 'Value' => 'bar', +]); +``` + +Cookies parsed from normal `Set-Cookie` headers continue to be normalized by +`SetCookie::fromString()`. Attributes that require a value (`Domain`, `Path`, +`Expires`, `Max-Age`) are ignored when they appear without one. + +#### SetCookie Max-Age Precedence + +`SetCookie::fromString()` now follows RFC cookie precedence when a `Set-Cookie` +header carries both `Max-Age` and `Expires`. A valid `Max-Age` value controls +the effective expiration time, including `Max-Age=0` expiring the cookie +immediately, even when `Expires` is a future date. Cookies built from an array +keep a supplied `Expires`, as in Guzzle 7, so persisted cookies do not restart +their lifetime when a jar is loaded. + +#### Cookie Max-Age Parsing + +`SetCookie::fromString()` now ignores float-like or exponent `Max-Age` values +such as `0.5`, `1.5`, or `1e3`. Guzzle 7 truncated these numeric forms toward +zero. Use integer-second `Max-Age` values. + +#### Set-Cookie Parsing Whitespace + +`SetCookie::fromString()` now trims cookie names, cookie values, and attribute +segments with the RFC 6265 whitespace characters, space and horizontal tab. +Guzzle 7 also trimmed line feeds, carriage returns, null bytes, and vertical +tabs. Header values produced by Guzzle PSR-7 cannot contain those bytes, so +this only affects strings passed to `SetCookie::fromString()` directly. + +#### CookieJar::clear Null Semantics + +`CookieJar::clear()` now treats only `null` as an omitted path or name. +Previously, falsy path or name values such as `'0'` or `''` could be interpreted +as omitted and clear a broader set of cookies than intended. + +If you call `clear()` to clear all cookies, continue passing no arguments: + +```php +$jar->clear(); +``` + +If you pass a path or name, that value is now treated as provided. + +#### Cookie Name Lookup + +`CookieJar::getCookieByName()` now matches cookie names case-sensitively. If a +jar contains distinct cookies such as `SID` and `sid`, retrieve each one with the +exact stored name. + +#### Cookie Jar Persistence + +`FileCookieJar` and `SessionCookieJar` can no longer be restored with +`unserialize()`; attempting to unserialize either jar now throws a +`LogicException`. Rebuild persisted jars instead: `new FileCookieJar($path)` +reloads the persisted cookie file when it exists, and +`new SessionCookieJar($key)` reloads the cookie data stored in the session. + +`FileCookieJar` now writes its cookie file with owner-only permissions (`0600`), +so persisted cookies are not world-readable under the default umask; if another +user or process must read the file, adjust its permissions after saving. Saved +cookie files also JSON-escape tag characters without changing cookie values. + +Persisted cookie data must now be a JSON list. Each list entry must decode to an +array, and recognized `SetCookie` fields must use their documented constructor +types. Malformed JSON, an invalid stored shape, or a recognized field with the +wrong type causes a `RuntimeException`. Cookie records are constructed before +any are passed to `setCookie()`, so such failures leave the jar unchanged. +Numeric or string-keyed JSON objects must be converted to lists. + +Every cookie record must include an explicit boolean `HostOnly` marker. The +built-in jars write this marker automatically. Delete or rotate older nonempty +data without it, or annotate each record only when its original `Domain` +semantics are known. + +In Guzzle 7, malformed JSON in a cookie file and `FileCookieJar` encoding +failures threw `GuzzleHttp\Exception\InvalidArgumentException`. Now they throw +`RuntimeException`, consistently with other persistent cookie failures. Both +jars expose the native `JsonException` through `getPrevious()` when JSON +encoding or decoding fails. + +An empty cookie file remains a no-op. A missing or `null` session value still +means no stored cookie data. Any other session value must be a string containing +a JSON list; malformed JSON and an empty string are rejected. `SessionCookieJar` +does not replace the stored value when construction fails. + +#### Logging Middleware Formatter Types + +`GuzzleHttp\MessageFormatter` is now final. Applications that extended +`MessageFormatter` should implement `GuzzleHttp\MessageFormatterInterface` +instead and pass the custom formatter to `GuzzleHttp\Middleware::log()`. + +`Middleware::log()` now requires its formatter argument to implement +`MessageFormatterInterface`. Passing `new MessageFormatter()` still works +because `MessageFormatter` implements `MessageFormatterInterface`. Passing any +other value now fails with PHP's native `TypeError` instead of Guzzle's previous +`LogicException`. + +```php +use GuzzleHttp\MessageFormatterInterface; +use GuzzleHttp\Middleware; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + +final class RedactingFormatter implements MessageFormatterInterface +{ + public function format( + RequestInterface $request, + ?ResponseInterface $response = null, + ?\Throwable $error = null + ): string { + return $request->getMethod().' '.$request->getUri()->getPath(); + } +} + +$stack->push(Middleware::log($logger, new RedactingFormatter())); +``` + +#### Built-in Handler Inheritance + +`GuzzleHttp\Handler\CurlFactory`, `GuzzleHttp\Handler\CurlHandler`, +`GuzzleHttp\Handler\CurlMultiHandler`, `GuzzleHttp\Handler\MockHandler`, and +`GuzzleHttp\Handler\StreamHandler` are now final. + +Applications that extended `CurlFactory` should implement +`GuzzleHttp\Handler\CurlFactoryInterface` instead. Applications that extended +`CurlHandler`, `CurlMultiHandler`, `MockHandler`, or `StreamHandler` should use +composition instead: wrap a handler instance in a custom callable or provide a +custom handler rather than subclassing the built-in handler. + +#### Custom cURL Handle Factories + +Custom `GuzzleHttp\Handler\CurlFactoryInterface` implementations that create or +mutate `GuzzleHttp\Handler\EasyHandle` instances must assign values compatible +with EasyHandle's documented public property types. Several EasyHandle +bookkeeping properties now use native property types, so assigning incompatible +values to those properties raises `TypeError`. + +Custom factories must assign the request and sink state before returning an +EasyHandle to Guzzle because those properties are required typed invariants. +Reading them before assignment raises PHP's uninitialized typed-property `Error`. + +The native cURL handle properties intentionally remain untyped because PHP 7.4 +represents cURL handles as resources while PHP 8 represents them as cURL handle +objects. Custom factories must still unset `$easy->handle` when releasing an +easy handle, as required by `CurlFactoryInterface::release()`. + +#### Built-In Handler Constructor Options + +`CurlHandler`, `CurlMultiHandler`, and `StreamHandler` now reject unknown +constructor option keys with `GuzzleHttp\Exception\InvalidArgumentException`. +Remove misspelled or application-specific keys before constructing built-in +handlers. + +`CurlMultiHandler` now rejects cURL multi options that cannot be applied by the +installed runtime libcurl. Values passed through the constructor `options` key +must be an array keyed by integer `CURLMOPT_*` constants. Guzzle 7 already +fails closed when a named connection cap cannot be applied; Guzzle 8 extends +this rejection to every cURL multi option, including raw `CURLMOPT_*` entries +that Guzzle 7 only warns about. + +`CurlMultiHandler` now rejects `CURLMOPT_PIPELINING` in the constructor +`options` array, deprecated since Guzzle 7.15. Pass `Multiplexing::NONE` as the +`multiplex` client option or, when constructing the handler yourself, as the +`multiplex` constructor option to disallow multiplexing on the handler +(replacing `CURLPIPE_NOTHING` and `0`), or remove the option entirely for +multiplex-capable behavior (replacing masks containing `CURLPIPE_MULTIPLEX`); +multiplexing is on by default from libcurl 7.62, except on 7.65.0 and 7.65.1 +where a regression dropped the default, and Guzzle 8's HTTP/2 floor of libcurl +7.65.2 is the version that restored it, so removing the option preserves +multiplex-capable behavior on every supported HTTP/2 runtime. `CURLPIPE_HTTP1` +and `1` also map to `Multiplexing::NONE` on libcurl 7.62 and newer, where +HTTP/1.1 pipelining is a no-op; on older libcurl they enabled HTTP/1.1 +pipelining, which has no replacement. A handler configured with +`Multiplexing::NONE` wins over the default `WAIT` request mode: default requests +run without waiting, explicitly requested wait modes are rejected as a +configuration conflict when the transfer would actually wait, and the required +modes are always rejected. `Multiplexing::NONE` is also accepted as a request +option value exactly where its guarantee - the transfer does not share its +connection with any concurrent transfer - holds and can be verified; see the +`multiplex` request option documentation for the acceptance rules. + +`CurlMultiHandler` now rejects `CURLMOPT_MAX_HOST_CONNECTIONS` and +`CURLMOPT_MAX_TOTAL_CONNECTIONS` entries in the constructor `options` array. Use +the `max_host_connections` and `max_total_connections` client options when +Guzzle creates the default handler, or the same named `CurlMultiHandler` +constructor options when constructing the handler directly. + +Direct magic access to `CurlMultiHandler::$_mh` has been removed. This was an +undocumented internal lazy cURL multi handle. Applications that used it to set +`CURLMOPT_*` options should pass those values through the `options` key of the +`CurlMultiHandler` constructor. + +#### Progress Callback Parameter Types + +The built-in handlers now pass integer byte counts to `progress` callbacks. +Callbacks with `int` parameter types continue to work, and callbacks with +`float` parameter types can still receive integer byte counts in PHP. If a +callback used other scalar parameter types, update it to accept integers or +remove the scalar parameter declarations. + +#### CurlMultiHandler Select Timeout + +The `GUZZLE_CURL_SELECT_TIMEOUT` environment variable is no longer read. Pass +the `select_timeout` option to `CurlMultiHandler` instead. The +`select_timeout` option must be numeric, finite, and non-negative. It must be +`0` or greater than or equal to `0.001` seconds. + +#### Removed Client::__call and ClientInterface::getConfig + +`Client::__call()` has been removed. The typed HTTP verb methods (`get()`, +`head()`, `put()`, `post()`, `patch()`, `delete()`, and their `*Async()` +variants) have been real methods since Guzzle 7.0 and are unaffected. Only +verbs without a typed method lose their magic form: calls such as +`$client->options($uri)`, `$client->trace($uri)`, +`$client->optionsAsync($uri)`, or any custom verb such as +`$client->purge($uri)` now fail with a PHP undefined method error. Use +`request()` or `requestAsync()` with an explicit method instead: + +```php +// 7.x +$response = $client->options('http://example.com'); + +// 8.0 +$response = $client->request('OPTIONS', 'http://example.com'); +``` + +`ClientInterface::getConfig()` has been removed from the interface. The +concrete `Client::getConfig()` method remains available and is no longer +deprecated. Code reading configuration through a `ClientInterface`-typed +value must type against `Client` instead, and custom `ClientInterface` +implementations no longer need to provide `getConfig()`, although keeping the +method still satisfies the interface. + +#### Removed Function and JSON Helper APIs + +The deprecated `GuzzleHttp` namespace functions were removed, along with the +`functions.php` and `functions_include.php` files and the Composer `files` +autoload entry that loaded them on every request. + +Replace namespaced function calls with their native or class equivalents: + +```php +// Before: +use function GuzzleHttp\json_decode; + +$data = json_decode($json); + +// After: +$data = \json_decode($json, false, 512, \JSON_THROW_ON_ERROR); +``` + +| Original Function | Replacement | +|-------------------|-------------| +| `describe_type` | PHP's `get_debug_type` | +| `headers_from_lines` | `Utils::headersFromLines` | +| `debug_resource` | `Utils::debugResource` | +| `choose_handler` | `Utils::chooseHandler` | +| `default_user_agent` | `Utils::defaultUserAgent` | +| `default_ca_bundle` | none; use the system trust store or `verify` | +| `normalize_header_keys` | `Utils::normalizeHeaderKeys` | +| `is_host_in_noproxy` | `ProxyOptions::isHostInNoProxy` | +| `json_decode` | PHP's `json_decode` with `JSON_THROW_ON_ERROR` | +| `json_encode` | PHP's `json_encode` with `JSON_THROW_ON_ERROR` | + +The deprecated `Utils::jsonDecode()` and `Utils::jsonEncode()` methods have +also been removed. Use PHP's native JSON functions with +`JSON_THROW_ON_ERROR`. Failures throw `JsonException` directly. + +See the "Removed Proxy Helper API" section below for `is_host_in_noproxy()` +behavior differences. The deprecated `Utils::defaultCaBundle()` and the +internal `Utils::isUriInNoProxy()` helpers have also been removed; use the +`verify` option and `ProxyOptions::isUriInNoProxy()` respectively. + +#### Removed Middleware Helper APIs + +`RetryMiddleware::exponentialDelay()` has been removed. The retry middleware +continues to use the same exponential backoff calculation by default. This only +affects code that called the static helper directly; inline that calculation or +pass a custom delay callable to `Middleware::retry()`. + +`RedirectMiddleware::$defaultSettings` has been removed. Use +`RedirectMiddleware::DEFAULT_SETTINGS` instead. + +#### Removed Proxy Helper API + +`Utils::isHostInNoProxy()` has been removed. + +Use `ProxyOptions::resolve()` when implementing Guzzle-compatible proxy handling +in a custom handler. Use `ProxyOptions::isUriInNoProxy()` when checking whether +a request URI matches a no-proxy list. Use `ProxyOptions::isHostInNoProxy()` +only when checking a host string directly. The environment-variable fallback +performed by the built-in handlers is not part of `ProxyOptions::resolve()`; +custom handlers that want it must implement their own environment lookup. + +These helpers share the normalized no-proxy matching of the Guzzle 7 `Utils` +helpers: domain matching is case-insensitive and ignores a single trailing DNS +root dot, IP literals are normalized before comparison, and CIDR entries match +IP literal hosts. They differ from the Guzzle 7 helpers in three ways — they +throw `InvalidArgumentException` for non-string list entries where Guzzle 7 +skips them, a leading-dot entry such as `.example.com` also matches the bare +domain, and string no-proxy lists are split on whitespace as well as commas. + +#### Removed Type Description Helper API + +`Utils::describeType()` has been removed. Use PHP's `get_debug_type()` instead. + +#### Non-instantiable Utility Classes + +Static utility and constant classes such as `GuzzleHttp\Middleware`, +`GuzzleHttp\Utils`, `GuzzleHttp\RequestOptions`, +`GuzzleHttp\Handler\HeaderProcessor`, and `GuzzleHttp\Handler\Proxy` now have +private constructors. `GuzzleHttp\Handler\Proxy` is also declared `final`. + +These classes only expose static members. Replace any accidental instantiation +with static method calls or constant access. + +#### Removed HandlerStack String Dump + +`HandlerStack::__toString()` has been removed. + +#### Native PHP Serialization of Runtime Objects + +Runtime objects such as clients, handler stacks, middleware, handlers, pools, +mock handlers, cURL transport objects, and persistent cookie jars no longer +support native PHP `serialize()` or `unserialize()`. Persist configuration or +cookie data explicitly and rebuild runtime objects during bootstrap. + +#### Sensitive Stack Trace Arguments + +Guzzle 8 marks credential-bearing parameters with `SensitiveParameter`. On PHP +8.2 and later, selected exception-trace arguments are represented by +`SensitiveParameterValue` instead of exposing the original argument. PHP 7.4 +through 8.1 do not redact trace arguments. The attribute does not redact logs, +exception messages, HTTP traffic, properties, captured variables, return +values, custom callback frames, or the separate `$this`/`object` entry in +explicit backtraces. PHP 8.2 also does not reliably redact named values +collected by an attributed variadic; PHP 8.3+ does. + +6.0 to 7.0 +---------- + +In order to take advantage of the new features of PHP, Guzzle dropped the support +of PHP 5. The minimum supported PHP version is now PHP 7.2. Type hints and return +types for functions and methods have been added wherever possible. + +Please make sure: +- You are calling a function or a method with the correct type. +- If you extend a class of Guzzle; update all signatures on methods you override. + +#### Other Backwards Compatibility Breaking Changes + +- Class `GuzzleHttp\UriTemplate` is removed. +- Class `GuzzleHttp\Exception\SeekException` is removed. +- Classes `GuzzleHttp\Exception\BadResponseException`, `GuzzleHttp\Exception\ClientException`, + `GuzzleHttp\Exception\ServerException` can no longer be initialized with an empty + Response as argument. +- Class `GuzzleHttp\Exception\ConnectException` now extends `GuzzleHttp\Exception\TransferException` + instead of `GuzzleHttp\Exception\RequestException`. +- Function `GuzzleHttp\Exception\ConnectException::getResponse()` is removed. +- Function `GuzzleHttp\Exception\ConnectException::hasResponse()` is removed. +- Constant `GuzzleHttp\ClientInterface::VERSION` is removed. Added `GuzzleHttp\ClientInterface::MAJOR_VERSION` instead. +- Function `GuzzleHttp\Exception\RequestException::getResponseBodySummary` is removed. + Use `\GuzzleHttp\Psr7\get_message_body_summary` as an alternative. +- Function `GuzzleHttp\Cookie\CookieJar::getCookieValue` is removed. +- Request option `exceptions` is removed. Please use `http_errors`. +- Request option `save_to` is removed. Please use `sink`. +- Pool option `pool_size` is removed. Please use `concurrency`. +- We now look for environment variables in the `$_SERVER` super global, due to thread safety issues with `getenv`. We continue to fallback to `getenv` in CLI environments, for maximum compatibility. +- The `get`, `head`, `put`, `post`, `patch`, `delete`, `getAsync`, `headAsync`, `putAsync`, `postAsync`, `patchAsync`, and `deleteAsync` methods are now implemented as genuine methods on `GuzzleHttp\Client`, with strong typing. The original `__call` implementation remains unchanged for now, for maximum backwards compatibility, but won't be invoked under normal operation. +- The `log` middleware will log the errors with level `error` instead of `notice` +- Support for international domain names (IDN) is now disabled by default, and enabling it requires installing ext-intl, linked against a modern version of the C library (ICU 4.6 or higher). + +#### Native Functions Calls + +All internal native functions calls of Guzzle are now prefixed with a slash. This +change makes it impossible for method overloading by other libraries or applications. +Example: + +```php +// Before: +curl_version(); + +// After: +\curl_version(); +``` + +For the full diff you can check [here](https://github.com/guzzle/guzzle/compare/6.5.4..7.0.0). + +5.0 to 6.0 +---------- + +Guzzle now uses [PSR-7](https://www.php-fig.org/psr/psr-7/) for HTTP messages. +Due to the fact that these messages are immutable, this prompted a refactoring +of Guzzle to use a middleware based system rather than an event system. Any +HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be +updated to work with the new immutable PSR-7 request and response objects. Any +event listeners or subscribers need to be updated to become middleware +functions that wrap handlers (or are injected into a +`GuzzleHttp\HandlerStack`). + +- Removed `GuzzleHttp\BatchResults` +- Removed `GuzzleHttp\Collection` +- Removed `GuzzleHttp\HasDataTrait` +- Removed `GuzzleHttp\ToArrayInterface` +- The `guzzlehttp/streams` dependency has been removed. Stream functionality + is now present in the `GuzzleHttp\Psr7` namespace provided by the + `guzzlehttp/psr7` package. +- Guzzle no longer uses ReactPHP promises and now uses the + `guzzlehttp/promises` library. We use a custom promise library for three + significant reasons: + 1. React promises (at the time of writing this) are recursive. Promise + chaining and promise resolution will eventually blow the stack. Guzzle + promises are not recursive as they use a sort of trampolining technique. + Note: there has been movement in the React project to modify promises to + no longer utilize recursion. + 2. Guzzle needs to have the ability to synchronously block on a promise to + wait for a result. Guzzle promises allows this functionality (and does + not require the use of recursion). + 3. Because we need to be able to wait on a result, doing so using React + promises requires wrapping react promises with RingPHP futures. This + overhead is no longer needed, reducing stack sizes, reducing complexity, + and improving performance. +- `GuzzleHttp\Mimetypes` has been moved to a function in + `GuzzleHttp\Psr7\mimetype_from_extension` and + `GuzzleHttp\Psr7\mimetype_from_filename`. +- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query + strings must now be passed into request objects as strings, or provided to + the `query` request option when creating requests with clients. The `query` + option uses PHP's `http_build_query` to convert an array to a string. If you + need a different serialization technique, you will need to pass the query + string in as a string. There are a couple helper functions that will make + working with query strings easier: `GuzzleHttp\Psr7\parse_query` and + `GuzzleHttp\Psr7\build_query`. +- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware + system based on PSR-7, using RingPHP and it's middleware system as well adds + more complexity than the benefits it provides. All HTTP handlers that were + present in RingPHP have been modified to work directly with PSR-7 messages + and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces + complexity in Guzzle, removes a dependency, and improves performance. RingPHP + will be maintained for Guzzle 5 support, but will no longer be a part of + Guzzle 6. +- As Guzzle now uses a middleware based systems the event system and RingPHP + integration has been removed. Note: while the event system has been removed, + it is possible to add your own type of event system that is powered by the + middleware system. + - Removed the `Event` namespace. + - Removed the `Subscriber` namespace. + - Removed `Transaction` class + - Removed `RequestFsm` + - Removed `RingBridge` + - `GuzzleHttp\Subscriber\Cookie` is now provided by + `GuzzleHttp\Middleware::cookies` + - `GuzzleHttp\Subscriber\HttpError` is now provided by + `GuzzleHttp\Middleware::httpError` + - `GuzzleHttp\Subscriber\History` is now provided by + `GuzzleHttp\Middleware::history` + - `GuzzleHttp\Subscriber\Mock` is now provided by + `GuzzleHttp\Handler\MockHandler` + - `GuzzleHttp\Subscriber\Prepare` is now provided by + `GuzzleHttp\PrepareBodyMiddleware` + - `GuzzleHttp\Subscriber\Redirect` is now provided by + `GuzzleHttp\RedirectMiddleware` +- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in + `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone. +- Static functions in `GuzzleHttp\Utils` have been moved to namespaced + functions under the `GuzzleHttp` namespace. This requires either a Composer + based autoloader or you to include functions.php. +- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to + `GuzzleHttp\ClientInterface::getConfig`. +- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed. +- The `json` and `xml` methods of response objects has been removed. With the + migration to strictly adhering to PSR-7 as the interface for Guzzle messages, + adding methods to message interfaces would actually require Guzzle messages + to extend from PSR-7 messages rather then work with them directly. + +## Migrating to middleware + +The change to PSR-7 unfortunately required significant refactoring to Guzzle +due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event +system from plugins. The event system relied on mutability of HTTP messages and +side effects in order to work. With immutable messages, you have to change your +workflow to become more about either returning a value (e.g., functional +middlewares) or setting a value on an object. Guzzle v6 has chosen the +functional middleware approach. + +Instead of using the event system to listen for things like the `before` event, +you now create a stack based middleware function that intercepts a request on +the way in and the promise of the response on the way out. This is a much +simpler and more predictable approach than the event system and works nicely +with PSR-7 middleware. Due to the use of promises, the middleware system is +also asynchronous. + +v5: + +```php +use GuzzleHttp\Event\BeforeEvent; +$client = new GuzzleHttp\Client(); +// Get the emitter and listen to the before event. +$client->getEmitter()->on('before', function (BeforeEvent $e) { + // Guzzle v5 events relied on mutation + $e->getRequest()->setHeader('X-Foo', 'Bar'); +}); +``` + +v6: + +In v6, you can modify the request before it is sent using the `mapRequest` +middleware. The idiomatic way in v6 to modify the request/response lifecycle is +to setup a handler middleware stack up front and inject the handler into a +client. + +```php +use GuzzleHttp\Middleware; +// Create a handler stack that has all of the default middlewares attached +$handler = GuzzleHttp\HandlerStack::create(); +// Push the handler onto the handler stack +$handler->push(Middleware::mapRequest(function (RequestInterface $request) { + // Notice that we have to return a request object + return $request->withHeader('X-Foo', 'Bar'); +})); +// Inject the handler into the client +$client = new GuzzleHttp\Client(['handler' => $handler]); +``` + +## POST Requests + +This version added the [`form_params`](https://github.com/guzzle/guzzle/blob/6.5/docs/request-options.rst#form_params) +and `multipart` request options. `form_params` is an associative array of +strings or array of strings and is used to serialize an +`application/x-www-form-urlencoded` POST request. The +[`multipart`](https://github.com/guzzle/guzzle/blob/6.5/docs/request-options.rst#multipart) +option is now used to send a multipart/form-data POST request. + +`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add +POST files to a multipart/form-data request. + +The `body` option no longer accepts an array to send POST requests. Please use +`multipart` or `form_params` instead. + +The `base_url` option has been renamed to `base_uri`. + +4.x to 5.0 +---------- + +## Rewritten Adapter Layer + +Guzzle now uses [RingPHP](https://github.com/guzzle/RingPHP) to send +HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor +is still supported, but it has now been renamed to `handler`. Instead of +passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP +`callable` that follows the RingPHP specification. + +## Removed Fluent Interfaces + +[Fluent interfaces were removed](https://ocramius.github.io/blog/fluent-interfaces-are-evil/) +from the following classes: + +- `GuzzleHttp\Collection` +- `GuzzleHttp\Url` +- `GuzzleHttp\Query` +- `GuzzleHttp\Post\PostBody` +- `GuzzleHttp\Cookie\SetCookie` + +## Removed functions.php + +Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following +functions can be used as replacements. + +- `GuzzleHttp\json_decode` -> PHP's `json_decode` +- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath` +- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path` +- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however, + deprecated in favor of using `GuzzleHttp\Pool::batch()`. + +The "procedural" global client has been removed with no replacement (e.g., +`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client` +object as a replacement. + +## `throwImmediately` has been removed + +The concept of "throwImmediately" has been removed from exceptions and error +events. This control mechanism was used to stop a transfer of concurrent +requests from completing. This can now be handled by throwing the exception or +by cancelling a pool of requests or each outstanding future request +individually. + +## headers event has been removed + +Removed the "headers" event. This event was only useful for changing the +body a response once the headers of the response were known. You can implement +a similar behavior in a number of ways. One example might be to use a +FnStream that has access to the transaction being sent. For example, when the +first byte is written, you could check if the response headers match your +expectations, and if so, change the actual stream body that is being +written to. + +## Updates to HTTP Messages + +Removed the `asArray` parameter from +`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header +value as an array, then use the newly added `getHeaderAsArray()` method of +`MessageInterface`. This change makes the Guzzle interfaces compatible with +the PSR-7 interfaces. + +3.x to 4.0 +---------- + +## Overarching changes: + +- Now requires PHP 5.4 or greater. +- No longer requires cURL to send requests. +- Guzzle no longer wraps every exception it throws. Only exceptions that are + recoverable are now wrapped by Guzzle. +- Various namespaces have been removed or renamed. +- No longer requiring the Symfony EventDispatcher. A custom event dispatcher + based on the Symfony EventDispatcher is + now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant + speed and functionality improvements). + +Changes per Guzzle 3.x namespace are described below. + +## Batch + +The `Guzzle\Batch` namespace has been removed. This is best left to +third-parties to implement on top of Guzzle's core HTTP library. + +## Cache + +The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement +has been implemented yet, but hoping to utilize a PSR cache interface). + +## Common + +- Removed all of the wrapped exceptions. It's better to use the standard PHP + library for unrecoverable exceptions. +- `FromConfigInterface` has been removed. +- `Guzzle\Common\Version` has been removed. The VERSION constant can be found + at `GuzzleHttp\ClientInterface::VERSION`. + +### Collection + +- `getAll` has been removed. Use `toArray` to convert a collection to an array. +- `inject` has been removed. +- `keySearch` has been removed. +- `getPath` no longer supports wildcard expressions. Use something better like + JMESPath for this. +- `setPath` now supports appending to an existing array via the `[]` notation. + +### Events + +Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses +`GuzzleHttp\Event\Emitter`. + +- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by + `GuzzleHttp\Event\EmitterInterface`. +- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by + `GuzzleHttp\Event\Emitter`. +- `Symfony\Component\EventDispatcher\Event` is replaced by + `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in + `GuzzleHttp\Event\EventInterface`. +- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and + `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the + event emitter of a request, client, etc. now uses the `getEmitter` method + rather than the `getDispatcher` method. + +#### Emitter + +- Use the `once()` method to add a listener that automatically removes itself + the first time it is invoked. +- Use the `listeners()` method to retrieve a list of event listeners rather than + the `getListeners()` method. +- Use `emit()` instead of `dispatch()` to emit an event from an emitter. +- Use `attach()` instead of `addSubscriber()` and `detach()` instead of + `removeSubscriber()`. + +```php +$mock = new Mock(); +// 3.x +$request->getEventDispatcher()->addSubscriber($mock); +$request->getEventDispatcher()->removeSubscriber($mock); +// 4.x +$request->getEmitter()->attach($mock); +$request->getEmitter()->detach($mock); +``` + +Use the `on()` method to add a listener rather than the `addListener()` method. + +```php +// 3.x +$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); +// 4.x +$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); +``` + +## Http + +### General changes + +- The cacert.pem certificate has been moved to `src/cacert.pem`. +- Added the concept of adapters that are used to transfer requests over the + wire. +- Simplified the event system. +- Sending requests in parallel is still possible, but batching is no longer a + concept of the HTTP layer. Instead, you must use the `complete` and `error` + events to asynchronously manage parallel request transfers. +- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`. +- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`. +- QueryAggregators have been rewritten so that they are simply callable + functions. +- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in + `functions.php` for an easy to use static client instance. +- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from + `GuzzleHttp\Exception\TransferException`. + +### Client + +Calling methods like `get()`, `post()`, `head()`, etc. no longer create and +return a request, but rather creates a request, sends the request, and returns +the response. + +```php +// 3.0 +$request = $client->get('/'); +$response = $request->send(); + +// 4.0 +$response = $client->get('/'); + +// or, to mirror the previous behavior +$request = $client->createRequest('GET', '/'); +$response = $client->send($request); +``` + +`GuzzleHttp\ClientInterface` has changed. + +- The `send` method no longer accepts more than one request. Use `sendAll` to + send multiple requests in parallel. +- `setUserAgent()` has been removed. Use a default request option instead. You + could, for example, do something like: + `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`. +- `setSslVerification()` has been removed. Use default request options instead, + like `$client->setConfig('defaults/verify', true)`. + +`GuzzleHttp\Client` has changed. + +- The constructor now accepts only an associative array. You can include a + `base_url` string or array to use a URI template as the base URL of a client. + You can also specify a `defaults` key that is an associative array of default + request options. You can pass an `adapter` to use a custom adapter, + `batch_adapter` to use a custom adapter for sending requests in parallel, or + a `message_factory` to change the factory used to create HTTP requests and + responses. +- The client no longer emits a `client.create_request` event. +- Creating requests with a client no longer automatically utilize a URI + template. You must pass an array into a creational method (e.g., + `createRequest`, `get`, `put`, etc.) in order to expand a URI template. + +### Messages + +Messages no longer have references to their counterparts (i.e., a request no +longer has a reference to it's response, and a response no loger has a +reference to its request). This association is now managed through a +`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to +these transaction objects using request events that are emitted over the +lifecycle of a request. + +#### Requests with a body + +- `GuzzleHttp\Message\EntityEnclosingRequest` and + `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The + separation between requests that contain a body and requests that do not + contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface` + handles both use cases. +- Any method that previously accepts a `GuzzleHttp\Response` object now accept a + `GuzzleHttp\Message\ResponseInterface`. +- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to + `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create + both requests and responses and is implemented in + `GuzzleHttp\Message\MessageFactory`. +- POST field and file methods have been removed from the request object. You + must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface` + to control the format of a POST body. Requests that are created using a + standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use + a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if + the method is POST and no body is provided. + +```php +$request = $client->createRequest('POST', '/'); +$request->getBody()->setField('foo', 'bar'); +$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); +``` + +#### Headers + +- `GuzzleHttp\Message\Header` has been removed. Header values are now simply + represented by an array of values or as a string. Header values are returned + as a string by default when retrieving a header value from a message. You can + pass an optional argument of `true` to retrieve a header value as an array + of strings instead of a single concatenated string. +- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to + `GuzzleHttp\Post`. This interface has been simplified and now allows the + addition of arbitrary headers. +- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most + of the custom headers are now handled separately in specific + subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has + been updated to properly handle headers that contain parameters (like the + `Link` header). + +#### Responses + +- `GuzzleHttp\Message\Response::getInfo()` and + `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event + system to retrieve this type of information. +- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed. +- `GuzzleHttp\Message\Response::getMessage()` has been removed. +- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific + methods have moved to the CacheSubscriber. +- Header specific helper functions like `getContentMd5()` have been removed. + Just use `getHeader('Content-MD5')` instead. +- `GuzzleHttp\Message\Response::setRequest()` and + `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event + system to work with request and response objects as a transaction. +- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the + Redirect subscriber instead. +- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have + been removed. Use `getStatusCode()` instead. + +#### Streaming responses + +Streaming requests can now be created by a client directly, returning a +`GuzzleHttp\Message\ResponseInterface` object that contains a body stream +referencing an open PHP HTTP stream. + +```php +// 3.0 +use Guzzle\Stream\PhpStreamRequestFactory; +$request = $client->get('/'); +$factory = new PhpStreamRequestFactory(); +$stream = $factory->fromRequest($request); +$data = $stream->read(1024); + +// 4.0 +$response = $client->get('/', ['stream' => true]); +// Read some data off of the stream in the response body +$data = $response->getBody()->read(1024); +``` + +#### Redirects + +The `configureRedirects()` method has been removed in favor of a +`allow_redirects` request option. + +```php +// Standard redirects with a default of a max of 5 redirects +$request = $client->createRequest('GET', '/', ['allow_redirects' => true]); + +// Strict redirects with a custom number of redirects +$request = $client->createRequest('GET', '/', [ + 'allow_redirects' => ['max' => 5, 'strict' => true] +]); +``` + +#### EntityBody + +EntityBody interfaces and classes have been removed or moved to +`GuzzleHttp\Stream`. All classes and interfaces that once required +`GuzzleHttp\EntityBodyInterface` now require +`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no +longer uses `GuzzleHttp\EntityBody::factory` but now uses +`GuzzleHttp\Stream\Stream::factory` or even better: +`GuzzleHttp\Stream\create()`. + +- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface` +- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream` +- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream` +- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream` +- `Guzzle\Http\IoEmittyinEntityBody` has been removed. + +#### Request lifecycle events + +Requests previously submitted a large number of requests. The number of events +emitted over the lifecycle of a request has been significantly reduced to make +it easier to understand how to extend the behavior of a request. All events +emitted during the lifecycle of a request now emit a custom +`GuzzleHttp\Event\EventInterface` object that contains context providing +methods and a way in which to modify the transaction at that specific point in +time (e.g., intercept the request and set a response on the transaction). + +- `request.before_send` has been renamed to `before` and now emits a + `GuzzleHttp\Event\BeforeEvent` +- `request.complete` has been renamed to `complete` and now emits a + `GuzzleHttp\Event\CompleteEvent`. +- `request.sent` has been removed. Use `complete`. +- `request.success` has been removed. Use `complete`. +- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`. +- `request.exception` has been removed. Use `error`. +- `request.receive.status_line` has been removed. +- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to + maintain a status update. +- `curl.callback.write` has been removed. Use a custom `StreamInterface` to + intercept writes. +- `curl.callback.read` has been removed. Use a custom `StreamInterface` to + intercept reads. + +`headers` is a new event that is emitted after the response headers of a +request have been received before the body of the response is downloaded. This +event emits a `GuzzleHttp\Event\HeadersEvent`. + +You can intercept a request and inject a response using the `intercept()` event +of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and +`GuzzleHttp\Event\ErrorEvent` event. + +## Inflection + +The `Guzzle\Inflection` namespace has been removed. This is not a core concern +of Guzzle. + +## Iterator + +The `Guzzle\Iterator` namespace has been removed. + +- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and + `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of + Guzzle itself. +- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent + class is shipped with PHP 5.4. +- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because + it's easier to just wrap an iterator in a generator that maps values. + +For a replacement of these iterators, see https://github.com/nikic/iter + +## Log + +The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The +`Guzzle\Log` namespace has been removed. Guzzle now relies on +`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been +moved to `GuzzleHttp\Subscriber\Log\Formatter`. + +## Parser + +The `Guzzle\Parser` namespace has been removed. This was previously used to +make it possible to plug in custom parsers for cookies, messages, URI +templates, and URLs; however, this level of complexity is not needed in Guzzle +so it has been removed. + +- Cookie: Cookie parsing logic has been moved to + `GuzzleHttp\Cookie\SetCookie::fromString`. +- Message: Message parsing logic for both requests and responses has been moved + to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only + used in debugging or deserializing messages, so it doesn't make sense for + Guzzle as a library to add this level of complexity to parsing messages. +- UriTemplate: URI template parsing has been moved to + `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL + URI template library if it is installed. +- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously + it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary, + then developers are free to subclass `GuzzleHttp\Url`. + +## Plugin + +The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`. +Several plugins are shipping with the core Guzzle library under this namespace. + +- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar + code has moved to `GuzzleHttp\Cookie`. +- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin. +- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is + received. +- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin. +- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before + sending. This subscriber is attached to all requests by default. +- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin. + +The following plugins have been removed (third-parties are free to re-implement +these if needed): + +- `GuzzleHttp\Plugin\Async` has been removed. +- `GuzzleHttp\Plugin\CurlAuth` has been removed. +- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This + functionality should instead be implemented with event listeners that occur + after normal response parsing occurs in the guzzle/command package. + +The following plugins are not part of the core Guzzle package, but are provided +in separate repositories: + +- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler + to build custom retry policies using simple functions rather than various + chained classes. See: https://github.com/guzzle/retry-subscriber +- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to + https://github.com/guzzle/cache-subscriber +- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to + https://github.com/guzzle/log-subscriber +- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to + https://github.com/guzzle/message-integrity-subscriber +- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to + `GuzzleHttp\Subscriber\MockSubscriber`. +- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to + https://github.com/guzzle/oauth-subscriber + +## Service + +The service description layer of Guzzle has moved into two separate packages: + +- https://github.com/guzzle/command Provides a high level abstraction over web + services by representing web service operations using commands. +- https://github.com/guzzle/guzzle-services Provides an implementation of + guzzle/command that provides request serialization and response parsing using + Guzzle service descriptions. + +## Stream + +Stream have moved to a separate package available at +https://github.com/guzzle/streams. + +`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take +on the responsibilities of `Guzzle\Http\EntityBody` and +`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number +of methods implemented by the `StreamInterface` has been drastically reduced to +allow developers to more easily extend and decorate stream behavior. + +## Removed methods from StreamInterface + +- `getStream` and `setStream` have been removed to better encapsulate streams. +- `getMetadata` and `setMetadata` have been removed in favor of + `GuzzleHttp\Stream\MetadataStreamInterface`. +- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been + removed. This data is accessible when + using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`. +- `rewind` has been removed. Use `seek(0)` for a similar behavior. + +## Renamed methods + +- `detachStream` has been renamed to `detach`. +- `feof` has been renamed to `eof`. +- `ftell` has been renamed to `tell`. +- `readLine` has moved from an instance method to a static class method of + `GuzzleHttp\Stream\Stream`. + +## Metadata streams + +`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams +that contain additional metadata accessible via `getMetadata()`. +`GuzzleHttp\Stream\StreamInterface::getMetadata` and +`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed. + +## StreamRequestFactory + +The entire concept of the StreamRequestFactory has been removed. The way this +was used in Guzzle 3 broke the actual interface of sending streaming requests +(instead of getting back a Response, you got a StreamInterface). Streaming +PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`. + +3.6 to 3.7 +---------- + +### Deprecations + +- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: + +```php +\Guzzle\Common\Version::$emitWarnings = true; +``` + +The following APIs and options have been marked as deprecated: + +- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +- Marked `Guzzle\Common\Collection::inject()` as deprecated. +- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use + `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or + `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` + +3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational +request methods. When paired with a client's configuration settings, these options allow you to specify default settings +for various aspects of a request. Because these options make other previous configuration options redundant, several +configuration options and methods of a client and AbstractCommand have been deprecated. + +- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. +- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. +- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` +- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 + + $command = $client->getCommand('foo', array( + 'command.headers' => array('Test' => '123'), + 'command.response_body' => '/path/to/file' + )); + + // Should be changed to: + + $command = $client->getCommand('foo', array( + 'command.request_options' => array( + 'headers' => array('Test' => '123'), + 'save_as' => '/path/to/file' + ) + )); + +### Interface changes + +Additions and changes (you will need to update any implementations or subclasses you may have created): + +- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +- Added `Guzzle\Stream\StreamInterface::isRepeatable` +- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. + +The following methods were removed from interfaces. All of these methods are still available in the concrete classes +that implement them, but you should update your code to use alternative methods: + +- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or + `$client->setDefaultOption('headers/{header_name}', 'value')`. or + `$client->setDefaultOption('headers', array('header_name' => 'value'))`. +- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. +- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. +- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. +- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. +- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. + +### Cache plugin breaking changes + +- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +- Always setting X-cache headers on cached responses +- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +- Added `CacheStorageInterface::purge($url)` +- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +3.5 to 3.6 +---------- + +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). + For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). + Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Moved getLinks() from Response to just be used on a Link header object. + +If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the +HeaderInterface (e.g. toArray(), getAll(), etc.). + +### Interface changes + +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() + +### Removed deprecated functions + +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). + +### Deprecations + +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. + +### Other changes + +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess + +3.3 to 3.4 +---------- + +Base URLs of a client now follow the rules of https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.2 when merging URLs. + +3.2 to 3.3 +---------- + +### Response::getEtag() quote stripping removed + +`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header + +### Removed `Guzzle\Http\Utils` + +The `Guzzle\Http\Utils` class was removed. This class was only used for testing. + +### Stream wrapper and type + +`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase. + +### curl.emit_io became emit_io + +Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the +'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' + +3.1 to 3.2 +---------- + +### CurlMulti is no longer reused globally + +Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added +to a single client can pollute requests dispatched from other clients. + +If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the +ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is +created. + +```php +$multi = new Guzzle\Http\Curl\CurlMulti(); +$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); +$builder->addListener('service_builder.create_client', function ($event) use ($multi) { + $event['client']->setCurlMulti($multi); +} +}); +``` + +### No default path + +URLs no longer have a default path value of '/' if no path was specified. + +Before: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com/ +``` + +After: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com +``` + +### Less verbose BadResponseException + +The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and +response information. You can, however, get access to the request and response object by calling `getRequest()` or +`getResponse()` on the exception object. + +### Query parameter aggregation + +Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a +setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is +responsible for handling the aggregation of multi-valued query string variables into a flattened hash. + +2.8 to 3.x +---------- + +### Guzzle\Service\Inspector + +Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` + +**Before** + +```php +use Guzzle\Service\Inspector; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Inspector::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +**After** + +```php +use Guzzle\Common\Collection; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Collection::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +### Convert XML Service Descriptions to JSON + +**Before** + +```xml + + + + + + Get a list of groups + + + Uses a search query to get a list of groups + + + + Create a group + + + + + Delete a group by ID + + + + + + + Update a group + + + + + + +``` + +**After** + +```json +{ + "name": "Zendesk REST API v2", + "apiVersion": "2012-12-31", + "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", + "operations": { + "list_groups": { + "httpMethod":"GET", + "uri": "groups.json", + "summary": "Get a list of groups" + }, + "search_groups":{ + "httpMethod":"GET", + "uri": "search.json?query=\"{query} type:group\"", + "summary": "Uses a search query to get a list of groups", + "parameters":{ + "query":{ + "location": "uri", + "description":"Zendesk Search Query", + "type": "string", + "required": true + } + } + }, + "create_group": { + "httpMethod":"POST", + "uri": "groups.json", + "summary": "Create a group", + "parameters":{ + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + }, + "delete_group": { + "httpMethod":"DELETE", + "uri": "groups/{id}.json", + "summary": "Delete a group", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to delete by ID", + "type": "integer", + "required": true + } + } + }, + "get_group": { + "httpMethod":"GET", + "uri": "groups/{id}.json", + "summary": "Get a ticket", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to get by ID", + "type": "integer", + "required": true + } + } + }, + "update_group": { + "httpMethod":"PUT", + "uri": "groups/{id}.json", + "summary": "Update a group", + "parameters":{ + "id": { + "location": "uri", + "description":"Group to update by ID", + "type": "integer", + "required": true + }, + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + } +} +``` + +### Guzzle\Service\Description\ServiceDescription + +Commands are now called Operations + +**Before** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getCommands(); // @returns ApiCommandInterface[] +$sd->hasCommand($name); +$sd->getCommand($name); // @returns ApiCommandInterface|null +$sd->addCommand($command); // @param ApiCommandInterface $command +``` + +**After** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getOperations(); // @returns OperationInterface[] +$sd->hasOperation($name); +$sd->getOperation($name); // @returns OperationInterface|null +$sd->addOperation($operation); // @param OperationInterface $operation +``` + +### Guzzle\Common\Inflection\Inflector + +Namespace is now `Guzzle\Inflection\Inflector` + +### Guzzle\Http\Plugin + +Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. + +### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log + +Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. + +**Before** + +```php +use Guzzle\Common\Log\ClosureLogAdapter; +use Guzzle\Http\Plugin\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $verbosity is an integer indicating desired message verbosity level +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); +``` + +**After** + +```php +use Guzzle\Log\ClosureLogAdapter; +use Guzzle\Log\MessageFormatter; +use Guzzle\Plugin\Log\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $format is a string indicating desired message format -- @see MessageFormatter +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); +``` + +### Guzzle\Http\Plugin\CurlAuthPlugin + +Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. + +### Guzzle\Http\Plugin\ExponentialBackoffPlugin + +Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. + +**Before** + +```php +use Guzzle\Http\Plugin\ExponentialBackoffPlugin; + +$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( + ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) + )); + +$client->addSubscriber($backoffPlugin); +``` + +**After** + +```php +use Guzzle\Plugin\Backoff\BackoffPlugin; +use Guzzle\Plugin\Backoff\HttpBackoffStrategy; + +// Use convenient factory method instead -- see implementation for ideas of what +// you can do with chaining backoff strategies +$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( + HttpBackoffStrategy::getDefaultFailureCodes(), array(429) + )); +$client->addSubscriber($backoffPlugin); +``` + +### Known Issues + +#### [BUG] Accept-Encoding header behavior changed unintentionally. + +(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) + +In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to +properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. +See issue #217 for a workaround, or use a version containing the fix. diff --git a/vendor/guzzlehttp/guzzle/composer.json b/vendor/guzzlehttp/guzzle/composer.json new file mode 100644 index 0000000..d3c8905 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/composer.json @@ -0,0 +1,132 @@ +{ + "name": "guzzlehttp/guzzle", + "description": "Guzzle is a PHP HTTP client library", + "license": "MIT", + "keywords": [ + "framework", + "http", + "rest", + "web service", + "curl", + "client", + "HTTP client", + "PSR-7", + "PSR-18" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.4 || ^8.0", + "ext-json": "*", + "guzzlehttp/promises": "^3.1.1", + "guzzlehttp/psr7": "^3.5.1", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0", + "symfony/polyfill-php80": "^1.25", + "symfony/polyfill-php82": "^1.27" + }, + "require-dev": { + "ext-curl": "*", + "bamarni/composer-bin-plugin": "^1.8.2", + "guzzle/client-integration-tests": "4.0.1", + "guzzlehttp/test-server": "^1.1", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^9.6.34", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "repositories": [ + { + "type": "package", + "package": { + "name": "guzzle/client-integration-tests", + "version": "v4.0.1", + "require": { + "guzzlehttp/psr7": "^3.5.1", + "php": "^7.4 || ^8.0", + "php-http/message": "^1.0 || ^2.0", + "phpunit/phpunit": "^9.6.34", + "th3n3rd/cartesian-product": "^0.3" + }, + "autoload": { + "psr-4": { + "Http\\Client\\Tests\\": "src/" + } + }, + "bin": [ + "bin/http_test_server" + ], + "dist": { + "type": "zip", + "url": "https://codeload.github.com/guzzle/client-integration-tests/zip/e54cb9d94e3aa5e125dcd7d01bec22db202444ac" + } + } + } + ], + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\": "tests/" + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Auth/DigestAuth.php b/vendor/guzzlehttp/guzzle/src/Auth/DigestAuth.php new file mode 100644 index 0000000..d3dcbf5 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Auth/DigestAuth.php @@ -0,0 +1,515 @@ + + */ + private const ALGORITHMS = [ + 'MD5' => ['hash' => 'md5', 'sess' => false, 'rank' => 10, 'header' => 'MD5'], + 'MD5-SESS' => ['hash' => 'md5', 'sess' => true, 'rank' => 11, 'header' => 'MD5-sess'], + 'SHA-256' => ['hash' => 'sha256', 'sess' => false, 'rank' => 20, 'header' => 'SHA-256'], + 'SHA-256-SESS' => ['hash' => 'sha256', 'sess' => true, 'rank' => 21, 'header' => 'SHA-256-sess'], + 'SHA-512-256' => ['hash' => 'sha512/256', 'sess' => false, 'rank' => 30, 'header' => 'SHA-512-256'], + 'SHA-512-256-SESS' => ['hash' => 'sha512/256', 'sess' => true, 'rank' => 31, 'header' => 'SHA-512-256-sess'], + ]; + + /** + * @var array + */ + private const DIGEST_CHALLENGE_PARAMETER_NAMES = [ + 'realm' => true, + 'domain' => true, + 'nonce' => true, + 'opaque' => true, + 'stale' => true, + 'algorithm' => true, + 'qop' => true, + 'charset' => true, + 'userhash' => true, + ]; + + private function __construct() + { + } + + public static function selectChallenge( + #[\SensitiveParameter] + ResponseInterface $response + ): ?DigestChallenge { + $selected = null; + + foreach ($response->getHeader('WWW-Authenticate') as $header) { + foreach (self::parseAuthenticateHeader($header) as $challenge) { + if ($challenge['scheme'] !== 'digest' || $challenge['invalid']) { + continue; + } + + $digest = self::createChallenge($challenge['params']); + if ($digest === null) { + continue; + } + + if ($selected === null || $digest->algorithm['rank'] > $selected->algorithm['rank']) { + $selected = $digest; + } + } + } + + return $selected; + } + + public static function authorizationHeader( + #[\SensitiveParameter] + RequestInterface $request, + DigestChallenge $challenge, + string $username, + #[\SensitiveParameter] + string $password, + string $cnonce, + string $nc = '00000001' + ): ?string { + if ($challenge->algorithm['sess'] && $challenge->qop === null) { + return null; + } + + $uri = $request->getRequestTarget(); + if ($uri === '') { + $uri = '/'; + } + + foreach ([$username, $challenge->realm, $challenge->nonce, $uri, $cnonce] as $value) { + if (!self::isHeaderSafe($value)) { + return null; + } + } + + if ($challenge->opaque !== null && !self::isHeaderSafe($challenge->opaque)) { + return null; + } + + if ($challenge->qop !== null && !self::isNonceCount($nc)) { + return null; + } + + $hash = $challenge->algorithm['hash']; + $ha1 = \hash($hash, $username.':'.$challenge->realm.':'.$password); + + if ($challenge->algorithm['sess']) { + $ha1 = \hash($hash, $ha1.':'.$challenge->nonce.':'.$cnonce); + } + + $ha2 = \hash($hash, $request->getMethod().':'.$uri); + $response = $challenge->qop === null + ? \hash($hash, $ha1.':'.$challenge->nonce.':'.$ha2) + : \hash($hash, $ha1.':'.$challenge->nonce.':'.$nc.':'.$cnonce.':'.$challenge->qop.':'.$ha2); + + if ($challenge->userhash) { + $headerUsername = \hash($hash, $username.':'.$challenge->realm); + if ($headerUsername === false) { + return null; + } + } else { + $headerUsername = $username; + } + + $parts = [ + 'username='.self::quote($headerUsername), + 'realm='.self::quote($challenge->realm), + 'nonce='.self::quote($challenge->nonce), + 'uri='.self::quote($uri), + 'response='.self::quote($response), + 'algorithm='.$challenge->algorithm['header'], + ]; + + if ($challenge->opaque !== null) { + $parts[] = 'opaque='.self::quote($challenge->opaque); + } + + if ($challenge->qop !== null) { + $parts[] = 'qop='.$challenge->qop; + $parts[] = 'nc='.$nc; + $parts[] = 'cnonce='.self::quote($cnonce); + } + + if ($challenge->userhash) { + $parts[] = 'userhash=true'; + } + + return 'Digest '.\implode(', ', $parts); + } + + /** + * @return list, invalid: bool}> + */ + public static function parseAuthenticateHeader(string $header): array + { + $length = \strlen($header); + $offset = 0; + $challenges = []; + + while (true) { + self::skipSeparators($header, $offset, $length); + if ($offset >= $length) { + break; + } + + $scheme = self::readToken($header, $offset, $length); + if ($scheme === null) { + break; + } + + self::skipWhitespace($header, $offset, $length); + + if (self::skipToken68Challenge($header, $offset, $length)) { + $challenges[] = [ + 'scheme' => Psr7\Utils::asciiToLower($scheme), + 'params' => [], + 'invalid' => false, + ]; + + continue; + } + + $params = []; + $invalid = false; + + while ($offset < $length) { + self::skipWhitespace($header, $offset, $length); + + if ($offset < $length && $header[$offset] === ',') { + if (self::commaStartsNextChallenge($header, $offset + 1, $length)) { + if (Psr7\Utils::caselessEquals($scheme, 'Digest') + && self::commaStartsKnownDigestParameterWithoutValue($header, $offset + 1, $length) + ) { + $invalid = true; + break; + } + + ++$offset; + break; + } + + ++$offset; + continue; + } + + $name = self::readToken($header, $offset, $length); + if ($name === null) { + if ($offset < $length) { + $invalid = true; + } + + break; + } + + self::skipWhitespace($header, $offset, $length); + if ($offset >= $length || $header[$offset] !== '=') { + $invalid = true; + break; + } + + ++$offset; + self::skipWhitespace($header, $offset, $length); + + $value = self::readValue($header, $offset, $length); + if ($value === null) { + $invalid = true; + break; + } + + $lowerName = Psr7\Utils::asciiToLower($name); + if (\array_key_exists($lowerName, $params)) { + $invalid = true; + } + + $params[$lowerName] = $value; + + self::skipWhitespace($header, $offset, $length); + if ($offset >= $length) { + break; + } + + if ($header[$offset] !== ',') { + $invalid = true; + break; + } + } + + $challenges[] = [ + 'scheme' => Psr7\Utils::asciiToLower($scheme), + 'params' => $params, + 'invalid' => $invalid, + ]; + } + + return $challenges; + } + + /** + * @param array $params + */ + private static function createChallenge(array $params): ?DigestChallenge + { + if (!isset($params['nonce']) || $params['nonce'] === '') { + return null; + } + + if (isset($params['charset']) && !Psr7\Utils::caselessEquals($params['charset'], 'UTF-8')) { + return null; + } + + $algorithm = self::algorithm($params['algorithm'] ?? null); + if ($algorithm === null) { + return null; + } + + $qop = self::selectQop($params['qop'] ?? null); + if ($qop === false) { + return null; + } + + if ($algorithm['sess'] && $qop === null) { + return null; + } + + $challenge = new DigestChallenge(); + $challenge->algorithm = $algorithm; + $challenge->realm = $params['realm'] ?? ''; + $challenge->nonce = $params['nonce']; + $challenge->opaque = $params['opaque'] ?? null; + if (isset($params['domain'])) { + $domainAreas = \preg_split('/[ \t]+/', $params['domain']); + + if ($domainAreas === false) { + throw new \RuntimeException('Unable to split the Digest domain list: '.\preg_last_error_msg()); + } + + $challenge->domain = \array_values(\array_filter($domainAreas)); + } else { + $challenge->domain = []; + } + $challenge->qop = $qop; + $challenge->stale = isset($params['stale']) && Psr7\Utils::caselessEquals($params['stale'], 'true'); + $challenge->userhash = isset($params['userhash']) && Psr7\Utils::caselessEquals($params['userhash'], 'true'); + + return $challenge; + } + + /** + * @return array{name: string, hash: string, sess: bool, rank: int, header: string}|null + */ + private static function algorithm(?string $algorithm): ?array + { + $name = Psr7\Utils::asciiToUpper($algorithm ?? 'MD5'); + + if (!isset(self::ALGORITHMS[$name])) { + return null; + } + + $mapped = self::ALGORITHMS[$name]; + if (!\in_array($mapped['hash'], \hash_algos(), true)) { + return null; + } + + return ['name' => $name] + $mapped; + } + + /** + * @return string|false|null + */ + private static function selectQop(?string $qop) + { + if ($qop === null) { + return null; + } + + $tokens = \array_map( + static function (string $token): string { + return Psr7\Utils::asciiToLower(\trim($token, " \t")); + }, + \explode(',', $qop) + ); + + return \in_array('auth', $tokens, true) ? 'auth' : false; + } + + private static function quote(string $value): string + { + return '"'.\strtr($value, [ + '\\' => '\\\\', + '"' => '\\"', + ]).'"'; + } + + private static function isHeaderSafe(string $value): bool + { + return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value) === 1; + } + + private static function isNonceCount(string $nc): bool + { + // Nonce counts start at one. + return $nc !== '00000000' && \preg_match('/^[0-9a-f]{8}$/D', $nc) === 1; + } + + private static function commaStartsNextChallenge(string $header, int $offset, int $length): bool + { + self::skipWhitespace($header, $offset, $length); + $nextOffset = $offset; + $token = self::readToken($header, $nextOffset, $length); + if ($token === null) { + return false; + } + + self::skipWhitespace($header, $nextOffset, $length); + + return $nextOffset >= $length || $header[$nextOffset] !== '='; + } + + private static function commaStartsKnownDigestParameterWithoutValue(string $header, int $offset, int $length): bool + { + self::skipWhitespace($header, $offset, $length); + $name = self::readToken($header, $offset, $length); + if ($name === null || !isset(self::DIGEST_CHALLENGE_PARAMETER_NAMES[Psr7\Utils::asciiToLower($name)])) { + return false; + } + + self::skipWhitespace($header, $offset, $length); + + return $offset >= $length || $header[$offset] !== '='; + } + + private static function skipToken68Challenge(string $header, int &$offset, int $length): bool + { + $cursor = $offset; + $hasValue = false; + while ($cursor < $length && self::isToken68Char($header[$cursor])) { + $hasValue = true; + ++$cursor; + } + + while ($cursor < $length && $header[$cursor] === '=') { + ++$cursor; + } + + if (!$hasValue) { + return false; + } + + $after = $cursor; + self::skipWhitespace($header, $after, $length); + + if ($after < $length && $header[$after] !== ',') { + return false; + } + + $offset = $after; + + return true; + } + + private static function skipSeparators(string $header, int &$offset, int $length): void + { + while ($offset < $length) { + $char = $header[$offset]; + if ($char !== ',' && !self::isWhitespace($char)) { + return; + } + + ++$offset; + } + } + + private static function skipWhitespace(string $header, int &$offset, int $length): void + { + while ($offset < $length && self::isWhitespace($header[$offset])) { + ++$offset; + } + } + + private static function isWhitespace(string $char): bool + { + return $char === ' ' || $char === "\t"; + } + + private static function readToken(string $header, int &$offset, int $length): ?string + { + $start = $offset; + while ($offset < $length && self::isTokenChar($header[$offset])) { + ++$offset; + } + + if ($offset === $start) { + return null; + } + + $token = \substr($header, $start, $offset - $start); + + return $token === false ? null : $token; + } + + private static function isTokenChar(string $char): bool + { + return \strspn($char, "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") === 1; + } + + private static function isToken68Char(string $char): bool + { + return \strspn($char, '-._~+/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') === 1; + } + + private static function readValue(string $header, int &$offset, int $length): ?string + { + if ($offset >= $length) { + return null; + } + + if ($header[$offset] === '"') { + return self::readQuotedString($header, $offset, $length); + } + + return self::readToken($header, $offset, $length); + } + + private static function readQuotedString(string $header, int &$offset, int $length): ?string + { + ++$offset; + $value = ''; + $escaped = false; + + while ($offset < $length) { + $char = $header[$offset++]; + + if ($escaped) { + $value .= $char; + $escaped = false; + continue; + } + + if ($char === '\\') { + $escaped = true; + continue; + } + + if ($char === '"') { + return $value; + } + + $value .= $char; + } + + return null; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Auth/DigestChallenge.php b/vendor/guzzlehttp/guzzle/src/Auth/DigestChallenge.php new file mode 100644 index 0000000..d030203 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Auth/DigestChallenge.php @@ -0,0 +1,29 @@ + */ + public array $domain = []; + + public ?string $qop = null; + + public bool $stale = false; + + public bool $userhash = false; +} diff --git a/vendor/guzzlehttp/guzzle/src/AuthMiddleware.php b/vendor/guzzlehttp/guzzle/src/AuthMiddleware.php new file mode 100644 index 0000000..fc708d9 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/AuthMiddleware.php @@ -0,0 +1,846 @@ + + */ + private const DIGEST_PROBE_PAYLOAD_HEADERS = [ + 'Transfer-Encoding', + 'Expect', + 'Trailer', + 'Content-Range', + 'Content-Encoding', + 'Content-MD5', + 'Digest', + 'Content-Digest', + 'Repr-Digest', + ]; + + /** + * @var callable(RequestInterface, array): PromiseInterface + */ + private $nextHandler; + + /** + * @var callable(): string + */ + private $cnonceGenerator; + + private bool $reuseChallenges; + + private ?string $credentialHashSecret = null; + + /** + * @var array + */ + private array $digestChallenges = []; + + /** + * @param callable(RequestInterface, array): PromiseInterface $nextHandler + * @param (callable(): string)|null $cnonceGenerator + */ + public function __construct(callable $nextHandler, ?callable $cnonceGenerator = null, bool $reuseChallenges = true) + { + $this->nextHandler = $nextHandler; + $this->cnonceGenerator = $cnonceGenerator ?? static function (): string { + return \bin2hex(\random_bytes(16)); + }; + $this->reuseChallenges = $reuseChallenges; + } + + /** + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + $auth = $options['auth'] ?? null; + if ($auth === null || $auth === false || $auth === [] || \is_string($auth)) { + return ($this->nextHandler)($request, $options); + } + + $normalizedAuth = self::normalizeAuth($auth); + if ($normalizedAuth === null) { + return ($this->nextHandler)($request, $options); + } + + [$username, $password, $type] = $normalizedAuth; + + if ($type === 'basic') { + return $this->sendBasic($request, $options, $username, $password); + } + + return $this->sendDigest($request, $options, $username, $password); + } + + /** + * @param array $auth + * + * @return array{0: string, 1: string, 2: 'basic'|'digest'}|null + */ + private static function normalizeAuth( + #[\SensitiveParameter] + array $auth + ): ?array { + $type = 'basic'; + if (\array_key_exists(2, $auth) && $auth[2] !== null) { + if (!\is_string($auth[2])) { + throw new InvalidArgumentException('auth type must be a string'); + } + + $type = Psr7\Utils::asciiToLower($auth[2]); + } + + if (!\in_array($type, ['basic', 'digest'], true)) { + return null; + } + + if (!\array_key_exists(0, $auth) || !\array_key_exists(1, $auth)) { + throw new InvalidArgumentException('auth must contain username and password strings'); + } + + if (!\is_string($auth[0]) || !\is_string($auth[1])) { + throw new InvalidArgumentException('auth must contain username and password strings'); + } + + return [$auth[0], $auth[1], $type]; + } + + /** + * @return PromiseInterface + */ + private function sendBasic( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + string $username, + #[\SensitiveParameter] + string $password + ): PromiseInterface { + if (\strpos($username, ':') !== false) { + throw new InvalidArgumentException('Basic authentication username must not contain a colon'); + } + + if (\preg_match('/[\x00-\x1F\x7F]/', $username.$password) !== 0) { + throw new InvalidArgumentException('Basic authentication credentials must not contain ASCII control characters'); + } + + unset($options['auth']); + + return ($this->nextHandler)( + $request->withHeader('Authorization', 'Basic '.\base64_encode($username.':'.$password)), + $options + ); + } + + /** + * @return PromiseInterface + */ + private function sendDigest( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + string $username, + #[\SensitiveParameter] + string $password + ): PromiseInterface { + $preemptive = $this->reuseChallenges + ? $this->preemptiveDigestRequest($request, $username, $password) + : null; + + if ($preemptive !== null) { + $preemptiveOptions = self::withTemporarySink($options); + unset($preemptiveOptions['auth']); + + return ($this->nextHandler)($preemptive, $preemptiveOptions)->then( + function ( + #[\SensitiveParameter] + ResponseInterface $response + ) use ($request, $options, $preemptiveOptions, $username, $password) { + // Clear on 4xx/5xx other than 401 so non-conformant stale-nonce + // errors cannot poison the cache indefinitely. + $status = $response->getStatusCode(); + if ($status >= 400 && $status !== 401) { + $this->clearDigestChallenge($request); + } + + return $this->handleDigestResponse($request, $options, $preemptiveOptions, $response, $username, $password, false); + }, + function ( + #[\SensitiveParameter] + $reason + ) use ($request, $preemptiveOptions) { + return $this->handleDigestRejection($request, $preemptiveOptions, $reason, true); + } + ); + } + + $probeOptions = self::withTemporarySink($options); + unset($probeOptions['auth']); + + [$probeRequest, $bodyWithheld] = self::probeRequest($request, $options); + + if ($bodyWithheld) { + // The probe has no payload, so prepare_body must not add Expect + // if a custom empty stream has unknown size. + $probeOptions[RequestOptions::EXPECT] = false; + } + + return ($this->nextHandler)($probeRequest, $probeOptions)->then( + function ( + #[\SensitiveParameter] + ResponseInterface $response + ) use ($request, $options, $probeOptions, $username, $password, $bodyWithheld) { + return $this->handleDigestResponse($request, $options, $probeOptions, $response, $username, $password, $bodyWithheld); + }, + function ( + #[\SensitiveParameter] + $reason + ) use ($request, $probeOptions) { + return $this->handleDigestRejection($request, $probeOptions, $reason, false); + } + ); + } + + private function preemptiveDigestRequest( + #[\SensitiveParameter] + RequestInterface $request, + string $username, + #[\SensitiveParameter] + string $password + ): ?RequestInterface { + try { + if ($request->getBody()->getSize() !== 0) { + return null; + } + } catch (\Exception $e) { + return null; + } + + $key = self::digestCacheKey($request); + if ($key === null) { + return null; + } + + $entry = $this->digestChallenges[$key] ?? null; + if ($entry === null + || $entry['credentials'] !== $this->digestCredentialKey($username, $password) + || !self::challengeCoversRequest($entry['challenge'], $request) + ) { + return null; + } + + $authorization = DigestAuth::authorizationHeader( + $request, + $entry['challenge'], + $username, + $password, + ($this->cnonceGenerator)(), + \sprintf('%08x', $entry['nextNc']) + ); + + if ($authorization === null) { + return null; + } + + ++$this->digestChallenges[$key]['nextNc']; + + return $request->withHeader('Authorization', $authorization); + } + + /** + * Builds the unauthenticated probe request for a Digest handshake. + * + * @return array{0: RequestInterface, 1: bool} + */ + private static function probeRequest( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): array { + $probe = $request->withoutHeader('Authorization'); + + try { + $size = $probe->getBody()->getSize(); + } catch (\Exception $e) { + $size = null; + } + + if ($size === 0) { + return [$probe, false]; + } + + $streamFactory = self::requireStreamFactory( + $options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory() + ); + + $probe = $probe->withBody($streamFactory->createStream('')) + ->withHeader('Content-Length', '0'); + + foreach (self::DIGEST_PROBE_PAYLOAD_HEADERS as $header) { + $probe = $probe->withoutHeader($header); + } + + return [$probe, true]; + } + + /** + * @return ResponseInterface|PromiseInterface + */ + private function handleDigestResponse( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + array $probeOptions, + #[\SensitiveParameter] + ResponseInterface $response, + string $username, + #[\SensitiveParameter] + string $password, + bool $bodyWithheld + ) { + $status = $response->getStatusCode(); + + $previousEntry = null; + if ($this->reuseChallenges && $status === 401) { + $key = self::digestCacheKey($request); + $previousEntry = $key !== null ? ($this->digestChallenges[$key] ?? null) : null; + $this->clearDigestChallenge($request); + } + + if ($status !== 401) { + if ($this->reuseChallenges && $response->hasHeader('Authentication-Info')) { + $this->clearDigestChallenge($request); + } + + $response = self::restoreOriginalSink($request, $response, $probeOptions); + + if ($bodyWithheld && $status !== 407 && !self::isRedirectLikeResponse($response)) { + throw new ResponseException( + 'Digest authentication failed because the server did not issue a challenge; the request was probed without its body', + $request, + $response + ); + } + + return $response; + } + + $challenge = DigestAuth::selectChallenge($response); + if ($challenge === null) { + return self::restoreOriginalSink($request, $response, $probeOptions); + } + + $retries = $options['__guzzle_digest_retries'] ?? 0; + if (!\is_int($retries)) { + $retries = 0; + } + + if (($retries > 0 && !$challenge->stale) || $retries >= self::DIGEST_MAX_RETRIES) { + return self::restoreOriginalSink($request, $response, $probeOptions); + } + + try { + self::rewindBodyForRetry($request, $bodyWithheld); + } catch (\Exception $e) { + $response = self::restoreOriginalSink($request, $response, $probeOptions); + + throw new ResponseException( + 'Digest authentication failed because the request body could not be rewound', + $request, + $response, + $e + ); + } + + $nonceCounts = self::digestNonceCountsFromOptions($options); + + if ($previousEntry !== null + && $previousEntry['credentials'] === $this->digestCredentialKey($username, $password) + ) { + self::rememberDigestNonceCount($nonceCounts, $previousEntry['challenge'], $previousEntry['nextNc']); + } + + $nc = $challenge->qop === null ? 1 : ($nonceCounts[self::digestNonceCountKey($challenge)] ?? 1); + + $authorization = DigestAuth::authorizationHeader( + $request, + $challenge, + $username, + $password, + ($this->cnonceGenerator)(), + \sprintf('%08x', $nc) + ); + + if ($authorization === null) { + return self::restoreOriginalSink($request, $response, $probeOptions); + } + + $response->getBody()->close(); + + self::rememberDigestNonceCount($nonceCounts, $challenge, $nc + 1); + + $retryOptions = $options; + $retryOptions['__guzzle_digest_retries'] = $retries + 1; + $retryOptions[self::DIGEST_NONCE_COUNTS_OPTION] = $nonceCounts; + $downstreamOptions = $retryOptions; + // The nonce-count map only carries handshake state into the retry + // recursion; downstream handlers must not observe it. + unset($downstreamOptions[self::DIGEST_NONCE_COUNTS_OPTION]); + // The caller's delay applies once, before the first Digest leg, not + // before each handshake retry. + unset($downstreamOptions[RequestOptions::DELAY]); + $downstreamOptions = self::withTemporarySink($downstreamOptions); + unset($downstreamOptions['auth']); + + $retryRequest = $request->withHeader('Authorization', $authorization); + + return ($this->nextHandler)($retryRequest, $downstreamOptions)->then( + function ( + #[\SensitiveParameter] + ResponseInterface $retryResponse + ) use ($retryRequest, $retryOptions, $downstreamOptions, $username, $password, $challenge, $nc) { + if ($this->reuseChallenges && self::isCacheableDigestSuccess($retryResponse)) { + $this->storeDigestChallenge($retryRequest, $challenge, $username, $password, $nc + 1); + } + + return $this->handleDigestResponse($retryRequest, $retryOptions, $downstreamOptions, $retryResponse, $username, $password, false); + }, + function ( + #[\SensitiveParameter] + $reason + ) use ($retryRequest, $downstreamOptions) { + return $this->handleDigestRejection($retryRequest, $downstreamOptions, $reason, false); + } + ); + } + + private static function isCacheableDigestSuccess(ResponseInterface $response): bool + { + $status = $response->getStatusCode(); + + return $status >= 200 && $status < 400 && !$response->hasHeader('Authentication-Info'); + } + + private function storeDigestChallenge( + #[\SensitiveParameter] + RequestInterface $request, + DigestChallenge $challenge, + string $username, + #[\SensitiveParameter] + string $password, + int $nextNc + ): void { + $key = self::digestCacheKey($request); + if ($key === null || $challenge->qop === null) { + return; + } + + unset($this->digestChallenges[$key]); + + if (\count($this->digestChallenges) >= self::CHALLENGE_CACHE_LIMIT) { + \array_shift($this->digestChallenges); + } + + $this->digestChallenges[$key] = [ + 'challenge' => $challenge, + 'credentials' => $this->digestCredentialKey($username, $password), + 'nextNc' => $nextNc, + ]; + } + + private function clearDigestChallenge(RequestInterface $request): void + { + $key = self::digestCacheKey($request); + if ($key !== null) { + unset($this->digestChallenges[$key]); + } + } + + /** + * @param array $options + * + * @return array + */ + private static function digestNonceCountsFromOptions(array $options): array + { + $counts = $options[self::DIGEST_NONCE_COUNTS_OPTION] ?? []; + if (!\is_array($counts)) { + return []; + } + + $normalized = []; + foreach ($counts as $key => $nextNc) { + if (\is_string($key) && \is_int($nextNc) && $nextNc > 0 && $nextNc < \PHP_INT_MAX) { + $normalized[$key] = $nextNc; + } + } + + return $normalized; + } + + private static function digestNonceCountKey(DigestChallenge $challenge): string + { + return \implode("\0", [ + $challenge->realm, + $challenge->nonce, + $challenge->qop ?? '', + $challenge->algorithm['header'], + ]); + } + + /** + * @param array $counts + */ + private static function rememberDigestNonceCount(array &$counts, DigestChallenge $challenge, int $nextNc): void + { + if ($challenge->qop === null) { + return; + } + + $key = self::digestNonceCountKey($challenge); + $counts[$key] = \max($counts[$key] ?? 1, $nextNc); + } + + /** + * @param mixed $reason + * + * @return PromiseInterface + */ + private function handleDigestRejection( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + $reason, + bool $preemptive + ): PromiseInterface { + if ($this->reuseChallenges && $reason instanceof ResponseException) { + $response = $reason->getResponse(); + + if ($response->getStatusCode() === 401 + || $response->hasHeader('Authentication-Info') + || ($preemptive && $response->getStatusCode() >= 400) + ) { + $this->clearDigestChallenge($request); + } + } + + return self::restoreOriginalSinkOnRejection($options, $reason); + } + + private static function digestCacheKey(RequestInterface $request): ?string + { + $uri = $request->getUri(); + $scheme = Psr7\Utils::asciiToLower($uri->getScheme()); + $host = HostIdentity::canonicalHost($uri->getHost()); + + if (($scheme !== 'http' && $scheme !== 'https') || $host === '') { + return null; + } + + $port = $uri->getPort() ?? ($scheme === 'https' ? 443 : 80); + + return $scheme.'://'.$host.':'.$port.'|'.HostIdentity::canonicalHostHeader($request->getHeaderLine('Host')); + } + + private function digestCredentialKey( + string $username, + #[\SensitiveParameter] + string $password + ): string { + if ($this->credentialHashSecret === null) { + $this->credentialHashSecret = \random_bytes(32); + } + + return \hash_hmac('sha256', $username."\0".$password, $this->credentialHashSecret); + } + + private static function challengeCoversRequest(DigestChallenge $challenge, RequestInterface $request): bool + { + if ($challenge->domain === []) { + return true; + } + + $target = $request->getRequestTarget(); + foreach ($challenge->domain as $space) { + $prefix = self::protectionSpacePath($space, $request); + if ($prefix !== null && \str_starts_with($target, $prefix)) { + return true; + } + } + + return false; + } + + private static function protectionSpacePath(string $space, RequestInterface $request): ?string + { + if ($space === '') { + return null; + } + + if ($space[0] === '/') { + return $space; + } + + try { + // A server must not be able to raise the psr7 host deprecation. + $uri = (new Psr7\ErrorScope(\E_USER_DEPRECATED))->run(static function () use ($space): Psr7\Uri { + return new Psr7\Uri($space); + }); + } catch (\InvalidArgumentException $e) { + return null; + } + + if (Psr7\UriComparator::isCrossOrigin($uri, self::effectiveRequestUri($request))) { + return null; + } + + $path = $uri->getPath(); + $prefix = $path === '' ? '/' : $path; + + if ($uri->getQuery() !== '') { + $prefix .= '?'.$uri->getQuery(); + } + + return $prefix; + } + + private static function effectiveRequestUri(RequestInterface $request): UriInterface + { + $uri = $request->getUri(); + $host = $request->getHeaderLine('Host'); + if ($host === '' || Psr7\Utils::caselessEquals($host, $uri->getHost())) { + return $uri; + } + + try { + $authority = new Psr7\Uri('//'.$host); + if ($authority->getHost() === '') { + return $uri; + } + + return $uri->withHost($authority->getHost())->withPort($authority->getPort()); + } catch (\InvalidArgumentException $e) { + return $uri; + } + } + + private static function isRedirectLikeResponse(ResponseInterface $response): bool + { + return $response->hasHeader('Location') + && \in_array($response->getStatusCode(), [301, 302, 303, 307, 308], true); + } + + private static function rewindBodyForRetry( + #[\SensitiveParameter] + RequestInterface $request, + bool $bodyWithheld + ): void { + $body = $request->getBody(); + + if (!$bodyWithheld) { + try { + if ($body->getSize() === 0) { + return; + } + } catch (\Exception $e) { + // Fall through to the standard rewind path. + } + + Psr7\Message::rewindBody($request); + + return; + } + + if ($body->isSeekable()) { + $body->rewind(); + } + } + + private static function withTemporarySink( + #[\SensitiveParameter] + array $options + ): array { + // The 'stream' option is deliberately not checked here: the cURL + // handlers do not support streaming and write each leg to the sink, + // so a configured sink always needs challenge-body protection. + if (!isset($options[RequestOptions::SINK])) { + return $options; + } + + $streamFactory = self::requireStreamFactory( + $options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory() + ); + + $options['__guzzle_auth_original_sink'] = $options[RequestOptions::SINK]; + $options[RequestOptions::SINK] = $streamFactory->createStreamFromResource( + Psr7\Utils::tryFopen('php://temp', 'w+') + ); + + return $options; + } + + private static function restoreOriginalSink( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + ResponseInterface $response, + #[\SensitiveParameter] + array $options + ): ResponseInterface { + if (!\array_key_exists('__guzzle_auth_original_sink', $options)) { + return $response; + } + + try { + $source = $response->getBody(); + if ($source->isSeekable()) { + $source->rewind(); + } + + $target = self::streamForOriginalSink($options['__guzzle_auth_original_sink']); + + Psr7\Utils::copyToStream($source, $target); + + if ($target->isSeekable()) { + $target->rewind(); + } + + return $response->withBody($target); + } catch (\Exception $e) { + throw new ResponseException( + $e->getMessage() !== '' ? $e->getMessage() : 'Failed to write the response body', + $request, + $response, + $e + ); + } + } + + /** + * @param mixed $reason + * + * @return PromiseInterface + */ + private static function restoreOriginalSinkOnRejection( + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + $reason + ): PromiseInterface { + if (!$reason instanceof ResponseException || !\array_key_exists('__guzzle_auth_original_sink', $options)) { + /** @var PromiseInterface */ + return P\Create::rejectionFor($reason); + } + + try { + $response = self::restoreOriginalSink($reason->getRequest(), $reason->getResponse(), $options); + + /** @var PromiseInterface */ + return P\Create::rejectionFor($reason->withResponse($response)); + } catch (\Throwable $e) { + /** @var PromiseInterface */ + return P\Create::rejectionFor($e); + } + } + + /** + * @param mixed $sink + */ + private static function streamForOriginalSink($sink): StreamInterface + { + if (\is_string($sink)) { + return new LazyOpenStream($sink, 'w+'); + } + + if (\is_resource($sink)) { + return self::streamForResourceSink(Psr7\Utils::streamFor($sink)); + } + + if (!$sink instanceof StreamInterface) { + throw new InvalidArgumentException(\sprintf( + 'sink must be a resource, string, or %s', + StreamInterface::class + )); + } + + return Psr7\Utils::streamFor($sink); + } + + /** + * Decorates a caller-owned sink stream so that closing the response body + * detaches Guzzle's wrapper without closing the original PHP resource. + */ + private static function streamForResourceSink(StreamInterface $stream): StreamInterface + { + return Psr7\FnStream::decorate($stream, [ + 'close' => static function () use ($stream): void { + $stream->detach(); + }, + ]); + } + + /** + * @param mixed $factory + */ + private static function requireStreamFactory($factory): StreamFactoryInterface + { + if (!$factory instanceof StreamFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::STREAM_FACTORY, + StreamFactoryInterface::class + )); + } + + return $factory; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/BodySummarizer.php b/vendor/guzzlehttp/guzzle/src/BodySummarizer.php new file mode 100644 index 0000000..8912d33 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/BodySummarizer.php @@ -0,0 +1,29 @@ +truncateAt = $truncateAt; + } + + /** + * Returns a summarized message body. + */ + public function summarize(MessageInterface $message): ?string + { + try { + return Psr7\Message::bodySummary($message, $this->truncateAt); + } catch (\Exception $e) { + return null; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php b/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php new file mode 100644 index 0000000..9d23d9a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php @@ -0,0 +1,15 @@ + 'http://www.foo.com/1.0/', + * 'timeout' => 0, + * 'allow_redirects' => false, + * 'proxy' => '192.168.16.1:10' + * ]); + * + * Client configuration settings include the following options: + * + * - handler: (callable) Function that transfers HTTP requests over the + * wire. The function is called with a Psr7\Http\Message\RequestInterface + * and array of transfer options, and must return a + * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a + * Psr7\Http\Message\ResponseInterface on success. If no handler is + * provided, a default handler will be created that enables all of the + * request options below by attaching all of the default middleware to the + * handler. + * - base_uri: (string|UriInterface) Base URI of the client that is merged + * into relative URIs. Can be a string or instance of UriInterface. + * - transport_sharing: (string|null) Transport sharing mode for the default + * handler. Accepts TransportSharing::* or null. Defaults to null. + * - max_host_connections: (int|null) Maximum concurrent connections per + * host, enforced by the default CurlMultiHandler. The default stream + * fallback receives the cap as a marker only: it rejects enabled + * response streaming ("stream" => true) and does not limit overlapping + * buffered calls. + * - max_idle_handles: (int|null) Maximum number of idle cURL easy handles + * retained by each default cURL handler. Zero disables retention; null or + * omission keeps the defaults of 3 for CurlHandler and 50 for + * CurlMultiHandler. This setting does not affect the stream handler. + * - max_total_connections: (int|null) Maximum concurrent connections + * overall, enforced by the default CurlMultiHandler. The default stream + * fallback receives the cap as a marker only: it rejects enabled + * response streaming ("stream" => true) and does not limit overlapping + * buffered calls. + * - multiplex: (string|null) Multiplexing::NONE to disable multiplexing on + * the default CurlMultiHandler; the value also becomes the default + * "multiplex" request option. Other Multiplexing::* values act as the + * default request option only. + * - **: any request option + * + * @param array{ + * handler?: callable(RequestInterface, array): PromiseInterface, + * base_uri?: string|UriInterface, + * transport_sharing?: string|null, + * max_host_connections?: int|null, + * max_idle_handles?: int|null, + * max_total_connections?: int|null, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: bool|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $config Client configuration settings and default request options. + * + * @see RequestOptions for a list of available request options. + */ + public function __construct( + #[\SensitiveParameter] + array $config = [] + ) { + $handlerOptions = []; + foreach (['max_host_connections', 'max_idle_handles', 'max_total_connections'] as $handlerOption) { + if (\array_key_exists($handlerOption, $config)) { + if ($config[$handlerOption] !== null) { + $handlerOptions[$handlerOption] = $config[$handlerOption]; + } + + unset($config[$handlerOption]); + } + } + + // Deliberately not unset: the value also becomes the default + // "multiplex" request option, which the configured handler accepts. + $handlerMultiplex = ($config['multiplex'] ?? null) === Multiplexing::NONE; + + $transportSharing = \array_key_exists('transport_sharing', $config) ? $config['transport_sharing'] : null; + $transportSharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing'); + unset($config['transport_sharing']); + + if (!isset($config['handler'])) { + if ($transportSharingMode !== TransportSharing::NONE) { + $handlerOptions['transport_sharing'] = $transportSharingMode; + } + + if ($handlerMultiplex) { + $handlerOptions['multiplex'] = Multiplexing::NONE; + } + + $config['handler'] = $handlerOptions === [] + ? HandlerStack::create() + : HandlerStack::create(Utils::chooseHandler($handlerOptions)); + } elseif (!\is_callable($config['handler'])) { + throw new InvalidArgumentException('handler must be a callable'); + } elseif (isset($handlerOptions['max_idle_handles'])) { + throw new InvalidArgumentException('The "max_idle_handles" client option requires Guzzle to create the default handler. Configure the option on the CurlHandler or CurlMultiHandler constructor when providing a custom handler.'); + } elseif ($handlerOptions !== []) { + throw new InvalidArgumentException('The "max_host_connections" and "max_total_connections" client options require Guzzle to create the default handler. Configure the options on the CurlMultiHandler constructor for numeric enforcement, or on the StreamHandler constructor to reject enabled response streaming, when providing a custom handler.'); + } elseif ($transportSharingMode === TransportSharing::HANDLER_REQUIRE) { + throw new InvalidArgumentException('The "transport_sharing" client option can only require sharing when Guzzle creates the default handler. Configure the "transport_sharing" option on CurlHandler, CurlMultiHandler, or StreamHandler when providing a custom handler.'); + } elseif ($transportSharingMode === TransportSharing::PERSISTENT_REQUIRE) { + throw new InvalidArgumentException('The "transport_sharing" client option can only require sharing when Guzzle creates the default handler. Configure the "transport_sharing" option on CurlHandler or CurlMultiHandler when providing a custom handler.'); + } + + $factory = new HttpFactory(); + + if (!isset($config[RequestOptions::REQUEST_FACTORY])) { + $config[RequestOptions::REQUEST_FACTORY] = $factory; + } + + if (!isset($config[RequestOptions::URI_FACTORY])) { + $config[RequestOptions::URI_FACTORY] = $factory; + } + + if (!isset($config[RequestOptions::STREAM_FACTORY])) { + $config[RequestOptions::STREAM_FACTORY] = $factory; + } + + if (!isset($config[RequestOptions::RESPONSE_FACTORY])) { + $config[RequestOptions::RESPONSE_FACTORY] = $factory; + } + + self::requireRequestFactory($config[RequestOptions::REQUEST_FACTORY]); + self::requireResponseFactory($config[RequestOptions::RESPONSE_FACTORY]); + self::requireStreamFactory($config[RequestOptions::STREAM_FACTORY]); + $uriFactory = self::requireUriFactory($config[RequestOptions::URI_FACTORY]); + + // Convert the base_uri to a UriInterface using the configured URI factory. + if (isset($config['base_uri'])) { + $config['base_uri'] = self::createUri($config['base_uri'], $uriFactory); + } + + $this->configureDefaults($config); + } + + /** + * Asynchronously send an HTTP request. + * + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply to the given request and to the transfer. See {@see RequestOptions}. + * + * @return PromiseInterface + */ + public function sendAsync( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options = [] + ): PromiseInterface { + // Merge the base URI into the request URI if needed. + $options = $this->prepareDefaults($options); + + return $this->transfer( + $request->withUri($this->buildUri($request->getUri(), $options), self::shouldPreserveHost($request)), + $options + ); + } + + /** + * Send an HTTP request. + * + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply to the given request and to the transfer. See {@see RequestOptions}. + * + * @throws GuzzleException + */ + public function send( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options = [] + ): ResponseInterface { + $options[RequestOptions::SYNCHRONOUS] = true; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * The HttpClient PSR (PSR-18) specifies this method. + * + * {@inheritDoc} + */ + public function sendRequest( + #[\SensitiveParameter] + RequestInterface $request + ): ResponseInterface { + $options[RequestOptions::SYNCHRONOUS] = true; + $options[RequestOptions::ALLOW_REDIRECTS] = false; + $options[RequestOptions::HTTP_ERRORS] = false; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. See {@see RequestOptions}. + * + * @return PromiseInterface + */ + public function requestAsync( + string $method, + $uri = '', + #[\SensitiveParameter] + array $options = [] + ): PromiseInterface { + $options = $this->prepareDefaults($options); + + $version = self::normalizeProtocolVersion($options['version'] ?? '1.1'); + unset($options['version']); + + if (isset($options['body']) && \is_array($options['body'])) { + throw $this->invalidBody(); + } + + $uriFactory = isset($options[RequestOptions::URI_FACTORY]) + ? self::requireUriFactory($options[RequestOptions::URI_FACTORY]) + : new HttpFactory(); + $requestFactory = isset($options[RequestOptions::REQUEST_FACTORY]) + ? self::requireRequestFactory($options[RequestOptions::REQUEST_FACTORY]) + : new HttpFactory(); + + // Merge the URI into the base URI. + $uriIsString = \is_string($uri); + $uri = self::createUri($uri, $uriFactory); + $builtUri = $this->buildUri($uri, $options); + if ($uriIsString && $builtUri !== $uri) { + // The string form of an invalid host can name another host or port. + if (!Psr7\Rfc3986::isValidHost($builtUri->getHost())) { + throw new InvalidArgumentException(\sprintf('Invalid host: %s', DiagnosticValue::escape($builtUri->getHost()))); + } + + $builtUri = self::createUri((string) $builtUri, $uriFactory); + } + + $uri = $builtUri; + $request = $requestFactory->createRequest($method, $uri); + $request = Psr7\Utils::modifyRequest($request, ['version' => $version]); + + return $this->transfer($request, $options); + } + + /** + * Create and send an HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method. + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. See {@see RequestOptions}. + * + * @throws GuzzleException + */ + public function request( + string $method, + $uri = '', + #[\SensitiveParameter] + array $options = [] + ): ResponseInterface { + $options[RequestOptions::SYNCHRONOUS] = true; + + return $this->requestAsync($method, $uri, $options)->wait(); + } + + /** + * Get a client configuration option. + * + * These options include default request options of the client, a "handler" + * (if utilized by the concrete client), and a "base_uri" if utilized by the + * concrete client. + * + * @param string|null $option The config option to retrieve. + * + * @return ($option is null ? array : mixed) + */ + public function getConfig(?string $option = null) + { + return $option === null + ? $this->config + : ($this->config[$option] ?? null); + } + + private static function defaultUserAgent(): string + { + return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION); + } + + private function buildUri( + UriInterface $uri, + #[\SensitiveParameter] + array $config + ): UriInterface { + if (isset($config['base_uri'])) { + $uriFactory = self::requireUriFactory($config[RequestOptions::URI_FACTORY] ?? new HttpFactory()); + $uri = Psr7\UriResolver::resolve(self::createUri($config['base_uri'], $uriFactory), $uri); + } + + $idnOptions = Idn::normalizeConversionOption($config['idn_conversion'] ?? null); + if ($idnOptions !== null) { + $uri = Idn::convertUri($uri, $idnOptions); + } + + if ($uri->getScheme() === '' && $uri->getHost() !== '') { + $uri = $uri->withScheme('http'); + } + + return $uri; + } + + /** + * Whether to preserve an existing Host header when the URI changes. + * + * A header matching the current URI carries no explicit override and is + * regenerated after base URI resolution or IDN conversion. Other values + * are preserved as deliberate overrides, as PSR-7 requires. + */ + private static function shouldPreserveHost(RequestInterface $request): bool + { + if (!$request->hasHeader('Host')) { + return false; + } + + $uri = $request->getUri(); + $host = $uri->getHost(); + $port = $uri->getPort(); + + if ($port !== null) { + $host .= ':'.$port; + } + + return $host !== $request->getHeaderLine('Host'); + } + + /** + * @param mixed $factory + */ + private static function requireRequestFactory($factory): RequestFactoryInterface + { + if (!$factory instanceof RequestFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::REQUEST_FACTORY, + RequestFactoryInterface::class + )); + } + + return $factory; + } + + /** + * @param mixed $factory + */ + private static function requireResponseFactory($factory): ResponseFactoryInterface + { + if (!$factory instanceof ResponseFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::RESPONSE_FACTORY, + ResponseFactoryInterface::class + )); + } + + return $factory; + } + + /** + * @param mixed $factory + */ + private static function requireUriFactory($factory): UriFactoryInterface + { + if (!$factory instanceof UriFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::URI_FACTORY, + UriFactoryInterface::class + )); + } + + return $factory; + } + + /** + * @param mixed $factory + */ + private static function requireStreamFactory($factory): StreamFactoryInterface + { + if (!$factory instanceof StreamFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::STREAM_FACTORY, + StreamFactoryInterface::class + )); + } + + return $factory; + } + + /** + * @param mixed $uri + */ + private static function createUri($uri, UriFactoryInterface $uriFactory): UriInterface + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (\is_string($uri)) { + return $uriFactory->createUri($uri); + } + + throw new InvalidArgumentException(\sprintf('URI must be a string or %s', UriInterface::class)); + } + + /** + * @param mixed $body + */ + private static function createBodyStream($body, StreamFactoryInterface $streamFactory): StreamInterface + { + if ($body instanceof StreamInterface) { + return $body; + } + + if (\is_resource($body)) { + return $streamFactory->createStreamFromResource($body); + } + + if ($body === null) { + return $streamFactory->createStream(); + } + + if (\is_string($body)) { + return $streamFactory->createStream($body); + } + + if ($body instanceof \Iterator) { + return Psr7\Utils::streamFor($body); + } + + if (\is_object($body) && \method_exists($body, '__toString')) { + return $streamFactory->createStream((string) $body); + } + + if (\is_callable($body)) { + return Psr7\Utils::streamFor($body); + } + + throw new InvalidArgumentException(\sprintf( + 'Passing %s to request option "body" is invalid; expected resource|string|null|StreamInterface|callable&object|Iterator|Stringable.', + \get_debug_type($body) + )); + } + + /** + * Configures the default options for a client. + */ + private function configureDefaults( + #[\SensitiveParameter] + array $config + ): void { + $defaults = [ + 'allow_redirects' => RedirectMiddleware::DEFAULT_SETTINGS, + 'http_errors' => true, + 'decode_content' => true, + 'verify' => true, + 'cookies' => false, + 'idn_conversion' => false, + 'protocols' => ['http', 'https'], + ]; + + // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. + + // We can only trust the HTTP_PROXY environment variable in a CLI + // process due to the fact that PHP has no reliable mechanism to + // get environment variables that start with "HTTP_". + if (\PHP_SAPI === 'cli' && ($proxy = Env::get('HTTP_PROXY'))) { + $defaults['proxy']['http'] = $proxy; + } + + if ($proxy = Env::get('HTTPS_PROXY')) { + $defaults['proxy']['https'] = $proxy; + } + + $noProxy = Env::get('NO_PROXY'); + if ($noProxy !== null) { + $noProxy = ProxyOptions::normalizeNoProxy($noProxy); + if ($noProxy !== []) { + $defaults['proxy']['no'] = $noProxy; + } + } + + $this->config = $config + $defaults; + + if (!empty($config['cookies']) && $config['cookies'] === true) { + $this->config['cookies'] = new CookieJar(); + } + + // Add the default user-agent header. + if (!isset($this->config['headers'])) { + $this->config['headers'] = ['User-Agent' => self::defaultUserAgent()]; + } else { + self::assertHeaderOptionTypes($this->config['headers']); + + // Add the User-Agent header if one was not already set. + $hasUserAgent = false; + foreach (\array_keys($this->config['headers']) as $name) { + if (Psr7\Utils::asciiToLower((string) $name) === 'user-agent') { + $hasUserAgent = true; + break; + } + } + + if (!$hasUserAgent) { + $this->config['headers']['User-Agent'] = self::defaultUserAgent(); + } + } + } + + /** + * Merges default options into the array. + * + * @param array $options Options to modify by reference + */ + private function prepareDefaults( + #[\SensitiveParameter] + array $options + ): array { + if (isset($options['handler'])) { + throw new InvalidArgumentException('The "handler" request option is not supported; configure the handler when creating the client, or use a separate client instance for requests that need a different handler.'); + } + + $defaults = $this->config; + + if (!empty($defaults['headers'])) { + // Default headers are only added if they are not present. + $defaults['_conditional'] = $defaults['headers']; + unset($defaults['headers']); + } + + // Special handling for headers is required as they are added as + // conditional headers and as headers passed to a request ctor. + if (\array_key_exists('headers', $options)) { + // Allows default headers to be unset. + if ($options['headers'] === null) { + $defaults['_conditional'] = []; + unset($options['headers']); + } elseif (!\is_array($options['headers'])) { + throw new InvalidArgumentException('headers must be an array'); + } + } + + // Shallow merge defaults underneath options. + $result = $options + $defaults; + + // Remove null values. + foreach ($result as $k => $v) { + if ($v === null) { + unset($result[$k]); + } + } + + self::assertRequestOptionTypes($result); + + return $result; + } + + private static function assertRequestOptionTypes( + #[\SensitiveParameter] + array $options + ): void { + if (isset($options['allow_redirects'])) { + if (!\is_bool($options['allow_redirects']) && !\is_array($options['allow_redirects'])) { + self::invalidRequestOptionType('allow_redirects', 'bool|array', $options['allow_redirects']); + } + + if (\is_array($options['allow_redirects'])) { + self::assertAllowRedirectsOptionTypes($options['allow_redirects']); + } + } + + if ( + isset($options['auth']) + && $options['auth'] !== false + && !\is_string($options['auth']) + && !\is_array($options['auth']) + ) { + self::invalidRequestOptionType('auth', 'array{0: string, 1: string, 2?: string|null}|string|false|null', $options['auth']); + } + + if (isset($options['auth']) && \is_array($options['auth']) && $options['auth'] !== []) { + self::assertAuthOptionTypes($options['auth']); + } + + self::assertTlsFileOptionTypes($options, 'cert'); + self::assertIfPresentAndNotString($options, 'cert_type'); + self::assertIfPresentAndNotNumber($options, 'connect_timeout'); + self::assertIfPresentAndNotInt($options, 'crypto_method'); + self::assertIfPresentAndNotInt($options, 'crypto_method_max'); + self::assertIfPresentAndNotBoolOrResource($options, 'debug'); + self::assertIfPresentAndNotBoolOrString($options, 'decode_content'); + self::assertIfPresentAndNotFiniteNonNegativeNumber($options, 'delay'); + self::assertIfPresentAndNotBoolOrInt($options, 'expect'); + + if (isset($options['form_params'])) { + self::assertFormParamTypes($options['form_params']); + } + + self::assertIfPresentAndNotForceIpResolve($options); + + if (isset($options['headers'])) { + self::assertHeaderOptionTypes($options['headers']); + } + + self::assertIfPresentAndNotBool($options, 'http_errors'); + + if (isset($options['multipart'])) { + self::assertMultipartOptionTypes($options['multipart']); + } + + self::assertValidMultiplex($options); + self::assertIfPresentAndNotCallable($options, 'on_headers'); + self::assertIfPresentAndNotCallable($options, 'on_stats'); + self::assertIfPresentAndNotCallable($options, 'on_trailers'); + self::assertIfPresentAndNotCallable($options, 'progress'); + self::assertIfPresentAndNotProtocolArray($options, 'protocols'); + self::assertProxyOptionTypes($options); + self::assertIfPresentAndNotNumber($options, 'read_timeout'); + self::assertIfPresentAndNotInt($options, 'retries'); + + if (isset($options['sink']) && !\is_resource($options['sink']) && !\is_string($options['sink']) && !$options['sink'] instanceof StreamInterface) { + self::invalidRequestOptionType('sink', 'resource|string|StreamInterface', $options['sink']); + } + + self::assertTlsFileOptionTypes($options, 'ssl_key'); + self::assertIfPresentAndNotString($options, 'ssl_key_type'); + self::assertIfPresentAndNotBool($options, 'stream'); + self::assertIfPresentAndNotArray($options, 'stream_context', 'array'); + self::assertIfPresentAndNotBool($options, 'synchronous'); + self::assertIfPresentAndNotNumber($options, 'timeout'); + self::assertIfPresentAndNotBoolOrString($options, 'verify'); + self::assertIfPresentAndNotStringOrNumber($options, 'version'); + self::assertIfPresentAndNotArray($options, 'curl', 'array'); + + if (isset($options['cookies']) && $options['cookies'] !== false && !$options['cookies'] instanceof CookieJarInterface) { + self::invalidRequestOptionType('cookies', 'false|CookieJarInterface', $options['cookies']); + } + } + + private static function assertAllowRedirectsOptionTypes(array $allowRedirects): void + { + self::assertIfPresentAndNotInt($allowRedirects, 'max', 'allow_redirects.max'); + self::assertIfPresentAndNotBool($allowRedirects, 'strict', 'allow_redirects.strict'); + self::assertIfPresentAndNotBool($allowRedirects, 'referer', 'allow_redirects.referer'); + self::assertIfPresentAndNotProtocolArray($allowRedirects, 'protocols', 'allow_redirects.protocols'); + self::assertIfPresentAndNotCallable($allowRedirects, 'on_redirect', 'allow_redirects.on_redirect'); + self::assertIfPresentAndNotBool($allowRedirects, 'track_redirects', 'allow_redirects.track_redirects'); + } + + /** + * @param array $auth + */ + private static function assertAuthOptionTypes( + #[\SensitiveParameter] + array $auth + ): void { + if (!\array_key_exists(0, $auth) || !\is_string($auth[0])) { + self::invalidRequestOptionType('auth.0', 'string', $auth[0] ?? null); + } + + if (!\array_key_exists(1, $auth) || !\is_string($auth[1])) { + self::invalidRequestOptionType('auth.1', 'string', $auth[1] ?? null); + } + + if (\array_key_exists(2, $auth) && $auth[2] !== null && !\is_string($auth[2])) { + self::invalidRequestOptionType('auth.2', 'string|null', $auth[2]); + } + } + + /** + * @param mixed $value + */ + private static function assertFormParamTypes($value): void + { + if (!\is_array($value)) { + self::invalidRequestOptionType('form_params', 'array', $value); + + return; + } + + self::assertFormParamArray($value, 'form_params'); + self::assertFiniteFloats($value, 'form_params'); + } + + private static function assertFormParamArray(array $values, string $path): bool + { + foreach ($values as $key => $item) { + $itemPath = $path.'.'.(string) $key; + if (\is_array($item)) { + if (!self::assertFormParamArray($item, $itemPath)) { + return false; + } + + continue; + } + + if ($item !== null && !\is_scalar($item)) { + self::invalidRequestOptionType($itemPath, 'string|int|float|bool|null|array', $item); + + return false; + } + } + + return true; + } + + private static function assertFiniteFloats(array $values, string $option): void + { + foreach ($values as $key => $value) { + if (\is_array($value)) { + self::assertFiniteFloats($value, $option.'.'.(string) $key); + } elseif (\is_float($value) && !\is_finite($value)) { + throw new InvalidArgumentException(\sprintf( + 'Passing a non-finite float to request option "%s" is invalid; non-finite floats are not supported.', + DiagnosticValue::escape($option.'.'.(string) $key) + )); + } + } + } + + /** + * @param mixed $headers + */ + private static function assertHeaderOptionTypes( + #[\SensitiveParameter] + $headers + ): void { + if (!\is_array($headers)) { + self::invalidRequestOptionType('headers', 'array>|null', $headers); + + return; + } + + foreach ($headers as $name => $value) { + $path = 'headers.'.(string) $name; + if (\is_array($value)) { + if ($value === []) { + self::invalidRequestOptionType($path, 'string|non-empty-array', $value); + } + + foreach ($value as $index => $item) { + if (!\is_string($item)) { + self::invalidRequestOptionType($path.'.'.(string) $index, 'string', $item); + } + } + } elseif (!\is_string($value)) { + self::invalidRequestOptionType($path, 'string|non-empty-array', $value); + } + } + } + + /** + * @param mixed $multipart + */ + private static function assertMultipartOptionTypes($multipart): void + { + if (!\is_array($multipart)) { + self::invalidRequestOptionType('multipart', 'array, filename?: string}>', $multipart); + + return; + } + + foreach ($multipart as $index => $part) { + $path = 'multipart.'.(string) $index; + if (!\is_array($part)) { + self::invalidRequestOptionType($path, 'array{name: string|int, contents: mixed, headers?: array, filename?: string}', $part); + + return; + } + + if (!\array_key_exists('name', $part) || (!\is_string($part['name']) && !\is_int($part['name']))) { + self::invalidRequestOptionType($path.'.name', 'string|int', $part['name'] ?? null); + } + + if (!\array_key_exists('contents', $part)) { + self::invalidRequestOptionType($path, 'array{name: string|int, contents: mixed, headers?: array, filename?: string}', $part); + } + + if (\array_key_exists('headers', $part)) { + if (!\is_array($part['headers'])) { + self::invalidRequestOptionType($path.'.headers', 'array', $part['headers']); + + return; + } + + foreach ($part['headers'] as $name => $value) { + if (!\is_string($value)) { + self::invalidRequestOptionType($path.'.headers.'.(string) $name, 'string', $value); + } + } + } + + if (\array_key_exists('filename', $part) && !\is_string($part['filename'])) { + self::invalidRequestOptionType($path.'.filename', 'string', $part['filename']); + } + } + } + + private static function assertProxyOptionTypes( + #[\SensitiveParameter] + array $options + ): void { + if (!isset($options['proxy'])) { + return; + } + + if (!\is_string($options['proxy']) && !\is_array($options['proxy'])) { + self::invalidRequestOptionType('proxy', 'string|array{http?: string|null, https?: string|null, no?: string|array|null}', $options['proxy']); + + return; + } + + if (!\is_array($options['proxy'])) { + return; + } + + foreach (['http', 'https'] as $scheme) { + if (\array_key_exists($scheme, $options['proxy']) && $options['proxy'][$scheme] !== null && !\is_string($options['proxy'][$scheme])) { + self::invalidRequestOptionType('proxy.'.$scheme, 'string|null', $options['proxy'][$scheme]); + } + } + + if (!\array_key_exists('no', $options['proxy']) || $options['proxy']['no'] === null) { + return; + } + + if (\is_string($options['proxy']['no'])) { + return; + } + + if (!\is_array($options['proxy']['no'])) { + self::invalidRequestOptionType('proxy.no', 'string|array|null', $options['proxy']['no']); + + return; + } + + foreach ($options['proxy']['no'] as $index => $noProxy) { + if (!\is_string($noProxy)) { + self::invalidRequestOptionType('proxy.no.'.(string) $index, 'string', $noProxy); + } + } + } + + private static function assertTlsFileOptionTypes( + #[\SensitiveParameter] + array $options, + string $option + ): void { + if (!isset($options[$option])) { + return; + } + + if (\is_string($options[$option])) { + return; + } + + if (!\is_array($options[$option])) { + self::invalidRequestOptionType($option, 'string|array{0: string, 1?: string}', $options[$option]); + + return; + } + + if (!\array_key_exists(0, $options[$option]) || !\is_string($options[$option][0])) { + self::invalidRequestOptionType($option.'.0', 'string', $options[$option][0] ?? null); + } + + if (\array_key_exists(1, $options[$option]) && $options[$option][1] !== null && !\is_string($options[$option][1])) { + self::invalidRequestOptionType($option.'.1', 'string|null', $options[$option][1]); + } + } + + private static function assertIfPresentAndNotArray( + #[\SensitiveParameter] + array $options, + string $option, + string $expected + ): void { + if (\array_key_exists($option, $options) && !\is_array($options[$option])) { + self::invalidRequestOptionType($option, $expected, $options[$option]); + } + } + + private static function assertIfPresentAndNotBool( + #[\SensitiveParameter] + array $options, + string $option, + ?string $path = null + ): void { + if (\array_key_exists($option, $options) && !\is_bool($options[$option])) { + self::invalidRequestOptionType($path ?? $option, 'bool', $options[$option]); + } + } + + private static function assertValidMultiplex( + #[\SensitiveParameter] + array $options + ): void { + if (!\array_key_exists('multiplex', $options) || $options['multiplex'] === null) { + return; + } + + if (!\in_array($options['multiplex'], [Multiplexing::NONE, Multiplexing::EAGER, Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new InvalidArgumentException(\sprintf( + 'The "multiplex" option must be null or a GuzzleHttp\\Multiplexing::* constant; received %s.', + \get_debug_type($options['multiplex']) + )); + } + } + + private static function assertIfPresentAndNotBoolOrInt( + #[\SensitiveParameter] + array $options, + string $option + ): void { + if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_int($options[$option])) { + self::invalidRequestOptionType($option, 'bool|int', $options[$option]); + } + } + + private static function assertIfPresentAndNotBoolOrResource( + #[\SensitiveParameter] + array $options, + string $option + ): void { + if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_resource($options[$option])) { + self::invalidRequestOptionType($option, 'bool|resource', $options[$option]); + } + } + + private static function assertIfPresentAndNotBoolOrString( + #[\SensitiveParameter] + array $options, + string $option + ): void { + if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_string($options[$option])) { + self::invalidRequestOptionType($option, 'bool|string', $options[$option]); + } + } + + private static function assertIfPresentAndNotCallable( + #[\SensitiveParameter] + array $options, + string $option, + ?string $path = null + ): void { + if (\array_key_exists($option, $options) && !\is_callable($options[$option])) { + self::invalidRequestOptionType($path ?? $option, 'callable', $options[$option]); + } + } + + private static function assertIfPresentAndNotInt( + #[\SensitiveParameter] + array $options, + string $option, + ?string $path = null + ): void { + if (\array_key_exists($option, $options) && !\is_int($options[$option])) { + self::invalidRequestOptionType($path ?? $option, 'int', $options[$option]); + } + } + + private static function assertIfPresentAndNotNumber( + #[\SensitiveParameter] + array $options, + string $option + ): void { + if (\array_key_exists($option, $options) && !\is_int($options[$option]) && !\is_float($options[$option])) { + self::invalidRequestOptionType($option, 'int|float', $options[$option]); + } + } + + /** + * @param array $options + */ + private static function assertIfPresentAndNotFiniteNonNegativeNumber( + #[\SensitiveParameter] + array $options, + string $option + ): void { + if (!\array_key_exists($option, $options)) { + return; + } + + if (!\is_int($options[$option]) && !\is_float($options[$option])) { + self::invalidRequestOptionType($option, 'finite int|float greater than or equal to 0', $options[$option]); + + return; + } + + if (!\is_finite((float) $options[$option]) || $options[$option] < 0) { + self::invalidRequestOptionType($option, 'finite int|float greater than or equal to 0', $options[$option]); + } + } + + /** + * @param array $options + */ + private static function assertIfPresentAndNotForceIpResolve( + #[\SensitiveParameter] + array $options + ): void { + if (!\array_key_exists('force_ip_resolve', $options)) { + return; + } + + if ( + !\is_string($options['force_ip_resolve']) + || ($options['force_ip_resolve'] !== 'v4' && $options['force_ip_resolve'] !== 'v6') + ) { + self::invalidRequestOptionType('force_ip_resolve', '"v4"|"v6"', $options['force_ip_resolve']); + } + } + + private static function assertIfPresentAndNotString( + #[\SensitiveParameter] + array $options, + string $option + ): void { + if (\array_key_exists($option, $options) && !\is_string($options[$option])) { + self::invalidRequestOptionType($option, 'string', $options[$option]); + } + } + + /** + * @param array $options + */ + private static function assertIfPresentAndNotProtocolArray( + #[\SensitiveParameter] + array $options, + string $option, + ?string $path = null + ): void { + if (!\array_key_exists($option, $options)) { + return; + } + + $path = $path ?? $option; + + if (!\is_array($options[$option]) || $options[$option] === []) { + self::invalidRequestOptionType($path, 'non-empty-array', $options[$option]); + + return; + } + + foreach ($options[$option] as $index => $protocol) { + if (!\is_string($protocol)) { + self::invalidRequestOptionType($path.'.'.(string) $index, 'string', $protocol); + + continue; + } + + if ($protocol !== 'http' && $protocol !== 'https') { + self::invalidRequestOptionType($path.'.'.(string) $index, '"http"|"https"', $protocol); + } + } + } + + private static function assertIfPresentAndNotStringOrNumber( + #[\SensitiveParameter] + array $options, + string $option + ): void { + if ( + \array_key_exists($option, $options) + && !\is_string($options[$option]) + && !\is_int($options[$option]) + && !\is_float($options[$option]) + ) { + self::invalidRequestOptionType($option, 'string|int|float', $options[$option]); + } + } + + /** + * @param mixed $value + */ + private static function invalidRequestOptionType( + string $option, + string $expected, + #[\SensitiveParameter] + $value + ): void { + throw new InvalidArgumentException(\sprintf( + 'Passing %s to request option "%s" is invalid; expected %s.', + \get_debug_type($value), + DiagnosticValue::escape($option), + $expected + )); + } + + /** + * Transfers the given request and applies request options. + * + * The URI of the request is not modified and the request options are used + * as-is without merging in default options. + * + * @param array $options See {@see RequestOptions}. + * + * @return PromiseInterface + */ + private function transfer( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + $request = $this->applyOptions($request, $options); + + /** @var callable(RequestInterface, array): PromiseInterface $handler */ + $handler = $this->config['handler']; + + try { + self::assertRequestProtocolVersion($request); + + /** @var PromiseInterface */ + return P\Create::promiseFor($handler($request, $options)); + } catch (\Throwable $e) { + /** @var PromiseInterface */ + return P\Create::rejectionFor($e); + } + } + + /** + * Applies the array of request options to a request. + */ + private function applyOptions( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array &$options + ): RequestInterface { + $modify = [ + 'set_headers' => [], + ]; + + // Validate the response and stream factories up front. Every request + // yields a response, and the built-in handlers build the response body + // stream via the stream factory even when the request has no body, so + // both must be validated unconditionally. + self::requireResponseFactory($options[RequestOptions::RESPONSE_FACTORY] ?? new HttpFactory()); + $streamFactory = self::requireStreamFactory($options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()); + + if (isset($options['headers'])) { + if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) { + throw new InvalidArgumentException('The headers array must have header name as keys.'); + } + $modify['set_headers'] = $options['headers']; + unset($options['headers']); + } + + if (isset($options['form_params'])) { + if (isset($options['multipart'])) { + throw new InvalidArgumentException('You cannot use ' + .'form_params and multipart at the same time. Use the ' + .'form_params option if you want to send application/' + .'x-www-form-urlencoded requests, and the multipart ' + .'option to send multipart/form-data requests.'); + } + $options['body'] = \http_build_query($options['form_params'], '', '&'); + unset($options['form_params']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + if (isset($options['multipart'])) { + $options['body'] = new Psr7\MultipartStream($options['multipart']); + unset($options['multipart']); + } + + if (isset($options['json'])) { + try { + $options['body'] = \json_encode($options['json'], \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new InvalidArgumentException('json_encode error: '.$e->getMessage(), 0, $e); + } + + unset($options['json']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/json'; + } + + if (isset($options['decode_content']) && \is_string($options['decode_content'])) { + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']); + $modify['set_headers']['Accept-Encoding'] = (string) $options['decode_content']; + } + + if (isset($options['body'])) { + if (\is_array($options['body'])) { + throw $this->invalidBody(); + } + $modify['body'] = self::createBodyStream($options['body'], $streamFactory); + unset($options['body']); + } + + if (isset($options['query'])) { + $value = $options['query']; + if (\is_array($value)) { + self::assertFiniteFloats($value, 'query'); + $value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986); + } + if (!\is_string($value)) { + throw new InvalidArgumentException('query must be a string or array'); + } + $modify['query'] = $value; + unset($options['query']); + } + + if (isset($options['version'])) { + $modify['version'] = self::normalizeProtocolVersion($options['version']); + } + + $request = Psr7\Utils::modifyRequest($request, $modify); + if ($request->getBody() instanceof Psr7\MultipartStream) { + // Use a multipart/form-data POST if a Content-Type is not set. + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = self::getMultipartContentType($request->getBody()); + } + + // Merge in conditional headers if they are not present. + if (isset($options['_conditional'])) { + // Build up the changes so it's in a single clone of the message. + $modify = []; + foreach ($options['_conditional'] as $k => $v) { + $name = (string) $k; + if (!$request->hasHeader($name)) { + $modify['set_headers'][$name] = $v; + } + } + $request = Psr7\Utils::modifyRequest($request, $modify); + // Don't pass this internal value along to middleware/handlers. + unset($options['_conditional']); + } + + return $request; + } + + /** + * @param string|int|float $version + */ + private static function normalizeProtocolVersion($version): string + { + $version = \is_float($version) ? \number_format($version, 1, '.', '') : (string) $version; + + self::assertProtocolVersion($version); + + return $version; + } + + private static function assertProtocolVersion(string $version): void + { + if ('' === $version) { + throw new InvalidArgumentException('HTTP protocol version must not be empty.'); + } + + if (1 !== \preg_match('/^\d+(?:\.\d+)?$/D', $version)) { + throw new InvalidArgumentException('HTTP protocol version must be a valid HTTP version number.'); + } + } + + private static function assertRequestProtocolVersion( + #[\SensitiveParameter] + RequestInterface $request + ): void { + $version = $request->getProtocolVersion(); + + if ('' === $version) { + throw new RequestException('HTTP protocol version must not be empty.', $request); + } + + if (1 !== \preg_match('/^\d+(?:\.\d+)?$/D', $version)) { + throw new RequestException('HTTP protocol version must be a valid HTTP version number.', $request); + } + } + + private static function getMultipartContentType(Psr7\MultipartStream $body): string + { + $boundary = $body->getBoundary(); + + if (false !== \strpbrk($boundary, '()<>@,;:\"/[]?= ')) { + $boundary = '"'.$boundary.'"'; + } + + return 'multipart/form-data; boundary='.$boundary; + } + + /** + * Return an InvalidArgumentException with pre-set message. + */ + private function invalidBody(): InvalidArgumentException + { + return new InvalidArgumentException('Passing in the "body" request ' + .'option as an array to send a request is not supported. ' + .'Please use the "form_params" request option to send a ' + .'application/x-www-form-urlencoded request, or the "multipart" ' + .'request option to send a multipart/form-data request.'); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/ClientInterface.php b/vendor/guzzlehttp/guzzle/src/ClientInterface.php new file mode 100644 index 0000000..187459b --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/ClientInterface.php @@ -0,0 +1,370 @@ +, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply to the given request and to the transfer. + * + * @throws GuzzleException + */ + public function send(RequestInterface $request, array $options = []): ResponseInterface; + + /** + * Asynchronously send an HTTP request. + * + * @param RequestInterface $request Request to send + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply to the given request and to the transfer. + * + * @return PromiseInterface + */ + public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface; + + /** + * Create and send an HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method. + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @throws GuzzleException + */ + public function request(string $method, $uri, array $options = []): ResponseInterface; + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @return PromiseInterface + */ + public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; +} diff --git a/vendor/guzzlehttp/guzzle/src/ClientTrait.php b/vendor/guzzlehttp/guzzle/src/ClientTrait.php new file mode 100644 index 0000000..8eed76a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/ClientTrait.php @@ -0,0 +1,1315 @@ +, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @throws GuzzleException + */ + abstract public function request(string $method, $uri, array $options = []): ResponseInterface; + + /** + * Create and send an HTTP GET request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @throws GuzzleException + */ + public function get( + $uri, + #[\SensitiveParameter] + array $options = [] + ): ResponseInterface { + return $this->request('GET', $uri, $options); + } + + /** + * Create and send an HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @throws GuzzleException + */ + public function head( + $uri, + #[\SensitiveParameter] + array $options = [] + ): ResponseInterface { + return $this->request('HEAD', $uri, $options); + } + + /** + * Create and send an HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @throws GuzzleException + */ + public function put( + $uri, + #[\SensitiveParameter] + array $options = [] + ): ResponseInterface { + return $this->request('PUT', $uri, $options); + } + + /** + * Create and send an HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @throws GuzzleException + */ + public function post( + $uri, + #[\SensitiveParameter] + array $options = [] + ): ResponseInterface { + return $this->request('POST', $uri, $options); + } + + /** + * Create and send an HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @throws GuzzleException + */ + public function patch( + $uri, + #[\SensitiveParameter] + array $options = [] + ): ResponseInterface { + return $this->request('PATCH', $uri, $options); + } + + /** + * Create and send an HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @throws GuzzleException + */ + public function delete( + $uri, + #[\SensitiveParameter] + array $options = [] + ): ResponseInterface { + return $this->request('DELETE', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @return PromiseInterface + */ + abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; + + /** + * Create and send an asynchronous HTTP GET request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @return PromiseInterface + */ + public function getAsync( + $uri, + #[\SensitiveParameter] + array $options = [] + ): PromiseInterface { + return $this->requestAsync('GET', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @return PromiseInterface + */ + public function headAsync( + $uri, + #[\SensitiveParameter] + array $options = [] + ): PromiseInterface { + return $this->requestAsync('HEAD', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @return PromiseInterface + */ + public function putAsync( + $uri, + #[\SensitiveParameter] + array $options = [] + ): PromiseInterface { + return $this->requestAsync('PUT', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @return PromiseInterface + */ + public function postAsync( + $uri, + #[\SensitiveParameter] + array $options = [] + ): PromiseInterface { + return $this->requestAsync('POST', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @return PromiseInterface + */ + public function patchAsync( + $uri, + #[\SensitiveParameter] + array $options = [] + ): PromiseInterface { + return $this->requestAsync('PATCH', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options Request options to apply. + * + * @return PromiseInterface + */ + public function deleteAsync( + $uri, + #[\SensitiveParameter] + array $options = [] + ): PromiseInterface { + return $this->requestAsync('DELETE', $uri, $options); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php new file mode 100644 index 0000000..f1aeedc --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php @@ -0,0 +1,452 @@ +strictMode = $strictMode; + + foreach ($cookieArray as $cookie) { + if (!$cookie instanceof SetCookie) { + $cookie = new SetCookie($cookie); + } + $this->setCookie($cookie); + } + } + + /** + * Create a new Cookie jar from an associative array and domain. + * + * @param array $cookies Cookies to create the jar from + * @param string $domain Domain to set the cookies to + */ + public static function fromArray( + #[\SensitiveParameter] + array $cookies, + string $domain + ): self { + $cookieJar = new self(); + foreach ($cookies as $name => $value) { + if (!\is_scalar($value) && !(\is_object($value) && \method_exists($value, '__toString'))) { + throw new \InvalidArgumentException('Cookie value must be scalar or stringable'); + } + + $cookieJar->setCookie(new SetCookie([ + 'Domain' => $domain, + 'Name' => (string) $name, + 'Value' => (string) $value, + 'Discard' => true, + ])); + } + + return $cookieJar; + } + + /** + * Evaluate if this cookie should be persisted to storage + * that survives between requests. + * + * @param SetCookie $cookie Being evaluated. + * @param bool $allowSessionCookies If we should persist session cookies + */ + public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool + { + if ($cookie->getExpires() || $allowSessionCookies) { + if (!$cookie->getDiscard()) { + return true; + } + } + + return false; + } + + /** + * Finds and returns the cookie based on the name + * + * @param string $name cookie name to search for + * + * @return SetCookie|null cookie that was found or null if not found + */ + public function getCookieByName(string $name): ?SetCookie + { + foreach ($this->cookies as $cookie) { + if ($cookie->getName() === $name) { + return $cookie; + } + } + + return null; + } + + public function toArray(): array + { + return \array_map(static function (SetCookie $cookie): array { + return $cookie->toArray(); + }, $this->getIterator()->getArrayCopy()); + } + + public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void + { + if ($domain === null) { + $this->cookies = []; + + return; + } elseif ($path === null) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($domain): bool { + return $cookie->getDomain() === null || !$cookie->matchesDomain($domain); + } + ); + } elseif ($name === null) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain): bool { + return !($cookie->getDomain() !== null + && $cookie->matchesPath($path) + && $cookie->matchesDomain($domain)); + } + ); + } else { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain, $name): bool { + return !($cookie->getDomain() !== null + && $cookie->getName() === $name + && $cookie->matchesPath($path) + && $cookie->matchesDomain($domain)); + } + ); + } + } + + public function clearSessionCookies(): void + { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie): bool { + return !$cookie->getDiscard() && $cookie->getExpires(); + } + ); + } + + public function setCookie( + #[\SensitiveParameter] + SetCookie $cookie + ): bool { + // If the name string is empty (but not 0), ignore the set-cookie + // string entirely. + $name = $cookie->getName(); + if (!$name && $name !== '0') { + return false; + } + + // Only allow cookies with set and valid domain, name, value + $result = $cookie->validate(); + if ($result !== true) { + if ($this->strictMode) { + throw new \RuntimeException('Invalid cookie: '.$result); + } + $this->removeCookieIfEmpty($cookie); + + return false; + } + + $maxAge = $cookie->getMaxAge(); + if (($maxAge !== null && $maxAge <= 0) || $cookie->isExpired()) { + if ($cookie->getDomain() !== null) { + $this->removeCookie($cookie); + } + + return false; + } + + // Resolve conflicts with previously set cookies + $replaced = false; + foreach ($this->cookies as $i => $c) { + // Two cookies are identical, when their path, and domain are + // identical. + if ($c->getPath() !== $cookie->getPath() + || $c->getDomain() !== $cookie->getDomain() + || $c->getHostOnly() !== $cookie->getHostOnly() + || $c->getName() !== $cookie->getName() + ) { + continue; + } + + // An expired cookie is gone, so it must not lend its position + if ($c->isExpired()) { + unset($this->cookies[$i]); + continue; + } + + // A stored cookie can be mutated into a duplicate, so drop later matches + if ($replaced) { + unset($this->cookies[$i]); + continue; + } + + // Replace the old cookie in place when its value, expiry or flags + // changed, so it keeps its position among the other cookies + if ($cookie->getValue() !== $c->getValue() + || $cookie->getExpires() !== $c->getExpires() + || $cookie->getDiscard() !== $c->getDiscard() + || $cookie->getSecure() !== $c->getSecure() + || $cookie->getHttpOnly() !== $c->getHttpOnly() + ) { + $this->cookies[$i] = $cookie; + $replaced = true; + continue; + } + + // The cookie exists, so no need to continue + return false; + } + + if (!$replaced) { + $this->cookies[] = $cookie; + } + + return true; + } + + public function count(): int + { + return \count($this->cookies); + } + + /** + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator(\array_values($this->cookies)); + } + + public function extractCookies( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + ResponseInterface $response + ): void { + if ($cookieHeader = $response->getHeader('Set-Cookie')) { + $uri = $request->getUri(); + $requestHost = HostIdentity::canonicalHost($uri->getHost()); + $secure = $uri->getScheme() === 'https'; + $accepted = 0; + + foreach ($cookieHeader as $cookie) { + if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) { + continue; + } + + $sc = SetCookie::fromString($cookie); + $domain = $sc->getDomain(); + if ($domain === null || $domain === '') { + $sc->setDomain($requestHost); + $sc->setHostOnly(true); + } else { + $sc->setHostOnly(false); + } + if (0 !== \strpos($sc->getPath(), '/')) { + $sc->setPath($this->getCookiePathFromRequest($request)); + } + if (!$sc->matchesDomain($requestHost)) { + continue; + } + if (!$secure && ($sc->getSecure() || $this->overlaysSecureCookie($sc))) { + continue; + } + $prefixName = Psr7\Utils::asciiToLower((string) $sc->getName()); + if (\str_starts_with($prefixName, '__secure-') && !$sc->getSecure()) { + continue; + } + if (\str_starts_with($prefixName, '__host-') && (!$sc->getSecure() || !$sc->getHostOnly() || $sc->getPath() !== '/' || !self::hasPathAttribute($cookie))) { + continue; + } + // Note: At this point `$sc->getDomain()` being a public suffix should + // be rejected, but we don't want to pull in the full PSL dependency. + if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) { + break; + } + } + } + } + + private function overlaysSecureCookie(SetCookie $cookie): bool + { + foreach ($this->cookies as $stored) { + if (self::isSecureCookieOverlay($cookie, $stored)) { + return true; + } + } + + return false; + } + + private static function isSecureCookieOverlay(SetCookie $cookie, SetCookie $stored): bool + { + if ($stored->getName() !== $cookie->getName() || !$stored->getSecure() || $stored->isExpired()) { + return false; + } + + $domain = $cookie->getDomain(); + $storedDomain = $stored->getDomain(); + if ($domain === null || $storedDomain === null) { + return false; + } + + if (!HostIdentity::cookieDomainMatches($storedDomain, $domain) && !HostIdentity::cookieDomainMatches($domain, $storedDomain)) { + return false; + } + + return $stored->matchesPath($cookie->getPath()); + } + + /** + * Mirrors SetCookie::fromString()'s splitting because parsed cookies cannot + * distinguish an absent Path attribute from a defaulted path. + */ + private static function hasPathAttribute(string $header): bool + { + $parts = \explode(';', $header); + \array_shift($parts); + + foreach ($parts as $part) { + $separator = \strpos($part, '='); + if ($separator !== false && Psr7\Utils::caselessEquals(\trim(\substr($part, 0, $separator), " \t"), 'Path')) { + return true; + } + } + + return false; + } + + /** + * Computes cookie path following RFC 6265 section 5.1.4 + * + * @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4 + */ + private function getCookiePathFromRequest(RequestInterface $request): string + { + $uriPath = $request->getUri()->getPath(); + if ('' === $uriPath) { + return '/'; + } + if (0 !== \strpos($uriPath, '/')) { + return '/'; + } + if ('/' === $uriPath) { + return '/'; + } + $lastSlashPos = \strrpos($uriPath, '/'); + if (0 === $lastSlashPos || false === $lastSlashPos) { + return '/'; + } + + return \substr($uriPath, 0, $lastSlashPos); + } + + public function withCookieHeader( + #[\SensitiveParameter] + RequestInterface $request + ): RequestInterface { + $values = []; + $count = 0; + $headerLength = 8; + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + $host = HostIdentity::canonicalHost($uri->getHost()); + $path = $uri->getPath() ?: '/'; + + foreach ($this->cookies as $cookie) { + if ($cookie->getDomain() !== null + && $cookie->matchesPath($path) + && $cookie->matchesDomain($host) + && !$cookie->isExpired() + && (!$cookie->getSecure() || $scheme === 'https') + ) { + $name = (string) $cookie->getName(); + $value = (string) $cookie->getValue(); + $separatorLength = $values === [] ? 0 : 2; + $valueLength = \strlen($name) + 1 + \strlen($value); + if ($headerLength + $separatorLength + $valueLength > self::MAX_COOKIE_HEADER_LENGTH) { + break; + } + + $values[\strlen($cookie->getPath())][] = $name.'='.$value; + $headerLength += $separatorLength + $valueLength; + if (++$count === self::MAX_REQUEST_COOKIES) { + break; + } + } + } + + // Longer paths first, then creation order, as in RFC 6265 section 5.4, + // sorted after the limits so later cookies cannot crowd out older ones + \krsort($values); + + return $values + ? $request->withHeader('Cookie', \implode('; ', \array_merge(...$values))) + : $request; + } + + /** + * If a cookie already exists and the server asks to set it again with a + * null value, the cookie must be deleted. + */ + private function removeCookieIfEmpty(SetCookie $cookie): void + { + $cookieValue = $cookie->getValue(); + if (($cookieValue === null || $cookieValue === '') && $cookie->getDomain() !== null) { + $this->removeCookie($cookie); + } + } + + private function removeCookie(SetCookie $cookie): void + { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $stored) use ($cookie): bool { + return !($stored->getName() === $cookie->getName() + && $stored->getPath() === $cookie->getPath() + && $stored->getDomain() === $cookie->getDomain() + && $stored->getHostOnly() === $cookie->getHostOnly()); + } + ); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php new file mode 100644 index 0000000..b2efa3c --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php @@ -0,0 +1,82 @@ + + */ +interface CookieJarInterface extends \Countable, \IteratorAggregate +{ + /** + * Create a request with added cookie headers. + * + * If no matching cookies are found in the cookie jar, then no Cookie + * header is added to the request and the same request is returned. + * + * @param RequestInterface $request Request object to modify. + * + * @return RequestInterface returns the modified request. + */ + public function withCookieHeader(RequestInterface $request): RequestInterface; + + /** + * Extract cookies from an HTTP response and store them in the CookieJar. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface $response Response that was received + */ + public function extractCookies(RequestInterface $request, ResponseInterface $response): void; + + /** + * Sets a cookie in the cookie jar. + * + * @param SetCookie $cookie Cookie to set. + * + * @return bool Returns true on success or false on failure + */ + public function setCookie(SetCookie $cookie): bool; + + /** + * Remove cookies currently held in the cookie jar. + * + * Invoking this method without arguments will empty the whole cookie jar. + * If given a $domain argument only cookies belonging to that domain will + * be removed. If given a $domain and $path argument, cookies belonging to + * the specified path within that domain are removed. If given all three + * arguments, then the cookie with the specified name, path and domain is + * removed. + * + * @param string|null $domain Clears cookies matching a domain + * @param string|null $path Clears cookies matching a domain and path + * @param string|null $name Clears cookies matching a domain, path, and name + */ + public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void; + + /** + * Discard all sessions cookies. + * + * Removes cookies that don't have an expire field or a have a discard + * field set to true. To be called when the user agent shuts down according + * to RFC 2965. + */ + public function clearSessionCookies(): void; + + /** + * Converts the cookie jar to an array. + */ + public function toArray(): array; +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php b/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php new file mode 100644 index 0000000..1ba3bc5 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php @@ -0,0 +1,168 @@ +filename = $cookieFile; + $this->storeSessionCookies = $storeSessionCookies; + + if (\file_exists($cookieFile)) { + $this->load($cookieFile); + } + + $this->autoSave = true; + } + + /** + * Saves the file when shutting down + */ + public function __destruct() + { + if ($this->autoSave) { + $this->save($this->filename); + } + } + + /** + * Disable automatic persistence after unserialization. + */ + public function __wakeup(): void + { + $this->autoSave = false; + } + + public function __unserialize(array $data): void + { + $this->autoSave = false; + + throw new \LogicException(static::class.' should never be unserialized'); + } + + /** + * Saves the cookies to a file. + * + * @param string $filename File to save + * + * @throws \RuntimeException if the cookie data cannot be encoded or the + * file cannot be written + */ + public function save(string $filename): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $data = $cookie->toArray(); + $data['HostOnly'] = $cookie->getHostOnly(); + $json[] = $data; + } + } + + try { + $jsonStr = \json_encode($json, \JSON_HEX_TAG | \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new \RuntimeException('Unable to encode cookie data', 0, $e); + } + + if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) { + throw new \RuntimeException(\sprintf('Unable to save file %s', DiagnosticValue::escape($filename))); + } + + // Best-effort: restrict the cookie file to the owner so persisted + // cookies are not world-readable. + @\chmod($filename, 0600); + } + + /** + * Load cookies from a JSON formatted file. + * + * Old cookies are kept unless overwritten by newly loaded ones. + * Cookie records are constructed before any are passed to setCookie(). + * + * @param string $filename Cookie file to load. + * + * @throws \RuntimeException if the file cannot be loaded or is invalid + */ + public function load(string $filename): void + { + $json = \file_get_contents($filename); + if (false === $json) { + throw new \RuntimeException(\sprintf('Unable to load file %s', DiagnosticValue::escape($filename))); + } + if ($json === '') { + return; + } + + $message = \sprintf('Invalid cookie file: %s', DiagnosticValue::escape($filename)); + + try { + $data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new \RuntimeException($message, 0, $e); + } + + // Associative decoding turns JSON objects into arrays, so inspect the root syntax too. + if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') { + throw new \RuntimeException($message); + } + + $cookies = []; + foreach ($data as $cookie) { + if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) { + throw new \RuntimeException($message); + } + + try { + $cookies[] = new SetCookie($cookie); + } catch (\InvalidArgumentException $e) { + throw new \RuntimeException($message, 0, $e); + } + } + + foreach ($cookies as $cookie) { + $this->setCookie($cookie); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php b/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php new file mode 100644 index 0000000..9e703ec --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php @@ -0,0 +1,150 @@ +sessionKey = $sessionKey; + $this->storeSessionCookies = $storeSessionCookies; + $this->load(); + $this->autoSave = true; + } + + /** + * Saves cookies to session when shutting down + */ + public function __destruct() + { + if ($this->autoSave) { + $this->save(); + } + } + + /** + * Disable automatic persistence after unserialization. + */ + public function __wakeup(): void + { + $this->autoSave = false; + } + + public function __unserialize(array $data): void + { + $this->autoSave = false; + + throw new \LogicException(static::class.' should never be unserialized'); + } + + /** + * Save cookies to the client session. + * + * @throws \RuntimeException if the cookie data cannot be encoded + */ + public function save(): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $data = $cookie->toArray(); + $data['HostOnly'] = $cookie->getHostOnly(); + $json[] = $data; + } + } + + try { + $json = \json_encode($json, \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new \RuntimeException('Unable to encode cookie data', 0, $e); + } + + $_SESSION[$this->sessionKey] = $json; + } + + /** + * Load cookies from the client session. + * + * @throws \RuntimeException if the session contains invalid cookie data + */ + protected function load(): void + { + if (!isset($_SESSION[$this->sessionKey])) { + return; + } + + $message = 'Invalid cookie data'; + $json = $_SESSION[$this->sessionKey]; + if (!\is_string($json)) { + throw new \RuntimeException($message); + } + + try { + $data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new \RuntimeException($message, 0, $e); + } + + // Associative decoding turns JSON objects into arrays, so inspect the root syntax too. + if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') { + throw new \RuntimeException($message); + } + + $cookies = []; + foreach ($data as $cookie) { + if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) { + throw new \RuntimeException($message); + } + + try { + $cookies[] = new SetCookie($cookie); + } catch (\InvalidArgumentException $e) { + throw new \RuntimeException($message, 0, $e); + } + } + + foreach ($cookies as $cookie) { + $this->setCookie($cookie); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php b/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php new file mode 100644 index 0000000..6ce2213 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php @@ -0,0 +1,601 @@ + null, + 'Value' => null, + 'Domain' => null, + 'Path' => '/', + 'Max-Age' => null, + 'Expires' => null, + 'Secure' => false, + 'Discard' => false, + 'HttpOnly' => false, + ]; + + /** + * @var array Cookie data + */ + private array $data; + + /** + * @var bool Whether this cookie was set without a Domain attribute. + */ + private bool $hostOnly = false; + + /** + * Create a new SetCookie object from a string. + * + * @param string $cookie Set-Cookie header string + */ + public static function fromString( + #[\SensitiveParameter] + string $cookie + ): self { + // Create the default return array + $data = self::DEFAULTS; + // Explode the cookie string using a series of semicolons + $pieces = \array_filter(\array_map(static function (string $piece): string { + return \trim($piece, " \t"); + }, \explode(';', $cookie))); + // The name of the cookie (first kvp) must exist and include an equal sign. + if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) { + return new self($data); + } + + // Add the cookie pieces into the parsed data array + foreach ($pieces as $part) { + $cookieParts = \explode('=', $part, 2); + $key = \trim($cookieParts[0], " \t"); + $value = isset($cookieParts[1]) + ? \trim($cookieParts[1], " \t") + : true; + + // Only check for non-cookies when cookies have been found + if (!isset($data['Name'])) { + $data['Name'] = $key; + $data['Value'] = $value; + } else { + foreach (\array_keys(self::DEFAULTS) as $search) { + if (Psr7\Utils::caselessEquals($search, $key)) { + if ($search === 'Max-Age') { + if (\is_string($value) && \preg_match('/^[+-]?[0-9]+$/D', $value) === 1) { + $maxAge = self::parseNumericInteger($value); + if ($maxAge !== null) { + $data[$search] = $maxAge; + } + } + } elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') { + if ($value) { + $data[$search] = true; + } + } elseif (\is_string($value)) { + $data[$search] = $value; + } + continue 2; + } + } + if (Psr7\Utils::caselessEquals('HostOnly', $key)) { + continue; + } + $data[$key] = $value; + } + } + + // Max-Age takes precedence over Expires, RFC 6265 section 5.3 + if ($data['Max-Age'] !== null) { + $data['Expires'] = null; + } + + return new self($data); + } + + /** + * @param array $data Array of cookie data provided by a Cookie parser + */ + public function __construct( + #[\SensitiveParameter] + array $data = [] + ) { + $this->data = self::DEFAULTS; + self::validateFieldTypes($data); + + if (\array_key_exists('HostOnly', $data)) { + $this->setHostOnly($data['HostOnly']); + unset($data['HostOnly']); + } + + if (isset($data['Name'])) { + $this->setName($data['Name']); + } + + if (isset($data['Value'])) { + $this->setValue($data['Value']); + } + + if (isset($data['Domain'])) { + $this->setDomain($data['Domain']); + } + + if (isset($data['Path'])) { + $this->setPath($data['Path']); + } + + if (isset($data['Max-Age'])) { + $this->setMaxAge($data['Max-Age']); + } + + if (isset($data['Expires'])) { + $this->setExpires($data['Expires']); + } + + if (isset($data['Secure'])) { + $this->setSecure($data['Secure']); + } + + if (isset($data['Discard'])) { + $this->setDiscard($data['Discard']); + } + + if (isset($data['HttpOnly'])) { + $this->setHttpOnly($data['HttpOnly']); + } + + // Set the remaining values that don't have extra validation logic + foreach (array_diff(array_keys($data), array_keys(self::DEFAULTS)) as $key) { + $this->data[$key] = $data[$key]; + } + + // Derive Expires from Max-Age unless the data already carries one + $maxAge = $this->getMaxAge(); + if ($maxAge !== null && $this->getExpires() === null) { + $this->setExpires(self::maxAgeToExpires($maxAge, \time())); + } + } + + public function __toString(): string + { + $str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; '; + foreach ($this->data as $k => $v) { + if ($k === 'Domain' && $this->getHostOnly()) { + continue; + } + if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { + if ($k === 'Expires') { + $str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; '; + } else { + $str .= ($v === true ? $k : "{$k}={$v}").'; '; + } + } + } + + return \rtrim($str, '; '); + } + + public function toArray(): array + { + $data = $this->data; + if ($this->getHostOnly()) { + $data['HostOnly'] = true; + } + + return $data; + } + + /** + * Get the cookie name. + */ + public function getName(): ?string + { + return $this->data['Name']; + } + + /** + * Set the cookie name. + * + * @param string $name Cookie name + */ + public function setName(string $name): void + { + $this->data['Name'] = $name; + } + + /** + * Get the cookie value. + */ + public function getValue(): ?string + { + return $this->data['Value']; + } + + /** + * Set the cookie value. + * + * @param string $value Cookie value + */ + public function setValue(string $value): void + { + $this->data['Value'] = $value; + } + + /** + * Get the domain. + */ + public function getDomain(): ?string + { + return $this->data['Domain']; + } + + /** + * Set the domain of the cookie. + * + * @param string|null $domain Domain of the cookie + */ + public function setDomain(?string $domain): void + { + $this->data['Domain'] = null === $domain ? null : self::normalizeDomain($domain); + } + + /** + * Get whether this cookie is scoped to the origin host only. + */ + public function getHostOnly(): bool + { + return $this->hostOnly; + } + + /** + * Set whether this cookie is scoped to the origin host only. + * + * @param bool $hostOnly Set to true for host-only cookies + */ + public function setHostOnly(bool $hostOnly): void + { + $this->hostOnly = $hostOnly; + } + + /** + * Get the path. + */ + public function getPath(): string + { + return $this->data['Path']; + } + + /** + * Set the path of the cookie. + * + * @param string $path Path of the cookie + */ + public function setPath(string $path): void + { + $this->data['Path'] = $path; + } + + /** + * Maximum lifetime of the cookie in seconds. + */ + public function getMaxAge(): ?int + { + return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age']; + } + + /** + * Set the max-age of the cookie. + * + * @param int|null $maxAge Max age of the cookie in seconds + */ + public function setMaxAge(?int $maxAge): void + { + $this->data['Max-Age'] = $maxAge; + } + + /** + * The UNIX timestamp when the cookie Expires. + */ + public function getExpires(): ?int + { + return $this->data['Expires']; + } + + /** + * Set the unix timestamp for which the cookie will expire. + * + * @param int|string|null $timestamp Unix timestamp or any English textual datetime description. + */ + public function setExpires($timestamp): void + { + if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) { + // TODO: Move this to the parameter definition in 9.0. + throw new \TypeError(__METHOD__.'(): Argument #1 ($timestamp) must be of type int|string|null'); + } + + if ($timestamp === null) { + $this->data['Expires'] = null; + + return; + } + + if (\is_string($timestamp)) { + if (\is_numeric($timestamp)) { + $this->data['Expires'] = self::parseNumericInteger($timestamp); + + return; + } + } elseif (\is_int($timestamp)) { + $this->data['Expires'] = $timestamp; + + return; + } + + $expires = \strtotime($timestamp); + $this->data['Expires'] = $expires === false ? null : $expires; + } + + /** + * Get whether or not this is a secure cookie. + */ + public function getSecure(): bool + { + return $this->data['Secure']; + } + + /** + * Set whether or not the cookie is secure. + * + * @param bool $secure Set to true or false if secure + */ + public function setSecure(bool $secure): void + { + $this->data['Secure'] = $secure; + } + + /** + * Get whether or not this is a session cookie. + */ + public function getDiscard(): bool + { + return $this->data['Discard']; + } + + /** + * Set whether or not this is a session cookie. + * + * @param bool $discard Set to true or false if this is a session cookie + */ + public function setDiscard(bool $discard): void + { + $this->data['Discard'] = $discard; + } + + /** + * Get whether or not this is an HTTP only cookie. + */ + public function getHttpOnly(): bool + { + return $this->data['HttpOnly']; + } + + /** + * Set whether or not this is an HTTP only cookie. + * + * @param bool $httpOnly Set to true or false if this is HTTP only + */ + public function setHttpOnly(bool $httpOnly): void + { + $this->data['HttpOnly'] = $httpOnly; + } + + /** + * Check if the cookie matches a path value. + * + * A request-path path-matches a given cookie-path if at least one of + * the following conditions holds: + * + * - The cookie-path and the request-path are identical. + * - The cookie-path is a prefix of the request-path, and the last + * character of the cookie-path is %x2F ("/"). + * - The cookie-path is a prefix of the request-path, and the first + * character of the request-path that is not included in the cookie- + * path is a %x2F ("/") character. + * + * @param string $requestPath Path to check against + */ + public function matchesPath(string $requestPath): bool + { + $cookiePath = $this->getPath(); + + // Match on exact matches or when path is the default empty "/" + if ($cookiePath === '/' || $cookiePath === $requestPath) { + return true; + } + + // Ensure that the cookie-path is a prefix of the request path. + if (0 !== \strpos($requestPath, $cookiePath)) { + return false; + } + + // Match if the last character of the cookie-path is "/" + if (\substr($cookiePath, -1, 1) === '/') { + return true; + } + + // Match if the first character not included in cookie path is "/" + return \substr($requestPath, \strlen($cookiePath), 1) === '/'; + } + + /** + * Check if the cookie matches a domain value. + * + * @param string $domain Domain to check against + */ + public function matchesDomain(string $domain): bool + { + $cookieDomain = $this->getDomain(); + if (null === $cookieDomain || $cookieDomain === '') { + return false; + } + + if ($this->getHostOnly()) { + return HostIdentity::canonicalCookieDomain($domain) === HostIdentity::canonicalCookieDomain($cookieDomain); + } + + return HostIdentity::cookieDomainMatches($domain, $cookieDomain); + } + + /** + * Check if the cookie is expired. + */ + public function isExpired(): bool + { + return $this->getExpires() !== null && \time() > $this->getExpires(); + } + + /** + * Check if the cookie is valid according to RFC 6265. + * + * @return string|true Returns true if valid or an error message if invalid + */ + public function validate() + { + $name = $this->getName(); + if ($name === null || $name === '') { + return 'The cookie name must not be empty'; + } + + // Check if any of the invalid characters are present in the cookie name + if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $name) !== 0) { + return 'Cookie name must not contain invalid characters: ASCII ' + .'Control characters (0-31;127), space, tab and the ' + .'following characters: ()<>@,;:\"/?={}'; + } + + // Value must not be null. 0 and empty string are valid. Empty strings + // are technically against RFC 6265, but known to happen in the wild. + $value = $this->getValue(); + if ($value === null) { + return 'The cookie value must not be empty'; + } + + // Domains must not be empty, but may be omitted. "0" is not a valid + // internet domain, but may be used as server name in a private network. + $domain = $this->getDomain(); + if ($domain === '' || ($domain !== null && \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.') === '')) { + return 'The cookie domain must not be empty'; + } + + if ($this->getHostOnly() && $domain === null) { + return 'Host-only cookies must have a domain'; + } + + return true; + } + + private static function normalizeDomain(string $domain): string + { + $domain = Psr7\Utils::asciiToLower($domain); + + // Treat trailing-dot domains as host-only, but keep pure-dot domains invalid. + if ($domain !== '' && \substr($domain, -1) === '.' && \trim($domain, '.') !== '') { + return ''; + } + + if ($domain !== '' && $domain !== '.' && $domain[0] === '.') { + $domain = \substr_replace($domain, '', 0, 1); + } + + return HostIdentity::canonicalCookieDomain($domain); + } + + private static function maxAgeToExpires(int $maxAge, int $now): int + { + if ($maxAge <= 0) { + return $now - 1; + } + + // Clamp absurd Max-Age values so addition cannot promote to float + if ($maxAge > \PHP_INT_MAX - $now) { + return \PHP_INT_MAX; + } + + return $now + $maxAge; + } + + private static function parseNumericInteger(string $value): ?int + { + if (!\is_numeric($value)) { + return null; + } + + if (\preg_match('/^[+-]?[0-9]+$/D', $value) === 1) { + $negative = $value[0] === '-'; + $digits = \ltrim($value, '+-'); + $digits = \ltrim($digits, '0'); + $digits = $digits === '' ? '0' : $digits; + $limit = $negative ? \substr((string) \PHP_INT_MIN, 1) : (string) \PHP_INT_MAX; + + if (\strlen($digits) > \strlen($limit) || (\strlen($digits) === \strlen($limit) && \strcmp($digits, $limit) > 0)) { + return null; + } + + return (int) ($negative ? '-'.$digits : $digits); + } + + $number = (float) $value; + if (!\is_finite($number) || $number < \PHP_INT_MIN || $number > \PHP_INT_MAX) { + return null; + } + + if (\PHP_INT_SIZE === 8 && ($number <= (float) \PHP_INT_MIN || $number >= (float) \PHP_INT_MAX)) { + return null; + } + + return (int) $number; + } + + /** + * @param mixed[] $data + */ + private static function validateFieldTypes( + #[\SensitiveParameter] + array $data + ): void { + foreach (['Name', 'Value', 'Domain', 'Path'] as $field) { + if (isset($data[$field]) && !\is_string($data[$field])) { + throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a string', $field)); + } + } + + if (isset($data['Max-Age']) && !\is_int($data['Max-Age'])) { + throw new \InvalidArgumentException('Cookie field "Max-Age" must be an integer'); + } + + if (isset($data['Expires']) && !\is_int($data['Expires']) && !\is_string($data['Expires'])) { + throw new \InvalidArgumentException('Cookie field "Expires" must be an integer or string'); + } + + foreach (['Secure', 'Discard', 'HttpOnly'] as $field) { + if (isset($data[$field]) && !\is_bool($data[$field])) { + throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a boolean', $field)); + } + } + + if (\array_key_exists('HostOnly', $data) && !\is_bool($data['HostOnly'])) { + throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean'); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Env.php b/vendor/guzzlehttp/guzzle/src/Env.php new file mode 100644 index 0000000..aaabd9a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Env.php @@ -0,0 +1,33 @@ +getStatusCode() / 100); + if ($level === 4) { + $label = 'Client error'; + } elseif ($level === 5) { + $label = 'Server error'; + } else { + $label = 'Unsuccessful request'; + } + + $uri = \GuzzleHttp\Psr7\UriRedactor::redactUriForMessage($request->getUri()); + + // Client error: `GET /` resulted in a `404 Not Found` response: ... (truncated) + $message = \sprintf( + '%s: `%s %s` resulted in a `%s %s` response', + $label, + DiagnosticValue::escape($request->getMethod()), + $uri, + $response->getStatusCode(), + DiagnosticValue::escape($response->getReasonPhrase()) + ); + + $summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response); + + if ($summary !== null) { + $message .= \sprintf(': %s', DiagnosticValue::escape($summary)); + } + + if ($level === 4) { + return new ClientException($message, $request, $response, $previous); + } + + if ($level === 5) { + return new ServerException($message, $request, $response, $previous); + } + + return new ResponseException($message, $request, $response, $previous); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/ResponseException.php b/vendor/guzzlehttp/guzzle/src/Exception/ResponseException.php new file mode 100644 index 0000000..b5cd964 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Exception/ResponseException.php @@ -0,0 +1,63 @@ +getStatusCode(), $previous); + $this->response = $response; + } + + /** + * Return a new exception instance with an updated response. + * + * @param \Throwable|null $previous Previous exception, or the current + * previous exception when omitted. + * + * @return static + */ + public function withResponse( + #[\SensitiveParameter] + ResponseInterface $response, + #[\SensitiveParameter] + ?\Throwable $previous = null + ): self { + if ($response->getStatusCode() !== $this->response->getStatusCode()) { + throw new InvalidArgumentException('Cannot replace response with a different status code.'); + } + + return new static( + $this->getMessage(), + $this->getRequest(), + $response, + $previous ?? $this->getPrevious() + ); + } + + /** + * Get the associated response. + */ + public function getResponse(): ResponseInterface + { + return $this->response; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/ResponseTimeoutException.php b/vendor/guzzlehttp/guzzle/src/Exception/ResponseTimeoutException.php new file mode 100644 index 0000000..4969441 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Exception/ResponseTimeoutException.php @@ -0,0 +1,13 @@ +request = $request; + } + + /** + * Get the request that caused the exception. + */ + public function getRequest(): RequestInterface + { + return $this->request; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/ChunkedBodyStream.php b/vendor/guzzlehttp/guzzle/src/Handler/ChunkedBodyStream.php new file mode 100644 index 0000000..e8e4b87 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/ChunkedBodyStream.php @@ -0,0 +1,431 @@ +stream = $stream; + } + + public function __clone() + { + // A clone shares the transport, so detaching it would break this body. + $this->detachable = false; + } + + public function read(int $length): string + { + if ($this->failure !== null) { + throw $this->failure; + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + do { + $data = $this->decode($length); + } while ($data === '' && $length > 0 && !$this->eof() && $this->fill()); + + $this->position = TransferByteCounter::add( + $this->position, + \strlen($data), + 'Response body exceeds the maximum integer size supported on this platform' + ); + + return $data; + } + + public function eof(): bool + { + return $this->state === self::DONE; + } + + /** + * @return mixed + */ + public function getMetadata(?string $key = null) + { + // A failed body has not timed out, whatever a stale flag on the + // transport says, so callers report the failure itself. + if ($this->failure !== null && $key === 'timed_out') { + return false; + } + + $metadata = $this->stream->getMetadata($key); + if ($this->failure !== null && $key === null && \is_array($metadata)) { + $metadata['timed_out'] = false; + } + + return $metadata; + } + + public function tell(): int + { + return $this->position; + } + + public function getSize(): ?int + { + return null; + } + + public function isSeekable(): bool + { + return false; + } + + public function seek(int $offset, int $whence = \SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a chunked response body'); + } + + public function isWritable(): bool + { + return false; + } + + public function write(string $string): int + { + throw new \RuntimeException('Cannot write to a chunked response body'); + } + + public function close(): void + { + $this->buffer = ''; + $this->offset = 0; + $this->detachable = false; + $this->stream->close(); + } + + public function detach() + { + if (!$this->detachable) { + return null; + } + + if ($this->state === self::DONE) { + return $this->stream->detach(); + } + + if ($this->buffer === '' && $this->failure === null) { + $resource = $this->stream->detach(); + if (\is_resource($resource)) { + // Nothing has been decoded yet, so PHP's filter can take over. + \stream_filter_append($resource, 'dechunk', \STREAM_FILTER_READ); + } + + return $resource; + } + + // PHP's filter cannot resume part way through a chunk, so hand the + // decoder over to a resource that keeps decoding the rest of the body. + $decoder = clone $this; + $this->buffer = ''; + $this->offset = 0; + $this->detachable = false; + $this->stream = Utils::streamFor(''); + $this->stream->detach(); + + return StreamWrapper::getResource($decoder); + } + + /** + * Appends what the transport has available to the buffer, waiting for at + * least one byte. + */ + private function fill(): bool + { + $data = $this->stream->read(self::READ_SIZE); + if ($data === '') { + if (!$this->stream->eof()) { + return false; + } + + $this->failure = new \RuntimeException('Response body ended before the chunked body was complete'); + + throw $this->failure; + } + + $this->buffer = \substr($this->buffer, $this->offset).$data; + $this->offset = 0; + + return true; + } + + /** + * Decodes up to $length bytes from the buffer, and any framing after them, + * so the end of the body is noticed without another transport read. + */ + private function decode(int $length): string + { + $data = ''; + + try { + while ($this->offset < \strlen($this->buffer) && $this->state !== self::DONE) { + if ($this->state === self::DATA) { + $take = \min($this->remaining, $length - \strlen($data), \strlen($this->buffer) - $this->offset); + if ($take === 0) { + break; + } + $data .= \substr($this->buffer, $this->offset, $take); + $this->offset += $take; + $this->remaining -= $take; + if ($this->remaining === 0) { + $this->state = self::DATA_END; + } + } elseif ($this->state === self::SIZE) { + $chunks = $this->digits === '' ? $this->decodeChunks($length - \strlen($data)) : null; + if ($chunks === null) { + $this->decodeSize(); + } else { + $data .= $chunks; + } + } elseif ($this->state === self::SIZE_LINE) { + $this->skipSizeLine(); + } elseif ($this->state === self::DATA_END) { + $this->decodeDataEnd(); + } else { + $this->decodeTrailer(); + } + } + } catch (\RuntimeException $e) { + $this->failure = $e; + if ($data === '') { + throw $e; + } + } + + return $data; + } + + /** + * Decodes buffered chunks in bulk, up to $length bytes, and leaves the + * state machine at the first chunk that needs more care. Returns null when + * it consumes nothing. + */ + private function decodeChunks(int $length): ?string + { + $buffer = $this->buffer; + $end = \strlen($buffer); + $offset = $this->offset; + $data = ''; + + while (true) { + // Up to seven digits keep the size an int on every platform. + $digits = \strspn($buffer, '0123456789abcdefABCDEF', $offset, 8); + if ($digits === 0 || $digits === 8) { + break; + } + $lineEnd = \strpos($buffer, "\n", $offset + $digits); + if ($lineEnd === false) { + break; + } + + $size = (int) \hexdec(\substr($buffer, $offset, $digits)); + $offset = $lineEnd + 1; + if ($size === 0) { + $this->state = self::TRAILER; + break; + } + if ($size > $length || $offset + $size > $end) { + $this->remaining = $size; + $this->state = self::DATA; + break; + } + + $data .= \substr($buffer, $offset, $size); + $length -= $size; + $offset += $size; + if ($offset + 1 < $end && $buffer[$offset] === "\r" && $buffer[$offset + 1] === "\n") { + $offset += 2; + } elseif ($offset < $end && $buffer[$offset] === "\n") { + ++$offset; + } else { + $this->state = self::DATA_END; + break; + } + } + + if ($offset === $this->offset) { + return null; + } + + $this->offset = $offset; + + return $data; + } + + private function decodeSize(): void + { + $count = \strspn($this->buffer, '0123456789abcdefABCDEF', $this->offset); + $this->digits .= \substr($this->buffer, $this->offset, $count); + $this->offset += $count; + if (\strlen($this->digits) > self::MAX_SIZE_DIGITS) { + throw new \RuntimeException('Invalid chunked response body: invalid chunk size'); + } + if ($this->offset === \strlen($this->buffer)) { + return; + } + if ($this->digits === '') { + throw new \RuntimeException('Invalid chunked response body: invalid chunk size'); + } + + $significant = \ltrim($this->digits, '0'); + if (\strlen($significant) > 16 || (\strlen($significant) === 16 && $significant[0] > '7')) { + throw new \RuntimeException('Invalid chunked response body: invalid chunk size'); + } + + $size = \hexdec($this->digits); + if (!\is_int($size)) { + throw new \OverflowException('Chunk size exceeds the maximum integer size supported on this platform'); + } + + $this->digits = ''; + $this->remaining = $size; + $this->state = self::SIZE_LINE; + } + + private function skipSizeLine(): void + { + // Chunk extensions, and anything else up to the line feed, are ignored + // the way libcurl ignores them. + $end = \strpos($this->buffer, "\n", $this->offset); + if ($end === false) { + $this->offset = \strlen($this->buffer); + + return; + } + + $this->offset = $end + 1; + $this->state = $this->remaining === 0 ? self::TRAILER : self::DATA; + } + + private function decodeDataEnd(): void + { + $this->offset += \strspn($this->buffer, "\r", $this->offset); + if ($this->offset === \strlen($this->buffer)) { + return; + } + if ($this->buffer[$this->offset] !== "\n") { + throw new \RuntimeException('Invalid chunked response body: missing CRLF after chunk data'); + } + + ++$this->offset; + $this->state = self::SIZE; + } + + private function decodeTrailer(): void + { + if ($this->state !== self::TRAILER) { + if ($this->buffer[$this->offset] !== "\n") { + throw new \RuntimeException('Invalid chunked response body: invalid trailer section'); + } + + ++$this->offset; + $this->state = $this->state === self::FINAL_CR ? self::DONE : self::TRAILER; + + return; + } + + $count = \strcspn($this->buffer, "\r\n", $this->offset); + $this->line .= \substr($this->buffer, $this->offset, $count); + $this->offset += $count; + $this->trailerLength += $count; + if (\strlen($this->line) > self::MAX_TRAILER_LINE_LENGTH || $this->trailerLength > self::MAX_TRAILER_SECTION_LENGTH) { + throw new \RuntimeException('Invalid chunked response body: invalid trailer section'); + } + if ($this->offset === \strlen($this->buffer)) { + return; + } + + $carriageReturn = $this->buffer[$this->offset] === "\r"; + ++$this->offset; + if ($this->line === '') { + $this->state = $carriageReturn ? self::FINAL_CR : self::DONE; + + return; + } + + if (\strpos($this->line, "\0") !== false || \strpos($this->line, ':') === false) { + throw new \RuntimeException('Invalid chunked response body: invalid trailer section'); + } + + $this->line = ''; + if ($carriageReturn) { + $this->state = self::TRAILER_CR; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/Clock.php b/vendor/guzzlehttp/guzzle/src/Handler/Clock.php new file mode 100644 index 0000000..20f284b --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/Clock.php @@ -0,0 +1,32 @@ + 0) { + $slice = \min($microseconds, 0xFFFFFFFF); + \usleep($slice); + $microseconds -= $slice; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php new file mode 100644 index 0000000..28e9c3b --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php @@ -0,0 +1,3179 @@ + true, // CURLE_COULDNT_RESOLVE_PROXY + 6 => true, // CURLE_COULDNT_RESOLVE_HOST + 7 => true, // CURLE_COULDNT_CONNECT + 35 => true, // CURLE_SSL_CONNECT_ERROR + 51 => true, // CURLE_PEER_FAILED_VERIFICATION before libcurl 7.62.0 + 60 => true, // CURLE_SSL_CACERT / modern CURLE_PEER_FAILED_VERIFICATION + 83 => true, // CURLE_SSL_ISSUER_ERROR + 90 => true, // CURLE_SSL_PINNEDPUBKEYNOTMATCH + 91 => true, // CURLE_SSL_INVALIDCERTSTATUS + 96 => true, // CURLE_QUIC_CONNECT_ERROR + 97 => true, // CURLE_PROXY + 98 => true, // CURLE_SSL_CLIENTCERT + 101 => true, // CURLE_ECH_REQUIRED + ]; + + private const CURL_NETWORK_ERRORS = [ + 16 => true, // CURLE_HTTP2 + 52 => true, // CURLE_GOT_NOTHING + 55 => true, // CURLE_SEND_ERROR + 56 => true, // CURLE_RECV_ERROR + 92 => true, // CURLE_HTTP2_STREAM + 95 => true, // CURLE_HTTP3 + ]; + + private const CURL_RESPONSE_TRANSFER_ERRORS = [ + 8 => true, // CURLE_WEIRD_SERVER_REPLY + 18 => true, // CURLE_PARTIAL_FILE + 23 => true, // CURLE_WRITE_ERROR from libcurl's content decoders + 61 => true, // CURLE_BAD_CONTENT_ENCODING + ]; + + private const CURL_CONNECT_TIMEOUT_ERRORS = [ + 'Connection timed out', + 'Connection timeout', + 'Connection time-out', + 'Resolving timed out', + 'name lookup timed out', + 'Proxy CONNECT aborted due to timeout', + 'SSL connection timeout', + ]; + + /** + * libcurl's CURL_READFUNC_ABORT value. + */ + private const CURL_READFUNC_ABORT = 0x10000000; + + /** + * libcurl's CURL_SEEKFUNC_OK value. + */ + private const CURL_SEEKFUNC_OK = 0; + + /** + * libcurl's CURL_SEEKFUNC_FAIL value. + */ + private const CURL_SEEKFUNC_FAIL = 1; + + /** + * libcurl's CURL_SEEKFUNC_CANTSEEK value. + */ + private const CURL_SEEKFUNC_CANTSEEK = 2; + + /** + * Maximum number of times libcurl may replay a streamed request body. + */ + private const CURL_SEEK_MAX_REPLAYS = 3; + + /** + * libcurl's CURLE_SEND_FAIL_REWIND value. + */ + private const CURLE_SEND_FAIL_REWIND = 65; + + /** + * Guzzle's default connect timeout in milliseconds, replacing libcurl's + * 300 seconds. + */ + private const DEFAULT_CONNECT_TIMEOUT_MS = 60000; + + /** + * Milliseconds passed to libcurl to disable the connect timeout: libcurl + * treats zero as its own 300-second default, so disabling means passing + * the largest value a 32-bit libcurl long accepts. + */ + private const CONNECT_TIMEOUT_DISABLED_MS = 2147483647; + + /** + * @var resource[]|\CurlHandle[] + */ + private array $handles = []; + + /** + * @var string|null Owner signature of the proxy tunnels that pooled idle + * handles may still hold + */ + private ?string $proxyTunnelOwner = null; + + /** + * @var bool Whether an in-domain handle has been pooled since the last purge + */ + private bool $poolMayHoldTunnels = false; + + /** + * @var int Total number of idle handles to keep in cache + */ + private int $maxHandles; + + private bool $closed = false; + + /** + * @var resource|\CurlShareHandle|\CurlSharePersistentHandle|null + */ + private $shareHandle; + + private string $shareMode; + + /** + * @var bool Whether the configured share handle may own a connection + * cache populated outside this factory + */ + private bool $opaqueShareConnectionCache = false; + + /** + * @param int $maxHandles Maximum number of idle handles. + * @param resource|\CurlShareHandle|\CurlSharePersistentHandle|CurlShareHandleState|null $shareHandle + */ + public function __construct(int $maxHandles, string $shareMode = TransportSharing::NONE, $shareHandle = null) + { + $this->maxHandles = $maxHandles; + $this->shareMode = CurlShareHandleState::normalizeMode($shareMode, 'transport_sharing'); + + if ($shareHandle instanceof CurlShareHandleState) { + if ($shareHandle->mode !== $this->shareMode) { + throw new InvalidArgumentException('The cURL share handle state mode does not match the configured transport sharing mode.'); + } + + // A Guzzle-created handler-lifetime state locks only DNS and TLS + // session data, so its handle can never own a connection cache. A + // persistent state's connection cache is worker-global, so other + // producers in the worker may populate it. + $this->opaqueShareConnectionCache = $shareHandle->mode === TransportSharing::PERSISTENT_PREFER + || $shareHandle->mode === TransportSharing::PERSISTENT_REQUIRE; + $shareHandle = $shareHandle->handle; + } elseif ($shareHandle !== null) { + // An externally supplied handle's cached contents cannot be + // inspected from PHP, so it may own a connection cache populated + // outside this factory. + $this->opaqueShareConnectionCache = true; + } + + if ($this->shareMode === TransportSharing::NONE && $shareHandle !== null) { + throw new InvalidArgumentException('A cURL share handle cannot be provided when transport sharing is disabled.'); + } + + if ($this->shareMode !== TransportSharing::NONE && $shareHandle === null) { + throw new InvalidArgumentException('A cURL share handle is required when transport sharing is enabled.'); + } + + if ($shareHandle !== null && !self::isCurlShareHandle($shareHandle)) { + throw new InvalidArgumentException('A cURL share handle must be an instance of CurlShareHandle, CurlSharePersistentHandle, or a curl_share resource.'); + } + + $this->shareHandle = $shareHandle; + } + + /** + * @param mixed $value + */ + private static function isCurlShareHandle($value): bool + { + if (\PHP_VERSION_ID < 80000) { + return \is_resource($value) && \get_resource_type($value) === 'curl_share'; + } + + if ($value instanceof \CurlShareHandle) { + return true; + } + + return \class_exists('CurlSharePersistentHandle') + && $value instanceof \CurlSharePersistentHandle; + } + + public function create( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): EasyHandle { + $this->assertOpen(); + self::validateRequestUriScheme($request); + + if (\strpbrk($request->getMethod(), "\r\n") !== false) { + throw new RequestException('HTTP method must not contain a carriage return or line feed.', $request); + } + + $protocolVersion = $request->getProtocolVersion(); + + if ('' === $protocolVersion) { + throw new RequestException('HTTP protocol version must not be empty.', $request); + } + + if (1 !== \preg_match('/^\d+(?:\.\d+)?$/D', $protocolVersion)) { + throw new RequestException('HTTP protocol version must be a valid HTTP version number.', $request); + } + + CurlVersion::ensureSupported($request); + + $multiplex = self::normalizeMultiplex($options); + + if ('3' === $protocolVersion || '3.0' === $protocolVersion) { + if (!CurlVersion::supportsHttp3()) { + if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new RequestException('Required multiplexing for HTTP/3 needs libcurl 8.13.0 or newer built with HTTP/3 support.', $request); + } + + throw new RequestException('HTTP/3 is supported by the cURL handler, however the installed PHP cURL extension or libcurl does not support HTTP/3.', $request); + } + } elseif ('2' === $protocolVersion || '2.0' === $protocolVersion) { + if (!CurlVersion::supportsHttp2()) { + if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new RequestException('Required multiplexing needs libcurl 8.14.0 or newer built with HTTP/2 support.', $request); + } + + throw new RequestException('HTTP/2 is supported by the cURL handler, however libcurl 7.65.2 or newer built with HTTP/2 support is required.', $request); + } + } elseif ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) { + throw new RequestException(sprintf('HTTP/%s is not supported by the cURL handler.', $protocolVersion), $request); + } + + if (isset($options['curl']['body_as_string'])) { + $options['_body_as_string'] = $options['curl']['body_as_string']; + unset($options['curl']['body_as_string']); + } + + self::rejectUnsupportedRequestOptions($options); + self::assertOnStatsCallable($options); + self::assertOnTrailersCallable($options); + $this->rejectRequestLevelShareConflict($options); + $this->rejectPersistentRequireConnectionReuseConflicts($options); + self::rejectUnsupportedCurlOptions($options); + self::rejectConflictingCurlOptions($options); + + $framing = RequestFraming::analyze($request, $request->getMethod() !== 'HEAD'); + $request = $framing->request; + + $managedProxyAuthorization = self::managedProxyAuthorizationHeaderLines($request); + + $easy = new EasyHandle(); + $easy->request = $request; + $easy->options = $options; + $conf = $this->getDefaultConf($easy); + $this->applyMethod($easy, $conf, $framing); + $this->applyHandlerOptions($easy, $conf); + $this->applyHeaders($easy, $conf); + unset($conf['_headers']); + + // Add handler options from the request configuration options + if (isset($options['curl'])) { + $conf = \array_replace($conf, $options['curl']); + } + + self::normalizeStringableProxyCredentialOptions($conf); + + if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + self::assertRequiredMultiplexAuthSupported($conf); + } + + self::applyProxyConnectHeaderSuppression($request, $conf); + self::normalizeCurlHeaderOptions($conf); + self::applyProxyAuthorizationHeaderHandling($request, $conf, $managedProxyAuthorization); + // Validate the managed lines appended above too: a custom + // RequestInterface can return unvalidated header values. + self::normalizeCurlHeaderOptions($conf); + + if ($this->shareHandle !== null) { + // Conservative blanket mode: a configured share handle hides the + // pooled connections' provenance, so sectioned reuse cannot reason + // about them. + $this->forceFreshConnectionForAuthenticatedProxy($request, $conf); + } else { + $signature = self::proxyTunnelSignature($request, $conf); + $easy->proxyTunnelSignature = $signature; + if ($signature !== null && $signature !== $this->proxyTunnelOwner) { + if ($this->poolMayHoldTunnels) { + // Pooled idle handles may hold a different owner's tunnel. + $this->discardIdleHandles(); + $this->poolMayHoldTunnels = false; + } + // The first in-domain owner latches without purging: the pool + // provably holds no in-domain tunnel yet. + $this->proxyTunnelOwner = $signature; + } + } + + $easy->effectiveProxy = self::getEffectiveProxy($conf); + + $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); + if ($this->shareHandle !== null) { + if (!\defined('CURLOPT_SHARE')) { + throw new RequestException('The configured cURL share handle requires CURLOPT_SHARE, but it is not available in the installed PHP cURL extension.', $easy->request); + } + + $conf[(int) \constant('CURLOPT_SHARE')] = $this->shareHandle; + } + + if (\defined('CURLOPT_PIPEWAIT')) { + $easy->usesPipewait = !empty($conf[(int) \constant('CURLOPT_PIPEWAIT')]); + } + + $handle = $this->handles ? \array_pop($this->handles) : \curl_init(); + if (false === $handle) { + throw new RequestException('Can not initialize cURL handle.', $request); + } + $easy->handle = $handle; + + try { + $this->applyCurlOptions($handle, $conf); + } catch (\Throwable $e) { + if (PHP_VERSION_ID < 80000 && \is_resource($handle)) { + \curl_close($handle); + } + unset($easy->handle); + + throw $e; + } + + return $easy; + } + + /** + * @param resource|\CurlHandle $handle + * @param array $conf + */ + private function applyCurlOptions( + #[\SensitiveParameter] + $handle, + #[\SensitiveParameter] + array $conf + ): void { + foreach ($conf as $option => $value) { + if (!\is_int($option)) { + throw new InvalidArgumentException(\sprintf( + 'Invalid cURL option %s.', + self::formatCurlOption($option) + )); + } + + try { + $success = curl_setopt($handle, $option, $value); + } catch (\Throwable $e) { + throw new InvalidArgumentException( + \sprintf( + 'Unable to set cURL option %s: %s', + self::formatCurlOption($option), + $e->getMessage() + ), + 0, + $e + ); + } + + if (!$success) { + throw new InvalidArgumentException(\sprintf( + 'Unable to set cURL option %s.', + self::formatCurlOption($option) + )); + } + } + } + + /** + * @param array $conf + */ + private static function normalizeStringableProxyCredentialOptions( + #[\SensitiveParameter] + array &$conf + ): void { + foreach (self::STRINGABLE_PROXY_CREDENTIAL_OPTIONS as $name) { + if (!\defined($name)) { + continue; + } + + $option = (int) \constant($name); + if (!isset($conf[$option]) || !\is_object($conf[$option]) || !\method_exists($conf[$option], '__toString')) { + continue; + } + + try { + $conf[$option] = (string) $conf[$option]; + } catch (\Throwable $e) { + // Wrap the failure exactly as applyCurlOptions() does for a + // value that cannot be applied. + throw new InvalidArgumentException( + \sprintf( + 'Unable to set cURL option %s: %s', + self::formatCurlOption($option), + $e->getMessage() + ), + 0, + $e + ); + } + } + } + + private function rejectRequestLevelShareConflict( + #[\SensitiveParameter] + array $options + ): void { + if ($this->shareHandle === null) { + return; + } + + if ( + !\defined('CURLOPT_SHARE') + || !isset($options['curl']) + || !\is_array($options['curl']) + || !\array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl']) + ) { + return; + } + + throw new InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with configured transport sharing.'); + } + + private function rejectPersistentRequireConnectionReuseConflicts( + #[\SensitiveParameter] + array $options + ): void { + if ( + $this->shareMode !== TransportSharing::PERSISTENT_REQUIRE + || !isset($options['curl']) + || !\is_array($options['curl']) + ) { + return; + } + + if (!empty($options['curl'][\CURLOPT_FRESH_CONNECT])) { + throw new InvalidArgumentException('The CURLOPT_FRESH_CONNECT cURL option cannot be used when persistent cURL sharing is required because it disables connection reuse.'); + } + + if (!empty($options['curl'][\CURLOPT_FORBID_REUSE])) { + throw new InvalidArgumentException('The CURLOPT_FORBID_REUSE cURL option cannot be used when persistent cURL sharing is required because it disables connection reuse.'); + } + } + + private static function normalizeMultiplex( + #[\SensitiveParameter] + array $options + ): string { + $multiplex = $options['multiplex'] ?? null; + + if ($multiplex === null) { + return Multiplexing::WAIT; + } + + if (!\in_array($multiplex, [Multiplexing::NONE, Multiplexing::EAGER, Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new InvalidArgumentException(\sprintf( + 'The "multiplex" option must be null or a GuzzleHttp\\Multiplexing::* constant; received %s.', + \get_debug_type($multiplex) + )); + } + + return $multiplex; + } + + private static function assertRequiredMultiplexSupported( + #[\SensitiveParameter] + EasyHandle $easy + ): void { + if (!CurlVersion::supportsRequiredHttp2Multiplex()) { + throw new RequestException('Required multiplexing needs libcurl 8.14.0 or newer built with HTTP/2 support.', $easy->request); + } + + $proxy = ProxyEnv::resolveProxySelection($easy->request->getUri(), $easy->options['proxy'] ?? null); + self::assertSelectedProxySupported($proxy->getProxy(), $easy->request); + + if ('https' !== $easy->request->getUri()->getScheme() && $proxy->hasProxy()) { + throw new RequestException('Required multiplexing cannot be guaranteed for cleartext requests sent through a proxy.', $easy->request); + } + } + + /** + * libcurl forces NTLM-authenticated transfers onto HTTP/1.1: when the + * server picks NTLM from the offered mask, the connection is closed and the + * request is retried over HTTP/1.1 whatever HTTP version was asked for, + * silently defeating the required protocol guarantee on both cleartext and + * TLS routes. The final merged mask is checked because the raw + * CURLOPT_HTTPAUTH cURL option is allow-listed, and any mask permitting + * NTLM, such as CURLAUTH_ANY, is rejected because the selection is + * server-controlled. + * + * @param array $conf + */ + private static function assertRequiredMultiplexAuthSupported( + #[\SensitiveParameter] + array $conf + ): void { + if (!\array_key_exists(\CURLOPT_HTTPAUTH, $conf)) { + return; + } + + $auth = $conf[\CURLOPT_HTTPAUTH]; + if (!\is_scalar($auth)) { + throw new InvalidArgumentException('The "multiplex" request option cannot be required when the final CURLOPT_HTTPAUTH cURL option value is not an integer.'); + } + + $ntlmBits = \CURLAUTH_NTLM; + if (\defined('CURLAUTH_NTLM_WB')) { + $ntlmBits |= (int) \constant('CURLAUTH_NTLM_WB'); + } + + if (((int) $auth & $ntlmBits) !== 0) { + throw new InvalidArgumentException('The "multiplex" request option cannot be required when the final CURLOPT_HTTPAUTH cURL option value permits NTLM; libcurl retries NTLM authentication over HTTP/1.1.'); + } + } + + private static function assertSelectedProxySupported( + #[\SensitiveParameter] + ?string $selectedProxy, + #[\SensitiveParameter] + RequestInterface $request + ): void { + if ($selectedProxy === null || $selectedProxy === '') { + return; + } + + $scheme = ProxyOptions::proxyScheme($selectedProxy); + + if (!\in_array($scheme, ['http', 'https', 'socks4', 'socks4a', 'socks5', 'socks5h'], true)) { + throw new InvalidArgumentException(\sprintf('The "%s" proxy scheme is not supported by the cURL handler.', Psr7\DiagnosticValue::escape($scheme))); + } + + // libcurl 7.76.0-8.17.0 skips a proxy with undecodable credentials. + if (\preg_match('/%[01][0-9A-Fa-f]/', \substr($selectedProxy, 0, (int) \strrpos($selectedProxy, '@'))) !== 0) { + throw new InvalidArgumentException('Proxy credentials must not contain percent-encoded control characters.'); + } + + // libcurl before 7.65.0 reads the proxy host after the first '@'. + if (\substr_count($selectedProxy, '@') > 1) { + throw new InvalidArgumentException('Invalid proxy URL.'); + } + + $authority = \explode('://', $selectedProxy, 2)[1] ?? $selectedProxy; + $host = \explode('@', $authority, 2)[1] ?? $authority; + + // libcurl 7.47.0-7.51.0 skips a proxy with a host of '.'. + if (\preg_match('#^\.(?:[:/]|$)#D', $host) !== 0) { + throw new InvalidArgumentException('Invalid proxy URL.'); + } + + if ($scheme === 'https' && !CurlVersion::supportsHttpsProxy()) { + throw new RequestException('HTTPS proxies are not supported by the installed libcurl; libcurl 7.54.0 or newer built with HTTPS-proxy support is required.', $request); + } + } + + /** + * @param int|string $option + */ + private static function formatCurlOption($option): string + { + if (!\is_int($option)) { + return \sprintf('"%s"', Psr7\DiagnosticValue::escape((string) $option)); + } + + static $names = null; + + if (null === $names) { + $names = []; + foreach (\get_defined_constants(true)['curl'] ?? [] as $name => $value) { + if (\is_int($value) && \strpos($name, 'CURLOPT_') === 0 && !isset($names[$value])) { + $names[$value] = $name; + } + } + } + + if (isset($names[$option])) { + return \sprintf('%s (%d)', $names[$option], $option); + } + + return (string) $option; + } + + private static function rejectConflictingCurlOptions( + #[\SensitiveParameter] + array $options + ): void { + if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) { + return; + } + + $conflictingOptions = self::conflictingCurlOptions(); + + foreach ($options['curl'] as $option => $_) { + if (!\array_key_exists($option, $conflictingOptions)) { + continue; + } + + $name = self::formatCurlOption($option); + $replacement = $conflictingOptions[$option]; + if ($replacement !== null) { + throw new InvalidArgumentException(\sprintf( + 'Passing %s in the "curl" request option is not supported because it conflicts with Guzzle-managed request handling. Use %s instead.', + $name, + $replacement + )); + } + + throw new InvalidArgumentException(\sprintf( + 'Passing %s in the "curl" request option is not supported because it conflicts with Guzzle-managed cURL internals.', + $name + )); + } + } + + private static function rejectUnsupportedCurlOptions( + #[\SensitiveParameter] + array $options + ): void { + if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) { + return; + } + + $supportedOptions = self::supportedCurlOptions(); + $conflictingOptions = self::conflictingCurlOptions(); + + foreach ($options['curl'] as $option => $_) { + if ( + !\is_int($option) + || \array_key_exists($option, $supportedOptions) + || \array_key_exists($option, $conflictingOptions) + ) { + continue; + } + + throw new InvalidArgumentException(\sprintf( + 'Passing %s in the "curl" request option is not supported because it is outside the built-in cURL handlers\' allow-list.', + self::formatCurlOption($option) + )); + } + } + + private static function rejectUnsupportedRequestOptions( + #[\SensitiveParameter] + array $options + ): void { + if (\array_key_exists('stream_context', $options)) { + throw new InvalidArgumentException('Passing the "stream_context" request option to a cURL handler is not supported because cURL handlers ignore PHP stream context options.'); + } + } + + private static function assertOnStatsCallable( + #[\SensitiveParameter] + array $options + ): void { + if (isset($options['on_stats']) && !\is_callable($options['on_stats'])) { + throw new InvalidArgumentException('on_stats must be callable'); + } + } + + private static function assertOnTrailersCallable( + #[\SensitiveParameter] + array $options + ): void { + if (isset($options['on_trailers']) && !\is_callable($options['on_trailers'])) { + throw new InvalidArgumentException('on_trailers must be callable'); + } + } + + /** + * @return array + */ + private static function conflictingCurlOptions(): array + { + static $options = null; + + if ($options !== null) { + return $options; + } + + $options = []; + + self::addConflictingCurlOption($options, 'CURLOPT_SHARE', 'the "transport_sharing" client option or cURL handler option'); + self::addConflictingCurlOption($options, 'CURLOPT_URL', 'the request URI'); + self::addConflictingCurlOption($options, 'CURLOPT_PORT', 'the request URI'); + self::addConflictingCurlOption($options, 'CURLOPT_CUSTOMREQUEST', 'the request method'); + self::addConflictingCurlOption($options, 'CURLOPT_HTTPGET', 'the request method'); + self::addConflictingCurlOption($options, 'CURLOPT_POST', 'the request method and body'); + self::addConflictingCurlOption($options, 'CURLOPT_PUT', 'the request method and body'); + self::addConflictingCurlOption($options, 'CURLOPT_NOBODY', 'the request method'); + self::addConflictingCurlOption($options, 'CURLOPT_UPLOAD', 'the request body'); + self::addConflictingCurlOption($options, 'CURLOPT_POSTFIELDS', 'the request body'); + self::addConflictingCurlOption($options, 'CURLOPT_READFUNCTION', 'the request body'); + self::addConflictingCurlOption($options, 'CURLOPT_SEEKFUNCTION', 'the request body'); + self::addConflictingCurlOption($options, 'CURLOPT_READDATA', 'the request body'); + self::addConflictingCurlOption($options, 'CURLOPT_INFILE', 'the request body'); + self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE', 'the request body'); + self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE_LARGE', 'the request body'); + self::addConflictingCurlOption($options, 'CURLOPT_HTTPHEADER', 'the request headers'); + self::addConflictingCurlOption($options, 'CURLOPT_USERAGENT', 'the request headers'); + self::addConflictingCurlOption($options, 'CURLOPT_REFERER', 'the request headers'); + self::addConflictingCurlOption($options, 'CURLOPT_HEADERFUNCTION', 'the "on_headers" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_WRITEFUNCTION', 'the "sink" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_FILE', 'the "sink" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT', 'the "timeout" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT_MS', 'the "timeout" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT', 'the "connect_timeout" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT_MS', 'the "connect_timeout" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_NOSIGNAL', 'the "timeout" or "connect_timeout" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_NOPROGRESS', 'the "progress" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_PROGRESSFUNCTION', 'the "progress" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_XFERINFOFUNCTION', 'the "progress" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_VERBOSE', 'the "debug" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_STDERR', 'the "debug" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_PROXY', 'the "proxy" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_NOPROXY', 'the "proxy" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_PROXYTYPE', 'the "proxy" request option with a scheme-prefixed URL'); + self::addConflictingCurlOption($options, 'CURLOPT_FOLLOWLOCATION', 'the "allow_redirects" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_MAXREDIRS', 'the "allow_redirects" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_POSTREDIR', 'the "allow_redirects" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS', 'the "allow_redirects" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS_STR', 'the "allow_redirects" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS', 'the "protocols" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS_STR', 'the "protocols" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_HTTP_VERSION', 'the request protocol version'); + self::addConflictingCurlOption($options, 'CURLOPT_PIPEWAIT', 'the "multiplex" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_IPRESOLVE', 'the "force_ip_resolve" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYPEER', 'the "verify" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYHOST', 'the "verify" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_CAINFO', 'the "verify" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_CAPATH', 'the "verify" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSLVERSION', 'the "crypto_method" or "crypto_method_max" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSLCERT', 'the "cert" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTPASSWD', 'the "cert" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTTYPE', 'the "cert_type" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSLKEY', 'the "ssl_key" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYPASSWD', 'the "ssl_key" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_KEYPASSWD', 'the "ssl_key" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYTYPE', 'the "ssl_key_type" request option'); + self::addConflictingCurlOption($options, 'CURLOPT_COOKIE', 'the "Cookie" request header or Guzzle cookie middleware'); + self::addConflictingCurlOption($options, 'CURLOPT_COOKIEFILE', 'Guzzle cookie middleware'); + self::addConflictingCurlOption($options, 'CURLOPT_COOKIEJAR', 'Guzzle cookie middleware'); + self::addConflictingCurlOption($options, 'CURLOPT_COOKIELIST', 'Guzzle cookie middleware'); + self::addConflictingCurlOption($options, 'CURLOPT_COOKIESESSION', 'Guzzle cookie middleware'); + + return $options; + } + + /** + * @return array + */ + private static function supportedCurlOptions(): array + { + static $options = null; + + if ($options !== null) { + return $options; + } + + $options = []; + + self::addSupportedCurlOption($options, 'CURLOPT_ADDRESS_SCOPE'); + self::addSupportedCurlOption($options, 'CURLOPT_CERTINFO'); + self::addSupportedCurlOption($options, 'CURLOPT_CONNECT_TO'); + self::addSupportedCurlOption($options, 'CURLOPT_DNS_CACHE_TIMEOUT'); + self::addSupportedCurlOption($options, 'CURLOPT_DNS_INTERFACE'); + self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP4'); + self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP6'); + self::addSupportedCurlOption($options, 'CURLOPT_DNS_SERVERS'); + self::addSupportedCurlOption($options, 'CURLOPT_DNS_SHUFFLE_ADDRESSES'); + self::addSupportedCurlOption($options, 'CURLOPT_ENCODING'); + self::addSupportedCurlOption($options, 'CURLOPT_FORBID_REUSE'); + self::addSupportedCurlOption($options, 'CURLOPT_FRESH_CONNECT'); + self::addSupportedCurlOption($options, 'CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS'); + self::addSupportedCurlOption($options, 'CURLOPT_HTTPAUTH'); + self::addSupportedCurlOption($options, 'CURLOPT_INTERFACE'); + self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORT'); + self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORTRANGE'); + self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_LIMIT'); + self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_TIME'); + self::addSupportedCurlOption($options, 'CURLOPT_MAXAGE_CONN'); + self::addSupportedCurlOption($options, 'CURLOPT_MAXCONNECTS'); + self::addSupportedCurlOption($options, 'CURLOPT_MAXLIFETIME_CONN'); + self::addSupportedCurlOption($options, 'CURLOPT_HTTPPROXYTUNNEL'); + self::addSupportedCurlOption($options, 'CURLOPT_PREREQFUNCTION'); + self::addSupportedCurlOption($options, 'CURLOPT_PROXYHEADER'); + self::addSupportedCurlOption($options, 'CURLOPT_PROXYUSERPWD'); + self::addSupportedCurlOption($options, 'CURLOPT_RESOLVE'); + self::addSupportedCurlOption($options, 'CURLOPT_SSL_CIPHER_LIST'); + self::addSupportedCurlOption($options, 'CURLOPT_SSL_EC_CURVES'); + self::addSupportedCurlOption($options, 'CURLOPT_TCP_FASTOPEN'); + self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPALIVE'); + self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPIDLE'); + self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPINTVL'); + self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPCNT'); + self::addSupportedCurlOption($options, 'CURLOPT_TCP_NODELAY'); + self::addSupportedCurlOption($options, 'CURLOPT_TLS13_CIPHERS'); + self::addSupportedCurlOption($options, 'CURLOPT_UNIX_SOCKET_PATH'); + self::addSupportedCurlOption($options, 'CURLOPT_USERPWD'); + + return $options; + } + + /** + * @param array $options + */ + private static function addSupportedCurlOption(array &$options, string $constant): void + { + if (!\defined($constant)) { + return; + } + + $value = \constant($constant); + if (\is_int($value)) { + $options[$value] = true; + } + } + + /** + * @param array $options + */ + private static function addConflictingCurlOption(array &$options, string $constant, ?string $replacement): void + { + if (!\defined($constant)) { + return; + } + + $value = \constant($constant); + if (\is_int($value)) { + $options[$value] = $replacement; + } + } + + private static function validateRequestUriScheme( + #[\SensitiveParameter] + RequestInterface $request + ): void { + $scheme = $request->getUri()->getScheme(); + if ($scheme === '') { + throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $request); + } + + if (!\in_array($scheme, ['http', 'https'], true)) { + throw new RequestException(\sprintf("The scheme '%s' is not supported.", Psr7\DiagnosticValue::escape($scheme)), $request); + } + } + + public function release( + #[\SensitiveParameter] + EasyHandle $easy + ): void { + $this->assertOpen(); + + $resource = $easy->handle; + unset($easy->handle); + + if ( + \count($this->handles) >= $this->maxHandles + || ($easy->proxyTunnelSignature !== null && $easy->proxyTunnelSignature !== $this->proxyTunnelOwner) + ) { + // Pool is full, or this handle belongs to a superseded tunnel + // owner (an async create/release overlap can hand a stale-owner + // handle back after a purge) - drop it instead of pooling it. + $this->discardHandle($resource); + + return; + } + + if ($easy->proxyTunnelSignature !== null) { + // A pooled handle now carries the current owner's tunnel. + $this->poolMayHoldTunnels = true; + } + + // Remove all callback functions as they can hold onto references and + // are not cleaned up by curl_reset. Using curl_setopt_array does not + // work for some reason, so removing each one individually. + $this->clearEasyHandleCallbacks($resource); + \curl_reset($resource); + $this->handles[] = $resource; + } + + /** + * Closes idle cURL handles owned by this factory. + * + * After closing, the factory is terminal and must not be reused. + */ + public function close(): void + { + $this->doClose(true); + } + + private function assertOpen(): void + { + if ($this->closed) { + // Programmer misuse (reusing a closed factory), not a transfer failure; + // intentionally a LogicException outside the GuzzleException hierarchy. + throw new \BadMethodCallException('Cannot use the cURL factory after it has been closed.'); + } + } + + private function doClose(bool $explicit): void + { + if ($this->closed) { + return; + } + + $this->closed = true; + $failure = null; + + try { + foreach ($this->handles as $id => $handle) { + try { + $this->discardHandle($handle); + } catch (\Throwable $e) { + if ($failure === null) { + $failure = $e; + } + } finally { + unset($this->handles[$id]); + } + } + } finally { + $this->shareMode = TransportSharing::NONE; + $this->shareHandle = null; + } + + if ($explicit && $failure !== null) { + throw $failure; + } + } + + /** + * @param resource|\CurlHandle $handle + */ + private function discardHandle( + #[\SensitiveParameter] + $handle + ): void { + $failure = null; + + try { + $this->clearEasyHandleCallbacks($handle); + } catch (\Throwable $e) { + $failure = $e; + } + + try { + if (PHP_VERSION_ID < 80000 && \is_resource($handle)) { + \curl_close($handle); + } + } catch (\Throwable $e) { + if ($failure === null) { + $failure = $e; + } + } + + if ($failure !== null) { + throw $failure; + } + } + + /** + * @param resource|\CurlHandle $handle + */ + private function clearEasyHandleCallbacks( + #[\SensitiveParameter] + $handle + ): void { + curl_setopt($handle, \CURLOPT_HEADERFUNCTION, null); + curl_setopt($handle, \CURLOPT_READFUNCTION, null); + curl_setopt($handle, \CURLOPT_WRITEFUNCTION, null); + curl_setopt($handle, \CURLOPT_PROGRESSFUNCTION, null); + + if (\defined('CURLOPT_PREREQFUNCTION')) { + curl_setopt($handle, (int) \constant('CURLOPT_PREREQFUNCTION'), null); + } + + if (\defined('CURLOPT_SEEKFUNCTION')) { + curl_setopt($handle, (int) \constant('CURLOPT_SEEKFUNCTION'), null); + } + + if (\defined('CURLOPT_XFERINFOFUNCTION')) { + curl_setopt($handle, (int) \constant('CURLOPT_XFERINFOFUNCTION'), null); + } + } + + /** + * Completes a cURL transaction, either returning a response promise or a + * rejected promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + * @param CurlFactoryInterface $factory Dictates how the handle is released + * + * @return PromiseInterface + */ + public static function finish( + callable $handler, + #[\SensitiveParameter] + EasyHandle $easy, + CurlFactoryInterface $factory + ): PromiseInterface { + /** @var (callable(TransferStats): mixed)|null $onStats */ + $onStats = $easy->options['on_stats'] ?? null; + $stats = $onStats !== null ? self::createStats($easy) : null; + + if (self::shouldFinishWithError($easy)) { + return self::finishError($handler, $easy, $factory, $stats, $onStats); + } + + /** @var ResponseInterface $response */ + $response = $easy->response; + + // Return the response if it is present and there is no error. + $factory->release($easy); + + // Rewind the body of the response if possible. Failures here are local + // response finalization errors, not response-transfer failures. + $body = $response->getBody(); + try { + if ($body->isSeekable()) { + $body->rewind(); + } + } catch (\Exception $e) { + $reason = new ResponseException( + $e->getMessage() !== '' ? $e->getMessage() : 'Failed to rewind the response body', + $easy->request, + $response, + $e + ); + + if ($onStats !== null && $stats !== null) { + // Report the ResponseException rather than errno 0 to match the + // stream handler's response finalization stats. + $onStats(new TransferStats( + $easy->request, + $response, + $stats->getTransferTime(), + $reason, + $stats->getHandlerStats() + )); + } + + /** @var PromiseInterface */ + return P\Create::rejectionFor($reason); + } + + if (isset($easy->options['on_trailers'])) { + /** @var callable(array>, ResponseInterface, RequestInterface): mixed $onTrailers */ + $onTrailers = $easy->options['on_trailers']; + + try { + $onTrailers(self::headersFromTrailerLines($easy->trailers), $response, $easy->request); + } catch (\Throwable $e) { + $reason = new ResponseException( + 'An error was encountered during the on_trailers event', + $easy->request, + $response, + $e + ); + + if ($onStats !== null && $stats !== null) { + // Report the ResponseException rather than errno 0 to match + // the response finalization stats above. + $onStats(new TransferStats( + $easy->request, + $response, + $stats->getTransferTime(), + $reason, + $stats->getHandlerStats() + )); + } + + /** @var PromiseInterface */ + return P\Create::rejectionFor($reason); + } + } + + if ($onStats !== null && $stats !== null) { + $onStats($stats); + } + + /** @var PromiseInterface */ + return P\Create::promiseFor($response); + } + + private static function createStats( + #[\SensitiveParameter] + EasyHandle $easy + ): TransferStats { + $curlStats = \curl_getinfo($easy->handle); + $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME); + + if ($easy->createResponseException) { + $curlStats = [ + 'total_time' => $curlStats['total_time'], + 'appconnect_time' => $curlStats['appconnect_time'], + ]; + } + + $handlerErrorData = $easy->responseHeaderException ?? $easy->responseBodySizeException ?? $easy->errno; + + return new TransferStats( + $easy->request, + $easy->response, + $curlStats['total_time'], + $handlerErrorData, + $curlStats + ); + } + + /** + * @param callable(RequestInterface, array): PromiseInterface $handler + * @param (callable(TransferStats): mixed)|null $onStats + * + * @return PromiseInterface + */ + private static function finishError( + callable $handler, + #[\SensitiveParameter] + EasyHandle $easy, + CurlFactoryInterface $factory, + ?TransferStats $stats, + ?callable $onStats + ): PromiseInterface { + // Get error information and release the handle to the factory. + $ctx = self::createErrorContext($easy); + + if (self::shouldRetryFailedRewind($easy)) { + // Release after dispatching the retry so the replacement + // transfer cannot reuse this native handle ID. + try { + if ($onStats !== null && $stats !== null) { + $onStats($stats); + } + + return self::retryFailedRewind($handler, $easy, $ctx); + } finally { + $factory->release($easy); + } + } + + $factory->release($easy); + + if ($onStats !== null && $stats !== null) { + $onStats($stats); + } + + if (self::isResponseRewindFailure($easy)) { + $status = $easy->response !== null ? $easy->response->getStatusCode() : 0; + $ctx['error'] = $status === 401 || $status === 407 + ? 'The server issued an authentication challenge ' + .'after the request body had already been sent, and the body ' + .'could not be rewound to resend it. The request was not ' + .'retried because a retry replays the same challenge. See ' + .'https://bugs.php.net/bug.php?id=47204 for more information.' + : 'The server responded after the request body had already ' + .'been sent, and the body could not be rewound for ' + .'libcurl\'s automatic retry. The request was not retried ' + .'because a retry replays the same response. See ' + .'https://bugs.php.net/bug.php?id=47204 for more information.'; + } + + return self::createRejection($easy, $ctx); + } + + private static function shouldFinishWithError(EasyHandle $easy): bool + { + return !$easy->response + || $easy->errno !== 0 + || self::hasLocalFailure($easy); + } + + private static function hasLocalFailure(EasyHandle $easy): bool + { + return $easy->bodyReadTimeoutException !== null + || $easy->bodyRewindTimeoutException !== null + || $easy->bodyRewindException !== null + || $easy->bodyReadException !== null + || $easy->responseHeaderException !== null + || $easy->sinkWriteTimeoutException !== null + || $easy->sinkWriteException !== null + || $easy->sinkWriteIncomplete + || $easy->responseBodySizeException !== null; + } + + private static function shouldRetryFailedRewind(EasyHandle $easy): bool + { + if (self::hasLocalFailure($easy)) { + return false; + } + + if (self::isResponseRewindFailure($easy)) { + // Re-issuing the identical request replays the same response and + // the same in-transfer rewind, so retrying is futile and the + // received response is surfaced instead. + return false; + } + + // Two transfer outcomes warrant rewinding the body and retrying: + // + // - errno === CURLE_SEND_FAIL_REWIND (65): libcurl needed to rewind an + // already-partially-sent upload to resend it on a reused connection + // that died before any response arrived, but could not. PHP builds + // without CURLOPT_SEEKFUNCTION register no seek callback for a + // streamed request body (https://bugs.php.net/bug.php?id=47204); + // builds with it can still report 65 when the body is not seekable. + // + // - errno === 0: libcurl reported success yet no usable response + // reached us. This is the legacy curl_multi silent-failure variant of + // the same rewind problem. libcurl 7.61.1 fixed it to surface as + // CURLE_SEND_FAIL_REWIND instead (curl/curl@d6cf930), so this arm is + // only load-bearing for libcurl < 7.61.1 and may be removed once the + // minimum supported libcurl is >= 7.61.1. + return $easy->errno === 0 || $easy->errno === self::CURLE_SEND_FAIL_REWIND; + } + + /** + * Whether the transfer failed because libcurl could not rewind the + * request body to resend it in reply to a response, such as a 401 or + * 407 during multi-pass authentication, or a 417 that makes libcurl + * retry an Expect: 100-continue upload without the expectation. Rewinds + * for replays that follow no response, such as a reused connection that + * died or a refused HTTP/2 stream, retry through + * shouldRetryFailedRewind() instead. Followed redirects also rewind, + * but the built-in handlers never enable them. + */ + private static function isResponseRewindFailure(EasyHandle $easy): bool + { + return $easy->errno === self::CURLE_SEND_FAIL_REWIND + && $easy->response !== null + && !self::hasLocalFailure($easy); + } + + private static function createErrorContext(EasyHandle $easy): array + { + return [ + 'errno' => $easy->errno, + 'error' => \curl_error($easy->handle), + ]; + } + + /** + * @return PromiseInterface + */ + private static function createRejection( + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array $ctx, + #[\SensitiveParameter] + ?\Throwable $previous = null + ): PromiseInterface { + if ($easy->createResponseException) { + /** @var PromiseInterface */ + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered while creating the response', + $easy->request, + 0, + $easy->createResponseException + ) + ); + } + + if ($easy->responseHeaderException) { + /** @var PromiseInterface */ + return P\Create::rejectionFor($easy->responseHeaderException); + } + + // If an exception was encountered during the onHeaders event, then + // return a rejected promise that wraps that exception. + if ($easy->onHeadersException) { + return self::createRequestOrResponseRejection( + $easy, + 'An error was encountered during the on_headers event', + $easy->onHeadersException + ); + } + + if ($easy->progressException) { + return self::createRequestOrResponseRejection( + $easy, + 'An error was encountered during the progress event', + $easy->progressException + ); + } + + if ($easy->bodyReadTimeoutException) { + // Reading the request body stalled, which is a caller-stream failure. + return self::createRequestOrResponseRejection( + $easy, + 'Timed out while reading the request body', + $easy->bodyReadTimeoutException + ); + } + + if ($easy->bodyRewindTimeoutException) { + // Rewinding the request body stalled, which is a caller-stream failure. + return self::createRequestOrResponseRejection( + $easy, + 'Timed out while rewinding the request body', + $easy->bodyRewindTimeoutException + ); + } + + if ($easy->bodyRewindException) { + $message = $easy->bodyRewindException->getMessage() !== '' + ? $easy->bodyRewindException->getMessage() + : 'Failed to rewind the request body'; + + return self::createRequestOrResponseRejection($easy, $message, $easy->bodyRewindException); + } + + if ($easy->bodyReadException) { + $message = $easy->bodyReadException->getMessage() !== '' + ? $easy->bodyReadException->getMessage() + : 'Failed to read the request body'; + + return self::createRequestOrResponseRejection($easy, $message, $easy->bodyReadException); + } + + if ($easy->sinkWriteTimeoutException) { + // Writing the response body to the caller's sink stalled, which is a + // caller-stream failure. + return self::createRequestOrResponseRejection( + $easy, + 'Timed out while writing the response body', + $easy->sinkWriteTimeoutException + ); + } + + if ($easy->sinkWriteException) { + $message = $easy->sinkWriteException->getMessage() !== '' + ? $easy->sinkWriteException->getMessage() + : 'Failed to write the response body'; + + return self::createRequestOrResponseRejection($easy, $message, $easy->sinkWriteException); + } + + if ($easy->sinkWriteIncomplete) { + return self::createRequestOrResponseRejection($easy, 'Unable to write to stream'); + } + + if ($easy->responseBodySizeException) { + return self::createRequestOrResponseRejection( + $easy, + $easy->responseBodySizeException->getMessage(), + $easy->responseBodySizeException + ); + } + + if ($easy->progressAborted && $easy->errno === \CURLE_ABORTED_BY_CALLBACK) { + return self::createRequestOrResponseRejection( + $easy, + 'The transfer was aborted by the progress callback' + ); + } + + $uri = $easy->request->getUri(); + + $sanitizedError = self::sanitizeCurlError($ctx['error'] ?? '', $uri, $easy->effectiveProxy); + + $message = \sprintf( + 'cURL error %s: %s (%s)', + $ctx['errno'], + $sanitizedError, + 'see https://curl.se/libcurl/c/libcurl-errors.html' + ); + + if ('' !== $sanitizedError) { + $safeUri = Psr7\UriRedactor::redactUriForMessage($uri); + if ($safeUri !== '' && false === \strpos($sanitizedError, $safeUri)) { + $message .= \sprintf(' for %s', $safeUri); + } + } + + if ($easy->errno === \CURLE_OPERATION_TIMEOUTED) { + if ($easy->response !== null) { + $error = new ResponseTimeoutException($message, $easy->request, $easy->response, $previous); + } elseif (self::isConnectTimeoutError($ctx['error'] ?? '')) { + $error = new ConnectTimeoutException($message, $easy->request, $previous); + } else { + $error = new NetworkTimeoutException($message, $easy->request, $previous); + } + } elseif ($easy->response) { + $error = self::isResponseTransferError($easy->errno) + ? new ResponseTransferException($message, $easy->request, $easy->response, $previous) + : new ResponseException($message, $easy->request, $easy->response, $previous); + } elseif (self::isConnectionError($easy->errno)) { + $error = new ConnectException($message, $easy->request, $previous); + } elseif (self::isNetworkError($easy->errno)) { + $error = new NetworkException($message, $easy->request, $previous); + } else { + $error = new RequestException($message, $easy->request, 0, $previous); + } + + /** @var PromiseInterface */ + return P\Create::rejectionFor($error); + } + + /** + * @return PromiseInterface + */ + private static function createRequestOrResponseRejection( + #[\SensitiveParameter] + EasyHandle $easy, + string $message, + #[\SensitiveParameter] + ?\Throwable $previous = null + ): PromiseInterface { + if ($easy->response !== null) { + /** @var PromiseInterface */ + return P\Create::rejectionFor( + new ResponseException($message, $easy->request, $easy->response, $previous) + ); + } + + /** @var PromiseInterface */ + return P\Create::rejectionFor( + new RequestException($message, $easy->request, 0, $previous) + ); + } + + private static function isConnectionError(int $errno): bool + { + return isset(self::CURL_CONNECTION_ERRORS[$errno]); + } + + private static function isNetworkError(int $errno): bool + { + return isset(self::CURL_NETWORK_ERRORS[$errno]); + } + + private static function isResponseTransferError(int $errno): bool + { + return self::isConnectionError($errno) + || self::isNetworkError($errno) + || isset(self::CURL_RESPONSE_TRANSFER_ERRORS[$errno]); + } + + private static function isConnectTimeoutError(string $error): bool + { + if ('' === $error) { + return false; + } + + foreach (self::CURL_CONNECT_TIMEOUT_ERRORS as $connectTimeoutError) { + if (Psr7\Utils::caselessContains($error, $connectTimeoutError)) { + return true; + } + } + + return Psr7\Utils::caselessContains($error, 'Failed to resolve') + && Psr7\Utils::caselessContains($error, 'timeout'); + } + + private static function sanitizeCurlError( + #[\SensitiveParameter] + string $error, + #[\SensitiveParameter] + UriInterface $uri, + #[\SensitiveParameter] + ?string $proxy = null + ): string { + if ('' === $error) { + return $error; + } + + $error = self::redactProxyUserInfo($error, $proxy); + + return UriDiagnostic::redactInMessage($error, $uri); + } + + private static function redactProxyUserInfo( + #[\SensitiveParameter] + string $error, + #[\SensitiveParameter] + ?string $proxy + ): string { + if ($proxy === null || $proxy === '') { + return $error; + } + + return Psr7\UriRedactor::redactUserInfoInString($error, $proxy); + } + + /** + * @param array $conf + */ + private function forceFreshConnectionForAuthenticatedProxy( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array &$conf + ): void { + $proxy = self::getEffectiveProxy($conf); + + if ( + $proxy === null + || (!self::requiresFreshConnectionForAuthenticatedProxy($request, $proxy, $conf) + && !$this->isOpaqueShareAnonymousProxyTunnel($request, $proxy, $conf)) + ) { + return; + } + + if ($this->shareMode === TransportSharing::PERSISTENT_REQUIRE) { + throw new InvalidArgumentException(self::PERSISTENT_REQUIRE_FRESH_PROXY_TUNNEL_MESSAGE); + } + + $conf[\CURLOPT_FRESH_CONNECT] = true; + $conf[\CURLOPT_FORBID_REUSE] = true; + } + + /** + * @param array $conf + */ + private function isOpaqueShareAnonymousProxyTunnel(RequestInterface $request, string $proxy, array $conf): bool + { + if (!$this->opaqueShareConnectionCache || !CurlVersion::supportsShareConnectionCaches()) { + return false; + } + + if (!self::usesProxyTunnel($request, $conf) || !self::isHttpProxyForConnectionReuse($proxy, $conf)) { + return false; + } + + if ( + self::hasCurlProxyAuthorizationHeader($conf) + || self::hasCurlProxyTlsCredentials($conf) + || self::hasCurlProxyCredentials($conf) + ) { + return false; + } + + $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy; + $proxyParts = \parse_url($proxyForParsing); + if ( + \is_array($proxyParts) + && (\array_key_exists('user', $proxyParts) || \array_key_exists('pass', $proxyParts)) + ) { + return false; + } + + // From libcurl 7.57.0 an opaque share handle can own a connection + // cache, and a tunnel seeded there with a literal Proxy-Authorization + // header is never keyed on credentials, so an anonymous request could + // inherit it on every later libcurl version. Requests carrying + // recognized credential state keep the version-gated channel + // safeguards in requiresFreshConnectionForAuthenticatedProxy(). + return true; + } + + /** + * @param array $conf + */ + private static function getEffectiveProxy(array $conf): ?string + { + if (!\array_key_exists(\CURLOPT_PROXY, $conf)) { + return null; + } + + $proxy = $conf[\CURLOPT_PROXY]; + + return \is_string($proxy) && $proxy !== '' ? $proxy : null; + } + + /** + * @param array $conf + */ + private static function normalizeCurlHeaderOptions( + #[\SensitiveParameter] + array &$conf + ): void { + $options = [\CURLOPT_HTTPHEADER => 'CURLOPT_HTTPHEADER']; + if (\defined('CURLOPT_PROXYHEADER')) { + $options[(int) \constant('CURLOPT_PROXYHEADER')] = 'CURLOPT_PROXYHEADER'; + } + + foreach ($options as $option => $label) { + if (!\array_key_exists($option, $conf) || !\is_array($conf[$option])) { + continue; + } + + $normalized = []; + foreach ($conf[$option] as $key => $entry) { + if (\is_object($entry) && \method_exists($entry, '__toString')) { + $entry = (string) $entry; + } elseif (!\is_string($entry)) { + throw new InvalidArgumentException(\sprintf('%s entries must be strings or stringable objects.', $label)); + } + + if (\strpbrk($entry, "\r\n") !== false) { + throw new InvalidArgumentException(\sprintf('%s entries must not contain a carriage return or line feed.', $label)); + } + + $normalized[$key] = $entry; + } + + $conf[$option] = $normalized; + } + } + + /** + * @param array $conf + */ + private static function requiresFreshConnectionForAuthenticatedProxy(RequestInterface $request, string $proxy, array $conf): bool + { + // SOCKS authentication binds an identity to the connection itself, and + // below 7.69.0 an opaque configured share may already contain a SOCKS + // connection whose credential state Guzzle cannot inspect. Isolate + // authenticated and anonymous requests so neither can inherit it. + if (self::isSocksProxy($proxy, $conf)) { + return !CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse(); + } + + if (!self::usesProxyTunnel($request, $conf) || !self::isHttpProxyForConnectionReuse($proxy, $conf)) { + return false; + } + + $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy; + $proxyParts = \parse_url($proxyForParsing); + if (!\is_array($proxyParts)) { + return false; + } + + if (self::hasCurlProxyAuthorizationHeader($conf)) { + return true; + } + + // A proxy client certificate or TLS-SRP authenticates the client to the + // HTTPS proxy at the TLS layer; libcurl ignored TLS-SRP before 7.83.1 + // (CVE-2022-27782), so an old build can reuse a tunnel across those + // identities. Force a fresh one, as the non-share signature path does. + // See docs/contributing/curl-connection-reuse.md. + if ( + !CurlVersion::supportsProxyTlsCredentialAwareConnectionReuse() + && self::hasCurlProxyTlsCredentials($conf) + ) { + return true; + } + + if (CurlVersion::supportsProxyCredentialAwareConnectionReuse()) { + return false; + } + + return \array_key_exists('user', $proxyParts) + || \array_key_exists('pass', $proxyParts) + || self::hasCurlProxyCredentials($conf); + } + + /** + * @param array $conf + */ + private static function applyProxyConnectHeaderSuppression( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array &$conf + ): void { + $proxy = $conf[\CURLOPT_PROXY] ?? null; + + if (!\is_string($proxy) + || $proxy === '' + || self::isSocksProxy($proxy, $conf) + || !self::usesProxyTunnel($request, $conf) + ) { + return; + } + + if (!CurlVersion::supportsProxyTunneling()) { + throw new RequestException('Tunneling requests through an HTTP proxy is not supported by the installed libcurl; libcurl 7.54.0 or newer is required.', $request); + } + + // Keep the proxy CONNECT reply out of the header callback so a + // tunnelled transfer failure is not misclassified as a response + // failure carrying the proxy's interim 200. + $conf[(int) \constant('CURLOPT_SUPPRESS_CONNECT_HEADERS')] = true; + } + + /** + * @param array $conf + */ + private static function usesProxyTunnel(RequestInterface $request, array $conf): bool + { + $scheme = $request->getUri()->getScheme(); + + if ('https' === $scheme) { + return true; + } + + // An HTTP proxy auto-switches to a CONNECT tunnel when CONNECT_TO + // redirects the origin, so an http:// target with it set tunnels too. + if ('http' === $scheme && self::hasCurlConnectTo($conf)) { + return true; + } + + return \defined('CURLOPT_HTTPPROXYTUNNEL') + && \array_key_exists((int) \constant('CURLOPT_HTTPPROXYTUNNEL'), $conf) + && (bool) $conf[(int) \constant('CURLOPT_HTTPPROXYTUNNEL')]; + } + + /** + * @param array $conf + */ + private static function hasCurlConnectTo(array $conf): bool + { + if (!\defined('CURLOPT_CONNECT_TO')) { + return false; + } + + $option = (int) \constant('CURLOPT_CONNECT_TO'); + if (!\array_key_exists($option, $conf)) { + return false; + } + + $value = $conf[$option]; + + return \is_array($value) + ? $value !== [] + : $value !== null && $value !== false && $value !== ''; + } + + /** + * @param array $conf + */ + private static function isHttpProxyForConnectionReuse(string $proxy, array $conf): bool + { + if (\strpos($proxy, '://') !== false) { + $proxyParts = \parse_url($proxy); + if (!\is_array($proxyParts) || !isset($proxyParts['scheme'])) { + return false; + } + + $proxyScheme = Psr7\Utils::asciiToLower($proxyParts['scheme']); + + return $proxyScheme === 'http' || $proxyScheme === 'https'; + } + + return !self::isSocksProxyType($conf[\CURLOPT_PROXYTYPE] ?? null); + } + + private static function proxyScheme(string $proxy): ?string + { + $position = \strpos($proxy, '://'); + + return $position === false ? null : Psr7\Utils::asciiToLower(\substr($proxy, 0, $position)); + } + + /** + * @param array $conf + */ + private static function isSocksProxy(string $proxy, array $conf): bool + { + $scheme = self::proxyScheme($proxy); + if ($scheme !== null) { + if (\in_array($scheme, ['socks', 'socks4', 'socks4a', 'socks5', 'socks5h'], true)) { + return true; + } + + // libcurl preserves a raw SOCKS CURLOPT_PROXYTYPE behind an http + // scheme, while every other scheme overrides the proxy type. + if ($scheme !== 'http') { + return false; + } + } + + return self::isSocksProxyType($conf[\CURLOPT_PROXYTYPE] ?? null); + } + + /** + * Computes the connection-reuse section signature for a SOCKS proxy. + * libcurl compares SOCKS credentials on connection reuse from 7.69.0 (curl + * #4835), so no sectioning is needed there. Older libcurl matches a SOCKS + * proxy by type, host, and port only, so every SOCKS request is sectioned + * by its credential state; hashing the credential-less state too keeps an + * unauthenticated request from inheriting an authenticated connection. See + * docs/contributing/curl-connection-reuse.md. + * + * @param array $conf + */ + private static function socksProxySignature( + #[\SensitiveParameter] + string $proxy, + #[\SensitiveParameter] + array $conf + ): ?string { + if (CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse()) { + return null; + } + + $credentialState = []; + foreach (['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD', 'CURLOPT_PROXYTYPE'] as $name) { + $credentialState[$name] = \defined($name) + ? ($conf[(int) \constant($name)] ?? null) + : null; + } + + return \hash('sha256', \serialize(['socks', $proxy, $credentialState])); + } + + /** + * @param mixed $proxyType + */ + private static function isSocksProxyType($proxyType): bool + { + if (!\is_int($proxyType)) { + return false; + } + + foreach ([ + 'CURLPROXY_SOCKS4' => 4, + 'CURLPROXY_SOCKS5' => 5, + 'CURLPROXY_SOCKS4A' => 6, + 'CURLPROXY_SOCKS5_HOSTNAME' => 7, + ] as $name => $fallback) { + $value = \defined($name) ? (int) \constant($name) : $fallback; + if ($proxyType === $value) { + return true; + } + } + + return false; + } + + /** + * @param array $conf + */ + private static function hasCurlProxyCredentials(array $conf): bool + { + foreach (['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD'] as $option) { + if (\defined($option) && \array_key_exists((int) \constant($option), $conf)) { + return true; + } + } + + return false; + } + + /** + * @param array $conf + */ + private static function hasCurlProxyTlsCredentials(array $conf): bool + { + foreach ([ + 'CURLOPT_PROXY_SSLCERT', + 'CURLOPT_PROXY_SSLCERT_BLOB', + 'CURLOPT_PROXY_TLSAUTH_USERNAME', + 'CURLOPT_PROXY_TLSAUTH_PASSWORD', + ] as $option) { + if (\defined($option) && \array_key_exists((int) \constant($option), $conf)) { + return true; + } + } + + return false; + } + + /** + * @param array $conf + */ + private static function hasCurlProxyAuthorizationHeader(array $conf): bool + { + return self::curlProxyAuthorizationHeaderValues($conf) !== []; + } + + /** + * Collects the first-class Proxy-Authorization request header lines that + * Guzzle configures in cURL's proxy-only header channel. Empty values use + * cURL's semicolon form so they suppress an automatically generated proxy + * authorization field without carrying a credential. getHeaderLine() is + * deliberately not used: comma-joining multiple credentials would change + * their wire representation and connection signature. + * + * @return list + */ + private static function managedProxyAuthorizationHeaderLines( + #[\SensitiveParameter] + RequestInterface $request + ): array { + $headers = []; + + foreach ($request->getHeader('Proxy-Authorization') as $value) { + $headers[] = $value === '' + ? 'Proxy-Authorization;' + : 'Proxy-Authorization: '.$value; + } + + return $headers; + } + + /** + * Routes the managed Proxy-Authorization lines and any caller-provided + * proxy headers through cURL's proxy-only header channel without + * consulting Guzzle's route prediction, so no proxy-classification + * discrepancy can disclose them to an origin server. libcurl uses the + * proxy-only list only for HTTP requests it actually sends to a proxy, so + * direct, no-proxy-bypassed, and SOCKS transfers never deliver it. + * + * @param array $conf + * @param list $managedHeaders + */ + private static function applyProxyAuthorizationHeaderHandling( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array &$conf, + #[\SensitiveParameter] + array $managedHeaders + ): void { + if ($managedHeaders !== [] || self::hasCurlProxyHeaderOption($conf)) { + if (!CurlVersion::supportsProxyHeaderSeparation()) { + throw new RequestException('Proxy headers require libcurl 7.37.0 or newer built with proxy header separation support.', $request); + } + + if ($managedHeaders !== []) { + self::appendCurlProxyHeaders($conf, $managedHeaders); + } + + $conf[(int) \constant('CURLOPT_HEADEROPT')] = (int) \constant('CURLHEADER_SEPARATE'); + } + + // Keep the conservative CONNECT header-list separation for effective + // HTTP(S) proxy tunnels without a proxy header: on libcurl + // 7.37.0-7.42.0 the default is CURLHEADER_UNIFIED. This broad route + // approximation never decides managed credential routing. + $proxy = self::getEffectiveProxy($conf); + if ( + CurlVersion::supportsProxyHeaderSeparation() + && $proxy !== null + && self::isHttpProxyForConnectionReuse($proxy, $conf) + && self::usesProxyTunnel($request, $conf) + ) { + $conf[(int) \constant('CURLOPT_HEADEROPT')] = (int) \constant('CURLHEADER_SEPARATE'); + } + } + + /** + * @param array $conf + * @param list $headers + */ + private static function appendCurlProxyHeaders( + #[\SensitiveParameter] + array &$conf, + #[\SensitiveParameter] + array $headers + ): void { + $option = (int) \constant('CURLOPT_PROXYHEADER'); + + if (\array_key_exists($option, $conf)) { + if (!\is_array($conf[$option])) { + throw new InvalidArgumentException('CURLOPT_PROXYHEADER must be an array when a Proxy-Authorization request header is routed to the proxy header channel.'); + } + + $headers = \array_merge($conf[$option], $headers); + } + + $conf[$option] = $headers; + } + + /** + * @param array $conf + */ + private static function hasCurlProxyHeaderOption(array $conf): bool + { + return \defined('CURLOPT_PROXYHEADER') + && \array_key_exists((int) \constant('CURLOPT_PROXYHEADER'), $conf); + } + + /** + * @param mixed[] $headers + * + * @return list + */ + private static function proxyAuthorizationHeaderValuesFromList(array $headers): array + { + $values = []; + + foreach ($headers as $header) { + if (!\is_string($header)) { + continue; + } + + $position = \strpos($header, ':'); + if ($position === false) { + continue; + } + + if (!Psr7\Utils::caselessEquals(\trim(\substr($header, 0, $position), " \n\r\t\0\x0B"), 'Proxy-Authorization')) { + continue; + } + + $value = \trim(\substr($header, $position + 1), " \n\r\t\0\x0B"); + if ($value !== '') { + $values[] = $value; + } + } + + return $values; + } + + /** + * Computes the connection-reuse section signature for a proxy tunnel or + * SOCKS proxy, or null when the request does not require sectioning. + * + * @param array $conf + */ + private static function proxyTunnelSignature( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $conf + ): ?string { + $proxy = self::getEffectiveProxy($conf); + if ($proxy === null) { + return null; + } + + // SOCKS authentication binds an identity to the connection itself, for + // plain http:// requests as much as https://, so it sections ahead of + // the CONNECT tunnel domain checks. + if (self::isSocksProxy($proxy, $conf)) { + return self::socksProxySignature($proxy, $conf); + } + + if ( + !self::usesProxyTunnel($request, $conf) + || !self::isHttpProxyForConnectionReuse($proxy, $conf) + ) { + return null; + } + + $headerAuth = self::curlProxyAuthorizationHeaderValues($conf); + if ($headerAuth === [] && CurlVersion::supportsProxyCredentialAwareConnectionReuse()) { + // libcurl keys reuse on parsed proxy credentials only from 8.19.0, + // trusted from 8.20.0 (PROXY_CREDENTIAL_REUSE_VERSION); a literal + // Proxy-Authorization header is never keyed and always sections. + // See docs/contributing/curl-connection-reuse.md. + return self::DELEGATED_PROXY_TUNNEL_OWNER; + } + + // Hash every proxy channel an old libcurl might not key reuse on. A + // changed signature only forces a fresh connection, never relaxes + // reuse, so over-covering is always safe; under-covering leaks. Proxy + // credentials are the channel CVE-2026-3784 missed; the proxy-TLS + // options are load-bearing on builds before the proxy-TLS reuse fixes + // (the proxy client cert is keyed from 7.52.0, libcurl's first + // HTTPS-proxy release; CVE-2016-5420 (7.50.1) is only the origin-cert + // precedent; TLS-SRP from 7.83.1, CVE-2022-27782) and harmless after. + // The private-key file and passphrase are hashed on this non-delegated + // path too, as fallback hardening: libcurl's mTLS private-key matching + // on reuse was incomplete before 8.21.0 (CVE-2026-8932). This does not + // cover the delegated path (the early return above) or configured share + // handles, so it is not a complete pre-8.21.0 mitigation. The key blob + // and cert/key type encodings (PROXY_SSLKEY_BLOB, PROXY_SSLKEYTYPE, + // PROXY_SSLCERTTYPE) are not hashed and are an accepted residual. See + // docs/contributing/curl-connection-reuse.md. + $credentialState = []; + foreach ([ + 'CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD', + 'CURLOPT_PROXYTYPE', + 'CURLOPT_PROXY_SSLCERT', 'CURLOPT_PROXY_SSLCERT_BLOB', 'CURLOPT_PROXY_SSLKEY', + 'CURLOPT_PROXY_KEYPASSWD', 'CURLOPT_PROXY_TLSAUTH_USERNAME', + 'CURLOPT_PROXY_TLSAUTH_PASSWORD', 'CURLOPT_PROXY_SSLVERSION', + ] as $name) { + $credentialState[$name] = \defined($name) + ? ($conf[(int) \constant($name)] ?? null) + : null; + } + + return \hash('sha256', \serialize([$proxy, $credentialState, $headerAuth])); + } + + /** + * @param array $conf + * + * @return list + */ + private static function curlProxyAuthorizationHeaderValues(array $conf): array + { + if (!\defined('CURLOPT_PROXYHEADER')) { + return []; + } + + $option = (int) \constant('CURLOPT_PROXYHEADER'); + if (!\array_key_exists($option, $conf)) { + return []; + } + + $headers = $conf[$option]; + if (!\is_array($headers)) { + return []; + } + + return self::proxyAuthorizationHeaderValuesFromList($headers); + } + + private function discardIdleHandles(): void + { + foreach ($this->handles as $id => $handle) { + try { + // Best effort: a cleanup hiccup on a superseded idle handle + // must not abort the unrelated request that triggered the purge. + $this->discardHandle($handle); + } catch (\Throwable $e) { + // Ignored. + } finally { + unset($this->handles[$id]); + } + } + } + + /** + * @return array + */ + private function getDefaultConf( + #[\SensitiveParameter] + EasyHandle $easy + ): array { + $uri = $easy->request->getUri(); + $protocols = Protocols::normalize($easy->options['protocols'] ?? ['http', 'https']); + $scheme = $uri->getScheme(); + if (!\in_array($scheme, $protocols, true)) { + throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', Psr7\DiagnosticValue::escape($scheme)), $easy->request); + } + + if ($uri->getHost() === '') { + throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $easy->request); + } + + $conf = [ + '_headers' => $easy->request->getHeaders(), + \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), + \CURLOPT_URL => (string) $uri->withFragment(''), + \CURLOPT_RETURNTRANSFER => false, + \CURLOPT_HEADER => false, + \CURLOPT_CONNECTTIMEOUT_MS => self::DEFAULT_CONNECT_TIMEOUT_MS, + ]; + + if (CurlVersion::supportsProtocolsStr()) { + $conf[(int) \constant('CURLOPT_PROTOCOLS_STR')] = \implode(',', $protocols); + } else { + $conf[\CURLOPT_PROTOCOLS] = self::curlProtocolMask($protocols); + } + + $version = $easy->request->getProtocolVersion(); + $multiplex = self::normalizeMultiplex($easy->options); + + if ('3' === $version || '3.0' === $version) { + if (!\defined('CURL_HTTP_VERSION_3')) { + throw new RequestException('HTTP/3 is not supported by this cURL installation.', $easy->request); + } + + $proxy = ProxyEnv::resolveProxySelection($easy->request->getUri(), $easy->options['proxy'] ?? null); + + if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + self::assertSelectedProxySupported($proxy->getProxy(), $easy->request); + + if ($proxy->hasProxy()) { + throw new RequestException('Required multiplexing cannot be guaranteed for HTTP/3 requests sent through a proxy.', $easy->request); + } + if (!CurlVersion::supportsRequiredHttp3Multiplex()) { + throw new RequestException('Required multiplexing for HTTP/3 needs libcurl 8.13.0 or newer built with HTTP/3 support.', $easy->request); + } + // HTTP/3 or fail: required multiplexing never downgrades, not + // even to HTTP/2. + $conf[\CURLOPT_HTTP_VERSION] = (int) \constant('CURL_HTTP_VERSION_3ONLY'); + } else { + $conf[\CURLOPT_HTTP_VERSION] = $proxy->hasProxy() + ? (CurlVersion::supportsHttp2() ? \CURL_HTTP_VERSION_2_0 : \CURL_HTTP_VERSION_1_1) + : (int) \constant('CURL_HTTP_VERSION_3'); + } + } elseif ('2' === $version || '2.0' === $version) { + if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + self::assertRequiredMultiplexSupported($easy); + // New HTTP/2 connections cannot negotiate HTTP/1.x here, and + // the 8.14.0 floor's version-aware reuse matching keeps + // reused connections on HTTP/2 as well. + $conf[\CURLOPT_HTTP_VERSION] = (int) \constant('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE'); + } else { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; + } + } elseif ('1.1' === $version) { + if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new RequestException(\sprintf('The "multiplex" request option cannot be required for HTTP/%s requests; use protocol version 2 or 3.', $version), $easy->request); + } + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; + } else { + if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new RequestException(\sprintf('The "multiplex" request option cannot be required for HTTP/%s requests; use protocol version 2 or 3.', $version), $easy->request); + } + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; + } + + $resolvedVersion = $conf[\CURLOPT_HTTP_VERSION]; + if (\in_array($multiplex, [Multiplexing::WAIT, Multiplexing::REQUIRE_WAIT], true) + && CurlVersion::supportsMultiplex() + && ($resolvedVersion === \CURL_HTTP_VERSION_2_0 + || (\defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE') && $resolvedVersion === (int) \constant('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE')) + || (\defined('CURL_HTTP_VERSION_3') && $resolvedVersion === (int) \constant('CURL_HTTP_VERSION_3')) + || (\defined('CURL_HTTP_VERSION_3ONLY') && $resolvedVersion === (int) \constant('CURL_HTTP_VERSION_3ONLY'))) + ) { + // Wait for an in-progress connection to the same origin to reveal + // whether it can be multiplexed instead of opening another one. + $conf[(int) \constant('CURLOPT_PIPEWAIT')] = true; + } + + return $conf; + } + + /** + * @param string[] $protocols + */ + private static function curlProtocolMask(array $protocols): int + { + $mask = 0; + + if (\in_array('http', $protocols, true)) { + $mask |= \CURLPROTO_HTTP; + } + + if (\in_array('https', $protocols, true)) { + $mask |= \CURLPROTO_HTTPS; + } + + return $mask; + } + + /** + * @param mixed $type + */ + private static function normalizeTlsFileType(string $option, $type): string + { + if (!\is_string($type) || $type === '') { + throw new InvalidArgumentException(\sprintf('%s must be a non-empty string', $option)); + } + + return Psr7\Utils::asciiToUpper($type); + } + + private static function shouldValidateSslKeyFile(?string $type): bool + { + return $type !== 'ENG' && $type !== 'PROV'; + } + + private function applyMethod( + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array &$conf, + RequestFraming $framing + ): void { + if ($easy->request->getMethod() === 'HEAD') { + // libcurl stops at HEAD response headers only when CURLOPT_NOBODY + // is set; CURLOPT_CUSTOMREQUEST changes only the method string. + // NOBODY also suppresses request upload, so strip non-zero body + // length, transfer coding, and a 100-continue expectation. + $conf[\CURLOPT_CUSTOMREQUEST] = null; + $conf[\CURLOPT_NOBODY] = true; + unset( + $conf[\CURLOPT_WRITEFUNCTION], + $conf[\CURLOPT_READFUNCTION], + $conf[\CURLOPT_FILE], + $conf[\CURLOPT_INFILE] + ); + if (\defined('CURLOPT_SEEKFUNCTION')) { + unset($conf[(int) \constant('CURLOPT_SEEKFUNCTION')]); + } + if (\trim($easy->request->getHeaderLine('Content-Length'), " \n\r\t\0\x0B") !== '0') { + $this->removeHeader('Content-Length', $conf); + } + $this->removeHeader('Transfer-Encoding', $conf); + if (Psr7\Utils::caselessEquals(\trim($easy->request->getHeaderLine('Expect'), " \n\r\t\0\x0B"), '100-continue')) { + $this->removeHeader('Expect', $conf); + } + + return; + } + + if ($framing->bodySize !== 0 && $framing->contentLength !== 0) { + $this->applyBody($easy, $conf, $framing); + } + } + + private function applyBody( + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array &$conf, + RequestFraming $framing + ): void { + $request = $easy->request; + $options = $easy->options; + $contentLength = $framing->contentLength; + + // Send the body as a string if the size is less than 1MB OR if the + // [curl][body_as_string] request value is set. + if (($framing->bodySize !== null && $framing->bodySize < 1000000) || !empty($options['_body_as_string'])) { + $conf[\CURLOPT_POSTFIELDS] = $framing->materialize(); + // Don't duplicate the Content-Length header + $this->removeHeader('Content-Length', $conf); + $this->removeHeader('Transfer-Encoding', $conf); + } else { + $conf[\CURLOPT_UPLOAD] = true; + + if ($contentLength !== null) { + // Never let cURL emit our header; it sizes the upload via a cURL input-size option. + $this->removeHeader('Content-Length', $conf); + $conf[self::curlInputSizeOption($request, $contentLength)] = $contentLength; + } + + $body = $request->getBody(); + try { + if ($body->isSeekable()) { + $body->rewind(); + } + } catch (\Exception $e) { + $message = $e instanceof TimeoutException + ? 'Timed out while rewinding the request body' + : ($e->getMessage() !== '' ? $e->getMessage() : 'Failed to rewind the request body'); + + throw new RequestException($message, $request, 0, $e); + } + /** + * @return int|string + */ + $remaining = $contentLength; + $conf[\CURLOPT_READFUNCTION] = static function ( + #[\SensitiveParameter] + $ch, + #[\SensitiveParameter] + $fd, + int $length + ) use ($easy, $body, &$remaining) { + if ($remaining === 0) { + return ''; + } + + $limit = $remaining === null ? $length : \min($length, $remaining); + + try { + $data = $body->read($limit); + } catch (TimeoutException $e) { + $easy->bodyReadTimeoutException = $e; + + return self::CURL_READFUNC_ABORT; + } catch (\Throwable $e) { + $easy->bodyReadException = $e; + + return self::CURL_READFUNC_ABORT; + } + + $dataLength = \strlen($data); + if ($dataLength > $limit) { + $easy->bodyReadException = new \RuntimeException('Request body stream returned more bytes than requested'); + + return self::CURL_READFUNC_ABORT; + } + + if ($remaining !== null) { + if ($data === '') { + $easy->bodyReadException = new \RuntimeException('Request body ended before the declared Content-Length was reached'); + + return self::CURL_READFUNC_ABORT; + } + + $remaining -= $dataLength; + } + + return $data; + }; + if (\defined('CURLOPT_SEEKFUNCTION')) { + // Give libcurl a seek callback so it can reposition the + // streamed upload itself when a transfer must resend the body + // (multi-pass auth such as NTLM/Negotiate, or a reused + // connection that died) instead of failing with + // CURLE_SEND_FAIL_REWIND. See + // https://bugs.php.net/bug.php?id=47204. A failed seek is + // recorded so the rejection carries the caller's exception + // and the failed-rewind retry does not fire. + $successfulSeeks = 0; + $conf[(int) \constant('CURLOPT_SEEKFUNCTION')] = static function ( + #[\SensitiveParameter] + $ch, + int $offset, + int $origin + ) use ($easy, $body, $contentLength, &$remaining, &$successfulSeeks): int { + if ($origin !== \SEEK_SET) { + return self::CURL_SEEKFUNC_CANTSEEK; + } + + try { + if (!$body->isSeekable()) { + return self::CURL_SEEKFUNC_CANTSEEK; + } + + if ($offset < 0 || ($contentLength !== null && $offset > $contentLength)) { + throw new \RuntimeException('Request body seek offset is outside the declared Content-Length'); + } + + if ($successfulSeeks >= self::CURL_SEEK_MAX_REPLAYS) { + throw new \RuntimeException(\sprintf('Request body cannot be replayed more than %d times', self::CURL_SEEK_MAX_REPLAYS)); + } + + $body->seek($offset, \SEEK_SET); + } catch (TimeoutException $e) { + $easy->bodyRewindTimeoutException = $e; + + return self::CURL_SEEKFUNC_FAIL; + } catch (\Throwable $e) { + $easy->bodyRewindException = $e; + + return self::CURL_SEEKFUNC_FAIL; + } + + $remaining = $contentLength === null ? null : $contentLength - $offset; + ++$successfulSeeks; + + return self::CURL_SEEKFUNC_OK; + }; + } + } + + // If the Expect header is not present, prevent curl from adding it + if (!$request->hasHeader('Expect')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Expect:'; + } + + // cURL sometimes adds a content-type by default. Prevent this. + if (!$request->hasHeader('Content-Type')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:'; + } + } + + private static function curlInputSizeOption( + #[\SensitiveParameter] + RequestInterface $request, + int $contentLength + ): int { + $option = \defined('CURLOPT_INFILESIZE_LARGE') + ? (int) \constant('CURLOPT_INFILESIZE_LARGE') + : \CURLOPT_INFILESIZE; + + // cURL's long remains 32-bit on 64-bit Windows. + if (\PHP_OS_FAMILY === 'Windows' && $option === \CURLOPT_INFILESIZE && $contentLength > 2147483647) { + throw new RequestException('Content-Length exceeds the maximum cURL upload size supported by this PHP build', $request); + } + + return $option; + } + + private function applyHeaders( + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array &$conf + ): void { + foreach ($conf['_headers'] as $name => $values) { + // The managed Proxy-Authorization field never enters the origin + // header list; applyProxyAuthorizationHeaderHandling() routes the + // values through cURL's proxy-only header channel. + if (Psr7\Utils::caselessEquals((string) $name, 'Proxy-Authorization')) { + continue; + } + + foreach ($values as $value) { + $value = (string) $value; + if (\strpos("$name$value", "\0") !== false) { + throw new RequestException('Request header fields must not contain a NUL byte.', $easy->request); + } + + if ($value === '') { + // cURL requires a special format for empty headers. + // See https://github.com/guzzle/guzzle/issues/1882 for more details. + $conf[\CURLOPT_HTTPHEADER][] = "$name;"; + } else { + $conf[\CURLOPT_HTTPHEADER][] = "$name: $value"; + } + } + } + + // Remove the Accept header if one was not set + if (!$easy->request->hasHeader('Accept')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Accept:'; + } + } + + /** + * Remove a header from the options array. + * + * @param string $name Case-insensitive header to remove + * @param array $options Array of options to modify + */ + private function removeHeader(string $name, array &$options): void + { + foreach (\array_keys($options['_headers']) as $key) { + if (Psr7\Utils::caselessEquals((string) $key, $name)) { + unset($options['_headers'][$key]); + + return; + } + } + } + + /** + * Decorates a caller-owned sink stream so that closing the response body + * detaches Guzzle's wrapper without closing the original PHP resource. + */ + private static function streamForResourceSink(StreamInterface $stream): StreamInterface + { + return FnStream::decorate($stream, [ + 'close' => static function () use ($stream): void { + $stream->detach(); + }, + ]); + } + + /** + * @param mixed $factory + */ + private static function requireStreamFactory($factory): StreamFactoryInterface + { + if (!$factory instanceof StreamFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::STREAM_FACTORY, + StreamFactoryInterface::class + )); + } + + return $factory; + } + + private function applyHandlerOptions( + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array &$conf + ): void { + $options = $easy->options; + if (isset($options['verify'])) { + if ($options['verify'] === false) { + unset($conf[\CURLOPT_CAINFO]); + $conf[\CURLOPT_SSL_VERIFYHOST] = 0; + $conf[\CURLOPT_SSL_VERIFYPEER] = false; + } else { + $conf[\CURLOPT_SSL_VERIFYHOST] = 2; + $conf[\CURLOPT_SSL_VERIFYPEER] = true; + if (\is_string($options['verify'])) { + // Throw an error if the file/folder/link path is not valid or doesn't exist. + if (!\file_exists($options['verify'])) { + throw new InvalidArgumentException(\sprintf('SSL CA bundle not found: %s', Psr7\DiagnosticValue::escape($options['verify']))); + } + // If it's a directory or a link to a directory use CURLOPT_CAPATH. + // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. + if ( + \is_dir($options['verify']) + || ( + \is_link($options['verify']) === true + && ($verifyLink = \readlink($options['verify'])) !== false + && \is_dir($verifyLink) + ) + ) { + $conf[\CURLOPT_CAPATH] = $options['verify']; + } else { + $conf[\CURLOPT_CAINFO] = $options['verify']; + } + } + } + } + + if (!isset($options['curl'][\CURLOPT_ENCODING]) && isset($options['decode_content']) && $options['decode_content'] !== false) { + $accept = $easy->request->getHeaderLine('Accept-Encoding'); + if ($accept !== '') { + $conf[\CURLOPT_ENCODING] = $accept; + } else { + // The empty string enables all available decoders and implicitly + // sets a matching 'Accept-Encoding' header. + $conf[\CURLOPT_ENCODING] = ''; + // But as the user did not specify any encoding preference, + // let's leave it up to server by preventing curl from sending + // the header, which will be interpreted as 'Accept-Encoding: *'. + // https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding + $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; + } + } + + $streamFactory = self::requireStreamFactory($options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()); + $hasSink = isset($options['sink']); + if (!$hasSink) { + // Use a default temp stream if no sink was set. + $options['sink'] = Psr7\Utils::tryFopen('php://temp', 'w+'); + } + $sink = $options['sink']; + if ($hasSink && \is_resource($sink)) { + $sink = self::streamForResourceSink(Psr7\Utils::streamFor($sink)); + } elseif (\is_resource($sink)) { + $sink = $streamFactory->createStreamFromResource($sink); + } elseif (!\is_string($sink)) { + $sink = Psr7\Utils::streamFor($sink); + } elseif (!\is_dir(\dirname($sink))) { + // Ensure that the directory exists before failing in curl. + throw new RequestException(\sprintf('Directory %s does not exist for sink value of %s', Psr7\DiagnosticValue::escape(\dirname($sink)), Psr7\DiagnosticValue::escape($sink)), $easy->request); + } else { + $sink = new LazyOpenStream($sink, 'w+'); + } + $easy->sink = $sink; + $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, string $write) use ($easy, $sink): int { + $length = \strlen($write); + + try { + $newResponseBodyBytes = TransferByteCounter::add( + $easy->responseBodyBytes, + $length, + 'Response body exceeds the maximum integer size supported on this platform' + ); + } catch (\OverflowException $e) { + $easy->responseBodySizeException = $e; + + return 0; + } + + try { + $written = $sink->write($write); + } catch (TimeoutException $e) { + $easy->sinkWriteTimeoutException = $e; + + return 0; + } catch (\Throwable $e) { + $easy->sinkWriteException = $e; + + return 0; + } + + if ($written !== $length) { + $easy->sinkWriteIncomplete = true; + + return 0; + } + + $easy->responseBodyBytes = $newResponseBodyBytes; + + return $written; + }; + + $timeoutRequiresNoSignal = false; + if (isset($options['timeout'])) { + $timeout = Timeout::toMilliseconds($options['timeout'], 'timeout'); + $timeoutRequiresNoSignal |= $timeout > 0 && $timeout < 1000; + $conf[\CURLOPT_TIMEOUT_MS] = $timeout; + } + + // CURL default value is CURL_IPRESOLVE_WHATEVER + if (isset($options['force_ip_resolve'])) { + if ('v4' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4; + } elseif ('v6' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6; + } + } + + if (isset($options['connect_timeout'])) { + $connectTimeout = Timeout::toMilliseconds($options['connect_timeout'], 'connect_timeout'); + if ($connectTimeout > 0) { + $timeoutRequiresNoSignal |= $connectTimeout < 1000; + $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $connectTimeout; + } else { + $conf[\CURLOPT_CONNECTTIMEOUT_MS] = self::CONNECT_TIMEOUT_DISABLED_MS; + } + } + + if ($timeoutRequiresNoSignal && \PHP_OS_FAMILY !== 'Windows') { + $conf[\CURLOPT_NOSIGNAL] = true; + } + + // Always pin CURLOPT_PROXY and CURLOPT_NOPROXY so that libcurl never + // falls back to reading proxy environment variables itself. + $proxy = ProxyEnv::resolveProxySelection($easy->request->getUri(), $options['proxy'] ?? null); + $selectedProxy = $proxy->getProxy(); + if ($selectedProxy !== null) { + // Validate the whole proxy URL up front (ProxyOptions leans on + // Psr7\Uri), so a malformed proxy fails the same way on every + // handler, then check the scheme against what libcurl can use. + self::assertSelectedProxySupported($selectedProxy, $easy->request); + + $conf[\CURLOPT_PROXY] = $selectedProxy; + $conf[\CURLOPT_NOPROXY] = ''; + } else { + $conf[\CURLOPT_PROXY] = ''; + $conf[\CURLOPT_NOPROXY] = $proxy->isBypassed() ? '*' : ''; + } + + $this->applyTlsVersionRange($easy, $conf); + + $certType = null; + if (isset($options['cert_type'])) { + $certType = self::normalizeTlsFileType('cert_type', $options['cert_type']); + $conf[\CURLOPT_SSLCERTTYPE] = $certType; + } + + if (isset($options['cert'])) { + $cert = $options['cert']; + if (\is_array($cert)) { + if (!isset($cert[0]) || !\is_string($cert[0])) { + throw new InvalidArgumentException('Invalid cert request option'); + } + if (isset($cert[1])) { + if (!\is_string($cert[1])) { + throw new InvalidArgumentException('Invalid cert request option'); + } + $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1]; + } + $cert = $cert[0]; + } + if (!\is_string($cert)) { + throw new InvalidArgumentException('Invalid cert request option'); + } + if (!\file_exists($cert)) { + throw new InvalidArgumentException(\sprintf('SSL certificate not found: %s', Psr7\DiagnosticValue::escape($cert))); + } + // OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files. + // see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html + $ext = pathinfo($cert, \PATHINFO_EXTENSION); + if ($certType === null && preg_match('#^(der|p12)$#iD', $ext)) { + $conf[\CURLOPT_SSLCERTTYPE] = Psr7\Utils::asciiToUpper($ext); + } + $conf[\CURLOPT_SSLCERT] = $cert; + } + + $sslKeyType = null; + if (isset($options['ssl_key_type'])) { + $sslKeyType = self::normalizeTlsFileType('ssl_key_type', $options['ssl_key_type']); + $conf[\CURLOPT_SSLKEYTYPE] = $sslKeyType; + } + + if (isset($options['ssl_key'])) { + if (\is_array($options['ssl_key'])) { + if (!isset($options['ssl_key'][0]) || !\is_string($options['ssl_key'][0])) { + throw new InvalidArgumentException('Invalid ssl_key request option'); + } + if (isset($options['ssl_key'][1])) { + if (!\is_string($options['ssl_key'][1])) { + throw new InvalidArgumentException('Invalid ssl_key request option'); + } + $conf[\CURLOPT_SSLKEYPASSWD] = $options['ssl_key'][1]; + } + $sslKey = $options['ssl_key'][0]; + } + + $sslKey = $sslKey ?? $options['ssl_key']; + + if (!\is_string($sslKey)) { + throw new InvalidArgumentException('Invalid ssl_key request option'); + } + + if (self::shouldValidateSslKeyFile($sslKeyType) && !\file_exists($sslKey)) { + throw new InvalidArgumentException(\sprintf('SSL private key not found: %s', Psr7\DiagnosticValue::escape($sslKey))); + } + $conf[\CURLOPT_SSLKEY] = $sslKey; + } + + $progress = $options['progress'] ?? null; + if ($progress !== null && !\is_callable($progress)) { + throw new InvalidArgumentException('progress client option must be callable'); + } + + // The streaming read callback (set by applyBody) aborts the upload on a + // body read failure by returning CURL_READFUNC_ABORT, but PHP ignores + // that integer return before 8.1.17/8.2.4. Install a progress callback + // so older PHP still has a cross-version abort path; the failure is + // classified from the stored request-body exception regardless of errno + // (a truncated request may reach the server first on those versions). + $abortsOnBodyReadFailure = isset($conf[\CURLOPT_READFUNCTION]); + + if ($progress !== null || $abortsOnBodyReadFailure) { + /** @var (callable(int, int, int, int): mixed)|null $progress */ + $conf[\CURLOPT_NOPROGRESS] = false; + $progressCallback = static function ($resource, $downloadSize, $downloaded, $uploadSize, $uploaded) use ($easy, $progress): int { + // Abort the transfer when the request body read or rewind + // failed (the cross-version abort path, since older PHP + // ignores the read callback's return). progressAborted is left + // unset so the failure is classified from the stored + // request-body exception. + if ($easy->bodyReadTimeoutException !== null || $easy->bodyRewindTimeoutException !== null || $easy->bodyRewindException !== null || $easy->bodyReadException !== null) { + return 1; + } + + if ($progress === null) { + return 0; + } + + try { + if ($progress( + TransferByteCounter::progressValueToInt($downloadSize), + TransferByteCounter::progressValueToInt($downloaded), + TransferByteCounter::progressValueToInt($uploadSize), + TransferByteCounter::progressValueToInt($uploaded) + )) { + $easy->progressAborted = true; + + return 1; + } + + return 0; + } catch (\Throwable $e) { + $easy->progressException = $e; + + return 1; + } + }; + + if (\defined('CURLOPT_XFERINFOFUNCTION')) { + $conf[(int) \constant('CURLOPT_XFERINFOFUNCTION')] = $progressCallback; + } else { + $conf[\CURLOPT_PROGRESSFUNCTION] = $progressCallback; + } + } + + if (!empty($options['debug'])) { + $conf[\CURLOPT_STDERR] = DebugResource::from($options['debug']); + $conf[\CURLOPT_VERBOSE] = true; + } + } + + private function applyTlsVersionRange( + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array &$conf + ): void { + $options = $easy->options; + $cryptoMethod = $options['crypto_method'] ?? null; + $cryptoMethodMax = $options['crypto_method_max'] ?? null; + + if ($cryptoMethod === null && 'https' === $easy->request->getUri()->getScheme()) { + $cryptoMethod = \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; + } + + if ($cryptoMethod === null && $cryptoMethodMax === null) { + return; + } + + $protocolVersion = $easy->request->getProtocolVersion(); + $isHttp3 = '3' === $protocolVersion || '3.0' === $protocolVersion; + $isHttp2 = '2' === $protocolVersion || '2.0' === $protocolVersion; + + if (($isHttp2 || $isHttp3) && $cryptoMethodMax !== null && TlsVersion::ordinal('crypto_method_max', $cryptoMethodMax) < 12) { + throw new InvalidArgumentException( + 'Invalid crypto_method_max request option: HTTP/2 and HTTP/3 require TLS 1.2 or higher' + ); + } + + if (($isHttp2 || $isHttp3) && $cryptoMethod !== null && TlsVersion::ordinal('crypto_method', $cryptoMethod) < 12) { + $cryptoMethod = \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; + } + + TlsVersion::assertRange($cryptoMethod, $cryptoMethodMax); + + $sslVersion = $cryptoMethod === null + ? \CURL_SSLVERSION_DEFAULT + : self::curlMinSslVersion($easy, $cryptoMethod); + + if ($cryptoMethodMax !== null) { + $sslVersion |= self::curlMaxSslVersion($easy, $cryptoMethodMax); + } + + $conf[\CURLOPT_SSLVERSION] = $sslVersion; + } + + private static function curlMinSslVersion( + #[\SensitiveParameter] + EasyHandle $easy, + int $value + ): int { + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) { + return \CURL_SSLVERSION_TLSv1_0; + } + + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) { + return \CURL_SSLVERSION_TLSv1_1; + } + + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) { + return \CURL_SSLVERSION_TLSv1_2; + } + + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) { + if (!CurlVersion::supportsTls13()) { + throw new RequestException( + 'Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL', + $easy->request + ); + } + + return \CURL_SSLVERSION_TLSv1_3; + } + + throw new InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); + } + + private static function curlMaxSslVersion( + #[\SensitiveParameter] + EasyHandle $easy, + int $value + ): int { + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) { + return self::requireCurlMaxSslVersion($easy, 'CURL_SSLVERSION_MAX_TLSv1_0'); + } + + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) { + return self::requireCurlMaxSslVersion($easy, 'CURL_SSLVERSION_MAX_TLSv1_1'); + } + + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) { + return self::requireCurlMaxSslVersion($easy, 'CURL_SSLVERSION_MAX_TLSv1_2'); + } + + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) { + return self::requireCurlMaxSslVersion($easy, 'CURL_SSLVERSION_MAX_TLSv1_3'); + } + + throw new InvalidArgumentException('Invalid crypto_method_max request option: unknown version provided'); + } + + private static function requireCurlMaxSslVersion( + #[\SensitiveParameter] + EasyHandle $easy, + string $constant + ): int { + if (\defined($constant)) { + /** @var int */ + return \constant($constant); + } + + throw new RequestException( + 'Invalid crypto_method_max request option: maximum TLS version control is not supported by your version of cURL', + $easy->request + ); + } + + /** + * This function ensures that a response was set on a transaction. If one + * was not set, then the request is retried if possible. This error + * typically means you are sending a payload, curl encountered a + * "Connection died, retrying a fresh connect" error, tried to rewind the + * stream, and then encountered a "necessary data rewind wasn't possible" + * error, causing the request to be sent through curl_multi_info_read() + * without an error status. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + * + * @return PromiseInterface + */ + private static function retryFailedRewind( + callable $handler, + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array $ctx + ): PromiseInterface { + try { + // Only rewind if the body has been read from. + $body = $easy->request->getBody(); + if ($body->tell() > 0) { + $body->rewind(); + } + } catch (\Exception $e) { + $ctx['error'] = 'The connection unexpectedly failed without providing an error. The request would have been retried, but attempting to rewind the request body failed.'; + + return self::createRejection($easy, $ctx, $e); + } + + // Retry no more than 3 times before giving up. + if (!isset($easy->options['_curl_retries'])) { + $easy->options['_curl_retries'] = 1; + } elseif ($easy->options['_curl_retries'] == 2) { + $ctx['error'] = 'The cURL request was retried 3 times ' + .'and did not succeed. The most likely reason for the failure ' + .'is that cURL was unable to rewind the body of the request ' + .'and subsequent retries resulted in the same error. Turn on ' + .'the debug option to see what went wrong. See ' + .'https://bugs.php.net/bug.php?id=47204 for more information.'; + + return self::createRejection($easy, $ctx); + } else { + ++$easy->options['_curl_retries']; + } + + return $handler($easy->request, $easy->options); + } + + /** + * Parses validated trailer field lines into an associative array keyed by + * lowercased field name, preserving first-occurrence key order and wire + * value order. + * + * @param list $lines + * + * @return array> + */ + private static function headersFromTrailerLines(array $lines): array + { + $headers = []; + + foreach ($lines as $line) { + [$name, $value] = \explode(':', $line, 2); + $name = Psr7\Utils::asciiToLower(\trim($name, " \n\r\t\0\x0B")); + $headers[$name][] = \trim($value, " \n\r\t\0\x0B"); + } + + return $headers; + } + + private function createHeaderFn( + #[\SensitiveParameter] + EasyHandle $easy + ): callable { + if (isset($easy->options['on_headers'])) { + $onHeaders = $easy->options['on_headers']; + + if (!\is_callable($onHeaders)) { + throw new InvalidArgumentException('on_headers must be callable'); + } + } else { + $onHeaders = null; + } + + $startingResponse = false; + $collectingTrailers = false; + $retainTrailers = isset($easy->options['on_trailers']); + + return static function ($ch, string $h) use ( + $onHeaders, + $easy, + &$startingResponse, + &$collectingTrailers, + $retainTrailers + ): int { + $value = \trim($h, " \n\r\t\0\x0B"); + if ($h === "\r\n" || $h === "\n" || $h === "\r" || $h === '') { + if ($collectingTrailers) { + // A blank line ends the trailer section; the response has + // already been created. + return \strlen($h); + } + + $startingResponse = true; + + try { + $easy->createResponse(); + } catch (\Throwable $e) { + $easy->response = null; + $easy->createResponseException = $e; + + return -1; + } + + if ($easy->responseHeaderException !== null) { + return -1; + } + + if ($onHeaders !== null && $easy->response !== null) { + try { + $onHeaders($easy->response, $easy->request); + } catch (\Throwable $e) { + // Associate the exception with the handle and trigger + // a curl header write error by returning 0. + $easy->onHeadersException = $e; + + return -1; + } + } + } elseif ($startingResponse || $collectingTrailers) { + if ($easy->response !== null && !HeaderProcessor::isStatusLineCandidate($h)) { + // Trailer fields arrive through the header callback after + // the body; a new header block always begins with a status + // line. + $collectingTrailers = true; + + if ($retainTrailers && HeaderProcessor::isValidHeaderFieldLine($h)) { + $easy->trailers[] = $value; + } + } else { + $collectingTrailers = false; + $easy->trailers = []; + $easy->headers = [$value]; + } + + $startingResponse = false; + } else { + $easy->headers[] = $value; + } + + return \strlen($h); + }; + } + + public function __destruct() + { + try { + $this->doClose(false); + } catch (\Throwable $e) { + // Destructors must not throw. + } + } + + public function __unserialize(array $data): void + { + $this->closed = true; + $this->handles = []; + $this->shareHandle = null; + + throw new \LogicException(static::class.' should never be unserialized'); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php new file mode 100644 index 0000000..ddafa3d --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php @@ -0,0 +1,31 @@ + true, + 'max_idle_handles' => true, + 'transport_sharing' => true, + ]; + + private CurlFactoryInterface $factory; + + private bool $ownsFactory; + + private bool $closed = false; + + private ?CurlShareHandleState $shareHandleState; + + /** + * Accepts an associative array of options: + * + * - handle_factory: Optional curl factory used to create cURL handles. + * - max_idle_handles: Optional maximum number of idle cURL easy handles. + * Zero disables retention; null or omission keeps the default of 3. + * - transport_sharing: Optional transport sharing mode. + * + * @param array{handle_factory?: ?CurlFactoryInterface, max_idle_handles?: mixed, transport_sharing?: mixed} $options Array of options to use with the handler + */ + public function __construct(array $options = []) + { + foreach ($options as $name => $_) { + if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) { + throw new InvalidArgumentException(\sprintf('Invalid CurlHandler constructor option "%s".', DiagnosticValue::escape((string) $name))); + } + } + + CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlHandler'); + $transportSharing = $options['transport_sharing'] ?? null; + $sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing'); + + $maxIdleHandles = $options['max_idle_handles'] ?? 3; + if (!\is_int($maxIdleHandles) || $maxIdleHandles < 0) { + throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); + } + + if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) { + if (isset($options['max_idle_handles'])) { + throw new InvalidArgumentException('The "max_idle_handles" CurlHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); + } + + $this->shareHandleState = null; + $this->factory = $options['handle_factory']; + $this->ownsFactory = false; + + return; + } + + $this->shareHandleState = $sharingMode !== TransportSharing::NONE + ? CurlShareHandleState::fromOption($transportSharing) + : null; + + $this->factory = $this->shareHandleState !== null + ? new CurlFactory($maxIdleHandles, $this->shareHandleState->mode, $this->shareHandleState) + : new CurlFactory($maxIdleHandles); + + $this->ownsFactory = true; + } + + /** + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + $this->assertOpen(); + HostValidator::assertRequestHost($request); + + if (isset($options['delay'])) { + Clock::sleep((int) ($options['delay'] * 1000)); + } + + // A Multiplexing::NONE request option holds unconditionally here: + // the transfer runs alone during the blocking curl_exec(), and even + // under persistent transport sharing an in-use connection cannot be + // joined from another multi handle, so it never shares its + // connection with a concurrent transfer. + $easy = $this->factory->create($request, $options); + + \curl_exec($easy->handle); + $easy->errno = \curl_errno($easy->handle); + + return CurlFactory::finish($this, $easy, $this->factory); + } + + /** + * Closes native cURL resources owned by this handler. + * + * After closing, the handler is terminal and must not be reused. + */ + public function close(): void + { + $this->doClose(true); + } + + public function __destruct() + { + try { + $this->doClose(false); + } catch (\Throwable $e) { + // Destructors must not throw. + } + } + + public function __unserialize(array $data): void + { + $this->closed = true; + + throw new \LogicException(static::class.' should never be unserialized'); + } + + private function assertOpen(): void + { + if ($this->closed) { + // Programmer misuse (reusing a closed handler), not a transfer failure; + // intentionally a LogicException outside the GuzzleException hierarchy. + throw new \BadMethodCallException('Cannot use the cURL handler after it has been closed.'); + } + } + + private function doClose(bool $explicit): void + { + if ($this->closed) { + return; + } + + $this->closed = true; + + try { + if ($this->ownsFactory && $this->factory instanceof CurlFactory) { + $this->factory->close(); + } + } catch (\Throwable $e) { + if ($explicit) { + throw $e; + } + } finally { + $this->shareHandleState = null; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php new file mode 100644 index 0000000..5208a03 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php @@ -0,0 +1,1673 @@ + true, + 'max_host_connections' => true, + 'max_idle_handles' => true, + 'max_total_connections' => true, + 'multiplex' => true, + 'options' => true, + 'select_timeout' => true, + 'transport_sharing' => true, + ]; + + private const CONNECTION_CAP_OPTIONS = [ + 'max_host_connections' => 'CURLMOPT_MAX_HOST_CONNECTIONS', + 'max_total_connections' => 'CURLMOPT_MAX_TOTAL_CONNECTIONS', + ]; + + /** + * cURL options that isolate a transfer from foreign proxy tunnel + * connections. Failing to apply either one would fall open into + * credential-bearing connection reuse. + */ + private const PROXY_TUNNEL_ISOLATION_OPTIONS = [ + 'CURLOPT_FRESH_CONNECT', + 'CURLOPT_FORBID_REUSE', + ]; + + private CurlFactoryInterface $factory; + + private bool $ownsFactory; + + private ?CurlShareHandleState $shareHandleState; + + private float $selectTimeout; + + /** + * @var int Will be higher than 0 when `curl_multi_exec` is still running. + */ + private int $active = 0; + + /** + * @var array Request entry handles, indexed by handle id in `addRequest`. + * + * @see CurlMultiHandler::addRequest + */ + private array $handles = []; + + /** + * @var array An array of delay times, indexed by handle id in `addRequest`. + * + * @see CurlMultiHandler::addRequest + */ + private array $delays = []; + + /** + * @var array An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() + */ + private array $options = []; + + /** + * @var bool Whether the "multiplex" constructor option disabled + * multiplexing on this handler's multi handle + */ + private bool $multiplexDisabled = false; + + /** + * @var resource|\CurlMultiHandle|null + */ + private $multiHandle; + + private bool $closed = false; + + private bool $closing = false; + + /** + * @var int Depth of nested guarded native operations (execution and + * handle removal, both of which can run user callbacks). A + * callback can re-enter tick(), and the nested frame must not + * clear the outer frame's guard; deferred work stays parked + * until the outermost frame unwinds. + */ + private int $multiExecDepth = 0; + + /** + * @var bool Guards finishDeferredWork() against re-entry from the + * guarded native removals it performs while flushing. + */ + private bool $finishingDeferredWork = false; + + /** + * @var array + */ + private array $deferredCancels = []; + + /** + * @var array Wait tokens of requests created from inside + * a cURL callback, keyed by handle id; native + * attachment is deferred until the outermost + * native execution unwinds. + */ + private array $deferredAdds = []; + + private bool $deferredClose = false; + + private bool $deferredCloseExplicit = false; + + /** + * @var string|null Owner signature of the proxy tunnels the multi handle's + * connection cache may hold + */ + private ?string $proxyTunnelOwner = null; + + /** @var array Count of attached transfers per proxy tunnel signature. */ + private array $activeProxyTunnelSignatures = []; + + /** @var array Maps an attached handle id to its proxy tunnel signature. */ + private array $activeProxyTunnelHandles = []; + + /** + * @var int Depth of nested processMessages() calls. Guards against + * multi-handle recreation re-entrancy from processMessages (a + * retried transfer re-invokes the handler) and keeps deferred + * work parked until the outermost message loop unwinds. + */ + private int $messageProcessingDepth = 0; + + /** + * This handler accepts the following options: + * + * - handle_factory: An optional factory used to create curl handles + * - transport_sharing: Optional transport sharing mode. + * - select_timeout: Optional timeout (in seconds) to block before timing + * out while selecting curl handles. Defaults to 1 second. + * - max_host_connections: Optional maximum concurrent connections per host. + * - max_idle_handles: Optional maximum number of idle cURL easy handles. + * Zero disables retention; null or omission keeps the default of 50. + * - max_total_connections: Optional maximum concurrent connections overall. + * - multiplex: Optional Multiplexing::NONE to disallow multiplexing on + * this handler's multi handle. The eager, wait, and required modes are + * request options, not handler options; Multiplexing::NONE is also + * conditionally accepted as a request option value. + * - options: An associative array of CURLMOPT_* options and + * corresponding values for curl_multi_setopt() + */ + public function __construct(array $options = []) + { + foreach ($options as $name => $_) { + if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) { + throw new InvalidArgumentException(\sprintf('Invalid CurlMultiHandler constructor option "%s".', Psr7\DiagnosticValue::escape((string) $name))); + } + } + + $handlerMultiplex = $options['multiplex'] ?? null; + if (null !== $handlerMultiplex && Multiplexing::NONE !== $handlerMultiplex) { + if (\in_array($handlerMultiplex, [Multiplexing::EAGER, Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new InvalidArgumentException('The "multiplex" CurlMultiHandler option only accepts Multiplexing::NONE; the eager, wait, and required modes are request options.'); + } + + throw new InvalidArgumentException(\sprintf('The "multiplex" CurlMultiHandler option must be null or Multiplexing::NONE; received %s.', \get_debug_type($handlerMultiplex))); + } + $this->multiplexDisabled = null !== $handlerMultiplex; + + if ($this->multiplexDisabled && !\defined('CURLMOPT_PIPELINING')) { + // ext-curl only defines the constant when built against libcurl + // 7.16 or newer headers, and such builds compile out the matching + // curl_multi_setopt() case, so the guarantee cannot be applied. + throw new InvalidArgumentException('The "multiplex" CurlMultiHandler option requires CURLMOPT_PIPELINING, but it is not available in the installed PHP cURL extension.'); + } + + CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlMultiHandler'); + $transportSharing = $options['transport_sharing'] ?? null; + $sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing'); + + $selectTimeout = $options['select_timeout'] ?? 1.0; + Timeout::toMilliseconds($selectTimeout, 'select_timeout'); + $this->selectTimeout = (float) $selectTimeout; + + $multiOptions = $options['options'] ?? []; + if (!\is_array($multiOptions)) { + throw new InvalidArgumentException('options must be an array of cURL multi options'); + } + + $this->options = $multiOptions; + self::rejectConflictingCurlMultiOptions($this->options); + $this->addConnectionCapOptions($options); + + if ($this->multiplexDisabled) { + // CURLPIPE_NOTHING; the constant itself needs libcurl 7.43 + // headers, newer than the oldest supported runtimes. + $this->options[\CURLMOPT_PIPELINING] = 0; + } + + $connectionCapOption = self::firstConnectionCapOption($options); + if ($connectionCapOption !== null && !CurlVersion::supportsSharedPoolConnectionCaps()) { + $persistentShareState = $transportSharing instanceof CurlShareHandleState + && \in_array($sharingMode, [TransportSharing::PERSISTENT_PREFER, TransportSharing::PERSISTENT_REQUIRE], true); + + if ($persistentShareState || $sharingMode === TransportSharing::PERSISTENT_REQUIRE) { + throw new InvalidArgumentException(\sprintf('%s cannot be combined with persistent transport sharing because applying connection caps to shared connection pools requires libcurl %s or higher.', $connectionCapOption, CurlVersion::SHARED_POOL_CONNECTION_CAP_VERSION)); + } + + if ($sharingMode === TransportSharing::PERSISTENT_PREFER) { + // libcurl below 8.22.0 does not apply cURL multi connection + // caps to transfers using a shared connection pool (curl + // #22265), so the best honorable offer for preferred persistent + // sharing is a handler-lifetime share. + $transportSharing = TransportSharing::HANDLER_PREFER; + $sharingMode = TransportSharing::HANDLER_PREFER; + } + } + + $maxIdleHandles = $options['max_idle_handles'] ?? 50; + if (!\is_int($maxIdleHandles) || $maxIdleHandles < 0) { + throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); + } + + if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) { + if (isset($options['max_idle_handles'])) { + throw new InvalidArgumentException('The "max_idle_handles" CurlMultiHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); + } + + $this->shareHandleState = null; + $this->factory = $options['handle_factory']; + $this->ownsFactory = false; + } else { + $this->shareHandleState = $sharingMode !== TransportSharing::NONE + ? CurlShareHandleState::fromOption($transportSharing) + : null; + + $this->factory = $this->shareHandleState !== null + ? new CurlFactory($maxIdleHandles, $this->shareHandleState->mode, $this->shareHandleState) + : new CurlFactory($maxIdleHandles); + + $this->ownsFactory = true; + } + } + + public function __destruct() + { + try { + $this->doClose(false); + } catch (\Throwable $e) { + // Destructors must not throw. + } + } + + public function __unserialize(array $data): void + { + $this->closed = true; + + throw new \LogicException(static::class.' should never be unserialized'); + } + + /** + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + $this->assertOpen(); + HostValidator::assertRequestHost($request); + + $easy = $this->factory->create($request, $options); + + try { + $this->rejectDisabledMultiplexConflict($easy, $options); + $this->applyMultiplexNone($easy, $options); + $this->applyProxyTunnelOwnership($easy); + } catch (\Throwable $e) { + try { + $this->factory->release($easy); + } catch (\Throwable $releaseFailure) { + // Preserve the original failure. + } + + throw $e; + } + + $id = (int) $easy->handle; + + $waitToken = new \stdClass(); + + $promise = null; + /** @var Promise $promise */ + $promise = new Promise( + function () use ($id, $waitToken, $easy, &$promise): void { + // Waiting cannot drive native cURL while a callback has the + // multi handle busy; fail the wait promptly instead of + // self-deadlocking. + try { + $stalled = $this->multiExecDepth > 0 + ? $this->failNestedWait($id, $waitToken) + : $this->executeUntil($id, $waitToken); + } catch (\Throwable $e) { + throw $this->discardInterruptedRequest($id, $waitToken, $e); + } + + // Settling can be queued, and guzzlehttp/promises drains the + // queue before deciding a wait function achieved nothing. + P\Utils::queue()->run(); + + // Never null: assigned below before any wait can invoke this. + /** @var Promise $promise */ + if ($easy->deferredSettled || !P\State::isPending($promise)) { + return; + } + + // Neither path guarantees the transfer settled, and returning + // while pending makes guzzlehttp/promises reject with a bare + // string naming nothing. + $message = \sprintf('Waiting on cURL multi handler transfer %d cannot make progress (%s).', $id, $stalled); + + // The entry is gone, so the easy handle is the only route to + // a response that already arrived. + $response = $easy->response; + $failure = $response !== null + ? new ResponseException($message, $easy->request, $response) + : new RequestException($message, $easy->request); + + $promise->reject($failure); + }, + function () use ($id, $waitToken): void { + $this->cancel($id, $waitToken); + } + ); + + $entry = ['easy' => $easy, 'deferred' => $promise, 'wait_token' => $waitToken]; + try { + $this->addRequest($entry); + } catch (\Throwable $e) { + throw $this->discardPendingRequest($id, $entry, $e); + } + + return $promise; + } + + /** + * The "multiplex" request option sets CURLOPT_PIPEWAIT, which libcurl + * ignores entirely when the multi handle disallows multiplexing, so an + * explicit request for multiplexing on a handler configured with + * Multiplexing::NONE is a configuration error. The required family + * conflicts marker-independently: a required guarantee on such a handler + * is contradictory even when the transfer would not wait. The default + * WAIT mode adapts instead of conflicting: the handler option wins and + * nothing waits. + */ + private function rejectDisabledMultiplexConflict( + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array $options + ): void { + if (!$this->multiplexDisabled) { + return; + } + + $multiplex = $options['multiplex'] ?? null; + + if (Multiplexing::WAIT === $multiplex && !$easy->usesPipewait) { + // Explicit wait only conflicts when the transfer would actually + // wait; an HTTP/1.1 wait request never sets the marker. + return; + } + + if (!\in_array($multiplex, [Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + return; + } + + throw new InvalidArgumentException('The "multiplex" request option cannot be combined with a CurlMultiHandler whose "multiplex" option is Multiplexing::NONE; remove the handler option or set the request option to "eager".'); + } + + /** + * A Multiplexing::NONE request option is a sole-use guarantee: the + * transfer must not share its connection with any concurrent transfer. + * It holds structurally on a handler whose "multiplex" option is + * Multiplexing::NONE, and for HTTP/1.x transfers, which never join a + * multiplexed connection and open connections nothing can join. An + * HTTP/2 or HTTP/3 request on a handler that multiplexes is rejected, + * as is any configuration under which the guarantee cannot be verified + * (custom handle factories control the native handle), cannot be + * hardened (challenge-response authentication retries and Expect + * 417 retries re-enter connection selection as internal follows, which + * disarm CURLOPT_FRESH_CONNECT), or must not be hardened (required + * persistent sharing forbids fresh connections). On runtimes whose + * matcher can hand an HTTP/1.x transfer an idle multiplexed connection + * (below libcurl 7.77.0, and 8.11.0-8.12.1), accepted transfers force a + * fresh connection. + */ + private function applyMultiplexNone( + #[\SensitiveParameter] + EasyHandle $easy, + #[\SensitiveParameter] + array $options + ): void { + if (Multiplexing::NONE !== ($options['multiplex'] ?? null) || $this->multiplexDisabled) { + return; + } + + if (!$this->ownsFactory) { + throw new InvalidArgumentException('The "multiplex" request option can only be Multiplexing::NONE on a CurlMultiHandler with a custom "handle_factory" when the handler\'s own "multiplex" option is Multiplexing::NONE, because the guarantee is enforced against the native easy handle the factory controls.'); + } + + $version = $easy->request->getProtocolVersion(); + if ('1.0' !== $version && '1.1' !== $version) { + throw new InvalidArgumentException('The "multiplex" request option can only be Multiplexing::NONE for an HTTP/1.x request on a CurlMultiHandler that permits multiplexing; set the "multiplex" client or CurlMultiHandler constructor option to Multiplexing::NONE to disable multiplexing for every transfer, or send the request with its "version" option set to "1.1".'); + } + + if (null !== $this->shareHandleState && TransportSharing::PERSISTENT_REQUIRE === $this->shareHandleState->mode) { + // The matcher-window hardening below may force a fresh + // connection, which required persistent sharing forbids because + // it disables connection reuse (CurlFactory applies the same + // rule to the raw option); rejected on every runtime so + // acceptance stays version-independent. + throw new InvalidArgumentException('The "multiplex" request option cannot be Multiplexing::NONE on a CurlMultiHandler that permits multiplexing and requires persistent transport sharing; set the "multiplex" client or CurlMultiHandler constructor option to Multiplexing::NONE, or use TransportSharing::PERSISTENT_PREFER.'); + } + + if (\defined('CURLOPT_HTTPAUTH') + && isset($options['curl']) + && \is_array($options['curl']) + && \array_key_exists((int) \constant('CURLOPT_HTTPAUTH'), $options['curl']) + ) { + // Key presence alone conflicts: challenge-response retries are + // libcurl-internal follows, which disarm CURLOPT_FRESH_CONNECT + // (reuse_fresh && !this_is_a_follow), so the hardening below + // cannot cover them. + throw new InvalidArgumentException('The "multiplex" request option cannot be Multiplexing::NONE combined with the raw CURLOPT_HTTPAUTH cURL option on a CurlMultiHandler that permits multiplexing; remove the raw option, or set the "multiplex" client or CurlMultiHandler constructor option to Multiplexing::NONE.'); + } + + if (Psr7\Utils::caselessContains($easy->request->getHeaderLine('Expect'), '100-continue')) { + // libcurl arms its Expect handling by a caseless substring scan + // of the header value (Curl_compareheader), so any value + // containing 100-continue can make a 417 response retry as an + // internal follow, which disarms CURLOPT_FRESH_CONNECT; requests + // without the header are safe because the factory suppresses + // libcurl's automatic Expect. + throw new InvalidArgumentException('The "multiplex" request option cannot be Multiplexing::NONE for a request carrying an "Expect: 100-continue" header on a CurlMultiHandler that permits multiplexing; remove the explicitly supplied "Expect" header, set the "expect" request option to false to prevent it being added automatically, or set the "multiplex" client or CurlMultiHandler constructor option to Multiplexing::NONE.'); + } + + if (CurlVersion::supportsHttpVersionReuseMatching()) { + return; + } + + // Unqualified curl_setopt so the test bootstrap shadow records it. + if (true !== curl_setopt($easy->handle, \CURLOPT_FRESH_CONNECT, true)) { + // The hardening is the guarantee on these runtimes; failing to + // apply it must fail closed, mirroring applyCurlOptions(). + throw new InvalidArgumentException('Unable to set cURL option CURLOPT_FRESH_CONNECT.'); + } + } + + /** + * @param array $options + */ + private static function rejectConflictingCurlMultiOptions(array $options): void + { + if ($options === []) { + return; + } + + $conflictingOptions = self::conflictingCurlMultiOptions(); + foreach ($options as $option => $_) { + if (\array_key_exists($option, $conflictingOptions)) { + throw new InvalidArgumentException(\sprintf('Passing %s in the cURL multi handler "options" is not supported. Use %s instead.', self::formatCurlMultiOption($option), $conflictingOptions[$option])); + } + } + } + + /** + * @param array $options + */ + private static function firstConnectionCapOption(array $options): ?string + { + foreach (self::CONNECTION_CAP_OPTIONS as $name => $_) { + if (($options[$name] ?? null) !== null) { + return $name; + } + } + + return null; + } + + /** + * @param array $options + */ + private function addConnectionCapOptions(array $options): void + { + foreach (self::CONNECTION_CAP_OPTIONS as $name => $constant) { + $value = $options[$name] ?? null; + if ($value === null) { + continue; + } + + if (!\is_int($value) || $value < 1) { + throw new InvalidArgumentException(\sprintf('%s must be a positive integer.', $name)); + } + + if (!\defined($constant)) { + throw new InvalidArgumentException(\sprintf('%s requires %s, but it is not available in the installed PHP cURL extension.', $name, $constant)); + } + + $option = \constant($constant); + if (\array_key_exists($option, $this->options)) { + throw new InvalidArgumentException(\sprintf('%s conflicts with a %s entry in the "options" array.', $name, $constant)); + } + + $this->options[$option] = $value; + } + } + + /** + * @param int|string $option + */ + private static function formatCurlMultiOption($option): string + { + if (!\is_int($option)) { + return \sprintf('"%s"', Psr7\DiagnosticValue::escape((string) $option)); + } + + static $names = null; + + if (null === $names) { + $names = []; + foreach (\get_defined_constants(true)['curl'] ?? [] as $name => $value) { + if (\is_int($value) && \strpos($name, 'CURLMOPT_') === 0 && !isset($names[$value])) { + $names[$value] = $name; + } + } + } + + if (isset($names[$option])) { + return \sprintf('%s (%d)', $names[$option], $option); + } + + return (string) $option; + } + + /** + * @return array + */ + private static function conflictingCurlMultiOptions(): array + { + static $options = null; + + if ($options !== null) { + return $options; + } + + $options = []; + + self::addConflictingCurlMultiOption($options, 'CURLMOPT_MAX_HOST_CONNECTIONS', 'the "max_host_connections" client option or cURL multi handler option'); + self::addConflictingCurlMultiOption($options, 'CURLMOPT_MAX_TOTAL_CONNECTIONS', 'the "max_total_connections" client option or cURL multi handler option'); + self::addConflictingCurlMultiOption($options, 'CURLMOPT_PIPELINING', 'Multiplexing::NONE via the "multiplex" cURL multi handler or client option to disable multiplexing, or remove the raw option for the runtime default (multiplexing defaults on from libcurl 7.62, except 7.65.0 and 7.65.1)'); + + return $options; + } + + /** + * @param array $options + */ + private static function addConflictingCurlMultiOption(array &$options, string $constant, string $replacement): void + { + if (!\defined($constant)) { + return; + } + + $value = \constant($constant); + if (\is_int($value)) { + $options[$value] = $replacement; + } + } + + /** + * Isolates the connection cache when the request's proxy tunnel section + * differs from the one the multi handle's cache may already hold. + */ + private function applyProxyTunnelOwnership( + #[\SensitiveParameter] + EasyHandle $easy + ): void { + $signature = $easy->proxyTunnelSignature; + if ($signature === null || $signature === $this->proxyTunnelOwner) { + return; + } + + if ($this->proxyTunnelOwner === null) { + // No in-domain transfer has ever run on this multi handle: latch + // the owner without destroying pooled direct connections. + $this->proxyTunnelOwner = $signature; + + return; + } + + if ( + $this->handles === [] + && 0 === $this->multiExecDepth + && 0 === $this->messageProcessingDepth + && $this->deferredCancels === [] + && !$this->deferredClose + ) { + // Idle: hand the connection cache over by recreating the multi + // handle. getMultiHandle() lazily re-initializes it (re-applying + // the CURLMOPT_* options) on the next access. + if ($this->multiHandle !== null) { + \curl_multi_close($this->multiHandle); + $this->multiHandle = null; + } + $this->proxyTunnelOwner = $signature; + + return; + } + + // Busy: isolate this transfer from the owner's pooled tunnels. + $this->isolateProxyTunnelTransfer($easy); + } + + private function addHandleToMulti( + int $id, + #[\SensitiveParameter] + EasyHandle $easy + ): void { + $this->isolateFromForeignActiveProxyTunnel($easy); + + $multiHandle = $this->getMultiHandle(); + + // Unqualified curl_multi_add_handle so the test bootstrap shadow can + // override the result. + $result = curl_multi_add_handle($multiHandle, $easy->handle); + + if (\CURLM_OK !== $result) { + if (\PHP_VERSION_ID < 80226 || (\PHP_VERSION_ID >= 80300 && \PHP_VERSION_ID < 80314)) { + // Before PHP 8.2.26 and 8.3.14, ext-curl kept the easy handle + // in its multi bookkeeping even when the native add failed + // (https://github.com/php/php-src/pull/16302); remove it so + // the handle can be disposed safely. + \curl_multi_remove_handle($multiHandle, $easy->handle); + } + + throw new RequestException(\sprintf('Unable to add the cURL handle to the cURL multi handler: %s (%d).', (string) \curl_multi_strerror($result), $result), $easy->request); + } + + $this->markProxyTunnelActive($id, $easy); + + if (isset($this->handles[$id])) { + $this->handles[$id]['attached'] = true; + } + } + + private function isolateFromForeignActiveProxyTunnel( + #[\SensitiveParameter] + EasyHandle $easy + ): void { + $signature = $easy->proxyTunnelSignature; + + if ($signature === null || $this->activeProxyTunnelSignatures === []) { + return; + } + + if (\count($this->activeProxyTunnelSignatures) === 1 && isset($this->activeProxyTunnelSignatures[$signature])) { + return; + } + + $this->isolateProxyTunnelTransfer($easy); + } + + private function isolateProxyTunnelTransfer( + #[\SensitiveParameter] + EasyHandle $easy + ): void { + foreach (self::PROXY_TUNNEL_ISOLATION_OPTIONS as $name) { + try { + // Unqualified curl_setopt so the test bootstrap shadow records it. + $applied = curl_setopt($easy->handle, (int) \constant($name), true); + } catch (\Throwable $e) { + throw new RequestException(self::proxyTunnelIsolationFailureMessage($name), $easy->request, 0, $e); + } + + if (true !== $applied) { + throw new RequestException(self::proxyTunnelIsolationFailureMessage($name), $easy->request); + } + } + } + + private static function proxyTunnelIsolationFailureMessage(string $name): string + { + return \sprintf('Unable to apply the %s cURL option required to isolate the transfer from foreign proxy tunnel connections.', $name); + } + + private function markProxyTunnelActive(int $id, EasyHandle $easy): void + { + $signature = $easy->proxyTunnelSignature; + if ($signature === null) { + return; + } + + if (isset($this->activeProxyTunnelHandles[$id])) { + if ($this->activeProxyTunnelHandles[$id] === $signature) { + return; + } + + $this->unmarkProxyTunnelActiveById($id); + } + + $this->activeProxyTunnelHandles[$id] = $signature; + $this->activeProxyTunnelSignatures[$signature] = ($this->activeProxyTunnelSignatures[$signature] ?? 0) + 1; + } + + private function unmarkProxyTunnelActiveById(int $id): void + { + if (!isset($this->activeProxyTunnelHandles[$id])) { + return; + } + + $signature = $this->activeProxyTunnelHandles[$id]; + unset($this->activeProxyTunnelHandles[$id]); + + if (!isset($this->activeProxyTunnelSignatures[$signature])) { + return; + } + + --$this->activeProxyTunnelSignatures[$signature]; + + if ($this->activeProxyTunnelSignatures[$signature] <= 0) { + unset($this->activeProxyTunnelSignatures[$signature]); + } + } + + /** + * Ticks the curl event loop. + */ + public function tick(): void + { + $this->tickFor(null, null); + } + + /** + * Ticks the curl event loop, returning before the blocking select if the + * targeted transfer has settled, been canceled, or been replaced by a + * request that reused its native handle ID. + */ + private function tickFor(?int $targetId, ?object $waitToken): void + { + $this->assertOpen(); + + // Add any delayed handles if needed. Attachment is skipped while a + // callback has native execution busy; the outer frame attaches due + // transfers once it unwinds. + if ($this->delays && 0 === $this->multiExecDepth) { + $currentTime = Clock::now(); + foreach ($this->delays as $id => $delay) { + if ($currentTime >= $delay) { + $entry = $this->handles[$id]; + unset($this->delays[$id]); + + try { + $this->addHandleToMulti($id, $entry['easy']); + } catch (\Throwable $e) { + $rejection = $this->discardPendingRequest($id, $entry, $e); + if (P\State::isPending($entry['deferred'])) { + $entry['deferred']->reject($rejection); + } + } + } + } + } + + // Run curl_multi_exec in the queue to enable other async tasks to + // run, surface completions, and drain any work they queued so a + // ready cancellation or new transfer is not held behind the select. + do { + P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue'])); + + // Step through the task queue which may add additional requests. + P\Utils::queue()->run(); + + if ($this->multiExecDepth > 0) { + // A cURL callback re-entered the handler while native + // execution is running; the outer frame drives native cURL + // once it unwinds. + return; + } + + if ($this->closed || $this->closing || !$this->hasMultiHandle()) { + return; + } + + $this->processMessages(); + + if ($this->closed || $this->closing || !$this->hasMultiHandle()) { + return; + } + } while (!P\Utils::queue()->isEmpty()); + + if ($targetId !== null && !$this->hasRequest($targetId, $waitToken)) { + return; + } + + if ($this->active && \curl_multi_select($this->getMultiHandle(), $this->effectiveSelectTimeout()) === -1) { + // Perform a usleep if a select returns -1. + // See: https://bugs.php.net/bug.php?id=61141 + \usleep(250); + } + + do { + $exec = $this->executeMulti(); + + if ($this->closed || $this->closing || !$this->hasMultiHandle()) { + return; + } + + // Prevent busy looping for slow HTTP requests. + if ($exec === \CURLM_CALL_MULTI_PERFORM) { + \curl_multi_select($this->getMultiHandle(), $this->effectiveSelectTimeout()); + } + } while ($exec === \CURLM_CALL_MULTI_PERFORM); + + $this->processMessages(); + } + + /** + * Runs \curl_multi_exec() inside the event loop, to prevent busy looping + */ + private function tickInQueue(): void + { + if ($this->multiExecDepth > 0) { + // A cURL callback re-entered the handler while native execution + // is running; the outer frame drives native cURL once it unwinds. + return; + } + + if ($this->closed || $this->closing || !$this->hasMultiHandle()) { + return; + } + + $exec = $this->executeMulti(); + + if ($this->closed || $this->closing || !$this->hasMultiHandle()) { + return; + } + + if ($exec === \CURLM_CALL_MULTI_PERFORM) { + \curl_multi_select($this->getMultiHandle(), 0); + P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue'])); + } + } + + /** + * Runs until all outstanding connections have completed. + */ + public function execute(): void + { + $this->assertOpen(); + + if ($this->multiExecDepth > 0) { + // Native cURL cannot be driven while a callback has it busy, so + // the loop would spin without ever progressing. + throw new \LogicException('Cannot run the cURL multi event loop from inside a cURL callback; the callback must return before transfers can progress.'); + } + + $queue = P\Utils::queue(); + + while (!$this->closed && !$this->closing && ($this->handles || !$queue->isEmpty())) { + // If there are no transfers, then sleep for the next delay, + // unless ready queue work could change what is pending. + if (!$this->active && $this->delays && $queue->isEmpty()) { + Clock::sleep($this->timeToNext()); + } + $this->tick(); + } + } + + /** + * Runs the event loop until the given transfer has finished, so waiting + * on a promise does not wait for every other transfer on the handler + * like execute() does. + * + * The native cURL handle ID can be reused by a request created from a + * completion callback, so the wait token guards against waiting on an + * unrelated transfer that inherited the ID. + * + * @return string Why waiting stopped, for the caller to report when the + * transfer did not settle + */ + private function executeUntil(int $id, object $waitToken): string + { + $this->assertOpen(); + + $queue = P\Utils::queue(); + + while ( + !$this->closed + && !$this->closing + && $this->hasRequest($id, $waitToken) + ) { + // If the transfer is delayed, then sleep until it is due, unless + // ready queue work could cancel or replace it first. + if (!$this->active && isset($this->delays[$id]) && $queue->isEmpty()) { + Clock::sleep($this->timeToNext()); + } + $this->tickFor($id, $waitToken); + } + + // Sample before the drain below, which can add or remove an entry + // under this ID and so rewrite the answer. + $stalled = $this->describeStalledWait($id, $waitToken); + + if (!$this->closed && !$this->closing && !$queue->isEmpty()) { + $queue->run(); + } + + return $stalled; + } + + /** + * Describes the state that stopped a wait, for the fallback rejection in + * __invoke(). Only meaningful when the transfer did not settle. + */ + private function describeStalledWait(int $id, object $waitToken): string + { + if ($this->hasRequest($id, $waitToken)) { + // Reached when waiting stopped for another reason, such as the + // handler being closed underneath it. + return 'the handler stopped driving it while it was still tracked'; + } + + return isset($this->handles[$id]) + ? 'its native cURL handle ID was reused by another request' + : 'its entry was removed without settling'; + } + + /** + * Checks that the request with the given handle ID is still pending and, + * when a wait token is given, has not been replaced by a request that + * reused the ID. + */ + private function hasRequest(int $id, ?object $waitToken = null): bool + { + if (!isset($this->handles[$id])) { + return false; + } + + return $waitToken === null || ($this->handles[$id]['wait_token'] ?? null) === $waitToken; + } + + /** + * Closes native cURL resources owned by this handler. + * + * Pending transfers are rejected with HandlerClosedException. After + * closing, the handler is terminal and must not be reused. + */ + public function close(): void + { + $this->doClose(true); + } + + private function assertOpen(): void + { + if ($this->closed || $this->closing) { + // Programmer misuse (reusing a closed handler), not a transfer failure; + // intentionally a LogicException outside the GuzzleException hierarchy. + throw new \BadMethodCallException('Cannot use the cURL multi handler after it has been closed.'); + } + } + + private function doClose(bool $explicit): void + { + if ($this->closed || $this->closing) { + return; + } + + $this->closing = true; + $failure = null; + + if ($this->multiExecDepth > 0 || $this->messageProcessingDepth > 0) { + $this->deferClose($explicit, $failure); + + if ($explicit && $failure !== null) { + throw $failure; + } + + return; + } + + try { + $this->cleanupPendingTransfers($explicit, $failure); + $this->closeMultiHandle($failure); + $this->closeOwnedFactory($failure); + } finally { + $this->finishClose(); + } + + if ($explicit && $failure !== null) { + throw $failure; + } + } + + private function deferClose(bool $explicit, ?\Throwable &$failure): void + { + $this->deferredClose = true; + $this->deferredCloseExplicit = $this->deferredCloseExplicit || $explicit; + + $entries = $this->handles; + + $this->handles = []; + $this->delays = []; + $this->deferredAdds = []; + + foreach ($entries as $id => $entry) { + $this->deferredCancels[$id] = [ + 'easy' => $entry['easy'], + 'attached' => !empty($entry['attached']), + ]; + + if ($explicit && P\State::isPending($entry['deferred'])) { + $this->captureFailure($failure, function () use ($entry): void { + $entry['deferred']->reject(new HandlerClosedException('The cURL multi handler was closed before the transfer completed.', $entry['easy']->request)); + }); + } + } + } + + private function finishClose(): void + { + $this->handles = []; + $this->delays = []; + $this->deferredCancels = []; + $this->deferredAdds = []; + $this->activeProxyTunnelSignatures = []; + $this->activeProxyTunnelHandles = []; + $this->active = 0; + $this->shareHandleState = null; + $this->deferredClose = false; + $this->deferredCloseExplicit = false; + $this->closed = true; + $this->closing = false; + } + + private function captureFailure(?\Throwable &$failure, callable $callback): void + { + try { + $callback(); + } catch (\Throwable $e) { + if ($failure === null) { + $failure = $e; + } + } + } + + /** + * @param array{easy: EasyHandle, deferred: Promise, wait_token: object} $entry + */ + private function discardPendingRequest(int $id, array $entry, \Throwable $failure): \Throwable + { + unset($this->handles[$id], $this->delays[$id], $this->deferredAdds[$id]); + + try { + $this->disposeEasyHandle($entry['easy']); + } catch (\Throwable $e) { + // Preserve the original attach failure. + } + + return $failure; + } + + private function cleanupPendingTransfers(bool $reject, ?\Throwable &$failure): void + { + $entries = $this->handles; + + $this->handles = []; + $this->delays = []; + $this->deferredAdds = []; + + foreach ($entries as $id => $entry) { + $easy = $entry['easy']; + $attached = !empty($entry['attached']); + + if ($attached && $this->hasMultiHandle() && self::hasEasyHandle($easy)) { + $this->captureFailure($failure, function () use ($id, $easy): void { + $this->removeHandleFromMulti($id, $easy->handle); + }); + } + + if ($reject && P\State::isPending($entry['deferred'])) { + $this->captureFailure($failure, function () use ($entry): void { + $entry['deferred']->reject(new HandlerClosedException('The cURL multi handler was closed before the transfer completed.', $entry['easy']->request)); + }); + } + + $this->captureFailure($failure, function () use ($easy): void { + $this->disposeEasyHandle($easy); + }); + } + } + + private function closeMultiHandle(?\Throwable &$failure): void + { + if ($this->multiHandle === null) { + return; + } + + $multiHandle = $this->multiHandle; + + $this->captureFailure($failure, function () use ($multiHandle): void { + try { + \curl_multi_close($multiHandle); + } finally { + $this->multiHandle = null; + } + }); + } + + private function closeOwnedFactory(?\Throwable &$failure): void + { + $factory = $this->factory; + if (!$this->ownsFactory || !$factory instanceof CurlFactory) { + return; + } + + $this->captureFailure($failure, static function () use ($factory): void { + $factory->close(); + }); + } + + /** + * @phpstan-impure + */ + private function executeMulti(): int + { + ++$this->multiExecDepth; + + try { + return \curl_multi_exec($this->getMultiHandle(), $this->active); + } finally { + --$this->multiExecDepth; + $this->finishDeferredWork(); + } + } + + /** + * Flushes attachments deferred while the multi handle was busy executing + * transfers or removing a handle, and cancels and a close deferred while + * it was executing transfers or processing completion messages. + */ + private function finishDeferredWork(): void + { + if ($this->multiExecDepth > 0 || $this->finishingDeferredWork) { + // A nested frame (a completion callback re-entered the handler) + // must not flush while an outer frame is still using the multi + // handle; the outermost frame flushes once it unwinds. + return; + } + + $this->finishingDeferredWork = true; + + try { + if (!$this->closed && !$this->closing) { + // Deferred adds only need native execution to be idle; a + // completion callback may drive and wait on them while the + // outermost message loop is still active. + $this->flushDeferredAdds(); + } + + if ($this->messageProcessingDepth > 0) { + // Cancels and a deferred close must wait for the outermost + // message loop to unwind. + return; + } + + $failure = null; + + // Removing a cancelled transfer runs its final progress update, + // whose callback can cancel other transfers, create requests, or + // close the handler; drain until no deferred work remains. + do { + $this->cleanupDeferredCancels($failure); + + if (!$this->closed && !$this->closing) { + $this->flushDeferredAdds(); + } + } while ($this->deferredCancels !== [] || (!$this->closed && !$this->closing && $this->deferredAdds !== [])); + + if ($this->deferredClose) { + $explicit = $this->deferredCloseExplicit; + + try { + $this->closeMultiHandle($failure); + $this->closeOwnedFactory($failure); + } finally { + $this->finishClose(); + } + + if ($explicit && $failure !== null) { + throw $failure; + } + + return; + } + + if ($failure !== null) { + throw $failure; + } + } finally { + $this->finishingDeferredWork = false; + } + } + + /** + * Attaches requests whose native attachment was deferred because they + * were created from inside a cURL callback. + */ + private function flushDeferredAdds(): void + { + if ($this->deferredAdds === []) { + return; + } + + $adds = $this->deferredAdds; + $this->deferredAdds = []; + + foreach ($adds as $id => $token) { + if (!$this->hasRequest($id, $token)) { + // Cancelled or replaced while the attachment was deferred. + continue; + } + + $entry = $this->handles[$id]; + + try { + $this->addHandleToMulti($id, $entry['easy']); + } catch (\Throwable $e) { + // The promise has already escaped, so reject it rather than + // throw. User code may have settled it directly; a settled + // promise must not abort the rest of the snapshot. + $rejection = $this->discardPendingRequest($id, $entry, $e); + if (P\State::isPending($entry['deferred'])) { + $entry['deferred']->reject($rejection); + } + } + } + } + + /** + * Fails a synchronous wait attempted from inside a cURL callback, where + * native execution cannot progress until the callback returns. + * + * @return string Why waiting stopped, for the caller to report when this + * method left the transfer unsettled + */ + private function failNestedWait(int $id, object $token): string + { + $stalled = $this->describeStalledWait($id, $token); + + if (!$this->hasRequest($id, $token)) { + return $stalled; + } + + $entry = $this->handles[$id]; + $message = 'Cannot synchronously wait for a transfer from inside a cURL callback on the same cURL multi handler; the callback must return before the transfer can progress.'; + $response = $entry['easy']->response; + $failure = $response !== null + ? new ResponseException($message, $entry['easy']->request, $response) + : new RequestException($message, $entry['easy']->request); + + if (!empty($entry['attached'])) { + // Native removal must wait until the outermost execution unwinds. + unset($this->handles[$id], $this->delays[$id], $this->deferredAdds[$id]); + $this->deferredCancels[$id] = ['easy' => $entry['easy'], 'attached' => true]; + } else { + $this->discardPendingRequest($id, $entry, $failure); + } + + $entry['deferred']->reject($failure); + + return $stalled; + } + + /** + * Cancels a request whose wait threw, since that rejects its promise. + */ + private function discardInterruptedRequest(int $id, object $waitToken, \Throwable $failure): \Throwable + { + try { + $this->cancel($id, $waitToken); + } catch (\Throwable $e) { + // Preserve the original failure. + } + + return $failure; + } + + private function disposeEasyHandle( + #[\SensitiveParameter] + EasyHandle $easy + ): void { + if (!self::hasEasyHandle($easy)) { + return; + } + + $handle = $easy->handle; + unset($easy->handle); + + $failure = null; + + try { + $this->clearEasyHandleCallbacks($handle); + } catch (\Throwable $e) { + $failure = $e; + } + + try { + if (PHP_VERSION_ID < 80000 && \is_resource($handle)) { + \curl_close($handle); + } + } catch (\Throwable $e) { + if ($failure === null) { + $failure = $e; + } + } + + if ($failure !== null) { + throw $failure; + } + } + + /** + * @param resource|\CurlHandle $handle + */ + private function clearEasyHandleCallbacks( + #[\SensitiveParameter] + $handle + ): void { + curl_setopt($handle, \CURLOPT_HEADERFUNCTION, null); + curl_setopt($handle, \CURLOPT_READFUNCTION, null); + curl_setopt($handle, \CURLOPT_WRITEFUNCTION, null); + curl_setopt($handle, \CURLOPT_PROGRESSFUNCTION, null); + + if (\defined('CURLOPT_PREREQFUNCTION')) { + curl_setopt($handle, (int) \constant('CURLOPT_PREREQFUNCTION'), null); + } + + if (\defined('CURLOPT_SEEKFUNCTION')) { + curl_setopt($handle, (int) \constant('CURLOPT_SEEKFUNCTION'), null); + } + + if (\defined('CURLOPT_XFERINFOFUNCTION')) { + curl_setopt($handle, (int) \constant('CURLOPT_XFERINFOFUNCTION'), null); + } + } + + /** + * @param resource|\CurlHandle $handle + */ + private function removeHandleFromMulti( + int $id, + #[\SensitiveParameter] + $handle + ): void { + // Removing a still-running transfer performs a final progress update + // that can run a user progress callback, so removal is guarded like + // native execution. + ++$this->multiExecDepth; + + try { + \curl_multi_remove_handle($this->getMultiHandle(), $handle); + } finally { + --$this->multiExecDepth; + $this->unmarkProxyTunnelActiveById($id); + $this->finishDeferredWork(); + } + } + + private function hasMultiHandle(): bool + { + return $this->multiHandle !== null; + } + + private static function hasEasyHandle(EasyHandle $easy): bool + { + return \array_key_exists('handle', \get_object_vars($easy)); + } + + private function addRequest( + #[\SensitiveParameter] + array $entry + ): void { + $easy = $entry['easy']; + $id = (int) $easy->handle; + $entry['attached'] = false; + + $displaced = $this->handles[$id] ?? null; + if ($displaced !== null) { + // Never silently discard a tracked entry; settle it first. + unset($this->handles[$id], $this->delays[$id], $this->deferredAdds[$id]); + if (P\State::isPending($displaced['deferred'])) { + $message = \sprintf('cURL multi handler transfer %d was displaced by another request that reused its native cURL handle ID.', $id); + $response = $displaced['easy']->response; + $failure = $response !== null + ? new ResponseException($message, $displaced['easy']->request, $response) + : new RequestException($message, $displaced['easy']->request); + $displaced['deferred']->reject($failure); + } + } + + $this->handles[$id] = $entry; + + if (!empty($easy->options['delay'])) { + $this->delays[$id] = Clock::now() + ($easy->options['delay'] / 1000); + } elseif ($this->multiExecDepth > 0) { + // A request created from inside a cURL callback cannot be added + // natively while curl_multi_exec() is running; libcurl 7.59+ + // rejects the recursive call. Attach it once the outermost + // native execution unwinds. + $this->deferredAdds[$id] = $entry['wait_token'] ?? null; + } else { + $this->addHandleToMulti($id, $easy); + } + } + + /** + * Cancels a handle from sending and removes references to it. + * + * @param int $id Handle ID to cancel and remove. + * @param object|null $waitToken Identity token that must still match the + * entry when given. + * + * @return bool True on success, false on failure. + */ + private function cancel(int $id, ?object $waitToken = null): bool + { + // Cannot cancel if it has been processed or replaced by a request + // that reused the native handle ID. + if (!$this->hasRequest($id, $waitToken)) { + return false; + } + + $entry = $this->handles[$id]; + $easy = $entry['easy']; + $attached = !empty($entry['attached']); + unset($this->delays[$id], $this->deferredAdds[$id], $this->handles[$id]); + + if ($this->multiExecDepth > 0) { + $this->deferredCancels[$id] = ['easy' => $easy, 'attached' => $attached]; + + return true; + } + + $failure = null; + + if ($attached && $this->hasMultiHandle() && self::hasEasyHandle($easy)) { + $this->captureFailure($failure, function () use ($id, $easy): void { + $this->removeHandleFromMulti($id, $easy->handle); + }); + } + + $this->captureFailure($failure, function () use ($easy): void { + $this->disposeEasyHandle($easy); + }); + + if ($failure !== null) { + throw $failure; + } + + return true; + } + + private function cleanupDeferredCancels(?\Throwable &$failure): void + { + if ($this->deferredCancels === []) { + return; + } + + $entries = $this->deferredCancels; + $this->deferredCancels = []; + + foreach ($entries as $id => $entry) { + $easy = $entry['easy']; + + if ($entry['attached'] && $this->hasMultiHandle() && self::hasEasyHandle($easy)) { + $this->captureFailure($failure, function () use ($id, $easy): void { + $this->removeHandleFromMulti($id, $easy->handle); + }); + } + + $this->captureFailure($failure, function () use ($easy): void { + $this->disposeEasyHandle($easy); + }); + } + } + + private function processMessages(): void + { + // CurlFactory::finish can retry a transfer by re-invoking this handler + // from inside this loop; the guard keeps that re-entry from recreating + // the multi handle mid-iteration (see applyProxyTunnelOwnership). A + // depth is tracked because a completion callback can re-enter tick(), + // and the nested frame must not clear the outer loop's guard. + ++$this->messageProcessingDepth; + + try { + // A completion callback may close the handler mid-loop; the close + // is deferred (closing is set first), and the loop must stop + // before touching the multi handle again. Remaining in-flight + // transfers were moved to the deferred cancels by deferClose(). + while (!$this->closed && !$this->closing) { + $done = \curl_multi_info_read($this->getMultiHandle()); + if (false === $done) { + break; + } + + if ($done['msg'] !== \CURLMSG_DONE) { + // If it is not done, removing the handle would be premature. + // See https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216. + continue; + } + if (!isset($done['handle'])) { + // Work around a PHP issue where cancelled transfers may omit the handle. + // Remove this once we no longer support PHP versions before the fix in + // https://github.com/php/php-src/pull/16302. + continue; + } + $id = (int) $done['handle']; + $this->removeHandleFromMulti($id, $done['handle']); + + if (!isset($this->handles[$id])) { + // Probably was cancelled. + continue; + } + + $entry = $this->handles[$id]; + unset($this->handles[$id], $this->delays[$id]); + $entry['easy']->errno = $done['result']; + + // finish() can run completion callbacks that cancel this + // promise; a settled promise must not be settled again. + try { + $result = CurlFactory::finish($this, $entry['easy'], $this->factory); + } catch (\Throwable $e) { + if (P\State::isPending($entry['deferred'])) { + $entry['easy']->deferredSettled = true; + $entry['deferred']->reject($e); + } + + continue; + } + + if (P\State::isPending($entry['deferred'])) { + $entry['easy']->deferredSettled = true; + $entry['deferred']->resolve($result); + } + } + } finally { + --$this->messageProcessingDepth; + $this->finishDeferredWork(); + } + } + + /** + * Bounds a blocking select by the earliest pending request delay so a + * delayed transfer becoming due does not wait out an unrelated + * transfer's full select timeout. + */ + private function effectiveSelectTimeout(): float + { + if ($this->delays === []) { + return $this->selectTimeout; + } + + return \min($this->selectTimeout, $this->secondsToNext()); + } + + /** + * @return float Seconds until the earliest pending delay is due + */ + private function secondsToNext(): float + { + $currentTime = Clock::now(); + $nextTime = \PHP_FLOAT_MAX; + foreach ($this->delays as $time) { + if ($time < $nextTime) { + $nextTime = $time; + } + } + + return \max(0.0, $nextTime - $currentTime); + } + + private function timeToNext(): int + { + // PHP_INT_MAX first: min() then returns the int operand whenever the + // microseconds exceed it, so the cast never sees an oversized float. + return (int) \min(\PHP_INT_MAX, $this->secondsToNext() * 1000000); + } + + /** + * @return resource|\CurlMultiHandle + */ + private function getMultiHandle() + { + if ($this->multiHandle !== null) { + return $this->multiHandle; + } + + $this->assertOpen(); + + $multiHandle = \curl_multi_init(); + if (false === $multiHandle) { + throw new \RuntimeException('Can not initialize curl multi handle.'); + } + + try { + foreach ($this->options as $option => $value) { + if (!\is_int($option)) { + throw new InvalidArgumentException(\sprintf('Invalid cURL multi option "%s".', Psr7\DiagnosticValue::escape((string) $option))); + } + + try { + $applied = @curl_multi_setopt($multiHandle, $option, $value); + } catch (\Throwable $e) { + throw new InvalidArgumentException( + \sprintf('Unable to apply the cURL multi option %s; it was rejected by the runtime libcurl.', self::formatCurlMultiOption($option)), + 0, + $e + ); + } + + if (true !== $applied) { + throw new InvalidArgumentException(\sprintf('Unable to apply the cURL multi option %s; it was rejected by the runtime libcurl.', self::formatCurlMultiOption($option))); + } + } + } catch (\Throwable $e) { + \curl_multi_close($multiHandle); + + throw $e; + } + + $this->multiHandle = $multiHandle; + + return $this->multiHandle; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlShareHandleState.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlShareHandleState.php new file mode 100644 index 0000000..77bcc8b --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlShareHandleState.php @@ -0,0 +1,276 @@ +mode = $mode; + $this->handle = $handle; + } + + /** + * @param mixed $sharing + */ + public static function fromOption($sharing): ?self + { + if ($sharing instanceof self) { + return $sharing; + } + + $mode = self::normalizeMode($sharing, 'transport_sharing'); + if ($mode === TransportSharing::NONE) { + return null; + } + + if ($mode === TransportSharing::HANDLER_PREFER) { + return self::createHandlerShareOrNull($mode); + } + + if ($mode === TransportSharing::HANDLER_REQUIRE) { + return self::createHandlerShare($mode); + } + + if ($mode === TransportSharing::PERSISTENT_PREFER) { + return self::createPersistentShareOrFallback(); + } + + return self::createPersistentShare($mode); + } + + /** + * @param mixed $sharing + */ + public static function normalizeMode($sharing, string $option): string + { + if ($sharing instanceof self) { + return $sharing->mode; + } + + if ($sharing === null || $sharing === TransportSharing::NONE) { + return TransportSharing::NONE; + } + + if ( + $sharing === TransportSharing::HANDLER_PREFER + || $sharing === TransportSharing::HANDLER_REQUIRE + || $sharing === TransportSharing::PERSISTENT_PREFER + || $sharing === TransportSharing::PERSISTENT_REQUIRE + ) { + return $sharing; + } + + throw new InvalidArgumentException(\sprintf( + 'The "%s" option must be null or a GuzzleHttp\\TransportSharing::* constant; received %s.', + $option, + \get_debug_type($sharing) + )); + } + + public static function assertNoRequiredSharingCustomFactoryConflict(array $options, string $handlerName): void + { + if (!\array_key_exists('handle_factory', $options) || $options['handle_factory'] === null) { + return; + } + + $mode = self::normalizeMode($options['transport_sharing'] ?? null, 'transport_sharing'); + if (!\in_array($mode, [TransportSharing::HANDLER_REQUIRE, TransportSharing::PERSISTENT_REQUIRE], true)) { + return; + } + + throw new InvalidArgumentException(\sprintf( + 'The "transport_sharing" %s option cannot require sharing with a custom "handle_factory" because Guzzle cannot ensure that the custom factory applies CURLOPT_SHARE.', + $handlerName + )); + } + + /** + * Whether cURL can share both the DNS and SSL session cache state that + * required handler-lifetime sharing needs, checked without configuring a + * share handle so default handler selection can fall back to the stream + * handler instead. + */ + public static function supportsHandlerRequireShare(): bool + { + return CurlVersion::supportsHandlerSharing() + && CurlVersion::supportsSslSessionSharing() + && \function_exists('curl_share_init') + && \function_exists('curl_share_setopt') + && \defined('CURLOPT_SHARE') + && \defined('CURLSHOPT_SHARE') + && \defined('CURL_LOCK_DATA_DNS') + && \defined('CURL_LOCK_DATA_SSL_SESSION'); + } + + private static function createHandlerShareOrNull(string $mode): ?self + { + try { + return self::createHandlerShare($mode); + } catch (\Throwable $e) { + return null; + } + } + + private static function createHandlerShare(string $mode): self + { + if (!\function_exists('curl_share_init') || !\function_exists('curl_share_setopt')) { + throw new InvalidArgumentException('The "transport_sharing" option requires cURL share support.'); + } + + self::requireCurlConstant('CURLOPT_SHARE'); + $shareOption = self::requireCurlConstant('CURLSHOPT_SHARE'); + $locks = self::handlerLocks($mode); + $handle = curl_share_init(); + + try { + foreach ($locks as $lock) { + try { + $success = curl_share_setopt($handle, $shareOption, $lock); + } catch (\Throwable $e) { + throw new InvalidArgumentException('Unable to configure cURL share handle: '.$e->getMessage(), 0, $e); + } + + if (!$success) { + throw new InvalidArgumentException(\sprintf('Unable to configure cURL share handle with lock data %d.', $lock)); + } + } + } catch (\Throwable $e) { + self::closeHandlerShareHandleOnPhp7($handle); + + throw $e; + } + + return new self($mode, $handle); + } + + private static function createPersistentShareOrFallback(): ?self + { + if (self::supportsPersistentShare()) { + try { + return self::createPersistentShare(TransportSharing::PERSISTENT_PREFER); + } catch (\Throwable $e) { + // Fall back to handler-lifetime best effort below. + } + } + + return self::createHandlerShareOrNull(TransportSharing::HANDLER_PREFER); + } + + private static function createPersistentShare(string $mode): self + { + CurlVersion::ensureConnectionSharingSupported(); + CurlVersion::ensureSslSessionSharingSupported(); + + if (!self::supportsPersistentShare()) { + throw new InvalidArgumentException('The "transport_sharing" option requires persistent cURL share handle support.'); + } + + self::requireCurlConstant('CURLOPT_SHARE'); + + try { + $handle = curl_share_init_persistent(self::persistentLocks()); + } catch (\Throwable $e) { + throw new InvalidArgumentException( + 'Unable to create persistent cURL share handle: '.$e->getMessage(), + 0, + $e + ); + } + + return new self($mode, $handle); + } + + private static function supportsPersistentShare(): bool + { + return CurlVersion::supportsConnectionSharing() + && CurlVersion::supportsSslSessionSharing() + && \function_exists('curl_share_init_persistent') + && \class_exists('CurlSharePersistentHandle') + && \defined('CURL_LOCK_DATA_DNS') + && \defined('CURL_LOCK_DATA_CONNECT') + && \defined('CURL_LOCK_DATA_SSL_SESSION'); + } + + /** + * @return int[] + */ + private static function handlerLocks(string $mode): array + { + CurlVersion::ensureHandlerSharingSupported(); + + if ($mode === TransportSharing::HANDLER_REQUIRE) { + CurlVersion::ensureSslSessionSharingSupported(); + } + + $locks = [ + self::requireCurlConstant('CURL_LOCK_DATA_DNS'), + ]; + + if (CurlVersion::supportsSslSessionSharing()) { + $locks[] = self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION'); + } + + return $locks; + } + + /** + * @return int[] + */ + private static function persistentLocks(): array + { + return [ + self::requireCurlConstant('CURL_LOCK_DATA_DNS'), + self::requireCurlConstant('CURL_LOCK_DATA_CONNECT'), + self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION'), + ]; + } + + private static function requireCurlConstant(string $constant): int + { + if (!\defined($constant)) { + throw new InvalidArgumentException(\sprintf( + 'The "transport_sharing" option requires %s, but it is not available in the installed PHP cURL extension.', + $constant + )); + } + + $value = \constant($constant); + if (!\is_int($value)) { + throw new InvalidArgumentException(\sprintf('The cURL constant %s must resolve to an integer.', $constant)); + } + + return $value; + } + + /** + * @param resource|\CurlShareHandle $handle + */ + private static function closeHandlerShareHandleOnPhp7($handle): void + { + if (\PHP_VERSION_ID < 80000 && \is_resource($handle)) { + curl_share_close($handle); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlVersion.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlVersion.php new file mode 100644 index 0000000..c3df944 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlVersion.php @@ -0,0 +1,407 @@ +=') + && 0 !== (\CURL_VERSION_SSL & $versionInfo['features']); + } + + public static function supportsTls13(): bool + { + $version = self::get(); + + return \defined('CURL_SSLVERSION_TLSv1_3') + && null !== $version + && version_compare($version, self::TLS_13_VERSION, '>='); + } + + public static function supportsMultiplex(): bool + { + $version = self::get(); + + return \defined('CURLOPT_PIPEWAIT') + && null !== $version + && version_compare($version, self::MULTIPLEX_VERSION, '>='); + } + + public static function supportsHttpVersionReuseMatching(): bool + { + $version = self::get(); + + if (null === $version || version_compare($version, self::HTTP_VERSION_REUSE_MATCH_VERSION, '<')) { + return false; + } + + return version_compare($version, self::HTTP_VERSION_REUSE_MATCH_REGRESSION, '<') + || version_compare($version, self::HTTP_VERSION_REUSE_MATCH_RESTORED, '>='); + } + + public static function supportsRequiredHttp2Multiplex(): bool + { + $version = self::get(); + + return \defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE') + && null !== $version + && self::supportsHttp2() + && version_compare($version, self::REQUIRED_HTTP2_MULTIPLEX_VERSION, '>='); + } + + public static function supportsHttp2(): bool + { + $versionInfo = self::getVersionInfo(); + + // Requiring dependable CURLOPT_PIPEWAIT support keeps waiting from + // ever being silently unavailable where HTTP/2 works. + return \defined('CURL_VERSION_HTTP2') + && null !== $versionInfo + && self::supportsMultiplex() + && 0 !== (\CURL_VERSION_HTTP2 & $versionInfo['features']); + } + + public static function supportsHttp3(): bool + { + if (!\defined('CURL_VERSION_HTTP3') || !\defined('CURL_HTTP_VERSION_3') || !\defined('CURL_HTTP_VERSION_3ONLY')) { + return false; + } + + $versionInfo = self::getVersionInfo(); + if (null === $versionInfo || version_compare($versionInfo['version'], self::HTTP_3_VERSION, '<')) { + return false; + } + + return 0 !== ((int) \constant('CURL_VERSION_HTTP3') & $versionInfo['features']); + } + + public static function supportsRequiredHttp3Multiplex(): bool + { + $version = self::get(); + + return self::supportsHttp3() + && null !== $version + && version_compare($version, self::REQUIRED_HTTP3_MULTIPLEX_VERSION, '>='); + } + + public static function supportsHttpsProxy(): bool + { + $versionInfo = self::getVersionInfo(); + + return \defined('CURL_VERSION_HTTPS_PROXY') + && null !== $versionInfo + && version_compare($versionInfo['version'], self::HTTPS_PROXY_VERSION, '>=') + && 0 !== (\CURL_VERSION_HTTPS_PROXY & $versionInfo['features']); + } + + public static function supportsHandlerSharing(): bool + { + $version = self::get(); + + return null !== $version + && version_compare($version, self::HANDLER_SHARING_VERSION, '>='); + } + + public static function ensureHandlerSharingSupported(): void + { + if (!self::supportsHandlerSharing()) { + throw new InvalidArgumentException(\sprintf( + 'The "transport_sharing" option requires libcurl %s or higher for cURL share handles.', + self::HANDLER_SHARING_VERSION + )); + } + } + + public static function supportsSslSessionSharing(): bool + { + $versionInfo = self::getVersionInfo(); + + return \defined('CURL_VERSION_SSL') + && null !== $versionInfo + && version_compare($versionInfo['version'], self::SSL_SESSION_SHARING_VERSION, '>=') + && 0 !== (\CURL_VERSION_SSL & $versionInfo['features']); + } + + public static function ensureSslSessionSharingSupported(): void + { + if (!self::supportsSslSessionSharing()) { + throw new InvalidArgumentException(\sprintf( + 'The "transport_sharing" option requires libcurl %s or higher with SSL support for SSL session sharing.', + self::SSL_SESSION_SHARING_VERSION + )); + } + } + + public static function supportsConnectionSharing(): bool + { + $version = self::get(); + + return null !== $version + && version_compare($version, self::CONNECTION_SHARING_VERSION, '>='); + } + + public static function ensureConnectionSharingSupported(): void + { + if (!self::supportsConnectionSharing()) { + throw new InvalidArgumentException(\sprintf( + 'The "transport_sharing" option requires libcurl %s or higher for persistent connection sharing.', + self::CONNECTION_SHARING_VERSION + )); + } + } + + public static function supportsSharedPoolConnectionCaps(): bool + { + $version = self::get(); + + return null !== $version + && version_compare($version, self::SHARED_POOL_CONNECTION_CAP_VERSION, '>='); + } + + public static function supportsShareConnectionCaches(): bool + { + $version = self::get(); + + // An undetectable libcurl version is treated as capable so the + // opaque share safeguards fail closed. + return null === $version + || version_compare($version, self::SHARE_CONNECTION_CACHE_VERSION, '>='); + } + + public static function supportsProxyTlsCredentialAwareConnectionReuse(): bool + { + $version = self::get(); + + return null !== $version + && version_compare($version, self::PROXY_TLS_CREDENTIAL_REUSE_VERSION, '>='); + } + + public static function supportsProxyCredentialAwareConnectionReuse(): bool + { + $version = self::get(); + + return null !== $version + && version_compare($version, self::PROXY_CREDENTIAL_REUSE_VERSION, '>='); + } + + public static function supportsSocksProxyCredentialAwareConnectionReuse(): bool + { + $version = self::get(); + + return null !== $version + && version_compare($version, self::SOCKS_PROXY_CREDENTIAL_REUSE_VERSION, '>='); + } + + public static function supportsProxyHeaderSeparation(): bool + { + $version = self::get(); + + return null !== $version + && version_compare($version, self::PROXY_HEADER_SEPARATION_VERSION, '>=') + && \defined('CURLOPT_PROXYHEADER') + && \defined('CURLOPT_HEADEROPT') + && \defined('CURLHEADER_SEPARATE'); + } + + public static function supportsProtocolsStr(): bool + { + $version = self::get(); + + return \defined('CURLOPT_PROTOCOLS_STR') + && null !== $version + && version_compare($version, self::PROTOCOLS_STR_VERSION, '>='); + } + + public static function supportsProxyTunneling(): bool + { + $version = self::get(); + + return \defined('CURLOPT_SUPPRESS_CONNECT_HEADERS') + && null !== $version + && version_compare($version, self::PROXY_TUNNEL_VERSION, '>='); + } + + public static function ensureSupported( + #[\SensitiveParameter] + RequestInterface $request + ): void { + if (self::supportsCurlHandler()) { + return; + } + + $version = self::get(); + + if (null === $version || version_compare($version, self::MIN_VERSION, '<')) { + throw new ConnectException(\sprintf( + 'cURL %s or higher is required by the cURL handler; %s is installed.', + self::MIN_VERSION, + $version ?? 'an unknown version' + ), $request); + } + + if (!\defined('CURL_SSLVERSION_TLSv1_2')) { + throw new ConnectException(\sprintf( + 'The PHP cURL extension must be built against cURL %s or higher to use the cURL handler.', + self::MIN_VERSION + ), $request); + } + + if (!\defined('CURLMOPT_MAX_HOST_CONNECTIONS') || !\defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')) { + throw new ConnectException('The PHP cURL extension must expose CURLMOPT_MAX_HOST_CONNECTIONS and CURLMOPT_MAX_TOTAL_CONNECTIONS to use the cURL handler.', $request); + } + + throw new ConnectException('The cURL handler requires libcurl SSL support.', $request); + } + + private static function get(): ?string + { + $versionInfo = self::getVersionInfo(); + + return null === $versionInfo ? null : $versionInfo['version']; + } + + /** + * @return array{version: string, features: int}|null + */ + private static function getVersionInfo(): ?array + { + if (null === self::$versionInfo) { + if (!\function_exists('curl_version')) { + self::$versionInfo = false; + } else { + $versionInfo = \curl_version(); + self::$versionInfo = \is_array($versionInfo) + && isset($versionInfo['version'], $versionInfo['features']) + && \is_string($versionInfo['version']) + && \is_int($versionInfo['features']) + ? [ + 'version' => $versionInfo['version'], + 'features' => $versionInfo['features'], + ] + : false; + } + } + + return false === self::$versionInfo ? null : self::$versionInfo; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/DeadlineSourceStream.php b/vendor/guzzlehttp/guzzle/src/Handler/DeadlineSourceStream.php new file mode 100644 index 0000000..122548d --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/DeadlineSourceStream.php @@ -0,0 +1,82 @@ +stream = $stream; + $this->deadline = $deadline; + $this->readTimeout = $readTimeout; + } + + public function read(int $length): string + { + $idleStart = null; + + while (true) { + $remaining = $this->deadline - Clock::now(); + if ($remaining <= 0) { + throw new TimeoutException('Unable to read from stream: timed out'); + } + + $data = $this->stream->read($length); + if ($data !== '') { + return $data; + } + if ($this->stream->eof()) { + return ''; + } + + $now = Clock::now(); + if ($idleStart === null) { + $idleStart = $now; + } + if ($this->readTimeout !== null && $now - $idleStart >= $this->readTimeout) { + throw new TimeoutException('Unable to read from stream: timed out'); + } + + $wait = \min($remaining, self::POLL_INTERVAL); + if ($this->readTimeout !== null) { + $wait = \min($wait, $this->readTimeout - ($now - $idleStart)); + } + \usleep((int) \ceil($wait * 1e6)); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/DebugResource.php b/vendor/guzzlehttp/guzzle/src/Handler/DebugResource.php new file mode 100644 index 0000000..c2bdc38 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/DebugResource.php @@ -0,0 +1,36 @@ +stream = $stream; + $this->remaining = $declaredLength; + } + + public function __clone() + { + // Detaching a clone must not detach this body's transport. + $this->stream = clone $this->stream; + } + + public function eof(): bool + { + return $this->remaining === 0; + } + + public function isSeekable(): bool + { + return false; + } + + public function seek(int $offset, int $whence = \SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a response body bounded by its declared Content-Length'); + } + + /** + * @return mixed + */ + public function getMetadata(?string $key = null) + { + // A failed body has not timed out, whatever a stale flag on the + // transport says, so callers report the failure itself. + if ($this->failure !== null && $key === 'timed_out') { + return false; + } + + $metadata = $this->stream->getMetadata($key); + if ($this->failure !== null && $key === null && \is_array($metadata)) { + $metadata['timed_out'] = false; + } + + return $metadata; + } + + public function read(int $length): string + { + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if ($this->failure !== null) { + throw $this->failure; + } + + if ($length === 0 || $this->remaining === 0) { + return ''; + } + + $data = $this->stream->read(\min($length, $this->remaining)); + if ($data === '' && $this->stream->eof()) { + $this->failure = new \RuntimeException('Response body ended before the declared Content-Length was reached'); + + throw $this->failure; + } + + $this->remaining -= \strlen($data); + + return $data; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php b/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php new file mode 100644 index 0000000..99eb58a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php @@ -0,0 +1,260 @@ + Received HTTP headers so far + */ + public array $headers = []; + + /** + * @var list Valid trailer lines, retained only when an + * on_trailers callback is configured + */ + public array $trailers = []; + + /** + * @var bool Whether this handle was configured with CURLOPT_PIPEWAIT + */ + public bool $usesPipewait = false; + + /** + * @var bool Whether processMessages() settled the deferred promise, which + * a rewind retry settles with a still-pending promise + */ + public bool $deferredSettled = false; + + /** + * @var ResponseInterface|null Received response (if any) + */ + public ?ResponseInterface $response = null; + + /** + * @var array Request options + */ + public array $options = []; + + /** + * @var int cURL error number (if any) + */ + public int $errno = 0; + + /** + * @var string|null Effective CURLOPT_PROXY value the handle was created with (if any) + */ + public ?string $effectiveProxy = null; + + /** + * Proxy tunnel or SOCKS proxy section signature for connection-reuse + * isolation, or null when the request does not require sectioning. + */ + public ?string $proxyTunnelSignature = null; + + /** + * @var \Throwable|null Exception during on_headers (if any) + */ + public ?\Throwable $onHeadersException = null; + + /** + * @var \Throwable|null Exception during progress callback (if any) + */ + public ?\Throwable $progressException = null; + + /** + * @var bool Whether the progress callback requested abort + */ + public bool $progressAborted = false; + + /** + * @var \Throwable|null Exception during createResponse (if any) + */ + public ?\Throwable $createResponseException = null; + + /** + * @var ResponseException|null Response header failure, if any. + */ + public ?ResponseException $responseHeaderException = null; + + /** + * @var TimeoutException|null Exception during request body read timeout. + */ + public ?TimeoutException $bodyReadTimeoutException = null; + + /** + * @var TimeoutException|null Exception during request body rewind timeout. + */ + public ?TimeoutException $bodyRewindTimeoutException = null; + + /** + * @var \Throwable|null Exception during request body rewind. + */ + public ?\Throwable $bodyRewindException = null; + + /** + * @var \Throwable|null Exception during request body read. + */ + public ?\Throwable $bodyReadException = null; + + /** + * @var TimeoutException|null Exception during response sink write timeout. + */ + public ?TimeoutException $sinkWriteTimeoutException = null; + + /** + * @var \Throwable|null Exception during response sink write. + */ + public ?\Throwable $sinkWriteException = null; + + /** + * @var bool Whether the response sink accepted a different byte count. + */ + public bool $sinkWriteIncomplete = false; + + /** + * @var int Number of response body bytes accepted by the sink. + */ + public int $responseBodyBytes = 0; + + /** + * @var \OverflowException|null Unrepresentable response body size or byte count. + */ + public ?\OverflowException $responseBodySizeException = null; + + /** + * Attach a response to the easy handle based on the received headers. + * + * @throws \RuntimeException if no headers have been received or the first + * header line is invalid. + */ + public function createResponse(): void + { + $this->response = null; + $this->responseBodyBytes = 0; + $this->responseBodySizeException = null; + $this->responseHeaderException = null; + + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers); + + // Non-101 informational responses precede the final response. Do not + // expose them as the response for a transfer that ends before the final + // response arrives. 101 switches protocol and is kept as terminal. + if ($status < 200 && $status !== 101) { + return; + } + + $framingFailure = null; + try { + $declaredLength = HeaderProcessor::validateResponseFraming($this->request->getMethod(), $status, $headers); + HeaderProcessor::assertContentLengthWithinPlatformLimit($declaredLength); + } catch (\RuntimeException $e) { + $framingFailure = $e; + } + + $normalizedKeys = HeaderProcessor::normalizeHeaderKeys($headers); + $decodeContent = $this->options['decode_content'] ?? false; + if ($framingFailure === null && $decodeContent !== false && isset($normalizedKeys['content-encoding'])) { + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + unset($headers[$normalizedKeys['content-encoding']]); + $encodedContentLength = HeaderProcessor::removeHeader('Content-Length', $headers); + if ($encodedContentLength !== []) { + $headers['x-encoded-content-length'] = $encodedContentLength; + + try { + $bodyLength = $this->sink->getSize(); + } catch (\Exception $e) { + $bodyLength = null; + } + if ($bodyLength) { + $headers['Content-Length'] = [(string) $bodyLength]; + } + } + } + + // Attach a response to the easy handle with the parsed headers. Any + // exception propagates to the caller (CurlFactory), which records it as + // the createResponseException — do not catch it here. + $responseFactory = self::requireResponseFactory($this->options[RequestOptions::RESPONSE_FACTORY] ?? new HttpFactory()); + $response = $responseFactory->createResponse($status, $reason ?? '')->withProtocolVersion($ver); + foreach ($headers as $name => $value) { + $response = $response->withAddedHeader((string) $name, $value); + } + $this->response = $response->withBody($this->sink); + + if ($framingFailure instanceof \OverflowException) { + $this->responseHeaderException = new ResponseException( + $framingFailure->getMessage(), + $this->request, + $this->response, + $framingFailure + ); + } elseif ($framingFailure !== null) { + $this->responseHeaderException = new ResponseTransferException( + $framingFailure->getMessage(), + $this->request, + $this->response, + $framingFailure + ); + } + } + + /** + * @param mixed $factory + */ + private static function requireResponseFactory($factory): ResponseFactoryInterface + { + if (!$factory instanceof ResponseFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::RESPONSE_FACTORY, + ResponseFactoryInterface::class + )); + } + + return $factory; + } + + /** + * @throws \BadMethodCallException + */ + public function __get(string $name): void + { + $msg = $name === 'handle' + ? 'The EasyHandle has been released' + : \sprintf('Invalid property: %s', DiagnosticValue::escape($name)); + + throw new \BadMethodCallException($msg); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/EncodedBodyStream.php b/vendor/guzzlehttp/guzzle/src/Handler/EncodedBodyStream.php new file mode 100644 index 0000000..ad648e6 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/EncodedBodyStream.php @@ -0,0 +1,83 @@ +stream = $stream; + + $limit = HeaderProcessor::contentLengthToInt($declaredLength); + $this->limit = $limit !== null && $limit > 0 ? $limit : null; + } + + public function eof(): bool + { + return ($this->limit !== null && $this->bytesRead >= $this->limit) + || $this->stream->eof(); + } + + public function isSeekable(): bool + { + return false; + } + + public function seek(int $offset, int $whence = \SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a stream while tracking encoded response bytes'); + } + + public function read(int $length): string + { + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if ($this->limit !== null) { + $remaining = $this->limit - $this->bytesRead; + if ($remaining === 0) { + return ''; + } + + $length = \min($length, $remaining); + } + + $data = $this->stream->read($length); + $this->bytesRead = TransferByteCounter::add( + $this->bytesRead, + \strlen($data), + 'Response body exceeds the maximum integer size supported on this platform' + ); + + return $data; + } + + public function getBytesRead(): int + { + return $this->bytesRead; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php b/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php new file mode 100644 index 0000000..24edafd --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php @@ -0,0 +1,330 @@ + \strlen($max) + || (\strlen($length) === \strlen($max) && \strcmp($length, $max) > 0) + ) { + return null; + } + + return (int) $length; + } + + public static function assertContentLengthWithinPlatformLimit(?string $length): void + { + if ($length === null || self::contentLengthToInt($length) !== null) { + return; + } + + throw new \OverflowException('Content-Length exceeds the maximum integer size supported on this platform'); + } + + /** + * Validates response framing and returns its normalized Content-Length. + * Returns null when absent or when ordinary body framing does not apply. + * + * @param array $headers + * + * @throws \RuntimeException when Content-Length is malformed, conflicting, + * or combined with Transfer-Encoding, or when a + * transfer coding is unsupported or follows + * chunked on the same field line + */ + public static function validateResponseFraming( + string $method, + int $status, + array $headers + ): ?string { + if (!self::responseCanHaveBody($method, $status)) { + return null; + } + + $normalizedKeys = self::normalizeHeaderKeys($headers); + $contentLength = self::removeHeader('Content-Length', $headers); + + try { + $length = self::parseContentLength($contentLength); + } catch (\RuntimeException $e) { + throw new \RuntimeException('Invalid Content-Length response header: '.$e->getMessage(), 0, $e); + } + + if ($length !== null && isset($normalizedKeys['transfer-encoding'])) { + throw new \RuntimeException('A response must not contain both Content-Length and Transfer-Encoding'); + } + + self::parseTransferEncoding($headers); + + return $length; + } + + /** + * Returns whether the response uses the chunked transfer coding. + * + * Guzzle never asks for a transfer coding, so like libcurl 8.14 and newer + * it accepts only identity and chunked, with nothing but chunked after + * chunked on the same field line. Empty list elements are ignored. + * + * @param array $headers + * + * @throws \RuntimeException when a coding is unsupported or follows chunked + * on the same field line + */ + public static function parseTransferEncoding(array $headers): bool + { + $chunked = false; + + foreach ($headers as $name => $values) { + if (!Psr7\Utils::caselessEquals((string) $name, 'Transfer-Encoding')) { + continue; + } + + foreach ($values as $value) { + $afterChunked = false; + foreach (\explode(',', $value) as $coding) { + $coding = \trim($coding, " \t"); + if ($coding === '') { + continue; + } + + if (Psr7\Utils::caselessEquals($coding, 'chunked')) { + $chunked = true; + $afterChunked = true; + } elseif ($afterChunked) { + throw new \RuntimeException('Invalid Transfer-Encoding response header: chunked is not the final transfer coding'); + } elseif (!Psr7\Utils::caselessEquals($coding, 'identity')) { + throw new \RuntimeException(\sprintf( + 'Invalid Transfer-Encoding response header: unsupported transfer coding "%s"', + Psr7\DiagnosticValue::escape($coding) + )); + } + } + } + } + + return $chunked; + } + + /** + * Removes every case-insensitive occurrence of a header and returns all + * removed values in their original field order. + * + * @param array $headers + * + * @return string[] Removed values across all header-name casings + */ + public static function removeHeader(string $name, array &$headers): array + { + $values = []; + + foreach ($headers as $key => $headerValues) { + if (Psr7\Utils::caselessEquals((string) $key, $name)) { + \array_push($values, ...$headerValues); + unset($headers[$key]); + } + } + + return $values; + } + + /** + * Creates an associative array of lowercase header names to the actual + * header casing. + */ + public static function normalizeHeaderKeys(array $headers): array + { + $result = []; + foreach (\array_keys($headers) as $key) { + $result[Psr7\Utils::asciiToLower((string) $key)] = $key; + } + + return $result; + } + + /** + * Whether a response uses ordinary body framing. A response to HEAD, a + * response with a 1xx, 204, or 304 status code, or a 2xx response to + * CONNECT never has a body, whatever its framing headers claim. A 205 + * remains subject to framing even though its semantics require no content. + */ + public static function responseCanHaveBody(string $method, int $status): bool + { + return $method !== 'HEAD' + && !($method === 'CONNECT' && $status >= 200 && $status < 300) + && $status >= 200 + && $status !== 204 + && $status !== 304; + } + + /** + * @param non-empty-list $headers + * + * @return list + */ + private static function getLastHeaderBlock(array $headers): array + { + $lastStatusLine = 0; + + foreach ($headers as $index => $line) { + if (self::isStatusLineCandidate($line)) { + $lastStatusLine = $index; + } + } + + return \array_slice($headers, $lastStatusLine); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/HostValidator.php b/vendor/guzzlehttp/guzzle/src/Handler/HostValidator.php new file mode 100644 index 0000000..1e74caf --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/HostValidator.php @@ -0,0 +1,162 @@ +getUri()->getHost(), $request); + + foreach ($request->getHeader('Host') as $value) { + self::assertPrintableAscii((string) $value, 'The request Host header "%s" must contain only printable ASCII characters, because an intermediary or an origin server can otherwise read it as an authority that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', $request); + } + } + + /** + * Only the URI host is reparsed for the connection. A Host header is sent + * verbatim and may carry a port, brackets, and an RFC 6874 zone identifier. + * + * @throws RequestException + */ + private static function assertUriHost( + string $host, + #[\SensitiveParameter] + RequestInterface $request + ): void { + self::assertPrintableAscii($host, 'The request URI host "%s" must contain only printable ASCII characters, because a handler can otherwise connect to a host that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', $request); + + if (\strpos($host, '%') !== false) { + throw new RequestException(\sprintf('The request URI host "%s" must not contain a percent escape, because a handler decodes it and can then connect to a host that differs from the one the request names.', self::escape($host)), $request); + } + + // GuzzleHttp\Psr7\Uri already enforces this predicate, so it only + // rejects invalid third-party UriInterface values. + if (!Psr7\Rfc3986::isValidHost($host)) { + throw new RequestException(\sprintf('The request URI host "%s" must be a valid RFC 3986 host, because a handler reparses the URI and can then connect to a host that differs from the one the request names.', self::escape($host)), $request); + } + + // libcurl 8.21.0 drops a trailing dot from inet_aton-style numeric + // hosts before connecting, while other readers treat the input as a + // name. Test the shape rather than the range so malformed numeric + // values fail closed. rtrim() also covers multiple trailing dots if + // libcurl later relaxes its current guard. Plain shorthand stays + // accepted. HostIdentity uses a broader grammar for cookie matching. + // + // @see \GuzzleHttp\HostIdentity::canonicalHost() + if (\str_ends_with($host, '.') && self::isNumericIpv4Host(\rtrim($host, '.'))) { + throw new RequestException(\sprintf('The request URI host "%s" must not be written as one to four decimal, octal or hexadecimal parts followed by one or more trailing dots, because a handler can read that spelling as an IPv4 address and connect to that address while the rest of the process reads a name.', self::escape($host)), $request); + } + } + + /** + * Reports whether a host has libcurl's inet_aton-style shape: one to four + * decimal, 0-prefixed octal, or 0x-prefixed hexadecimal parts. + * + * Range and 32-bit overflow checks are deliberately omitted. This may + * reject a trailing-dot spelling the transport reads as a name, but avoids + * missing one it resolves as an address. + */ + public static function isNumericIpv4Host(string $host): bool + { + if ($host === '') { + return false; + } + + $parts = \explode('.', $host); + + if (\count($parts) > 4) { + return false; + } + + foreach ($parts as $part) { + if (!self::isNumericIpv4Part($part)) { + return false; + } + } + + return true; + } + + private static function isNumericIpv4Part(string $part): bool + { + if ($part === '') { + return false; + } + + if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) { + return \strlen($part) > 2 && \strspn($part, '0123456789abcdefABCDEF', 2) === \strlen($part) - 2; + } + + $digits = $part[0] === '0' ? '01234567' : '0123456789'; + + return \strspn($part, $digits) === \strlen($part); + } + + /** + * @throws RequestException + */ + private static function assertPrintableAscii( + string $value, + string $message, + #[\SensitiveParameter] + RequestInterface $request + ): void { + // Match positively so a PCRE failure rejects. + if (\preg_match('/\A[\x21-\x7E]*\z/D', $value) !== 1) { + throw new RequestException(\sprintf($message, self::escape($value)), $request); + } + } + + /** + * Escapes non-printable bytes as uppercase \xNN for safe diagnostics. + * + * Psr7\DiagnosticValue is not used because it preserves valid non-ASCII + * UTF-8, including invisible characters rejected here. + */ + private static function escape(string $value): string + { + $escaped = ''; + + for ($offset = 0, $length = \strlen($value); $offset < $length; ++$offset) { + $byte = \ord($value[$offset]); + if ($byte >= 0x20 && $byte <= 0x7E) { + $escaped .= $value[$offset]; + + continue; + } + + $escaped .= \sprintf('\\x%02X', $byte); + } + + return $escaped; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/InflateBodyStream.php b/vendor/guzzlehttp/guzzle/src/Handler/InflateBodyStream.php new file mode 100644 index 0000000..2d92df8 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/InflateBodyStream.php @@ -0,0 +1,330 @@ +stream = $stream; + $this->deflate = $deflate; + } + + public function __toString(): string + { + return $this->getContents(); + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + public function close(): void + { + $stream = $this->stream; + $this->release(); + + if ($stream !== null) { + $stream->close(); + } + } + + public function detach() + { + if ($this->stream === null || !$this->detachable) { + return null; + } + + // Hand the decoder over to a resource that keeps yielding decoded + // bytes. That decoder cannot be detached again, so casting the resource + // to a descriptor fails instead of recursing. + $stream = clone $this; + $stream->detachable = false; + $this->release(); + + return StreamWrapper::getResource($stream); + } + + public function getSize(): ?int + { + return null; + } + + public function tell(): int + { + $this->attached(); + + return $this->position; + } + + public function eof(): bool + { + $stream = $this->attached(); + + // A failed body never ends, so resource readers see the failure + // instead of a clean end of the stream. + return $this->error === null && $this->offset === \strlen($this->buffer) && $stream->eof(); + } + + public function isSeekable(): bool + { + return false; + } + + public function seek(int $offset, int $whence = \SEEK_SET): void + { + throw new \RuntimeException('Stream is not seekable'); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function isWritable(): bool + { + return false; + } + + public function write(string $string): int + { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + public function isReadable(): bool + { + return $this->stream !== null && $this->stream->isReadable(); + } + + public function read(int $length): string + { + $stream = $this->attached(); + + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if ($length === 0) { + return ''; + } + + while ($this->offset === \strlen($this->buffer)) { + if ($this->error !== null) { + throw $this->error; + } + + $encoded = $stream->read(self::CHUNK_SIZE); + if ($encoded === '') { + return ''; + } + + if ($this->finished) { + if ($this->allowTrailing(\strlen($encoded))) { + continue; + } + + throw $this->fail(self::TRAILING_DATA); + } + + $this->buffer = $this->inflate($encoded); + $this->offset = 0; + } + + // Slice by offset, since a single inflate_add() call can return + // megabytes of highly compressible data. + $data = (string) \substr($this->buffer, $this->offset, $length); + $this->offset += \strlen($data); + $this->position = TransferByteCounter::add( + $this->position, + \strlen($data), + 'Response body exceeds the maximum integer size supported on this platform' + ); + + return $data; + } + + /** + * @return mixed + */ + public function getMetadata(?string $key = null) + { + if ($this->stream === null) { + return $key === null ? [] : null; + } + + // A decoding failure is not a timeout, even when Windows leaves the + // transport's timed_out flag set after a read drains PHP's buffer. + if ($key === 'timed_out' && $this->error !== null) { + return false; + } + + $metadata = $this->stream->getMetadata($key); + if ($key === null && $this->error !== null && \is_array($metadata)) { + $metadata['timed_out'] = false; + } + + return $metadata; + } + + private function inflate(string $encoded, ?int $encoding = null): string + { + $retry = false; + if ($this->context === null) { + $this->header .= $encoded; + if (\strlen($this->header) < 2) { + return ''; + } + + $encoded = $this->header; + $this->header = ''; + + if (!\function_exists('inflate_init')) { + throw $this->fail('Unable to decode the response body: the zlib extension is not loaded'); + } + + // inflate_init() has no automatic header detection, so pick the + // format the way zlib does for the window bits 15 + 32 that the + // zlib.inflate filter is given. + $encoding = $encoding ?? (\strncmp($encoded, "\x1f\x8b", 2) === 0 ? \ZLIB_ENCODING_GZIP : \ZLIB_ENCODING_DEFLATE); + $retry = $this->deflate && $encoding === \ZLIB_ENCODING_DEFLATE; + $context = \inflate_init($encoding); + if ($context === false) { + throw $this->fail(self::INVALID_DATA); + } + + $this->context = $context; + } + + $readBefore = \inflate_get_read_len($this->context); + + // Application error handlers also see @-suppressed warnings, so keep + // the warning inflate_add() emits before returning false from them. + \set_error_handler(static function (): bool { + return true; + }); + + try { + $decoded = \inflate_add($this->context, $encoded); + } finally { + \restore_error_handler(); + } + + if ($decoded === false) { + // Like libcurl, decode deflate data that zlib rejects in the first + // call as raw deflate, which may be followed by up to 4 unknown + // bytes such as the checksum of a zlib stream missing its header. + if ($retry) { + $this->context = null; + $this->trailingAllowance = 4; + + return $this->inflate($encoded, \ZLIB_ENCODING_RAW); + } + + throw $this->fail(self::INVALID_DATA); + } + + $this->finished = \inflate_get_status($this->context) === \ZLIB_STREAM_END; + if ($this->finished) { + $consumed = \inflate_get_read_len($this->context) - $readBefore; + if ($consumed < 0) { + // zlib counts input in an unsigned long, which wraps at 4 GiB + // on Windows and 32-bit builds. + $consumed += 0x100000000; + } + + if (!$this->allowTrailing(\strlen($encoded) - (int) $consumed)) { + // Throw only after the bytes decoded so far have been read. + $this->fail(self::TRAILING_DATA); + } + } + + return $decoded; + } + + private function allowTrailing(int $length): bool + { + if ($length > $this->trailingAllowance) { + return false; + } + + $this->trailingAllowance -= $length; + + return true; + } + + private function attached(): StreamInterface + { + if ($this->stream === null) { + throw new \RuntimeException('Stream is detached'); + } + + return $this->stream; + } + + private function release(): void + { + $this->stream = null; + $this->context = null; + $this->buffer = ''; + $this->offset = 0; + } + + private function fail(string $message): \RuntimeException + { + return $this->error = new \RuntimeException($message); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php b/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php new file mode 100644 index 0000000..9d80e8d --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php @@ -0,0 +1,276 @@ +|callable(RequestInterface, array): (ResponseInterface|\Throwable|PromiseInterface)> + */ + private array $queue = []; + + private ?RequestInterface $lastRequest = null; + + /** + * @var array + */ + private array $lastOptions = []; + + /** + * @var (callable(ResponseInterface|null): mixed)|null + */ + private $onFulfilled; + + /** + * @var (callable(mixed): mixed)|null + */ + private $onRejected; + + /** + * Creates a new MockHandler that uses the default handler stack list of + * middlewares. + * + * @param array|callable(RequestInterface, array): (ResponseInterface|\Throwable|PromiseInterface)>|null $queue Array of responses, promises, callables, or throwables. + * @param (callable(ResponseInterface|null): mixed)|null $onFulfilled Callback to invoke when the return value is fulfilled. + * @param (callable(mixed): mixed)|null $onRejected Callback to invoke when the return value is rejected. + * + * @return HandlerStack): PromiseInterface> + */ + public static function createWithMiddleware( + #[\SensitiveParameter] + ?array $queue = null, + ?callable $onFulfilled = null, + ?callable $onRejected = null + ): HandlerStack { + return HandlerStack::create(new self($queue, $onFulfilled, $onRejected)); + } + + /** + * The passed in value must be an array of + * {@see ResponseInterface} objects, throwables, callables, or promises. + * + * @param array|callable(RequestInterface, array): (ResponseInterface|\Throwable|PromiseInterface)>|null $queue The parameters to be passed to the append function, as an indexed array. + * @param (callable(ResponseInterface|null): mixed)|null $onFulfilled Callback to invoke when the return value is fulfilled. + * @param (callable(mixed): mixed)|null $onRejected Callback to invoke when the return value is rejected. + */ + public function __construct( + #[\SensitiveParameter] + ?array $queue = null, + ?callable $onFulfilled = null, + ?callable $onRejected = null + ) { + $this->onFulfilled = $onFulfilled; + $this->onRejected = $onRejected; + + if ($queue) { + // array_values included for BC + $this->append(...array_values($queue)); + } + } + + /** + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + if (!$this->queue) { + // Test-setup error (more requests made than responses queued); + // intentionally a bare SPL exception, not a GuzzleException. + throw new \OutOfBoundsException('Mock queue is empty'); + } + + if (isset($options['delay']) && \is_numeric($options['delay'])) { + Clock::sleep((int) ($options['delay'] * 1000)); + } + + if (isset($options['on_stats']) && !\is_callable($options['on_stats'])) { + throw new InvalidArgumentException('on_stats must be callable'); + } + + $this->lastRequest = $request; + $this->lastOptions = $options; + $response = \array_shift($this->queue); + $onHeaders = null; + $onHeadersResponse = null; + + if (isset($options['on_headers'])) { + if (!\is_callable($options['on_headers'])) { + throw new InvalidArgumentException('on_headers must be callable'); + } + + $onHeaders = $options['on_headers']; + } + + if (\is_callable($response)) { + $response = $response($request, $options); + } + + $response = $response instanceof \Throwable + ? P\Create::rejectionFor($response) + : P\Create::promiseFor($response); + + if (\is_callable($onHeaders)) { + $response = $response->then( + static function ( + #[\SensitiveParameter] + $value + ) use ($onHeaders, $request, &$onHeadersResponse) { + if (!$value instanceof ResponseInterface) { + return $value; + } + + try { + $onHeaders($value, $request); + } catch (\Throwable $e) { + $msg = 'An error was encountered during the on_headers event'; + $onHeadersResponse = $value; + + throw new ResponseException($msg, $request, $value, $e); + } + + return $value; + } + ); + } + + $promise = $response->then( + function ( + #[\SensitiveParameter] + $value + ) use ($request, $options): ?ResponseInterface { + /** @var ResponseInterface|null $value */ + $this->invokeStats($request, $options, $value); + if ($this->onFulfilled) { + ($this->onFulfilled)($value); + } + + if ($value !== null && isset($options['sink'])) { + $contents = (string) $value->getBody(); + $sink = $options['sink']; + + if (\is_resource($sink)) { + \fwrite($sink, $contents); + } elseif (\is_string($sink)) { + \file_put_contents($sink, $contents); + } elseif ($sink instanceof StreamInterface) { + $sink->write($contents); + } + } + + return $value; + }, + function ( + #[\SensitiveParameter] + $reason + ) use ($request, $options, &$onHeadersResponse): PromiseInterface { + $this->invokeStats($request, $options, $onHeadersResponse, $reason); + if ($this->onRejected) { + ($this->onRejected)($reason); + } + + return P\Create::rejectionFor($reason); + } + ); + + /** @var PromiseInterface $promise */ + return $promise; + } + + /** + * Adds one or more variadic requests, exceptions, callables, or promises + * to the queue. + * + * @param mixed ...$values Responses, promises, throwables, or request-aware callables. + */ + public function append( + #[\SensitiveParameter] + ...$values + ): void { + foreach ($values as $value) { + if ($value instanceof ResponseInterface + || $value instanceof \Throwable + || $value instanceof PromiseInterface + || \is_callable($value) + ) { + $this->queue[] = $value; + } else { + throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.\get_debug_type($value)); + } + } + } + + /** + * Get the last received request. + */ + public function getLastRequest(): ?RequestInterface + { + return $this->lastRequest; + } + + /** + * Get the last received request options. + */ + public function getLastOptions(): array + { + return $this->lastOptions; + } + + /** + * Returns the number of remaining items in the queue. + */ + public function count(): int + { + return \count($this->queue); + } + + public function reset(): void + { + $this->queue = []; + } + + /** + * @param mixed $reason Promise or reason. + */ + private function invokeStats( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + ?ResponseInterface $response = null, + #[\SensitiveParameter] + $reason = null + ): void { + if (isset($options['on_stats'])) { + $transferTime = $options['transfer_time'] ?? 0.0; + if (!\is_int($transferTime) && !\is_float($transferTime) && (!\is_string($transferTime) || !\is_numeric($transferTime))) { + throw new InvalidArgumentException('transfer_time must be a number of seconds'); + } + + $stats = new TransferStats($request, $response, (float) $transferTime, $reason); + ($options['on_stats'])($stats); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/Protocols.php b/vendor/guzzlehttp/guzzle/src/Handler/Protocols.php new file mode 100644 index 0000000..2860308 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/Protocols.php @@ -0,0 +1,47 @@ +): PromiseInterface $default Handler used for normal responses + * @param callable(RequestInterface, array): PromiseInterface $sync Handler used for synchronous responses. + * + * @return callable(RequestInterface, array): PromiseInterface Returns the composed handler. + */ + public static function wrapSync(callable $default, callable $sync): callable + { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) use ($default, $sync): PromiseInterface { + return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options); + }; + } + + /** + * Sends streaming requests to a streaming compatible handler while sending + * all other requests to a default handler. + * + * This, for example, could be useful for taking advantage of the + * performance benefits of curl while still supporting true streaming + * through the StreamHandler. + * + * @param callable(RequestInterface, array): PromiseInterface $default Handler used for non-streaming responses + * @param callable(RequestInterface, array): PromiseInterface $streaming Handler used for streaming responses + * + * @return callable(RequestInterface, array): PromiseInterface Returns the composed handler. + */ + public static function wrapStreaming(callable $default, callable $streaming): callable + { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) use ($default, $streaming): PromiseInterface { + return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options); + }; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/ProxyEnv.php b/vendor/guzzlehttp/guzzle/src/Handler/ProxyEnv.php new file mode 100644 index 0000000..f0147ea --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/ProxyEnv.php @@ -0,0 +1,159 @@ +hasProxy() || $selection->shouldDisableProxy()) { + return $selection; + } + + $envProxy = self::getProxyForScheme($uri->getScheme()); + if ($envProxy === null) { + return $selection; + } + + $noProxy = self::getNoProxy(); + if ($noProxy !== null && ProxyOptions::isUriInNoProxy($uri, self::splitNoProxy($noProxy))) { + return ProxySelection::bypassed(); + } + + // $envProxy is never '' (empty env values are treated as unset). + return ProxySelection::proxy($envProxy); + } + + /** + * Resolves the proxy to use for the given request scheme. + * + * The lookup mirrors libcurl for the http and https schemes the handlers + * accept: the lowercase scheme-specific variable first, its uppercase + * variant next (except for "http", where uppercase HTTP_PROXY is never + * read), then all_proxy/ALL_PROXY. + * + * @return string|null The proxy to use; null when the environment + * configures none. + */ + public static function getProxyForScheme(string $scheme): ?string + { + $scheme = Psr7\Utils::asciiToLower($scheme); + $candidates = [$scheme.'_proxy']; + if ($scheme !== 'http') { + // Uppercase HTTP_PROXY is deliberately never consulted: a CGI + // request header "Proxy:" becomes HTTP_PROXY in the environment. + // See https://httpoxy.org for more information. + $candidates[] = Psr7\Utils::asciiToUpper($scheme).'_PROXY'; + } + $candidates[] = 'all_proxy'; + $candidates[] = 'ALL_PROXY'; + + foreach ($candidates as $name) { + $value = self::getenv($name); + if ($value !== null) { + return $value; + } + } + + return null; + } + + /** + * @return string|null The no-proxy list; null when nothing is set. + */ + public static function getNoProxy(): ?string + { + foreach (['no_proxy', 'NO_PROXY'] as $name) { + $value = self::getenv($name); + if ($value !== null) { + return $value; + } + } + + return null; + } + + /** + * Splits a no_proxy environment value into matchable entries. + * + * Entries may be separated by commas or blanks, the way libcurl tokenizes + * the value. + * + * @return string[] + */ + public static function splitNoProxy(string $noProxy): array + { + $entries = []; + + $split = \preg_split('/[\s,]+/', $noProxy); + + if ($split === false) { + throw new \RuntimeException('Unable to split the no_proxy value: '.\preg_last_error_msg()); + } + + foreach ($split as $entry) { + if ($entry !== '') { + $entries[] = $entry; + } + } + + return $entries; + } + + private static function getenv(string $name): ?string + { + // Windows environment variables are case-insensitive, so the + // lowercase-only httpoxy defence does not hold there. Outside the + // CLI SAPI on Windows, environment proxies are not resolved at all + // (a safe-side divergence from libcurl). + if (\PHP_OS_FAMILY === 'Windows' && \PHP_SAPI !== 'cli') { + return null; + } + + // local_only: the OS environment and putenv() only - the same + // environ(7) libcurl reads. SAPI request environments such as + // fastcgi_param or SetEnv are deliberately excluded. + $value = \getenv($name, true); + + // libcurl's GetEnv (lib/getenv.c) treats variables set to an empty + // string as unset on every version, so the lookup falls through to + // the next candidate. + return $value === false || $value === '' ? null : $value; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/RequestFraming.php b/vendor/guzzlehttp/guzzle/src/Handler/RequestFraming.php new file mode 100644 index 0000000..c9772dc --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/RequestFraming.php @@ -0,0 +1,256 @@ +request = $request; + $this->bodySize = $bodySize; + $this->contentLength = $contentLength; + } + + /** + * Finalizes request framing for a handler dispatch. + * + * When $sendBody is false, body-dependent validation and size probing are + * skipped. Content-Length is still canonicalized and Transfer-Encoding is + * removed. + * + * @throws RequestException when framing or body metadata is unsafe + */ + public static function analyze( + #[\SensitiveParameter] + RequestInterface $request, + bool $sendBody = true + ): self { + try { + $length = HeaderProcessor::parseContentLength($request->getHeader('Content-Length')); + } catch (\RuntimeException $e) { + throw new RequestException('Invalid Content-Length request header: '.$e->getMessage(), $request, 0, $e); + } + + try { + HeaderProcessor::assertContentLengthWithinPlatformLimit($length); + } catch (\OverflowException $e) { + throw new RequestException($e->getMessage(), $request, 0, $e); + } + + $contentLength = HeaderProcessor::contentLengthToInt($length); + if ($length !== null) { + $request = $request->withHeader('Content-Length', $length); + } + + if (!$sendBody) { + return new self($request->withoutHeader('Transfer-Encoding'), null, $contentLength); + } + + $transferEncoding = $request->getHeader('Transfer-Encoding'); + if ($length !== null && $transferEncoding !== []) { + throw new RequestException( + 'A request must not contain both Content-Length and Transfer-Encoding', + $request + ); + } + + if ($transferEncoding !== []) { + $tokens = []; + foreach ($transferEncoding as $value) { + foreach (\explode(',', $value) as $part) { + $tokens[] = \trim($part, " \t"); + } + } + + if (\count($tokens) !== 1 || !Psr7\Utils::caselessEquals($tokens[0], 'chunked') || $request->getProtocolVersion() !== '1.1') { + throw new RequestException('Unsupported Transfer-Encoding request header', $request); + } + } + + $bodySize = self::bodySize($request); + if ($bodySize !== null && $contentLength !== null && $bodySize !== $contentLength) { + throw new RequestException('Content-Length does not match the request body size', $request); + } + + if ($bodySize === null && $contentLength === null && $request->getProtocolVersion() === '1.0') { + throw new RequestException('An unknown-size HTTP/1.0 request body requires Content-Length', $request); + } + + if ($length === null && $bodySize !== null && ($bodySize > 0 || \in_array($request->getMethod(), ['PUT', 'POST'], true))) { + $contentLength = $bodySize; + $request = $request->withHeader('Content-Length', (string) $bodySize); + } + + return new self($request->withoutHeader('Transfer-Encoding'), $bodySize, $contentLength); + } + + /** + * Returns the number of bytes available for dispatch, or null when unknown. + * + * Seekable bodies use their total size because handlers rewind them. + * Positioned non-seekable bodies use the total size minus their current + * position. + * + * @throws RequestException when body metadata cannot be read safely + */ + public static function bodySize( + #[\SensitiveParameter] + RequestInterface $request + ): ?int { + $body = $request->getBody(); + + try { + $size = $body->getSize(); + if ($size === null) { + return null; + } + + if ($size < 0) { + throw new \RuntimeException('Request body size must not be negative'); + } + + $seekable = $body->isSeekable(); + } catch (\Exception $e) { + throw self::bodyException( + $request, + $e, + 'Timed out while determining the request body size', + 'Failed to determine the request body size' + ); + } + + if ($seekable) { + return $size; + } + + try { + $position = $body->tell(); + } catch (\RuntimeException $e) { + return null; + } + + if ($position < 0 || $position > $size) { + throw new RequestException('The request body position is outside the stream size', $request); + } + + return $size - $position; + } + + /** + * Materializes the body, stopping at the selected Content-Length when + * present. + * + * @throws RequestException when the body cannot be fully rewound or read + */ + public function materialize(): string + { + $body = $this->request->getBody(); + + if ($this->contentLength === null) { + try { + return (string) $body; + } catch (\Exception $e) { + throw self::bodyException( + $this->request, + $e, + 'Timed out while reading the request body', + 'Failed to read the request body' + ); + } + } + + if ($this->contentLength === 0) { + return ''; + } + + try { + if ($body->isSeekable()) { + $body->rewind(); + } + } catch (\Exception $e) { + throw self::bodyException( + $this->request, + $e, + 'Timed out while rewinding the request body', + 'Failed to rewind the request body' + ); + } + + $contents = ''; + $remaining = $this->contentLength; + while ($remaining > 0) { + $limit = \min(8192, $remaining); + + try { + $chunk = $body->read($limit); + } catch (\Exception $e) { + throw self::bodyException( + $this->request, + $e, + 'Timed out while reading the request body', + 'Failed to read the request body' + ); + } + + if ($chunk === '') { + throw new RequestException( + 'Request body ended before the declared Content-Length was reached', + $this->request + ); + } + + if (\strlen($chunk) > $limit) { + throw new RequestException('Request body stream returned more bytes than requested', $this->request); + } + + $contents .= $chunk; + $remaining -= \strlen($chunk); + } + + return $contents; + } + + private static function bodyException( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + \Exception $exception, + string $timeoutMessage, + string $fallbackMessage + ): RequestException { + $message = $exception instanceof TimeoutException + ? $timeoutMessage + : ($exception->getMessage() !== '' ? $exception->getMessage() : $fallbackMessage); + + return new RequestException($message, $request, 0, $exception); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php b/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php new file mode 100644 index 0000000..be5537d --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php @@ -0,0 +1,2073 @@ + true, + 'max_total_connections' => true, + 'transport_sharing' => true, + ]; + + /** + * Peers tracked by the TLS session cache, matching libcurl's share handle + * TLS session cache (25 peers, up to 2 sessions each). + */ + private const TLS_SESSION_CACHE_MAX_KEYS = 25; + + private const CONNECTION_ERRORS = [ + 'php_network_getaddresses:', + 'getaddrinfo', + 'gethostbyname failed', + 'Unable to connect to', + 'Connection refused', + 'No connection could be made because the target machine actively refused it', + 'connection attempt failed', + 'connect() failed', + 'Network is unreachable', + 'No route to host', + 'Host is unreachable', + 'Host is down', + 'Cannot connect to HTTPS server through proxy', + 'Failed to enable crypto', + ]; + + private const CONNECT_TIMEOUT_ERRORS = [ + 'Connection timed out', + 'Operation timed out', + 'SSL: Handshake timed out', + 'did not properly respond after a period of time', + ]; + + private const NETWORK_ERRORS = [ + 'SSL: Connection reset by peer', + 'SSL: Broken pipe', + 'unexpected eof while reading', + ]; + + // PHP's HTTP wrapper can collapse wrapper-level errors to OpenFailed. + // These codes classify only errors delivered directly to the context + // handler. NetworkRecvFailed is omitted because PHP currently emits it for + // handshake-time certificate policy failures. + private const STRUCTURED_NETWORK_ERROR_CODES = [ + 'NetworkSendFailed', + ]; + + // SslNotSupported can be emitted directly by a transport that cannot + // enable crypto. Standard ext-openssl proxy failures are normally + // collapsed to OpenFailed and continue to use message classification. + private const STRUCTURED_CONNECTION_ERROR_CODES = [ + 'SslNotSupported', + ]; + + /** + * Default idle timeout in milliseconds when the "read_timeout" option is + * not set. Matches PHP's default_socket_timeout default, which the + * handler never consults. + */ + private const DEFAULT_IDLE_TIMEOUT_MS = 60000; + + /** + * Number of transfers currently opening, which share the from ini setting. + */ + private static int $fromBlankDepth = 0; + + /** + * @var string|false + */ + private static $fromToRestore = false; + + private ?\Throwable $onStatsException = null; + + private string $transportSharingMode; + + private bool $connectionCapsConfigured = false; + + private ?StreamTlsSessionCache $sessionCache = null; + + /** + * Accepts an associative array of options: + * + * - max_host_connections: Optional positive integer or null. A non-null + * value marks the handler as incompatible with enabled response + * streaming; the number is not used for stream-handler admission. + * - max_total_connections: Optional positive integer or null. A non-null + * value marks the handler as incompatible with enabled response + * streaming; the number is not used for stream-handler admission. + * - transport_sharing: Optional transport sharing mode. + * + * The stream handler cannot cap streamed connections, so a configured cap + * marker rejects enabled response streaming ("stream" => true). Accepted + * transfers are buffered and hold at most one connection per in-flight + * call, but overlapping buffered calls are not collectively limited. + * + * @param array{max_host_connections?: mixed, max_total_connections?: mixed, transport_sharing?: mixed} $options Array of options to use with the handler + */ + public function __construct(array $options = []) + { + foreach ($options as $name => $_) { + if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) { + throw new InvalidArgumentException(\sprintf('Invalid StreamHandler constructor option "%s".', Psr7\DiagnosticValue::escape((string) $name))); + } + } + + $this->transportSharingMode = CurlShareHandleState::normalizeMode( + $options['transport_sharing'] ?? null, + 'transport_sharing' + ); + + foreach (['max_host_connections', 'max_total_connections'] as $capOption) { + $value = $options[$capOption] ?? null; + if ($value === null) { + continue; + } + + if (!\is_int($value) || $value < 1) { + throw new InvalidArgumentException(\sprintf('%s must be a positive integer.', $capOption)); + } + + $this->connectionCapsConfigured = true; + } + } + + /** + * Sends an HTTP request. + * + * @param RequestInterface $request Request to send. + * @param array $options Request transfer options. + * + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + $this->onStatsException = null; + + // Sleep if there is a delay specified. + if (isset($options['delay'])) { + Clock::sleep((int) ($options['delay'] * 1000)); + } + + $multiplex = $options['multiplex'] ?? null; + + // Multiplexing::NONE is trivially satisfied: the stream handler sends + // one HTTP/1.x request per connection and never multiplexes. + if (null !== $multiplex && !\in_array($multiplex, [Multiplexing::NONE, Multiplexing::EAGER, Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new InvalidArgumentException(\sprintf( + 'The "multiplex" option must be null or a GuzzleHttp\\Multiplexing::* constant; received %s.', + \get_debug_type($multiplex) + )); + } + + if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) { + throw new RequestException('The stream handler cannot guarantee a multiplexed protocol; required multiplexing needs a cURL handler.', $request); + } + + if (\strpbrk($request->getMethod(), "\r\n\0") !== false) { + throw new RequestException('HTTP method must not contain a carriage return, line feed or NUL byte.', $request); + } + + $protocolVersion = $request->getProtocolVersion(); + + if ('' === $protocolVersion) { + throw new RequestException('HTTP protocol version must not be empty.', $request); + } + + if (1 !== \preg_match('/^\d+(?:\.\d+)?$/D', $protocolVersion)) { + throw new RequestException('HTTP protocol version must be a valid HTTP version number.', $request); + } + + if ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) { + throw new RequestException(sprintf('HTTP/%s is not supported by the stream handler.', $protocolVersion), $request); + } + + if (isset($options['on_stats']) && !\is_callable($options['on_stats'])) { + throw new InvalidArgumentException('on_stats must be callable'); + } + + $startTime = isset($options['on_stats']) ? Clock::now() : null; + + self::rejectUnsupportedRequestOptions($request, $options); + $this->rejectStreamingWithConnectionCaps($options); + $this->assertTransportSharingSupported(); + + // The stream wrapper sends HEAD request bodies, unlike cURL's NOBODY + // path, so validate their framing normally. + $framing = RequestFraming::analyze($request->withoutHeader('Expect')); + $request = $framing->request; + + try { + self::assertRequestUriSupported($request, $options); + $body = $framing->materialize(); + if ($framing->contentLength === null && ($body !== '' || \in_array($request->getMethod(), ['PUT', 'POST'], true))) { + $request = $request->withHeader('Content-Length', (string) \strlen($body)); + } + + $deadline = null; + $stream = $this->createStream($request, $options, $body, $deadline); + $headers = \stream_get_meta_data($stream)['wrapper_data']; + + return $this->createResponse( + $request, + $options, + $stream, + \is_array($headers) ? $headers : [], + $startTime, + $deadline + ); + } catch (\InvalidArgumentException $e) { + throw $e; + } catch (\Exception $e) { + if ($this->isOnStatsException($e)) { + throw $e; + } + + if (!$e instanceof TransferException) { + $message = $e->getMessage(); + $e = self::createStreamFailureException($message, $request, $e, []); + } + $this->invokeStats($options, $request, $startTime, null, $e); + + /** @var PromiseInterface */ + return P\Create::rejectionFor($e); + } + } + + private function isOnStatsException(\Throwable $e): bool + { + if ($this->onStatsException !== $e) { + return false; + } + + $this->onStatsException = null; + + return true; + } + + private static function isConnectTimeoutError(string $message): bool + { + foreach (self::CONNECT_TIMEOUT_ERRORS as $timeoutError) { + if (Psr7\Utils::caselessContains($message, $timeoutError)) { + return true; + } + } + + return false; + } + + private static function isConnectionError(string $message): bool + { + foreach (self::CONNECTION_ERRORS as $connectionError) { + if (Psr7\Utils::caselessContains($message, $connectionError)) { + return true; + } + } + + return false; + } + + private static function isSendError(string $message): bool + { + // A failed write ("Send of N bytes failed ...") implies an established connection. + return Psr7\Utils::caselessContains($message, 'bytes failed with errno='); + } + + private static function isNetworkError(string $message): bool + { + foreach (self::NETWORK_ERRORS as $networkError) { + if (Psr7\Utils::caselessContains($message, $networkError)) { + return true; + } + } + + return false; + } + + /** + * @param string[] $streamErrorCodes + */ + private static function createStreamFailureException( + #[\SensitiveParameter] + string $message, + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + \Exception $previous, + array $streamErrorCodes + ): TransferException { + if (self::isSendError($message) || self::hasStreamErrorCode($streamErrorCodes, self::STRUCTURED_NETWORK_ERROR_CODES)) { + return self::isConnectTimeoutError($message) + ? new NetworkTimeoutException($message, $request, $previous) + : new NetworkException($message, $request, $previous); + } + + if (self::isConnectTimeoutError($message)) { + return new ConnectTimeoutException($message, $request, $previous); + } + + if (self::hasStreamErrorCode($streamErrorCodes, self::STRUCTURED_CONNECTION_ERROR_CODES) || self::isConnectionError($message)) { + return new ConnectException($message, $request, $previous); + } + + if (self::isNetworkError($message)) { + return new NetworkException($message, $request, $previous); + } + + return new RequestException($message, $request, 0, $previous); + } + + /** + * @param string[] $streamErrorCodes + * @param string[] $codes + */ + private static function hasStreamErrorCode(array $streamErrorCodes, array $codes): bool + { + foreach ($streamErrorCodes as $streamErrorCode) { + foreach ($codes as $code) { + if ($streamErrorCode === $code) { + return true; + } + } + } + + return false; + } + + private function invokeStats( + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + RequestInterface $request, + ?float $startTime, + #[\SensitiveParameter] + ?ResponseInterface $response = null, + #[\SensitiveParameter] + ?\Throwable $error = null + ): void { + if (isset($options['on_stats'])) { + $stats = new TransferStats($request, $response, Clock::now() - $startTime, $error, []); + try { + ($options['on_stats'])($stats); + } catch (\Throwable $e) { + $this->onStatsException = $e; + + throw $e; + } + } + } + + /** + * @param resource $stream + * + * @return PromiseInterface + */ + private function createResponse( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + $stream, + #[\SensitiveParameter] + array $hdrs, + ?float $startTime, + ?float $deadline + ): PromiseInterface { + try { + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); + } catch (\Throwable $e) { + return $this->rejectResponseCreation($options, $request, $startTime, $e); + } + + $canHaveBody = HeaderProcessor::responseCanHaveBody($request->getMethod(), $status); + $framingFailure = null; + $declaredLength = null; + $chunked = false; + try { + $declaredLength = HeaderProcessor::validateResponseFraming($request->getMethod(), $status, $headers); + $chunked = $canHaveBody && HeaderProcessor::parseTransferEncoding($headers); + if (empty($options['stream'])) { + HeaderProcessor::assertContentLengthWithinPlatformLimit($declaredLength); + } + } catch (\RuntimeException $e) { + $framingFailure = $e; + } + + if ($chunked) { + HeaderProcessor::removeHeader('Transfer-Encoding', $headers); + } elseif (!$canHaveBody) { + $headers = self::removeChunkedTransferCoding($headers); + } + + $streamFactory = self::requireStreamFactory($options[RequestOptions::STREAM_FACTORY] ?? new Psr7\HttpFactory()); + $responseFactory = self::requireResponseFactory($options[RequestOptions::RESPONSE_FACTORY] ?? new Psr7\HttpFactory()); + + // Wrap the transport resource with the configured stream factory, and + // decorate buffered transfers with the deadline source before framing + // and optional content decoding layer on top, so every read that pulls + // from the transport observes the deadline. + $resource = $stream; + $stream = $streamFactory->createStreamFromResource($stream); + if ($framingFailure === null && $deadline !== null && empty($options['stream'])) { + $stream = self::createDeadlineSource($stream, $resource, $deadline, $options); + } + if ($chunked || !empty($options['stream'])) { + $stream = new TransportStream($stream); + } + if ($chunked) { + $stream = new ChunkedBodyStream($stream); + } elseif (!empty($options['stream'])) { + $length = HeaderProcessor::contentLengthToInt($declaredLength); + if ($length !== null) { + $stream = new DeclaredLengthStream($stream, $length); + } + } + + $encodedBody = null; + if ($framingFailure === null) { + [$stream, $headers, $encodedBody] = self::checkDecode($options, $headers, $stream, $declaredLength); + } + + $sink = $framingFailure !== null || !$canHaveBody + ? $streamFactory->createStream('') + : $this->createSink($stream, $options); + + try { + $response = $responseFactory->createResponse($status, $reason ?? '')->withProtocolVersion($ver); + foreach ($headers as $name => $value) { + $response = $response->withAddedHeader((string) $name, $value); + } + $response = $response->withBody($sink); + } catch (\Throwable $e) { + return $this->rejectResponseCreation($options, $request, $startTime, $e); + } + + if ($framingFailure !== null) { + try { + $stream->close(); + } catch (\Exception $e) { + // Best-effort release; a failing transport close must not + // mask the framing rejection. + } + + $reason = $framingFailure instanceof \OverflowException + ? new ResponseException($framingFailure->getMessage(), $request, $response, $framingFailure) + : new ResponseTransferException($framingFailure->getMessage(), $request, $response, $framingFailure); + $this->invokeStats($options, $request, $startTime, $response, $reason); + + /** @var PromiseInterface */ + return P\Create::rejectionFor($reason); + } + + // The header phase inside fopen() can only bound the time between + // packets, so a header block that trickled in past the deadline is + // rejected here, once it is complete. The transport is closed so a + // streamed response cannot hold the connection open through the + // rejection. + if ($deadline !== null && Clock::now() >= $deadline) { + try { + $stream->close(); + } catch (\Exception $e) { + // Best-effort release; a failing transport close must not + // mask the timeout rejection. + } + + $reason = new ResponseTimeoutException('Timed out while receiving the response headers', $request, $response); + $this->invokeStats($options, $request, $startTime, $response, $reason); + + /** @var PromiseInterface */ + return P\Create::rejectionFor($reason); + } + + if (isset($options['on_headers'])) { + try { + $options['on_headers']($response, $request); + } catch (\Throwable $e) { + $reason = new ResponseException('An error was encountered during the on_headers event', $request, $response, $e); + $this->invokeStats($options, $request, $startTime, $response, $reason); + + /** @var PromiseInterface */ + return P\Create::rejectionFor($reason); + } + } + + if (!$canHaveBody) { + // RFC 9110 / RFC 9112 section 6.3: octets after the header section + // of a HEAD, 1xx, 204, 304, or CONNECT-2xx response are not part + // of this response's body. Never read them, and release the + // transport as soon as the headers are complete. + try { + $stream->close(); + } catch (\Exception $e) { + // Best-effort release; a failing transport close must not fail + // a fully received no-content response. + } + } elseif ($sink !== $stream) { + try { + $this->drain($request, $response, $stream, $sink, $declaredLength, $encodedBody); + } catch (ResponseException $e) { + $this->invokeStats($options, $request, $startTime, $response, $e); + + /** @var PromiseInterface */ + return P\Create::rejectionFor($e); + } + } + + $this->invokeStats($options, $request, $startTime, $response, null); + + /** @var PromiseInterface */ + return P\Create::promiseFor($response); + } + + /** + * @return PromiseInterface + */ + private function rejectResponseCreation( + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + RequestInterface $request, + ?float $startTime, + #[\SensitiveParameter] + \Throwable $previous + ): PromiseInterface { + $reason = new RequestException( + 'An error was encountered while creating the response', + $request, + 0, + $previous + ); + + $this->invokeStats($options, $request, $startTime, null, $reason); + + /** @var PromiseInterface */ + return P\Create::rejectionFor($reason); + } + + private function createSink( + StreamInterface $stream, + #[\SensitiveParameter] + array $options + ): StreamInterface { + if (!empty($options['stream'])) { + return $stream; + } + + $streamFactory = self::requireStreamFactory($options[RequestOptions::STREAM_FACTORY] ?? new Psr7\HttpFactory()); + $hasSink = isset($options['sink']); + $sink = $hasSink ? $options['sink'] : Psr7\Utils::tryFopen('php://temp', 'r+'); + + if ($hasSink && \is_resource($sink)) { + return self::streamForResourceSink(Psr7\Utils::streamFor($sink)); + } + + if (\is_string($sink)) { + return new Psr7\LazyOpenStream($sink, 'w+'); + } + + if (!\is_resource($sink)) { + return Psr7\Utils::streamFor($sink); + } + + return $streamFactory->createStreamFromResource($sink); + } + + /** + * Decorates a caller-owned sink stream so that closing the response body + * detaches Guzzle's wrapper without closing the original PHP resource. + */ + private static function streamForResourceSink(StreamInterface $stream): StreamInterface + { + return Psr7\FnStream::decorate($stream, [ + 'close' => static function () use ($stream): void { + $stream->detach(); + }, + ]); + } + + /** + * @param mixed $factory + */ + private static function requireStreamFactory($factory): StreamFactoryInterface + { + if (!$factory instanceof StreamFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::STREAM_FACTORY, + StreamFactoryInterface::class + )); + } + + return $factory; + } + + /** + * @param mixed $factory + */ + private static function requireResponseFactory($factory): ResponseFactoryInterface + { + if (!$factory instanceof ResponseFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::RESPONSE_FACTORY, + ResponseFactoryInterface::class + )); + } + + return $factory; + } + + /** + * Removes Transfer-Encoding values that start with chunked from a response + * that cannot have a body, as PHP's HTTP wrapper did. + * + * @param array $headers + * + * @return array + */ + private static function removeChunkedTransferCoding(array $headers): array + { + foreach ($headers as $name => $values) { + if (!Psr7\Utils::caselessEquals((string) $name, 'Transfer-Encoding')) { + continue; + } + + $remaining = []; + foreach ($values as $value) { + if (!Psr7\Utils::caselessEquals(\substr($value, 0, 7), 'chunked')) { + $remaining[] = $value; + } + } + + if ($remaining === []) { + unset($headers[$name]); + } else { + $headers[$name] = $remaining; + } + } + + return $headers; + } + + /** + * @return array{0: StreamInterface, 1: array, 2: ?EncodedBodyStream} + */ + private static function checkDecode( + #[\SensitiveParameter] + array $options, + array $headers, + StreamInterface $stream, + ?string $declaredLength + ): array { + $encodedBody = null; + + // Automatically decode responses when instructed. + if (isset($options['decode_content']) && $options['decode_content'] !== false) { + $normalizedKeys = HeaderProcessor::normalizeHeaderKeys($headers); + if (isset($normalizedKeys['content-encoding'])) { + $encoding = $headers[$normalizedKeys['content-encoding']]; + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { + if (empty($options['stream']) && $declaredLength !== null && $declaredLength !== '0') { + $encodedBody = new EncodedBodyStream($stream, $declaredLength); + $stream = $encodedBody; + } + + $stream = new InflateBodyStream($stream, $encoding[0] === 'deflate'); + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + + // Remove content-encoding header + unset($headers[$normalizedKeys['content-encoding']]); + + // The decoded length cannot be known without inflating the + // stream, so keep the original length for inspection and + // drop the now-unknown Content-Length header. + $encodedContentLength = HeaderProcessor::removeHeader('Content-Length', $headers); + if ($encodedContentLength !== []) { + $headers['x-encoded-content-length'] = $encodedContentLength; + } + } + } + } + + return [$stream, $headers, $encodedBody]; + } + + /** + * Drains the source stream into the "sink" client option. + * + * @throws \RuntimeException when the sink option is invalid. + */ + private function drain( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + ResponseInterface $response, + StreamInterface $source, + StreamInterface $sink, + ?string $declaredResponseBodyLength, + ?EncodedBodyStream $encodedBody = null + ): StreamInterface { + try { + // Buffered paths reject unrepresentable lengths before draining. + $declaredLength = HeaderProcessor::contentLengthToInt($declaredResponseBodyLength); + $copyLimit = $encodedBody === null ? $declaredLength ?? -1 : -1; + + try { + $target = $this->createResponseSink($request, $response, $sink); + // If a content-length header is provided, then stop reading once + // that number of bytes has been read. This can prevent infinitely + // reading from a stream when dealing with servers that do not + // honor Connection: Close headers. + $copied = Psr7\Utils::copyToStream($source, $target, $copyLimit); + } catch (ResponseException $e) { + throw $e; + } catch (TimeoutException $e) { + throw new ResponseTimeoutException( + 'Timed out while transferring the response body', + $request, + $response, + $e + ); + } catch (\OverflowException $e) { + throw new ResponseException($e->getMessage(), $request, $response, $e); + } catch (\Exception $e) { + // Any other response-body transfer failure surfaces as a + // ResponseTransferException carrying the response. + throw new ResponseTransferException( + $e->getMessage() !== '' ? $e->getMessage() : 'Failed while transferring the response body', + $request, + $response, + $e + ); + } + + $receivedLength = $encodedBody !== null ? $encodedBody->getBytesRead() : $copied; + if ($declaredLength !== null && $receivedLength < $declaredLength) { + throw new ResponseTransferException( + 'Response body ended before the declared Content-Length was reached', + $request, + $response + ); + } + + try { + if ($sink->isSeekable()) { + $sink->rewind(); + } + } catch (\Exception $e) { + throw new ResponseException( + $e->getMessage() !== '' ? $e->getMessage() : 'Failed to rewind the response body', + $request, + $response, + $e + ); + } + + return $sink; + } finally { + try { + $source->close(); + } catch (\Exception $e) { + // Best-effort cleanup after the response body has been received. + } + } + } + + private function createResponseSink( + RequestInterface $request, + ResponseInterface $response, + StreamInterface $sink + ): StreamInterface { + return Psr7\FnStream::decorate($sink, [ + 'close' => static function (): void { + }, + 'write' => static function (string $data) use ($request, $response, $sink): int { + try { + $written = $sink->write($data); + } catch (TimeoutException $e) { + throw new ResponseException( + 'Timed out while writing the response body', + $request, + $response, + $e + ); + } catch (\Exception $e) { + throw new ResponseException( + $e->getMessage() !== '' ? $e->getMessage() : 'Failed to write the response body', + $request, + $response, + $e + ); + } + + if ($written <= 0) { + throw new ResponseException('Unable to write to stream', $request, $response); + } + + return $written; + }, + 'getMetadata' => static function (?string $key = null) use ($sink) { + // Force timed_out to false so Utils::writeAll() can't reclassify a sink-write + // failure as a transport timeout. Sink write failures are ResponseException; + // source-read timeouts are ResponseTimeoutException. + if ($key === 'timed_out') { + return false; + } + + return $sink->getMetadata($key); + }, + ]); + } + + /** + * Decorates the transport stream so each buffered-body read observes the + * remaining wall-clock budget of the "timeout" request option, bounded by + * the "read_timeout" idle timeout when that is shorter. The transport is + * switched to non-blocking mode because a blocking read waits for data up + * to the transport's own timeout, which would keep the deadline from being + * enforced while the server stalls. + * + * @param resource $resource + */ + private static function createDeadlineSource( + StreamInterface $stream, + $resource, + float $deadline, + #[\SensitiveParameter] + array $options + ): StreamInterface { + $idleTimeout = isset($options['read_timeout']) + ? Timeout::toMilliseconds($options['read_timeout'], 'read_timeout') + : self::DEFAULT_IDLE_TIMEOUT_MS; + + \stream_set_blocking($resource, false); + + return new DeadlineSourceStream($stream, $deadline, $idleTimeout > 0 ? $idleTimeout / 1000 : null); + } + + /** + * Create a resource and check to ensure it was created successfully + * + * @param callable(): (resource|false) $callback Callable that returns a stream resource, or false when resource creation fails. + * + * @return resource + * + * @throws \RuntimeException when the callback returns false or resource creation emits an error. + */ + private function createResource( + callable $callback, + #[\SensitiveParameter] + ?UriInterface $diagnosticUri = null + ) { + $scope = new Psr7\ErrorScope(); + $resource = $scope->run($callback); + + if (!$resource) { + $details = []; + foreach ($scope->getErrors() as $err) { + foreach ($err as $key => $value) { + $rendered = $key === 'message' && $diagnosticUri !== null + ? UriDiagnostic::redactInMessage((string) $value, $diagnosticUri) + : Psr7\DiagnosticValue::escape((string) $value); + $details[] = \sprintf('[%s] %s', $key, $rendered); + } + } + + $message = 'Error creating resource'; + if ($details !== []) { + $message .= ': '.\implode('; ', $details); + } + + throw new \RuntimeException($message); + } + + return $resource; + } + + /** + * @return resource + */ + private function createStream( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + string $body, + ?float &$deadline + ) { + // Report a stream-open failure against the request passed here, not the + // Connection: close clone built for the wire. + $callerRequest = $request; + + // HTTP/1.1 streams using the PHP stream wrapper require a + // Connection: close header + if ($request->getProtocolVersion() === '1.1' + && !$request->hasHeader('Connection') + ) { + $request = $request->withHeader('Connection', 'close'); + } + + // Ensure SSL is verified by default + if (!isset($options['verify'])) { + $options['verify'] = true; + } + + $params = []; + $context = $this->getDefaultContext($request, $body); + $customSslContext = []; + + if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { + throw new InvalidArgumentException('on_headers must be callable'); + } + + $idleTimeout = isset($options['read_timeout']) + ? Timeout::toMilliseconds($options['read_timeout'], 'read_timeout') + : self::DEFAULT_IDLE_TIMEOUT_MS; + + $timeout = isset($options['timeout']) + ? Timeout::toMilliseconds($options['timeout'], 'timeout') + : 0; + + self::assertTlsVersionRangeForOptions($request, $options); + + $this->applyHandlerOptions($request, $context, $options, $params); + + // Resolve the proxy unconditionally (option first, then environment), + // so an env-configured proxy applies even when no proxy option is set. + $this->applyProxy($request, $context, $options['proxy'] ?? null); + + if (isset($options['stream_context'])) { + $streamContext = $options['stream_context']; + if (!\is_array($streamContext)) { + throw new InvalidArgumentException('stream_context must be an array'); + } + self::rejectConflictingStreamContextOptions($streamContext); + self::rejectUnsupportedStreamContextOptions($streamContext); + $context = \array_replace_recursive($context, $streamContext); + + $sslContext = $streamContext['ssl'] ?? null; + if (\is_array($sslContext)) { + $customSslContext = $sslContext; + } + } + + $this->addDefaultTlsMinimum($request, $context); + + $commitTlsSessions = $this->applyTlsSessionResumption($request, $context, $customSslContext); + + // The context timeout governs connecting and the header-phase packet + // gaps: the idle timeout, tightened to the deadline when that is + // lower; -1 disables it so default_socket_timeout is never consulted. + if ($timeout > 0 && ($idleTimeout <= 0 || $timeout < $idleTimeout)) { + $context['http']['timeout'] = $timeout / 1000; + } elseif ($idleTimeout > 0) { + $context['http']['timeout'] = $idleTimeout / 1000; + } else { + $context['http']['timeout'] = -1; + } + + $streamErrorCodes = []; + $captureStreamErrors = true; + $this->addStructuredStreamErrorHandler($context, $streamErrorCodes, $captureStreamErrors); + + $uri = $this->resolveHost($request, $options); + + $contextResource = $this->createResource( + static function () use ($context, $params) { + return \stream_context_create($context, $params); + } + ); + + try { + $resource = $this->createResource(function () use ($uri, $contextResource, $idleTimeout, $timeout, &$deadline) { + $deadline = $timeout > 0 ? Clock::now() + $timeout / 1000 : null; + + // Blank the from ini setting for the transfer so ambient + // configuration cannot leak into a From header; the wrapper + // cannot omit the header, so a configured ini sends it empty. + // An empty setting is left alone, as blanking an unset one adds + // the header. Overlapping transfers share the setting, so only + // the first one saves it and only the last one restores it. + $blankFrom = \function_exists('ini_set'); + if ($blankFrom) { + $iniFrom = \ini_get('from') !== '' ? \ini_set('from', '') : false; + if (self::$fromBlankDepth++ === 0) { + self::$fromToRestore = $iniFrom; + } + } + try { + $resource = @\fopen((string) $uri->withFragment(''), 'r', false, $contextResource); + } finally { + if ($blankFrom && --self::$fromBlankDepth === 0 && self::$fromToRestore !== false) { + \ini_set('from', self::$fromToRestore); + } + } + + if (false === $resource) { + return false; + } + + // Arm reads with the idle timeout, replacing the context + // value the deadline may have tightened; -1 disables it. + if ($idleTimeout > 0) { + $sec = \intdiv($idleTimeout, 1000); + $usec = ($idleTimeout % 1000) * 1000; + \stream_set_timeout($resource, $sec, $usec); + } else { + \stream_set_timeout($resource, -1); + } + + return $resource; + }, $uri); + } catch (TransferException $e) { + // Notification callbacks run during fopen(); an exception a + // callback throws is already a fully-formed transfer failure for + // its own request, so it passes through unchanged instead of + // being reclassified against this request. + throw $e; + } catch (\RuntimeException $e) { + throw self::createStreamFailureException($e->getMessage(), $callerRequest, $e, $streamErrorCodes); + } finally { + $captureStreamErrors = false; + } + + if ($commitTlsSessions !== null) { + $commitTlsSessions(); + } + + return $resource; + } + + /** + * @param string[] $streamErrorCodes + */ + private function addStructuredStreamErrorHandler( + #[\SensitiveParameter] + array &$context, + array &$streamErrorCodes, + bool &$captureStreamErrors + ): void { + if (!self::supportsStructuredStreamErrors()) { + return; + } + + if (!isset($context['stream']) || !\is_array($context['stream'])) { + $context['stream'] = []; + } + + $context['stream']['error_mode'] = \StreamErrorMode::Error; + $context['stream']['error_store'] = \StreamErrorStore::None; + /** @param \StreamError[] $errors */ + $context['stream']['error_handler'] = static function ( + #[\SensitiveParameter] + array $errors + ) use (&$streamErrorCodes, &$captureStreamErrors): void { + if (!$captureStreamErrors) { + return; + } + + foreach ($errors as $error) { + $name = $error->code->name; + if (!\in_array($name, $streamErrorCodes, true)) { + $streamErrorCodes[] = $name; + } + } + }; + } + + private static function supportsStructuredStreamErrors(): bool + { + // Any PHP 8.6 build qualifies, including pre-release and nightly + // builds; the class check keeps unstable builds that do not carry + // the final API fail-closed. + return \PHP_VERSION_ID >= 80600 && \class_exists(\StreamError::class, false); + } + + private static function assertRequestUriSupported( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): void { + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + if ($scheme === '') { + throw new RequestException( + 'URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', + $request + ); + } + + if (!\in_array($scheme, ['http', 'https'], true)) { + throw new RequestException(\sprintf("The scheme '%s' is not supported.", Psr7\DiagnosticValue::escape($scheme)), $request); + } + + $protocols = Protocols::normalize($options['protocols'] ?? ['http', 'https']); + if (!\in_array($scheme, $protocols, true)) { + throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', Psr7\DiagnosticValue::escape($scheme)), $request); + } + + if ($uri->getHost() === '') { + throw new RequestException( + 'URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', + $request + ); + } + + HostValidator::assertRequestHost($request); + } + + private function applyHandlerOptions( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array &$context, + #[\SensitiveParameter] + array $options, + array &$params + ): void { + foreach ($options as $key => $value) { + if ($key === 'crypto_method') { + $this->applyCryptoMethodOption($context, $value); + } elseif ($key === 'crypto_method_max') { + $this->applyCryptoMethodMaxOption($context, $value); + } elseif ($key === 'verify') { + $this->applyVerifyOption($context, $value); + } elseif ($key === 'cert') { + $this->applyCertOption($context, $value); + } elseif ($key === 'cert_type') { + $this->applyCertTypeOption($value); + } elseif ($key === 'ssl_key') { + $this->applySslKeyOption($context, $value); + } elseif ($key === 'ssl_key_type') { + $this->applySslKeyTypeOption($value); + } elseif ($key === 'progress') { + $this->applyProgressOption($value, $params); + } elseif ($key === 'debug') { + $this->applyDebugOption($request, $value, $params); + } + } + } + + private function resolveHost( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): UriInterface { + $uri = $request->getUri(); + + $host = $uri->getHost(); + + // Fold a numeric IPv4 spelling to the dotted quad libcurl connects + // to, rather than leaving it to the platform resolver: macOS reads + // the zero-padded 0177 as decimal 177 where glibc, musl and FreeBSD + // read octal 127. The Host header is serialized from the request and + // stays as written; the TLS peer name follows the same fold. + $canonicalHost = self::canonicalConnectionHost($host); + if ($canonicalHost !== $host) { + $uri = $uri->withHost($canonicalHost); + $host = $canonicalHost; + } + + $hostForIpCheck = \str_starts_with($host, '[') && \str_ends_with($host, ']') + ? \substr($host, 1, -1) + : $host; + if (isset($options['force_ip_resolve']) && !\filter_var($hostForIpCheck, \FILTER_VALIDATE_IP)) { + if ('v4' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_A); + if (false === $records || !isset($records[0]['ip'])) { + throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", Psr7\DiagnosticValue::escape($uri->getHost())), $request); + } + + return $uri->withHost($records[0]['ip']); + } + if ('v6' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_AAAA); + if (false === $records || !isset($records[0]['ipv6'])) { + throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", Psr7\DiagnosticValue::escape($uri->getHost())), $request); + } + + return $uri->withHost('['.$records[0]['ipv6'].']'); + } + } + + return $uri; + } + + /** + * Returns a numeric IPv4 spelling folded to the dotted quad libcurl's + * ipv4_normalize() produces, and every other host unchanged. + */ + private static function canonicalConnectionHost(string $host): string + { + $binary = HostIdentity::numericIpv4ToBinary($host); + if ($binary === null) { + return $host; + } + + return (string) \inet_ntop($binary); + } + + private function addDefaultTlsMinimum(RequestInterface $request, array &$context): void + { + if ('https' !== $request->getUri()->getScheme() || !isset($context['ssl']) || !\is_array($context['ssl'])) { + return; + } + + if ( + \array_key_exists('crypto_method', $context['ssl']) + || \array_key_exists('min_proto_version', $context['ssl']) + ) { + return; + } + + $context['ssl']['min_proto_version'] = \STREAM_CRYPTO_PROTO_TLSv1_2; + } + + /** + * Wires PHP 8.6+ TLS session resumption into the SSL context. Preferred + * sharing modes fall back to no sharing when a request cannot safely use + * Guzzle-managed sessions; HANDLER_REQUIRE fails loudly instead. + * + * New sessions are held temporarily and committed only after the HTTPS + * stream opens successfully. If PHP rejects peer verification or another + * stream-open step fails, any session reported during that attempt is + * discarded. + * + * @param array $customSslContext User-supplied stream_context['ssl'] + * values. + */ + private function applyTlsSessionResumption( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array &$context, + #[\SensitiveParameter] + array $customSslContext = [] + ): ?\Closure { + if (!$this->transportSharingRequested()) { + return null; + } + + $uri = $request->getUri(); + + if ('https' !== $uri->getScheme()) { + $this->failRequiredTlsSharingForRequest($request, 'handler-lifetime TLS session sharing only applies to HTTPS requests.'); + + return null; + } + + $host = $uri->getHost(); + + // PHP opens a proxy transport with the full stream context, so a TLS + // proxy handshake would consume origin-keyed session state; only a + // tcp:// proxy keeps TLS on the origin leg alone. + $proxy = $context['http']['proxy'] ?? null; + if (\is_string($proxy) && ProxyOptions::proxyScheme($proxy) !== 'tcp') { + $this->failRequiredTlsSharingForRequest($request, 'the proxy uses a TLS stream transport, which would mix proxy and origin TLS session state.'); + + return null; + } + + if (!isset($context['ssl']) || !\is_array($context['ssl'])) { + $this->failRequiredTlsSharingForConfiguration('the final stream SSL context is not an array.'); + + return null; + } + + $unsupported = StreamTlsSessionCache::unsupportedContextReason($context['ssl'], $customSslContext); + if ($unsupported !== null) { + $this->failRequiredTlsSharingForConfiguration($unsupported); + + return null; + } + + $cache = $this->sessionCache(); + if ($cache === null) { + $this->failRequiredTlsSharingForConfiguration('PHP 8.6+ with the OpenSSL session API is required.'); + + return null; + } + + $key = StreamTlsSessionCache::peerKey(self::canonicalConnectionHost($host), $uri->getPort() ?? 443, $context['ssl']); + $credentials = StreamTlsSessionCache::credentialFingerprint($context['ssl']); + + $session = $cache->find($key, $credentials); + if ($session !== null) { + $context['ssl']['session_data'] = $session; + } + + // Sessions captured before the stream opens are staged so handshakes + // that fail PHP's peer verification policy are never cached. + $accepted = false; + $staged = []; + + $context['ssl']['session_new_cb'] = static function ( + #[\SensitiveParameter] + $stream, + #[\SensitiveParameter] + Session $session + ) use ($cache, $key, $credentials, &$accepted, &$staged): void { + if ($accepted) { + $cache->store($key, $credentials, $session); + + return; + } + + // A server can stream session tickets while withholding response + // headers; keep only as many staged sessions as the cache retains. + if (\count($staged) >= StreamTlsSessionCache::MAX_SESSIONS_PER_KEY) { + \array_shift($staged); + } + + $staged[] = $session; + }; + + return static function () use ($cache, $key, $credentials, &$accepted, &$staged): void { + $accepted = true; + + foreach ($staged as $session) { + $cache->store($key, $credentials, $session); + } + + $staged = []; + }; + } + + private function transportSharingRequested(): bool + { + return $this->transportSharingMode !== TransportSharing::NONE + && $this->transportSharingMode !== TransportSharing::PERSISTENT_REQUIRE; + } + + private function transportSharingRequired(): bool + { + return $this->transportSharingMode === TransportSharing::HANDLER_REQUIRE; + } + + private function failRequiredTlsSharingForRequest( + #[\SensitiveParameter] + RequestInterface $request, + string $reason + ): void { + if ($this->transportSharingRequired()) { + throw new RequestException('The "transport_sharing" option requires stream handler TLS session sharing, but '.$reason, $request); + } + } + + private function failRequiredTlsSharingForConfiguration(string $reason): void + { + if ($this->transportSharingRequired()) { + throw new InvalidArgumentException('The "transport_sharing" option requires stream handler TLS session sharing, but '.$reason); + } + } + + /** + * Returns this handler's TLS session cache, or null when the configured + * sharing mode shares nothing or the OpenSSL session API is unavailable. + * Persistent (process-wide) sharing is a cURL-only feature, so + * PERSISTENT_PREFER degrades to this per-handler cache while + * PERSISTENT_REQUIRE is rejected before sharing applies. + */ + private function sessionCache(): ?StreamTlsSessionCache + { + if (!$this->transportSharingRequested() || !StreamTlsSessionCache::isSupported()) { + return null; + } + + return $this->sessionCache ?? ($this->sessionCache = new StreamTlsSessionCache(self::TLS_SESSION_CACHE_MAX_KEYS)); + } + + private function getDefaultContext( + #[\SensitiveParameter] + RequestInterface $request, + string $body + ): array { + $headers = ''; + foreach ($request->getHeaders() as $name => $value) { + // The first-class Proxy-Authorization field never enters the + // stream context header block: PHP streams have no proxy-only + // header channel, so applyProxy() rejects the field when a proxy + // is selected and it is omitted on direct and bypassed routes. + if (Psr7\Utils::caselessEquals((string) $name, 'Proxy-Authorization')) { + continue; + } + + foreach ($value as $val) { + $val = (string) $val; + if (\strpbrk("$name$val", "\r\n\0") !== false) { + throw new RequestException('Request header fields must not contain a carriage return, line feed or NUL byte.', $request); + } + + $headers .= "$name: $val\r\n"; + } + } + + $context = [ + 'http' => [ + 'auto_decode' => false, + 'method' => $request->getMethod(), + 'header' => $headers, + 'protocol_version' => $request->getProtocolVersion(), + 'ignore_errors' => true, + 'follow_location' => 0, + ], + 'ssl' => [ + 'peer_name' => self::canonicalConnectionHost($request->getUri()->getHost()), + ], + ]; + + // An empty context user_agent stops the HTTP stream wrapper from + // appending a User-Agent header from the user_agent ini setting, so a + // request without the header sends none, like the cURL handlers. + if (!$request->hasHeader('User-Agent')) { + $context['http']['user_agent'] = ''; + } + + if ('' !== $body) { + $context['http']['content'] = $body; + // Prevent the HTTP handler from adding a Content-Type header. + if (!$request->hasHeader('Content-Type')) { + $context['http']['header'] .= "Content-Type:\r\n"; + } + } + + $context['http']['header'] = \rtrim($context['http']['header'], "\r\n"); + + return $context; + } + + private function assertTransportSharingSupported(): void + { + // The stream handler cannot pool live connections or share state across + // handler instances; persistent sharing is cURL-only. + if ($this->transportSharingMode === TransportSharing::PERSISTENT_REQUIRE) { + throw new InvalidArgumentException('The "transport_sharing" option requires persistent transport sharing, which is only available through cURL share handles. The stream handler can only share handler-lifetime TLS sessions.'); + } + + // Handler-scoped sharing needs the PHP 8.6+ OpenSSL session API. + if ($this->transportSharingMode === TransportSharing::HANDLER_REQUIRE && !StreamTlsSessionCache::isSupported()) { + throw new InvalidArgumentException('The "transport_sharing" option requires handler-lifetime transport sharing, but the stream handler only supports it through TLS session resumption on PHP 8.6+ with the OpenSSL session API.'); + } + } + + private static function rejectUnsupportedRequestOptions( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): void { + if ( + \array_key_exists('curl', $options) + && $options['curl'] !== null + && $options['curl'] !== [] + ) { + throw new InvalidArgumentException('Passing the "curl" request option to the stream handler is not supported because the stream handler ignores cURL options.'); + } + + if (\array_key_exists('expect', $options) && $options['expect'] !== false && $request->hasHeader('Expect')) { + throw new InvalidArgumentException('Passing the "expect" request option to the stream handler is not supported when it adds an Expect header because the stream handler does not support Expect: 100-Continue.'); + } + + if (isset($options['on_trailers'])) { + throw new InvalidArgumentException('Passing the "on_trailers" request option to the stream handler is not supported because the stream handler cannot observe trailers.'); + } + } + + private function rejectStreamingWithConnectionCaps( + #[\SensitiveParameter] + array $options + ): void { + if ($this->connectionCapsConfigured && !empty($options['stream'])) { + throw new InvalidArgumentException('Enabling the "stream" request option on a stream handler configured with the "max_host_connections" or "max_total_connections" option is not supported because streamed connections cannot be capped.'); + } + } + + private static function rejectConflictingStreamContextOptions( + #[\SensitiveParameter] + array $streamContext + ): void { + $conflictingOptions = self::conflictingStreamContextOptions(); + + foreach ($streamContext as $wrapper => $contextOptions) { + if (!\is_string($wrapper) || !isset($conflictingOptions[$wrapper]) || !\is_array($contextOptions)) { + continue; + } + + foreach ($contextOptions as $option => $_) { + if (!\is_string($option) || !\array_key_exists($option, $conflictingOptions[$wrapper])) { + continue; + } + + $replacement = $conflictingOptions[$wrapper][$option]; + throw new InvalidArgumentException(\sprintf( + 'Passing stream_context.%s.%s in the "stream_context" request option is not supported because it conflicts with Guzzle-managed request handling. Use %s instead.', + Psr7\DiagnosticValue::escape($wrapper), + Psr7\DiagnosticValue::escape($option), + $replacement + )); + } + } + } + + private static function rejectUnsupportedStreamContextOptions( + #[\SensitiveParameter] + array $streamContext + ): void { + $unsupportedOptions = self::unsupportedStreamContextOptions($streamContext); + if ($unsupportedOptions === []) { + return; + } + + throw new InvalidArgumentException(\sprintf( + 'Passing PHP stream context options outside the built-in stream handler allow-list to the "stream_context" request option is not supported. Unsupported option%s: %s.', + \count($unsupportedOptions) === 1 ? '' : 's', + \implode(', ', $unsupportedOptions) + )); + } + + /** + * @return string[] + */ + private static function unsupportedStreamContextOptions(array $streamContext): array + { + $supportedOptions = self::supportedStreamContextOptions(); + $conflictingOptions = self::conflictingStreamContextOptions(); + $unsupportedOptions = []; + + foreach ($streamContext as $wrapper => $contextOptions) { + if (!\is_string($wrapper) || !isset($supportedOptions[$wrapper])) { + if (\is_array($contextOptions)) { + foreach ($contextOptions as $option => $_) { + if (\is_string($wrapper) && \is_string($option) && isset($conflictingOptions[$wrapper]) && \array_key_exists($option, $conflictingOptions[$wrapper])) { + continue; + } + + $unsupportedOptions[] = \sprintf('stream_context.%s.%s', Psr7\DiagnosticValue::escape((string) $wrapper), Psr7\DiagnosticValue::escape((string) $option)); + } + } else { + $unsupportedOptions[] = \sprintf('stream_context.%s', Psr7\DiagnosticValue::escape((string) $wrapper)); + } + + continue; + } + + if (!\is_array($contextOptions)) { + $unsupportedOptions[] = \sprintf('stream_context.%s', Psr7\DiagnosticValue::escape($wrapper)); + + continue; + } + + foreach ($contextOptions as $option => $_) { + if (\is_string($option) && isset($conflictingOptions[$wrapper]) && \array_key_exists($option, $conflictingOptions[$wrapper])) { + continue; + } + + if (!\is_string($option) || !\array_key_exists($option, $supportedOptions[$wrapper])) { + $unsupportedOptions[] = \sprintf('stream_context.%s.%s', Psr7\DiagnosticValue::escape($wrapper), Psr7\DiagnosticValue::escape((string) $option)); + } + } + } + + return $unsupportedOptions; + } + + /** + * @return array> + */ + private static function supportedStreamContextOptions(): array + { + return [ + 'http' => [ + 'request_fulluri' => true, + ], + 'socket' => [ + 'bindto' => true, + 'tcp_nodelay' => true, + ], + 'ssl' => [ + 'SNI_enabled' => true, + 'capture_peer_cert' => true, + 'capture_peer_cert_chain' => true, + 'ciphers' => true, + 'disable_compression' => true, + 'no_ticket' => true, + 'peer_fingerprint' => true, + 'security_level' => true, + 'verify_depth' => true, + ], + ]; + } + + /** + * @return array> + */ + private static function conflictingStreamContextOptions(): array + { + return [ + 'http' => [ + 'auto_decode' => 'Guzzle response framing and decoding', + 'content' => 'the request body', + 'follow_location' => 'the "allow_redirects" request option', + 'header' => 'the request headers', + 'max_redirects' => 'the "allow_redirects" request option', + 'method' => 'the request method', + 'protocol_version' => 'the request protocol version', + 'proxy' => 'the "proxy" request option', + 'timeout' => 'the "timeout" and "read_timeout" request options', + ], + 'ssl' => [ + 'allow_self_signed' => 'the "verify" request option', + 'cafile' => 'the "verify" request option', + 'capath' => 'the "verify" request option', + 'crypto_method' => 'the "crypto_method" request option', + 'local_cert' => 'the "cert" request option', + 'local_pk' => 'the "ssl_key" request option', + 'max_proto_version' => 'the "crypto_method_max" request option', + 'min_proto_version' => 'the "crypto_method" request option', + 'passphrase' => 'the "cert" or "ssl_key" request option', + 'peer_name' => 'the request URI', + 'verify_peer' => 'the "verify" request option', + 'verify_peer_name' => 'the "verify" request option', + ], + 'stream' => [ + 'error_handler' => 'Guzzle stream error handling', + 'error_mode' => 'Guzzle stream error handling', + 'error_store' => 'Guzzle stream error handling', + ], + ]; + } + + /** + * @param mixed $value as passed via Request transfer options. + * + * @return array{0: string, 1: string|null} + */ + private static function normalizeTlsFileOption( + string $option, + #[\SensitiveParameter] + $value + ): array { + $passphrase = null; + + if (\is_array($value)) { + if (!isset($value[0]) || !\is_string($value[0])) { + throw new InvalidArgumentException(\sprintf('Invalid %s request option', $option)); + } + if (isset($value[1])) { + if (!\is_string($value[1])) { + throw new InvalidArgumentException(\sprintf('Invalid %s request option', $option)); + } + $passphrase = $value[1]; + } + $value = $value[0]; + } + + if (!\is_string($value)) { + throw new InvalidArgumentException(\sprintf('Invalid %s request option', $option)); + } + + return [$value, $passphrase]; + } + + private static function setTlsPassphrase( + #[\SensitiveParameter] + array &$options, + #[\SensitiveParameter] + ?string $passphrase, + string $option + ): void { + if ($passphrase === null) { + return; + } + + if (isset($options['ssl']['passphrase']) && $options['ssl']['passphrase'] !== $passphrase) { + throw new InvalidArgumentException(\sprintf('Cannot use different passphrases for cert and ssl_key with the stream handler; %s conflicts with an existing TLS passphrase.', $option)); + } + + $options['ssl']['passphrase'] = $passphrase; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private static function assertStreamTlsType(string $option, $value): void + { + if (!\is_string($value) || $value === '') { + throw new InvalidArgumentException(\sprintf('%s must be a non-empty string', $option)); + } + + if (Psr7\Utils::asciiToUpper($value) !== 'PEM') { + throw new InvalidArgumentException(\sprintf('The stream handler only supports "PEM" for the %s request option.', $option)); + } + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applyProxy( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array &$context, + #[\SensitiveParameter] + $value + ): void { + $proxy = ProxyEnv::resolveProxySelection($request->getUri(), $value); + $proxyUri = $proxy->getProxy(); + if ($proxyUri === null) { + return; + } + + // Validate the whole proxy authority up front (ProxyOptions leans on + // Psr7\Rfc3986), so a malformed proxy fails the same way on every + // handler. PHP's HTTP stream wrapper can only carry HTTP over a + // TCP-family socket, so reject any scheme it can never execute instead + // of letting PHP fail with a misleading "unable to find the socket + // transport" error. The supported set is a scheme-less value, http, or + // a TCP-family transport (tcp://, ssl://, tls://, tlsv1.*) the build has. + $scheme = ProxyOptions::proxyScheme($proxyUri); + + if ($scheme === 'https') { + throw new InvalidArgumentException('HTTPS proxies are not supported by the stream handler.'); + } + + if (\in_array($scheme, ['socks4', 'socks4a', 'socks5', 'socks5h'], true)) { + throw new InvalidArgumentException('SOCKS proxies are not supported by the stream handler.'); + } + + // Only http or a TCP-family raw transport (tcp, ssl, tls, tlsv1.*) can + // carry HTTP through the stream wrapper; udp/unix/udg/ftp/ws and typos + // cannot on any build, so reject them as a caller error rather than + // install an unusable proxy. + if ($scheme !== 'http' && !self::isRawTransportName($scheme)) { + throw new InvalidArgumentException(\sprintf('The "%s" proxy scheme is not supported by the stream handler.', Psr7\DiagnosticValue::escape($scheme))); + } + + // A recognized SSL/TLS transport may still be absent from this build + // (tls:// without OpenSSL, tlsv1.3:// on OpenSSL < 1.1.1); that is + // build-specific, so it is a RequestException, distinct from the caller + // error above. http maps to tcp and tcp is always registered, so only + // the SSL/TLS family reaches the stream_get_transports() lookup. + if (!\in_array($scheme, ['http', 'tcp'], true) && !\in_array($scheme, \stream_get_transports(), true)) { + throw new RequestException(\sprintf('The "%s" proxy transport is not available in this PHP build.', Psr7\DiagnosticValue::escape($scheme)), $request); + } + + $parsed = $this->parseProxy($proxyUri, $scheme); + + // PHP streams do not expose separate proxy and origin header lists; + // the wrapper's CONNECT handling copies one textual match out of a + // generic user-header buffer and forwards the rest to the tunneled + // origin, so arbitrary first-class Proxy-Authorization values cannot + // be routed safely. Fail closed before any stream is created. + if ($request->hasHeader('Proxy-Authorization')) { + throw new InvalidArgumentException('Proxy-Authorization request headers are not supported through the stream handler; configure credentials in the proxy URI or use a cURL handler.'); + } + + $context['http']['proxy'] = $parsed['proxy']; + + if ($parsed['auth']) { + if (!isset($context['http']['header'])) { + $context['http']['header'] = ''; + } + $context['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; + } + } + + /** + * Whether the scheme is a TCP-family transport name that can carry HTTP + * for a proxy (tcp, ssl, tls, tlsv1.*), regardless of build support. + */ + private static function isRawTransportName(string $scheme): bool + { + return \in_array($scheme, ['tcp', 'ssl', 'tls'], true) + || \preg_match('/^tlsv\d+(?:\.\d+)?$/D', $scheme) === 1; + } + + /** + * Parses the given proxy URL to make it compatible with the format PHP's + * stream context expects. + */ + private function parseProxy(string $url, string $scheme): array + { + // applyProxy() has already validated the scheme, so only an http + // proxy needs translating to the tcp:// form the wrapper expects; a + // port-less proxy defaults to 1080 to match libcurl's HTTP default. + if ($scheme !== 'http') { + return [ + 'proxy' => $url, + 'auth' => null, + ]; + } + + $parsed = \parse_url(\strpos($url, '://') === false ? 'http://'.$url : $url); + if (\is_array($parsed) && isset($parsed['host'])) { + $port = $parsed['port'] ?? 1080; + $user = $parsed['user'] ?? ''; + $pass = $parsed['pass'] ?? ''; + $auth = ($user !== '' || $pass !== '') ? 'Basic '.\base64_encode("{$user}:{$pass}") : null; + + return [ + 'proxy' => "tcp://{$parsed['host']}:{$port}", + 'auth' => $auth, + ]; + } + + return [ + 'proxy' => $url, + 'auth' => null, + ]; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applyCryptoMethodOption( + #[\SensitiveParameter] + array &$context, + $value + ): void { + $context['ssl']['min_proto_version'] = TlsVersion::streamProtocolVersion('crypto_method', $value); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applyCryptoMethodMaxOption( + #[\SensitiveParameter] + array &$context, + $value + ): void { + $context['ssl']['max_proto_version'] = TlsVersion::streamProtocolVersion('crypto_method_max', $value); + } + + private static function assertTlsVersionRangeForOptions( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): void { + if (!isset($options['crypto_method_max'])) { + return; + } + + $cryptoMethod = $options['crypto_method'] ?? null; + if ($cryptoMethod === null && 'https' === $request->getUri()->getScheme()) { + $cryptoMethod = \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; + } + + TlsVersion::assertRange($cryptoMethod, $options['crypto_method_max']); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applyVerifyOption( + #[\SensitiveParameter] + array &$context, + $value + ): void { + if ($value === false) { + $context['ssl']['verify_peer'] = false; + $context['ssl']['verify_peer_name'] = false; + + return; + } + + if (\is_string($value)) { + $context['ssl']['cafile'] = $value; + if (!\file_exists($value)) { + throw new \RuntimeException(\sprintf('SSL CA bundle not found: %s', Psr7\DiagnosticValue::escape($value))); + } + } elseif ($value !== true) { + throw new InvalidArgumentException('Invalid verify request option'); + } + + $context['ssl']['verify_peer'] = true; + $context['ssl']['verify_peer_name'] = true; + $context['ssl']['allow_self_signed'] = false; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applyCertOption( + #[\SensitiveParameter] + array &$context, + #[\SensitiveParameter] + $value + ): void { + [$value, $passphrase] = self::normalizeTlsFileOption('cert', $value); + + if (!\file_exists($value)) { + throw new \RuntimeException(\sprintf('SSL certificate not found: %s', Psr7\DiagnosticValue::escape($value))); + } + + self::setTlsPassphrase($context, $passphrase, 'cert'); + $context['ssl']['local_cert'] = $value; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applyCertTypeOption($value): void + { + self::assertStreamTlsType('cert_type', $value); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applySslKeyOption( + #[\SensitiveParameter] + array &$context, + #[\SensitiveParameter] + $value + ): void { + [$value, $passphrase] = self::normalizeTlsFileOption('ssl_key', $value); + + if (!\file_exists($value)) { + throw new \RuntimeException(\sprintf('SSL private key not found: %s', Psr7\DiagnosticValue::escape($value))); + } + + self::setTlsPassphrase($context, $passphrase, 'ssl_key'); + $context['ssl']['local_pk'] = $value; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applySslKeyTypeOption($value): void + { + self::assertStreamTlsType('ssl_key_type', $value); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applyProgressOption($value, array &$params): void + { + if (!\is_callable($value)) { + throw new InvalidArgumentException('progress client option must be callable'); + } + + self::addNotification( + $params, + static function ($code, $a, $b, $c, $transferred, $total) use ($value): void { + if ($code == \STREAM_NOTIFY_PROGRESS) { + // The upload progress cannot be determined. Use 0 for cURL compatibility: + // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html + $value( + TransferByteCounter::progressValueToInt($total), + TransferByteCounter::progressValueToInt($transferred), + 0, + 0 + ); + } + } + ); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function applyDebugOption( + #[\SensitiveParameter] + RequestInterface $request, + $value, + array &$params + ): void { + if ($value === false) { + return; + } + + static $map = [ + \STREAM_NOTIFY_CONNECT => 'CONNECT', + \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', + \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', + \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', + \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', + \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', + \STREAM_NOTIFY_PROGRESS => 'PROGRESS', + \STREAM_NOTIFY_FAILURE => 'FAILURE', + \STREAM_NOTIFY_COMPLETED => 'COMPLETED', + \STREAM_NOTIFY_RESOLVE => 'RESOLVE', + ]; + static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; + + $value = DebugResource::from($value); + $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); + self::addNotification( + $params, + static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { + \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); + foreach (\array_filter($passed) as $i => $v) { + \fwrite($value, $args[$i].': "'.$v.'" '); + } + \fwrite($value, "\n"); + } + ); + } + + private static function addNotification(array &$params, callable $notify): void + { + // Wrap the existing function if needed. + if (!isset($params['notification'])) { + $params['notification'] = $notify; + } else { + $params['notification'] = self::callArray([ + $params['notification'], + $notify, + ]); + } + } + + private static function callArray(array $functions): callable + { + return static function (...$args) use ($functions): void { + foreach ($functions as $fn) { + $fn(...$args); + } + }; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/StreamTlsSessionCache.php b/vendor/guzzlehttp/guzzle/src/Handler/StreamTlsSessionCache.php new file mode 100644 index 0000000..8abe67d --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/StreamTlsSessionCache.php @@ -0,0 +1,583 @@ + true, + 'session_cache_size' => true, + 'session_data' => true, + 'session_get_cb' => true, + 'session_id_context' => true, + 'session_new_cb' => true, + 'session_remove_cb' => true, + 'session_stream' => true, + 'session_timeout' => true, + ]; + + private const USER_MANAGED_PSK_OPTIONS = [ + 'psk_client_cb' => true, + 'psk_server_cb' => true, + ]; + + /** + * TLS 1.3 early data (0-RTT) options are deliberately never shared: an + * injected cached session would let PHP send the replayable early data + * payload ahead of the HTTP request. + */ + private const USER_MANAGED_EARLY_DATA_OPTIONS = [ + 'early_data' => true, + 'early_data_cb' => true, + 'max_early_data' => true, + ]; + + /** + * File/path-bearing SSL context options are deliberately not shared: their + * contents can change outside this handler. + */ + private const PATH_OPTIONS = [ + 'SNI_server_certs' => true, + 'cafile' => true, + 'capath' => true, + 'dh_param' => true, + 'local_cert' => true, + 'local_pk' => true, + ]; + + private const CERT_CAPTURE_OPTIONS = [ + 'capture_peer_cert' => true, + 'capture_peer_cert_chain' => true, + ]; + + /** + * Scalar custom SSL context options that are known to be self-contained + * and safe to include in the TLS session cache identity. + */ + private const CUSTOM_SCALAR_KEYABLE_OPTIONS = [ + 'SNI_enabled' => true, + 'allow_self_signed' => true, + 'alpn_protocols' => true, + 'ciphers' => true, + 'crypto_method' => true, + 'disable_compression' => true, + 'max_proto_version' => true, + 'min_proto_version' => true, + 'peer_name' => true, + 'security_level' => true, + 'verify_depth' => true, + 'verify_peer' => true, + 'verify_peer_name' => true, + ]; + + private const INVALID_PEER_FINGERPRINT_REASON = 'the SSL context option "peer_fingerprint" must be a string or a non-empty, flat array with string algorithm names and string fingerprints.'; + + private int $maxKeys; + + /** + * @var array> + */ + private array $sessions = []; + + public function __construct(int $maxKeys) + { + if ($maxKeys < 1) { + throw new InvalidArgumentException('maxKeys must be a positive integer.'); + } + + $this->maxKeys = $maxKeys; + } + + public static function isSupported(): bool + { + // Any PHP 8.6 build qualifies, including pre-release and nightly + // builds; the class check keeps unstable builds that do not carry + // the final API fail-closed. + return \PHP_VERSION_ID >= 80600 && \class_exists(Session::class, false); + } + + /** + * @param array $ssl The assembled 'ssl' stream context array. + * @param array $customSsl The user-supplied stream_context['ssl'] array. + */ + public static function unsupportedContextReason(array $ssl, array $customSsl = []): ?string + { + foreach ($customSsl as $key => $value) { + if ( + !isset(self::CUSTOM_SCALAR_KEYABLE_OPTIONS[$key]) + && !isset(self::PATH_OPTIONS[$key]) + && !isset(self::USER_MANAGED_SESSION_OPTIONS[$key]) + && !isset(self::USER_MANAGED_PSK_OPTIONS[$key]) + && !isset(self::USER_MANAGED_EARLY_DATA_OPTIONS[$key]) + && !isset(self::CERT_CAPTURE_OPTIONS[$key]) + && $key !== 'no_ticket' + && $key !== 'peer_fingerprint' + ) { + return \sprintf('the custom SSL context option "%s" is not known to be safe for TLS session sharing.', Psr7\DiagnosticValue::escape((string) $key)); + } + } + + foreach ($ssl as $key => $value) { + if (isset(self::PATH_OPTIONS[$key])) { + return \sprintf('the SSL context option "%s" uses file or path state that cannot be safely shared.', Psr7\DiagnosticValue::escape((string) $key)); + } + + if (isset(self::USER_MANAGED_SESSION_OPTIONS[$key])) { + return \sprintf('the SSL context option "%s" is user-managed TLS session state.', Psr7\DiagnosticValue::escape((string) $key)); + } + + if (isset(self::USER_MANAGED_PSK_OPTIONS[$key])) { + return \sprintf('the SSL context option "%s" is user-managed TLS PSK state.', Psr7\DiagnosticValue::escape((string) $key)); + } + + if (isset(self::USER_MANAGED_EARLY_DATA_OPTIONS[$key])) { + return \sprintf('the SSL context option "%s" is user-managed TLS early data state.', Psr7\DiagnosticValue::escape((string) $key)); + } + + if (isset(self::CERT_CAPTURE_OPTIONS[$key]) && $value) { + return \sprintf('the SSL context option "%s" requires a fresh peer certificate handshake.', Psr7\DiagnosticValue::escape((string) $key)); + } + + if ($key === 'no_ticket' && $value) { + return 'the SSL context option "no_ticket" disables TLS ticket sharing.'; + } + + if ($key === 'peer_fingerprint') { + if (!self::isPeerFingerprint($value)) { + return self::INVALID_PEER_FINGERPRINT_REASON; + } + + continue; + } + + if (!self::isCanonicalScalar($value)) { + return \sprintf('the SSL context option "%s" cannot be safely included in the TLS session cache identity.', Psr7\DiagnosticValue::escape((string) $key)); + } + } + + return null; + } + + /** + * Builds the non-secret lookup key: host/port plus every TLS parameter that + * defines the verification/identity context. Keyed on the connection host + * a transport reads, with numeric IPv4 spellings folded to one dotted + * quad; names are never resolved. Secret material is excluded. + * + * @param array $ssl The assembled 'ssl' stream context array. + */ + public static function peerKey( + string $host, + ?int $port, + #[\SensitiveParameter] + array $ssl + ): string { + $identity = [ + 'schema' => 'guzzle-stream-tls-session-v1', + 'runtime' => self::runtimeIdentity(), + 'peer' => [ + 'host' => self::canonicalHost($host), + 'port' => $port, + ], + 'ssl' => self::canonicalPeerSslContext($ssl), + ]; + + return \hash('sha256', \serialize($identity)); + } + + /** + * Builds the secret-aware credential fingerprint matched in constant time, + * keeping the passphrase out of the loggable peer key. + * + * Every credential-bearing context is currently rejected by + * unsupportedContextReason() before sharing, so fingerprints can only + * diverge if the allow-lists are ever widened; the constant-time match is + * retained as defense in depth for that case. + * + * @param array $ssl The assembled 'ssl' stream context array. + */ + public static function credentialFingerprint(array $ssl): string + { + $material = [ + 'local_cert' => isset($ssl['local_cert']) && \is_string($ssl['local_cert']) ? self::pathIdentity($ssl['local_cert']) : null, + 'local_pk' => isset($ssl['local_pk']) && \is_string($ssl['local_pk']) ? self::pathIdentity($ssl['local_pk']) : null, + 'passphrase' => isset($ssl['passphrase']) && \is_string($ssl['passphrase']) ? $ssl['passphrase'] : null, + ]; + + return \hash('sha256', \serialize($material)); + } + + public function find(string $key, string $credentials): ?Session + { + if (!isset($this->sessions[$key])) { + return null; + } + + $now = \time(); + $entries = $this->sessions[$key]; + $found = null; + + foreach ($entries as $i => $entry) { + if ($entry['expiresAt'] <= $now) { + unset($entries[$i]); + continue; + } + + if (!\hash_equals($entry['credentials'], $credentials)) { + continue; + } + + if (!$entry['session']->isResumable()) { + unset($entries[$i]); + continue; + } + + $found = $entry['session']; + + // TLS 1.3 tickets are single-use; consume on take. + if ($entry['singleUse']) { + unset($entries[$i]); + } + + break; + } + + if ($entries === []) { + unset($this->sessions[$key]); + } else { + $this->sessions[$key] = \array_values($entries); + if ($found !== null) { + $this->touch($key); + } + } + + return $found; + } + + public function store( + string $key, + string $credentials, + #[\SensitiveParameter] + Session $session + ): void { + if (!$session->isResumable()) { + return; + } + + $expiresAt = self::expiry($session); + if ($expiresAt === null) { + return; + } + + $list = $this->sessions[$key] ?? []; + $list[] = [ + 'session' => $session, + 'credentials' => $credentials, + 'expiresAt' => $expiresAt, + 'singleUse' => self::isTls13($session), + ]; + + if (\count($list) > self::MAX_SESSIONS_PER_KEY) { + $list = \array_slice($list, -self::MAX_SESSIONS_PER_KEY); + } + + $this->sessions[$key] = $list; + $this->touch($key); + $this->evictExcessKeys(); + } + + private function touch(string $key): void + { + if (!isset($this->sessions[$key])) { + return; + } + + $value = $this->sessions[$key]; + unset($this->sessions[$key]); + $this->sessions[$key] = $value; + } + + private function evictExcessKeys(): void + { + while (\count($this->sessions) > $this->maxKeys) { + \array_shift($this->sessions); + } + } + + private static function isTls13( + #[\SensitiveParameter] + Session $session + ): bool { + $protocol = $session->getProtocol(); + + return $protocol !== null && Psr7\Utils::caselessContains($protocol, '1.3'); + } + + /** + * Returns the absolute expiry timestamp, or null when the session must + * not be cached. + */ + private static function expiry( + #[\SensitiveParameter] + Session $session + ): ?int { + return self::expiryFromLifetimes( + self::isTls13($session), + $session->hasTicket(), + $session->getTicketLifetimeHint(), + $session->getTimeout(), + $session->getCreatedAt(), + \time() + ); + } + + /** + * Decides the absolute expiry timestamp from a session's scalar lifetime + * attributes, or null when the session must not be cached. + * + * A non-positive session timeout is never cached. TLS 1.3 resumption + * requires a New Session Ticket, so a TLS 1.3 session without a ticket + * or without a positive RFC 8446 ticket lifetime is not cached, and the + * ticket lifetime bounds the expiry together with the session timeout + * and the seven-day cap. Pre-TLS-1.3 tickets treat a zero or missing + * lifetime hint as unspecified per RFC 5077, so only a positive hint + * tightens the session timeout and the one-day cap. An expiry that has + * already passed is not cached. + */ + private static function expiryFromLifetimes(bool $isTls13, bool $hasTicket, ?int $ticketLifetimeHint, int $timeout, int $createdAt, int $now): ?int + { + if ($timeout <= 0) { + return null; + } + + $lifetime = \min($timeout, $isTls13 ? self::MAX_TLS13_LIFETIME : self::MAX_PRE_TLS13_LIFETIME); + + if ($isTls13) { + if (!$hasTicket || $ticketLifetimeHint === null || $ticketLifetimeHint <= 0) { + return null; + } + + $lifetime = \min($lifetime, $ticketLifetimeHint); + } elseif ($hasTicket && $ticketLifetimeHint !== null && $ticketLifetimeHint > 0) { + $lifetime = \min($lifetime, $ticketLifetimeHint); + } + + $expiresAt = $createdAt + $lifetime; + + return $expiresAt > $now ? $expiresAt : null; + } + + private static function runtimeIdentity(): array + { + return [ + 'php' => \PHP_VERSION_ID, + 'openssl' => \defined('OPENSSL_VERSION_NUMBER') ? \OPENSSL_VERSION_NUMBER : null, + 'trust' => [ + 'openssl.cafile' => (string) \ini_get('openssl.cafile'), + 'openssl.capath' => (string) \ini_get('openssl.capath'), + 'SSL_CERT_FILE' => (string) \getenv('SSL_CERT_FILE'), + 'SSL_CERT_DIR' => (string) \getenv('SSL_CERT_DIR'), + 'cwd' => \getcwd(), + ], + ]; + } + + /** + * Returns the host identity hashed into the cache key. Valid bracketed + * IPv6 literals are canonicalized to their RFC 5952 form so equivalent + * spellings of one address share a single session entry; other valid + * hosts, such as reg-names and IPvFuture literals, fall back to ASCII + * case folding. Text that is not a valid RFC 3986 host, such as + * zone-bearing or malformed bracketed literals, must never become a + * usable cache key, so it is rejected. + */ + private static function canonicalHost(string $host): string + { + if (!Psr7\Rfc3986::isValidHost($host)) { + throw new InvalidArgumentException('Hosts used in the TLS session cache identity must be valid RFC 3986 hosts.'); + } + + return HostIdentity::canonicalHost($host); + } + + private static function canonicalPeerSslContext( + #[\SensitiveParameter] + array $ssl + ): array { + $context = []; + + foreach ($ssl as $key => $value) { + if (isset(self::USER_MANAGED_SESSION_OPTIONS[$key]) || isset(self::USER_MANAGED_PSK_OPTIONS[$key]) || isset(self::USER_MANAGED_EARLY_DATA_OPTIONS[$key]) || $key === 'passphrase') { + continue; + } + + if ($key === 'peer_name' && \is_string($value)) { + $context[$key] = ['string', self::canonicalHost($value)]; + + continue; + } + + if ($key === 'peer_fingerprint') { + $context[$key] = self::canonicalPeerFingerprint($value); + + continue; + } + + if (\in_array($key, ['cafile', 'capath', 'local_cert', 'local_pk'], true) && \is_string($value)) { + $context[$key] = self::pathIdentity($value); + + continue; + } + + $context[$key] = self::canonicalScalar($value); + } + + \ksort($context); + + return $context; + } + + private static function pathIdentity(string $path): array + { + $realPath = \realpath($path); + + return [ + 'path', + $realPath !== false ? $realPath : $path, + ]; + } + + /** + * @param mixed $value + */ + private static function isCanonicalScalar($value): bool + { + return $value === null + || \is_bool($value) + || \is_int($value) + || \is_float($value) + || \is_string($value); + } + + /** + * @param mixed $value + */ + private static function isPeerFingerprint($value): bool + { + if (\is_string($value)) { + return true; + } + + if (!\is_array($value) || $value === []) { + return false; + } + + foreach ($value as $algorithm => $fingerprint) { + if (!\is_string($algorithm) || !\is_string($fingerprint)) { + return false; + } + } + + return true; + } + + /** + * @param mixed $value + * + * @return array{0: string, 1: mixed} + */ + private static function canonicalScalar($value): array + { + if ($value === null) { + return ['null', null]; + } + + if (\is_bool($value)) { + return ['bool', $value]; + } + + if (\is_int($value)) { + return ['int', $value]; + } + + if (\is_float($value)) { + return ['float', \bin2hex(\pack('E', $value))]; + } + + if (\is_string($value)) { + return ['string', $value]; + } + + throw new InvalidArgumentException('SSL context values used in the TLS session cache identity must be scalar or null.'); + } + + /** + * @param mixed $value + * + * @return array{0: string, 1: mixed} + */ + private static function canonicalPeerFingerprint($value): array + { + if (!self::isPeerFingerprint($value)) { + throw new InvalidArgumentException(self::INVALID_PEER_FINGERPRINT_REASON); + } + + if (\is_string($value)) { + return ['string', $value]; + } + + if (!\is_array($value)) { + throw new InvalidArgumentException(self::INVALID_PEER_FINGERPRINT_REASON); + } + + $items = []; + foreach ($value as $algorithm => $fingerprint) { + $items[$algorithm] = ['string', $fingerprint]; + } + \ksort($items, \SORT_STRING); + + return ['map', $items]; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/Timeout.php b/vendor/guzzlehttp/guzzle/src/Handler/Timeout.php new file mode 100644 index 0000000..0c9da6c --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/Timeout.php @@ -0,0 +1,41 @@ + 0 && $milliseconds === 0) { + throw new InvalidArgumentException($option.' must be 0 or greater than or equal to 0.001 seconds'); + } + + return $milliseconds; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/TlsVersion.php b/vendor/guzzlehttp/guzzle/src/Handler/TlsVersion.php new file mode 100644 index 0000000..90cf7c8 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/TlsVersion.php @@ -0,0 +1,70 @@ + \PHP_INT_MAX + || (\PHP_INT_SIZE === 8 && $value >= (float) \PHP_INT_MAX) + ) { + throw new \OverflowException('Progress byte count exceeds the maximum integer size supported on this platform'); + } + + $intValue = (int) $value; + if ($intValue < 0) { + throw new \OverflowException('Progress byte count exceeds the maximum integer size supported on this platform'); + } + + return $intValue; + } + + public static function add(int $current, int $delta, string $message): int + { + if ($current < 0 || $delta < 0) { + throw new \OverflowException($message); + } + + if ($delta > \PHP_INT_MAX - $current) { + throw new \OverflowException($message); + } + + return $current + $delta; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/TransportStream.php b/vendor/guzzlehttp/guzzle/src/Handler/TransportStream.php new file mode 100644 index 0000000..1fe673f --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/TransportStream.php @@ -0,0 +1,48 @@ +stream = $stream; + } + + public function __clone() + { + // Detaching a clone must not detach this body's transport. + $this->stream = clone $this->stream; + } + + public function read(int $length): string + { + $buffered = $this->stream->getMetadata('unread_bytes'); + + return $this->stream->read(\is_int($buffered) && $buffered > 0 ? \min($length, $buffered) : $length); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/UriDiagnostic.php b/vendor/guzzlehttp/guzzle/src/Handler/UriDiagnostic.php new file mode 100644 index 0000000..660a131 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/UriDiagnostic.php @@ -0,0 +1,39 @@ +getQuery(); + if ($query !== '') { + $message = \str_replace('?'.$query, '', $message); + } + + $fragment = $uri->getFragment(); + if ($fragment !== '') { + $message = \str_replace('#'.$fragment, '', $message); + } + + return Psr7\DiagnosticValue::escape($message); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/HandlerStack.php b/vendor/guzzlehttp/guzzle/src/HandlerStack.php new file mode 100644 index 0000000..ed49d7e --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/HandlerStack.php @@ -0,0 +1,274 @@ + + */ + private array $stack = []; + + /** + * @var (callable&THandler)|null + */ + private $cached; + + /** + * Creates a default handler stack that can be used by clients. + * + * The returned handler will wrap the provided handler or use the most + * appropriate default handler for your system. The returned HandlerStack + * has support for authentication, cookies, redirects, HTTP error + * exceptions, and preparing a body before sending. + * + * The returned handler stack can be passed to a client in the "handler" + * option. + * + * @param (callable(RequestInterface, array): PromiseInterface)|null $handler HTTP handler function to use with the stack. If no + * handler is provided, the best handler for your + * system will be utilized. + * + * @return self): PromiseInterface> + */ + public static function create(?callable $handler = null): self + { + $stack = new self($handler ?: Utils::chooseHandler()); + $stack->push(Middleware::httpErrors(), 'http_errors'); + $stack->push(Middleware::redirect(), 'allow_redirects'); + $stack->push(Middleware::auth(), 'auth'); + $stack->push(Middleware::cookies(), 'cookies'); + $stack->push(Middleware::prepareBody(), 'prepare_body'); + + return $stack; + } + + /** + * @param (callable&THandler)|null $handler Underlying handler. + */ + public function __construct(?callable $handler = null) + { + $this->handler = $handler; + } + + /** + * Invokes the handler stack as a composed handler + * + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) { + $handler = $this->resolve(); + + return $handler($request, $options); + } + + /** + * Set the HTTP handler that actually returns a promise. + * + * @param callable&THandler $handler Accepts a request and array of options and returns a value expected by the stack. + */ + public function setHandler(callable $handler): void + { + $this->handler = $handler; + $this->cached = null; + } + + /** + * Returns true if the builder has a handler. + */ + public function hasHandler(): bool + { + return $this->handler !== null; + } + + /** + * Unshift a middleware to the bottom of the stack. + * + * @param callable(callable&THandler): (callable&THandler) $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function unshift(callable $middleware, ?string $name = null): void + { + \array_unshift($this->stack, [$middleware, $name]); + $this->cached = null; + } + + /** + * Push a middleware to the top of the stack. + * + * @param callable(callable&THandler): (callable&THandler) $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function push(callable $middleware, string $name = ''): void + { + $this->stack[] = [$middleware, $name]; + $this->cached = null; + } + + /** + * Add a middleware before another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable&THandler): (callable&THandler) $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function before(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, true); + } + + /** + * Add a middleware after another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable&THandler): (callable&THandler) $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function after(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, false); + } + + /** + * Remove a middleware by instance or name from the stack. + * + * @param (callable(callable&THandler): (callable&THandler))|string $remove Middleware to remove by instance or name. + */ + public function remove($remove): void + { + if (!\is_string($remove) && !\is_callable($remove)) { + // TODO: Move this to the parameter definition in 9.0. + throw new \TypeError(__METHOD__.'(): Argument #1 ($remove) must be of type callable|string'); + } + + $this->cached = null; + + if (\is_string($remove)) { + $count = \count($this->stack); + $this->stack = \array_values(\array_filter( + $this->stack, + static function (array $tuple) use ($remove): bool { + return $tuple[1] !== $remove; + } + )); + + if ($count !== \count($this->stack) || !\is_callable($remove)) { + return; + } + } + + $this->stack = \array_values(\array_filter( + $this->stack, + static function (array $tuple) use ($remove): bool { + return $tuple[0] !== $remove; + } + )); + } + + /** + * Compose the middleware and handler into a single callable function. + * + * @return callable&THandler + */ + public function resolve(): callable + { + if ($this->cached === null) { + if (($prev = $this->handler) === null) { + throw new \LogicException('No handler has been specified'); + } + + if (!\is_callable($prev)) { + throw new \LogicException('Handler must be callable'); + } + + foreach (\array_reverse($this->stack) as $fn) { + if (!\is_array($fn) || !\array_key_exists(0, $fn) || !\is_callable($fn[0])) { + throw new \LogicException('Middleware must be callable'); + } + + $prev = $fn[0]($prev); + + if (!\is_callable($prev)) { + throw new \LogicException('Middleware must return a callable'); + } + } + + $this->cached = $prev; + } + + return $this->cached; + } + + public function __unserialize(array $data): void + { + $this->handler = null; + $this->stack = []; + $this->cached = null; + + throw new \LogicException(static::class.' should never be unserialized'); + } + + private function findByName(string $name): int + { + foreach ($this->stack as $k => $v) { + if ($v[1] === $name) { + return $k; + } + } + + throw new \InvalidArgumentException(\sprintf('Middleware not found: %s', DiagnosticValue::escape($name))); + } + + /** + * Splices a function into the middleware list at a specific position. + * + * @param callable(callable&THandler): (callable&THandler) $middleware + */ + private function splice(string $findName, string $withName, callable $middleware, bool $before): void + { + $this->cached = null; + $idx = $this->findByName($findName); + $tuple = [$middleware, $withName]; + + if ($before) { + if ($idx === 0) { + \array_unshift($this->stack, $tuple); + } else { + $replacement = [$tuple, $this->stack[$idx]]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } elseif ($idx === \count($this->stack) - 1) { + $this->stack[] = $tuple; + } else { + $replacement = [$this->stack[$idx], $tuple]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/HostIdentity.php b/vendor/guzzlehttp/guzzle/src/HostIdentity.php new file mode 100644 index 0000000..5bd6c27 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/HostIdentity.php @@ -0,0 +1,233 @@ + 2 && \ctype_xdigit(\substr($last, 2)); + } + + /** + * Returns the four-byte binary form of a host that a transport reads as a + * numeric IPv4 address, or null when it reads it as a name. + * + * The shape test is Handler\HostValidator::isNumericIpv4Host(); this + * method adds the range checks that predicate omits: every part but the + * last must fit one octet, and the last must fit the octets the earlier + * parts left. A trailing root dot is not swallowed, unlike libcurl 8.21.0 + * and later, because assertRequestHost() rejects that spelling first. + */ + public static function numericIpv4ToBinary(string $host): ?string + { + if (!Handler\HostValidator::isNumericIpv4Host($host)) { + return null; + } + + $values = []; + foreach (\explode('.', $host) as $part) { + $values[] = self::numericIpv4PartValue($part); + } + + // Every accepted value is a whole number no larger than 0xFFFFFFFF, + // which a float holds exactly, so the arithmetic below is correct on a + // 32-bit build too, where the widest part overflows an integer. + $address = (float) \array_pop($values); + + $packed = ''; + foreach ($values as $value) { + if ($value > 255.0) { + return null; + } + + $packed .= \chr((int) $value); + } + + $width = 4 - \count($values); + if ($address >= 256.0 ** $width) { + return null; + } + + for ($shift = $width - 1; $shift >= 0; --$shift) { + $packed .= \chr((int) \fmod(\floor($address / 256.0 ** $shift), 256.0)); + } + + return $packed; + } + + /** + * Returns the value of one accepted part as a float, so a part filling + * all four octets such as 2130706433 stays exact on every integer width. + */ + private static function numericIpv4PartValue(string $part): float + { + if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) { + return self::digitsValue((string) \substr($part, 2), 16); + } + + if ($part[0] === '0') { + return self::digitsValue($part, 8); + } + + return (float) $part; + } + + private static function digitsValue(string $digits, int $base): float + { + $value = 0.0; + foreach (\str_split($digits) as $digit) { + $value = $value * $base + \hexdec($digit); + if ($value > 0xFFFFFFFF) { + break; + } + } + + return $value; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Idn.php b/vendor/guzzlehttp/guzzle/src/Idn.php new file mode 100644 index 0000000..46953dd --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Idn.php @@ -0,0 +1,106 @@ +getHost()) { + $asciiHost = self::idnToAsci($uri->getHost(), $options, $info); + if ($asciiHost === false) { + $errorBitSet = $info['errors'] ?? 0; + + $errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool { + return substr($name, 0, 11) === 'IDNA_ERROR_'; + }); + + $errors = []; + foreach ($errorConstants as $errorConstant) { + if ($errorBitSet & constant($errorConstant)) { + $errors[] = $errorConstant; + } + } + + $errorMessage = 'IDN conversion failed'; + if ($errors) { + $errorMessage .= ' (errors: '.implode(', ', $errors).')'; + } + + throw new InvalidArgumentException($errorMessage); + } + if ($uri->getHost() !== $asciiHost) { + // The conversion can map a character to a URI delimiter. + if (!Psr7\Rfc3986::isValidHost($asciiHost)) { + throw new InvalidArgumentException('IDN conversion failed'); + } + + // Replace URI only if the ASCII version is different + try { + $uri = $uri->withHost($asciiHost); + } catch (\InvalidArgumentException $e) { + throw new InvalidArgumentException('IDN conversion failed', 0, $e); + } + } + } + + return $uri; + } + + /** + * @return string|false + */ + private static function idnToAsci(string $domain, int $options, ?array &$info = []) + { + if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) { + // ICU can take quadratic time, and no valid name needs more bytes. + if (\strlen($domain) > 4096) { + return false; + } + + try { + return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info); + } catch (\IntlException $e) { + // With intl.use_exceptions, a label too long to encode throws. + return false; + } + } + + throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old'); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/MessageFormatter.php b/vendor/guzzlehttp/guzzle/src/MessageFormatter.php new file mode 100644 index 0000000..e763522 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/MessageFormatter.php @@ -0,0 +1,207 @@ +>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; + public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; + + /** + * @var string Template used to format log messages + */ + private string $template; + + /** + * @param string $template Log message template + */ + public function __construct(?string $template = self::CLF) + { + $this->template = $template ?: self::CLF; + } + + /** + * Returns a formatted message string. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface|null $response Response that was received + * @param \Throwable|null $error Exception that was received + */ + public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string + { + $cache = []; + + $result = \preg_replace_callback( + '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', + function (array $matches) use ($request, $response, $error, &$cache): string { + if (isset($cache[$matches[1]])) { + return $cache[$matches[1]]; + } + + $result = ''; + switch ($matches[1]) { + case 'request': + $result = Psr7\Message::toString($request); + break; + case 'response': + $result = $response ? Psr7\Message::toString($response) : ''; + break; + case 'req_headers': + $result = \trim($request->getMethod() + .' '.$request->getRequestTarget(), " \n\r\t\0\x0B") + .' HTTP/'.$request->getProtocolVersion()."\r\n" + .$this->headers($request); + break; + case 'res_headers': + $result = $response ? + \sprintf( + 'HTTP/%s %d %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + )."\r\n".$this->headers($response) + : 'NULL'; + break; + case 'req_body': + $result = $request->getBody()->__toString(); + break; + case 'res_body': + if (!$response instanceof ResponseInterface) { + $result = 'NULL'; + break; + } + + $body = $response->getBody(); + + if (!$body->isSeekable()) { + $result = 'RESPONSE_NOT_LOGGEABLE'; + break; + } + + $result = $response->getBody()->__toString(); + break; + case 'ts': + case 'date_iso_8601': + $result = \gmdate('c'); + break; + case 'date_common_log': + $result = \date('d/M/Y:H:i:s O'); + break; + case 'method': + $result = $request->getMethod(); + break; + case 'version': + $result = $request->getProtocolVersion(); + break; + case 'uri': + case 'url': + $result = $request->getUri()->__toString(); + break; + case 'target': + $result = $request->getRequestTarget(); + break; + case 'req_version': + $result = $request->getProtocolVersion(); + break; + case 'res_version': + $result = $response + ? $response->getProtocolVersion() + : 'NULL'; + break; + case 'host': + $result = $request->getHeaderLine('Host'); + break; + case 'hostname': + $result = \gethostname(); + break; + case 'code': + $result = $response ? $response->getStatusCode() : 'NULL'; + break; + case 'phrase': + $result = $response ? $response->getReasonPhrase() : 'NULL'; + break; + case 'error': + $result = $error ? $error->getMessage() : 'NULL'; + break; + default: + // handle prefixed dynamic headers + if (\strpos($matches[1], 'req_header_') === 0) { + $result = $request->getHeaderLine(\substr($matches[1], 11)); + } elseif (\strpos($matches[1], 'res_header_') === 0) { + $result = $response + ? $response->getHeaderLine(\substr($matches[1], 11)) + : 'NULL'; + } + } + + $result = (string) $result; + $cache[$matches[1]] = $result; + + return $result; + }, + $this->template + ); + + if ($result === null) { + throw new \RuntimeException('Unable to format message: '.\preg_last_error_msg()); + } + + return $result; + } + + /** + * Get headers from message as string + */ + private function headers(MessageInterface $message): string + { + $result = ''; + foreach ($message->getHeaders() as $name => $values) { + $result .= $name.': '.\implode(', ', $values)."\r\n"; + } + + return \trim($result, " \n\r\t\0\x0B"); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php b/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php new file mode 100644 index 0000000..b72e24c --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php @@ -0,0 +1,20 @@ +): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function auth(bool $reuseChallenges = true): callable + { + return static function (callable $handler) use ($reuseChallenges): AuthMiddleware { + return new AuthMiddleware($handler, null, $reuseChallenges); + }; + } + + /** + * Middleware that adds cookies to requests. + * + * The options array must be set to a CookieJarInterface in order to use + * cookies. This is typically handled for you by a client. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function cookies(): callable + { + return static function (callable $handler): callable { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) use ($handler): PromiseInterface { + if (empty($options['cookies'])) { + return $handler($request, $options); + } elseif (!$options['cookies'] instanceof CookieJarInterface) { + throw new \InvalidArgumentException('cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface'); + } + $cookieJar = $options['cookies']; + $request = $cookieJar->withCookieHeader($request); + + return $handler($request, $options) + ->then( + static function ( + #[\SensitiveParameter] + ResponseInterface $response + ) use ($cookieJar, $request): ResponseInterface { + $cookieJar->extractCookies($request, $response); + + return $response; + } + ); + }; + }; + } + + /** + * Middleware that throws exceptions for 4xx or 5xx responses when the + * "http_errors" request option is set to true. + * + * @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function httpErrors(?BodySummarizerInterface $bodySummarizer = null): callable + { + return static function (callable $handler) use ($bodySummarizer): callable { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) use ($handler, $bodySummarizer): PromiseInterface { + if (empty($options['http_errors'])) { + return $handler($request, $options); + } + + return $handler($request, $options)->then( + static function ( + #[\SensitiveParameter] + ResponseInterface $response + ) use ($request, $bodySummarizer): ResponseInterface { + $code = $response->getStatusCode(); + if ($code < 400) { + return $response; + } + throw RequestException::create($request, $response, null, $bodySummarizer); + } + ); + }; + }; + } + + /** + * Middleware that pushes history data to an ArrayAccess container. + * + * @param array}>|\ArrayAccess}> $container Container to hold the history (by reference). + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + * + * @throws \InvalidArgumentException if container is not an array or ArrayAccess. + */ + public static function history(&$container): callable + { + if (!\is_array($container) && !$container instanceof \ArrayAccess) { + throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); + } + + return static function (callable $handler) use (&$container): callable { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) use ($handler, &$container): PromiseInterface { + return $handler($request, $options)->then( + static function ( + #[\SensitiveParameter] + ResponseInterface $value + ) use ($request, &$container, $options): ResponseInterface { + $container[] = [ + 'request' => $request, + 'response' => $value, + 'error' => null, + 'options' => $options, + ]; + + return $value; + }, + static function ( + #[\SensitiveParameter] + $reason + ) use ($request, &$container, $options): PromiseInterface { + $container[] = [ + 'request' => $request, + 'response' => null, + 'error' => $reason, + 'options' => $options, + ]; + + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * Middleware that observes requests and responses as they flow through the + * stack without modifying them. This is useful for metrics, tracing, and + * debugging. + * + * The provided listener cannot modify or alter the response. It simply + * "taps" into the chain to be notified before returning the promise. The + * before listener accepts a request and options array, and the after + * listener accepts a request, options array, and response promise. + * + * @param (callable(RequestInterface, array): mixed)|null $before Function to invoke before forwarding the request. + * @param (callable(RequestInterface, array, PromiseInterface): mixed)|null $after Function invoked after forwarding. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function tap(?callable $before = null, ?callable $after = null): callable + { + return static function (callable $handler) use ($before, $after): callable { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) use ($handler, $before, $after): PromiseInterface { + if ($before) { + $before($request, $options); + } + $response = $handler($request, $options); + if ($after) { + $after($request, $options, $response); + } + + return $response; + }; + }; + } + + /** + * Middleware that handles request redirects. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function redirect(): callable + { + return static function (callable $handler): RedirectMiddleware { + return new RedirectMiddleware($handler); + }; + } + + /** + * Middleware that retries requests based on the boolean result of + * invoking the provided "decider" function. + * + * If no delay function is provided, a simple implementation of exponential + * backoff will be utilized. + * + * @param callable(int, RequestInterface, ResponseInterface|null, mixed): bool $decider Function that accepts the number of retries, + * a request, [response], and [rejection reason] + * and returns true if the request is to be retried. + * @param (callable(int, ResponseInterface|null, RequestInterface): int)|null $delay Function that accepts the number of retries, + * [response], and request, and returns the + * number of milliseconds to delay. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function retry(callable $decider, ?callable $delay = null): callable + { + return static function (callable $handler) use ($decider, $delay): RetryMiddleware { + return new RetryMiddleware($decider, $handler, $delay); + }; + } + + /** + * Middleware that logs requests, responses, and errors using a message + * formatter. + * + * @param LoggerInterface $logger Logs messages. + * @param MessageFormatterInterface $formatter Formatter used to create message strings. + * @param string $logLevel Level at which to log requests. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function log(LoggerInterface $logger, MessageFormatterInterface $formatter, string $logLevel = 'info'): callable + { + return static function (callable $handler) use ($logger, $formatter, $logLevel): callable { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options = [] + ) use ($handler, $logger, $formatter, $logLevel): PromiseInterface { + return $handler($request, $options)->then( + static function ( + #[\SensitiveParameter] + ResponseInterface $response + ) use ($logger, $request, $formatter, $logLevel): ResponseInterface { + $message = $formatter->format($request, $response); + $logger->log($logLevel, $message); + + return $response; + }, + /** + * @return PromiseInterface + */ + static function ( + #[\SensitiveParameter] + $reason + ) use ($logger, $request, $formatter): PromiseInterface { + $response = $reason instanceof ResponseException ? $reason->getResponse() : null; + $message = $formatter->format($request, $response, P\Create::exceptionFor($reason)); + $logger->error($message); + + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * This middleware adds a default content-type if possible, a default + * content-length or transfer-encoding header, and the expect header. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function prepareBody(): callable + { + return static function (callable $handler): PrepareBodyMiddleware { + return new PrepareBodyMiddleware($handler); + }; + } + + /** + * Middleware that applies a map function to the request before passing to + * the next handler. + * + * @param callable(RequestInterface): RequestInterface $fn Function that accepts a RequestInterface and returns + * a RequestInterface. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function mapRequest(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) use ($handler, $fn): PromiseInterface { + return $handler($fn($request), $options); + }; + }; + } + + /** + * Middleware that applies a map function to the resolved promise's + * response. + * + * @param callable(ResponseInterface): ResponseInterface $fn Function that accepts a ResponseInterface and + * returns a ResponseInterface. + * + * @return callable((callable(RequestInterface, array): PromiseInterface)): (callable(RequestInterface, array): PromiseInterface) + */ + public static function mapResponse(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ) use ($handler, $fn): PromiseInterface { + return $handler($request, $options)->then($fn); + }; + }; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Multiplexing.php b/vendor/guzzlehttp/guzzle/src/Multiplexing.php new file mode 100644 index 0000000..90501ba --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Multiplexing.php @@ -0,0 +1,28 @@ + + */ +class Pool implements PromisorInterface +{ + use NonSerializableTrait; + + /** + * @var EachPromise + */ + private EachPromise $each; + + /** + * @param ClientInterface $client Client used to send the requests. + * @param iterable): (ResponseInterface|PromiseInterface)> $requests Requests or functions that return responses or response promises. + * @param array{ + * concurrency?: int|(callable(int): int), + * options?: array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface, int|string): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface, int|string): mixed, + * on_stats?: callable(TransferStats, int|string): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface, int|string): mixed, + * progress?: callable(int, int, int, int, int|string): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * }, + * fulfilled?: callable(ResponseInterface, int|string, PromiseInterface): mixed, + * rejected?: callable(mixed, int|string, PromiseInterface): mixed + * } $config Pool configuration. + */ + public function __construct( + ClientInterface $client, + iterable $requests, + #[\SensitiveParameter] + array $config = [] + ) { + if (!isset($config['concurrency'])) { + $config['concurrency'] = 25; + } + + if (isset($config['options'])) { + $opts = $config['options']; + unset($config['options']); + } else { + $opts = []; + } + + $requestGenerator = static function () use ($requests, $client, $opts): \Generator { + foreach ($requests as $key => $rfn) { + $keyedOpts = self::keyedRequestOptions($opts, $key); + + if ($rfn instanceof RequestInterface) { + yield $key => $client->sendAsync($rfn, $keyedOpts); + } elseif (\is_callable($rfn)) { + yield $key => $rfn($keyedOpts); + } else { + throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr\Http\Message\ResponseInterface object.'); + } + } + }; + + $this->each = new EachPromise($requestGenerator(), $config); + } + + /** + * Get promise + * + * @return PromiseInterface + */ + public function promise(): PromiseInterface + { + return $this->each->promise(); + } + + /** + * Sends multiple requests concurrently and returns an array of responses + * and exceptions that uses the same ordering as the provided requests. + * + * IMPORTANT: This method keeps every request and response in memory, and + * as such, is NOT recommended when sending a large number or an + * indeterminate number of requests concurrently. + * + * @param ClientInterface $client Client used to send the requests + * @param iterable): (ResponseInterface|PromiseInterface)> $requests Requests or functions that return responses or response promises. + * @param array{ + * concurrency?: int|(callable(int): int), + * options?: array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface, int|string): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface, int|string): mixed, + * on_stats?: callable(TransferStats, int|string): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface, int|string): mixed, + * progress?: callable(int, int, int, int, int|string): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * }, + * fulfilled?: callable(ResponseInterface, int|string): mixed, + * rejected?: callable(mixed, int|string): mixed + * } $options Passes through the options available in {@see Pool::__construct}. + * + * @return array Returns an array containing the response or rejection reason in the same order that the requests were sent. + * + * @throws \InvalidArgumentException if the event format is incorrect. + */ + public static function batch( + ClientInterface $client, + iterable $requests, + #[\SensitiveParameter] + array $options = [] + ): array { + $res = []; + self::cmpCallback($options, 'fulfilled', $res); + self::cmpCallback($options, 'rejected', $res); + $pool = new static($client, $requests, $options); + $pool->promise()->wait(); + \ksort($res); + + return $res; + } + + /** + * Execute callback(s) + */ + private static function cmpCallback(array &$options, string $name, array &$results): void + { + if (!isset($options[$name])) { + $options[$name] = static function ( + #[\SensitiveParameter] + $v, + $k + ) use (&$results): void { + $results[$k] = $v; + }; + } else { + $currentFn = $options[$name]; + $options[$name] = static function ( + #[\SensitiveParameter] + $v, + $k + ) use (&$results, $currentFn): void { + $currentFn($v, $k); + $results[$k] = $v; + }; + } + } + + /** + * Returns the request options with any observer callbacks wrapped so that + * they also receive the request's iterable key as a trailing argument. + * + * @param array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface, int|string): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface, int|string): mixed, + * on_stats?: callable(TransferStats, int|string): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface, int|string): mixed, + * progress?: callable(int, int, int, int, int|string): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } $options + * @param int|string $key + * + * @return array{ + * base_uri?: string|UriInterface, + * allow_redirects?: bool|array{ + * max?: int, + * strict?: bool, + * referer?: bool, + * protocols?: non-empty-array, + * on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed, + * track_redirects?: bool + * }, + * auth?: array{ + * 0: string, + * 1: string, + * 2?: string|null + * }|string|false|null, + * body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable, + * cert?: string|array{ + * 0: string, + * 1?: string|null + * }, + * cert_type?: string, + * connect_timeout?: int|float, + * cookies?: false|CookieJarInterface, + * crypto_method?: int, + * crypto_method_max?: int, + * debug?: bool|resource, + * decode_content?: bool|string, + * delay?: int|float, + * expect?: bool|int, + * form_params?: array, + * force_ip_resolve?: string, + * headers?: array>|null, + * http_errors?: bool, + * idn_conversion?: bool|int|null, + * json?: mixed, + * multipart?: array, + * filename?: string + * }>, + * multiplex?: string, + * on_headers?: callable(ResponseInterface, RequestInterface): mixed, + * on_stats?: callable(TransferStats): mixed, + * on_trailers?: callable(array>, ResponseInterface, RequestInterface): mixed, + * progress?: callable(int, int, int, int): mixed, + * protocols?: non-empty-array, + * proxy?: string|array{ + * http?: string|null, + * https?: string|null, + * no?: string|array|null + * }, + * query?: array|string, + * read_timeout?: int|float, + * retries?: int, + * request_factory?: RequestFactoryInterface, + * response_factory?: ResponseFactoryInterface, + * sink?: resource|string|StreamInterface, + * ssl_key?: string|array{ + * 0: string, + * 1?: string|null + * }, + * ssl_key_type?: string, + * stream?: bool, + * stream_factory?: StreamFactoryInterface, + * stream_context?: array, + * synchronous?: bool, + * timeout?: int|float, + * uri_factory?: UriFactoryInterface, + * verify?: bool|string, + * version?: string|int|float, + * curl?: array, + * ... + * } + */ + private static function keyedRequestOptions(array $options, $key): array + { + if (\is_array($options['allow_redirects'] ?? null) + && \is_callable($options['allow_redirects']['on_redirect'] ?? null) + ) { + $onRedirect = $options['allow_redirects']['on_redirect']; + $options['allow_redirects']['on_redirect'] = static function ( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + ResponseInterface $response, + #[\SensitiveParameter] + UriInterface $uri + ) use ($onRedirect, $key): void { + $onRedirect($request, $response, $uri, $key); + }; + } + + if (\is_callable($options['on_headers'] ?? null)) { + $onHeaders = $options['on_headers']; + $options['on_headers'] = static function ( + #[\SensitiveParameter] + ResponseInterface $response, + #[\SensitiveParameter] + RequestInterface $request + ) use ($onHeaders, $key): void { + $onHeaders($response, $request, $key); + }; + } + + if (\is_callable($options['on_stats'] ?? null)) { + $onStats = $options['on_stats']; + $options['on_stats'] = static function (TransferStats $stats) use ($onStats, $key): void { + $onStats($stats, $key); + }; + } + + if (\is_callable($options['on_trailers'] ?? null)) { + $onTrailers = $options['on_trailers']; + $options['on_trailers'] = static function ( + array $trailers, + #[\SensitiveParameter] + ResponseInterface $response, + #[\SensitiveParameter] + RequestInterface $request + ) use ($onTrailers, $key): void { + $onTrailers($trailers, $response, $request, $key); + }; + } + + if (\is_callable($options['progress'] ?? null)) { + $progress = $options['progress']; + $options['progress'] = static function (int $downloadTotal, int $downloadedBytes, int $uploadTotal, int $uploadedBytes) use ($progress, $key) { + return $progress($downloadTotal, $downloadedBytes, $uploadTotal, $uploadedBytes, $key); + }; + } + + return $options; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php b/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php new file mode 100644 index 0000000..d13e722 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php @@ -0,0 +1,123 @@ +): PromiseInterface + */ + private $nextHandler; + + /** + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. + */ + public function __construct(callable $nextHandler) + { + $this->nextHandler = $nextHandler; + } + + /** + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + $fn = $this->nextHandler; + $bodySize = RequestFraming::bodySize($request); + + // Don't do anything if the request has no body. + if ($bodySize === 0) { + return $fn($request, $options); + } + + $modify = []; + + // Add a default content-type if possible. + if (!$request->hasHeader('Content-Type')) { + if ($uri = $request->getBody()->getMetadata('uri')) { + if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) { + $modify['set_headers']['Content-Type'] = $type; + } + } + } + + // Add a default content-length or transfer-encoding header. + if (!$request->hasHeader('Content-Length') + && !$request->hasHeader('Transfer-Encoding') + ) { + if ($bodySize !== null) { + $modify['set_headers']['Content-Length'] = (string) $bodySize; + } elseif ($request->getProtocolVersion() === '1.1') { + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; + } + } + + // Add the expect header if needed. + $this->addExpectHeader($request, $options, $modify, $bodySize); + + return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); + } + + /** + * Add expect header + */ + private function addExpectHeader( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + array &$modify, + ?int $bodySize + ): void { + // Determine if the Expect header should be used + if ($request->hasHeader('Expect')) { + return; + } + + $expect = $options['expect'] ?? null; + + // Return if disabled or not using HTTP/1.1. + if ($expect === false || '1.1' !== $request->getProtocolVersion()) { + return; + } + + // The expect header is unconditionally enabled + if ($expect === true) { + $modify['set_headers']['Expect'] = '100-Continue'; + + return; + } + + // By default, send the expect header when the payload is > 1mb + if ($expect === null) { + $expect = 1048576; + } + + // Always add if the body cannot be rewound, the size cannot be + // determined, or the size is greater than the cutoff threshold + $body = $request->getBody(); + + if ($bodySize === null || $bodySize >= (int) $expect || !$body->isSeekable()) { + $modify['set_headers']['Expect'] = '100-Continue'; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/ProxyOptions.php b/vendor/guzzlehttp/guzzle/src/ProxyOptions.php new file mode 100644 index 0000000..53b8b9b --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/ProxyOptions.php @@ -0,0 +1,624 @@ +getScheme()] ?? null; + if ($schemeProxy !== null && !\is_string($schemeProxy)) { + throw new InvalidArgumentException('proxy values must be strings'); + } + + // A matching "no" entry is always a final decision, even when the + // array selects no proxy for the request scheme. Without this, an + // option-level bypass could fall through to handler-level environment + // fallback and route through a proxy the user excluded. + $noProxy = isset($proxy['no']) ? self::normalizeNoProxy($proxy['no']) : []; + if ($noProxy !== [] && self::isUriInNoProxy($uri, $noProxy)) { + return ProxySelection::bypassed(); + } + + if ($schemeProxy === null) { + return ProxySelection::none(); + } + + return ProxySelection::proxy($schemeProxy); + } + + /** + * Validate a proxy URL and return its lowercased scheme. + * + * A proxy is an authority ([userinfo@]host[:port]) with an optional scheme; + * a scheme-less value is an HTTP proxy. The scheme is matched anchored at + * the start, so leading junk before it is rejected as malformed, and the + * host and port grammar is delegated to Psr7\Rfc3986. The whole string is + * validated up front so a malformed proxy fails the same way on every + * handler, but the original value is what callers pin, so no normalization + * reaches the wire. The error message never includes the proxy, which may + * carry credentials. + * + * @throws InvalidArgumentException on a malformed proxy URL + */ + public static function proxyScheme( + #[\SensitiveParameter] + string $proxy + ): string { + $parts = \explode('://', $proxy, 2); + if (\count($parts) === 1) { + $scheme = 'http'; + $authority = $proxy; + } else { + [$scheme, $authority] = $parts; + $scheme = Psr7\Utils::asciiToLower($scheme); + if ($scheme === '' || !Rfc3986::isValidScheme($scheme)) { + throw new InvalidArgumentException('Invalid proxy URL.'); + } + } + + if (!self::isValidProxyAuthority($authority)) { + throw new InvalidArgumentException('Invalid proxy URL.'); + } + + return $scheme; + } + + /** + * Whether the string is a valid proxy authority: [userinfo@]host[:port]. + * + * A single trailing slash is tolerated; anything else after the authority + * (a path, query, or fragment) is rejected. Userinfo is not policed here + * (the proxy handles its own credentials); host and port grammar are + * delegated to Psr7\Rfc3986, where a zero port is accepted and left for the + * transport to handle as it did before. + */ + private static function isValidProxyAuthority(string $authority): bool + { + // A single trailing slash is tolerated; once removed, a proxy authority + // ([userinfo@]host[:port]) cannot contain a path, query, or fragment + // delimiter anywhere — including one before a later '@'. + if (\str_ends_with($authority, '/')) { + $authority = \substr($authority, 0, \strlen($authority) - 1); + } + + if ($authority === '' || \strpbrk($authority, '/?#') !== false) { + return false; + } + + // The host cannot contain '@', so userinfo is everything before the + // last one. It is not validated here. A value that is only userinfo, + // with nothing after the last '@', has no host and is rejected. + $segments = \explode('@', $authority); + $authority = $segments[\count($segments) - 1]; + if ($authority === '') { + return false; + } + + $port = null; + if (\str_starts_with($authority, '[')) { + $parts = \explode(']', $authority, 2); + if (\count($parts) !== 2) { + return false; + } + + $host = $parts[0].']'; + $remainder = $parts[1]; + if ($remainder !== '') { + if (!\str_starts_with($remainder, ':')) { + return false; + } + + [, $port] = \explode(':', $remainder, 2); + } + } elseif (\strpos($authority, ':') !== false) { + [$host, $port] = \explode(':', $authority, 2); + } else { + $host = $authority; + } + + // A dangling "host:" carries no port, matching the previous behavior. + if ($port === '') { + $port = null; + } + + if ($host === '' || !Rfc3986::isValidHost($host)) { + return false; + } + + return $port === null || Rfc3986::isValidPort($port); + } + + /** + * Normalize a no-proxy list from request options or NO_PROXY. + * + * @param mixed $noProxy No-proxy value as passed via request transfer options. + * + * @return string[] + * + * @throws InvalidArgumentException + */ + public static function normalizeNoProxy($noProxy): array + { + if ($noProxy === null) { + return []; + } + + if (\is_string($noProxy)) { + // Entries may be separated by whitespace as well as commas, + // matching the no_proxy environment variable conventions. + $noProxy = \preg_split('/[\s,]+/', $noProxy); + + if ($noProxy === false) { + throw new \RuntimeException('Unable to split the proxy no list: '.\preg_last_error_msg()); + } + } elseif (!\is_array($noProxy)) { + throw new InvalidArgumentException('proxy no list must be null, a string, or an array of strings'); + } + + $result = []; + foreach ($noProxy as $area) { + if (!\is_string($area)) { + throw new InvalidArgumentException('proxy no list must be null, a string, or an array of strings'); + } + + $area = \trim($area, " \n\r\t\0\x0B"); + if ($area !== '') { + $result[] = $area; + } + } + + return $result; + } + + /** + * Returns true if the provided URI matches any of the no-proxy areas. + * + * @param string[] $noProxy An array of host, host-and-port, or CIDR patterns. + * + * @throws InvalidArgumentException + */ + public static function isUriInNoProxy(UriInterface $uri, array $noProxy): bool + { + self::assertNoProxyList($noProxy); + + $target = self::parseNoProxyTarget($uri); + if ($target === null) { + return false; + } + + foreach ($noProxy as $area) { + $area = \trim($area, " \n\r\t\0\x0B"); + + if ($area === '*') { + return true; + } + + $rule = self::parseNoProxyRule($area); + if ($rule !== null && self::noProxyRuleMatches($target, $rule)) { + return true; + } + } + + return false; + } + + /** + * Returns true if the provided host matches any of the no-proxy areas. + * + * This method will strip a port from the host if it is present. Domain + * patterns are matched case-insensitively. Exact IP literal patterns are + * matched by their normalized binary address, and a host or pattern + * written in the inet_aton() shorthand a transport reads as an address, + * such as 127.1 or 0x7f000001, is matched as that address. + * + * Areas are matched in the following cases: + * 1. "*" (without quotes) always matches any hosts. + * 2. An exact domain or IP literal match. + * 3. A bare domain or a leading-dot domain matches itself and its + * subdomains. e.g. 'mit.edu' and '.mit.edu' both match 'mit.edu' + * and 'foo.mit.edu'. + * 4. IP CIDR entries match IP literal hosts. e.g. '192.168.0.0/16' will + * match '192.168.1.10' and 'fd00::/8' will match '[fd00::1]'. + * + * @param string $host Host to check against the patterns. + * @param string[] $noProxy An array of host or CIDR patterns. + * + * @throws InvalidArgumentException + */ + public static function isHostInNoProxy(string $host, array $noProxy): bool + { + if ($host === '') { + throw new InvalidArgumentException('Empty host provided'); + } + + self::assertNoProxyList($noProxy); + + $target = self::parseNoProxyHostString($host); + if ($target === null) { + return false; + } + + foreach ($noProxy as $area) { + $area = \trim($area, " \n\r\t\0\x0B"); + + if ($area === '*') { + return true; + } + + $rule = self::parseNoProxyRule($area); + if ($rule !== null && self::noProxyRuleMatches($target, $rule)) { + return true; + } + } + + return false; + } + + /** + * @param array $noProxy + * + * @throws InvalidArgumentException + */ + private static function assertNoProxyList(array $noProxy): void + { + foreach ($noProxy as $area) { + if (!\is_string($area)) { + throw new InvalidArgumentException('proxy no list must be null, a string, or an array of strings'); + } + } + } + + /** + * @return array{type: string, value: string, port: int|null}|null + */ + private static function parseNoProxyTarget(UriInterface $uri): ?array + { + $host = $uri->getHost(); + if ($host === '') { + return null; + } + + return self::parseNoProxyHost($host, $uri->getPort() ?? self::getDefaultPort($uri->getScheme())); + } + + /** + * @return array{type: string, value: string, port: int|null}|null + */ + private static function parseNoProxyHostString(string $host): ?array + { + $hostAndPort = self::splitNoProxyHostAndPort($host); + if ($hostAndPort === null) { + return null; + } + + [$host] = $hostAndPort; + + return self::parseNoProxyHost($host, null); + } + + /** + * @return array{type: string, value: string, port: int|null}|array{type: string, value: string, prefix: int}|null + */ + private static function parseNoProxyRule(string $area): ?array + { + $area = \trim($area, " \n\r\t\0\x0B"); + if ($area === '' || $area === '*') { + return null; + } + + // A single leading dot is ignored: ".example.com" matches + // example.com and its subdomains exactly like a bare domain, + // consistent with every libcurl era. The strip runs before the + // CIDR check so ".10.0.0.0/8" is a live rule on every path. + if ($area[0] === '.') { + $area = \substr($area, 1); + if ($area === '') { + return null; + } + } + + if (\strpos($area, '/') !== false) { + return self::parseNoProxyCidrRule($area); + } + + $hostAndPort = self::splitNoProxyHostAndPort($area); + if ($hostAndPort === null) { + return null; + } + + [$host, $port] = $hostAndPort; + + if ($host === '*') { + return [ + 'type' => 'wildcard', + 'value' => '*', + 'port' => $port, + ]; + } + + return self::parseNoProxyHost($host, $port); + } + + /** + * @return array{type: string, value: string, port: int|null}|null + */ + private static function parseNoProxyHost(string $host, ?int $port): ?array + { + if ($host !== '' && $host[0] === '[') { + if (\substr($host, -1) !== ']') { + return null; + } + + $address = \substr($host, 1, -1); + if (!\filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) { + return null; + } + + $host = $address; + } + + $packedIp = self::packHostAddress($host); + if ($packedIp !== false) { + return [ + 'type' => 'ip', + 'value' => $packedIp, + 'port' => $port, + ]; + } + + if ($host === '' || \strpos($host, ':') !== false) { + return null; + } + + // Normalize a single DNS root dot for no-proxy domain matching. + if (\substr($host, -1) === '.') { + $host = \substr($host, 0, -1); + if ($host === '') { + return null; + } + } + + return [ + 'type' => 'domain', + 'value' => Psr7\Utils::asciiToLower($host), + 'port' => $port, + ]; + } + + /** + * @return array{0: string, 1: int|null}|null + */ + private static function splitNoProxyHostAndPort(string $area): ?array + { + if ($area !== '' && $area[0] === '[') { + $closingBracket = \strpos($area, ']'); + if ($closingBracket === false) { + return null; + } + + $host = \substr($area, 0, $closingBracket + 1); + $tail = \substr($area, $closingBracket + 1); + if ($tail === '') { + return [$host, null]; + } + + if ($tail[0] !== ':') { + return null; + } + + $port = self::parseNoProxyPort(\substr($tail, 1)); + + return $port === null ? null : [$host, $port]; + } + + if (self::packHostAddress($area) !== false) { + return [$area, null]; + } + + $colon = \strrpos($area, ':'); + if ($colon === false) { + return [$area, null]; + } + + $port = self::parseNoProxyPort(\substr($area, $colon + 1)); + if ($port === null) { + return null; + } + + return [\substr($area, 0, $colon), $port]; + } + + private static function parseNoProxyPort(string $port): ?int + { + return self::parseBoundedUnsignedInteger($port, 65535); + } + + private static function getDefaultPort(string $scheme): ?int + { + if ($scheme === 'http') { + return 80; + } + + if ($scheme === 'https') { + return 443; + } + + return null; + } + + /** + * @return array{type: string, value: string, prefix: int}|null + */ + private static function parseNoProxyCidrRule(string $area): ?array + { + $slash = \strpos($area, '/'); + if ($slash === false) { + return null; + } + + $prefix = \substr($area, $slash + 1); + + $network = \substr($area, 0, $slash); + if ($network !== '' && $network[0] === '[' && \substr($network, -1) === ']') { + $network = \substr($network, 1, -1); + } + + // A bare rule denotes a host identity, but a CIDR rule uses network + // configuration syntax, so the inet_aton() shorthand is not read as + // a network: 127/8 would name 0.0.0.127/8 rather than 127.0.0.0/8. + $network = self::packIpAddress($network); + if ($network === false) { + return null; + } + + $prefix = self::parseBoundedUnsignedInteger($prefix, \strlen($network) * 8); + if ($prefix === null) { + return null; + } + + return [ + 'type' => 'cidr', + 'value' => $network, + 'prefix' => $prefix, + ]; + } + + private static function parseBoundedUnsignedInteger(string $value, int $max): ?int + { + if ($value === '' || !\ctype_digit($value)) { + return null; + } + + $normalized = \ltrim($value, '0'); + $normalized = $normalized === '' ? '0' : $normalized; + $limit = (string) $max; + + if (\strlen($normalized) > \strlen($limit) || (\strlen($normalized) === \strlen($limit) && \strcmp($normalized, $limit) > 0)) { + return null; + } + + return (int) $normalized; + } + + /** + * @param array{type: string, value: string, port: int|null} $target + * @param array{type: string, value: string, port?: int|null, prefix?: int|null} $rule + */ + private static function noProxyRuleMatches(array $target, array $rule): bool + { + if ($rule['type'] === 'wildcard') { + return ($rule['port'] ?? null) === null || $rule['port'] === $target['port']; + } + + if ($rule['type'] === 'cidr') { + if ($target['type'] !== 'ip' || !isset($rule['prefix'])) { + return false; + } + + if (\strlen($target['value']) !== \strlen($rule['value'])) { + return false; + } + + return self::ipMatchesPrefix($target['value'], $rule['value'], $rule['prefix']); + } + + if (($rule['port'] ?? null) !== null && $rule['port'] !== $target['port']) { + return false; + } + + if ($rule['type'] !== $target['type']) { + return false; + } + + if ($rule['type'] === 'ip') { + return $rule['value'] === $target['value']; + } + + if ($target['value'] === $rule['value']) { + return true; + } + + $suffix = '.'.$rule['value']; + + return \substr($target['value'], -\strlen($suffix)) === $suffix; + } + + /** + * @return string|false + */ + private static function packIpAddress(string $ip) + { + if (\filter_var($ip, \FILTER_VALIDATE_IP)) { + return \inet_pton($ip); + } + + return false; + } + + /** + * @return string|false + */ + private static function packHostAddress(string $host) + { + $packed = self::packIpAddress($host); + if ($packed !== false) { + return $packed; + } + + // A transport reads the inet_aton() shorthand as an address too, so a + // rule and a request host that name one address have to match + // whichever spelling each of them happens to use. + return HostIdentity::numericIpv4ToBinary($host) ?? false; + } + + private static function ipMatchesPrefix(string $address, string $network, int $prefix): bool + { + $fullBytes = \intdiv($prefix, 8); + $remainingBits = $prefix % 8; + + if ($fullBytes > 0 && \substr($address, 0, $fullBytes) !== \substr($network, 0, $fullBytes)) { + return false; + } + + if ($remainingBits === 0) { + return true; + } + + $mask = (0xFF << (8 - $remainingBits)) & 0xFF; + + return (\ord($address[$fullBytes]) & $mask) === (\ord($network[$fullBytes]) & $mask); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/ProxySelection.php b/vendor/guzzlehttp/guzzle/src/ProxySelection.php new file mode 100644 index 0000000..4c40f3e --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/ProxySelection.php @@ -0,0 +1,66 @@ +proxy = $proxy; + $this->bypassed = $bypassed; + $this->disabled = $disabled; + } + + public static function none(): self + { + return new self(null, false, false); + } + + public static function proxy(string $proxy): self + { + return $proxy === '' ? self::disabled() : new self($proxy, false, false); + } + + public static function bypassed(): self + { + return new self(null, true, false); + } + + public static function disabled(): self + { + return new self(null, false, true); + } + + public function getProxy(): ?string + { + return $this->proxy; + } + + public function hasProxy(): bool + { + return $this->proxy !== null; + } + + public function isBypassed(): bool + { + return $this->bypassed; + } + + public function isDisabled(): bool + { + return $this->disabled; + } + + public function shouldDisableProxy(): bool + { + return $this->bypassed || $this->disabled; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php b/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php new file mode 100644 index 0000000..794496e --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php @@ -0,0 +1,368 @@ + 5, + 'protocols' => ['http', 'https'], + 'strict' => false, + 'referer' => false, + 'track_redirects' => false, + ]; + + /** + * @var callable(RequestInterface, array): PromiseInterface + */ + private $nextHandler; + + /** + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. + */ + public function __construct(callable $nextHandler) + { + $this->nextHandler = $nextHandler; + } + + /** + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + $fn = $this->nextHandler; + + if (empty($options['allow_redirects'])) { + return $fn($request, $options); + } + + if ($options['allow_redirects'] === true) { + $options['allow_redirects'] = self::DEFAULT_SETTINGS; + } elseif (!\is_array($options['allow_redirects'])) { + throw new InvalidArgumentException('allow_redirects must be true, false, or array'); + } else { + // Merge the default settings with the provided settings + $options['allow_redirects'] += self::DEFAULT_SETTINGS; + } + + if (empty($options['allow_redirects']['max'])) { + return $fn($request, $options); + } + + return $fn($request, $options) + ->then(function ( + #[\SensitiveParameter] + ResponseInterface $response + ) use ($request, $options) { + return $this->checkRedirect($request, $options, $response); + }); + } + + /** + * @return ResponseInterface|PromiseInterface + */ + public function checkRedirect( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + ResponseInterface $response + ) { + if (!self::isRedirectStatusCode($response->getStatusCode()) + || !$response->hasHeader('Location') + ) { + return $response; + } + + $this->guardMax($request, $response, $options); + $nextRequest = $this->modifyRequest($request, $options, $response); + + // Remove HTTP origin credentials if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri())) { + unset($options['auth'], $options['__guzzle_digest_retries']); + + if (defined('\CURLOPT_HTTPAUTH') && defined('\CURLOPT_USERPWD')) { + unset( + $options['curl'][\CURLOPT_HTTPAUTH], + $options['curl'][\CURLOPT_USERPWD] + ); + } + } + + if (isset($options['allow_redirects']['on_redirect'])) { + ($options['allow_redirects']['on_redirect'])( + $request, + $response, + $nextRequest->getUri() + ); + } + + // The caller's delay applies once, before the initial request, not + // before each followed redirect. + unset($options['delay']); + + $promise = $this($nextRequest, $options); + + // Add headers to be able to track history of redirects. + if (!empty($options['allow_redirects']['track_redirects'])) { + return $this->withTracking( + $promise, + (string) $nextRequest->getUri(), + $response->getStatusCode() + ); + } + + return $promise; + } + + /** + * Enable tracking on promise. + * + * @param PromiseInterface $promise + * + * @return PromiseInterface + */ + private function withTracking( + PromiseInterface $promise, + #[\SensitiveParameter] + string $uri, + int $statusCode + ): PromiseInterface { + return $promise->then( + static function ( + #[\SensitiveParameter] + ResponseInterface $response + ) use ($uri, $statusCode): ResponseInterface { + // Note that we are pushing to the front of the list as this + // would be an earlier response than what is currently present + // in the history header. + $historyHeader = $response->getHeader(self::HISTORY_HEADER); + $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); + \array_unshift($historyHeader, $uri); + \array_unshift($statusHeader, (string) $statusCode); + + return $response->withHeader(self::HISTORY_HEADER, $historyHeader) + ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); + } + ); + } + + /** + * Check for too many redirects. + * + * @throws TooManyRedirectsException Too many redirects. + */ + private function guardMax( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + ResponseInterface $response, + #[\SensitiveParameter] + array &$options + ): void { + $current = $options['__redirect_count'] + ?? 0; + $options['__redirect_count'] = $current + 1; + $max = $options['allow_redirects']['max']; + + if ($options['__redirect_count'] > $max) { + throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response); + } + } + + public function modifyRequest( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + ResponseInterface $response + ): RequestInterface { + $modify = self::getRedirectRequestModifiers($request, $options, $response); + $protocols = $options['allow_redirects']['protocols']; + + $uriFactory = $options[RequestOptions::URI_FACTORY] ?? new HttpFactory(); + if (!$uriFactory instanceof UriFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::URI_FACTORY, + UriFactoryInterface::class + )); + } + + // A server must not be able to raise the psr7 host deprecation. + $scope = new Psr7\ErrorScope(\E_USER_DEPRECATED); + + $modify['uri'] = $scope->run(static function () use ($uriFactory, $request, $response, $protocols, $options): UriInterface { + $uri = self::redirectUri($uriFactory, $request, $response, $protocols); + $idnOptions = Idn::normalizeConversionOption($options['idn_conversion'] ?? null); + + return $idnOptions === null ? $uri : Idn::convertUri($uri, $idnOptions); + }); + + // The body only needs to be rewound when the next request reuses it. + if (!isset($modify['body'])) { + try { + Psr7\Message::rewindBody($request); + } catch (\Exception $e) { + throw new ResponseException( + 'Redirect failed because the request body could not be rewound', + $request, + $response, + $e + ); + } + } + + $crossOrigin = Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri']); + + // Add a Referer only when the scheme is unchanged, and reduce it to the + // origin on cross-origin redirects so a secret-bearing path or query is + // not leaked (strict-origin-when-cross-origin, like modern browsers). + if ($options['allow_redirects']['referer'] + && $modify['uri']->getScheme() === $request->getUri()->getScheme() + ) { + $referer = $request->getUri()->withUserInfo('')->withFragment(''); + if ($crossOrigin) { + $referer = $referer->withPath('/')->withQuery(''); + } + $modify['set_headers']['Referer'] = (string) $referer; + } else { + $modify['remove_headers'][] = 'Referer'; + } + + // Remove Authorization and Cookie headers if URI is cross-origin. + if ($crossOrigin) { + $modify['remove_headers'][] = 'Authorization'; + $modify['remove_headers'][] = 'Cookie'; + } + + return $scope->run(static function () use ($request, $modify): RequestInterface { + return Psr7\Utils::modifyRequest($request, $modify); + }); + } + + private static function isRedirectStatusCode(int $statusCode): bool + { + return \in_array($statusCode, [301, 302, 303, 307, 308], true); + } + + /** + * @return array{ + * method?: string, + * body?: StreamInterface, + * remove_headers?: list + * } + */ + private static function getRedirectRequestModifiers( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + ResponseInterface $response + ): array { + $statusCode = $response->getStatusCode(); + if ($statusCode !== 303 + && ($statusCode > 302 || $options['allow_redirects']['strict']) + ) { + return []; + } + + $requestMethod = $request->getMethod(); + + if ($requestMethod === 'QUERY' && \in_array($statusCode, [301, 302], true)) { + return []; + } + + $streamFactory = $options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory(); + if (!$streamFactory instanceof StreamFactoryInterface) { + throw new InvalidArgumentException(\sprintf( + '%s must be an instance of %s', + RequestOptions::STREAM_FACTORY, + StreamFactoryInterface::class + )); + } + + return [ + 'method' => \in_array($requestMethod, ['GET', 'HEAD', 'OPTIONS'], true) ? $requestMethod : 'GET', + 'body' => $streamFactory->createStream(''), + 'remove_headers' => ['Content-Length', 'Transfer-Encoding'], + ]; + } + + /** + * Set the appropriate URL on the request based on the location header. + */ + private static function redirectUri( + UriFactoryInterface $uriFactory, + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + ResponseInterface $response, + array $protocols + ): UriInterface { + $location = $response->getHeaderLine('Location'); + + try { + $locationUri = $uriFactory->createUri($location); + $resolvedUri = Psr7\UriResolver::resolve( + $request->getUri(), + $locationUri + ); + + if (!$uriFactory instanceof HttpFactory + && $locationUri->getScheme() === '' + && $locationUri->getAuthority() === '' + ) { + $resolvedUri = $uriFactory->createUri((string) $resolvedUri); + } + } catch (\InvalidArgumentException $e) { + throw new BadResponseException(\sprintf('Redirect URI, %s, is invalid.', Psr7\UriRedactor::redactUriStringForMessage($location)), $request, $response, $e); + } + + // Ensure that the redirect URI is allowed based on the protocols. + if (!\in_array($resolvedUri->getScheme(), $protocols, true)) { + throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', Psr7\UriRedactor::redactUriForMessage($resolvedUri), \implode(', ', $protocols)), $request, $response); + } + + return $resolvedUri; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/RequestOptions.php b/vendor/guzzlehttp/guzzle/src/RequestOptions.php new file mode 100644 index 0000000..a784978 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/RequestOptions.php @@ -0,0 +1,526 @@ +, + * default=['http', 'https']) Allowed redirect protocols. Values are + * case-sensitive; only "http" and "https" are accepted. + * - on_redirect: (callable(RequestInterface, ResponseInterface, UriInterface): mixed) + * PHP callable that is invoked when a redirect is encountered. The + * callable is invoked with the request, the redirect response that was + * received, and the effective URI. Any return value is ignored. When + * this callback is supplied via GuzzleHttp\Pool's "options" + * configuration, the pool appends the request's iterable key as a + * fourth argument. + * - track_redirects: (bool, default=false) Track redirected URI and status + * history in response headers. + */ + public const ALLOW_REDIRECTS = 'allow_redirects'; + + /** + * auth: (array{0: string, 1: string, 2?: string|null}|string|false|null) + * Pass an array of HTTP authentication parameters to use with the request. + * The array must contain the username in index [0], the password in index + * [1], and you can optionally provide a built-in authentication type in + * index [2]. Pass false or null to disable authentication for a request. + * Built-in Basic and Digest authentication are applied by the auth + * middleware, normally from HandlerStack::create(). String values are + * passed through for custom handlers. Built-in Basic usernames must not + * contain a colon, and neither Basic usernames nor passwords may contain + * ASCII control characters. Basic passwords may contain colons. + */ + public const AUTH = 'auth'; + + /** + * body: (resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable) + * Body to send in the request. Resource and stringable object values are + * converted using the configured stream_factory. Callable and iterator + * bodies use Guzzle's existing stream handling. Strings are used as literal + * body contents, even when they name a callable. Callable bodies may be + * closures or invokable objects; arrays, int, float, bool, and generic + * objects without __toString() are not valid body values. + */ + public const BODY = 'body'; + + /** + * cert: (string|array{0: string, 1?: string|null}) Set to a string to + * specify the path to a client certificate file. PEM is the default + * certificate format. If a password is required, set cert to an array + * containing the certificate path in the first array element followed by + * the certificate password in the second array element. A null password is + * treated the same as omitting it. Use cert_type to specify another + * supported certificate format. + * + * @see self::CERT_TYPE + */ + public const CERT = 'cert'; + + /** + * cert_type: (string) Specify the SSL client certificate file type. + */ + public const CERT_TYPE = 'cert_type'; + + /** + * cookies: (false|GuzzleHttp\Cookie\CookieJarInterface, default=false) + * Specifies whether or not cookies are used in a request or what cookie + * jar to use or what cookies to send. This option only works if your + * handler has the `cookie` middleware. Valid values are `false` and + * an instance of {@see Cookie\CookieJarInterface}. + */ + public const COOKIES = 'cookies'; + + /** + * connect_timeout: (int|float, default=60) Number of seconds to wait + * while trying to connect to a server. Use 0 to disable the connect + * timeout. Positive values below 0.001 seconds are rejected by the + * built-in cURL handler. + */ + public const CONNECT_TIMEOUT = 'connect_timeout'; + + /** + * crypto_method: (int) A value describing the minimum TLS protocol + * version to use. The built-in cURL and stream handlers default HTTPS + * requests to TLS 1.2 or newer. + * + * This setting must be set to one of the + * ``STREAM_CRYPTO_METHOD_TLS*_CLIENT`` constants. cURL 7.52.0 or higher + * is required to use TLS 1.3 with the cURL handler. + */ + public const CRYPTO_METHOD = 'crypto_method'; + + /** + * crypto_method_max: (int) A value describing the maximum TLS protocol + * version to use. The built-in cURL and stream handlers default HTTPS + * requests to TLS 1.2 or newer, so a lower maximum requires explicitly + * lowering crypto_method too. + * + * This setting must be set to one of the + * ``STREAM_CRYPTO_METHOD_TLS*_CLIENT`` constants. cURL 7.54.0 or higher + * is required in order to specify a maximum TLS version with the cURL + * handler. + */ + public const CRYPTO_METHOD_MAX = 'crypto_method_max'; + + /** + * curl: (array) Raw cURL options to apply when using a built-in cURL + * handler. + */ + public const CURL = 'curl'; + + /** + * debug: (bool|resource) Set to true or set to a PHP stream returned by + * fopen() to enable debug output with the handler used to send a request. + * For example, when using cURL to transfer requests, cURL's verbose of + * CURLOPT_VERBOSE will be emitted. When using the PHP stream wrapper, + * stream wrapper notifications will be emitted. If set to true, the output + * is written to PHP's STDOUT. If a PHP stream is provided, output is + * written to the stream. + */ + public const DEBUG = 'debug'; + + /** + * decode_content: (bool|string, default=true) Specify whether or not + * Content-Encoding responses (gzip, deflate, etc.) are automatically + * decoded. + */ + public const DECODE_CONTENT = 'decode_content'; + + /** + * delay: (int|float) The finite, non-negative amount of time to delay + * before sending in milliseconds. + */ + public const DELAY = 'delay'; + + /** + * expect: (bool|integer) Controls the behavior of the + * "Expect: 100-Continue" header. + * + * Set to `true` to enable the "Expect: 100-Continue" header for all + * requests that sends a body. Set to `false` to disable the + * "Expect: 100-Continue" header for all requests. Set to a number so that + * the size of the payload must be greater than the number in order to send + * the Expect header. Setting to a number will send the Expect header for + * all requests in which the size of the payload cannot be determined or + * where the body is not rewindable. + * + * By default, Guzzle will add the "Expect: 100-Continue" header when the + * size of the body of a request is greater than 1 MB and a request is + * using HTTP/1.1. + */ + public const EXPECT = 'expect'; + + /** + * form_params: (array) + * Associative array of form field names to scalar, null, or nested array + * values. Sets the Content-Type header to application/x-www-form-urlencoded + * when no Content-Type header is already present. + */ + public const FORM_PARAMS = 'form_params'; + + /** + * headers: (array>|null) + * Associative array of HTTP headers. Each value MUST be a string or + * non-empty array of strings. + */ + public const HEADERS = 'headers'; + + /** + * http_errors: (bool, default=true) Set to false to disable exceptions + * when a non-successful HTTP response is received. By default, + * exceptions will be thrown for 4xx and 5xx responses. This option only + * works if your handler has the `httpErrors` middleware. + */ + public const HTTP_ERRORS = 'http_errors'; + + /** + * idn_conversion: (bool|int|null, default=false) A combination of IDNA_* + * constants for PHP's idn_to_ascii() function. Set to false or null to + * disable IDN support, or true to use the default configuration + * (IDNA_DEFAULT constant). + */ + public const IDN_CONVERSION = 'idn_conversion'; + + /** + * json: (mixed) Adds JSON data to a request. The provided value is JSON + * encoded and a Content-Type header of application/json will be added to + * the request if no Content-Type header is already present. An Accept + * header is not added automatically. + */ + public const JSON = 'json'; + + /** + * multipart: (array) Array of part arrays, each containing a required + * "name" key mapping to the string or integer form field name, a required + * "contents" key mapping to any non-array value accepted by PSR-7 + * Utils::streamFor() or a nested array of field values, an optional + * "headers" array of string custom header values, and an optional + * "filename" key mapping to a string to send as the filename in the part. + * "headers" and "filename" cannot be used when "contents" is an array. + */ + public const MULTIPART = 'multipart'; + + /** + * multiplex: (string, default=GuzzleHttp\Multiplexing::WAIT) Controls how a + * request sent through a built-in cURL handler relates to shared, + * multiplexed connections: how an HTTP/2 or HTTP/3 request pursues one, or, + * with Multiplexing::NONE, whether the transfer may share its connection at + * all. Use Multiplexing::EAGER to avoid waiting for pending connections, + * Multiplexing::WAIT to wait on libcurl-eligible pending connections with + * CURLOPT_PIPEWAIT, normally to the same origin, + * Multiplexing::REQUIRE_EAGER to fail unless a multiplexed protocol is + * guaranteed while dialing eagerly, or Multiplexing::REQUIRE_WAIT for the + * same guarantee while also waiting on pending connections. The required + * modes require a handler that permits actual multiplexing, not merely a + * multiplexed protocol, and are rejected on a Multiplexing::NONE handler. + * The stream handler ignores EAGER and WAIT, and rejects the required + * family; CurlHandler has no multi handle to multiplex over. The required + * family also rejects final CURLOPT_HTTPAUTH masks that permit NTLM, which + * libcurl retries over HTTP/1.1. Multiplexing::NONE disables multiplexing + * for a whole handler when passed as the "multiplex" client configuration + * option, which configures the default handler and also becomes the default + * request option, or, when constructing a handler directly, as the + * CurlMultiHandler "multiplex" constructor option. A handler configured + * with Multiplexing::NONE wins over the default WAIT: default requests run + * without waiting, explicitly requested wait modes are rejected as a + * configuration conflict when the transfer would actually wait, and the + * required modes are always rejected, because they require a handler that + * permits actual multiplexing, not merely a multiplexed protocol. As a + * request option value, Multiplexing::NONE guarantees the transfer does not + * share its connection with any concurrent transfer. Multiplexing::NONE + * does not force HTTP/1.1: on a Multiplexing::NONE handler, HTTP/2 still + * negotiates and each transfer keeps its connection to itself. + * + * The request option value is accepted exactly where the guarantee holds + * and can be verified: on a CurlMultiHandler configured with + * Multiplexing::NONE, for requests whose declared protocol version is + * HTTP/1.x, on CurlHandler, and on the stream handler, which never + * multiplexes. An HTTP/2 or HTTP/3 request with a Multiplexing::NONE + * request option is rejected on a CurlMultiHandler that permits + * multiplexing. Acceptance is decided from the request's declared protocol + * version, before any transport-level downgrade: an HTTP/3 request sent + * through a proxy is delivered over HTTP/2 or HTTP/1.1 on the wire, but is + * still rejected. On a CurlMultiHandler that permits multiplexing, + * Multiplexing::NONE is also rejected with a custom "handle_factory", when + * the handler requires persistent transport sharing (the safeguards can + * require a fresh connection, which required sharing forbids), when the + * request carries an Expect: 100-continue header (its 417 retries select + * connections outside the safeguards; remove an explicitly supplied + * header, or set the "expect" request option to false to prevent it being + * added automatically), and combined with a raw CURLOPT_HTTPAUTH cURL + * option, whose authentication retries do the same. + * + * On a client whose multi handler permits multiplexing, the ordinary + * non-streaming default stack - both cURL handlers available and no + * connection caps forcing multi-only routing - runs synchronous requests on + * the CurlHandler path, which satisfies the guarantee for any protocol + * version, while asynchronous requests run on the CurlMultiHandler, so an + * HTTP/2 request with Multiplexing::NONE succeeds synchronously and is + * rejected asynchronously on the same client. Keep-alive reuse between + * consecutive transfers is unaffected, except on libcurl versions below + * 7.77.0 and from 8.11.0 through 8.12.1, where an accepted HTTP/1.x request + * on a multiplexing CurlMultiHandler forces a fresh connection. Custom + * handlers receive the "multiplex" option unchanged: its semantics are + * handler-defined, Guzzle does not guarantee it is honored, and a + * client-level Multiplexing::NONE with a custom handler flows to it as a + * default request option without client-side enforcement. + */ + public const MULTIPLEX = 'multiplex'; + + /** + * on_headers: (callable(ResponseInterface, RequestInterface): mixed) A + * callable that is invoked when the HTTP headers of the final response, or + * a 101 Switching Protocols response, have been received but the body has + * not yet begun to download. The callable is passed the response and + * request as {@see ResponseInterface} and {@see RequestInterface} objects, + * respectively. If it throws, the request promise is rejected with a + * GuzzleHttp\Exception\ResponseException (a RequestException subtype) + * wrapping the thrown exception. When this callback is supplied via + * GuzzleHttp\Pool's "options" configuration, the pool appends the request's + * iterable key as a third argument. + */ + public const ON_HEADERS = 'on_headers'; + + /** + * on_stats: (callable(TransferStats): mixed) allows you to get access to + * transfer statistics of a request and access the lower level transfer + * details of the handler associated with your client. ``on_stats`` is a + * callable that is invoked when a handler has finished sending a request. + * The callback is invoked with transfer statistics about the request, the + * response received, or the error encountered. Included in the data is the + * total amount of time taken to send the request. Exceptions thrown by + * on_stats are not wrapped by Guzzle. Built-in handlers reject non-callable + * values before starting the transfer. The built-in cURL handlers release + * native easy handles before invoking on_stats and invoke it per low-level + * transfer attempt. When this callback is supplied via GuzzleHttp\Pool's + * "options" configuration, the pool appends the request's iterable key as a + * second argument. + */ + public const ON_STATS = 'on_stats'; + + /** + * on_trailers: (callable(array>, ResponseInterface, RequestInterface): mixed) + * A callable that is invoked exactly once when a transfer completes + * successfully, with the HTTP trailer fields of the response. The callable + * is passed an associative array of trailer field names mapped to lists of + * field values, the response, and the request. The array is empty when the + * response carried no trailer fields, and trailer field names are + * lowercased and grouped case-insensitively while values keep their wire + * order. The callable is never invoked for failed transfers. If it throws, + * the request promise is rejected with a + * GuzzleHttp\Exception\ResponseException (a RequestException subtype) + * wrapping the thrown exception. Only the built-in cURL handlers invoke + * on_trailers; the built-in stream handler rejects the option because it + * cannot observe trailer fields, and the mock handler ignores it. + * Malformed trailer field lines are discarded before parsing. Trailer + * fields are reported separately from response headers and are never + * merged into the response. When this callback is supplied via + * GuzzleHttp\Pool's "options" configuration, the pool appends the + * request's iterable key as a fourth argument. + */ + public const ON_TRAILERS = 'on_trailers'; + + /** + * progress: (callable(int, int, int, int): mixed) + * Defines a function to invoke when transfer progress is made. The function + * accepts the following positional arguments: the total number of bytes + * expected to be downloaded, the number of bytes downloaded so far, the + * number of bytes expected to be uploaded, the number of bytes uploaded so + * far. With the built-in cURL handlers, returning a truthy value aborts the + * transfer and throwing rejects the promise with a RequestException. The + * built-in stream handler ignores return values. When this callback is + * supplied via GuzzleHttp\Pool's "options" configuration, the pool appends + * the request's iterable key as a fifth argument. + */ + public const PROGRESS = 'progress'; + + /** + * protocols: (non-empty-array, + * default=['http', 'https']) Allowed URI schemes. Values are + * case-sensitive; only "http" and "https" are accepted. + */ + public const PROTOCOLS = 'protocols'; + + /** + * proxy: (string|array) Pass a string to specify an HTTP proxy, or an array + * to specify different proxies for different protocols (where the key is + * the protocol and the value is a proxy string or null). Provide a "no" key + * as a comma- or whitespace-delimited string, array of strings, or null to + * specify hosts, host-and-port pairs, IP literals, IP CIDR rules, or + * wildcard rules that should not be proxied. Domain rules are matched + * case-insensitively. Exact IP literals are normalized before matching, + * including the inet_aton() shorthand spellings a transport reads as an + * address. CIDR rules match IP literals only and are not port-specific. + * Custom handlers can use ProxyOptions::resolve() to apply + * Guzzle-compatible proxy selection; the built-in handlers' + * environment-variable fallback is not part of that helper. + */ + public const PROXY = 'proxy'; + + /** + * query: (array|string) Associative array of query string + * values to add to the request. This option uses PHP's http_build_query() + * to create the string representation. Pass a string value if you need + * more control than what this method provides + */ + public const QUERY = 'query'; + + /** + * request_factory: (Psr\Http\Message\RequestFactoryInterface) PSR-17 + * request factory used when creating requests through request() and + * requestAsync(). + */ + public const REQUEST_FACTORY = 'request_factory'; + + /** + * stream_factory: (Psr\Http\Message\StreamFactoryInterface) PSR-17 + * stream factory used when creating request body streams from body, + * form_params, and json request options, and when the built-in handlers + * create response body streams. + */ + public const STREAM_FACTORY = 'stream_factory'; + + /** + * response_factory: (Psr\Http\Message\ResponseFactoryInterface) PSR-17 + * response factory used by the built-in handlers when creating the + * response message. + */ + public const RESPONSE_FACTORY = 'response_factory'; + + /** + * sink: (resource|string|StreamInterface) Where the data of the + * response is written to. Defaults to a PHP temp stream. Providing a + * string will write data to a file by the given name. Built-in handlers + * treat PHP resources as caller-owned; callers are responsible for closing + * resource sinks. + */ + public const SINK = 'sink'; + + /** + * synchronous: (bool) Set to true to inform HTTP handlers that you intend + * on waiting on the response. This can be useful for optimizations. Note + * that a promise is still returned if you are using one of the async + * client methods. + */ + public const SYNCHRONOUS = 'synchronous'; + + /** + * ssl_key: (array{0: string, 1?: string|null}|string) Specify the path to + * a private SSL key file. PEM is the default private key format. If a + * password is required, set ssl_key to an array containing the key path in + * the first array element followed by the key password in the second + * element. A null password is treated the same as omitting it. Use + * ssl_key_type to specify another supported key format. + * + * @see self::SSL_KEY_TYPE + */ + public const SSL_KEY = 'ssl_key'; + + /** + * ssl_key_type: (string) Specify the SSL private key file type. + */ + public const SSL_KEY_TYPE = 'ssl_key_type'; + + /** + * stream: (bool) Set to true to attempt to stream a response rather than + * download it all up-front. + */ + public const STREAM = 'stream'; + + /** + * stream_context: (array) PHP stream context options to merge into the + * context used by the built-in stream handler. + */ + public const STREAM_CONTEXT = 'stream_context'; + + /** + * verify: (bool|string, default=true) Describes the SSL certificate + * verification behavior of a request. Set to true to enable SSL + * certificate verification using the system CA bundle when available + * (the default). Set to false to disable certificate verification (this + * is insecure!). Set to a string to provide the path to a CA bundle on + * disk to enable verification using a custom certificate. + */ + public const VERIFY = 'verify'; + + /** + * timeout: (int|float, default=0) Number of seconds to use as the total + * timeout of the request. Use 0 to disable the total timeout (the default + * behavior). Positive values below 0.001 seconds are rejected by the + * built-in handlers. + */ + public const TIMEOUT = 'timeout'; + + /** + * read_timeout: (int|float, default=60) Number of seconds the connection + * may sit silent at any stage of the request. Use 0 to disable the idle + * timeout. Positive values below 0.001 seconds are rejected by the + * built-in stream handler. + */ + public const READ_TIMEOUT = 'read_timeout'; + + /** + * retries: (int) Current retry count used by the retry middleware. + */ + public const RETRIES = 'retries'; + + /** + * uri_factory: (Psr\Http\Message\UriFactoryInterface) PSR-17 URI factory + * used when creating URI objects from string request URI, base_uri, and + * redirect Location values. + */ + public const URI_FACTORY = 'uri_factory'; + + /** + * version: (string|int|float, default=1.1) Specifies the HTTP protocol + * version to attempt to use. + * + * Guzzle defaults to HTTP/1.1. The built-in stream handler supports + * HTTP/1.0 and HTTP/1.1. The built-in cURL handler also supports HTTP/2 + * and HTTP/3 when the installed cURL stack reports those features. For + * HTTP/2 and HTTP/3, libcurl may use a lower HTTP version when + * negotiation or connection setup falls back. + */ + public const VERSION = 'version'; + + /** + * force_ip_resolve: ("v4"|"v6") Set to "v4" to force IPv4 resolution or + * "v6" to force IPv6 resolution when supported by the handler. + */ + public const FORCE_IP_RESOLVE = 'force_ip_resolve'; +} diff --git a/vendor/guzzlehttp/guzzle/src/RetryMiddleware.php b/vendor/guzzlehttp/guzzle/src/RetryMiddleware.php new file mode 100644 index 0000000..2709653 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/RetryMiddleware.php @@ -0,0 +1,137 @@ +): PromiseInterface + */ + private $nextHandler; + + /** + * @var callable(int, RequestInterface, ResponseInterface|null, mixed): bool + */ + private $decider; + + /** + * @var callable(int, ResponseInterface|null, RequestInterface): int + */ + private $delay; + + /** + * @param callable(int, RequestInterface, ResponseInterface|null, mixed): bool $decider Function that accepts the number of retries, + * a request, [response], and [rejection reason] + * and returns true if the request is to be retried. + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. + * @param (callable(int, ResponseInterface|null, RequestInterface): int)|null $delay Function that returns the number of milliseconds to delay. + */ + public function __construct(callable $decider, callable $nextHandler, ?callable $delay = null) + { + $this->decider = $decider; + $this->nextHandler = $nextHandler; + $this->delay = $delay ?: static function (int $retries): int { + return (int) ((2 ** ($retries - 1)) * 1000); + }; + } + + /** + * @return PromiseInterface + */ + public function __invoke( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options + ): PromiseInterface { + if (!isset($options['retries'])) { + $options['retries'] = 0; + } elseif (!\is_int($options['retries'])) { + throw new \InvalidArgumentException('retries must be an integer'); + } + + /** @var PromiseInterface */ + return ($this->nextHandler)($request, $options) + ->then( + $this->onFulfilled($request, $options), + $this->onRejected($request, $options) + ); + } + + /** + * Execute fulfilled closure + */ + private function onFulfilled(RequestInterface $request, array $options): callable + { + return function ( + #[\SensitiveParameter] + $value + ) use ($request, $options) { + if (!($this->decider)( + $options['retries'], + $request, + $value, + null + )) { + return $value; + } + + return $this->doRetry($request, $options, $value); + }; + } + + /** + * Execute rejected closure + */ + private function onRejected(RequestInterface $req, array $options): callable + { + return function ( + #[\SensitiveParameter] + $reason + ) use ($req, $options): PromiseInterface { + if (!($this->decider)( + $options['retries'], + $req, + null, + $reason + )) { + return P\Create::rejectionFor($reason); + } + + /** @var PromiseInterface */ + return $this->doRetry($req, $options); + }; + } + + /** + * @return PromiseInterface + */ + private function doRetry( + #[\SensitiveParameter] + RequestInterface $request, + #[\SensitiveParameter] + array $options, + #[\SensitiveParameter] + ?ResponseInterface $response = null + ): PromiseInterface { + ++$options['retries']; + $options['delay'] = ($this->delay)($options['retries'], $response, $request); + + return $this($request, $options); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/TransferStats.php b/vendor/guzzlehttp/guzzle/src/TransferStats.php new file mode 100644 index 0000000..c9d4b66 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/TransferStats.php @@ -0,0 +1,123 @@ +request = $request; + $this->response = $response; + $this->transferTime = $transferTime; + $this->handlerErrorData = $handlerErrorData; + $this->handlerStats = $handlerStats; + } + + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Returns the response that was received (if any). + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Returns true if a response was received. + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Gets handler specific error data. + * + * This might be an exception, a integer representing an error code, or + * anything else. Relying on this value assumes that you know what handler + * you are using. + * + * @return mixed + */ + public function getHandlerErrorData() + { + return $this->handlerErrorData; + } + + /** + * Get the effective URI the request was sent to. + */ + public function getEffectiveUri(): UriInterface + { + return $this->request->getUri(); + } + + /** + * Get the estimated time the request was being transferred by the handler. + * + * @return float|null Time in seconds. + */ + public function getTransferTime(): ?float + { + return $this->transferTime; + } + + /** + * Gets an array of all of the handler specific transfer data. + */ + public function getHandlerStats(): array + { + return $this->handlerStats; + } + + /** + * Get a specific handler statistic from the handler by name. + * + * @param string $stat Handler specific transfer stat to retrieve. + * + * @return mixed|null + */ + public function getHandlerStat(string $stat) + { + return $this->handlerStats[$stat] ?? null; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/TransportSharing.php b/vendor/guzzlehttp/guzzle/src/TransportSharing.php new file mode 100644 index 0000000..5d27c5a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/TransportSharing.php @@ -0,0 +1,18 @@ +, callable(): callable): callable)|null + */ + private static $defaultHandlerFactory; + + private function __construct() + { + } + + /** + * Parses an array of header lines into an associative array of headers. + * + * @param iterable $lines Header lines array of strings in the following + * format: "Name: Value" + * + * @deprecated Utils::headersFromLines() will be removed in + * guzzlehttp/guzzle:9.0. + */ + public static function headersFromLines(iterable $lines): array + { + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return HeaderProcessor::headersFromLines($lines); + } + + /** + * Returns a debug stream based on the provided variable. + * + * @param mixed $value Optional value + * + * @return resource + * + * @deprecated Utils::debugResource() will be removed in + * guzzlehttp/guzzle:9.0. + */ + public static function debugResource($value = null) + { + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return DebugResource::from($value); + } + + /** + * Sets a factory that creates the default handler in place of the built-in + * selection. + * + * The factory receives the handler options and a callable that returns the + * handler Guzzle would have chosen. It is consulted each time a default + * handler is chosen, after the handler options have been checked for type + * and value. Passing null restores the built-in selection. + * + * The factory is process-wide, so set it from application bootstrap code, + * not from a library. + * + * @param (callable(array, callable(): callable): callable)|null $factory + */ + public static function setDefaultHandlerFactory(?callable $factory): void + { + self::$defaultHandlerFactory = $factory; + } + + /** + * Chooses and creates a default handler to use based on the environment. + * + * The returned handler is not wrapped by any default middlewares. + * + * A factory set with setDefaultHandlerFactory() creates the handler in + * place of the built-in selection. + * + * @param array{transport_sharing?: mixed, max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions Handler constructor options. + * + * @return callable(RequestInterface, array): PromiseInterface Returns the best handler for the given system. + * + * @throws \RuntimeException if no viable Handler is available. + */ + public static function chooseHandler(array $handlerOptions = []): callable + { + $sharingMode = CurlShareHandleState::normalizeMode($handlerOptions['transport_sharing'] ?? null, 'transport_sharing'); + $sharingRequired = self::isTransportSharingRequired($sharingMode); + $connectionCapsRequired = self::hasConnectionCapOptions($handlerOptions); + + $maxIdleHandles = $handlerOptions['max_idle_handles'] ?? null; + if ($maxIdleHandles !== null && (!\is_int($maxIdleHandles) || $maxIdleHandles < 0)) { + throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); + } + + if (self::$defaultHandlerFactory === null) { + return self::chooseBuiltInHandler($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions); + } + + return (self::$defaultHandlerFactory)($handlerOptions, static function () use ($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions): callable { + return self::chooseBuiltInHandler($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions); + }); + } + + /** + * @param array{max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions + * + * @return callable(RequestInterface, array): PromiseInterface + */ + private static function chooseBuiltInHandler(string $sharingMode, bool $sharingRequired, bool $connectionCapsRequired, array $handlerOptions): callable + { + $sharedPoolCapsSupported = CurlVersion::supportsSharedPoolConnectionCaps(); + + if ($connectionCapsRequired && !$sharedPoolCapsSupported && $sharingMode === TransportSharing::PERSISTENT_REQUIRE) { + throw new InvalidArgumentException(\sprintf('The "max_host_connections" and "max_total_connections" options cannot be combined with required persistent transport sharing because applying connection caps to shared connection pools requires libcurl %s or higher.', CurlVersion::SHARED_POOL_CONNECTION_CAP_VERSION)); + } + + if ($connectionCapsRequired && !$sharedPoolCapsSupported && $sharingMode === TransportSharing::PERSISTENT_PREFER) { + // libcurl below 8.22.0 does not apply cURL multi connection caps to + // transfers using a shared connection pool (curl #22265), so the + // best honorable offer for preferred persistent sharing is a + // handler-lifetime share. + $sharingMode = TransportSharing::HANDLER_PREFER; + } + + $handler = self::createCurlHandler($sharingMode, $handlerOptions); + + // Handler-scoped required sharing can also be satisfied by the stream + // handler's TLS session resumption (PHP 8.6+); persistent required + // sharing is cURL-only. + $streamCanShareSessions = (bool) \ini_get('allow_url_fopen') && StreamTlsSessionCache::isSupported(); + + if ($sharingRequired && $handler === null) { + if ($sharingMode === TransportSharing::PERSISTENT_REQUIRE) { + throw new \RuntimeException('Required persistent transport sharing requires the PHP cURL extension, curl_exec() or curl_multi_exec(), and a supported libcurl version with SSL support.'); + } + + if (!$streamCanShareSessions) { + throw new \RuntimeException('Required transport sharing requires the PHP cURL extension (curl_exec()/curl_multi_exec()) with a supported libcurl version and SSL support, or PHP 8.6+ with the OpenSSL TLS session API and the allow_url_fopen ini setting.'); + } + } + + if (\ini_get('allow_url_fopen')) { + return self::addStreamHandler($handler, $sharingMode, self::connectionCapOptions($handlerOptions)); + } + + if ($handler !== null) { + return $handler; + } + + if ($connectionCapsRequired) { + throw new \RuntimeException('Connection cap options require a cap-capable cURL multi handler or the allow_url_fopen ini setting for stream fallback.'); + } + + throw new \RuntimeException('GuzzleHttp requires a supported cURL version with SSL support, the allow_url_fopen ini setting, or a custom HTTP handler.'); + } + + private static function isTransportSharingRequired(string $sharingMode): bool + { + return \in_array($sharingMode, [TransportSharing::HANDLER_REQUIRE, TransportSharing::PERSISTENT_REQUIRE], true); + } + + /** + * @param array{max_host_connections?: mixed, max_total_connections?: mixed} $handlerOptions + */ + private static function hasConnectionCapOptions(array $handlerOptions): bool + { + return self::connectionCapOptions($handlerOptions) !== []; + } + + /** + * @param array{max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions + * + * @return (callable(RequestInterface, array): PromiseInterface)|null + */ + private static function createCurlHandler(string $sharingMode, array $handlerOptions): ?callable + { + if (!CurlVersion::supportsCurlHandler()) { + return null; + } + + if ($sharingMode === TransportSharing::HANDLER_REQUIRE && !CurlShareHandleState::supportsHandlerRequireShare()) { + // Required handler sharing can also be satisfied by the stream + // handler's TLS session resumption, so a cURL install that cannot + // share is skipped instead of failing handler selection. + return null; + } + + $connectionCapOptions = self::connectionCapOptions($handlerOptions); + if ($connectionCapOptions !== [] && !\function_exists('curl_multi_exec')) { + return null; + } + + $curlHandlerOptions = self::createCurlHandlerOptions($sharingMode); + if (isset($handlerOptions['max_idle_handles'])) { + $curlHandlerOptions['max_idle_handles'] = $handlerOptions['max_idle_handles']; + } + $curlMultiHandlerOptions = $curlHandlerOptions + $connectionCapOptions; + if (($handlerOptions['multiplex'] ?? null) === Multiplexing::NONE) { + // Forwarded to the CurlMultiHandler only: CurlHandler and + // StreamHandler validate known options, and both satisfy NONE + // per-request without a handler option. + $curlMultiHandlerOptions['multiplex'] = Multiplexing::NONE; + } + + if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) { + $multiHandler = new CurlMultiHandler($curlMultiHandlerOptions); + + if ($connectionCapOptions !== []) { + // Connection caps only govern transfers on the multi handle, so + // the synchronous CurlHandler fast path would escape them. + return $multiHandler; + } + + return Proxy::wrapSync($multiHandler, new CurlHandler($curlHandlerOptions)); + } + + if ($connectionCapOptions === [] && \function_exists('curl_exec')) { + return new CurlHandler($curlHandlerOptions); + } + + if (\function_exists('curl_multi_exec')) { + return new CurlMultiHandler($curlMultiHandlerOptions); + } + + return null; + } + + /** + * @return array + */ + private static function createCurlHandlerOptions(string $sharingMode): array + { + if ($sharingMode === TransportSharing::NONE) { + return []; + } + + $shareState = CurlShareHandleState::fromOption($sharingMode); + + return $shareState === null ? [] : ['transport_sharing' => $shareState]; + } + + /** + * @param array{max_host_connections?: mixed, max_total_connections?: mixed} $handlerOptions + * + * @return array{max_host_connections?: int, max_total_connections?: int} + */ + private static function connectionCapOptions(array $handlerOptions): array + { + $options = []; + foreach (['max_host_connections', 'max_total_connections'] as $capOption) { + $value = $handlerOptions[$capOption] ?? null; + if ($value === null) { + continue; + } + + if (!\is_int($value) || $value < 1) { + throw new InvalidArgumentException(\sprintf('%s must be a positive integer.', $capOption)); + } + + $options[$capOption] = $value; + } + + return $options; + } + + /** + * @param (callable(RequestInterface, array): PromiseInterface)|null $handler + * @param array{max_host_connections?: int, max_total_connections?: int} $connectionCapOptions + * + * @return callable(RequestInterface, array): PromiseInterface + */ + private static function addStreamHandler(?callable $handler, string $sharingMode, array $connectionCapOptions): callable + { + $streamHandler = new StreamHandler(['transport_sharing' => $sharingMode] + $connectionCapOptions); + + return $handler + ? Proxy::wrapStreaming($handler, $streamHandler) + : $streamHandler; + } + + /** + * Get the default User-Agent string to use with Guzzle. + * + * @deprecated Utils::defaultUserAgent() will be removed in + * guzzlehttp/guzzle:9.0. Use ClientInterface::MAJOR_VERSION + * to build the string instead. + */ + public static function defaultUserAgent(): string + { + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0. Use %s::MAJOR_VERSION to build the string instead.', + __METHOD__, + ClientInterface::class + ); + + return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION); + } + + /** + * Creates an associative array of lowercase header names to the actual + * header casing. + * + * @deprecated Utils::normalizeHeaderKeys() will be removed in + * guzzlehttp/guzzle:9.0. + */ + public static function normalizeHeaderKeys(array $headers): array + { + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return HeaderProcessor::normalizeHeaderKeys($headers); + } + + /** + * @param mixed $protocols + * + * @return string[] + * + * @throws InvalidArgumentException + * + * @deprecated Utils::normalizeProtocols() will be removed in + * guzzlehttp/guzzle:9.0. + */ + public static function normalizeProtocols($protocols): array + { + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return Protocols::normalize($protocols); + } +} diff --git a/vendor/guzzlehttp/promises/AGENTS.md b/vendor/guzzlehttp/promises/AGENTS.md new file mode 100644 index 0000000..d740e93 --- /dev/null +++ b/vendor/guzzlehttp/promises/AGENTS.md @@ -0,0 +1,62 @@ +# Agent Guidelines + +## Code and tooling + +- All code must remain compatible with PHP 7.4. Run PHPStan and PHP-CS-Fixer + only under a PHP 7.4.x runtime; never run either tool under any other PHP + major.minor version. +- Use fully qualified `#[\SensitiveParameter]` on concrete executable + parameters when their established role normally carries a secret, + credential-bearing aggregate, or confidential Guzzle-owned container, and + the active frame can throw or invoke throwing code. +- Repeat the attribute on every qualifying owned caller, callee, concrete trait + method, and closure parameter. Do not add it to interfaces, abstract-only + declarations, pure/no-realistic-throw helpers, assignment-only sites, + arbitrary generic payloads, or completed non-recoverable derivatives. +- For PHP 7.4 compatibility, put `#[\SensitiveParameter]` on its own line and + the parameter on the following line, expand the complete parameter list, and + never add a comma after the final parameter. Native trace redaction starts on + PHP 8.2 and does not redact logs, messages, properties, wire traffic, captured + variables, return values, or the separate backtrace `$this`/`object`. +- Always pass an explicit character list to `trim()`, `ltrim()`, and `rtrim()`; + never rely on the default characters. +- Handle `preg_*` engine failures: when the result is used as data, test for + `false` or `null` and throw a `\RuntimeException` including + `preg_last_error_msg()`; boolean validation guards must compare strictly, such + as `=== 1`, so an engine failure can only ever fail closed. Diagnostic + escaping is the narrow exception: use a deterministic bytewise fallback rather + than throwing, so it cannot obscure the original exception. +- Anchor validation patterns to the true end of input with the `D` modifier or + `\z`; a bare `$` accepts a trailing newline. +- Never embed raw control bytes in exception messages and other diagnostics; + escape or redact the offending value first. +- Helper classes that expose only public static methods are `final` and have a + private constructor. +- Resist native PHP serialization when a class holds live state (streams, + resources, handles, callbacks, credentials); plain data holders remain + serializable. +- To resist, `__serialize()` and `__unserialize()` both throw + `\LogicException(static::class.' should never be serialized')` and its + unserialized counterpart, via the `@internal` `NonSerializableTrait`. +- In general, numeric inputs should not accept non-finite floats. In situations + where they are accepted and we need to cast to a string, we should branch on + `\is_finite($value)`, using `(string) $value` for the finite case and + `\is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')` otherwise. +- Never call `strtolower()`, `strtoupper()`, `strcasecmp()`, `stripos()`, or + other locale-sensitive case functions; fold ASCII case with + `strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')` + and its inverse instead. +- Changes in behavior need a `CHANGELOG.md` entry in the unreleased section of + the target branch and an `UPGRADING.md` note when the behavior differs between + major versions. + +## Documentation + +- Wrap markdown prose and PHPDoc text to 80 columns using greedy wrapping. Never + split a markdown link or an inline code span across a line break; a line that + cannot be broken may exceed the limit. Avoid em dashes. +- Keep PHPDoc and the corresponding `docs/` pages in sync: shared prose is + deliberately word-for-word identical, including boilerplate copied verbatim + between related functions, so apply the same edit to every copy. Only + formatting and linking may differ, such as a docs link becoming a PHPDoc + `@see` tag; the wording must never drift. diff --git a/vendor/guzzlehttp/promises/CHANGELOG.md b/vendor/guzzlehttp/promises/CHANGELOG.md new file mode 100644 index 0000000..32a003a --- /dev/null +++ b/vendor/guzzlehttp/promises/CHANGELOG.md @@ -0,0 +1,303 @@ +# CHANGELOG + + +## 3.2.0 - 2026-11-21 + +### Changed + +- Changed `Coroutine` to forward cancellation from chained promises +- Changed `TaskQueue` to remove tasks in constant time + + +## 3.1.2 - 2026-11-21 + +### Fixed + +- Fixed `LogicException` when a callback settles its own promise + + +## 3.1.1 - 2026-11-19 + +### Fixed + +- Fixed `Promise` losing its handlers when a thenable's `then()` throws +- Fixed `Create::promiseFor()` throwing when a thenable's `then()` throws +- Fixed quadratic handler forwarding through chains of pending promises +- Fixed `Utils::inspect()` losing the outcome of a chained promise + + +## 3.1.0 - 2026-10-18 + +### Added + +- Added `State` promise state checks as a replacement for `Is` + +### Deprecated + +- Deprecated `Is` because PHP 8.6 deprecates `is` as a class name + + +## 3.0.2 - 2026-08-24 + +### Added + +- Added support for PHP 8.6 + + +## 3.0.1 - 2026-08-05 + +### Changed + +- Changed the default `TReason` of `FulfilledPromise` and `Create::promiseFor()` to `never` +- Changed the default `TValue` of `RejectedPromise` and `Create::rejectionFor()` to `never` + +### Fixed + +- Fixed `EachPromise` abandoning its aggregate when the pending window drains unsettled +- Fixed `EachPromise` admitting new work after its aggregate has settled + + +## 3.0.0 - 2026-07-20 + +### Added + +- Added `concurrency` config support to `Utils::all()` and `Each::of()` +- Added generic PHPDoc annotations to promise APIs and collection callbacks +- Added recursive and `concurrency` config support to `Utils::settle()` +- Allowed promises to be resolved without passing a value + +### Changed + +- Changed `Utils::inspect()` to return actual rejection reasons +- Changed `Utils::inspect()` to prefer the settled state over late wait function exceptions +- Changed late rejection callbacks to follow rejected promises +- Reject native PHP serialization of in-flight runtime objects +- Made static helper classes non-instantiable +- Require iterable inputs for promise collection helpers and `EachPromise` +- Iterate `IteratorAggregate` inputs to collection helpers instead of treating them as a single value +- Improved recursive `Utils::all()` handling of dynamically-added settled values and raw values + +### Removed + +- Dropped support for PHP 7.2 and 7.3 + + +## 2.5.1 - 2026-07-08 + +### Fixed + +- Fixed recursive `Utils::all()` rejecting generator inputs + + +## 2.5.0 - 2026-06-02 + +### Deprecated + +- Deprecated passing non-iterable inputs to promise collection helpers and `EachPromise` + + +## 2.4.1 - 2026-05-20 + +### Fixed + +- Fixed cancelling settled coroutines when no current promise remains + + +## 2.4.0 - 2026-05-20 + +### Changed + +- Empty `EachPromise` instances now resolve when the task queue runs without `wait()` + + +## 2.3.1 - 2026-05-19 + +### Fixed + +- Fixed `Utils::inspect()` returning the internal reason array instead of the `AggregateException` + + +## 2.3.0 - 2025-08-22 + +### Added + +- PHP 8.5 support + + +## 2.2.0 - 2025-03-27 + +### Fixed + +- Revert "Allow an empty EachPromise to be resolved by running the queue" + + +## 2.1.0 - 2025-03-27 + +### Added + +- Allow an empty EachPromise to be resolved by running the queue + + +## 2.0.4 - 2024-10-17 + +### Fixed + +- Once settled, don't allow further rejection of additional promises + + +## 2.0.3 - 2024-07-18 + +### Changed + +- PHP 8.4 support + + +## 2.0.2 - 2023-12-03 + +### Changed + +- Replaced `call_user_func*` with native calls + + +## 2.0.1 - 2023-08-03 + +### Changed + +- PHP 8.3 support + + +## 2.0.0 - 2023-05-21 + +### Added + +- Added PHP 7 type hints + +### Changed + +- All previously non-final non-exception classes have been marked as soft-final + +### Removed + +- Dropped PHP < 7.2 support +- All functions in the `GuzzleHttp\Promise` namespace + + +## 1.5.3 - 2023-05-21 + +### Changed + +- Removed remaining usage of deprecated functions + + +## 1.5.2 - 2022-08-07 + +### Changed + +- Officially support PHP 8.2 + + +## 1.5.1 - 2021-10-22 + +### Fixed + +- Revert "Call handler when waiting on fulfilled/rejected Promise" +- Fix pool memory leak when empty array of promises provided + + +## 1.5.0 - 2021-10-07 + +### Changed + +- Call handler when waiting on fulfilled/rejected Promise +- Officially support PHP 8.1 + +### Fixed + +- Fix manually settle promises generated with `Utils::task` + + +## 1.4.1 - 2021-02-18 + +### Fixed + +- Fixed `each_limit` skipping promises and failing + + +## 1.4.0 - 2020-09-30 + +### Added + +- Support for PHP 8 +- Optional `$recursive` flag to `all` +- Replaced functions by static methods + +### Fixed + +- Fix empty `each` processing +- Fix promise handling for Iterators of non-unique keys +- Fixed `method_exists` crashes on PHP 8 +- Memory leak on exceptions + + +## 1.3.1 - 2016-12-20 + +### Fixed + +- `wait()` foreign promise compatibility + + +## 1.3.0 - 2016-11-18 + +### Added + +- Adds support for custom task queues. + +### Fixed + +- Fixed coroutine promise memory leak. + + +## 1.2.0 - 2016-05-18 + +### Changed + +- Update to now catch `\Throwable` on PHP 7+ + + +## 1.1.0 - 2016-03-07 + +### Changed + +- Update EachPromise to prevent recurring on a iterator when advancing, as this + could trigger fatal generator errors. +- Update Promise to allow recursive waiting without unwrapping exceptions. + + +## 1.0.3 - 2015-10-15 + +### Changed + +- Update EachPromise to immediately resolve when the underlying promise iterator + is empty. Previously, such a promise would throw an exception when its `wait` + function was called. + + +## 1.0.2 - 2015-05-15 + +### Changed + +- Conditionally require functions.php. + + +## 1.0.1 - 2015-06-24 + +### Changed + +- Updating EachPromise to call next on the underlying promise iterator as late + as possible to ensure that generators that generate new requests based on + callbacks are not iterated until after callbacks are invoked. + + +## 1.0.0 - 2015-05-12 + +- Initial release diff --git a/vendor/guzzlehttp/promises/CLAUDE.md b/vendor/guzzlehttp/promises/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/vendor/guzzlehttp/promises/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/vendor/guzzlehttp/promises/LICENSE b/vendor/guzzlehttp/promises/LICENSE new file mode 100644 index 0000000..9f0f943 --- /dev/null +++ b/vendor/guzzlehttp/promises/LICENSE @@ -0,0 +1,24 @@ +The MIT License (MIT) + +Copyright (c) 2015 Michael Dowling +Copyright (c) 2015 Graham Campbell +Copyright (c) 2017 Tobias Schultze +Copyright (c) 2020 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/guzzlehttp/promises/README.md b/vendor/guzzlehttp/promises/README.md new file mode 100644 index 0000000..caf5334 --- /dev/null +++ b/vendor/guzzlehttp/promises/README.md @@ -0,0 +1,100 @@ +# Guzzle Promises + +`guzzlehttp/promises` is a small promise library used by Guzzle for asynchronous +operations. It implements promise chaining, synchronous waiting, cancellation, +and helpers for working with groups of promises. + +Most application developers use this package through +[`guzzlehttp/guzzle`](https://github.com/guzzle/guzzle/blob/8.0/README.md) by +calling methods such as `requestAsync()`. Install this package directly when you +need promise composition without the full HTTP client. + +## Installation + +```bash +composer require guzzlehttp/promises +``` + +## Version Guidance + +| Version | Status | PHP Version | +|---------|--------------|--------------| +| 3.2 | Latest | >=7.4,<8.7 | +| 2.6 | Maintenance | >=7.2.5,<8.7 | +| 1.5 | End of Life | >=5.5,<8.3 | + +## Quick Start + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\Utils; + +$promise = new Promise(); + +$promise->then( + function ($value) { + echo 'Fulfilled: ' . $value; + }, + function ($reason) { + echo 'Rejected: ' . $reason; + } +); + +$promise->resolve('done'); +Utils::queue()->run(); +``` + +You can wait for a promise to complete synchronously: + +```php +$value = $promise->wait(); +``` + +A promise's `getState()` describes how it was settled, not the eventual +outcome: a promise that was resolved with another promise, directly or by +returning one from a `then()` handler, reports `fulfilled` while the inner +promise may still be pending, and `wait()` can still throw if the inner +promise rejects. Poll the state only on promises settled with plain values, +or call `wait()` first (see +[guzzle/promises#101](https://github.com/guzzle/promises/issues/101)). + +When using Guzzle HTTP requests, asynchronous methods return +`GuzzleHttp\Promise\PromiseInterface` instances: + +```php +$promise = $client->requestAsync('GET', 'https://example.com'); +$response = $promise->wait(); +``` + +## Documentation + +- [Promise Quick Start](docs/promise-quick-start.md) +- [Promise API](docs/promise-api.md) +- [Promise Interoperability](docs/promise-interoperability.md) +- [Implementation Notes](docs/implementation-notes.md) +- [Upgrade Guide](UPGRADING.md) +- [Changelog](CHANGELOG.md) + +## Security + +If you discover a security vulnerability within this package, please send an +email to security@tidelift.com. All security vulnerabilities will be promptly +addressed by the security maintainers listed in the +[Security Policy](https://github.com/guzzle/promises/security/policy). Please do +not disclose security-related issues publicly until a fix has been announced. + +## License + +Guzzle is made available under the MIT License (MIT). Please see +[License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with +Tidelift to deliver commercial support and maintenance for the open source +dependencies you use to build your applications. Save time, reduce risk, and +improve code health, while paying the maintainers of the exact dependencies you +use. +[Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/vendor/guzzlehttp/promises/UPGRADING.md b/vendor/guzzlehttp/promises/UPGRADING.md new file mode 100644 index 0000000..691c588 --- /dev/null +++ b/vendor/guzzlehttp/promises/UPGRADING.md @@ -0,0 +1,279 @@ +Guzzle Promises Upgrade Guide +============================= + +2.x to 3.0 +---------- + +Guzzle Promises 3.0 is a major release that raises the minimum PHP version, +updates promise and collection helper signatures, adds generic PHPDoc types for +static analyzers, tightens collection helper inputs, improves recursive +collection behavior, and clarifies rejection inspection and late rejection +callback behavior. + +#### PHP Version and Dependencies + +Guzzle Promises 3.0 requires PHP `^7.4 || ^8.0`. Guzzle Promises 2.x supported +PHP `^7.2.5 || ^8.0`. + +If your application still supports PHP 7.2 or 7.3, continue using Guzzle +Promises 2.x until your minimum PHP version is raised. + +Guzzle Promises 3.0 has no runtime package dependencies beyond PHP. It removes +the 2.x runtime dependency on `symfony/deprecation-contracts`; require that +package directly if your application uses it. + +#### Optional Promise Resolution Values + +`PromiseInterface::resolve()` now accepts an optional value. Calling `resolve()` +without an argument fulfills the promise with `null`. + +Custom implementations of `PromiseInterface`, and subclasses that override +`resolve()` on `Promise`, `FulfilledPromise`, or `RejectedPromise`, must update +their method signature from `resolve($value): void` to +`resolve($value = null): void`. + +#### Generic PHPDoc Types + +`PromiseInterface`, `PromisorInterface`, and the built-in promise classes now +include generic PHPDoc annotations for static analysis tools. The first template +type represents the fulfillment value and the second represents the rejection +reason. This is a static-analysis-only change and does not alter runtime +behavior, but projects with stricter static analysis may see new or different +diagnostics: + +```php +use GuzzleHttp\Promise\PromiseInterface; + +/** @var PromiseInterface */ +$promise = $factory->createPromise(); + +$value = $promise->wait(); +``` + +Code that uses unparameterized promise types continues to work and is treated as +`PromiseInterface`. If your project implements promise interfaces, +extends promise classes, or has stricter static analysis, you may need to update +your PHPDoc annotations to include the generic value and reason types. The +expanded PHPDoc also preserves promise-chain fulfillment and rejection types +more precisely through `then()` and `otherwise()`, and documents collection +callbacks with value or reason, key, and aggregate-promise arguments so +callbacks may declare only the arguments they use. + +#### Collection Helper Inputs + +Promise collection helpers now require iterable inputs. Passing a single promise +or scalar value directly now throws a `TypeError`. + +Wrap single promises or values in an array before passing them to +`Create::iterFor()`, `Each::of()`, `Each::ofLimit()`, `Each::ofLimitAll()`, +`EachPromise`, or the `Utils` collection helpers. + +```php +use GuzzleHttp\Promise\Each; + +// 2.x +$promise = Each::ofLimit($singlePromise, 2); + +// 3.0 +$promise = Each::ofLimit([$singlePromise], 2); +``` + +`IteratorAggregate` inputs are now iterated via `getIterator()`. In 2.x an +aggregate was treated as a single value and produced one result; in 3.0 its +entries are consumed individually. + +```php +use GuzzleHttp\Promise\Utils; + +$aggregate = new \ArrayObject([$promiseA, $promiseB]); + +// 2.x: one result — the ArrayObject itself +// 3.0: two results — the fulfillment values of $promiseA and $promiseB +$promise = Utils::all($aggregate); +``` + +#### Collection Helper Signatures + +`Utils::all()`, `Utils::settle()`, and `Each::of()` now accept trailing optional +arguments. Direct calls using the 2.x argument lists continue to work, and the +affected helper classes are final so subclass signatures do not need to change. +Code that mirrors or reflects exact helper signatures may need to be updated. + +Pass the recursive flag before the config array when using `Utils::all()` or +`Utils::settle()`: + +```php +use GuzzleHttp\Promise\Utils; + +$promise = Utils::all($promises, false, ['concurrency' => 5]); +$promise = Utils::settle($promises, false, ['concurrency' => 5]); +``` + +Only `concurrency` is honored by these helper config arrays. Callback config +keys such as `fulfilled` and `rejected` are ignored; pass callbacks to +`Each::of()` directly or use `EachPromise`. + +#### Recursive Collection Helpers + +Existing `Utils::all($promises, true)` calls may return different results in +3.0. Recursive mode now detects dynamically-added settled promises and raw +values. In 2.x, recursive mode only checked for pending promises. + +If you previously worked around the lack of recursive `Utils::settle()` support, +you can replace that workaround with the new `$recursive` argument: + +```php +use GuzzleHttp\Promise\Utils; + +$promise = Utils::settle($promises, true); +``` + +When `$recursive` is true, collection helpers continue taking passes over the +collection until no new entries are found and no visible promises remain +pending. This is intended for rewindable mutable collections such as +`ArrayIterator`. Generators are safe to pass, but they cannot be traversed +again once consumed, so recursive mode degrades to a single pass; use a +rewindable mutable collection when recursion needs to observe added values. + +#### Promise Inspection + +`Utils::inspect()` and `Utils::inspectAll()` now return the actual rejection +reason delivered to rejection callbacks. They no longer unwrap +`RejectionException` instances to their inner reason. + +For example, a promise rejected with a `RejectionException` now inspects with +that exception as the reason: + +```php +use GuzzleHttp\Promise\RejectedPromise; +use GuzzleHttp\Promise\RejectionException; +use GuzzleHttp\Promise\Utils; + +$reason = new RejectionException('reason'); +$result = Utils::inspect(new RejectedPromise($reason)); + +assert($result['reason'] === $reason); +``` + +Cancelled promises now inspect with a `CancellationException` reason. If you +need the string reason from a `RejectionException` or subclass, call +`getReason()` on the exception. + +`Utils::inspect()` still reports wait-function failures as rejection reasons +when the wait function does not settle the promise. If the wait function +settles the promise and then throws, `inspect()` reports the settled +fulfillment or rejection state; direct `Promise::wait()` calls continue to +throw that late exception. + +#### Late Rejection Callbacks + +Rejection callbacks registered after a promise was resolved with a rejected +promise are now invoked with the nested rejection reason. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; +use GuzzleHttp\Promise\Utils; + +$promise = new Promise(); +$promise->resolve(new RejectedPromise('reason')); + +$promise->then(null, function ($reason): void { + assert($reason === 'reason'); +}); + +Utils::queue()->run(); +``` + +#### Non-instantiable Helper Classes + +Static helper classes such as `Create`, `Each`, `Is`, and `Utils` now have +private constructors. Replace any accidental instantiation with static method +calls. + +#### Native PHP Serialization of Runtime Objects + +`Promise`, `TaskQueue`, `EachPromise`, and `Coroutine` no longer support native +PHP `serialize()` or `unserialize()`. Persist application values instead of +promise runtime state. + +1.x to 2.0 +---------- + +Guzzle Promises 2.0 is a major release that removes deprecated APIs, raises the +minimum PHP version, and adds PHP 7 parameter and return types. Applications that +only use the object-oriented API should usually need small changes. Applications +that call helper functions, implement package interfaces, extend package classes, +or pass invalid argument types need closer review. + +#### PHP Version and Dependencies + +Guzzle Promises 2.0 requires PHP `^7.2.5 || ^8.0`. Guzzle Promises 1.x +supported PHP `>=5.5`. + +#### PHP 7 Type Hints and Return Types + +Type hints and return types were added wherever possible. Please make sure: + +- You pass values of the documented type when calling methods and functions. +- Classes that implement `PromiseInterface`, `PromisorInterface`, or + `TaskQueueInterface` update method signatures to remain compatible. +- Classes that extend Guzzle Promises classes update any overridden method + signatures to remain compatible. +- Code that expected package-specific exceptions for invalid argument types may + now receive PHP `TypeError` exceptions instead. + +#### Soft-Final Classes + +All previously non-final non-exception classes are now final or annotated with +`@final`. If your code extends one of these classes, replace inheritance with +composition or implement the relevant interface directly. + +#### Removed Function API + +The static API was introduced in 1.4.0 to mitigate problems with functions +conflicting between global and local copies of the package. The function API was +removed in 2.0.0, along with the Composer `files` autoload entry that loaded +`src/functions_include.php`. + +Replace namespaced function calls with the corresponding static methods in the +`GuzzleHttp\Promise` namespace: + +```php +// Before: +use function GuzzleHttp\Promise\promise_for; + +$promise = promise_for('value'); + +// After: +use GuzzleHttp\Promise\Create; + +$promise = Create::promiseFor('value'); +``` + +| Original Function | Replacement Method | +|-------------------|--------------------| +| `queue` | `Utils::queue` | +| `task` | `Utils::task` | +| `promise_for` | `Create::promiseFor` | +| `rejection_for` | `Create::rejectionFor` | +| `exception_for` | `Create::exceptionFor` | +| `iter_for` | `Create::iterFor` | +| `inspect` | `Utils::inspect` | +| `inspect_all` | `Utils::inspectAll` | +| `unwrap` | `Utils::unwrap` | +| `all` | `Utils::all` | +| `some` | `Utils::some` | +| `any` | `Utils::any` | +| `settle` | `Utils::settle` | +| `each` | `Each::of` | +| `each_limit` | `Each::ofLimit` | +| `each_limit_all` | `Each::ofLimitAll` | +| `!is_fulfilled` | `Is::pending` | +| `is_fulfilled` | `Is::fulfilled` | +| `is_rejected` | `Is::rejected` | +| `is_settled` | `Is::settled` | +| `coroutine` | `Coroutine::of` | + +For the full 2.0 diff, see +https://github.com/guzzle/promises/compare/1.5.3...2.0.0. diff --git a/vendor/guzzlehttp/promises/composer.json b/vendor/guzzlehttp/promises/composer.json new file mode 100644 index 0000000..eef7556 --- /dev/null +++ b/vendor/guzzlehttp/promises/composer.json @@ -0,0 +1,61 @@ +{ + "name": "guzzlehttp/promises", + "description": "Guzzle promises library", + "license": "MIT", + "keywords": [ + "promise" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.4 || ^8.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^9.6.34" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Promise\\Tests\\": "tests/" + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + } +} diff --git a/vendor/guzzlehttp/promises/docs/implementation-notes.md b/vendor/guzzlehttp/promises/docs/implementation-notes.md new file mode 100644 index 0000000..8e4071c --- /dev/null +++ b/vendor/guzzlehttp/promises/docs/implementation-notes.md @@ -0,0 +1,72 @@ +# Implementation Notes + +This document describes implementation details that explain observable behavior +in `guzzlehttp/promises`, especially queue-based callback execution, iterative +resolution, and why `Promise` also acts as the deferred value. Application code +usually only needs the [Promise Quick Start](promise-quick-start.md) and +[Promise API](promise-api.md). + +## Iterative Resolution and Chaining + +Promises are resolved iteratively by moving pending handlers between promises. +This keeps stack size constant even for very long `then()` chains. + +```php +then(function ($v) { + // The stack size remains constant. + echo xdebug_get_stack_depth() . ', '; + return $v + 1; + }); +} + +$parent->resolve(0); +var_dump($p->wait()); // int(1000) + +``` + +When a promise is fulfilled or rejected with a non-promise value, the promise +takes ownership of each child promise's handlers and delivers values down the +chain without recursion. + +When a promise is resolved with another promise, the original promise transfers +all of its pending handlers to the new promise. When the new promise is +eventually resolved, all pending handlers receive the forwarded +value. + +## A Promise Is the Deferred + +Some promise libraries implement promises using a deferred object to represent +a computation and a promise object to represent the delivery of the result of +the computation. That separation prevents consumers from modifying the value +that will eventually be delivered. + +Iterative resolution requires one promise to move handlers from another promise. +To do that without making handlers publicly mutable, `Promise` is also the +deferred value. Promises of the same class can modify each other's private +state, including handler ownership. This means a consumer that receives a +`Promise` can also resolve or reject it, but it keeps chaining efficient and +stack safe. + +```php +$promise = new Promise(); +$promise->then(function ($value) { echo $value; }); +// The promise is the deferred value, so you can deliver a value to it. +$promise->resolve('foo'); +GuzzleHttp\Promise\Utils::queue()->run(); +// Prints "foo" +``` + +## Related + +- [Quick Start](promise-quick-start.md) +- [Promise API](promise-api.md) +- [Promise Interoperability](promise-interoperability.md) diff --git a/vendor/guzzlehttp/promises/docs/promise-api.md b/vendor/guzzlehttp/promises/docs/promise-api.md new file mode 100644 index 0000000..df8ab66 --- /dev/null +++ b/vendor/guzzlehttp/promises/docs/promise-api.md @@ -0,0 +1,177 @@ +# Promise API + +This reference summarizes the public API provided by `guzzlehttp/promises`. +Promise APIs are documented for static analysis as +`PromiseInterface`. `TValue` is the fulfillment value type and +`TReason` is the rejection reason type. This typing is PHPDoc-only and does not +change runtime behavior. + +Callbacks registered with `then()` are queued. They are invoked when the global +task queue runs, when a returned promise is waited on, or when the queue is +drained by the default shutdown handler. + +## PromiseInterface and Promise + +`PromiseInterface` defines the common promise contract and the states +`pending`, `fulfilled`, and `rejected`. + +When creating a `Promise`, you can provide an optional `$waitFn` and +`$cancelFn`. `$waitFn` receives a boolean argument and is expected to resolve or +reject the promise. `$cancelFn` receives no arguments and is invoked when +`cancel()` is called. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise( + function (bool $recursive) use (&$promise) { + $promise->resolve('waited'); + }, + function () { + // Cancel the underlying operation, such as closing a socket. + } +); + +assert('waited' === $promise->wait()); +``` + +A promise has the following methods: + +- `then(?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface` appends fulfillment and rejection handlers and returns a new promise resolving to the return value of the called handler. If a handler is omitted, the original fulfillment value or rejection reason is forwarded. +- `otherwise(callable $onRejected) : PromiseInterface` appends a rejection handler and returns a new promise resolving to the callback result if called, or to the original fulfillment value if the promise is fulfilled. +- `wait(bool $unwrap = true) : mixed` synchronously waits on the promise. When `$unwrap` is `true`, fulfilled values are returned and rejected reasons are thrown. When `$unwrap` is `false`, the promise is settled without returning or throwing its result. +- `cancel() : void` attempts to cancel the promise and dependent promises. +- `getState() : string` returns `pending`, `fulfilled`, or `rejected`. +- `resolve($value = null) : void` fulfills the promise with `$value`, or with `null` if no value is given. +- `reject($reason) : void` rejects the promise with `$reason`. + +## Settled Promises + +`FulfilledPromise` represents an already fulfilled promise. Fulfillment +callbacks are still queued and run when the task queue runs or the returned +promise is waited on. + +```php +use GuzzleHttp\Promise\FulfilledPromise; +use GuzzleHttp\Promise\Utils; + +$promise = new FulfilledPromise('value'); +$promise->then(function ($value) { + echo $value; +}); + +Utils::queue()->run(); +``` + +`RejectedPromise` represents an already rejected promise. Rejection callbacks +are also queued and run when the queue is drained or the returned promise is +waited on. + +```php +use GuzzleHttp\Promise\RejectedPromise; +use GuzzleHttp\Promise\Utils; + +$promise = new RejectedPromise('Error'); +$promise->then(null, function ($reason) { + echo $reason; +}); + +Utils::queue()->run(); +``` + +## Utils + +`GuzzleHttp\Promise\Utils` provides helpers for inspecting, aggregating, and +queuing promise work. + +- `Utils::queue(?TaskQueueInterface $assign = null) : TaskQueueInterface` returns the global task queue, or assigns a replacement queue when `$assign` is provided. +- `Utils::task(callable $task) : PromiseInterface` adds a task to the global queue and returns a promise that is fulfilled or rejected with the task result. +- `Utils::inspect(PromiseInterface $promise) : array` waits for one promise to settle and returns an inspection array with `state` and either `value` or `reason`. +- `Utils::inspectAll(iterable $promises) : array` inspects each promise and returns inspection arrays keyed like the input iterable. +- `Utils::unwrap(iterable $promises) : array` waits on all promises and returns fulfilled values, throwing if any promise rejects. +- `Utils::all(iterable $promises, bool $recursive = false, array $config = []) : PromiseInterface` returns a promise fulfilled with all values, or rejected when any input rejects. +- `Utils::settle(iterable $promises, bool $recursive = false, array $config = []) : PromiseInterface` returns a promise fulfilled with inspection arrays after all inputs settle. +- `Utils::some(int $count, iterable $promises) : PromiseInterface` fulfills with the values of the first `$count` promises to fulfill, in the order they appear in the input, or rejects with `AggregateException` if too few fulfill. +- `Utils::any(iterable $promises) : PromiseInterface` fulfills with the first fulfilled value, or rejects with `AggregateException` if none fulfill. + +`Utils::all()` and `Utils::settle()` accept `['concurrency' => 5]` or +`['concurrency' => callable]` for lazy iterables. This limits how many items are +pulled from the iterable at one time; it does not throttle promises that have +already been created or started. + +```php +use GuzzleHttp\Promise\Utils; + +$promise = Utils::all($promises, false, ['concurrency' => 5]); +``` + +## Create + +`GuzzleHttp\Promise\Create` provides factories used by the promise +implementation and by callers that need to normalize values. + +- `Create::promiseFor($value) : PromiseInterface` returns `$value` when it is already a Guzzle promise, wraps foreign thenables in a Guzzle promise, or returns a fulfilled promise for plain values. +- `Create::rejectionFor($reason) : PromiseInterface` returns `$reason` when it is already a promise, or returns a rejected promise for plain reasons. +- `Create::exceptionFor($reason) : Throwable` returns throwable reasons as-is, or wraps non-throwable reasons in `RejectionException`. +- `Create::iterFor(iterable $value) : Iterator` returns an iterator for arrays, iterators, iterator aggregates, and traversables. + +## State + +`GuzzleHttp\Promise\State` provides readable state checks: + +- `State::isPending(PromiseInterface $promise) : bool` +- `State::isSettled(PromiseInterface $promise) : bool` +- `State::isFulfilled(PromiseInterface $promise) : bool` +- `State::isRejected(PromiseInterface $promise) : bool` + +`GuzzleHttp\Promise\Is` is deprecated because PHP 8.6 deprecates `is` as a class +name, and will be removed in Guzzle Promises 4.0. Replace `Is::pending()`, +`Is::settled()`, `Is::fulfilled()`, and `Is::rejected()` with the matching +`State` methods. + +## Each and EachPromise + +`Each::of()` consumes an iterable of promises or values and invokes callbacks as +items settle. Fulfillment callbacks receive the fulfilled value, iterable key, +and aggregate promise. Rejection callbacks receive the rejection reason, +iterable key, and aggregate promise. Callback return values are ignored. + +```php +use GuzzleHttp\Promise\Each; + +$promise = Each::of($promises, $onFulfilled, $onRejected, ['concurrency' => 5]); +``` + +- `Each::of(iterable $iterable, ?callable $onFulfilled = null, ?callable $onRejected = null, array $config = []) : PromiseInterface` consumes the iterable and optionally limits lazy iteration with `concurrency`. +- `Each::ofLimit(iterable $iterable, $concurrency, ?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface` is a convenience wrapper for `Each::of()` with a concurrency limit. +- `Each::ofLimitAll(iterable $iterable, $concurrency, ?callable $onFulfilled = null) : PromiseInterface` is like `ofLimit()`, but rejects the aggregate promise on the first rejection. +- `EachPromise` is the configurable class behind `Each`; use it directly when you need `fulfilled`, `rejected`, and `concurrency` keys in one configuration array. + +The concurrency options limit lazy promise creation. For HTTP request +concurrency, use `GuzzleHttp\Pool` from `guzzlehttp/guzzle`. + +## Coroutine + +`Coroutine::of(callable $generatorFn) : Coroutine` creates a promise resolved by +a generator that yields values or promises. The generator resumes with each +fulfilled value, and rejections are thrown into the generator. + +## Task Queue + +`TaskQueueInterface` exposes `isEmpty()`, `add(callable $task)`, and `run()`. +`TaskQueue` executes queued tasks in FIFO order. The default queue runs at +process shutdown unless disabled, and `wait()` drains the queue while resolving +the promise being waited on. + +## Exceptions + +- `RejectionException` is thrown by `wait()` when a rejected promise has a non-throwable reason. The original reason is available through `getReason()`. +- `AggregateException` extends `RejectionException` and is used by `Utils::some()` and `Utils::any()` when too few promises fulfill. +- `CancellationException` extends `RejectionException` and is used as the rejection reason for cancelled promises. + +## Related + +- [Quick Start](promise-quick-start.md) +- [Promise Interoperability](promise-interoperability.md) +- [Implementation Notes](implementation-notes.md) +- [Upgrade Guide](../UPGRADING.md) diff --git a/vendor/guzzlehttp/promises/docs/promise-interoperability.md b/vendor/guzzlehttp/promises/docs/promise-interoperability.md new file mode 100644 index 0000000..85cdc15 --- /dev/null +++ b/vendor/guzzlehttp/promises/docs/promise-interoperability.md @@ -0,0 +1,78 @@ +# Promise Interoperability + +This guide explains how Guzzle promises interact with foreign promise +implementations. A foreign promise is any object with a `then` method, such as a +[React promise](https://github.com/reactphp/promise). When a foreign promise is +returned from a `then` callback, Guzzle forwards resolution to that promise. + +## Foreign Promises + +Capture the promise returned from `then()`. That chained promise is the Guzzle +promise that follows the foreign promise's eventual result. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\Utils; + +$deferred = new React\Promise\Deferred(); +$reactPromise = $deferred->promise(); + +$guzzlePromise = new Promise(); +$chained = $guzzlePromise->then(function ($value) use ($reactPromise) { + // Use the Guzzle value, then continue with the React promise. + return $reactPromise; +}); + +$chained->then(function ($value) { + echo $value; +}); + +$guzzlePromise->resolve('start'); +Utils::queue()->run(); + +$deferred->resolve('done'); +Utils::queue()->run(); +``` + +Forwarding a foreign promise does not make Guzzle able to synchronously wait on +or cancel the foreign operation. The chained Guzzle promise settles only after +the foreign implementation invokes the callbacks registered through `then()`. +If the foreign promise has no compatible `wait()` or `cancel()` behavior, Guzzle +cannot invent that behavior. + +Use `Create::promiseFor($foreignPromise)` to shadow a foreign thenable as a +Guzzle promise. If the foreign object exposes `wait()` or `cancel()` methods, +the wrapper uses them. Otherwise, use the foreign implementation's event loop or +completion mechanism and drain Guzzle's task queue when callbacks need to run. + +## Event Loop Integration + +Guzzle promises use a task queue to keep stack size constant and to run promise +callbacks asynchronously. When waiting on promises synchronously, the task queue +is automatically run while resolving the blocking promise and forwarded Guzzle +promises. + +When using promises asynchronously in an event loop, run the task queue on loop +ticks. If you do not run the task queue, Guzzle promise callbacks may remain +queued. + +```php +$queue = GuzzleHttp\Promise\Utils::queue(); +$queue->run(); +``` + +For example, you could use Guzzle promises with React using a short periodic +timer. Avoid zero-interval timers because they may keep the loop busy even when +there is no promise work to run. + +```php +$queue = GuzzleHttp\Promise\Utils::queue(); +$loop = React\EventLoop\Factory::create(); +$loop->addPeriodicTimer(0.01, [$queue, 'run']); +``` + +## Related + +- [Quick Start](promise-quick-start.md) +- [Promise API](promise-api.md) +- [Implementation Notes](implementation-notes.md) diff --git a/vendor/guzzlehttp/promises/docs/promise-quick-start.md b/vendor/guzzlehttp/promises/docs/promise-quick-start.md new file mode 100644 index 0000000..07a60e5 --- /dev/null +++ b/vendor/guzzlehttp/promises/docs/promise-quick-start.md @@ -0,0 +1,319 @@ +# Promise Quick Start + +This guide covers the common promise operations needed when using +`guzzlehttp/promises` directly: registering callbacks, resolving or rejecting +promises, waiting synchronously, composing chains, and using generator-based +flows. For the full public surface, see the [Promise API](promise-api.md). + +A *promise* represents the eventual result of an asynchronous operation. The +primary way of interacting with a promise is through its `then` method, which +registers callbacks to receive either the eventual value or the reason why the +promise cannot be fulfilled. + +Guzzle promise callbacks are queued. They run when the task queue is drained, +for example by `Utils::queue()->run()`, by waiting on a returned promise, or by +the default shutdown handler at the end of the PHP process. Examples that show +callback output drain the queue explicitly. + +## Callbacks + +Callbacks are registered with the `then` method by providing an optional +`$onFulfilled` followed by an optional `$onRejected` function. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then( + // $onFulfilled + function ($value) { + echo 'The promise was fulfilled.'; + }, + // $onRejected + function ($reason) { + echo 'The promise was rejected.'; + } +); +``` + +*Resolving* a promise means that you either fulfill a promise with a *value* or +reject a promise with a *reason*. Callbacks registered with `then` are invoked +only once and in the order in which they were added when the queue is drained. + +## Resolving a Promise + +Promises are fulfilled using the `resolve($value = null)` method. Calling +`resolve()` without an argument fulfills the promise with `null`. Resolving a +promise with any value other than a `GuzzleHttp\Promise\RejectedPromise` queues +the `$onFulfilled` callbacks. Resolving with a rejected promise rejects the +promise and queues the `$onRejected` callbacks. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\Utils; + +$promise = new Promise(); +$promise + ->then(function ($value) { + return 'Hello, ' . $value; + }) + ->then(function ($value) { + echo $value; + }); + +$promise->resolve('reader.'); +Utils::queue()->run(); +// Outputs "Hello, reader." +``` + +## Promise Forwarding + +Promises can be chained one after the other. Each `then` call returns a new +promise. The return value of a callback is forwarded to the next promise in the +chain. Returning a promise from a callback makes the next promise wait for that +returned promise to settle. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\Utils; + +$promise = new Promise(); +$nextPromise = new Promise(); + +$promise + ->then(function ($value) use ($nextPromise) { + echo $value; + + return $nextPromise; + }) + ->then(function ($value) { + echo $value; + }); + +$promise->resolve('A'); +Utils::queue()->run(); +// Outputs "A" + +$nextPromise->resolve('B'); +Utils::queue()->run(); +// Outputs "B" +``` + +## Promise Rejection + +When a promise is rejected, the `$onRejected` callbacks are invoked with the +rejection reason when the queue is drained. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\Utils; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + echo $reason; +}); + +$promise->reject('Error!'); +Utils::queue()->run(); +// Outputs "Error!" +``` + +## Rejection Forwarding + +If an exception is thrown in an `$onRejected` callback, subsequent +`$onRejected` callbacks receive the thrown exception as the reason. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\Utils; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + throw new Exception($reason); +})->then(null, function ($reason) { + assert($reason->getMessage() === 'Error!'); +}); + +$promise->reject('Error!'); +Utils::queue()->run(); +``` + +You can also forward a rejection down the promise chain by returning a +`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or +`$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; +use GuzzleHttp\Promise\Utils; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + return new RejectedPromise($reason); +})->then(null, function ($reason) { + assert($reason === 'Error!'); +}); + +$promise->reject('Error!'); +Utils::queue()->run(); +``` + +If an exception is not thrown in an `$onRejected` callback and the callback +does not return a rejected promise, downstream `$onFulfilled` callbacks are +invoked using the value returned from the `$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\Utils; + +$promise = new Promise(); +$promise + ->then(null, function ($reason) { + return "It's ok"; + }) + ->then(function ($value) { + assert($value === "It's ok"); + }); + +$promise->reject('Error!'); +Utils::queue()->run(); +``` + +## Synchronous Wait + +You can synchronously force promises to complete using a promise's `wait` +method. When creating a promise, you can provide a wait function that is used +to synchronously complete the promise. The wait function receives a boolean +argument and is expected to resolve or reject the promise. If the wait function +does not settle the promise, an exception is thrown. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(function (bool $recursive) use (&$promise) { + $promise->resolve('foo'); +}); + +echo $promise->wait(); +// Outputs "foo" +``` + +If a throwable is encountered while invoking the wait function of a promise, +the promise is rejected with the throwable and the throwable is thrown. + +```php +$promise = new Promise(function (bool $recursive) use (&$promise) { + throw new Exception('foo'); +}); + +$promise->wait(); // Throws the exception. +``` + +Calling `wait` on a promise that has been fulfilled will not trigger the wait +function. It will simply return the previously resolved value. + +```php +$promise = new Promise(function (bool $recursive) { die('this is not called!'); }); +$promise->resolve('foo'); + +echo $promise->wait(); +// Outputs "foo" +``` + +Calling `wait` on a promise that has been rejected will throw. If the rejection +reason is an instance of `\Throwable`, the reason is thrown. Otherwise, a +`GuzzleHttp\Promise\RejectionException` is thrown and the reason can be +obtained by calling `getReason()` on the exception. + +```php +$promise = new Promise(); +$promise->reject('foo'); +$promise->wait(); +``` + +> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with reason: foo' + +## Unwrapping a Promise + +When synchronously waiting on a promise, you are joining the state of the +promise into the current execution: the fulfilled value is returned, or the +rejection reason is thrown. This is called "unwrapping" the promise. Waiting on +a promise unwraps by default. + +You can force a promise to resolve and *not* unwrap its state by passing +`false` to `wait()`: + +```php +$promise = new Promise(); +$promise->reject('foo'); + +// This does not throw. It only ensures the promise has been resolved. +$promise->wait(false); +``` + +When unwrapping a promise, the resolved value of the promise will be waited on +until the unwrapped value is not a promise. This means that if promise A is +resolved with promise B, unwrapping promise A returns the value delivered to +promise B. + +When you do not unwrap the promise, no value is returned. + +## Inspecting a Promise + +`Utils::inspect($promise)` waits for a promise to settle and returns an array +describing its final state. For rejected promises, the `reason` entry is the +actual rejection reason delivered to rejection callbacks. + +This means `RejectionException` and subclasses are not unwrapped by +`inspect()`. For example, cancelled promises inspect with a +`CancellationException` reason. + +## Generator-Based Async + +`Coroutine::of()` creates a promise from a generator that yields values or +promises. The generator resumes each time the yielded value settles, which can +make sequential asynchronous flows easier to read. + +```php +use GuzzleHttp\Promise\Coroutine; +use GuzzleHttp\Promise\FulfilledPromise; + +$promise = Coroutine::of(function () { + $first = yield new FulfilledPromise('A'); + $second = yield new FulfilledPromise($first . 'B'); + + yield $second . 'C'; +}); + +echo $promise->wait(); +// Outputs "ABC" +``` + +If a yielded promise rejects, the rejection is thrown into the generator. Catch +it inside the generator to recover, or let it reject the coroutine promise. + +## Cancellation + +You can cancel a promise that has not yet been fulfilled using `cancel()`. When +creating a promise, you can provide an optional cancel function that cancels the +underlying operation, such as closing a socket or aborting a query. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(null, function () { + // Cancel the underlying operation. +}); + +$promise->cancel(); +``` + +Cancellation rejects the promise with a `CancellationException` unless the +cancel function settles the promise first. + +## Related + +- [Promise API](promise-api.md) +- [Promise Interoperability](promise-interoperability.md) +- [Implementation Notes](implementation-notes.md) +- [Upgrade Guide](../UPGRADING.md) diff --git a/vendor/guzzlehttp/promises/src/AggregateException.php b/vendor/guzzlehttp/promises/src/AggregateException.php new file mode 100644 index 0000000..40ffdbc --- /dev/null +++ b/vendor/guzzlehttp/promises/src/AggregateException.php @@ -0,0 +1,19 @@ +then(function ($v) { echo $v; }); + * + * @template TValue = mixed + * @template TReason = mixed + * + * @implements PromiseInterface + * + * @see https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration + */ +final class Coroutine implements PromiseInterface +{ + use NonSerializableTrait; + + /** + * @var PromiseInterface|null + */ + private ?PromiseInterface $currentPromise = null; + + /** + * @var Generator + */ + private Generator $generator; + + /** + * @var Promise + */ + private PromiseInterface $result; + + /** + * @param callable(): Generator $generatorFn + */ + public function __construct(callable $generatorFn) + { + $this->generator = $generatorFn(); + $this->result = new Promise(function (): void { + while (isset($this->currentPromise)) { + $this->currentPromise->wait(); + } + }, function (): void { + if (isset($this->currentPromise)) { + $this->currentPromise->cancel(); + } + }); + try { + $this->nextCoroutine($this->generator->current()); + } catch (\Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * Create a new coroutine. + * + * @param callable(): Generator $generatorFn + * + * @return self + */ + public static function of(callable $generatorFn): self + { + return new self($generatorFn); + } + + /** + * @template TFulfilledValue = never + * @template TFulfilledReason = never + * @template TRejectedValue = never + * @template TRejectedReason = never + * + * @param (callable(TValue): (TFulfilledValue|PromiseInterface))|null $onFulfilled Invoked when the promise fulfills. + * @param (callable(TReason): (TRejectedValue|PromiseInterface))|null $onRejected Invoked when the promise is rejected. + * + * @return PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)> + */ + public function then( + ?callable $onFulfilled = null, + ?callable $onRejected = null + ): PromiseInterface { + return $this->result->then($onFulfilled, $onRejected); + } + + /** + * @template TRejectedValue = never + * @template TRejectedReason = never + * + * @param callable(TReason): (TRejectedValue|PromiseInterface) $onRejected Invoked when the promise is rejected. + * + * @return PromiseInterface + */ + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->result->otherwise($onRejected); + } + + public function wait(bool $unwrap = true) + { + return $this->result->wait($unwrap); + } + + public function getState(): string + { + return $this->result->getState(); + } + + public function resolve($value = null): void + { + $this->result->resolve($value); + } + + public function reject($reason): void + { + $this->result->reject($reason); + } + + public function cancel(): void + { + if (isset($this->currentPromise)) { + $this->currentPromise->cancel(); + } + + $this->result->cancel(); + } + + private function nextCoroutine($yielded): void + { + $this->currentPromise = Create::promiseFor($yielded) + ->then([$this, '_handleSuccess'], [$this, '_handleFailure']); + } + + /** + * @internal + */ + public function _handleSuccess($value): void + { + $this->currentPromise = null; + + try { + $next = $this->generator->send($value); + if ($this->generator->valid()) { + $this->nextCoroutine($next); + } else { + $this->result->resolve($value); + } + } catch (\Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * @internal + */ + public function _handleFailure($reason): void + { + $this->currentPromise = null; + + try { + $nextYield = $this->generator->throw(Create::exceptionFor($reason)); + // The throw was caught, so keep iterating on the coroutine + $this->nextCoroutine($nextYield); + } catch (\Throwable $throwable) { + $this->result->reject($throwable); + } + } +} diff --git a/vendor/guzzlehttp/promises/src/Create.php b/vendor/guzzlehttp/promises/src/Create.php new file mode 100644 index 0000000..cdeee83 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/Create.php @@ -0,0 +1,117 @@ + = PromiseInterface + * + * @param TValue|TPromise $value Promise or value. + * + * @return ($value is PromiseInterface ? TPromise : FulfilledPromise) + */ + public static function promiseFor($value): PromiseInterface + { + if ($value instanceof PromiseInterface) { + return $value; + } + + // Return a Guzzle promise that shadows the given promise. + if (is_object($value) && method_exists($value, 'then')) { + $wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null; + $cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null; + $promise = new Promise($wfn, $cfn); + try { + $value->then([$promise, 'resolve'], [$promise, 'reject']); + } catch (\Throwable $e) { + if (State::isPending($promise)) { + // The thenable may still hold the callbacks. + $promise = new Promise(); + $promise->reject($e); + } + } + + return $promise; + } + + return new FulfilledPromise($value); + } + + /** + * Returns `$reason` when it is already a promise, or returns a rejected + * promise for plain reasons. + * + * @template TReason + * @template TValue = never + * @template TPromise of PromiseInterface = PromiseInterface + * + * @param TReason|TPromise $reason Promise or reason. + * + * @return ($reason is PromiseInterface ? TPromise : RejectedPromise) + */ + public static function rejectionFor($reason): PromiseInterface + { + if ($reason instanceof PromiseInterface) { + return $reason; + } + + return new RejectedPromise($reason); + } + + /** + * Returns throwable reasons as-is, or wraps non-throwable reasons in + * `RejectionException`. + * + * @template TReason + * + * @param TReason $reason + */ + public static function exceptionFor($reason): \Throwable + { + if ($reason instanceof \Throwable) { + return $reason; + } + + return new RejectionException($reason); + } + + /** + * Returns an iterator for arrays, iterators, iterator aggregates, and + * traversables. + * + * @template TKey of array-key + * @template TValue + * + * @param iterable $value + * + * @return \Iterator + */ + public static function iterFor(iterable $value): \Iterator + { + if ($value instanceof \Iterator) { + return $value; + } + + if (is_array($value)) { + return new \ArrayIterator($value); + } + + if ($value instanceof \IteratorAggregate) { + return self::iterFor($value->getIterator()); + } + + return new \IteratorIterator($value); + } +} diff --git a/vendor/guzzlehttp/promises/src/Each.php b/vendor/guzzlehttp/promises/src/Each.php new file mode 100644 index 0000000..0a9e50a --- /dev/null +++ b/vendor/guzzlehttp/promises/src/Each.php @@ -0,0 +1,118 @@ +> $iterable Iterator or array to iterate over. + * @param (callable(TValue, TKey, PromiseInterface): mixed)|null $onFulfilled + * @param (callable(TReason, TKey, PromiseInterface): mixed)|null $onRejected + * @param array{concurrency?: int|(callable(int): int)} $config Configuration options. + * + * @return PromiseInterface + */ + public static function of( + iterable $iterable, + ?callable $onFulfilled = null, + ?callable $onRejected = null, + array $config = [] + ): PromiseInterface { + $eachConfig = []; + + if (null !== $onFulfilled) { + $eachConfig['fulfilled'] = $onFulfilled; + } + + if (null !== $onRejected) { + $eachConfig['rejected'] = $onRejected; + } + + if (isset($config['concurrency'])) { + $eachConfig['concurrency'] = $config['concurrency']; + } + + return (new EachPromise($iterable, $eachConfig))->promise(); + } + + /** + * Like of, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow + * for a dynamic concurrency size. + * + * @template TKey of array-key + * @template TValue + * @template TReason + * + * @param iterable> $iterable + * @param int|(callable(int): int) $concurrency + * @param (callable(TValue, TKey, PromiseInterface): mixed)|null $onFulfilled + * @param (callable(TReason, TKey, PromiseInterface): mixed)|null $onRejected + * + * @return PromiseInterface + */ + public static function ofLimit( + iterable $iterable, + $concurrency, + ?callable $onFulfilled = null, + ?callable $onRejected = null + ): PromiseInterface { + return self::of($iterable, $onFulfilled, $onRejected, ['concurrency' => $concurrency]); + } + + /** + * Like ofLimit, but rejects the aggregate promise on the first rejection. + * + * @template TKey of array-key + * @template TValue + * @template TReason + * + * @param iterable> $iterable + * @param int|(callable(int): int) $concurrency + * @param (callable(TValue, TKey, PromiseInterface): mixed)|null $onFulfilled + * + * @return PromiseInterface + */ + public static function ofLimitAll( + iterable $iterable, + $concurrency, + ?callable $onFulfilled = null + ): PromiseInterface { + return self::ofLimit( + $iterable, + $concurrency, + $onFulfilled, + function ($reason, $idx, PromiseInterface $aggregate): void { + $aggregate->reject($reason); + } + ); + } +} diff --git a/vendor/guzzlehttp/promises/src/EachPromise.php b/vendor/guzzlehttp/promises/src/EachPromise.php new file mode 100644 index 0000000..e84bd8f --- /dev/null +++ b/vendor/guzzlehttp/promises/src/EachPromise.php @@ -0,0 +1,295 @@ + + * + * @final + */ +class EachPromise implements PromisorInterface +{ + use NonSerializableTrait; + + /** @var array>|null */ + private ?array $pending = []; + + private int $nextPendingIndex = 0; + + /** @var \Iterator>|null */ + private ?\Iterator $iterable; + + /** @var (callable(int): int)|int|null */ + private $concurrency; + + /** @var (callable(TValue, TKey, PromiseInterface): mixed)|null */ + private $onFulfilled; + + /** @var (callable(TReason, TKey, PromiseInterface): mixed)|null */ + private $onRejected; + + /** @var Promise|null */ + private ?Promise $aggregate = null; + + private ?bool $mutex = null; + + private bool $stepWhileLocked = false; + + /** + * Configuration hash can include the following key value pairs: + * + * - fulfilled: (callable) Invoked when a promise fulfills. The function + * is invoked with three arguments: the fulfillment value, the index + * position from the iterable list of the promise, and the aggregate + * promise that manages all of the promises. The aggregate promise may + * be resolved from within the callback to short-circuit the promise. + * - rejected: (callable) Invoked when a promise is rejected. The + * function is invoked with three arguments: the rejection reason, the + * index position from the iterable list of the promise, and the + * aggregate promise that manages all of the promises. The aggregate + * promise may be resolved from within the callback to short-circuit + * the promise. + * - concurrency: (integer) Pass this configuration option to limit the + * allowed number of outstanding concurrently executing promises, + * creating a capped pool of promises. There is no limit by default. + * + * @param iterable> $iterable Promises or values to iterate. + * @param array{ + * fulfilled?: callable(TValue, TKey, PromiseInterface): mixed, + * rejected?: callable(TReason, TKey, PromiseInterface): mixed, + * concurrency?: int|(callable(int): int) + * } $config Configuration options + */ + public function __construct(iterable $iterable, array $config = []) + { + $this->iterable = Create::iterFor($iterable); + + if (isset($config['concurrency'])) { + $this->concurrency = $config['concurrency']; + } + + if (isset($config['fulfilled'])) { + $this->onFulfilled = $config['fulfilled']; + } + + if (isset($config['rejected'])) { + $this->onRejected = $config['rejected']; + } + } + + /** + * @return PromiseInterface + */ + public function promise(): PromiseInterface + { + if ($this->aggregate) { + return $this->aggregate; + } + + try { + $this->createPromise(); + $this->iterable->rewind(); + $this->refillPending(); + if (!$this->pending) { + Utils::queue()->add(function (): void { + if (!$this->aggregate || State::isSettled($this->aggregate)) { + return; + } + + try { + $this->checkIfFinished(); + } catch (\Throwable $e) { + $this->aggregate->reject($e); + } + }); + } + } catch (\Throwable $e) { + $this->aggregate->reject($e); + } + + return $this->aggregate; + } + + private function createPromise(): void + { + $this->mutex = false; + $this->aggregate = new Promise(function (): void { + while (true) { + if ($this->checkIfFinished()) { + return; + } + reset($this->pending); + // Consume a potentially fluctuating list of promises while + // ensuring that indexes are maintained (precluding array_shift). + while ($promise = current($this->pending)) { + next($this->pending); + $promise->wait(); + if (State::isSettled($this->aggregate)) { + return; + } + } + // Refill and re-sweep; give up only when nothing remains. + $this->refillPending(); + if (State::isSettled($this->aggregate) || !$this->pending) { + return; + } + } + }); + + // Clear the references when the promise is resolved. + $clearFn = function (): void { + $this->iterable = $this->concurrency = $this->pending = null; + $this->onFulfilled = $this->onRejected = null; + $this->nextPendingIndex = 0; + }; + + $this->aggregate->then($clearFn, $clearFn); + } + + private function refillPending(): void + { + if (!$this->concurrency) { + // Add all pending promises. + while ($this->addPending() && $this->advanceIterator()) { + } + + return; + } + + // Add only up to N pending promises. + $concurrency = is_callable($this->concurrency) + ? ($this->concurrency)(count($this->pending)) + : $this->concurrency; + // The callable can settle the aggregate; admit nothing more. + if (State::isSettled($this->aggregate)) { + return; + } + $concurrency = max($concurrency - count($this->pending), 0); + // Concurrency may be set to 0 to disallow new promises. + if (!$concurrency) { + return; + } + // Add the first pending promise. + $this->addPending(); + // Note this is special handling for concurrency=1 so that we do + // not advance the iterator after adding the first promise. This + // helps work around issues with generators that might not have the + // next value to yield until promise callbacks are called. + while (--$concurrency + && $this->advanceIterator() + && $this->addPending()) { + } + } + + private function addPending(): bool + { + if (!$this->iterable || !$this->iterable->valid()) { + return false; + } + + $promise = Create::promiseFor($this->iterable->current()); + $key = $this->iterable->key(); + + // Iterable keys may not be unique, so we use a counter to + // guarantee uniqueness + $idx = $this->nextPendingIndex++; + + $this->pending[$idx] = $promise->then( + function ($value) use ($idx, $key): void { + if ($this->onFulfilled) { + ($this->onFulfilled)( + $value, + $key, + $this->aggregate + ); + } + $this->step($idx); + }, + function ($reason) use ($idx, $key): void { + if ($this->onRejected) { + ($this->onRejected)( + $reason, + $key, + $this->aggregate + ); + } + $this->step($idx); + } + ); + + return true; + } + + private function advanceIterator(): bool + { + // Place a lock on the iterator so that we ensure to not recurse, + // preventing fatal generator errors. + if ($this->mutex) { + $this->stepWhileLocked = true; + + return false; + } + + $this->mutex = true; + + try { + $this->iterable->next(); + $this->mutex = false; + } catch (\Throwable $e) { + $this->aggregate->reject($e); + $this->mutex = false; + + return false; + } + + // Run the completion check that locked steps skipped. + if ($this->stepWhileLocked) { + $this->stepWhileLocked = false; + if (!State::isSettled($this->aggregate)) { + $this->checkIfFinished(); + } + } + + return true; + } + + private function step(int $idx): void + { + // If the promise was already resolved, then ignore this step. + if (State::isSettled($this->aggregate)) { + return; + } + + unset($this->pending[$idx]); + + // Only refill pending promises if we are not locked, preventing the + // EachPromise to recursively invoke the provided iterator, which + // cause a fatal error: "Cannot resume an already running generator" + if ($this->advanceIterator() && !$this->checkIfFinished()) { + // Add more pending promises if possible. + $this->refillPending(); + } + } + + /** @phpstan-impure */ + private function checkIfFinished(): bool + { + if (!$this->pending && !$this->iterable->valid()) { + // Resolve the promise if there's nothing left to do. + $this->aggregate->resolve(null); + + return true; + } + + return false; + } +} diff --git a/vendor/guzzlehttp/promises/src/FulfilledPromise.php b/vendor/guzzlehttp/promises/src/FulfilledPromise.php new file mode 100644 index 0000000..9346cef --- /dev/null +++ b/vendor/guzzlehttp/promises/src/FulfilledPromise.php @@ -0,0 +1,113 @@ + + * + * @final + */ +class FulfilledPromise implements PromiseInterface +{ + /** @var TValue */ + private $value; + + /** + * @param TValue $value + */ + public function __construct($value) + { + if (is_object($value) && method_exists($value, 'then')) { + throw new \InvalidArgumentException( + 'You cannot create a FulfilledPromise with a promise.' + ); + } + + $this->value = $value; + } + + /** + * @template TFulfilledValue = never + * @template TFulfilledReason = never + * @template TRejectedValue = never + * @template TRejectedReason = never + * + * @param (callable(TValue): (TFulfilledValue|PromiseInterface))|null $onFulfilled Invoked when the promise fulfills. + * @param (callable(TReason): (TRejectedValue|PromiseInterface))|null $onRejected Invoked when the promise is rejected. + * + * @return ($onFulfilled is null ? self : PromiseInterface) + */ + public function then( + ?callable $onFulfilled = null, + ?callable $onRejected = null + ): PromiseInterface { + // Return itself if there is no onFulfilled function. + if (!$onFulfilled) { + return $this; + } + + $queue = Utils::queue(); + $p = new Promise([$queue, 'run']); + $value = $this->value; + $queue->add(static function () use ($p, $value, $onFulfilled): void { + try { + if (State::isPending($p)) { + $p->resolve($onFulfilled($value)); + } + } catch (\Throwable $e) { + if (State::isPending($p)) { + $p->reject($e); + } + } + }); + + return $p; + } + + /** + * @param callable(TReason): mixed $onRejected Invoked when the promise is rejected. + * + * @return self + */ + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + return $unwrap ? $this->value : null; + } + + public function getState(): string + { + return self::FULFILLED; + } + + public function resolve($value = null): void + { + if ($value !== $this->value) { + throw new \LogicException('Cannot resolve a fulfilled promise'); + } + } + + public function reject($reason): void + { + throw new \LogicException('Cannot reject a fulfilled promise'); + } + + public function cancel(): void + { + // pass + } +} diff --git a/vendor/guzzlehttp/promises/src/Is.php b/vendor/guzzlehttp/promises/src/Is.php new file mode 100644 index 0000000..840d502 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/Is.php @@ -0,0 +1,91 @@ + + * + * @see https://promisesaplus.com/ + * + * @final + */ +class Promise implements PromiseInterface +{ + use NonSerializableTrait; + + /** @var self::PENDING|self::FULFILLED|self::REJECTED */ + private string $state = self::PENDING; + + /** @var TValue|TReason|PromiseInterface|null */ + private $result; + + /** @var (callable(): void)|null */ + private $cancelFn; + + /** @var (callable(bool): void)|null */ + private $waitFn; + + /** @var list>|null */ + private ?array $waitList = null; + + /** @var list, 1: callable|null, 2: callable|null}>|null */ + private ?array $handlersBefore = []; + + /** @var list, 1: callable|null, 2: callable|null}>|null */ + private ?array $handlers = []; + + /** + * @param (callable(bool): void)|null $waitFn Fn that when invoked resolves the promise. + * @param (callable(): void)|null $cancelFn Fn that when invoked cancels the promise. + */ + public function __construct( + ?callable $waitFn = null, + ?callable $cancelFn = null + ) { + $this->waitFn = $waitFn; + $this->cancelFn = $cancelFn; + } + + /** + * @template TFulfilledValue = never + * @template TFulfilledReason = never + * @template TRejectedValue = never + * @template TRejectedReason = never + * + * @param (callable(TValue): (TFulfilledValue|PromiseInterface))|null $onFulfilled Invoked when the promise fulfills. + * @param (callable(TReason): (TRejectedValue|PromiseInterface))|null $onRejected Invoked when the promise is rejected. + * + * @return PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)> + */ + public function then( + ?callable $onFulfilled = null, + ?callable $onRejected = null + ): PromiseInterface { + if ($this->state === self::PENDING) { + $p = new Promise(null, [$this, 'cancel']); + $this->handlers[] = [$p, $onFulfilled, $onRejected]; + $p->waitList = $this->waitList; + $p->waitList[] = $this; + + return $p; + } + + // Return a fulfilled promise and immediately invoke any callbacks. + if ($this->state === self::FULFILLED) { + $promise = Create::promiseFor($this->result); + + return $promise->then($onFulfilled, $onRejected); + } + + // It's either cancelled or rejected, so return a rejected promise + // and immediately invoke any callbacks. + $rejection = Create::rejectionFor($this->result); + + /** @var PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)> $promise */ + $promise = $onRejected ? $rejection->then(null, $onRejected) : $rejection; + + return $promise; + } + + /** + * @template TRejectedValue = never + * @template TRejectedReason = never + * + * @param callable(TReason): (TRejectedValue|PromiseInterface) $onRejected Invoked when the promise is rejected. + * + * @return PromiseInterface + */ + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + $this->waitIfPending(); + + if ($this->result instanceof PromiseInterface) { + return $this->result->wait($unwrap); + } + if ($unwrap) { + if ($this->state === self::FULFILLED) { + return $this->result; + } + // It's rejected so "unwrap" and throw an exception. + throw Create::exceptionFor($this->result); + } + + return null; + } + + public function getState(): string + { + return $this->state; + } + + public function cancel(): void + { + if ($this->state !== self::PENDING) { + return; + } + + $this->waitFn = $this->waitList = null; + + if ($this->cancelFn) { + $fn = $this->cancelFn; + $this->cancelFn = null; + try { + $fn(); + } catch (\Throwable $e) { + $this->reject($e); + } + } + + // Reject the promise only if it wasn't rejected in a then callback. + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject(new CancellationException('Promise has been cancelled')); + } + } + + public function resolve($value = null): void + { + $this->settle(self::FULFILLED, $value); + } + + public function reject($reason): void + { + $this->settle(self::REJECTED, $reason); + } + + private function settle(string $state, $value): void + { + if ($this->state !== self::PENDING) { + // Ignore calls with the same resolution. + if ($state === $this->state && $value === $this->result) { + return; + } + throw $this->state === $state + ? new \LogicException("The promise is already {$state}.") + : new \LogicException("Cannot change a {$this->state} promise to {$state}"); + } + + if ($value === $this) { + throw new \LogicException('Cannot fulfill or reject a promise with itself'); + } + + // Clear out the state of the promise but stash the handlers. + $this->state = $state; + $this->result = $value; + $handlers = $this->handlers; + $before = $this->handlersBefore; + $this->handlers = $this->handlersBefore = null; + $this->waitList = $this->waitFn = null; + $this->cancelFn = null; + + if (!$handlers) { + return; + } + + if ($value instanceof Promise && State::isPending($value)) { + // We can just hand our handlers to the next promise. Merging would + // copy both lists every time, so only the shorter one is moved. + if ($value->handlers === []) { + $value->handlers = $handlers; + $value->handlersBefore = $before; + } elseif (count($value->handlers) + count($value->handlersBefore) < count($handlers) + count($before)) { + array_push($before, ...array_reverse($value->handlers), ...$value->handlersBefore); + $value->handlers = $handlers; + $value->handlersBefore = $before; + } else { + array_push($value->handlers, ...array_reverse($before), ...$handlers); + } + + return; + } + + if ($before) { + $handlers = array_merge(array_reverse($before), $handlers); + } + + // If the value was not a settled promise or a thenable, then resolve + // it in the task queue using the correct ID. + if (!is_object($value) || !method_exists($value, 'then')) { + $id = $state === self::FULFILLED ? 1 : 2; + // It's a success, so resolve the handlers in the queue. + Utils::queue()->add(static function () use ($id, $value, $handlers): void { + foreach ($handlers as $handler) { + self::callHandler($id, $value, $handler); + } + }); + } else { + // Resolve the handlers when the forwarded promise is resolved. + try { + $value->then( + static function ($value) use (&$handlers): void { + foreach ($handlers as $handler) { + self::callHandler(1, $value, $handler); + } + }, + static function ($reason) use (&$handlers): void { + foreach ($handlers as $handler) { + self::callHandler(2, $reason, $handler); + } + } + ); + } catch (\Throwable $e) { + Utils::queue()->add(static function () use ($e, $handlers): void { + foreach ($handlers as $handler) { + self::callHandler(2, $e, $handler); + } + }); + // The thenable may still hold the callbacks. + $handlers = []; + } + } + } + + /** + * Call a stack of handlers using a specific callback index and value. + * + * @param int $index 1 (resolve) or 2 (reject). + * @param mixed $value Value to pass to the callback. + * @param array $handler Array of handler data (promise and callbacks). + */ + private static function callHandler(int $index, $value, array $handler): void + { + /** @var PromiseInterface $promise */ + $promise = $handler[0]; + + // The promise may have been cancelled or resolved before placing + // this thunk in the queue. + if (State::isSettled($promise)) { + return; + } + + try { + if (isset($handler[$index])) { + /* + * If $f throws an exception, then $handler will be in the exception + * stack trace. Since $handler contains a reference to the callable + * itself we get a circular reference. We clear the $handler + * here to avoid that memory leak. + */ + $f = $handler[$index]; + unset($handler); + $promise->resolve($f($value)); + } elseif ($index === 1) { + // Forward resolution values as-is. + $promise->resolve($value); + } else { + // Forward rejections down the chain. + $promise->reject($value); + } + } catch (\Throwable $reason) { + // The handler may have settled the promise itself. + if (State::isPending($promise)) { + $promise->reject($reason); + } + } + } + + private function waitIfPending(): void + { + if ($this->state !== self::PENDING) { + return; + } elseif ($this->waitFn) { + $this->invokeWaitFn(); + } elseif ($this->waitList) { + $this->invokeWaitList(); + } else { + // If there's no wait function, then reject the promise. + $this->reject('Cannot wait on a promise that has ' + .'no internal wait function. You must provide a wait ' + .'function when constructing the promise to be able to ' + .'wait on a promise.'); + } + + Utils::queue()->run(); + + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject('Invoking the wait callback did not resolve the promise'); + } + } + + private function invokeWaitFn(): void + { + try { + $wfn = $this->waitFn; + $this->waitFn = null; + $wfn(true); + } catch (\Throwable $reason) { + if ($this->state === self::PENDING) { + // The promise has not been resolved yet, so reject the promise + // with the exception. + $this->reject($reason); + } else { + // The promise was already resolved, so there's a problem in + // the application. + throw $reason; + } + } + } + + private function invokeWaitList(): void + { + $waitList = $this->waitList; + $this->waitList = null; + + foreach ($waitList as $result) { + do { + $result->waitIfPending(); + $result = $result->result; + } while ($result instanceof Promise); + + if ($result instanceof PromiseInterface) { + $result->wait(false); + } + } + } +} diff --git a/vendor/guzzlehttp/promises/src/PromiseInterface.php b/vendor/guzzlehttp/promises/src/PromiseInterface.php new file mode 100644 index 0000000..8b97e3b --- /dev/null +++ b/vendor/guzzlehttp/promises/src/PromiseInterface.php @@ -0,0 +1,119 @@ +))|null $onFulfilled Invoked when the promise fulfills. + * @param (callable(TReason): (TRejectedValue|PromiseInterface))|null $onRejected Invoked when the promise is rejected. + * + * @return PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)> + */ + public function then( + ?callable $onFulfilled = null, + ?callable $onRejected = null + ): PromiseInterface; + + /** + * Appends a rejection handler callback to the promise, and returns a new + * promise resolving to the return value of the callback if it is called, + * or to its original fulfillment value if the promise is instead + * fulfilled. + * + * @template TRejectedValue = never + * @template TRejectedReason = never + * + * @param callable(TReason): (TRejectedValue|PromiseInterface) $onRejected Invoked when the promise is rejected. + * + * @return PromiseInterface + */ + public function otherwise(callable $onRejected): PromiseInterface; + + /** + * Get the state of the promise ("pending", "rejected", or "fulfilled"). + * + * The three states can be checked against the constants defined on + * PromiseInterface: PENDING, FULFILLED, and REJECTED. + * + * The state describes how this promise was settled, not the eventual + * outcome: a promise that was resolved with another promise, directly or + * by returning one from a then() handler, reports FULFILLED while the + * inner promise may still be pending, and wait() can still throw if the + * inner promise rejects. Poll the state only on promises settled with + * plain values, or call wait() first. + * + * @return self::PENDING|self::FULFILLED|self::REJECTED + * + * @see https://github.com/guzzle/promises/issues/101 + */ + public function getState(): string; + + /** + * Resolve the promise with the given value, or with null if no value is given. + * + * @param TValue|PromiseInterface|null $value + * + * @throws \LogicException if the promise is already settled with a + * conflicting resolution. + */ + public function resolve($value = null): void; + + /** + * Reject the promise with the given reason. + * + * @param TReason $reason + * + * @throws \LogicException if the promise is already settled with a + * conflicting resolution. + */ + public function reject($reason): void; + + /** + * Cancels the promise if possible. + * + * @see https://github.com/promises-aplus/cancellation-spec/issues/7 + */ + public function cancel(): void; + + /** + * Waits until the promise completes if possible. + * + * Pass $unwrap as true to unwrap the result of the promise, either + * returning the resolved value or throwing the rejected exception. + * + * If the promise cannot be waited on, then the promise will be rejected. + * + * @return ($unwrap is true ? TValue : null) + * + * @throws \LogicException if the promise has no wait function or if the + * promise does not settle after waiting. + */ + public function wait(bool $unwrap = true); +} diff --git a/vendor/guzzlehttp/promises/src/PromisorInterface.php b/vendor/guzzlehttp/promises/src/PromisorInterface.php new file mode 100644 index 0000000..6ed6f1b --- /dev/null +++ b/vendor/guzzlehttp/promises/src/PromisorInterface.php @@ -0,0 +1,21 @@ + + */ + public function promise(): PromiseInterface; +} diff --git a/vendor/guzzlehttp/promises/src/RejectedPromise.php b/vendor/guzzlehttp/promises/src/RejectedPromise.php new file mode 100644 index 0000000..8947a9d --- /dev/null +++ b/vendor/guzzlehttp/promises/src/RejectedPromise.php @@ -0,0 +1,122 @@ + + * + * @final + */ +class RejectedPromise implements PromiseInterface +{ + /** @var TReason */ + private $reason; + + /** + * @param TReason $reason + */ + public function __construct($reason) + { + if (is_object($reason) && method_exists($reason, 'then')) { + throw new \InvalidArgumentException( + 'You cannot create a RejectedPromise with a promise.' + ); + } + + $this->reason = $reason; + } + + /** + * @template TFulfilledValue = never + * @template TFulfilledReason = never + * @template TRejectedValue = never + * @template TRejectedReason = never + * + * @param (callable(TValue): (TFulfilledValue|PromiseInterface))|null $onFulfilled Invoked when the promise fulfills. + * @param (callable(TReason): (TRejectedValue|PromiseInterface))|null $onRejected Invoked when the promise is rejected. + * + * @return ($onRejected is null ? self : PromiseInterface) + */ + public function then( + ?callable $onFulfilled = null, + ?callable $onRejected = null + ): PromiseInterface { + // If there's no onRejected callback then just return self. + if (!$onRejected) { + return $this; + } + + $queue = Utils::queue(); + $reason = $this->reason; + $p = new Promise([$queue, 'run']); + $queue->add(static function () use ($p, $reason, $onRejected): void { + try { + if (State::isPending($p)) { + // Return a resolved promise if onRejected does not throw. + $p->resolve($onRejected($reason)); + } + } catch (\Throwable $e) { + // onRejected threw, so return a rejected promise. + if (State::isPending($p)) { + $p->reject($e); + } + } + }); + + return $p; + } + + /** + * @template TRejectedValue = never + * @template TRejectedReason = never + * + * @param callable(TReason): (TRejectedValue|PromiseInterface) $onRejected Invoked when the promise is rejected. + * + * @return PromiseInterface + */ + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + if ($unwrap) { + throw Create::exceptionFor($this->reason); + } + + return null; + } + + public function getState(): string + { + return self::REJECTED; + } + + public function resolve($value = null): void + { + throw new \LogicException('Cannot resolve a rejected promise'); + } + + public function reject($reason): void + { + if ($reason !== $this->reason) { + throw new \LogicException('Cannot reject a rejected promise'); + } + } + + public function cancel(): void + { + // pass + } +} diff --git a/vendor/guzzlehttp/promises/src/RejectionException.php b/vendor/guzzlehttp/promises/src/RejectionException.php new file mode 100644 index 0000000..47dca86 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/RejectionException.php @@ -0,0 +1,49 @@ +reason = $reason; + + $message = 'The promise was rejected'; + + if ($description) { + $message .= ' with reason: '.$description; + } elseif (is_string($reason) + || (is_object($reason) && method_exists($reason, '__toString')) + ) { + $message .= ' with reason: '.$this->reason; + } elseif ($reason instanceof \JsonSerializable) { + $message .= ' with reason: '.json_encode($this->reason, JSON_PRETTY_PRINT); + } + + parent::__construct($message); + } + + /** + * Returns the rejection reason. + * + * @return mixed + */ + public function getReason() + { + return $this->reason; + } +} diff --git a/vendor/guzzlehttp/promises/src/State.php b/vendor/guzzlehttp/promises/src/State.php new file mode 100644 index 0000000..35d98a7 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/State.php @@ -0,0 +1,44 @@ +getState() === PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled or rejected. + */ + public static function isSettled(PromiseInterface $promise): bool + { + return $promise->getState() !== PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled. + */ + public static function isFulfilled(PromiseInterface $promise): bool + { + return $promise->getState() === PromiseInterface::FULFILLED; + } + + /** + * Returns true if a promise is rejected. + */ + public static function isRejected(PromiseInterface $promise): bool + { + return $promise->getState() === PromiseInterface::REJECTED; + } +} diff --git a/vendor/guzzlehttp/promises/src/TaskQueue.php b/vendor/guzzlehttp/promises/src/TaskQueue.php new file mode 100644 index 0000000..04ffea1 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/TaskQueue.php @@ -0,0 +1,84 @@ +run(); + * + * @final + */ +class TaskQueue implements TaskQueueInterface +{ + use NonSerializableTrait; + + private bool $enableShutdown = true; + /** @var \SplQueue */ + private \SplQueue $queue; + + public function __construct(bool $withShutdown = true) + { + $this->queue = new \SplQueue(); + + if ($withShutdown) { + register_shutdown_function(function (): void { + if ($this->enableShutdown) { + // Only run the tasks if an E_ERROR didn't occur. + $err = error_get_last(); + if (!$err || ($err['type'] ^ E_ERROR)) { + $this->run(); + } + } + }); + } + } + + public function __clone() + { + $this->queue = clone $this->queue; + } + + public function isEmpty(): bool + { + return $this->queue->isEmpty(); + } + + /** + * @param callable(): void $task + */ + public function add(callable $task): void + { + $this->queue->enqueue($task); + } + + public function run(): void + { + while (!$this->queue->isEmpty()) { + $task = $this->queue->dequeue(); + $task(); + } + } + + /** + * The task queue will be run and exhausted by default when the process + * exits IFF the exit is not the result of a PHP E_ERROR error. + * + * You can disable running the automatic shutdown of the queue by calling + * this function. If you disable the task queue shutdown process, then you + * MUST either run the task queue (as a result of running your event loop + * or manually using the run() method) or wait on each outstanding promise. + * + * Note: This shutdown will occur before any destructors are triggered. + */ + public function disableShutdown(): void + { + $this->enableShutdown = false; + } +} diff --git a/vendor/guzzlehttp/promises/src/TaskQueueInterface.php b/vendor/guzzlehttp/promises/src/TaskQueueInterface.php new file mode 100644 index 0000000..d44b7f6 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/TaskQueueInterface.php @@ -0,0 +1,26 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\Utils::queue()->run(); + * } + * + * + * @param TaskQueueInterface|null $assign Optionally specify a new queue instance. + */ + public static function queue(?TaskQueueInterface $assign = null): TaskQueueInterface + { + static $queue; + + if ($assign) { + $queue = $assign; + } elseif (!$queue) { + $queue = new TaskQueue(); + } + + return $queue; + } + + /** + * Adds a task to the global queue and returns a promise that is fulfilled + * or rejected with the task result. + * + * @template TValue + * + * @param callable(): TValue $task Task function to run. + * + * @return PromiseInterface + */ + public static function task(callable $task): PromiseInterface + { + $queue = self::queue(); + $promise = new Promise([$queue, 'run']); + $queue->add(function () use ($task, $promise): void { + try { + if (State::isPending($promise)) { + $promise->resolve($task()); + } + } catch (\Throwable $e) { + if (State::isPending($promise)) { + $promise->reject($e); + } + } + }); + + return $promise; + } + + /** + * Synchronously waits on a promise to settle and returns an inspection + * state array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the + * array will contain a "value" key mapping to the fulfilled value of the + * promise. If the promise is rejected, the array will contain a "reason" + * key mapping to the rejection reason of the promise. + * + * @template TValue + * @template TReason + * + * @param PromiseInterface $promise Promise to inspect. + * + * @return array{state: PromiseInterface::FULFILLED, value: TValue}|array{state: PromiseInterface::REJECTED, reason: TReason|\Throwable}|array{state: PromiseInterface::PENDING} + */ + public static function inspect(PromiseInterface $promise): array + { + $result = null; + $getResult = static function () use (&$result): ?array { + return $result; + }; + + $inspection = $promise->then( + static function ($value) use (&$result): void { + $result = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; + }, + static function ($reason) use (&$result): void { + $result = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; + } + ); + + try { + $inspection->wait(false); + } catch (\Throwable $e) { + $settled = $getResult(); + if (null !== $settled) { + return $settled; + } + + try { + self::queue()->run(); + } catch (\Throwable $queueError) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $queueError]; + } + + return $getResult() ?? ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } + + return $getResult() ?? ['state' => $promise->getState()]; + } + + /** + * Waits on all of the provided promises, but does not unwrap rejected + * promises as a thrown exception. + * + * Returns an array of inspection state arrays keyed like the input + * iterable. + * + * @see inspect for the inspection state array format. + * + * @template TKey of array-key + * @template TValue + * @template TReason + * + * @param iterable> $promises Traversable of promises to wait upon. + * + * @return array + */ + public static function inspectAll(iterable $promises): array + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = self::inspect($promise); + } + + return $results; + } + + /** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same + * order the promises were provided). An exception is thrown if any of the + * promises are rejected. + * + * @template TKey of array-key + * @template TValue + * @template TReason + * + * @param iterable> $promises Iterable of PromiseInterface objects to wait on. + * + * @return array + * + * @throws \Throwable on error + */ + public static function unwrap(iterable $promises): array + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = $promise->wait(); + } + + return $results; + } + + /** + * Given an array of promises, return a promise that is fulfilled when all + * the items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * The config array accepts a concurrency option for lazy iterables. Other + * config keys are ignored by this wrapper. + * + * @template TKey of array-key + * @template TValue + * @template TReason + * + * @param iterable> $promises Promises or values. + * @param bool $recursive If true, resolves newly-added entries until no unprocessed entries or pending promises remain. + * @param array{concurrency?: int|(callable(int): int)} $config Configuration options. + * + * @return PromiseInterface, TReason|\Throwable> + */ + public static function all(iterable $promises, bool $recursive = false, array $config = []): PromiseInterface + { + $results = []; + $promise = Each::of( + $promises, + function ($value, $idx) use (&$results): void { + $results[$idx] = $value; + }, + function ($reason, $idx, PromiseInterface $aggregate): void { + if (State::isPending($aggregate)) { + $aggregate->reject($reason); + } + }, + $config + )->then(function () use (&$results) { + ksort($results); + + return $results; + }); + + if (true === $recursive) { + $promise = $promise->then(function ($results) use (&$promises, $config) { + if (self::shouldRecurse($promises, $results)) { + return self::all($promises, true, $config); + } + + return $results; + }); + } + + return $promise; + } + + /** + * Initiate a competitive race between multiple promises or values (values + * will become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise + * is fulfilled with an array that contains the fulfillment values of the + * winners, in the order they appear in the input. + * + * This promise is rejected with a {@see AggregateException} if the number + * of fulfilled promises is less than the desired $count. + * + * @template TValue + * @template TReason + * + * @param int $count Total number of promises. + * @param iterable> $promises Promises or values. + * + * @return PromiseInterface, \Throwable> + */ + public static function some(int $count, iterable $promises): PromiseInterface + { + $results = []; + $rejections = []; + + $promise = Each::of( + $promises, + function ($value, $idx, PromiseInterface $p) use (&$results, $count): void { + if (State::isSettled($p)) { + return; + } + $results[$idx] = $value; + if (count($results) >= $count) { + $p->resolve(null); + } + }, + function ($reason) use (&$rejections): void { + $rejections[] = $reason; + } + )->then( + function () use (&$results, &$rejections, $count) { + if (count($results) !== $count) { + throw new AggregateException( + 'Not enough promises to fulfill count', + $rejections + ); + } + ksort($results); + + return array_values($results); + } + ); + + /** @var PromiseInterface, \Throwable> $promise */ + return $promise; + } + + /** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @template TValue + * @template TReason + * + * @param iterable> $promises Promises or values. + * + * @return PromiseInterface + */ + public static function any(iterable $promises): PromiseInterface + { + return self::some(1, $promises)->then(function (array $values) { + return $values[0]; + }); + } + + /** + * Returns a promise that is fulfilled when all of the provided promises + * have been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state + * arrays. + * + * The config array accepts a concurrency option for lazy iterables. Other + * config keys are ignored by this wrapper. + * + * @see inspect for the inspection state array format. + * + * @template TKey of array-key + * @template TValue + * @template TReason + * + * @param iterable> $promises Promises or values. + * @param bool $recursive If true, settles newly-added entries until no unprocessed entries or pending promises remain. + * @param array{concurrency?: int|(callable(int): int)} $config Configuration options. + * + * @return PromiseInterface, \Throwable> + */ + public static function settle(iterable $promises, bool $recursive = false, array $config = []): PromiseInterface + { + $results = []; + + $promise = Each::of( + $promises, + function ($value, $idx) use (&$results): void { + $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; + }, + function ($reason, $idx) use (&$results): void { + $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; + }, + $config + )->then(function () use (&$results) { + ksort($results); + + return $results; + }); + + if (true === $recursive) { + $promise = $promise->then(function ($results) use (&$promises, $config) { + if (self::shouldRecurse($promises, $results)) { + return self::settle($promises, true, $config); + } + + return $results; + }); + } + + return $promise; + } + + /** + * @template TKey of array-key + * + * @param iterable $promises Promises or values. + * @param array $results Results already collected for a pass. + */ + private static function shouldRecurse(iterable $promises, array $results): bool + { + // A consumed generator cannot be traversed again, so a recursive + // pass has nothing further to observe. + if ($promises instanceof \Generator) { + return false; + } + + foreach ($promises as $key => $promise) { + if (!array_key_exists($key, $results)) { + return true; + } + + if ($promise instanceof PromiseInterface && State::isPending($promise)) { + return true; + } + } + + return false; + } +} diff --git a/vendor/guzzlehttp/psr7/AGENTS.md b/vendor/guzzlehttp/psr7/AGENTS.md new file mode 100644 index 0000000..bd96333 --- /dev/null +++ b/vendor/guzzlehttp/psr7/AGENTS.md @@ -0,0 +1,69 @@ +# Agent Guidelines + +## Code and tooling + +- All code must remain compatible with PHP 7.4. Run PHPStan and PHP-CS-Fixer + only under a PHP 7.4.x runtime; never run either tool under any other PHP + major.minor version. +- Use fully qualified `#[\SensitiveParameter]` on concrete executable + parameters when their established role normally carries a secret, + credential-bearing aggregate, or confidential Guzzle-owned container, and + the active frame can throw or invoke throwing code. +- Repeat the attribute on every qualifying owned caller, callee, concrete trait + method, and closure parameter. Do not add it to interfaces, abstract-only + declarations, pure/no-realistic-throw helpers, assignment-only sites, + arbitrary generic payloads, or completed non-recoverable derivatives. +- For PHP 7.4 compatibility, put `#[\SensitiveParameter]` on its own line and + the parameter on the following line, expand the complete parameter list, and + never add a comma after the final parameter. Native trace redaction starts on + PHP 8.2 and does not redact logs, messages, properties, wire traffic, captured + variables, return values, or the separate backtrace `$this`/`object`. +- Always pass an explicit character list to `trim()`, `ltrim()`, and `rtrim()`; + never rely on the default characters. +- Handle `preg_*` engine failures: when the result is used as data, test for + `false` or `null` and throw a `\RuntimeException` including + `preg_last_error_msg()`; boolean validation guards must compare strictly, such + as `=== 1`, so an engine failure can only ever fail closed. Diagnostic + escaping is the narrow exception: use a deterministic bytewise fallback rather + than throwing, so it cannot obscure the original exception. +- Anchor validation patterns to the true end of input with the `D` modifier or + `\z`; a bare `$` accepts a trailing newline. +- Never embed raw control bytes in exception messages and other diagnostics; + escape or redact the offending value first. +- Helper classes that expose only public static methods are `final` and have a + private constructor. +- Resist native PHP serialization when a class holds live state (streams, + resources, handles, callbacks, credentials) or when magic methods such as + `__destruct()` have side effects that untrusted unserialized data could + redirect, as with the file and session write fixes in Guzzle's persisting + cookie jars. Plain data holders, such as Guzzle's in-memory cookie jar, remain + serializable. +- To resist, `__serialize()` and `__unserialize()` both throw + `\LogicException(static::class.' should never be serialized')` and its + unserialized counterpart, usually via the `@internal` + `NonSerializableStreamTrait`. Where a `__destruct()` has such a side effect, + it is enabled only by the constructor and disabled in `__wakeup()` and + `__unserialize()` before throwing, so the protection holds even if the + exception is swallowed. +- In general, numeric inputs should not accept non-finite floats. In situations + where they are accepted and we need to cast to a string, we should branch on + `\is_finite($value)`, using `(string) $value` for the finite case and + `\is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')` otherwise. +- Never call `strtolower()`, `strtoupper()`, `strcasecmp()`, `stripos()`, or + other locale-sensitive case functions; use the locale-independent + `Utils::asciiToLower()`, `Utils::asciiToUpper()`, `Utils::caselessEquals()`, + and `Utils::caselessContains()` helpers instead. +- Changes in behavior need a `CHANGELOG.md` entry in the unreleased section of + the target branch and an `UPGRADING.md` note when the behavior differs between + major versions. + +## Documentation + +- Wrap markdown prose and PHPDoc text to 80 columns using greedy wrapping. Never + split a markdown link or an inline code span across a line break; a line that + cannot be broken may exceed the limit. Avoid em dashes. +- Keep PHPDoc and the corresponding `docs/` pages in sync: shared prose is + deliberately word-for-word identical, including boilerplate copied verbatim + between related functions, so apply the same edit to every copy. Only + formatting and linking may differ, such as a docs link becoming a PHPDoc + `@see` tag; the wording must never drift. diff --git a/vendor/guzzlehttp/psr7/CHANGELOG.md b/vendor/guzzlehttp/psr7/CHANGELOG.md new file mode 100644 index 0000000..7f0f8dd --- /dev/null +++ b/vendor/guzzlehttp/psr7/CHANGELOG.md @@ -0,0 +1,840 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## 3.6.0 - 2026-11-21 + +### Changed + +- Recognize a plus sign in the scheme of a URI string instead of parsing the string as a relative path + +### Deprecated + +- Deprecated URI hosts with non-ASCII data that guzzlehttp/psr7 4.0 rejects +- Deprecated URI strings that start with a host and port, which guzzlehttp/psr7 4.0 rejects + +## 3.5.2 - 2026-11-21 + +### Fixed + +- Fix `AppendStream` rewinding when seeking to a negative offset +- Fix `InflateStream` returning no data after a rewind +- Fix `Message::bodySummary()` for truncated bodies of unknown size + +## 3.5.1 - 2026-11-19 + +### Fixed + +- Fix parsing of absolute-path references containing a colon followed by digits in a path segment +- Fix network-path references taking a port from a colon followed by digits in a path segment + +## 3.5.0 - 2026-11-18 + +### Added + +- Add `Idna` to convert internationalized hosts to ASCII + +## 3.4.0 - 2026-11-13 + +### Added + +- Add `UriRedactor` + +### Deprecated + +- Deprecated `Utils::redact` methods in favor of `UriRedactor` + +## 3.3.0 - 2026-11-12 + +### Added + +- Add `ErrorScope` to capture the PHP errors raised beneath a call + +### Changed + +- Stop stream helpers failing on deprecations and silenced errors + +### Fixed + +- Fix stream helpers capturing errors raised in other coroutines and fibers + +## 3.2.1 - 2026-11-12 + +### Fixed + +- Fix `Header::parse()` truncating parameter values at the first equals sign + +## 3.2.0 - 2026-10-18 + +### Fixed + +- Fix `InflateStream` ignoring source read failures that follow decoded bytes +- Fix `AppendStream` discarding bytes read before a timeout + +## 3.1.1 - 2026-10-18 + +### Fixed + +- Fix `StreamWrapper` flushes reporting failure +- Fix `CachingStream` skipping unread bytes after repeated writes + +## 3.1.0 - 2026-08-24 + +### Added + +- Add `Utils::redactUriForMessage()` and `Utils::redactUriStringForMessage()` for URI diagnostics +- Add support for PHP 8.6 + +### Changed + +- Omit rejected header values and sensitive URI components from automatic exception messages + +## 3.0.1 - 2026-08-24 + +### Fixed + +- Prefix relative paths that begin with a colon segment with `./` instead of throwing +- Apply the `/.` prefix for authority-less `//` paths to percent-encoding normalizations as well +- Keep colon-leading first path segments when reading the paths of scheme-less non-native URIs +- Stop throwing when removing the default `file` host strands a `//` path, prefixing it with `/.` + +## 3.0.0 - 2026-07-20 + +### Added + +- Add `DiagnosticValue::escape()` to escape controls and malformed UTF-8 in diagnostics +- Add `GuzzleHttp\Psr7\Exception\TimeoutException` for timed-out stream operations +- Add `GuzzleHttp\Psr7\Utils::redactUserInfoInString()` to redact the userinfo of a raw URI string within text +- Promote `GuzzleHttp\Psr7\Rfc3986` to public API with `isValid*()` predicates and `canonicalizeIpv6()` +- Add `GuzzleHttp\Psr7\UriNormalizer::CANONICALIZE_IPV6_HOST` to `PRESERVING_NORMALIZATIONS` + +### Changed + +- Require `psr/http-message:^2.0` and add native parameter and return types +- Require `psr/http-factory:^1.1` +- Reject native PHP serialization of stream implementations +- Preserve request method casing, except `ServerRequest::fromGlobals()` still uppercases +- Reject empty arrays and non-string values as header values +- Reject invalid uploaded file trees and invalid parsed body values +- Reject uploaded file specs missing `tmp_name`, `size`, or `error` +- Reject non-integer and negative uploaded file `error` values +- Reject invalid stream/upload sizes, buffer high-water marks, and dropping-stream limits +- Rewind seekable uploaded-file streams before copying in `UploadedFile::moveTo()` +- Reject negative `read()` lengths across all stream implementations +- Detect the `+` flag anywhere in a mode for `Stream::isReadable()`/`isWritable()` +- Reject empty strings returned by `PumpStream` source callables +- Discard buffered bytes on `PumpStream` close and detach +- Restore the original stream position after `Message::bodySummary()` +- Allow `null` for the `Message::bodySummary()` truncation length to use the default +- Validate `LimitStream` offset/limit and track non-seekable offset by bytes skipped +- Make `FnStream` close and detach terminal, calling close callbacks at most once +- Suppress exceptions from `FnStream` close callbacks during destructor cleanup +- Make `CachingStream::close()` idempotent, preserving remote cleanup after detach +- Do not move the `CachingStream` cursor when a `SEEK_END` target on an unknown-size stream is rejected +- Normalize multiple leading slashes in `Uri::getPath()` and origin-form request targets +- Serialize authority-less `file` URIs with rootless paths without the `//` separator +- Serialize authority-less `file` URIs with empty paths as `file:` instead of the unparseable `file://` +- Remove dot segments above the root per RFC 3986, prefixing authority-less `//` paths with `/.` +- Return a network-path reference from `UriResolver::relativize()` when an empty-path target requires one +- Stop returning an empty reference from `UriResolver::relativize()` when it would inherit the base fragment +- Stop throwing from `UriResolver::relativize()` when an equal-path target's last path segment contains a colon +- Harden URI host validation (delimiters, backslashes, IPv6, embedded ports); require schemes to start with a letter +- Validate `Uri::fromParts()` ports instead of casting them +- Treat ports 80 and 443 as defaults for the `ws` and `wss` schemes +- Use the `ws` and `wss` default ports in `UriComparator::isCrossOrigin()` port comparisons +- Redact all non-empty URI userinfo in `Utils::redactUserInfo()` +- Rebuild server request URIs from `$_SERVER` by `REQUEST_METHOD`, using target authority before `SERVER_PORT` +- Remove userinfo from absolute-form `REQUEST_URI` targets in `ServerRequest::fromGlobals()` +- Reject zero-port `HTTP_HOST` and malformed `SERVER_PORT` in `ServerRequest::getUriFromGlobals()` +- Reject malformed `REQUEST_METHOD` and `SERVER_PROTOCOL` server values in `ServerRequest::fromGlobals()` +- Reject zero-port `Host` and normalize leading-zero ports in `Message::parseRequest()` +- Reject duplicate `Host` headers and validate present values for all request-target forms +- Reject zero-port, hostless, and userinfo absolute-form request targets in `Message::parseRequest()` +- Synchronize the `Host` header in `Request::withUri()` when the URI changes or Host is empty +- Include the URI port in `Host` headers synthesized by `Message::toString()` +- Validate the Host header synthesized by `Message::toString()` from the request URI +- Include non-default URI ports in `Host` headers set by `Utils::modifyRequest()` URI changes +- Accept `OPTIONS *` and `CONNECT` authority-form request targets in `Message::parseRequest()` +- Hide credential-bearing URI, server, and cookie arguments in stack traces on PHP 8.2+ +- Reject malformed HTTP request/response start-lines +- Unfold obsolete HTTP/1.0 line folding for all valid request method tokens +- Reject empty and control-character request targets in `Request::withRequestTarget()` +- Validate iterator chunks passed to `Utils::streamFor()` +- Validate unsupported values passed to `Query::build()` +- Reject non-finite float values in `Query::build()` and `MultipartStream` contents +- Reject non-finite float values in iterator chunks passed to `Utils::streamFor()` +- `Utils::streamFor()` now rejects non-string scalar bodies +- `Uri::withQueryValues()` now rejects non-string values +- Reject invalid `Utils::modifyRequest()` change values +- Use PHP debug type names in type error messages +- Changed `Utils::copyToStream()` to throw when destination streams cannot make progress +- Throw `TimeoutException` from `Stream` read/write and `Utils` copy/hash/readLine on stream timeouts +- Throw `TimeoutException` from `AppendStream::read()`, `CachingStream::read()`, and `Utils::tryGetContents()` on stream timeouts +- Re-throw `TimeoutException` from `InflateStream` when the decoded source stream times out +- Close the compressed source stream from `InflateStream::close()` +- Return the number of bytes copied from `Utils::copyToStream()` +- Throw `OverflowException` when stream byte counts or offsets exceed `PHP_INT_MAX` +- Translate `StreamWrapper` runtime failures to PHP stream failure values +- Stop adding default `Content-Length` to `multipart/form-data` parts (RFC 7578 §4.8) +- Escape multipart `Content-Disposition` parameters and reject unsafe boundaries and part headers +- Preserve trailing whitespace in custom `MultipartStream` part header values +- Preserve explicit custom `MultipartStream` boundary `'0'` instead of replacing it with a generated boundary +- Made static utility classes non-instantiable +- Validate bracketed IP-literal hosts consistently between parsing and `withHost()`, including userinfo forms +- Percent-encode raw control bytes in userinfo before bracketed IP-literal hosts instead of parsing mutated values +- Reject invalid UTF-8 and preserve percent-sequences in userinfo before bracketed IP-literal hosts +- Normalize percent-encoded octets in the URI host to uppercase hex +- Canonicalize IPv6 hosts to RFC 5952 form in `Uri` construction, `fromParts()`, and `withHost()` +- Canonicalize bracketed IPv6 hosts in `UriComparator::isCrossOrigin()` +- Reject malformed percent-sequences and percent-encoded bytes forbidden by the URI host policy +- Extend `CAPITALIZE_PERCENT_ENCODING` and `DECODE_UNRESERVED_CHARACTERS` to userinfo and host +- Trim header list elements with only spaces, horizontal tabs, and line terminators in `Header::splitList()` +- Report header parameter PCRE failures explicitly in `Header::parse()` +- Escape controls and malformed UTF-8 consistently in generated exception messages + +### Removed + +- Dropped support for PHP 7.2 and 7.3 +- Removed the `ralouphie/getallheaders` dependency +- Removed deprecated `Header::normalize()` method + +## 2.13.0 - 2026-07-16 + +### Added + +- Add `Utils::` `asciiToLower`, `asciiToUpper`, `asciiUcFirst`, `caselessEquals`, `caselessContains` + +### Changed + +- Use locale-independent ASCII case folding everywhere case is normalized +- Trigger a runtime deprecation for previously deprecated functionality in 2.3.0 + +## 2.12.5 - 2026-07-13 + +### Fixed + +- Compare header names and hosts with locale-independent ASCII lowercasing +- Compare hosts without locale sensitivity when detecting cross-origin redirects + +## 2.12.4 - 2026-07-08 + +### Changed + +- Pass explicit trim characters ahead of the PHP 8.6 trim default change + +### Fixed + +- Anchor server port and response start-line patterns to the true end of input +- Treat host-less origin-form request targets starting with `//` as paths in `Message::parseRequest()` +- Reject raw DEL bytes in bracketed IP-literal hosts instead of parsing a mutated host +- Reject invalid bytes after a bracketed IP-literal host instead of reparsing a different host + +## 2.12.3 - 2026-06-23 + +### Security + +- Validate the URI host so `getHost()` matches the URI authority (GHSA-c2w2-prh8-qm98) + +## 2.12.2 - 2026-06-23 + +### Fixed + +- Report URI parsing, filtering, and normalization PCRE failures explicitly +- Report HTTP message parser PCRE failures explicitly +- Fail closed when PCRE validation fails for request targets and hosts + +## 2.12.1 - 2026-06-18 + +### Security + +- Reject CR/LF in HTTP method, protocol version, and reason phrase (GHSA-vm85-hxw5-5432) + +## 2.12.0 - 2026-06-16 + +### Deprecated + +- Deprecated non-finite float values in `Query::build()` that guzzlehttp/psr7 3.0 rejects +- Deprecated non-finite float multipart contents that guzzlehttp/psr7 3.0 rejects +- Deprecated non-string scalar bodies in `Utils::streamFor()`; cast them to a string for 3.0 +- Deprecated non-string `Uri::withQueryValues()` values; cast them to a string for 3.0 + +## 2.11.1 - 2026-06-12 + +### Fixed + +- Fixed non-finite float values emitting coercion warnings on PHP 8.5 + +## 2.11.0 - 2026-06-02 + +### Changed + +- Changed `Utils::modifyRequest()` to reject conflicting URI and `Host` header changes in the same call +- Changed `Header::parse()` to split semicolon-separated parameters without repeated regular expression lookaheads +- Changed `UriComparator::isCrossOrigin()` so only HTTP and HTTPS missing ports receive implicit default ports + +### Deprecated + +- Deprecated invalid PSR-7 arguments that guzzlehttp/psr7 3.0 will require native types for +- Deprecated non-string header values that guzzlehttp/psr7 3.0 will reject +- Deprecated empty header value arrays that guzzlehttp/psr7 3.0 will reject +- Deprecated URI schemes that do not match guzzlehttp/psr7 3.0 syntax requirements +- Deprecated multipart boundary and custom part header metadata that guzzlehttp/psr7 3.0 will reject +- Deprecated reliance on automatic uppercasing of request methods; guzzlehttp/psr7 3.0 preserves method casing +- Deprecated invalid `Utils::modifyRequest()` change values that guzzlehttp/psr7 3.0 will reject + +### Fixed + +- Fixed `Utils::copyToStream()` to retry short destination writes instead of dropping the unwritten remainder +- Fixed `Header::parse()` splitting of semicolon-separated parameters with escaped quotes + +## 2.10.4 - 2026-05-29 + +### Fixed + +- Apply `UriNormalizer` percent-encoding normalizations to URI fragments +- Make `LimitStream::getSize()` return `0` for slices past the underlying stream end +- Make `AppendStream::read()` return an empty string when no streams are attached +- Make `CachingStream::read()` throw on an incomplete cache-target write instead of silently corrupting replays +- Prevent `CachingStream::seek()` from looping indefinitely when the remote stream makes no progress + +## 2.10.3 - 2026-05-27 + +### Fixed + +- Fixed URI parsing for IPv6 literals containing embedded IPv4 addresses +- Fixed malformed UTF-8 URI strings being parsed as empty URIs + +## 2.10.2 - 2026-05-25 + +### Security + +- Reject control and whitespace characters in URI host components (GHSA-hq7v-mx3g-29hw) +- Reject malformed Host values when constructing request URIs (GHSA-34xg-wgjx-8xph) + +### Fixed + +- Make `ServerRequest::fromGlobals()` robust against unexpected HTTP header value types in `$_SERVER` + +## 2.10.1 - 2026-05-20 + +### Fixed + +- Fix `Utils::modifyRequest()` with numeric header names + +## 2.10.0 - 2026-05-19 + +### Changed + +- Harden `ServerRequest::fromGlobals()` against malformed `$_SERVER` values +- Prevent custom stream metadata from affecting internal size handling +- Throw when `StreamWrapper::getResource()` cannot create a resource +- Preserve custom request implementations in `Utils::modifyRequest()` +- Preserve custom URI implementations in `UriResolver::resolve()` +- Make `Uri::__toString()` side-effect-free + +## 2.9.1 - 2026-05-19 + +### Fixed + +- Fix parsing of relative path references containing a colon in a non-initial path segment +- Fix `CachingStream::detach()` returning an incomplete resource before the decorated stream has been fully read +- Fix `Message::bodySummary()` returning `null` when truncating printable UTF-8 bodies inside a multibyte character + +## 2.9.0 - 2026-03-10 + +### Added + +- Added nested array expansion support to `MultipartStream` +- Added `@return static` to `MessageTrait` methods + +### Changed + +- Updated MIME type mappings + +## 2.8.1 - 2026-03-10 + +### Fixed + +- Encode `+` signs in `Uri::withQueryValue()` and `Uri::withQueryValues()` to prevent them being interpreted as spaces + +## 2.8.0 - 2025-08-23 + +### Added + +- Allow empty lists as header values + +### Changed + +- PHP 8.5 support + +## 2.7.1 - 2025-03-27 + +### Fixed + +- Fixed uppercase IPv6 addresses in URI + +### Changed + +- Improve uploaded file error message + +## 2.7.0 - 2024-07-18 + +### Added + +- Add `Utils::redactUserInfo()` method +- Add ability to encode bools as ints in `Query::build` + +## 2.6.3 - 2024-07-18 + +### Fixed + +- Make `StreamWrapper::stream_stat()` return `false` if inner stream's size is `null` + +### Changed + +- PHP 8.4 support + +## 2.6.2 - 2023-12-03 + +### Fixed + +- Fixed another issue with the fact that PHP transforms numeric strings in array keys to ints + +### Changed + +- Updated links in docs to their canonical versions +- Replaced `call_user_func*` with native calls + +## 2.6.1 - 2023-08-27 + +### Fixed + +- Properly handle the fact that PHP transforms numeric strings in array keys to ints + +## 2.6.0 - 2023-08-03 + +### Changed + +- Updated the mime type map to add some new entries, fix a couple of invalid entries, and remove an invalid entry +- Fallback to `application/octet-stream` if we are unable to guess the content type for a multipart file upload + +## 2.5.1 - 2023-08-03 + +### Fixed + +- Corrected mime type for `.acc` files to `audio/aac` + +### Changed + +- PHP 8.3 support + +## 2.5.0 - 2023-04-17 + +### Changed + +- Adjusted `psr/http-message` version constraint to `^1.1 || ^2.0` + +## 2.4.5 - 2023-04-17 + +### Fixed + +- Prevent possible warnings on unset variables in `ServerRequest::normalizeNestedFileSpec` +- Fixed `Message::bodySummary` when `preg_match` fails +- Fixed header validation issue + +## 2.4.4 - 2023-03-09 + +### Changed + +- Removed the need for `AllowDynamicProperties` in `LazyOpenStream` + +## 2.4.3 - 2022-10-26 + +### Changed + +- Replaced `sha1(uniqid())` by `bin2hex(random_bytes(20))` + +## 2.4.2 - 2022-10-25 + +### Fixed + +- Fixed erroneous behaviour when combining host and relative path + +## 2.4.1 - 2022-08-28 + +### Fixed + +- Rewind body before reading in `Message::bodySummary` + +## 2.4.0 - 2022-06-20 + +### Added + +- Added provisional PHP 8.2 support +- Added `UriComparator::isCrossOrigin` method + +## 2.3.0 - 2022-06-09 + +### Fixed + +- Added `Header::splitList` method +- Added `Utils::tryGetContents` method +- Improved `Stream::getContents` method +- Updated mimetype mappings + +## 2.2.2 - 2022-06-08 + +### Fixed + +- Fix `Message::parseRequestUri` for numeric headers +- Re-wrap exceptions thrown in `fread` into runtime exceptions +- Throw an exception when multipart options is misformatted + +## 2.2.1 - 2022-03-20 + +### Fixed + +- Correct header value validation + +## 2.2.0 - 2022-03-20 + +### Added + +- A more compressive list of mime types +- Add JsonSerializable to Uri +- Missing return types + +### Fixed + +- Bug MultipartStream no `uri` metadata +- Bug MultipartStream with filename for `data://` streams +- Fixed new line handling in MultipartStream +- Reduced RAM usage when copying streams +- Updated parsing in `Header::normalize()` + +## 2.1.1 - 2022-03-20 + +### Fixed + +- Validate header values properly + +## 2.1.0 - 2021-10-06 + +### Changed + +- Attempting to create a `Uri` object from a malformed URI will no longer throw a generic + `InvalidArgumentException`, but rather a `MalformedUriException`, which inherits from the former + for backwards compatibility. Callers relying on the exception being thrown to detect invalid + URIs should catch the new exception. + +### Fixed + +- Return `null` in caching stream size if remote size is `null` + +## 2.0.0 - 2021-06-30 + +Identical to the RC release. + +## 2.0.0@RC-1 - 2021-04-29 + +### Fixed + +- Handle possibly unset `url` in `stream_get_meta_data` + +## 2.0.0@beta-1 - 2021-03-21 + +### Added + +- PSR-17 factories +- Made classes final +- PHP7 type hints + +### Changed + +- When building a query string, booleans are represented as 1 and 0. + +### Removed + +- PHP < 7.2 support +- All functions in the `GuzzleHttp\Psr7` namespace + +## 1.8.1 - 2021-03-21 + +### Fixed + +- Issue parsing IPv6 URLs +- Issue modifying ServerRequest lost all its attributes + +## 1.8.0 - 2021-03-21 + +### Added + +- Locale independent URL parsing +- Most classes got a `@final` annotation to prepare for 2.0 + +### Fixed + +- Issue when creating stream from `php://input` and curl-ext is not installed +- Broken `Utils::tryFopen()` on PHP 8 + +## 1.7.0 - 2020-09-30 + +### Added + +- Replaced functions by static methods + +### Fixed + +- Converting a non-seekable stream to a string +- Handle multiple Set-Cookie correctly +- Ignore array keys in header values when merging +- Allow multibyte characters to be parsed in `Message:bodySummary()` + +### Changed + +- Restored partial HHVM 3 support + + +## [1.6.1] - 2019-07-02 + +### Fixed + +- Accept null and bool header values again + + +## [1.6.0] - 2019-06-30 + +### Added + +- Allowed version `^3.0` of `ralouphie/getallheaders` dependency (#244) +- Added MIME type for WEBP image format (#246) +- Added more validation of values according to PSR-7 and RFC standards, e.g. status code range (#250, #272) + +### Changed + +- Tests don't pass with HHVM 4.0, so HHVM support got dropped. Other libraries like composer have done the same. (#262) +- Accept port number 0 to be valid (#270) + +### Fixed + +- Fixed subsequent reads from `php://input` in ServerRequest (#247) +- Fixed readable/writable detection for certain stream modes (#248) +- Fixed encoding of special characters in the `userInfo` component of an URI (#253) + + +## [1.5.2] - 2018-12-04 + +### Fixed + +- Check body size when getting the message summary + + +## [1.5.1] - 2018-12-04 + +### Fixed + +- Get the summary of a body only if it is readable + + +## [1.5.0] - 2018-12-03 + +### Added + +- Response first-line to response string exception (fixes #145) +- A test for #129 behavior +- `get_message_body_summary` function in order to get the message summary +- `3gp` and `mkv` mime types + +### Changed + +- Clarify exception message when stream is detached + +### Deprecated + +- Deprecated parsing folded header lines as per RFC 7230 + +### Fixed + +- Fix `AppendStream::detach` to not close streams +- `InflateStream` preserves `isSeekable` attribute of the underlying stream +- `ServerRequest::getUriFromGlobals` to support URLs in query parameters + + +Several other fixes and improvements. + + +## [1.4.2] - 2017-03-20 + +### Fixed + +- Reverted BC break to `Uri::resolve` and `Uri::removeDotSegments` by removing + calls to `trigger_error` when deprecated methods are invoked. + + +## [1.4.1] - 2017-02-27 + +### Added + +- Rriggering of silenced deprecation warnings. + +### Fixed + +- Reverted BC break by reintroducing behavior to automagically fix a URI with a + relative path and an authority by adding a leading slash to the path. It's only + deprecated now. + + +## [1.4.0] - 2017-02-21 + +### Added + +- Added common URI utility methods based on RFC 3986 (see documentation in the readme): + - `Uri::isDefaultPort` + - `Uri::isAbsolute` + - `Uri::isNetworkPathReference` + - `Uri::isAbsolutePathReference` + - `Uri::isRelativePathReference` + - `Uri::isSameDocumentReference` + - `Uri::composeComponents` + - `UriNormalizer::normalize` + - `UriNormalizer::isEquivalent` + - `UriResolver::relativize` + +### Changed + +- Ensure `ServerRequest::getUriFromGlobals` returns a URI in absolute form. +- Allow `parse_response` to parse a response without delimiting space and reason. +- Ensure each URI modification results in a valid URI according to PSR-7 discussions. + Invalid modifications will throw an exception instead of returning a wrong URI or + doing some magic. + - `(new Uri)->withPath('foo')->withHost('example.com')` will throw an exception + because the path of a URI with an authority must start with a slash "/" or be empty + - `(new Uri())->withScheme('http')` will return `'http://localhost'` + +### Deprecated + +- `Uri::resolve` in favor of `UriResolver::resolve` +- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` + +### Fixed + +- `Stream::read` when length parameter <= 0. +- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory. +- `ServerRequest::getUriFromGlobals` when `Host` header contains port. +- Compatibility of URIs with `file` scheme and empty host. + + +## [1.3.1] - 2016-06-25 + +### Fixed + +- `Uri::__toString` for network path references, e.g. `//example.org`. +- Missing lowercase normalization for host. +- Handling of URI components in case they are `'0'` in a lot of places, + e.g. as a user info password. +- `Uri::withAddedHeader` to correctly merge headers with different case. +- Trimming of header values in `Uri::withAddedHeader`. Header values may + be surrounded by whitespace which should be ignored according to RFC 7230 + Section 3.2.4. This does not apply to header names. +- `Uri::withAddedHeader` with an array of header values. +- `Uri::resolve` when base path has no slash and handling of fragment. +- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the + key/value both in encoded as well as decoded form to those methods. This is + consistent with withPath, withQuery etc. +- `ServerRequest::withoutAttribute` when attribute value is null. + + +## [1.3.0] - 2016-04-13 + +### Added + +- Remaining interfaces needed for full PSR7 compatibility + (ServerRequestInterface, UploadedFileInterface, etc.). +- Support for stream_for from scalars. + +### Changed + +- Can now extend Uri. + +### Fixed +- A bug in validating request methods by making it more permissive. + + +## [1.2.3] - 2016-02-18 + +### Fixed + +- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote + streams, which can sometimes return fewer bytes than requested with `fread`. +- Handling of gzipped responses with FNAME headers. + + +## [1.2.2] - 2016-01-22 + +### Added + +- Support for URIs without any authority. +- Support for HTTP 451 'Unavailable For Legal Reasons.' +- Support for using '0' as a filename. +- Support for including non-standard ports in Host headers. + + +## [1.2.1] - 2015-11-02 + +### Changes + +- Now supporting negative offsets when seeking to SEEK_END. + + +## [1.2.0] - 2015-08-15 + +### Changed + +- Body as `"0"` is now properly added to a response. +- Now allowing forward seeking in CachingStream. +- Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +- functions.php is now conditionally required. +- user-info is no longer dropped when resolving URIs. + + +## [1.1.0] - 2015-06-24 + +### Changed + +- URIs can now be relative. +- `multipart/form-data` headers are now overridden case-insensitively. +- URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +- A port is no longer added to a URI when the scheme is missing and no port is + present. + + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` + + + +[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0 +[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0 +[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3 +[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2 +[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0 diff --git a/vendor/guzzlehttp/psr7/CLAUDE.md b/vendor/guzzlehttp/psr7/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/vendor/guzzlehttp/psr7/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/vendor/guzzlehttp/psr7/LICENSE b/vendor/guzzlehttp/psr7/LICENSE new file mode 100644 index 0000000..51c7ec8 --- /dev/null +++ b/vendor/guzzlehttp/psr7/LICENSE @@ -0,0 +1,26 @@ +The MIT License (MIT) + +Copyright (c) 2015 Michael Dowling +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Graham Campbell +Copyright (c) 2016 Tobias Schultze +Copyright (c) 2016 George Mponos +Copyright (c) 2018 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/guzzlehttp/psr7/README.md b/vendor/guzzlehttp/psr7/README.md new file mode 100644 index 0000000..a95d69a --- /dev/null +++ b/vendor/guzzlehttp/psr7/README.md @@ -0,0 +1,88 @@ +# Guzzle PSR-7 + +`guzzlehttp/psr7` is a PSR-7 HTTP message implementation for PHP. It provides +request, response, URI, uploaded file, and stream objects that work with Guzzle +and any other library using the PSR-7 interfaces. + +Use this package directly when you need to create or inspect PSR-7 messages +without sending HTTP requests. If you only want to make HTTP requests, install +[`guzzlehttp/guzzle`](https://github.com/guzzle/guzzle/blob/8.0/README.md) +instead; it already depends on this package. + +## Installation + +```bash +composer require guzzlehttp/psr7 +``` + +## Version Guidance + +| Version | Status | PHP Version | +|---------|--------------|--------------| +| 3.6 | Latest | >=7.4,<8.7 | +| 2.13 | Maintenance | >=7.2.5,<8.7 | +| 1.9 | End of Life | >=5.4,<8.2 | + +## Quick Start + +```php +use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Response; +use GuzzleHttp\Psr7\Utils; + +$request = new Request('GET', 'https://example.com/api'); +$response = new Response(200, ['Content-Type' => 'text/plain'], 'OK'); +$stream = Utils::streamFor('request or response body'); + +echo $request->getMethod(); +echo $response->getStatusCode(); +echo $stream; +``` + +PSR-7 messages and URIs are immutable. Methods such as `withHeader()` and +`withUri()` return a changed copy instead of modifying the original object. +Streams are mutable body handles; reading, writing, seeking, and closing a +stream can change its cursor, contents, or usability. + +```php +$request = $request->withHeader('Accept', 'application/json'); +``` + +## Documentation + +- [PSR-7 Messages](docs/psr-7-messages.md) +- [Streams and Decorators](docs/streams-and-decorators.md) +- [URI Helpers](docs/uri-helpers.md) +- [PSR-17 Factories](docs/psr-17-factories.md) +- [Message Helpers](docs/message-helpers.md) +- [Diagnostic Values](docs/diagnostic-values.md) +- [Error Scopes](docs/error-scopes.md) +- [Header and Query Helpers](docs/header-and-query-helpers.md) +- [Stream Helpers](docs/stream-helpers.md) +- [URI and MIME Helpers](docs/uri-and-mime-helpers.md) +- [Upgrade Guide](UPGRADING.md) +- [Changelog](CHANGELOG.md) + +## Security + +If you discover a security vulnerability within this package, please send an +email to security@tidelift.com. All security vulnerabilities will be promptly +addressed by the security maintainers listed in the +[Security Policy](https://github.com/guzzle/psr7/security/policy). Please do not +disclose security-related issues publicly until a fix has been announced. + +## License + +Guzzle is made available under the MIT License (MIT). Please see +[License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with +Tidelift to deliver commercial support and maintenance for the open source +dependencies you use to build your applications. Save time, reduce risk, and +improve code health, while paying the maintainers of the exact dependencies you +use. +[Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/vendor/guzzlehttp/psr7/UPGRADING.md b/vendor/guzzlehttp/psr7/UPGRADING.md new file mode 100644 index 0000000..09d33de --- /dev/null +++ b/vendor/guzzlehttp/psr7/UPGRADING.md @@ -0,0 +1,1101 @@ +Guzzle PSR-7 Upgrade Guide +========================== + +2.x to 3.0 +---------- + +Guzzle PSR-7 3.0 is a major release that raises the minimum PHP version, +updates to the PSR-7 v2 interfaces, validates header values more strictly, +preserves explicit request method casing, and rejects several invalid URI, +request, response, upload, query, stream, and multipart values that 2.x +previously accepted or cast. + +#### PHP Version and Dependencies + +Guzzle PSR-7 3.0 requires PHP `^7.4 || ^8.0`. Guzzle PSR-7 2.x supported PHP +`^7.2.5 || ^8.0`. + +If your application still supports PHP 7.2 or 7.3, continue using Guzzle PSR-7 +2.x until your minimum PHP version is raised. + +Guzzle PSR-7 3.0 requires `psr/http-message:^2.0` and +`psr/http-factory:^1.1`. Guzzle PSR-7 2.x supported +`psr/http-message:^1.1 || ^2.0` and `psr/http-factory:^1.0`. If your dependency +constraints pin `psr/http-message` to v1, update them before upgrading. + +Guzzle PSR-7 no longer depends on `ralouphie/getallheaders` and no longer +provides a transitive global `getallheaders()` polyfill. +`ServerRequest::fromGlobals()` continues to collect request headers internally. +Applications that call `getallheaders()` directly on SAPIs where PHP does not +provide it should require their own polyfill. + +#### Header Values + +Header values must now be strings or non-empty arrays of strings. Empty strings +remain valid explicit header values, but empty arrays, `null`, `false`, integers, +floats, and other non-string values are no longer cast or accepted. + +```php +// 2.x, no longer accepted in 3.0 +$response = $response->withHeader('Api-Version', 1); +$response = $response->withHeader('Empty-List', []); + +// 3.0 +$response = $response->withHeader('Api-Version', '1'); +$response = $response->withHeader('Empty-Value', ''); +``` + +Use `withoutHeader()` to remove a header. + +#### Request Method Casing + +Request methods passed explicitly to `Request`, `ServerRequest`, `withMethod()`, +`Message::parseRequest()`, and the PSR-17 factories are no longer uppercased. +PSR-7 treats method names as case-sensitive, so these APIs now preserve the +method exactly as provided. If your application requires uppercase methods, +normalize methods before constructing or modifying requests. + +`ServerRequest::fromGlobals()` is the compatibility-oriented exception. It +continues to uppercase string `REQUEST_METHOD` values read from PHP server +globals, matching Guzzle PSR-7 2.x and common server request behavior. This +normalization only applies when hydrating from globals; it does not apply to +methods passed explicitly to constructors, factories, or `withMethod()`. + +```php +// 2.x +$request = new Request('get', '/'); +$request->getMethod(); // GET + +// 3.0 +$request = new Request('get', '/'); +$request->getMethod(); // get + +// 3.0, server globals +$_SERVER['REQUEST_METHOD'] = 'post'; +$request = ServerRequest::fromGlobals(); +$request->getMethod(); // POST +``` + +#### Native PSR-7 Parameter Types + +Guzzle PSR-7 3.0 requires the argument types documented by PSR-7 more strictly. +It adds the native parameter types from `psr/http-message` v2. Code passing +invalid argument types may now receive PHP `TypeError` exceptions instead of +package-specific `InvalidArgumentException` exceptions or implicit casts. + +Native parameter type changes include: + +- `MessageInterface::withProtocolVersion()` now requires `string`. +- Message header names now require `string`. +- `RequestInterface::withRequestTarget()` and `withMethod()` now require `string`. +- `RequestInterface::withUri()` now requires `bool` for `$preserveHost`. +- `ResponseInterface::withStatus()` now requires `int` status codes and `string` reason phrases. +- Server request attribute names now require `string`. +- `UriInterface::withPort()` now requires `int|null`. +- URI scheme, user info, host, path, query, and fragment mutators now require strings. +- Stream `seek()`, `read()`, `write()`, and `getMetadata()` now require their PSR-7 v2 parameter types. +- `UploadedFileInterface::moveTo()` now requires a string target path. + +Update callers to pass values of the documented type before calling these +methods: + +```php +// 2.x, no longer supported in 3.0 +$response = $response->withStatus('201'); +$uri = $uri->withPort('8080'); + +// 3.0 +$response = $response->withStatus(201); +$uri = $uri->withPort(8080); +``` + +#### Request Modification Changes + +`Utils::modifyRequest()` now validates recognized change values before applying +request modifications. Unknown change keys are still ignored. Explicit `null` +values are no longer treated as omitted recognized changes; omit the key instead. + +Recognized change values must use the documented types: + +- `method`: `string` +- `uri`: `UriInterface` +- `query`: `string` +- `version`: `string` +- `body`: `resource|string|StreamInterface|callable|\Iterator|\Stringable` +- `set_headers`: `array>` +- `remove_headers`: `array` + +When a `uri` change contains a host, the synthesized `Host` header now +includes any non-default URI port, matching the `Request` constructor. 2.x +omitted port zero and every port on schemes other than HTTP and HTTPS. + +#### Uploaded Files + +`ServerRequestInterface::withUploadedFiles()` now rejects invalid nested upload +trees. Every leaf must be an `UploadedFileInterface` instance. + +`ServerRequest::normalizeFiles()` and `ServerRequest::fromGlobals()` now reject +malformed `$_FILES` specifications earlier. Single-file specifications must +contain non-null `tmp_name`, `size`, and `error` values. Single-file and nested +file `size` values and `error` values must be non-negative PHP integers; +numeric strings are no longer cast. If PHP supplies an upload size as a string +because the byte count cannot fit in `PHP_INT_MAX`, it is rejected rather than +truncated or cast. Nested specifications must provide `tmp_name`, `size`, and +`error` as arrays. Every key in `tmp_name` must also exist in `size` and +`error`; additional metadata entries without a matching `tmp_name` entry are +ignored. When nested `name` or `type` metadata is provided, it must also be an +array. + +If your tests or adapters build `$_FILES` arrays manually, populate the full +shape or create `UploadedFile` instances directly. + +```php +// 2.x, no longer accepted in 3.0 +$files = ['file' => ['tmp_name' => '/tmp/php123', 'error' => '0']]; + +// 3.0 +$files = ['file' => ['tmp_name' => '/tmp/php123', 'size' => 123, 'error' => UPLOAD_ERR_OK]]; +``` + +For stream-backed uploads, `UploadedFile::moveTo()` now rewinds seekable streams +before copying them. If application code reads from a seekable uploaded stream +before calling `moveTo()`, 3.0 writes the full stream contents to the target +instead of only the unread suffix. Non-seekable stream-backed uploads continue to +copy from their current position because consumed bytes cannot be replayed. + +#### Parsed Body Values + +`ServerRequestInterface::withParsedBody()` now rejects values other than +`array`, `object`, or `null`. + +```php +// 2.x, no longer accepted in 3.0 +$request = $request->withParsedBody('name=value'); + +// 3.0 +$request = $request->withParsedBody(['name' => 'value']); +``` + +#### URI Host and Scheme Validation + +URI hosts containing URI delimiters, backslashes, embedded ports passed to +`withHost()`, malformed IP-literal brackets, unbracketed IPv6, or other +malformed host forms are no longer accepted. URI schemes containing whitespace +or control characters are also no longer accepted. + +If you previously passed a host and port together to `withHost()`, split them +between `withHost()` and `withPort()`: + +```php +// 2.x, no longer accepted in 3.0 +$uri = $uri->withHost('example.com:8080'); + +// 3.0 +$uri = $uri->withHost('example.com')->withPort(8080); +``` + +Normal URI strings with ports are still supported: + +```php +$uri = new Uri('https://example.com:8080/path'); +``` + +URI parsing now accepts bracketed IPv6 and IPvFuture hosts consistently with +`withHost()` for userinfo and network-path authorities such as +`http://user@[::1]/`, `//[::1]`, and `http://[v7.a:b]/`. Invalid +delimiter-free bracketed literals, such as `[gggg::1]`, are also reported with +the intact host. Bracketed literals containing authority/path delimiters, such +as `[a@b]` or `[v1.a/b]`, still reject after fallback parsing and may report the +mangled parsed host. + +Userinfo before a bracketed IP-literal host is now percent-encoded ahead of +parsing, so raw control bytes yield encoded userinfo, such as `us%01er`, +instead of a silently mutated value, and raw DEL bytes in bracketed hosts are +rejected instead of parsed as a mutated host. Consistent with registered-name +authorities, such userinfo containing invalid UTF-8 is now rejected, +percent-sequences such as `u%41` are preserved rather than decoded, and a +literal `+` is preserved rather than decoded to a space. + +Only an optional numeric port (which may be empty) and a path, query, or +fragment may follow a bracketed IP-literal host. Trailing bytes that are +neither, such as `http://[::1]:80@evil/` or `http://[::1]:80x/`, are now +rejected instead of being reparsed into a different host. + +Parsing still URL-decodes bracketed IP-literal hosts before validation +(registered-name hosts round-trip unchanged), so a literal `+` in a bracketed +IP-literal decodes to a space and is rejected: `withHost('[v1.fe80::a+en1]')` +accepts the literal while parsing `http://[v1.fe80::a+en1]/` rejects it. +Percent-encoding inside a bracketed IP-literal is now rejected during parsing as +well, since RFC 3986 IP-literals contain no percent-encoding, so +`http://[%3A%3A1]/` no longer decodes to `[::1]`; this matches `withHost()` and +`Rfc3986::isValidHost()`. + +Percent-encoded octets in a registered-name host are normalized to uppercase +hex, so a host such as `a%c3%a9b` is represented as `a%C3%A9b`. Malformed +percent sequences and percent-encoded octets that decode to a byte forbidden in +a host, such as `ex%zz` and `%2fhost`, are rejected. + +`Uri::fromParts()` accepts integer and decimal digit string ports, but floats and +other port values are no longer cast. + +Common host forms such as `localhost`, single-label hosts, underscores, Unicode +hosts, valid IPv6 literals, and normal host and port URI strings remain +supported. + +URI schemes must now match RFC 3986 syntax and begin with a letter. + +```php +// 2.x, no longer accepted in 3.0 +$uri = (new Uri())->withScheme('0'); + +// 3.0 +$uri = (new Uri())->withScheme('https'); +``` + +A URI string whose scheme contains a plus sign, such as +`svn+ssh://example.com/path`, is now parsed with that scheme, including one with +no authority such as `C++:intro`, which now has the scheme `c++`. In 2.x, both +were parsed as relative paths with no scheme and no host. The rest of the string +is held to the rules that apply after any other scheme, so a string whose +authority is empty or is not a valid host, such as `git+file:///srv/repo.git` or +`http+unix://%2Fvar%2Frun%2Fdocker.sock/info`, is now rejected. + +The stricter validation also applies when a request is created or modified from +a custom `UriInterface` implementation and its host is used to generate or +update a `Host` header. + +`ServerRequest::getUriFromGlobals()` now falls back to `SERVER_NAME`, then +`SERVER_ADDR`, then the existing default host behavior for malformed +`HTTP_HOST` values. It also rejects zero-port `HTTP_HOST` authorities and +malformed `SERVER_PORT` values when fallback authority reconstruction needs the +server port. When `REQUEST_URI` is absolute-form or CONNECT authority-form and +supplies a valid authority, that authority is used before fallback `SERVER_PORT` +validation. Origin-form, asterisk-form, missing `REQUEST_URI`, and fallback +reconstruction paths still reject malformed `SERVER_PORT` values when fallback +authority reconstruction needs the server port. + +Absolute-form `REQUEST_URI` userinfo is removed when reconstructing the URI and +request target from globals, including empty userinfo such as +`http://@example.com/`. The host after the last raw `@` remains the URI host. + +`Message::parseRequest()` now applies 3.0 authority rules when deriving a URI +from an origin-form or asterisk-form request target. Host ports with leading +zeroes are normalized for URI reconstruction, and port zero is rejected. +It also rejects duplicate `Host` field lines, including case-insensitive +duplicates. Any present raw `Host` field is validated before returning a parsed +request, even when the request target supplies the URI authority, such as +absolute-form and CONNECT requests. Valid `Host` values may still differ from +the absolute-form or CONNECT request-target authority. + +For server globals, applications that need to reject malformed inbound `Host` +headers should validate the original server parameters before calling +`getUriFromGlobals()` or inspect them afterward. + +`Message::parseRequest()` now applies the same HTTP authority validation to +absolute-form request targets. A zero or padded-zero port +(`http://example.com:0/admin`) is rejected instead of producing a request +whose synthesized `Host` header the same parser rejects elsewhere. +Absolute-form targets with no URI host, such as `file:///etc/passwd`, are +also rejected instead of producing a hostless request URI. + +Absolute-form targets whose authority contains userinfo are also rejected, +including empty userinfo such as `http://@example.com/`. RFC 9110 deprecates +userinfo in http(s) target URIs and directs recipients to treat its presence +as an error; `Host` headers and CONNECT targets already reject it. These +rules apply to absolute-form targets of every scheme. +`ServerRequest::fromGlobals()` is unchanged and continues to strip +`REQUEST_URI` userinfo. + +URI hosts now validate percent-encoding. Malformed sequences such as `ex%zz`, +and percent-encoded octets that decode to bytes the raw host grammar already +rejects (controls, space, DEL, `/`, `?`, `#`, `@`, `\`, `:`, `[`, `]`, and `%` +itself) throw `MalformedUriException` from URI parsing and +`InvalidArgumentException` from `Uri::withHost()`, and are rejected wherever +hosts are validated, including `Host` headers and request targets in +`Message::parseRequest()`. WHATWG-conformant browsers reject all of these hosts; +curl rejects them too, except encoded DEL (`%7F`), which it decodes and forwards +to name resolution. Other percent-encoded octets, including UTF-8 data such as +`a%C3%A9b`, remain accepted and are normalized to uppercase hex. + +IPv6 hosts are now canonicalized to their RFC 5952 form when a URI is +constructed, so `getHost()`, `getAuthority()`, and `(string) $uri` return the +canonical spelling and synthesized `Host` headers use it. Leading zeros are +suppressed, hexadecimal fields are lowercase, and the longest run of two or +more zero fields is collapsed with `::`. Embedded dotted-decimal notation +follows the rendering policy of BIND-derived `inet_ntop()` implementations and +curl 8.11 and newer: exactly the IPv4-mapped (`::ffff:0:0/96`) and deprecated +IPv4-compatible (`::/96`) layouts use it, while other embedded-IPv4 forms, +including translated (NAT64) well-known prefixes such as `64:ff9b::/96` +(RFC 6052), serialize in pure hexadecimal fields. + +```php +// 2.x preserved the spelling as given +(string) new Uri('http://[0:0:0:0:0:0:0:1]/'); // http://[0:0:0:0:0:0:0:1]/ + +// 3.0 +(string) new Uri('http://[0:0:0:0:0:0:0:1]/'); // http://[::1]/ +(string) new Uri('http://[::FFFF:7F00:1]/'); // http://[::ffff:127.0.0.1]/ +(string) new Uri('http://[2001:db8:3:4::192.0.2.33]/'); // http://[2001:db8:3:4::c000:221]/ +``` + +Applications that persist URI strings, for example as cache keys, will observe +the new canonical form for previously non-canonical IPv6 spellings. Equivalent +spellings of the same address now compare as same-origin in +`UriComparator::isCrossOrigin()`, which canonicalizes bracketed IPv6 literals +from any PSR-7 implementation before comparing hosts, and as equivalent in +`UriNormalizer::isEquivalent()`. The new +`UriNormalizer::CANONICALIZE_IPV6_HOST` flag, included in the default +`UriNormalizer::PRESERVING_NORMALIZATIONS`, requests the canonical host from +other PSR-7 implementations through `withHost()` and keeps the result only +when the returned `getHost()` exactly matches the requested spelling; a +nonexact result leaves that step unchanged while other selected normalizations +still apply, and setter exceptions propagate. `UriComparator` does not share +this limitation, since it canonicalizes the extracted host text directly. The +public helper `Rfc3986::canonicalizeIpv6()` exposes the underlying +transformation. + +#### Request Host Synchronization + +`Request::withUri()` now applies PSR-7 Host header synchronization before using +the same-URI no-op shortcut. When the provided URI is the same object already +attached to the request, the method may still return a new request if the URI +has a host and the current Host header is missing, empty, or stale. + +With `$preserveHost = true`, a non-empty Host header is still preserved. Missing +or empty Host headers are treated as absent and are populated from the URI when +the URI contains a host. + +```php +$request = (new Request('GET', 'http://example.com:8124/'))->withoutHeader('Host'); + +$updated = $request->withUri($request->getUri()); + +$updated->getHeaderLine('Host'); // example.com:8124 +``` + +If your application intentionally sends an empty or stale Host header, set it +after calling `withUri()` or preserve a non-empty Host header explicitly. + +`Message::toString()` now applies the same URI host and port synthesis when +serializing a request without a `Host` header. Generated `Host` lines include +non-null URI ports. + +`Message::toString()` also validates the host it synthesizes from the request +URI and throws `InvalidArgumentException` for an invalid host, closing a header- +injection vector. This affects only a custom `UriInterface` implementation that +returns an invalid host when the request has no stored `Host` header; first- +party `Uri` instances always carry a valid host and are unaffected. + +#### URI Paths and Request Targets + +`Uri::getPath()` now normalizes multiple leading slashes to one slash when +returning the path in isolation. Casting the URI to string still preserves the +original URI representation. + +```php +$uri = new Uri('http://example.org//valid///path'); + +$uri->getPath(); // /valid///path +(string) $uri; // http://example.org//valid///path +``` + +`Request::getRequestTarget()` applies the same normalization for URI-derived +origin-form request targets. + +Reference resolution and normalization (`UriResolver`, `UriNormalizer`, and +`Uri::isSameDocumentReference()`) operate on the raw path from the URI string +form and are therefore unaffected by this normalization. + +Authority-less `file` URIs with rootless paths now serialize without the `//` +authority separator: `(string) new Uri('file:foo/bar')` returns `file:foo/bar` +instead of `file://foo/bar`, which reparses with host `foo` and path `/bar`. +Rooted paths such as `file:///myfile` keep their existing serialization. + +Authority-less `file` URIs with empty paths now serialize as `file:` instead of +`file://`, which `new Uri()` itself rejects as unparseable. This affects +degenerate URIs such as `new Uri('file:')` or +`Uri::fromParts(['scheme' => 'file'])`; the serialization of every file URI +with a non-empty path is unchanged. + +`UriResolver::removeDotSegments()` now applies RFC 3986 Section 5.2.4 to `..` +segments above the root of an absolute path: excess `..` segments no longer +consume the root, so a following empty segment is preserved. Resolving `/..//a` +against `http://example.org/base` yields `http://example.org//a` where 2.x +produced `http://example.org/a`. When the resulting URI has no authority, +`UriResolver::resolve()` and `UriNormalizer::normalize()` serialize such a +`//`-leading path with a `/.` prefix (`mailto:/.//a`), like the WHATWG URL +Standard, instead of collapsing the slashes or throwing. + +#### URI Reference Relativization + +`UriResolver::relativize()` now returns a network-path reference (for example +`//example.com`) when the target URI has the same authority as the base URI +but an empty path that no other relative reference round-trips. No path +reference can express such a target, as resolving one always produces a path +of at least `/`, and an empty reference would keep the base path or inherit +the base query or fragment. The returned reference resolves back to the +exact target string, restoring the documented round-trip guarantee for these +targets. + +```php +$base = new Uri('http://example.com/a'); +$target = new Uri('http://example.com'); + +// 2.x +(string) UriResolver::relativize($base, $target); // ../ +// which resolved back to http://example.com/ + +// 3.0 +(string) UriResolver::relativize($base, $target); // //example.com +``` + +The same applies when the base URI has a query or fragment component that an +empty relative reference would otherwise inherit. When the base URI has an +empty path as well and nothing would be inherited, shorter references such +as the empty reference, `#fragment` or `?query` are still returned. + +`relativize()` also no longer returns the empty reference when the target +path equals the base path but the base has a fragment the target lacks, as +the empty reference would reintroduce that fragment. A relative-path +reference, or a query reference when the target has a query, is returned +instead. When the relative-path reference would be a single path segment +containing a colon, which would be mistaken for a scheme name, it is +prefixed with `./` (for example `./a:b`); 2.x threw a `MalformedUriException` +for such targets when the base had a query the target lacked. + +#### HTTP Start-line Parsing + +`Message::parseRequest()` and `Message::parseResponse()` now validate HTTP +start-line fields more strictly. Malformed request methods, request targets +containing whitespace or control characters, malformed protocol versions, +invalid response status codes, invalid response spacing, and reason phrases +containing invalid control characters now throw `InvalidArgumentException`. + +`Request` and `Response` constructors and mutators apply the same validation to +protocol versions, request targets, status codes, and reason phrases. If you +parse raw HTTP messages or construct messages from partially validated input, +normalize or reject invalid values before passing them to Guzzle PSR-7. + +```php +// 2.x-style tolerant input, no longer accepted in 3.0 +Message::parseRequest("GET /foo bar HTTP/1.1\r\nHost: example.com\r\n\r\n"); +new Response(200, [], null, 'HTTP/1.1'); + +// 3.0 +Message::parseRequest("GET /foo%20bar HTTP/1.1\r\nHost: example.com\r\n\r\n"); +new Response(200, [], null, '1.1'); +``` + +`ServerRequest::fromGlobals()` applies the same validation to the +`REQUEST_METHOD` and `SERVER_PROTOCOL` server values. Malformed values that 2.x +hydrated, such as the `SERVER_PROTOCOL` value `INCLUDED` that Apache sets for +server-side include subrequests, now throw `InvalidArgumentException`. Sanitize +`$_SERVER` before calling `fromGlobals()` if such environments must be +tolerated. + +`Request::withRequestTarget('')` throws `InvalidArgumentException`; omit the +explicit request target to derive `/` or the URI-derived target automatically. + +`Message::parseMessage()` no longer unfolds folded HTTP/1.0 messages whose +start line carries control bytes in the request target; such messages now +throw the obsolete-line-folding `InvalidArgumentException`. +`Message::parseRequest()` and `Message::parseResponse()` rejected these +messages either way. + +#### Query Builder Values + +`Query::build()` now rejects unsupported values instead of relying on PHP string +casts. Query values must be scalar, `null`, stringable objects, or flat arrays of +those values. + +Nested arrays, resources, and objects without `__toString()` now throw +`InvalidArgumentException`. + +```php +// Before: could produce warnings or silently mangle the value. +Query::build(['filter' => ['name' => ['value']]]); + +// After: use explicit query keys for nested query shapes. +Query::build(['filter[name]' => 'value']); +``` + +Flat arrays are still supported for repeated query parameters: + +```php +Query::build(['tag' => ['a', 'b']]); +// tag=a&tag=b +``` + +`Uri::withQueryValues()` is stricter than `Query::build()` and requires `string` +or `null` values; cast numeric and boolean query values to string. + +#### Non-string Scalar Bodies + +`Utils::streamFor()` and message bodies no longer accept `int`, `float`, or +`bool` values. Cast them to strings first. + +```php +// 2.x, no longer accepted in 3.0 +$response = new Response(200, [], 404); + +// 3.0 +$response = new Response(200, [], '404'); +``` + +#### PumpStream Source Callables + +`PumpStream` source callables must now return a non-empty string when producing +data. Returning an empty string now throws `RuntimeException` instead of being +retried indefinitely. Return `false` or `null` to signal EOF. + +If your callable used `''` to mean "temporarily no data", update it to wait +until data is available, return a non-empty string, or return `false` or `null` +when the stream is complete. + +#### Iterator-backed Streams + +`Utils::streamFor()` now validates values yielded by `Iterator` instances before +passing them to the internal `PumpStream`. Strings, integers, finite floats, +booleans, `null`, and stringable objects are converted to string chunks. +Non-finite floats, arrays, resources, and non-stringable objects now throw +`UnexpectedValueException` when the stream is read. + +Iterator exhaustion is now the only EOF signal for iterator-backed streams. +Yielding `false`, `null`, or an empty string no longer ends the stream; those +values are zero-length chunks and are skipped while the iterator advances. If +your iterator yielded `false` or `null` to stop streaming, update it to finish +iteration instead. + +Avoid iterators that yield only zero-length chunks indefinitely. Such iterators +never produce bytes and never reach EOF, so they cannot satisfy stream reads. + +```php +// Before: yielding false or null could stop an iterator-backed stream early. +$stream = Utils::streamFor(new ArrayIterator([false, 'body'])); + +// After: false and null are skipped chunks. End the iterator to signal EOF. +$stream = Utils::streamFor(new ArrayIterator(['body'])); +``` + +#### Stream Behavior Changes + +All stream implementations now reject negative `read()` lengths with +`RuntimeException`. In 2.x, some decorators passed negative lengths through, +some returned sliced data, and some behavior varied by PHP version. + +`LimitStream` now rejects negative offsets and limits below `-1`. For +non-seekable streams, offsets are tracked by the number of bytes actually +skipped. Short reads are retried until the offset is reached, EOF is reached, or +the decorated stream stops making progress. + +`StreamWrapper` now translates `RuntimeException` failures from the wrapped +PSR-7 stream into PHP stream-wrapper failure values. When using a resource from +`StreamWrapper::getResource()`, functions such as `fread()`, `fwrite()`, +`fseek()`, `feof()`, and `fstat()` may now return normal PHP failure values +instead of propagating the PSR-7 stream exception. Call the PSR-7 stream directly +if you need exception-based failure handling. + +The `StreamWrapper::stream_read()` callback no longer declares a native return +type so read failures can return `false`. The `StreamWrapper::stream_tell()` +callback no longer declares a native return type so post-seek position lookup +failures can make `fseek()` fail. + +`Utils::tryFopen()` and `Utils::tryGetContents()` no longer fail when a +deprecation is raised during the call, or when code inside the call silences an +error with the `@` operator. Those errors are passed on to the previously +installed error handler instead. In 2.x, any PHP error raised while the file was +opened or the stream was read made the call throw, even when a userland stream +wrapper or stream filter raised it and the operation itself succeeded. This also +applies to `Stream::getContents()`, `Stream::__toString()`, and +`LazyOpenStream`, which use these helpers. + +#### Stream Mode Capabilities + +`Stream::isReadable()` and `Stream::isWritable()` now follow PHP stream mode +semantics more closely. Update modes are detected by the presence of `+`, +including valid modes such as `rt+`, `wt+`, `at+`, `xt+`, and `ct+`. + +Literal `rw` metadata is now treated as read-only, matching PHP real-file +streams. If a custom stream wrapper previously exposed `rw` for a writable +resource, open it with a valid update mode such as `r+`, `w+`, or `a+` instead. + +#### Stream Copy Behavior + +Stream sizes, offsets, high-water marks, and byte counts are now validated as +non-negative PHP integers where applicable. Operations that would overflow +`PHP_INT_MAX` throw `OverflowException` instead of silently wrapping or producing +an invalid position or size. + +`Utils::copyToStream()` now returns the number of bytes copied and throws a +`RuntimeException` when the destination stream cannot make progress, for example +a `BufferStream` at its high-water mark or a full `DroppingStream`. Its +signature changed from `: void` to `: int`, but callers that ignore the return +value do not need to change anything. In 2.x, the copy stopped silently when the +destination could not make progress. For a guaranteed full copy, use a normal +writable stream such as a file or `php://temp` stream. + +#### Stream Timeout Detection + +Timed-out stream operations now throw +`GuzzleHttp\Psr7\Exception\TimeoutException`, which extends +`RuntimeException`. `Stream::read()`, `Stream::write()`, +`AppendStream::read()`, `CachingStream::read()`, `InflateStream::read()`, +`Utils::copyToStream()`, `Utils::copyToString()`, `Utils::hash()`, +`Utils::readLine()`, and `Utils::tryGetContents()` detect PHP-style stream +timeout metadata when a read or write operation cannot make progress. Timeout +detection is best-effort; custom stream implementations that do not expose +`timed_out` metadata continue to behave as before. Previously, timed-out reads +could be treated as EOF or return partial results, and timed-out writes could be +reported as generic write failures or no-progress writes. + +#### Message Body Summaries + +`Message::bodySummary()` still summarizes seekable bodies from the beginning, +even when the body was already partially read. It now restores the body cursor to +the position it had before the summary was created. In 2.x, calling +`bodySummary()` left seekable bodies rewound to the beginning. The optional +`$truncateAt` argument now accepts `null` as an explicit request for the default +summary length, matching the behavior of omitting the argument. + +Most applications do not need to change anything. Check your code only if you +called `bodySummary()` and then read the same body while relying on +`bodySummary()` to leave the body rewound. If you need to read the body from the +beginning after summarizing it, call `Message::rewindBody()` explicitly. + +#### Stream Lifecycle + +`FnStream` now treats `close()` and successful `detach()` calls as terminal +lifecycle operations. Its configured `close` callback is invoked at most once; +repeated `close()` calls are no-ops, destruction after explicit close no longer +invokes the close callback, and closed or detached streams no longer forward +read, write, seek, metadata, or stringification callbacks. `FnStream` also +suppresses exceptions thrown by destructor-triggered close callbacks. Call +`close()` explicitly if cleanup failures must be observed. + +`CachingStream::close()` is now idempotent. Calling `close()` after `detach()` +still closes the remote stream owned by the `CachingStream`, but it no longer +closes the detached cache resource returned to the caller. Repeated `close()` +calls are no-ops. + +`InflateStream::close()` now also closes the compressed source stream that was +passed to its constructor. In 2.x, closing an `InflateStream` left the source +stream open. Call `detach()` instead of `close()` if the compressed source +stream must stay open; `close()` after `detach()` no longer closes the source. + +`PumpStream::close()` and `PumpStream::detach()` now discard internally buffered +unread bytes. If a callable or iterator source returns more bytes than a read +requested, drain the stream before closing it if you need those buffered bytes. + +#### Multipart Part Headers and Metadata + +`MultipartStream` no longer adds default `Content-Length` headers to individual +`multipart/form-data` parts. RFC 7578 section 4.8 says multipart form-data +parts must not include `Content-*` headers other than the supported multipart +part headers, so 3.0 stops generating per-part `Content-Length` by default. + +If your tests compare raw multipart payloads, remove the generated +`Content-Length` lines from expected strings: + +```text +// 2.x generated: +--boundary\r\n +Content-Disposition: form-data; name="foo"\r\n +Content-Length: 3\r\n +\r\n +bar\r\n + +// 3.0 generates: +--boundary\r\n +Content-Disposition: form-data; name="foo"\r\n +\r\n +bar\r\n +``` + +Applications can still pass an explicit `Content-Length` header in a multipart +element's `headers` array if a non-standard peer requires it: + +```php +$body = new MultipartStream([ + [ + 'name' => 'foo', + 'contents' => 'bar', + 'headers' => ['Content-Length' => '3'], + ], +]); +``` + +`MultipartStream` now escapes generated `Content-Disposition` `name` and +`filename` parameters before serializing multipart part headers. Double quotes, +carriage returns, and line feeds are encoded as `%22`, `%0D`, and `%0A`. Literal +backslashes and other characters are serialized unchanged, matching browser +multipart form submission behavior. + +```php +// Before: these values were interpolated into the generated part header. +$body = new MultipartStream([ + [ + 'name' => "field\"\r\nname", + 'filename' => "avatar\"\r\n.txt", + 'contents' => 'body', + ], +]); + +// After: the generated Content-Disposition parameters contain +// field%22%0D%0Aname and avatar%22%0D%0A.txt. +``` + +Explicit custom boundaries are now validated using RFC 2046 multipart boundary +syntax. Omit the boundary or pass `null` to continue using a generated random +boundary. + +The string `'0'` is now treated as an explicit custom boundary and is serialized +literally. In 2.x, PHP truthiness caused `new MultipartStream($elements, '0')` +to use a generated random boundary. Omit the boundary or pass `null` when you +want a generated boundary. + +Custom multipart part header names and values are also validated before +serialization. Header names must be valid HTTP tokens, and header values must be +strings without CR, LF, or other invalid control bytes. + +`MultipartStream` now preserves trailing spaces and tabs in custom multipart +part header values when serializing the body. In 2.x, the final serialized part +header line was trimmed as a side effect of removing the generated header +terminator. Normal multipart parsers treat this optional whitespace as +insignificant, but tests, signatures, or snapshots that compare raw multipart +body bytes may need updated expectations. + +#### URI Userinfo Redaction + +`Utils::redactUserInfo()` now redacts all non-empty URI userinfo, including +username-only userinfo. In 2.x, it only redacted the password portion when +userinfo contained a password delimiter. + +```php +use GuzzleHttp\Psr7\Uri; +use GuzzleHttp\Psr7\Utils; + +// 2.x: https://TOKEN@example.com +// 3.0: https://***@example.com +(string) Utils::redactUserInfo(new Uri('https://TOKEN@example.com')); + +// 2.x: https://user:***@example.com +// 3.0: https://***@example.com +(string) Utils::redactUserInfo(new Uri('https://user:pass@example.com')); +``` + +#### Header List Helpers + +The deprecated `Header::normalize()` method was removed. Use +`Header::splitList()` to split HTTP headers that are defined as comma-separated +lists. + +`Header::splitList()` now trims list elements with spaces, horizontal tabs, +carriage returns, and line feeds. 2.x also trimmed null bytes and vertical +tabs. Validated header values cannot contain those bytes, so this only affects +strings passed to `Header::splitList()` directly. + +#### Non-instantiable Utility Classes + +Static utility and constant classes such as `Header`, `Message`, `MimeType`, +`Query`, and `Utils` now have private constructors. Replace any accidental +instantiation with static method calls or constant access. + +#### Native PHP Serialization of Streams + +Guzzle PSR-7 stream implementations no longer support native PHP `serialize()` +or `unserialize()`. Persist stream contents explicitly and recreate streams with +`Utils::streamFor()` when needed. + +#### URI Normalization of Userinfo and Host + +`UriNormalizer::CAPITALIZE_PERCENT_ENCODING` and +`UriNormalizer::DECODE_UNRESERVED_CHARACTERS` now also apply to the userinfo and +host components. In 2.x, these normalizations only rewrote the path, query, and +fragment. + +Since the host is case-insensitive and PSR-7 requires it to be lowercase, octets +decoded in the host are lowercased. Reserved percent-encoded octets such as +`%3A` are never decoded, so component boundaries cannot change, and these two +flags never modify bracketed IP-literal hosts, which only the separate +`UriNormalizer::CANONICALIZE_IPV6_HOST` normalization may canonicalize. Both +flags are part of `UriNormalizer::PRESERVING_NORMALIZATIONS`, so the output of +`UriNormalizer::normalize()` and the result of `UriNormalizer::isEquivalent()` +can change for URIs whose userinfo or host contains percent-encoded octets. +Custom `UriInterface` implementations now receive `withUserInfo()` or +`withHost()` calls from the normalizer when a normalization changes those +components; unchanged components are never rewritten. The rewrite is kept only +when the value returned by the implementation matches the normalized form, and +a userinfo with an empty user segment is never rewritten. If a setter returns a +different representation, that rewrite is discarded, while other selected +normalizations still apply, and setter exceptions propagate. No percent-encoding +normalization is applied to a component with malformed percent syntax, such as a +`%` not followed by two hexadecimal digits. + +```php +use GuzzleHttp\Psr7\Uri; +use GuzzleHttp\Psr7\UriNormalizer; + +// 2.x: http://%75ser@ex%61mple.com/ +// 3.0: http://user@example.com/ +(string) UriNormalizer::normalize(new Uri('http://%75ser@ex%61mple.com/')); +``` + +#### URI Ports and Authority Handling + +Several 3.0 changes affect how URI ports are accepted, validated, and rendered. +Each is described in its own section above: + +- `UriInterface::withPort()` now requires `int|null`; see "Native PSR-7 + Parameter Types". +- `Uri::fromParts()` validates ports instead of casting them, and `withHost()` + rejects embedded `host:port` values; see "URI Host and Scheme Validation". +- A generic `Uri` can represent ports 0 through 65535. Inbound HTTP authority + parsing is stricter: `Message::parseRequest()` rejects zero-valued ports but + accepts nonzero leading-zero ports, normalizing the reconstructed URI while + preserving the raw `Host` or request-target text; see "HTTP Start-line + Parsing" and "URI Host and Scheme Validation". +- Server globals reject a zero-valued `HTTP_HOST` and validate `SERVER_PORT` + when fallback authority reconstruction needs it. A recognized absolute-form + or CONNECT `REQUEST_URI` authority takes precedence and can still produce a + URI with port zero; see "URI Host and Scheme Validation". +- Synthesized `Host` headers now include any non-default URI port; see "Request + Modification Changes" and "Request Host Synchronization". + +`Uri` now knows the default ports of the `ws` and `wss` schemes, 80 and 443 per +RFC 6455. An explicit default port on a `ws` or `wss` URI is removed when the +URI is constructed or modified, `Uri::isDefaultPort()` returns `true` for such +URIs, and `UriNormalizer::normalize()` with the `REMOVE_DEFAULT_PORT` flag +removes the port from other `UriInterface` implementations as well. In 2.x, +these ports were preserved. + +```php +use GuzzleHttp\Psr7\Uri; + +// 2.x: ws://example.com:80/chat +// 3.0: ws://example.com/chat +(string) new Uri('ws://example.com:80/chat'); + +// 2.x: 443 +// 3.0: null +(new Uri('wss://example.com:443'))->getPort(); +``` + +Because a native `Uri` never carries a default `ws` or `wss` port, the `Host` +header synchronized from such a request URI omits the port. `Request` and +`Message` `Host` synthesis and `Utils::modifyRequest()` still append an explicit +default port that a `ws` or `wss` URI from another `UriInterface` implementation +reports. + +`UriComparator::isCrossOrigin()` now applies these default ports when comparing +effective ports, so two `ws` or `wss` URIs that differ only by an explicit +default port, such as `ws://example.com/` and `ws://example.com:80/`, are +same-origin no matter which `UriInterface` implementation supplies them. In 2.x, +such pairs were considered cross-origin. Schemes other than `http`, `https`, +`ws`, and `wss` still receive no implicit default port. + +#### Sensitive Stack Trace Arguments + +Credential-bearing URI, server-global, Authorization-header, and cookie +arguments are marked with `#[\SensitiveParameter]`. PHP 8.2 and later replace +those arguments in stack traces with `SensitiveParameterValue`. PHP 7.4 through +8.1 do not redact trace arguments. + +This does not redact logs, exception messages, object properties, wire traffic, +captured variables, return values, user callbacks, or the separate executing +object in an explicit backtrace. + +1.x to 2.0 +---------- + +Guzzle PSR-7 2.0 is a major release that removes deprecated APIs, raises the +minimum PHP version, and adds PHP 7 parameter and return types. Applications that +only depend on PSR-7 interfaces should usually need small changes. Applications +that call helper functions, extend package classes, or pass invalid argument +types need closer review. + +#### PHP Version and Dependencies + +Guzzle PSR-7 2.0 requires PHP `^7.2.5 || ^8.0`. Guzzle PSR-7 1.x supported PHP +`>=5.4.0`. + +Composer dependency changes that can affect upgrades: + +- `ralouphie/getallheaders` v2 support was dropped; 2.0 requires `^3.0`. +- `psr/http-factory:^1.0` is required because 2.0 ships PSR-17 factories through `GuzzleHttp\Psr7\HttpFactory`. + +#### PHP 7 Type Hints and Return Types + +Type hints and return types were added wherever possible. Please make sure: + +- You pass values of the documented type when calling methods and functions. +- Classes that extend Guzzle PSR-7 classes update any overridden method signatures to remain compatible. +- Code that expected package-specific `InvalidArgumentException` exceptions for invalid argument types may now receive PHP `TypeError` exceptions instead. + +Common examples include passing a real integer status code to `Response::__construct()` and passing a string method to `Request::__construct()`. + +#### Removed Function API + +The static API was introduced in 1.7.0 to mitigate problems with functions +conflicting between global and local copies of the package. The function API was +removed in 2.0.0, along with the Composer `files` autoload entry that loaded +`src/functions_include.php`. + +Replace namespaced function calls with the corresponding static methods in the +`GuzzleHttp\Psr7` namespace: + +```php +// Before: +use function GuzzleHttp\Psr7\stream_for; + +$stream = stream_for('body'); + +// After: +use GuzzleHttp\Psr7\Utils; + +$stream = Utils::streamFor('body'); +``` + +| Original Function | Replacement Method | +|-------------------|--------------------| +| `str` | `Message::toString` | +| `uri_for` | `Utils::uriFor` | +| `stream_for` | `Utils::streamFor` | +| `parse_header` | `Header::parse` | +| `normalize_header` | `Header::normalize` | +| `modify_request` | `Utils::modifyRequest` | +| `rewind_body` | `Message::rewindBody` | +| `try_fopen` | `Utils::tryFopen` | +| `copy_to_string` | `Utils::copyToString` | +| `copy_to_stream` | `Utils::copyToStream` | +| `hash` | `Utils::hash` | +| `readline` | `Utils::readLine` | +| `parse_request` | `Message::parseRequest` | +| `parse_response` | `Message::parseResponse` | +| `parse_query` | `Query::parse` | +| `build_query` | `Query::build` | +| `mimetype_from_filename` | `MimeType::fromFilename` | +| `mimetype_from_extension` | `MimeType::fromExtension` | +| `_parse_message` | `Message::parseMessage` | +| `_parse_request_uri` | `Message::parseRequestUri` | +| `get_message_body_summary` | `Message::bodySummary` | +| `_caseless_remove` | `Utils::caselessRemove` | + +`Header::normalize()` remains the direct 2.0 replacement for +`normalize_header()`. In newer 2.x versions, prefer `Header::splitList()` for +new code. + +#### Deprecated URI Methods Removed + +The deprecated `Uri::resolve()` and `Uri::removeDotSegments()` methods were +removed. Use `UriResolver` instead. + +```php +// Before: +$resolved = Uri::resolve($base, '../path'); +$path = Uri::removeDotSegments('/a/../b'); + +// After: +use GuzzleHttp\Psr7\UriResolver; +use GuzzleHttp\Psr7\Utils; + +$resolved = UriResolver::resolve($base, Utils::uriFor('../path')); +$path = UriResolver::removeDotSegments('/a/../b'); +``` + +#### Stricter URI Validation + +Guzzle PSR-7 1.x automatically fixed a URI that combined an authority with a +relative path by prepending `/` to the path. That deprecated behavior was removed +in 2.0. Such URIs now throw `InvalidArgumentException`. + +```php +// Before: automatically converted to //example.com/foo. +$uri = (new Uri())->withHost('example.com')->withPath('foo'); + +// After: make the absolute path explicit. +$uri = (new Uri())->withHost('example.com')->withPath('/foo'); +``` + +#### Header Validation + +Header names are validated more strictly according to RFC 7230 token syntax. +Names containing whitespace, `/`, `(`, `)`, `\\`, or other invalid characters are +rejected. + +If you construct messages from untrusted or non-standard input, normalize or +reject invalid header names before constructing `Request`, `Response`, or +`ServerRequest` instances. + +#### Query String Boolean Serialization + +`Query::build()` now serializes booleans as `1` and `0`, matching +`http_build_query()` behavior. + +```php +Query::build(['enabled' => true, 'disabled' => false]); +// enabled=1&disabled=0 +``` + +In current 2.x versions, pass `false` as the third argument if you need textual +boolean values: + +```php +Query::build(['enabled' => true, 'disabled' => false], PHP_QUERY_RFC3986, false); +// enabled=true&disabled=false +``` + +#### Final Stream and Decorator Classes + +Several classes that were annotated with `@final` in 1.x are declared `final` in +2.0: + +- `AppendStream` +- `BufferStream` +- `CachingStream` +- `DroppingStream` +- `FnStream` +- `InflateStream` +- `LazyOpenStream` +- `LimitStream` +- `MultipartStream` +- `NoSeekStream` +- `PumpStream` +- `StreamWrapper` + +If your code extends one of these classes, replace inheritance with composition. +For custom streams, implement `Psr\Http\Message\StreamInterface` directly or use +`GuzzleHttp\Psr7\StreamDecoratorTrait` in your own class. + +`Request`, `Response`, `ServerRequest`, `Stream`, `UploadedFile`, and `Uri` remain +extendable in 2.0, but overridden methods must have compatible signatures. + +#### Public Constants and Internal Details + +Some constants that were public in 1.x are implementation details in 2.0: + +- `Stream::READABLE_MODES` +- `Stream::WRITABLE_MODES` +- `Uri::HTTP_DEFAULT_HOST` + +If your code used these constants, define application-specific constants instead +of depending on package internals. + +#### Stream Behavior Changes + +`BufferStream::write()` returns `0` instead of `false` when the buffer exceeds +its high-water mark. This keeps the method compatible with the `int` return type +from `StreamInterface::write()`. + +Several stream `__toString()` implementations now catch `Throwable`. On PHP 7.4 +and newer, exceptions thrown during stringification are rethrown. Avoid relying +on `(string) $stream` to hide read failures; call `getContents()` or `read()` and +handle exceptions when failures are possible. + +#### PSR-17 Factories + +Guzzle PSR-7 2.0 adds `GuzzleHttp\Psr7\HttpFactory`, an implementation of the +PSR-17 factory interfaces from `psr/http-factory`. This is additive, but it is +the reason for the new required dependency. + +For the full 2.0 diff, see +https://github.com/guzzle/psr7/compare/1.8.1...2.0.0. diff --git a/vendor/guzzlehttp/psr7/composer.json b/vendor/guzzlehttp/psr7/composer.json new file mode 100644 index 0000000..8094ef7 --- /dev/null +++ b/vendor/guzzlehttp/psr7/composer.json @@ -0,0 +1,111 @@ +{ + "name": "guzzlehttp/psr7", + "description": "PSR-7 message implementation that also provides common utility methods", + "license": "MIT", + "keywords": [ + "request", + "response", + "message", + "stream", + "http", + "uri", + "url", + "psr-7" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "require": { + "php": "^7.4 || ^8.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^2.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0", + "symfony/polyfill-php80": "^1.25", + "symfony/polyfill-php82": "^1.27" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "1.1.0", + "jshttp/mime-db": "1.54.0.1", + "php-http/psr7-integration-tests": "^1.5.1", + "phpunit/phpunit": "^9.6.34" + }, + "provide": { + "psr/http-factory-implementation": "1.1", + "psr/http-message-implementation": "2.0" + }, + "suggest": { + "ext-intl": "Convert internationalized hosts with Idna", + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "repositories": [ + { + "type": "package", + "package": { + "name": "jshttp/mime-db", + "version": "1.54.0.1", + "dist": { + "type": "zip", + "url": "https://codeload.github.com/jshttp/mime-db/zip/0a9fd0bfbc87a725ff638495839114e7807b7177" + } + } + } + ], + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\Psr7\\": "tests/" + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + } +} diff --git a/vendor/guzzlehttp/psr7/docs/diagnostic-values.md b/vendor/guzzlehttp/psr7/docs/diagnostic-values.md new file mode 100644 index 0000000..36f99a9 --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/diagnostic-values.md @@ -0,0 +1,30 @@ +# Diagnostic Values + +## `GuzzleHttp\Psr7\DiagnosticValue::escape` + +`public static function escape(string $value): string` + +Escapes C0, DEL, and C1 controls as uppercase `\xNN` sequences. + +ASCII bytes from 0x20 through 0x7E and valid UTF-8 characters outside those +control ranges remain unchanged. If the input is malformed UTF-8 or PCRE cannot +process it, every byte outside printable ASCII is escaped. Valid C1 characters +are rendered as `\xNN` using their Unicode code points. During bytewise +fallback, each original byte outside printable ASCII is rendered in the same +form. The result is diagnostic text, not a reversible encoding. + +This does not encode values for HTML, JSON, shells, terminals, URLs, or protocol +fields. + +Use this helper when including an untrusted value in diagnostic text: + +```php +use GuzzleHttp\Psr7\DiagnosticValue; + +$value = "bad\nvalue"; +$message = sprintf('Invalid value: %s', DiagnosticValue::escape($value)); +// Invalid value: bad\x0Avalue +``` + +Applications must still encode the completed diagnostic for its final output +context, such as HTML or JSON. diff --git a/vendor/guzzlehttp/psr7/docs/error-scopes.md b/vendor/guzzlehttp/psr7/docs/error-scopes.md new file mode 100644 index 0000000..3afdd40 --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/error-scopes.md @@ -0,0 +1,64 @@ +# Error Scopes + +## `GuzzleHttp\Psr7\ErrorScope` + +Captures the PHP errors raised beneath a call. + +PHP keeps one error handler stack per process, shared by every coroutine and +fiber, so an error raised on another call stack is passed on to the previously +installed handler instead of being captured. That handler is called directly, so +it also receives error levels it was not registered for. + +```php +use GuzzleHttp\Psr7\DiagnosticValue; +use GuzzleHttp\Psr7\ErrorScope; + +$scope = new ErrorScope(); +$handle = $scope->run(static fn () => fopen('/path/to/file', 'r')); + +if ($handle === false) { + throw new RuntimeException( + DiagnosticValue::escape((string) $scope->getError()) + ); +} +``` + +## `GuzzleHttp\Psr7\ErrorScope::__construct` + +`public function __construct(int $levels = E_ALL, bool $silenced = true)` + +Creates a scope that captures errors of the given levels. + +Errors of other levels are passed on to the previously installed handler, which +may be an enclosing scope. When `$silenced` is false, so are errors silenced +inside the call with the `@` operator, which are those whose level was reported +as the call started and is not reported when they are raised. + +## `GuzzleHttp\Psr7\ErrorScope::run` + +`public function run(callable $operation): mixed` + +Runs the operation and returns its result, capturing the errors raised beneath +it. + +A scope runs one operation at a time, so calling this again before it returns +throws a `LogicException`. + +## `GuzzleHttp\Psr7\ErrorScope::getError` + +`public function getError(): ?string` + +Returns the message of the last error captured, if any. + +## `GuzzleHttp\Psr7\ErrorScope::getErrors` + +`public function getErrors(): array` + +Returns the errors captured, in the order they were raised. + +Each error is an array with `message`, `file`, and `line` keys. + +## Related + +- [Diagnostic Values](diagnostic-values.md) +- [Stream Helpers](stream-helpers.md) diff --git a/vendor/guzzlehttp/psr7/docs/header-and-query-helpers.md b/vendor/guzzlehttp/psr7/docs/header-and-query-helpers.md new file mode 100644 index 0000000..f143712 --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/header-and-query-helpers.md @@ -0,0 +1,107 @@ +# Header and Query Helpers + +This page covers helper methods for parsing structured header values, splitting +list headers, and parsing or building query strings. For basic message header +behavior, see [PSR-7 Messages](psr-7-messages.md). + +## `GuzzleHttp\Psr7\Header::parse` + +`public static function parse(string|array $header): array` + +Parses semicolon-separated header parameters into associative arrays, one per +comma-separated header value. Parameters without a value are appended as values +under integer keys. + +## `GuzzleHttp\Psr7\Header::splitList` + +`public static function splitList(string|string[] $header): string[]` + +Splits an HTTP header defined to contain a comma-separated list into each +individual value. Empty values are removed: + +```php +$knownEtags = Header::splitList($request->getHeader('if-none-match')); +``` + +Example headers include `accept`, `cache-control`, and `if-none-match`. + +This method must not be used to parse headers that are not defined as a list, +such as `user-agent` or `set-cookie`. + +## `GuzzleHttp\Psr7\Query::parse` + +`public static function parse(string $str, int|bool $urlEncoding = true): array` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key-value pair +becomes an array. This function does not parse nested PHP style arrays into an +associative array. For example, `foo[a]=1&foo[b]=2` will be parsed into +`['foo[a]' => '1', 'foo[b]' => '2']`. + +## `GuzzleHttp\Psr7\Query::build` + +`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986, bool $treatBoolsAsInts = true): string` + +Build a query string from an array of key-value pairs. + +This function can use the return value of `parse()` to build a query string. +This function does not modify the provided keys when an array is encountered, +unlike `http_build_query()`. + +## `GuzzleHttp\Psr7\Utils::asciiToLower` + +`public static function asciiToLower(string $string): string` + +Converts ASCII uppercase letters in a string to lowercase. + +Unlike `strtolower()`, which honors `LC_CTYPE` before PHP 8.2, the conversion is +locale-independent and leaves every non-ASCII byte unchanged, as HTTP protocol +elements require. + +## `GuzzleHttp\Psr7\Utils::asciiToUpper` + +`public static function asciiToUpper(string $string): string` + +Converts ASCII lowercase letters in a string to uppercase. + +Unlike `strtoupper()`, which honors `LC_CTYPE` before PHP 8.2, the conversion is +locale-independent and leaves every non-ASCII byte unchanged, as HTTP protocol +elements require. + +## `GuzzleHttp\Psr7\Utils::asciiUcFirst` + +`public static function asciiUcFirst(string $string): string` + +Converts the first character of a string to uppercase when it is an ASCII +lowercase letter. + +Unlike `ucfirst()`, which honors `LC_CTYPE` before PHP 8.2, the conversion is +locale-independent and leaves every non-ASCII byte unchanged, as HTTP protocol +elements require. + +## `GuzzleHttp\Psr7\Utils::caselessContains` + +`public static function caselessContains(string $haystack, string $needle): bool` + +Checks whether the haystack contains the needle, comparing ASCII letters +case-insensitively and without locale sensitivity. + +## `GuzzleHttp\Psr7\Utils::caselessEquals` + +`public static function caselessEquals(string $left, string $right): bool` + +Checks whether two strings are equal, comparing ASCII letters case-insensitively +and without locale sensitivity. + +## `GuzzleHttp\Psr7\Utils::caselessRemove` + +`public static function caselessRemove(array $keys, array $data): array` + +Remove the items given by the keys from the data, case-insensitively. + +## Related + +- [PSR-7 Messages](psr-7-messages.md) +- [Message Helpers](message-helpers.md) +- [URI Helpers](uri-helpers.md) diff --git a/vendor/guzzlehttp/psr7/docs/message-helpers.md b/vendor/guzzlehttp/psr7/docs/message-helpers.md new file mode 100644 index 0000000..b560ce0 --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/message-helpers.md @@ -0,0 +1,112 @@ +# Message Helpers + +This page covers static helper methods for converting, parsing, summarizing, +rewinding, and cloning PSR-7 messages. For conceptual request and response +behavior, start with [PSR-7 Messages](psr-7-messages.md). + +## `GuzzleHttp\Psr7\Message::toString` + +`public static function toString(MessageInterface $message): string` + +Returns the string representation of an HTTP message. + +```php +$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); +echo GuzzleHttp\Psr7\Message::toString($request); +``` + +## `GuzzleHttp\Psr7\Message::bodySummary` + +`public static function bodySummary(MessageInterface $message, ?int $truncateAt = null): string|null` + +Get a short summary of the message body. + +Will return `null` if the response is not printable. + +Reads seekable bodies from the beginning and restores the original cursor +position before returning. Pass `null` for `$truncateAt` to use the default +summary length. + +## `GuzzleHttp\Psr7\Message::rewindBody` + +`public static function rewindBody(MessageInterface $message): void` + +Attempts to rewind a message body and throws an exception on failure. + +The body of the message will only be rewound if a call to `tell()` returns a +value other than `0`. + +## `GuzzleHttp\Psr7\Message::parseMessage` + +`public static function parseMessage(string $message): array` + +Parses an HTTP message into an associative array. + +The array contains the `start-line` key containing the start line of the +message, `headers` key containing an associative array of header array values, +and a `body` key containing the body of the message. + +## `GuzzleHttp\Psr7\Message::parseRequestUri` + +`public static function parseRequestUri(string $path, array $headers): string` + +Constructs a URI for an HTTP request message. + +The URI is composed from the start-line path and the `Host` header, using +`https` when the host's port is `443` and `http` otherwise. Without a `Host` +header, only the path is returned, with extra leading slashes collapsed so an +origin-form target cannot be parsed as a network-path reference with its own +authority. An `InvalidArgumentException` is thrown when the `Host` header is +invalid. + +## `GuzzleHttp\Psr7\Message::parseRequest` + +`public static function parseRequest(string $message): RequestInterface` + +Parses a request message string into a request object. + +The request-target must be in origin form, absolute form (without a userinfo +component), authority form (`CONNECT`), or asterisk form (`OPTIONS`), and any +`Host` header must be a single valid value; otherwise an +`InvalidArgumentException` is thrown. Non-origin-form targets are preserved on +the returned request via `withRequestTarget()`. + +## `GuzzleHttp\Psr7\Message::parseResponse` + +`public static function parseResponse(string $message): ResponseInterface` + +Parses a response message string into a response object. + +## `GuzzleHttp\Psr7\Utils::modifyRequest` + +`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface` + +Clone and modify a request with the given changes. + +This method is useful for reducing the number of clones needed to mutate a +message. + +The changes can be one of: + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. Values must be strings or + non-empty arrays of strings. +- remove_headers: (array) Remove the given headers. Values may be strings or + integers. +- body: (mixed) Sets the given body. Present non-null values are converted with + `GuzzleHttp\Psr7\Utils::streamFor()`, including resources, streams, iterators, + callable arrays, closures, invokable objects, and stringable objects. String + inputs remain literal bodies. +- uri: (UriInterface) Set the URI. When the URI contains a host, the Host header + is updated from it, and combining this with an explicit Host entry in + set_headers throws an InvalidArgumentException. Apply an intentional Host + override separately with withHeader() afterwards. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + +## Related + +- [PSR-7 Messages](psr-7-messages.md) +- [Header and Query Helpers](header-and-query-helpers.md) +- [Stream Helpers](stream-helpers.md) +- [URI and MIME Helpers](uri-and-mime-helpers.md) diff --git a/vendor/guzzlehttp/psr7/docs/psr-17-factories.md b/vendor/guzzlehttp/psr7/docs/psr-17-factories.md new file mode 100644 index 0000000..463e776 --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/psr-17-factories.md @@ -0,0 +1,33 @@ +# PSR-17 Factories + +This page explains `GuzzleHttp\Psr7\HttpFactory`, the PSR-17 factory implementation provided by this package. Use it when code expects PSR-17 factory interfaces and you want factories that create Guzzle PSR-7 messages, streams, uploaded files, and URIs. + +## `GuzzleHttp\Psr7\HttpFactory` + +`GuzzleHttp\Psr7\HttpFactory` implements all PSR-17 factory interfaces: `RequestFactoryInterface`, `ResponseFactoryInterface`, `ServerRequestFactoryInterface`, `StreamFactoryInterface`, `UploadedFileFactoryInterface`, and `UriFactoryInterface`. + +```php +use GuzzleHttp\Psr7\HttpFactory; + +$factory = new HttpFactory(); + +$request = $factory->createRequest('GET', 'https://example.com'); +$response = $factory->createResponse(200); +$serverRequest = $factory->createServerRequest('POST', '/submit', ['REMOTE_ADDR' => '192.0.2.1']); +$stream = $factory->createStream('body'); +$uri = $factory->createUri('https://example.com/path'); +``` + +It also creates streams from files and resources, and uploaded files from streams. + +```php +$stream = $factory->createStreamFromFile('/path/to/file.txt', 'r'); +$upload = $factory->createUploadedFile($stream, $stream->getSize(), UPLOAD_ERR_OK, 'file.txt', 'text/plain'); +``` + +## Related + +- [PSR-7 Messages](psr-7-messages.md) +- [Streams and Decorators](streams-and-decorators.md) +- [URI Helpers](uri-helpers.md) +- [Message Helpers](message-helpers.md) diff --git a/vendor/guzzlehttp/psr7/docs/psr-7-messages.md b/vendor/guzzlehttp/psr7/docs/psr-7-messages.md new file mode 100644 index 0000000..1dd4cc2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/psr-7-messages.md @@ -0,0 +1,402 @@ +# PSR-7 Messages + +This page covers the PSR-7 message objects provided by this package: requests, responses, server requests, uploaded files, and the message-specific header, URI, and body APIs. Use these objects when you need HTTP messages that can move between Guzzle, PSR-18 clients, PSR-15 middleware, and other PSR-7 compatible libraries. + +HTTP requests and responses are both messages. A message has a start line, headers, and an optional body stream. Message and URI objects are immutable; methods named `with*()` return changed copies. Body streams are mutable handles, so reads and writes can change their cursor or contents. For body details, see [Streams and Decorators](streams-and-decorators.md). For URI helpers, see [URI Helpers](uri-helpers.md). + +## Creating Requests + +You can create a request with `GuzzleHttp\Psr7\Request`. + +```php +use GuzzleHttp\Psr7\Request; + +$request = new Request('GET', 'https://example.com/users/123'); + +// You can provide optional headers and a body. +$headers = ['Accept' => 'application/json']; +$body = 'request body'; +$request = new Request('PUT', 'https://example.com/users/123', $headers, $body); +``` + +## Creating Responses + +You can create a response with `GuzzleHttp\Psr7\Response`. + +```php +use GuzzleHttp\Psr7\Response; + +// The constructor requires no arguments. +$response = new Response(); +echo $response->getStatusCode(); +// 200 +echo $response->getProtocolVersion(); +// 1.1 + +// You can provide a status, headers, body, and protocol version. +$response = new Response(200, ['Content-Type' => 'application/json'], '{"ok":true}', '1.1'); +``` + +## Creating Server Requests + +Server requests represent incoming HTTP requests on the server side. They include the normal request method, URI, headers, and body, plus server parameters, cookies, query parameters, parsed body data, attributes, and uploaded files. + +```php +use GuzzleHttp\Psr7\ServerRequest; + +$request = new ServerRequest('POST', 'https://example.com/form', [], 'name=Guzzle', '1.1', [ + 'REMOTE_ADDR' => '192.0.2.1', +]); + +$request = $request + ->withCookieParams(['session' => 'abc']) + ->withQueryParams(['page' => '1']) + ->withParsedBody(['name' => 'Guzzle']) + ->withAttribute('route', 'profile'); + +echo $request->getServerParams()['REMOTE_ADDR']; +echo $request->getCookieParams()['session']; +echo $request->getQueryParams()['page']; +echo $request->getParsedBody()['name']; +echo $request->getAttribute('route'); +``` + +Use `ServerRequest::fromGlobals()` to create a server request from PHP superglobals. It reads `$_SERVER`, `$_GET`, `$_POST`, `$_COOKIE`, and `$_FILES`, and attempts to include request headers when available. + +```php +use GuzzleHttp\Psr7\ServerRequest; + +$request = ServerRequest::fromGlobals(); +``` + +Use `ServerRequest::getUriFromGlobals()` when you only need the URI derived from `$_SERVER`. + +```php +use GuzzleHttp\Psr7\ServerRequest; + +$uri = ServerRequest::getUriFromGlobals(); +``` + +For URI construction and normalization helpers, see [URI Helpers](uri-helpers.md). + +## Requests + +```php +use GuzzleHttp\Psr7\Request; + +$request = new Request('GET', 'https://example.com/users/123', [ + 'Accept' => 'application/json', +]); + +echo $request->getMethod(); +echo $request->getUri(); +``` + +PSR-7 messages are immutable. Methods such as `withHeader()` and `withUri()` return a modified copy. + +```php +$jsonRequest = $request->withHeader('Accept', 'application/json'); +``` + +## Responses + +```php +use GuzzleHttp\Psr7\Response; + +$response = new Response(200, ['Content-Type' => 'application/json'], '{"ok":true}'); + +echo $response->getStatusCode(); +echo $response->getHeaderLine('Content-Type'); +echo $response->getBody(); +``` + +## URIs + +```php +use GuzzleHttp\Psr7\Uri; + +$uri = new Uri('https://example.com/users?active=1'); + +echo $uri->getHost(); +echo $uri->getQuery(); +``` + +For URI-specific helper methods, see [URI Helpers](uri-helpers.md). + +## Headers + +Both request and response messages contain HTTP headers. + +### Accessing Headers + +You can check if a request or response has a specific header using `hasHeader()`. + +```php +use GuzzleHttp\Psr7\Request; + +$request = new Request('GET', '/', ['X-Foo' => 'bar']); + +if ($request->hasHeader('X-Foo')) { + echo 'It is there'; +} +``` + +Retrieve all header values as an array of strings with `getHeader()`. + +```php +$request->getHeader('X-Foo'); +// ['bar'] + +// Missing headers return an empty array. +$request->getHeader('X-Bar'); +// [] +``` + +Iterate over the headers of a message with `getHeaders()`. + +```php +foreach ($request->getHeaders() as $name => $values) { + echo $name . ': ' . implode(', ', $values) . "\r\n"; +} +``` + +### Complex Headers + +Some headers contain additional key-value pair information. For example, `Link` headers contain a link and additional parameters: + +```http +; rel="front"; type="image/jpeg" +``` + +Use `GuzzleHttp\Psr7\Header::parse()` to parse these headers. + +```php +use GuzzleHttp\Psr7\Header; +use GuzzleHttp\Psr7\Request; + +$request = new Request('GET', '/', [ + 'Link' => '; rel="front"; type="image/jpeg"', +]); + +$parsed = Header::parse($request->getHeader('Link')); +var_export($parsed); +``` + +This outputs: + +```php +array ( + 0 => + array ( + 0 => '', + 'rel' => 'front', + 'type' => 'image/jpeg', + ), +) +``` + +The result contains key-value pairs. Header values that have no key are indexed numerically, while header parts that form a key-value pair are added with their parameter name. + +## Body + +Request and response bodies are `Psr\Http\Message\StreamInterface` instances. Streams are used for both uploading data and downloading data. + +```php +use GuzzleHttp\Psr7\Response; + +$response = new Response(200, [], 'response body'); + +echo $response->getBody(); +// response body +``` + +The body can be cast to a string, or you can read bytes from the stream as needed. + +```php +$body = $response->getBody(); + +echo $body->read(4); +$body->seek(0); +echo $body->getContents(); +``` + +For more stream creation and decorator examples, see [Streams and Decorators](streams-and-decorators.md). + +## Uploaded Files + +Uploaded files are represented by `Psr\Http\Message\UploadedFileInterface` instances. This package provides `GuzzleHttp\Psr7\UploadedFile`, which can wrap a local file path, PHP stream resource, or PSR-7 stream. + +```php +use GuzzleHttp\Psr7\UploadedFile; +use GuzzleHttp\Psr7\Utils; + +$stream = Utils::streamFor('file contents'); +$upload = new UploadedFile($stream, $stream->getSize(), UPLOAD_ERR_OK, 'example.txt', 'text/plain'); + +echo $upload->getClientFilename(); +echo $upload->getClientMediaType(); +echo $upload->getSize(); +``` + +Call `getStream()` to read the uploaded content, or `moveTo()` to move or copy it to a target path. After `moveTo()` succeeds, `isMoved()` returns `true`, and calls that need the active upload stream will throw. + +```php +$body = $upload->getStream(); +echo $body->getContents(); + +$upload->moveTo('/path/to/target.txt'); +var_export($upload->isMoved()); +// true +``` + +If the upload error code is not `UPLOAD_ERR_OK`, the object still exposes `getError()`, `getSize()`, `getClientFilename()`, and `getClientMediaType()`, but `getStream()` and `moveTo()` throw because no successful upload content is available. + +`ServerRequest::normalizeFiles()` converts a `$_FILES`-style array into a tree of uploaded file instances. It accepts simple file specs, nested PHP `$_FILES` shapes, existing `UploadedFileInterface` instances, and nested arrays of uploaded files. + +```php +use GuzzleHttp\Psr7\ServerRequest; + +$files = ServerRequest::normalizeFiles([ + 'avatar' => [ + 'tmp_name' => '/tmp/php123', + 'size' => 1024, + 'error' => UPLOAD_ERR_OK, + 'name' => 'avatar.png', + 'type' => 'image/png', + ], + 'photos' => [ + 'tmp_name' => [ + 'first' => '/tmp/php456', + ], + 'size' => [ + 'first' => 2048, + ], + 'error' => [ + 'first' => UPLOAD_ERR_OK, + ], + 'name' => [ + 'first' => 'photo.jpg', + ], + 'type' => [ + 'first' => 'image/jpeg', + ], + ], +]); + +$request = (new ServerRequest('POST', '/upload'))->withUploadedFiles($files); +``` + +## HTTP Method Casing + +HTTP method names are case-sensitive in PSR-7. Requests created explicitly with +`Request`, `ServerRequest`, `withMethod()`, `Message::parseRequest()`, or the +PSR-17 factories preserve the method string as provided. `ServerRequest::fromGlobals()` +normalizes `$_SERVER['REQUEST_METHOD']` to uppercase for compatibility when +hydrating requests from PHP server globals. + +## Request Methods + +When creating a request, provide the HTTP method you want to perform. You can specify any method, including custom methods that are not part of RFC 9110. + +```php +use GuzzleHttp\Psr7\Request; + +$request = new Request('MOVE', 'https://example.com/resource'); + +echo $request->getMethod(); +// MOVE +``` + +## Request URI + +The request URI is represented by a `Psr\Http\Message\UriInterface` object. This package provides an implementation through `GuzzleHttp\Psr7\Uri`. + +When creating a request, you can provide the URI as a string or as a `UriInterface` instance. + +```php +use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Uri; + +$request = new Request('GET', new Uri('https://example.com/users?id=123')); +``` + +### Scheme + +The [scheme](https://datatracker.ietf.org/doc/html/rfc3986#section-3.1) specifies the protocol. For HTTP requests, this is usually `http` or `https`. + +```php +$request = new Request('GET', 'https://example.com'); +echo $request->getUri()->getScheme(); +// https +``` + +### Host + +The host is accessible from the URI and is also represented by the `Host` header. + +```php +$request = new Request('GET', 'https://example.com'); +echo $request->getUri()->getHost(); +// example.com +echo $request->getHeaderLine('Host'); +// example.com +``` + +### Port + +No port is necessary for the default `http` and `https` ports. + +```php +$request = new Request('GET', 'https://example.com:8443'); +echo $request->getUri()->getPort(); +// 8443 +``` + +### Path + +The request path is accessible through the URI object. + +```php +$request = new Request('GET', 'https://example.com/users/123'); +echo $request->getUri()->getPath(); +// /users/123 +``` + +Characters that are not allowed in a URI path are percent-encoded according to [RFC 3986 section 3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3). + +### Query String + +The query string is accessible through the URI object. + +```php +$request = new Request('GET', 'https://example.com/?foo=bar'); +echo $request->getUri()->getQuery(); +// foo=bar +``` + +Characters that are not allowed in a URI query are percent-encoded according to [RFC 3986 section 3.4](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4). + +## Response Status + +Responses expose the status code, reason phrase, and protocol version. + +```php +use GuzzleHttp\Psr7\Response; + +$response = new Response(200, [], 'OK'); + +echo $response->getStatusCode(); +// 200 +echo $response->getReasonPhrase(); +// OK +echo $response->getProtocolVersion(); +// 1.1 +``` + +## Related + +- [Streams and Decorators](streams-and-decorators.md) +- [URI Helpers](uri-helpers.md) +- [Message Helpers](message-helpers.md) +- [Header and Query Helpers](header-and-query-helpers.md) +- [PSR-17 Factories](psr-17-factories.md) diff --git a/vendor/guzzlehttp/psr7/docs/stream-helpers.md b/vendor/guzzlehttp/psr7/docs/stream-helpers.md new file mode 100644 index 0000000..e1acf3d --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/stream-helpers.md @@ -0,0 +1,150 @@ +# Stream Helpers + +This page covers `GuzzleHttp\Psr7\Utils` helper methods for creating, copying, +hashing, reading, and safely opening PSR-7 streams. For stream implementations +and decorators, see [Streams and Decorators](streams-and-decorators.md). + +## `GuzzleHttp\Psr7\Utils::copyToStream` + +`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): int` + +Copy the contents of a stream into another stream until the given number of +bytes have been read, returning the number of bytes copied as an `int`. On +32-bit PHP, an unbounded copy larger than `PHP_INT_MAX` bytes cannot be +represented by that return type. 64-bit PHP is not affected. + +The destination must accept writes that make positive progress. Streams that +return 0 as a backpressure or drop signal (a `BufferStream` at its high water +mark, or a full `DroppingStream`) will cause this method to throw. For full +copies, use a normal writable stream such as a file or `php://temp` stream. + +Throws `GuzzleHttp\Psr7\Exception\TimeoutException` when PHP-style timeout +metadata can be detected after a source read or destination write cannot make +progress. + +When a source read times out, the bytes copied before it remain in the +destination. + +## `GuzzleHttp\Psr7\Utils::copyToString` + +`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string` + +Copy the contents of a stream into a string until the given number of bytes have +been read. + +Throws `GuzzleHttp\Psr7\Exception\TimeoutException` when PHP-style timeout +metadata can be detected after a stream read cannot make progress. + +The bytes read before a timeout are discarded, so calling this method again does +not return them. + +## `GuzzleHttp\Psr7\Utils::hash` + +`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string` + +Calculate a hash of a stream. + +This method reads the entire stream to calculate a rolling hash, based on PHP's +`hash_init` functions. + +Throws `GuzzleHttp\Psr7\Exception\TimeoutException` when PHP-style timeout +metadata can be detected after a stream read cannot make progress. + +## `GuzzleHttp\Psr7\Utils::readLine` + +`public static function readLine(StreamInterface $stream, ?int $maxLength = null): string` + +Read a line from the stream up to the maximum allowed buffer length. + +Throws `GuzzleHttp\Psr7\Exception\TimeoutException` when PHP-style timeout +metadata can be detected after a stream read cannot make progress. + +The bytes read before a timeout are discarded, so calling this method again does +not return them. + +## `GuzzleHttp\Psr7\Utils::streamFor` + +`public static function streamFor(resource|string|null|StreamInterface|callable|\Iterator|\Stringable $resource = '', array $options = []): StreamInterface` + +Create a new stream based on the input type. + +Options are provided as an associative array that can contain the following +keys: + +- metadata: Array of custom metadata. +- size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Yielded strings, integers, finite floats, booleans, `null`, and stringable + objects are converted to string chunks; non-finite floats and other values + throw `UnexpectedValueException` when the stream is read. Values that + stringify to an empty string are skipped while the iterator advances. + Subsequent read calls will first read from the buffer and then call `next` on + the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, the + object will be cast to a string and then a stream will be returned that uses + the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable`: When a callable array, closure, or invokable object is passed and + no earlier resource or object rule applies, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + suggested number of bytes to read. The callable can return fewer or more bytes + than requested, but MUST return a non-empty string to provide data and MUST + return `false` or `null` when there is no more data to return. Any additional + bytes will be buffered and used in subsequent reads. String inputs are always + treated as string bodies, even when they name callable functions. + +```php +$stream = GuzzleHttp\Psr7\Utils::streamFor('foo'); +$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r')); + +$generator = function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +}; + +$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100)); +``` + +## `GuzzleHttp\Psr7\Utils::tryFopen` + +`public static function tryFopen(string $filename, string $mode): resource` + +Safely opens a PHP stream resource using a filename. + +When `fopen()` fails, PHP normally raises a warning. This function adds an error +handler that checks for errors and throws an exception instead. Deprecations, +and errors silenced inside the call with the `@` operator, are not failures and +are passed on to the previously installed error handler. + +## `GuzzleHttp\Psr7\Utils::tryGetContents` + +`public static function tryGetContents(resource $stream): string` + +Safely gets the contents of a given stream. + +When `stream_get_contents()` fails, PHP normally raises a warning. This function +adds an error handler that checks for errors and throws an exception instead. +Deprecations, and errors silenced inside the call with the `@` operator, are not +failures and are passed on to the previously installed error handler. + +Throws `GuzzleHttp\Psr7\Exception\TimeoutException` when PHP-style timeout +metadata can be detected after a stream read cannot make progress. + +The bytes read before a timeout are discarded, so calling this method again does +not return them. + +## Related + +- [Streams and Decorators](streams-and-decorators.md) +- [PSR-17 Factories](psr-17-factories.md) +- [Message Helpers](message-helpers.md) diff --git a/vendor/guzzlehttp/psr7/docs/streams-and-decorators.md b/vendor/guzzlehttp/psr7/docs/streams-and-decorators.md new file mode 100644 index 0000000..fd2aec7 --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/streams-and-decorators.md @@ -0,0 +1,397 @@ +# Streams and Decorators + +PSR-7 request and response bodies are streams. This page covers stream creation, cursor and I/O behavior, built-in stream decorators, and wrapping PSR-7 streams as PHP resources. + +Streams allow HTTP messages to represent small strings, large files, generated data, remote resources, and other body sources through a common interface. + +The PSR-7 `Psr\Http\Message\StreamInterface` exposes methods that let consumers read, write, seek, and inspect body data without requiring the entire body to be loaded into memory. + +Streams expose their capabilities using `isReadable()`, `isWritable()`, and `isSeekable()`. These methods help collaborators determine whether a stream supports the operations they need. + +## Creating Streams + +Use `GuzzleHttp\Psr7\Utils::streamFor()` to create streams from common PHP values. It accepts strings, resources returned from `fopen()`, objects that implement `__toString()`, iterators, callable arrays, closures, invokable objects, and existing `Psr\Http\Message\StreamInterface` instances. + +Strings and `null` are stored in `php://temp` streams. PHP keeps `php://temp` data in memory until the stream exceeds 2 MB, then spills to a temporary file on disk. Non-string scalars such as integers, floats, and booleans are rejected; cast them to strings first. + +Callable sources receive a suggested read length, may return fewer or more bytes, and end the stream by returning `false` or `null`. Strings remain literal body contents, even when they name a callable. + +```php +use GuzzleHttp\Psr7\Utils; + +$stream = Utils::streamFor('string data'); +echo $stream; +// string data +echo $stream->read(3); +// str +echo $stream->getContents(); +// ing data +var_export($stream->eof()); +// true +var_export($stream->tell()); +// 11 +``` + +You can create streams from iterators. The iterator can yield any number of bytes per iteration. Any excess bytes returned by the iterator that were not requested by a stream consumer will be buffered until a subsequent read. + +```php +use GuzzleHttp\Psr7\Utils; + +$generator = function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield '.'; + } +}; + +$stream = Utils::streamFor($generator(1024)); +echo $stream->read(3); +// ... +``` + +## Metadata + +Streams expose stream metadata through `getMetadata()`. This method provides the data returned by PHP's [stream_get_meta_data()](https://www.php.net/manual/en/function.stream-get-meta-data.php), and can optionally expose custom metadata. + +```php +use GuzzleHttp\Psr7\Utils; + +$resource = Utils::tryFopen('/path/to/file', 'r'); +$stream = Utils::streamFor($resource); + +echo $stream->getMetadata('uri'); +// /path/to/file +var_export($stream->isReadable()); +// true +var_export($stream->isWritable()); +// false +var_export($stream->isSeekable()); +// true +``` + +## Timeouts + +Reads throw `GuzzleHttp\Psr7\Exception\TimeoutException` when PHP-style timeout +metadata can be detected after a read cannot make progress, such as on a socket +with a read timeout. + +`getContents()`, `Utils::copyToString()`, and `Utils::readLine()` discard the +bytes they read before a timeout, so calling them again does not return those +bytes. + +## AppendStream + +`GuzzleHttp\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use GuzzleHttp\Psr7; + +$a = Psr7\Utils::streamFor('abc, '); +$b = Psr7\Utils::streamFor('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me')); + +echo $composed; // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`GuzzleHttp\Psr7\BufferStream` + +Provides a buffer stream that can be written to fill a buffer, then read +from it to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use GuzzleHttp\Psr7; + +// When the buffer reaches or exceeds 1024 bytes, it will begin returning 0 to +// writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + +By default the bytes are cached in a `php://temp` stream. You can supply your own +cache target as the second constructor argument, but it is used as a random-access +byte buffer to replay the remote stream, so it must be readable, writable, and +seekable, report an accurate position and size, and store writes losslessly. Lossy +or non-seekable streams such as `BufferStream` and `DroppingStream` are not valid +targets. + + +## DroppingStream + +`GuzzleHttp\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use GuzzleHttp\Psr7; + +// Create an empty stream +$stream = Psr7\Utils::streamFor(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$dropping->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`GuzzleHttp\Psr7\FnStream` + +Compose stream implementations based on a hash of callables. + +Allows for easy testing and extension of a provided stream without needing +to create a concrete class for a simple extension point. + +```php + +use GuzzleHttp\Psr7; + +$stream = Psr7\Utils::streamFor('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`GuzzleHttp\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content. + +This stream decorator converts the provided stream to a PHP stream resource, +appends the zlib.inflate filter, and wraps the filtered resource as a stream. + +Closing an `InflateStream` also closes the compressed source stream it decorates; `detach()` leaves the source stream open. + + +## LazyOpenStream + +`GuzzleHttp\Psr7\LazyOpenStream` + +Lazily reads from or writes to a file that is opened only after an I/O operation +takes place on the stream. + +```php +use GuzzleHttp\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`GuzzleHttp\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`GuzzleHttp\Psr7\MultipartStream` + +A stream that returns bytes for a streaming multipart or multipart/form-data +body when read. + +Each multipart element must contain a `name` and `contents` key. `contents` may +be any non-array value accepted by `GuzzleHttp\Psr7\Utils::streamFor()`, +including closures and invokable objects. Array contents are recursively +expanded into nested form fields. + + +## NoSeekStream + +`GuzzleHttp\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false + +try { + $noSeek->seek(0); +} catch (\RuntimeException $e) { + echo $e->getMessage(); + // Cannot seek a NoSeekStream +} +``` + + +## PumpStream + +`GuzzleHttp\Psr7\PumpStream` + +Provides a read-only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the suggested +number of bytes to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the `read()` method of the PumpStream. The provided callable MUST return a +non-empty string to provide data, and MUST return false or null when there is +no more data to read. Returning an empty string causes a RuntimeException +because it cannot satisfy a positive-length read. + +Userland callables that declare no parameters are tolerated by PHP, but +length-aware callables remain the recommended formal shape. + + +## Implementing Stream Decorators + +Creating a stream decorator is very easy thanks to the +`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use GuzzleHttp\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + private $stream; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read(int $length): string + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + ($this->callback)(); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use GuzzleHttp\Psr7\StreamWrapper; + +$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + +## Related + +- [PSR-7 Messages](psr-7-messages.md) +- [Stream Helpers](stream-helpers.md) +- [PSR-17 Factories](psr-17-factories.md) +- [URI Helpers](uri-helpers.md) diff --git a/vendor/guzzlehttp/psr7/docs/uri-and-mime-helpers.md b/vendor/guzzlehttp/psr7/docs/uri-and-mime-helpers.md new file mode 100644 index 0000000..5bd5fe7 --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/uri-and-mime-helpers.md @@ -0,0 +1,83 @@ +# URI and MIME Helpers + +This page covers small helper methods for redacting URI user info, converting +values into URI objects, and resolving MIME types from filenames or extensions. +For URI resolution, normalization, and comparison helpers, see +[URI Helpers](uri-helpers.md). + +## `GuzzleHttp\Psr7\UriRedactor::redactUserInfo` + +`public static function redactUserInfo(UriInterface $uri): UriInterface` + +Redact the user info part of a URI. + +Returns the URI with the whole userinfo component replaced by `***` when one +is present, so neither the username nor the password survives into logs and +diagnostics. A URI without userinfo is returned unchanged. + +## `GuzzleHttp\Psr7\UriRedactor::redactUserInfoInString` + +`public static function redactUserInfoInString(string $subject, string $uri): string` + +Redacts the userinfo of a raw URI string wherever it appears in a subject +string. + +The needle is taken verbatim from the raw URI rather than from parsed +components, so credentials that URI normalization would rewrite, such as raw +control bytes or unencoded reserved characters, are still found in text that +embeds the URI exactly as given, for example transport error messages. A URI +without `://` is treated as authority-form: a host and port with optional +userinfo. + +A URI that does not parse has no trustworthy authority boundary, so everything +between any scheme and its last `@` is redacted as a safe-side fallback. + +## `GuzzleHttp\Psr7\UriRedactor::redactUriForMessage` + +`public static function redactUriForMessage(UriInterface $uri): string` + +Formats a URI for automatic diagnostics. + +The whole userinfo component is replaced by "***", and the query and +fragment are removed. The scheme, host, port, and path are preserved. +The returned string is diagnostic-escaped and the formatter never +throws. + +## `GuzzleHttp\Psr7\UriRedactor::redactUriStringForMessage` + +`public static function redactUriStringForMessage(string $uri): string` + +Formats a raw URI for automatic diagnostics, including malformed input. + +The whole userinfo component is replaced by "***", and the query and +fragment are removed. The scheme, host, port, and path are preserved +where their boundaries can be determined safely. The returned string is +diagnostic-escaped and the formatter never throws. + +## `GuzzleHttp\Psr7\Utils::uriFor` + +`public static function uriFor(string|UriInterface $uri): UriInterface` + +Returns a `UriInterface` for the given value. + +This function accepts a string or `UriInterface` and returns a `UriInterface` +for the given value. If the value is already a `UriInterface`, it is returned +as-is. + +## `GuzzleHttp\Psr7\MimeType::fromFilename` + +`public static function fromFilename(string $filename): string|null` + +Determines the MIME type of a file by looking at its extension. + +## `GuzzleHttp\Psr7\MimeType::fromExtension` + +`public static function fromExtension(string $extension): string|null` + +Maps a file extension to a MIME type. + +## Related + +- [URI Helpers](uri-helpers.md) +- [Header and Query Helpers](header-and-query-helpers.md) +- [Stream Helpers](stream-helpers.md) diff --git a/vendor/guzzlehttp/psr7/docs/uri-helpers.md b/vendor/guzzlehttp/psr7/docs/uri-helpers.md new file mode 100644 index 0000000..d3c285a --- /dev/null +++ b/vendor/guzzlehttp/psr7/docs/uri-helpers.md @@ -0,0 +1,511 @@ +# URI Helpers + +This page covers this package's `Psr\Http\Message\UriInterface` implementation +and URI helper classes for classifying, composing, resolving, normalizing, +comparing, and safely modifying URIs. + +Aside from the standard `Psr\Http\Message\UriInterface` implementation provided +by the `GuzzleHttp\Psr7\Uri` class, this library also provides additional static +methods for working with URIs. + +## URI Types + +An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or +a relative reference. An absolute URI has a scheme. A relative reference is used +to express a URI relative to another URI, the base URI. Relative references can +be divided into several forms according to +[RFC 3986 Section 4.2](https://datatracker.ietf.org/doc/html/rfc3986#section-4.2): + +- network-path references, e.g. `//example.com/path` +- absolute-path references, e.g. `/path` +- relative-path references, e.g. `subpath` + +Passing a string that starts with a host and port, such as +`example.com:8080/path`, to `GuzzleHttp\Psr7\Uri` is deprecated and will be +rejected in 4.0. Start it with a scheme or with `//`. + +The following methods can be used to identify the type of the URI. + +### `GuzzleHttp\Psr7\Uri::isAbsolute` + +`public static function isAbsolute(UriInterface $uri): bool` + +Whether the URI is absolute, i.e. it has a scheme. + +### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` + +`public static function isNetworkPathReference(UriInterface $uri): bool` + +Whether the URI is a network-path reference. A relative reference that begins +with two slash characters is termed a network-path reference. + +### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` + +`public static function isAbsolutePathReference(UriInterface $uri): bool` + +Whether the URI is an absolute-path reference. A relative reference that begins +with a single slash character is termed an absolute-path reference. + +### `GuzzleHttp\Psr7\Uri::isRelativePathReference` + +`public static function isRelativePathReference(UriInterface $uri): bool` + +Whether the URI is a relative-path reference. A relative reference that does not +begin with a slash character is termed a relative-path reference. + +### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` + +`public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null): bool` + +Whether the URI is a same-document reference. A same-document reference refers +to a URI that is, aside from its fragment component, identical to the base URI. +When no base URI is given, only an empty URI reference (apart from its fragment) +is considered a same-document reference. + +## URI Syntax Validation + +`GuzzleHttp\Psr7\Rfc3986` provides static methods for validating and +canonicalizing individual URI components against the grammar defined by +[RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986). They operate on raw +component strings rather than on `Psr\Http\Message\UriInterface` instances. + +### `GuzzleHttp\Psr7\Rfc3986::isValidScheme` + +`public static function isValidScheme(string $scheme): bool` + +Whether the string is a valid URI scheme. Per +[RFC 3986 Section 3.1](https://datatracker.ietf.org/doc/html/rfc3986#section-3.1), +a scheme must start with a letter, followed by any number of letters, digits, +`+`, `-`, or `.`. The empty string is also accepted, since a URI reference may +omit the scheme. + +### `GuzzleHttp\Psr7\Rfc3986::isValidHost` + +`public static function isValidHost(string $host): bool` + +Whether the string is a valid URI host. Per +[RFC 3986 Section 3.2.2](https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2), +the host is an IP-literal, IPv4 address, or registered name. An empty host is +accepted, since the authority, and thus the host, may be empty. Bracketed values +are validated as IPv6 or IPvFuture literals; any other value is rejected if it +contains control characters, whitespace, an authority or path delimiter (`/`, +`?`, `#`, `@`, `\`), or an embedded colon denoting a port. Percent-encoding is +validated the same way: malformed sequences (a `%` not followed by two hex +digits) and percent-encoded octets that decode to one of the rejected bytes, to +a bracket (`[`, `]`), or to `%` itself are invalid, while all other +percent-encoded octets are accepted. Rejecting these percent-encoded octets is a +deliberate guzzle host policy, stricter than the RFC 3986 `reg-name` grammar, +which permits any well-formed `pct-encoded` octet; it matches the stricter +policy used throughout the library. RFC 6874 IPv6 zone identifiers (for example +`[fe80::1%25eth0]`) are not supported. + +Registered names are otherwise intentionally permissive: single-label hosts such +as `localhost`, underscores, sub-delims, and raw or percent-encoded non-ASCII +(IDN) data are accepted and preserved as given, with no punycode conversion. +Consumers that need DNS IDNs must perform the conversion themselves, with +`GuzzleHttp\Psr7\Idna`. Passing non-ASCII data in a host to +`GuzzleHttp\Psr7\Uri`, raw or percent-encoded, is deprecated and will be +rejected in 4.0. + +Validity here is a statement about URI syntax only. It does not imply that the +host resolves or that a client will interpret it exactly as written. A PSR-7 URI +object does not know which resolver or transport will consume it, so it cannot +establish destination identity. Consumers that restrict the destination must +enforce that policy at the client or transport boundary and ensure the +connection uses an approved address; checking the spelling or a separate DNS +lookup is insufficient. + +### `GuzzleHttp\Psr7\Rfc3986::isValidPort` + +`public static function isValidPort(string $port): bool` + +Whether the string is a valid port number. RFC 3986 defines the port as +`*DIGIT`, which also permits an empty port and has no upper bound; this applies +the stricter policy used throughout the library instead, accepting a non-empty +run of digits (leading zeros are accepted and normalized) that resolves to a +value in the range 0-65535. + +### `GuzzleHttp\Psr7\Rfc3986::canonicalizeIpv6` + +`public static function canonicalizeIpv6(string $address): string` + +Returns the [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-4) +canonical form of a valid IPv6 address. The address must be a valid textual +IPv6 address without brackets and without a zone identifier, such as the +inside of an IP-literal accepted by `isValidHost()`. Canonicalization +lowercases the hexadecimal fields, suppresses leading zeros, and collapses the +longest run of two or more zero fields (the leftmost on a tie) with `::`. +Embedded dotted-decimal notation follows the rendering policy of BIND-derived +`inet_ntop()` implementations and curl: exactly the IPv4-mapped +(`::ffff:0:0/96`) and deprecated IPv4-compatible (`::/96`) layouts use it, +while other embedded-IPv4 forms, including translated (NAT64) well-known +prefixes such as `64:ff9b::/96` (RFC 6052), serialize in pure hexadecimal +fields. An `\InvalidArgumentException` is thrown if the address cannot be +parsed. + +Validation is strict and platform-independent: the address is checked against +the RFC 3986 `IPv6address` grammar with PHP's `FILTER_VALIDATE_IP` filter and +parsed in pure PHP, so spellings that only some platform parsers accept, such as +the zero-padded dotted octets in `::ffff:192.168.001.001`, are rejected +everywhere. + +Emitting dotted-decimal notation for these two selected layouts is the +BIND-derived `inet_ntop()` and curl compatibility policy used here. +[RFC 5952 Section 5](https://datatracker.ietf.org/doc/html/rfc5952#section-5) +permits mixed notation for recognizable embedded-IPv4 prefixes but does not +limit that category to these layouts; RFC 6052, for example, defines +`64:ff9b::/96` as a Well-Known Prefix, which this implementation renders in +pure hexadecimal. The WHATWG URL Standard always emits pure hexadecimal +fields. + +## Internationalized Hosts + +`GuzzleHttp\Psr7\Idna` converts internationalized hosts to their ASCII form, the +A-labels that DNS, TLS, and HTTP `Host` fields carry. `GuzzleHttp\Psr7\Uri` does +not apply this conversion itself. + +```php +use GuzzleHttp\Psr7\Idna; + +echo Idna::uriFor('https://яндекс.рф/'); // https://xn--d1acpjx3f.xn--p1ai/ +``` + +### `GuzzleHttp\Psr7\Idna::toAscii` + +`public static function toAscii(string $host, ?int $options = null): string` + +Returns the ASCII form of a URI host. + +A host with no non-ASCII data, raw or percent-encoded, is returned unchanged. +Any other host is converted to A-labels with the +[UTS #46 ToASCII](https://www.unicode.org/reports/tr46/#ToASCII) operation, by +default non-transitionally and with the STD3 ASCII rules and the bidi and joiner +checks. `$options` replaces that default with `IDNA_*` constants. Whatever the +options, a converted host must be a valid ASCII host that is neither bracketed +nor percent-encoded. + +Conversion maps characters, so fullwidth digits can become an IPv4 address. +Apply any destination policy to the returned host, not to the input. + +An `\InvalidArgumentException` is thrown if the host cannot be converted or +decodes to more than 1024 characters, and a `\RuntimeException` if the intl +extension is not available. + +### `GuzzleHttp\Psr7\Idna::uriFor` + +`public static function uriFor(string $uri, ?int $options = null): UriInterface` + +Returns a URI for a string whose host may be internationalized. + +The string is parsed exactly as `new Uri($uri)` parses it, except that a host +containing non-ASCII data is converted with `toAscii()` and the given +`$options`. + +A `GuzzleHttp\Psr7\Exception\MalformedUriException` is thrown if the URI cannot +be parsed or its host cannot be converted, and a `\RuntimeException` if the intl +extension is not available. + +## URI Components + +Additional methods to work with URI components. + +### `GuzzleHttp\Psr7\Uri::isDefaultPort` + +`public static function isDefaultPort(UriInterface $uri): bool` + +Whether the URI has the default port of the current scheme. +`Psr\Http\Message\UriInterface::getPort` may return null or the standard port. +This method can be used independently of the implementation. + +### `GuzzleHttp\Psr7\Uri::composeComponents` + +`public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string` + +Composes a URI reference string from its various components according to +[RFC 3986 Section 5.3](https://datatracker.ietf.org/doc/html/rfc3986#section-5.3). +Usually this method does not need to be called manually but instead is used +indirectly via `Psr\Http\Message\UriInterface::__toString`. + +PSR-7 UriInterface treats an empty component the same as a missing component as +`getQuery()`, `getFragment()` etc. always return a string. This explains the +slight difference to RFC 3986 Section 5.3. + +Another adjustment is that the authority separator is added even when the +authority is missing/empty for the "file" scheme. This is because PHP stream +functions like `file_get_contents` only work with `file:///myfile` but not with +`file:/myfile` although they are equivalent according to RFC 3986. But +`file:///` is the more common syntax for the file scheme anyway (Chrome for +example redirects to that format). The separator is omitted when such a URI has +a rootless or empty path: adding it would turn the first path segment into the +authority of the composed URI, or compose the string `file://`, which cannot be +parsed back into a URI. + +### `GuzzleHttp\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts): UriInterface` + +Creates a URI from a hash of +[`parse_url`](https://www.php.net/manual/en/function.parse-url.php) components. + +### `GuzzleHttp\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface` + +Creates a new URI with a specific query string value. Any existing query string +values that exactly match the provided key are removed and replaced with the +given key value pair. A value of null will set the query string key without a +value, e.g. "key" instead of "key=value". + +### `GuzzleHttp\Psr7\Uri::withQueryValues` + +`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface` + +Creates a new URI with multiple query string values. It has the same behavior as +`withQueryValue()` but for an associative array of key => value. + +### `GuzzleHttp\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface` + +Creates a new URI with a specific query string value removed. Any existing query +string values that exactly match the provided key are removed. + +## Cross-Origin Detection + +`GuzzleHttp\Psr7\UriComparator` provides methods to determine if a modified URI +should be considered cross-origin. + +### `GuzzleHttp\Psr7\UriComparator::isCrossOrigin` + +`public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool` + +Determines if a modified URI should be considered cross-origin with respect to +an original URI. + +Two URIs are cross-origin when their scheme, host, or effective port differ. +Host comparison is case-insensitive, and bracketed IPv6 literals are +canonicalized to their RFC 5952 form from any PSR-7 implementation before +comparison, so equivalent spellings of the same address are same-origin. +IPvFuture literals and bracketed values that cannot be parsed as an IPv6 +address, such as those carrying zone identifiers, still compare as +case-insensitive text. Missing ports use the default port for `http`, `https`, +`ws`, or `wss`. Other schemes do not receive implicit default ports. + +This helper only compares URI origins. It does not implement redirect handling +or credential policy. + +## Reference Resolution + +`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the +context of a base URI according to +[RFC 3986 Section 5](https://datatracker.ietf.org/doc/html/rfc3986#section-5). +This is also what web browsers do when resolving a link in a document based on +the current request URI. + +### `GuzzleHttp\Psr7\UriResolver::resolve` + +`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` + +Converts the relative URI into a new URI that is resolved against the base URI. + +When the resolved path is a relative-path reference whose first segment contains +a colon, which would be mistaken for a scheme name (RFC 3986 Section 4.2), it is +prefixed with `./`, e.g. `./a:b`. + +### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` + +`public static function removeDotSegments(string $path): string` + +Removes dot segments from a path and returns the new path according to +[RFC 3986 Section 5.2.4](https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4). + +Excess `..` segments above the root of an absolute path are dropped without +consuming the root, so the result can begin with `//` (e.g. `/..//a` becomes +`//a`). Such a path is not valid for a URI without an authority (RFC 3986 +Section 3.3); `resolve()` and `UriNormalizer::normalize()` serialize it with a +`/.` prefix in that case, like the WHATWG URL Standard. + +### `GuzzleHttp\Psr7\UriResolver::relativize` + +`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` + +Returns the target URI as a relative reference from the base URI. This method is +the counterpart to `resolve()`: + +```php +(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) +``` + +One use case is to use the current request URI as the base URI and then generate +relative links in your documents to reduce the document size or offer +self-contained downloadable document archives. + +```php +$base = new Uri('http://example.com/a/b/'); +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. +echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. +echo UriResolver::relativize($base, new Uri('http://example.com')); // prints '//example.com'. +``` + +This method also accepts a target that is already relative and will try to +relativize it further. Only a relative-path reference will be returned as-is. + +```php +echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well +``` + +## Normalization and Comparison + +`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs +according to +[RFC 3986 Section 6](https://datatracker.ietf.org/doc/html/rfc3986#section-6). + +### `GuzzleHttp\Psr7\UriNormalizer::normalize` + +`public static function normalize(UriInterface $uri, int $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` + +Returns a normalized URI. The scheme and host component are already normalized +to lowercase per PSR-7 UriInterface. This method adds additional normalizations +that can be configured with the `$flags` parameter, which is a bitmask of +normalizations to apply. + +PSR-7 UriInterface cannot distinguish between an empty component and a missing +component as `getQuery()`, `getFragment()` etc. always return a string. This +means the URIs `/?#` and `/` are treated equivalent which is not necessarily +true according to RFC 3986. But that difference is highly uncommon in reality. +So this potential normalization is implied in PSR-7 as well. + +A path the URI cannot hold, such as a `//`-leading path without an authority or +a relative-path reference whose first segment contains a colon, is prefixed with +`/.` or `./` respectively instead of throwing, as `UriResolver::resolve()` does. +The percent-encoding normalizations only do so where they rewrote the path. For +example, decoding `a%41:` yields `./aA:`, since `aA:` would be an absolute URI +with the scheme `aa`. + +The following normalizations are available: + +- `UriNormalizer::PRESERVING_NORMALIZATIONS` + + Default normalizations which only include the ones that preserve semantics. + +- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` + + All letters within a percent-encoding triplet (e.g., "%3A") are + case-insensitive, and should be capitalized. This applies to the userinfo, + host, path, query, and fragment components. Bracketed IP-literal hosts are + skipped as a legacy tolerance for nonstandard values other implementations + may carry; zone-identifier text was briefly valid URI syntax under RFC 6874, + which RFC 9844 obsoleted and reverted. The userinfo and host are only + rewritten when the value returned by the implementation matches the + normalized form, and a userinfo with an empty user segment is never + rewritten. No percent-encoding normalization is applied to a component that + contains malformed percent syntax, such as a `%` not followed by two + hexadecimal digits. + + Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` + +- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` + + Decodes percent-encoded octets of unreserved characters. For consistency, + percent-encoded octets in the ranges of ALPHA (%41–%5A and %61–%7A), DIGIT + (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) + should not be created by URI producers and, when found in a URI, should be + decoded to their corresponding unreserved characters by URI normalizers. + This applies to the userinfo, host, path, query, and fragment components. + Since the host is case-insensitive and PSR-7 requires it to be lowercase, + octets decoded in the host are lowercased (e.g., "%41" becomes "a"). + Bracketed IP-literal hosts are skipped as a legacy tolerance for nonstandard + values other implementations may carry; zone-identifier text was briefly + valid URI syntax under RFC 6874, which RFC 9844 obsoleted and reverted. The + userinfo and host are only rewritten when the value returned by the + implementation matches the normalized form, and a userinfo with an empty + user segment is never rewritten. No percent-encoding normalization is + applied to a component that contains malformed percent syntax, such as a `%` + not followed by two hexadecimal digits. + + Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` + +- `UriNormalizer::CONVERT_EMPTY_PATH` + + Converts the empty path to "/" for http and https URIs. + + Example: `http://example.org` → `http://example.org/` + +- `UriNormalizer::REMOVE_DEFAULT_HOST` + + Removes the default host of the given URI scheme from the URI. Only the + "file" scheme defines the default host "localhost". All of `file:/myfile`, + `file:///myfile`, and `file://localhost/myfile` are equivalent according to + RFC 3986. + + When removing the host leaves a URI without an authority whose path begins + with `//`, the path is serialized with a `/.` prefix. + + Example: `file://localhost/myfile` → `file:///myfile`, + `file://localhost//x` → `file:///.//x` + +- `UriNormalizer::REMOVE_DEFAULT_PORT` + + Removes the default port of the given URI scheme from the URI. + + Example: `http://example.org:80/` → `http://example.org/` + +- `UriNormalizer::REMOVE_DOT_SEGMENTS` + + Removes unnecessary dot-segments. Dot-segments in relative-path references + are not removed as it would change the semantics of the URI reference. + + Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` + +- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` + + Paths which include two or more adjacent slashes are converted to one. + Webservers usually ignore duplicate slashes and treat those URIs equivalent. + But in theory those URIs do not need to be equivalent. So this normalization + may change the semantics. Encoded slashes (%2F) are not removed. + + Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` + +- `UriNormalizer::SORT_QUERY_PARAMETERS` + + Sort query parameters with their values in alphabetical order. However, the + order of parameters in a URI may be significant (this is not defined by the + standard). So this normalization is not safe and may change the semantics of + the URI. + + Example: `?lang=en&article=fred` → `?article=fred&lang=en` + +- `UriNormalizer::CANONICALIZE_IPV6_HOST` + + Canonicalizes IPv6 hosts to their RFC 5952 form. IPv6 addresses allow + leading zeros and multiple placements of the `::` elision, so the same + address has many textual spellings. The canonical form is required for + IPv6 literals in URIs by RFC 5952 Section 6 and never changes what the URI + refers to. Native `Uri` instances already guarantee canonical output; for + other implementations, the canonical host is requested through + `withHost()` and the result is kept only when the returned `getHost()` + exactly matches the requested spelling, otherwise this step leaves the URI + unchanged while other selected normalizations still apply, and setter + exceptions propagate. + + Example: `http://[::0:0a]/` → `http://[::a]/` + +### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` + +`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool` + +Whether two URIs can be considered equivalent. Both URIs are normalized +automatically before comparison with the given `$normalizations` bitmask. The +method also accepts relative URI references and returns true when they are +equivalent. This of course assumes they will be resolved against the same base +URI. If this is not the case, determination of equivalence or difference of +relative references does not mean anything. + +## Related + +- [PSR-7 Messages](psr-7-messages.md) +- [Streams and Decorators](streams-and-decorators.md) +- [URI and MIME Helpers](uri-and-mime-helpers.md) +- [Header and Query Helpers](header-and-query-helpers.md) diff --git a/vendor/guzzlehttp/psr7/src/AppendStream.php b/vendor/guzzlehttp/psr7/src/AppendStream.php new file mode 100644 index 0000000..57ff9bd --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/AppendStream.php @@ -0,0 +1,257 @@ +addStream($stream); + } + } + + public function __toString(): string + { + $this->rewind(); + + return $this->getContents(); + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream): void + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Closes each attached stream. + */ + public function close(): void + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = []; + } + + /** + * Detaches each attached stream. + * + * Returns null as it's not clear which underlying stream resource to return. + */ + public function detach() + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->detach(); + } + + $this->streams = []; + + return null; + } + + public function tell(): int + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + */ + public function getSize(): ?int + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size = Integers::add($size, $s); + } + + return $size; + } + + public function eof(): bool + { + return !$this->streams + || ($this->current >= count($this->streams) - 1 + && $this->streams[$this->current]->eof()); + } + + public function rewind(): void + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + */ + public function seek(int $offset, int $whence = SEEK_SET): void + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } elseif ($offset < 0) { + throw new \RuntimeException('The AppendStream cannot seek to a negative offset'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + .$i.' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + * + * A timeout after some bytes were read returns those bytes, and the next + * read waits on the same stream again. + */ + public function read(int $length): string + { + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if ($this->streams === []) { + return ''; + } + + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + ++$this->current; + } + + try { + $result = StreamTimeout::read($this->streams[$this->current], $remaining, 'Unable to read from stream: timed out'); + } catch (TimeoutException $e) { + if ($buffer === '') { + throw $e; + } + + break; + } + + if ($result === '') { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos = Integers::add($this->pos, strlen($buffer)); + + return $buffer; + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return false; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function write(string $string): int + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + public function getMetadata(?string $key = null): ?array + { + return $key === null ? [] : null; + } +} diff --git a/vendor/guzzlehttp/psr7/src/BufferStream.php b/vendor/guzzlehttp/psr7/src/BufferStream.php new file mode 100644 index 0000000..68ae060 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/BufferStream.php @@ -0,0 +1,151 @@ +hwm = Integers::assertNonNegativeInteger($hwm, 'High water mark'); + } + + public function __toString(): string + { + return $this->getContents(); + } + + public function getContents(): string + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close(): void + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + + return null; + } + + public function getSize(): ?int + { + return strlen($this->buffer); + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return true; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof(): bool + { + return strlen($this->buffer) === 0; + } + + public function tell(): int + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read(int $length): string + { + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write(string $string): int + { + $this->buffer .= $string; + + if (strlen($this->buffer) >= $this->hwm) { + return 0; + } + + return strlen($string); + } + + /** + * @return mixed + */ + public function getMetadata(?string $key = null) + { + if ($key === 'hwm') { + return $this->hwm; + } + + return $key === null ? [] : null; + } +} diff --git a/vendor/guzzlehttp/psr7/src/CachingStream.php b/vendor/guzzlehttp/psr7/src/CachingStream.php new file mode 100644 index 0000000..4a92255 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/CachingStream.php @@ -0,0 +1,239 @@ +remoteStream = $stream; + $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); + } + + public function getSize(): ?int + { + if ($this->detached) { + return null; + } + + $remoteSize = $this->remoteStream->getSize(); + + if (null === $remoteSize) { + return null; + } + + return max($this->stream->getSize(), $remoteSize); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + if ($whence === SEEK_SET) { + $byte = $offset; + } elseif ($whence === SEEK_CUR) { + $byte = Integers::addSigned($this->tell(), $offset); + } elseif ($whence === SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + // Discovering the size reads the remote stream to EOF and + // moves the cursor, so restore the cursor if the computed + // target is rejected to keep a failed seek side-effect free. + $position = $this->tell(); + $size = $this->cacheEntireStream(); + + try { + $byte = Integers::addSigned($size, $offset); + } catch (\Throwable $e) { + $this->stream->seek($position); + + throw $e; + } + } else { + $byte = Integers::addSigned($size, $offset); + } + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // Read the remoteStream until we have read in at least the amount + // of bytes requested, or we reach the end of the file. + while ($diff > 0 && !$this->remoteStream->eof()) { + $previousSize = $this->stream->getSize(); + $previousSkipReadBytes = $this->skipReadBytes; + $data = $this->read($diff); + $currentSize = $this->stream->getSize(); + + if ($data === '' && $currentSize === $previousSize && $this->skipReadBytes === $previousSkipReadBytes) { + break; + } + + $diff = $byte - $currentSize; + } + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read(int $length): string + { + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = StreamTimeout::read( + $this->remoteStream, + Integers::add($remaining, $this->skipReadBytes), + 'Unable to read from stream: timed out' + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + + // A short cache write would silently corrupt later replays, so fail loudly. + if ($this->stream->write($remoteData) !== strlen($remoteData)) { + throw new \RuntimeException('Unable to cache the entire read from the remote stream'); + } + } + + return $data; + } + + public function write(string $string): int + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = Integers::add(strlen($string), $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes = max($this->skipReadBytes, $overflow); + } + + return $this->stream->write($string); + } + + public function eof(): bool + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + public function detach() + { + if ($this->detached) { + return null; + } + + $position = $this->tell(); + + $this->cacheEntireStream(); + $this->stream->seek($position); + + $resource = $this->stream->detach(); + $this->detached = true; + + return $resource; + } + + /** + * Close the remote stream and any attached cache stream. + */ + public function close(): void + { + if ($this->closed) { + return; + } + + $closeCache = !$this->detached; + $this->closed = true; + $this->detached = true; + + $exception = null; + + try { + $this->remoteStream->close(); + } catch (\Throwable $e) { + $exception = $e; + } + + if ($closeCache) { + try { + $this->stream->close(); + } catch (\Throwable $e) { + if ($exception === null) { + $exception = $e; + } + } + } + + if ($exception !== null) { + throw $exception; + } + } + + private function cacheEntireStream(): int + { + $target = new FnStream(['write' => 'strlen']); + Utils::copyToStream($this, $target); + + return $this->tell(); + } +} diff --git a/vendor/guzzlehttp/psr7/src/DiagnosticValue.php b/vendor/guzzlehttp/psr7/src/DiagnosticValue.php new file mode 100644 index 0000000..151aa9f --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/DiagnosticValue.php @@ -0,0 +1,63 @@ += 0x20 && $byte <= 0x7E) { + $escaped .= $value[$offset]; + + continue; + } + + $escaped .= \sprintf('\\x%02X', $byte); + } + + return $escaped; + } +} diff --git a/vendor/guzzlehttp/psr7/src/DroppingStream.php b/vendor/guzzlehttp/psr7/src/DroppingStream.php new file mode 100644 index 0000000..3a84ef5 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/DroppingStream.php @@ -0,0 +1,48 @@ +stream = $stream; + $this->maxLength = Integers::assertNonNegativeInteger($maxLength, 'Maximum length'); + } + + public function write(string $string): int + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/vendor/guzzlehttp/psr7/src/ErrorScope.php b/vendor/guzzlehttp/psr7/src/ErrorScope.php new file mode 100644 index 0000000..7f14696 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/ErrorScope.php @@ -0,0 +1,138 @@ + + */ + private array $errors = []; + + /** + * Creates a scope that captures errors of the given levels. + * + * Errors of other levels are passed on to the previously installed handler, + * which may be an enclosing scope. When `$silenced` is false, so are errors + * silenced inside the call with the `@` operator, which are those whose + * level was reported as the call started and is not reported when they are + * raised. + * + * @param int $levels Error levels to capture + * @param bool $silenced Whether to capture errors silenced inside the call + */ + public function __construct(int $levels = \E_ALL, bool $silenced = true) + { + $this->levels = $levels; + $this->silenced = $silenced; + } + + /** + * Runs the operation and returns its result, capturing the errors raised + * beneath it. + * + * A scope runs one operation at a time, so calling this again before it + * returns throws a `LogicException`. + * + * @template T + * + * @param callable(): T $operation + * + * @return T + * + * @throws \LogicException if the scope is already running an operation + */ + public function run(callable $operation) + { + if ($this->running) { + throw new \LogicException(static::class.' is already running an operation'); + } + + $owner = $this; + $previous = null; + $previous = set_error_handler(static function (int $errno, string $errstr, string $errfile = '', int $errline = 0, ...$rest) use ($owner, &$previous): bool { + foreach (debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) { + $scope = $frame['object'] ?? null; + if (!$scope instanceof self) { + continue; + } + + if ($scope->captures($errno)) { + $scope->errors[] = [ + 'message' => $errstr, + 'file' => $errfile, + 'line' => $errline, + ]; + + return true; + } + + // Outer scopes are reached through the previous handler. + if ($scope === $owner) { + break; + } + } + + return $previous !== null && $previous($errno, $errstr, $errfile, $errline, ...$rest) !== false; + }); + + $this->reporting = error_reporting(); + $this->running = true; + + try { + return $operation(); + } finally { + $this->running = false; + restore_error_handler(); + } + } + + /** + * Returns the message of the last error captured, if any. + */ + public function getError(): ?string + { + $error = end($this->errors); + + return $error === false ? null : $error['message']; + } + + /** + * Returns the errors captured, in the order they were raised. + * + * @return list + */ + public function getErrors(): array + { + return $this->errors; + } + + private function captures(int $errno): bool + { + if (($this->levels & $errno) === 0) { + return false; + } + + // An error is silenced inside the call when its level was reported as + // the call started and is not reported now. + return $this->silenced || (error_reporting() & $errno) !== 0 || ($this->reporting & $errno) === 0; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php b/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php new file mode 100644 index 0000000..3a08477 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php @@ -0,0 +1,14 @@ + */ + private array $methods; + + private bool $detached = false; + + /** + * @param array $methods Hash of method name to a callable. + */ + public function __construct(array $methods) + { + $this->methods = $methods; + + // Create the callables on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_'.$name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * + * @throws \BadMethodCallException + */ + public function __get(string $name): void + { + throw new \BadMethodCallException(\sprintf('%s() is not implemented in the FnStream', DiagnosticValue::escape(str_replace('_fn_', '', $name)))); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if ($this->detached || !isset($this->_fn_close)) { + return; + } + + try { + $this->close(); + } catch (\Throwable $e) { + // Destructors must not surface cleanup failures. + } + } + + /** + * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. + * + * @throws \LogicException + */ + public function __wakeup(): void + { + $this->methods = []; + $this->detached = true; + + throw new \LogicException(static::class.' should never be unserialized'); + } + + public function __unserialize(array $data): void + { + $this->methods = []; + $this->detached = true; + + throw new \LogicException(static::class.' should never be unserialized'); + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a callable + */ + public static function decorate(StreamInterface $stream, array $methods): self + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::SLOTS, array_keys($methods)) as $diff) { + /** @var callable $callable */ + $callable = [$stream, $diff]; + $methods[$diff] = $callable; + } + + return new self($methods); + } + + public function __toString(): string + { + $this->assertAttached(); + + /** @var string */ + return ($this->_fn___toString)(); + } + + public function close(): void + { + if ($this->detached) { + return; + } + + $close = $this->_fn_close; + $this->detached = true; + $close(); + } + + public function detach() + { + if ($this->detached) { + return null; + } + + $detach = $this->_fn_detach; + $result = $detach(); + $this->detached = true; + + return $result; + } + + public function getSize(): ?int + { + if ($this->detached) { + return null; + } + + return ($this->_fn_getSize)(); + } + + public function tell(): int + { + $this->assertAttached(); + + return ($this->_fn_tell)(); + } + + public function eof(): bool + { + $this->assertAttached(); + + return ($this->_fn_eof)(); + } + + public function isSeekable(): bool + { + if ($this->detached) { + return false; + } + + return ($this->_fn_isSeekable)(); + } + + public function rewind(): void + { + $this->assertAttached(); + + ($this->_fn_rewind)(); + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + $this->assertAttached(); + + ($this->_fn_seek)($offset, $whence); + } + + public function isWritable(): bool + { + if ($this->detached) { + return false; + } + + return ($this->_fn_isWritable)(); + } + + public function write(string $string): int + { + $this->assertAttached(); + + return ($this->_fn_write)($string); + } + + public function isReadable(): bool + { + if ($this->detached) { + return false; + } + + return ($this->_fn_isReadable)(); + } + + public function read(int $length): string + { + $this->assertAttached(); + + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + return ($this->_fn_read)($length); + } + + public function getContents(): string + { + $this->assertAttached(); + + return ($this->_fn_getContents)(); + } + + /** + * @return mixed + */ + public function getMetadata(?string $key = null) + { + if ($this->detached) { + return $key === null ? [] : null; + } + + return ($this->_fn_getMetadata)($key); + } + + private function assertAttached(): void + { + if ($this->detached) { + throw new \RuntimeException('Stream is detached'); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/Header.php b/vendor/guzzlehttp/psr7/src/Header.php new file mode 100644 index 0000000..f26cd26 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Header.php @@ -0,0 +1,167 @@ +]+>|[^=]+)=*(.*)$/Ds', $kvp, $matches); + + if ($count === false) { + throw new \RuntimeException('Unable to parse header parameters: '.preg_last_error_msg()); + } + + if ($count !== 0) { + if ($matches[2] !== '') { + $part[trim($matches[1], $trimmed)] = trim($matches[2], $trimmed); + } else { + $part[] = trim($matches[1], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + } + + return $params; + } + + /** + * Split a header value into semicolon-separated parameters. + * + * @return string[] + */ + private static function splitParameters(string $value): array + { + $values = []; + $start = 0; + $isQuoted = false; + $isEscaped = false; + + for ($i = 0, $max = \strlen($value); $i < $max; ++$i) { + $char = $value[$i]; + + if ($isEscaped) { + $isEscaped = false; + + continue; + } + + if ($isQuoted && $char === '\\') { + $isEscaped = true; + + continue; + } + + if ($char === '"') { + $isQuoted = !$isQuoted; + + continue; + } + + if (!$isQuoted && $char === ';') { + $values[] = \substr($value, $start, $i - $start); + $start = $i + 1; + } + } + + $values[] = \substr($value, $start); + + return $values; + } + + /** + * Splits an HTTP header defined to contain a comma-separated list into each + * individual value. Empty values are removed. + * + * Example headers include `accept`, `cache-control`, and `if-none-match`. + * + * This method must not be used to parse headers that are not defined as a + * list, such as `user-agent` or `set-cookie`. + * + * @param string|string[] $values Header value as returned by + * MessageInterface::getHeader() + * + * @return string[] + */ + public static function splitList($values): array + { + if (!\is_array($values)) { + $values = [$values]; + } + + $result = []; + foreach ($values as $value) { + if (!\is_string($value)) { + throw new \TypeError('$header must either be a string or an array containing strings.'); + } + + $v = ''; + $isQuoted = false; + $isEscaped = false; + for ($i = 0, $max = \strlen($value); $i < $max; ++$i) { + if ($isEscaped) { + $v .= $value[$i]; + $isEscaped = false; + + continue; + } + + if (!$isQuoted && $value[$i] === ',') { + $v = \trim($v, " \t\n\r"); + if ($v !== '') { + $result[] = $v; + } + + $v = ''; + continue; + } + + if ($isQuoted && $value[$i] === '\\') { + $isEscaped = true; + $v .= $value[$i]; + + continue; + } + if ($value[$i] === '"') { + $isQuoted = !$isQuoted; + $v .= $value[$i]; + + continue; + } + + $v .= $value[$i]; + } + + $v = \trim($v, " \t\n\r"); + if ($v !== '') { + $result[] = $v; + } + } + + return $result; + } +} diff --git a/vendor/guzzlehttp/psr7/src/HttpFactory.php b/vendor/guzzlehttp/psr7/src/HttpFactory.php new file mode 100644 index 0000000..7f1b562 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/HttpFactory.php @@ -0,0 +1,111 @@ +getSize(); + } + + return new UploadedFile( + $stream, + Integers::assertOptionalNonNegativeSize($size, 'Uploaded file size'), + $error, + $clientFilename, + $clientMediaType + ); + } + + public function createStream(string $content = ''): StreamInterface + { + return Utils::streamFor($content); + } + + public function createStreamFromFile(string $file, string $mode = 'r'): StreamInterface + { + try { + $resource = Utils::tryFopen($file, $mode); + } catch (\RuntimeException $e) { + if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], true)) { + throw new \InvalidArgumentException(sprintf('Invalid file opening mode: %s', DiagnosticValue::escape($mode)), 0, $e); + } + + throw $e; + } + + return Utils::streamFor($resource); + } + + public function createStreamFromResource($resource): StreamInterface + { + return Utils::streamFor($resource); + } + + public function createServerRequest( + string $method, + $uri, + #[\SensitiveParameter] + array $serverParams = [] + ): ServerRequestInterface { + if (empty($method)) { + if (!empty($serverParams['REQUEST_METHOD'])) { + $method = $serverParams['REQUEST_METHOD']; + } else { + throw new \InvalidArgumentException('Cannot determine HTTP method'); + } + } + + if (is_string($uri)) { + // A peer must not be able to raise the URI deprecations. + $uri = (new ErrorScope(\E_USER_DEPRECATED))->run(static function () use ($uri): Uri { + return new Uri($uri); + }); + } + + return new ServerRequest($method, $uri, [], null, '1.1', $serverParams); + } + + public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface + { + return new Response($code, [], null, '1.1', $reasonPhrase); + } + + public function createRequest(string $method, $uri): RequestInterface + { + return new Request($method, $uri); + } + + public function createUri(string $uri = ''): UriInterface + { + return new Uri($uri); + } +} diff --git a/vendor/guzzlehttp/psr7/src/Idna.php b/vendor/guzzlehttp/psr7/src/Idna.php new file mode 100644 index 0000000..ff6e709 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Idna.php @@ -0,0 +1,162 @@ +getMessage(), 0, $e); + } + + if (!isset($parts['scheme']) && !str_starts_with($uri, '//')) { + \trigger_deprecation( + 'guzzlehttp/psr7', + '3.6', + 'Passing a URI string that starts with a host and port, such as "example.com:8080", is deprecated; guzzlehttp/psr7 4.0 rejects it. Start the string with a scheme or with "//".' + ); + } + + return Uri::fromParts($parts); + } + + private static function hasNonAsciiData(string $value): bool + { + // An engine failure counts as non-ASCII so it cannot skip conversion. + return preg_match('/[\x80-\xFF]|%[89A-Fa-f][0-9A-Fa-f]/', $value) !== 0; + } + + private static function isPlainAsciiHost(string $host): bool + { + return preg_match('/\A[\x21-\x7E]++\z/', $host) === 1 + && strpbrk($host, '%[]') === false + && Rfc3986::isValidHost($host); + } + + /** + * @param mixed $errors + */ + private static function describeErrors($errors): string + { + $names = []; + + if (is_int($errors) && $errors !== 0) { + foreach (get_defined_constants() as $name => $value) { + if (str_starts_with($name, 'IDNA_ERROR_') && is_int($value) && ($errors & $value) !== 0) { + $names[] = $name; + } + } + } + + return implode(', ', $names); + } +} diff --git a/vendor/guzzlehttp/psr7/src/InflateStream.php b/vendor/guzzlehttp/psr7/src/InflateStream.php new file mode 100644 index 0000000..7a7ebe3 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/InflateStream.php @@ -0,0 +1,146 @@ +source = $stream; + $this->capturingSource = new ReadFailureCapturingStream($stream); + $inflated = self::inflate($this->capturingSource); + $this->stream = $stream->isSeekable() ? $inflated : new NoSeekStream($inflated); + } + + public function eof(): bool + { + return ($this->capturingSource === null || !$this->capturingSource->hasReadFailure()) && $this->stream->eof(); + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + $this->stream->seek($offset, $whence); + + if ($offset === 0 && $whence === SEEK_SET && $this->capturingSource !== null) { + $this->capturingSource->takeReadFailure(); + $this->stream = self::inflate($this->capturingSource); + } + } + + public function read(int $length): string + { + if ($length <= 0 || $this->source === null || $this->capturingSource === null) { + return $this->stream->read($length); + } + + // A source failure that follows decoded bytes is reported by the next read. + $failure = $this->capturingSource->takeReadFailure(); + + if ($failure === null) { + try { + $data = $this->stream->read($length); + } catch (TimeoutException $e) { + throw $e; + } catch (\RuntimeException $e) { + if (StreamTimeout::isReadTimedOut($this->source)) { + throw new TimeoutException('Unable to read from stream: timed out', 0, $e); + } + + throw $e; + } + + if ($data !== '') { + return $data; + } + + $failure = $this->capturingSource->takeReadFailure(); + } + + if ($failure instanceof TimeoutException || StreamTimeout::isReadTimedOut($this->source)) { + throw new TimeoutException('Unable to read from stream: timed out', 0, $failure); + } + + if ($failure !== null) { + throw new \RuntimeException('Unable to read from stream', 0, $failure); + } + + return ''; + } + + public function close(): void + { + $source = $this->source; + $this->source = null; + $this->capturingSource = null; + + $exception = null; + + try { + $this->stream->close(); + } catch (\Throwable $e) { + $exception = $e; + } + + if ($source !== null) { + try { + $source->close(); + } catch (\Throwable $e) { + if ($exception === null) { + $exception = $e; + } + } + } + + if ($exception !== null) { + throw $exception; + } + } + + public function detach() + { + $this->source = null; + if ($this->capturingSource !== null) { + $this->capturingSource->stopCapturing(); + $this->capturingSource = null; + } + + return $this->stream->detach(); + } + + private static function inflate(StreamInterface $stream): Stream + { + $resource = StreamWrapper::getResource($stream); + // Specify window=15+32, so zlib will use header detection to both gzip (with header) and zlib data + // See https://www.zlib.net/manual.html#Advanced definition of inflateInit2 + // "Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection" + // Default window size is 15. + stream_filter_append($resource, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15 + 32]); + + return new Stream($resource); + } +} diff --git a/vendor/guzzlehttp/psr7/src/Integers.php b/vendor/guzzlehttp/psr7/src/Integers.php new file mode 100644 index 0000000..7eead64 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Integers.php @@ -0,0 +1,104 @@ + \PHP_INT_MAX - $a) { + throw new \OverflowException('Stream byte count exceeds the maximum integer size supported on this platform'); + } + + return $a + $b; + } + + public static function addSigned(int $base, int $delta): int + { + if ($base < 0) { + throw new \InvalidArgumentException('Stream offset must be non-negative'); + } + + if ($delta > 0 && $delta > \PHP_INT_MAX - $base) { + throw new \OverflowException('Stream offset exceeds the maximum integer size supported on this platform'); + } + + $value = $base + $delta; + if ($value < 0) { + // A negative computed offset is a seek failure at runtime, so throw + // RuntimeException per PSR-7, unlike the precondition check above. + throw new \RuntimeException('Stream offset must be non-negative'); + } + + return $value; + } + + /** + * @param mixed $value + */ + public static function assertEngineInteger($value, string $what): ?int + { + if ($value === false || $value === null) { + return null; + } + + if (!\is_int($value) || $value < 0) { + throw new \OverflowException($what.' exceeds the maximum integer size supported on this platform'); + } + + return $value; + } + + /** + * @param mixed $value + */ + public static function assertOptionalNonNegativeSize($value, string $name): ?int + { + if ($value === null) { + return null; + } + + if (!\is_int($value) || $value < 0) { + throw new \InvalidArgumentException($name.' must be a non-negative integer or null'); + } + + return $value; + } + + /** + * @param mixed $value + */ + public static function assertNonNegativeInteger($value, string $name): int + { + if (!\is_int($value) || $value < 0) { + throw new \InvalidArgumentException($name.' must be a non-negative integer'); + } + + return $value; + } + + /** + * @param mixed $value + */ + public static function assertLimitInteger($value, string $name): int + { + if (!\is_int($value) || $value < -1) { + throw new \InvalidArgumentException($name.' must be -1 or a non-negative integer'); + } + + return $value; + } +} diff --git a/vendor/guzzlehttp/psr7/src/LazyOpenStream.php b/vendor/guzzlehttp/psr7/src/LazyOpenStream.php new file mode 100644 index 0000000..06e0849 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/LazyOpenStream.php @@ -0,0 +1,52 @@ +filename = $filename; + $this->mode = $mode; + + // unsetting the property forces the first access to go through + // __get(). + unset($this->stream); + } + + public function __unserialize(array $data): void + { + $this->stream = new BufferStream(); + + throw new \LogicException(static::class.' should never be unserialized'); + } + + /** + * Creates the underlying stream lazily when required. + */ + protected function createStream(): StreamInterface + { + return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode)); + } +} diff --git a/vendor/guzzlehttp/psr7/src/LimitStream.php b/vendor/guzzlehttp/psr7/src/LimitStream.php new file mode 100644 index 0000000..03887b3 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/LimitStream.php @@ -0,0 +1,197 @@ +stream = $stream; + $this->setLimit($limit); + $this->setOffset($offset); + } + + public function eof(): bool + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit === -1) { + return false; + } + + return $this->stream->tell() >= Integers::add($this->offset, $this->limit); + } + + /** + * Returns the size of the limited subset of data + */ + public function getSize(): ?int + { + if (null === ($length = $this->stream->getSize())) { + return null; + } + + $size = $length - $this->offset; + + if ($this->limit !== -1) { + $size = min($this->limit, $size); + } + + return max(0, $size); + } + + /** + * Allow for a bounded seek on the read limited stream + */ + public function seek(int $offset, int $whence = SEEK_SET): void + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset %s with whence %s', + $offset, + $whence + )); + } + + $offset = Integers::add($this->offset, $offset); + + if ($this->limit !== -1) { + $upperBound = Integers::add($this->offset, $this->limit); + if ($offset > $upperBound) { + $offset = $upperBound; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + */ + public function tell(): int + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset(int $offset): void + { + $offset = Integers::assertNonNegativeInteger($offset, 'Offset'); + + $current = $this->stream->tell(); + + if ($current === $offset) { + $this->offset = $offset; + + return; + } + + // If the stream cannot seek to the offset position, then read to it. + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + $this->offset = $offset; + + return; + } + + if ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } + + while ($current < $offset) { + if ($this->stream->eof()) { + $this->offset = $current; + + return; + } + + $result = $this->stream->read($offset - $current); + + if ($result === '') { + if ($this->stream->eof()) { + $this->offset = $current; + + return; + } + + throw new \RuntimeException("Could not seek to stream offset $offset"); + } + + $current = Integers::add($current, strlen($result)); + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit(int $limit): void + { + $this->limit = Integers::assertLimitInteger($limit, 'Limit'); + } + + public function read(int $length): string + { + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if ($this->limit === -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = Integers::add($this->offset, $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Message.php b/vendor/guzzlehttp/psr7/src/Message.php new file mode 100644 index 0000000..293b4a8 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Message.php @@ -0,0 +1,262 @@ +getMethod().' ' + .$message->getRequestTarget(), " \n\r\t\0\x0B") + .' HTTP/'.$message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: ".self::hostHeaderFromUri($message->getUri()); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/'.$message->getProtocolVersion().' ' + .$message->getStatusCode().' ' + .$message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + if (is_string($name) && Utils::asciiToLower($name) === 'set-cookie') { + foreach ($values as $value) { + $msg .= "\r\n{$name}: ".$value; + } + } else { + $msg .= "\r\n{$name}: ".implode(', ', $values); + } + } + + return "{$msg}\r\n\r\n".$message->getBody(); + } + + private static function hostHeaderFromUri(UriInterface $uri): string + { + $host = $uri->getHost(); + + if ($host === '') { + return ''; + } + + Uri::assertValidHost($host); + + // A Uri has already raised the deprecation for its own host. + if (!$uri instanceof Uri) { + Uri::deprecateNonAsciiHost($host); + } + + if (($port = $uri->getPort()) !== null) { + $host .= ':'.$port; + } + + return $host; + } + + /** + * Get a short summary of the message body. + * + * Will return `null` if the response is not printable. + * + * Reads seekable bodies from the beginning and restores the original cursor + * position before returning. Pass `null` for `$truncateAt` to use the + * default summary length. + * + * @param MessageInterface $message The message to get the body summary + * @param int|null $truncateAt Maximum allowed size of the summary + */ + public static function bodySummary(MessageInterface $message, ?int $truncateAt = null): ?string + { + $truncateAt ??= self::DEFAULT_BODY_SUMMARY_TRUNCATE_AT; + + $body = $message->getBody(); + + if (!$body->isSeekable() || !$body->isReadable()) { + return null; + } + + $size = $body->getSize(); + + if ($size === 0) { + return null; + } + + $position = $body->tell(); + + try { + $body->rewind(); + $summary = $body->read($truncateAt); + $lookahead = $size === null ? $body->read(3) : ''; + + if ($size > $truncateAt || $lookahead !== '') { + if (preg_match('//u', $summary) !== 1) { + $summary = self::trimTrailingIncompleteUtf8Character($summary, $lookahead !== '' ? $lookahead : $body->read(3)); + } + + $summary .= ' (truncated...)'; + } + } finally { + $body->seek($position); + } + + // Matches any printable character, including unicode characters: + // letters, marks, numbers, punctuation, spacing, and separators. + if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary) !== 0) { + return null; + } + + return $summary; + } + + /** + * Trims a partial UTF-8 character from the end of a truncated string. + */ + private static function trimTrailingIncompleteUtf8Character(string $summary, string $lookahead): string + { + $length = strlen($summary); + + if ($length === 0) { + return $summary; + } + + $start = $length - 1; + + while ($start >= 0) { + $byte = ord($summary[$start]); + + if ($byte < 0x80 || $byte > 0xBF) { + break; + } + + --$start; + } + + if ($start < 0) { + return $summary; + } + + $lead = ord($summary[$start]); + + if ($lead >= 0xC2 && $lead <= 0xDF) { + $expectedLength = 2; + } elseif ($lead >= 0xE0 && $lead <= 0xEF) { + $expectedLength = 3; + } elseif ($lead >= 0xF0 && $lead <= 0xF4) { + $expectedLength = 4; + } else { + return $summary; + } + + $availableLength = $length - $start; + + if ($availableLength >= $expectedLength) { + return $summary; + } + + $sequence = substr($summary, $start).substr($lookahead, 0, $expectedLength - $availableLength); + + if (strlen($sequence) !== $expectedLength || preg_match('//u', $sequence) !== 1) { + return $summary; + } + + return substr($summary, 0, $start); + } + + /** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` + * returns a value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ + public static function rewindBody(MessageInterface $message): void + { + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } + } + + /** + * Parses an HTTP message into an associative array. + * + * The array contains the `start-line` key containing the start line of the + * message, `headers` key containing an associative array of header array + * values, and a `body` key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + */ + public static function parseMessage(string $message): array + { + return MessageParser::parseMessage($message); + } + + /** + * Constructs a URI for an HTTP request message. + * + * The URI is composed from the start-line path and the `Host` header, using + * `https` when the host's port is `443` and `http` otherwise. Without a + * `Host` header, only the path is returned, with extra leading slashes + * collapsed so an origin-form target cannot be parsed as a network-path + * reference with its own authority. An `InvalidArgumentException` is thrown + * when the `Host` header is invalid. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + */ + public static function parseRequestUri(string $path, array $headers): string + { + return MessageParser::parseRequestUri($path, $headers); + } + + /** + * Parses a request message string into a request object. + * + * The request-target must be in origin form, absolute form (without a + * userinfo component), authority form (`CONNECT`), or asterisk form + * (`OPTIONS`), and any `Host` header must be a single valid value; + * otherwise an `InvalidArgumentException` is thrown. Non-origin-form + * targets are preserved on the returned request via `withRequestTarget()`. + * + * @param string $message Request message string. + */ + public static function parseRequest(string $message): RequestInterface + { + return MessageParser::parseRequest($message); + } + + /** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + */ + public static function parseResponse(string $message): ResponseInterface + { + return MessageParser::parseResponse($message); + } +} diff --git a/vendor/guzzlehttp/psr7/src/MessageParser.php b/vendor/guzzlehttp/psr7/src/MessageParser.php new file mode 100644 index 0000000..377add0 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MessageParser.php @@ -0,0 +1,371 @@ +> $headerLines */ + if ($count === false) { + throw new \RuntimeException('Unable to parse HTTP headers: '.preg_last_error_msg()); + } + + // If these aren't the same, then one line didn't match and there's an invalid header. + if ($count !== substr_count($rawHeaders, "\n")) { + // Folding is deprecated, see https://datatracker.ietf.org/doc/html/rfc9112#section-5.2 + $hasFoldedHeader = preg_match(Rfc9112::HEADER_FOLD_REGEX, $rawHeaders); + + if ($hasFoldedHeader === false) { + throw new \RuntimeException('Unable to inspect HTTP header folding: '.preg_last_error_msg()); + } + + if ($hasFoldedHeader === 1) { + throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); + } + + throw new \InvalidArgumentException('Invalid header syntax'); + } + + $headers = []; + + foreach ($headerLines as $headerLine) { + $headers[$headerLine[1]][] = $headerLine[2]; + } + + return [ + 'start-line' => $startLine, + 'headers' => $headers, + 'body' => $body, + ]; + } + + public static function parseRequestUri(string $path, array $headers): string + { + $host = self::getHostFromHeaders($headers); + + // If no host is found, then a full URI cannot be constructed. + // Collapse leading slashes so an origin-form target cannot be + // parsed as a network-path reference with its own authority. + if ($host === null) { + return self::normalizePathForOriginForm($path); + } + + [$authorityHost, $port] = self::parseHostHeaderAuthority($host); + $scheme = $port === 443 ? 'https' : 'http'; + + return $scheme.'://'.self::composeAuthority($authorityHost, $port).'/'.ltrim($path, '/'); + } + + private static function normalizePathForOriginForm(string $path): string + { + if (str_starts_with($path, '//')) { + return '/'.ltrim($path, '/'); + } + + return $path; + } + + /** + * @return array{0: string, 1: int|null} + */ + private static function parseHostHeaderAuthority(string $authority): array + { + $parsed = Rfc9112::parseHostHeader($authority); + if ($parsed === null) { + throw new \InvalidArgumentException('Invalid request string'); + } + + return $parsed; + } + + private static function composeAuthority(string $host, ?int $port): string + { + return $host.($port !== null ? ':'.$port : ''); + } + + /** + * @param array $headers Array of headers (each value an array). + */ + private static function getHostFromHeaders(array $headers): ?string + { + $host = self::getSingleHostHeader($headers); + if ($host === null) { + return null; + } + + self::parseHostHeaderAuthority($host); + + return $host; + } + + /** + * @param array $headers Array of headers (each value an array). + */ + private static function getSingleHostHeader(array $headers): ?string + { + $host = null; + $found = false; + + foreach ($headers as $name => $values) { + if (Utils::asciiToLower((string) $name) !== 'host') { + continue; + } + + if ($found || !is_array($values) || count($values) !== 1) { + throw new \InvalidArgumentException('Invalid request string'); + } + + $found = true; + $host = reset($values); + } + + if (!$found) { + return null; + } + + if (!is_string($host)) { + throw new \InvalidArgumentException('Invalid request string'); + } + + return $host; + } + + /** + * @param array $headers Array of headers (each value an array). + */ + private static function parseRequestAuthorityUri(array $headers): string + { + $host = self::getHostFromHeaders($headers); + if ($host === null) { + return ''; + } + + [$authorityHost, $port] = self::parseHostHeaderAuthority($host); + $scheme = $port === 443 ? 'https' : 'http'; + + return $scheme.'://'.self::composeAuthority($authorityHost, $port); + } + + public static function parseRequest(string $message): RequestInterface + { + $data = self::parseMessage($message); + $matches = []; + $matched = preg_match( + '/^(?P'.Rfc9110::TOKEN_PATTERN.') (?P'.Rfc9112::REQUEST_TARGET_PATTERN.') HTTP\/(?P'.Rfc9112::PROTOCOL_VERSION_PATTERN.')$/D', + $data['start-line'], + $matches + ); + + if ($matched === false) { + throw new \RuntimeException('Unable to parse request start line: '.preg_last_error_msg()); + } + + if ($matched === 0) { + throw new \InvalidArgumentException('Invalid request string'); + } + + self::getHostFromHeaders($data['headers']); + + if (str_starts_with($matches['target'], '/')) { + return new Request( + $matches['method'], + self::createUri(self::parseRequestUri($matches['target'], $data['headers'])), + $data['headers'], + $data['body'], + $matches['version'] + ); + } + + $absoluteFormUri = self::parseAbsoluteFormRequestTarget($matches['target']); + if ($absoluteFormUri !== null) { + return (new Request( + $matches['method'], + $absoluteFormUri, + $data['headers'], + $data['body'], + $matches['version'] + ))->withRequestTarget($matches['target']); + } + + if (Rfc9112::isAsteriskFormRequestTarget($matches['method'], $matches['target'])) { + return (new Request( + $matches['method'], + self::createUri(self::parseRequestAuthorityUri($data['headers'])), + $data['headers'], + $data['body'], + $matches['version'] + ))->withRequestTarget($matches['target']); + } + + $connectUri = self::parseConnectAuthorityFormRequestTarget($matches['method'], $matches['target']); + if ($connectUri !== null) { + return (new Request( + $matches['method'], + $connectUri, + $data['headers'], + $data['body'], + $matches['version'] + ))->withRequestTarget($matches['target']); + } + + throw new \InvalidArgumentException('Invalid request string'); + } + + private static function parseAbsoluteFormRequestTarget(string $target): ?Uri + { + if (!Rfc9112::isAbsoluteFormRequestTarget($target)) { + return null; + } + + $authority = substr($target, strpos($target, '//') + 2); + $authority = substr($authority, 0, strcspn($authority, '/?#')); + + // RFC 9110 deprecates userinfo in message target URIs and directs + // recipients to treat its presence as an error, since it can obscure + // the authority. Host headers and CONNECT targets already reject it. + if (str_contains($authority, '@')) { + return null; + } + + try { + $uri = self::createUri($target); + } catch (\InvalidArgumentException $e) { + return null; + } + + if ($uri->getHost() === '') { + return null; + } + + try { + self::parseHostHeaderAuthority(self::composeAuthority($uri->getHost(), $uri->getPort())); + } catch (\InvalidArgumentException $e) { + return null; + } + + return $uri; + } + + private static function parseConnectAuthorityFormRequestTarget(string $method, string $target): ?Uri + { + if (!Rfc9112::isConnectAuthorityFormRequestTarget($method, $target)) { + return null; + } + + $parsed = Rfc9112::parseHostHeader($target); + if ($parsed === null) { + return null; + } + + [$host, $port] = $parsed; + if ($port === null) { + return null; + } + + try { + return self::createUri('//'.self::composeAuthority($host, $port)); + } catch (\InvalidArgumentException $e) { + return null; + } + } + + private static function createUri(string $uri): Uri + { + // A peer must not be able to raise the host deprecation. + return (new ErrorScope(\E_USER_DEPRECATED))->run(static function () use ($uri): Uri { + return new Uri($uri); + }); + } + + public static function parseResponse(string $message): ResponseInterface + { + $data = self::parseMessage($message); + // According to https://datatracker.ietf.org/doc/html/rfc9112#section-4 + // the space between status-code and reason-phrase is required. But + // browsers accept responses without space and reason as well. + $matched = preg_match( + '/^HTTP\/(?P'.Rfc9112::PROTOCOL_VERSION_PATTERN.') (?P[1-5][0-9]{2})(?: (?P'.Rfc9110::FIELD_VALUE_PATTERN.'))?$/D', + $data['start-line'], + $matches + ); + + if ($matched === false) { + throw new \RuntimeException('Unable to parse response start line: '.preg_last_error_msg()); + } + + if ($matched === 0) { + throw new \InvalidArgumentException(\sprintf('Invalid response string: %s', DiagnosticValue::escape($data['start-line']))); + } + + return new Response( + (int) $matches['status'], + $data['headers'], + $data['body'], + $matches['version'], + $matches['reason'] ?? null + ); + } +} diff --git a/vendor/guzzlehttp/psr7/src/MessageTrait.php b/vendor/guzzlehttp/psr7/src/MessageTrait.php new file mode 100644 index 0000000..15c4232 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MessageTrait.php @@ -0,0 +1,279 @@ + array of values */ + private array $headers = []; + + /** @var string[] Map of lowercase header name => original name at registration */ + private array $headerNames = []; + + private string $protocol = '1.1'; + + private ?StreamInterface $stream = null; + + public function getProtocolVersion(): string + { + return $this->protocol; + } + + /** + * @return static + */ + public function withProtocolVersion(string $version): MessageInterface + { + $this->assertProtocolVersion($version); + + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + + return $new; + } + + public function getHeaders(): array + { + return $this->headers; + } + + public function hasHeader(string $name): bool + { + return isset($this->headerNames[Utils::asciiToLower($name)]); + } + + public function getHeader(string $name): array + { + $header = Utils::asciiToLower($name); + + if (!isset($this->headerNames[$header])) { + return []; + } + + $header = $this->headerNames[$header]; + + return $this->headers[$header]; + } + + public function getHeaderLine(string $name): string + { + return implode(', ', $this->getHeader($name)); + } + + /** + * @return static + */ + public function withHeader(string $name, $value): MessageInterface + { + $this->assertHeader($name); + $value = $this->normalizeHeaderValue($name, $value); + $normalized = Utils::asciiToLower($name); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + unset($new->headers[$new->headerNames[$normalized]]); + } + $new->headerNames[$normalized] = $name; + $new->headers[$name] = $value; + + return $new; + } + + /** + * @return static + */ + public function withAddedHeader(string $name, $value): MessageInterface + { + $this->assertHeader($name); + $value = $this->normalizeHeaderValue($name, $value); + $normalized = Utils::asciiToLower($name); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + $name = $this->headerNames[$normalized]; + $new->headers[$name] = array_merge($this->headers[$name], $value); + } else { + $new->headerNames[$normalized] = $name; + $new->headers[$name] = $value; + } + + return $new; + } + + /** + * @return static + */ + public function withoutHeader(string $name): MessageInterface + { + $normalized = Utils::asciiToLower($name); + + if (!isset($this->headerNames[$normalized])) { + return $this; + } + + $name = $this->headerNames[$normalized]; + + $new = clone $this; + unset($new->headers[$name], $new->headerNames[$normalized]); + + return $new; + } + + public function getBody(): StreamInterface + { + if (!$this->stream) { + $this->stream = Utils::streamFor(''); + } + + return $this->stream; + } + + /** + * @return static + */ + public function withBody(StreamInterface $body): MessageInterface + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + + return $new; + } + + /** + * @param (string|string[])[] $headers + */ + private function setHeaders(array $headers): void + { + $this->headerNames = $this->headers = []; + foreach ($headers as $header => $value) { + // Numeric array keys are converted to int by PHP. + $header = (string) $header; + + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($header, $value); + $normalized = Utils::asciiToLower($header); + if (isset($this->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $this->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $this->headerNames[$normalized] = $header; + $this->headers[$header] = $value; + } + } + } + + /** + * @param mixed $value + * + * @return string[] + */ + private function normalizeHeaderValue(string $header, $value): array + { + if (is_array($value) && $value === []) { + throw new \InvalidArgumentException('Header value must be a non-empty array or string.'); + } + + if (!is_array($value)) { + return $this->trimAndValidateHeaderValues($header, [$value]); + } + + return $this->trimAndValidateHeaderValues($header, $value); + } + + /** + * Trims whitespace from the header values. + * + * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. + * + * header-field = field-name ":" OWS field-value OWS + * OWS = *( SP / HTAB ) + * + * @param mixed[] $values Header values + * + * @return string[] Trimmed header values + * + * @see https://datatracker.ietf.org/doc/html/rfc9110#section-5.5 + */ + private function trimAndValidateHeaderValues(string $header, array $values): array + { + return array_map(function ($value) use ($header): string { + if (!is_string($value)) { + throw new \InvalidArgumentException(sprintf( + 'Header value must be a string or array of strings but %s provided.', + \get_debug_type($value) + )); + } + + $trimmed = trim($value, " \t"); + $this->assertValue($header, $trimmed); + + return $trimmed; + }, array_values($values)); + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc9110#section-5.1 + */ + private function assertHeader(string $header): void + { + if (!Rfc9110::isToken($header)) { + throw new \InvalidArgumentException(sprintf('Invalid header name: %s', DiagnosticValue::escape($header))); + } + } + + private function assertProtocolVersion(string $version): void + { + if (!Rfc9112::isValidProtocolVersion($version)) { + throw new \InvalidArgumentException('Protocol version must be a valid HTTP version number.'); + } + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc9110#section-5.5 + * + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * VCHAR = %x21-7E + * obs-text = %x80-FF + * obs-fold = CRLF 1*( SP / HTAB ) + */ + private function assertValue(string $header, string $value): void + { + // The regular expression intentionally does not support the obs-fold + // production, because as per RFC 9112#5.2: + // + // A sender MUST NOT generate a message that includes line folding + // (i.e., that has any field-value that contains a match to the obs-fold + // rule) unless the message is intended for packaging within the + // message/http media type. + // + // Clients must not send a request with line folding and a server + // sending folded headers is likely very rare. Line folding is a fairly + // obscure feature of HTTP/1.1 and thus not accepting folding is not + // likely to break any legitimate use case. + if (!Rfc9110::isFieldValue($value)) { + $reason = strpbrk($value, "\r\n") !== false + ? 'must not contain CR or LF characters' + : 'contains an invalid control character'; + + throw new \InvalidArgumentException(sprintf('Header "%s" %s.', DiagnosticValue::escape($header), $reason)); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/MimeType.php b/vendor/guzzlehttp/psr7/src/MimeType.php new file mode 100644 index 0000000..0d17cd2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MimeType.php @@ -0,0 +1,1309 @@ + 'application/vnd.lotus-1-2-3', + '1km' => 'application/vnd.1000minds.decision-model+xml', + '210' => 'model/step', + '3dml' => 'text/vnd.in3d.3dml', + '3ds' => 'image/x-3ds', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gpp', + '3gpp' => 'video/3gpp', + '3mf' => 'model/3mf', + '7z' => 'application/x-7z-compressed', + '7zip' => 'application/x-7z-compressed', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/aac', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/pkix-attr-cert', + 'ac3' => 'audio/ac3', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'adts' => 'audio/aac', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'age' => 'application/vnd.age', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'aml' => 'application/automationml-aml+xml', + 'amlx' => 'application/automationml-amlx+zip', + 'amr' => 'audio/amr', + 'apk' => 'application/vnd.android.package-archive', + 'apng' => 'image/apng', + 'appcache' => 'text/cache-manifest', + 'appinstaller' => 'application/appinstaller', + 'application' => 'application/x-ms-application', + 'appx' => 'application/appx', + 'appxbundle' => 'application/appxbundle', + 'apr' => 'application/vnd.lotus-approach', + 'arc' => 'application/x-freearc', + 'arj' => 'application/x-arj', + 'asc' => 'application/pgp-keys', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomdeleted' => 'application/atomdeleted+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/basic', + 'avci' => 'image/avci', + 'avcs' => 'image/avcs', + 'avi' => 'video/x-msvideo', + 'avif' => 'image/avif', + 'aw' => 'application/applixware', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azv' => 'image/vnd.airzip.accelerator.azv', + 'azw' => 'application/vnd.amazon.ebook', + 'b16' => 'image/vnd.pco.b16', + 'bary' => 'model/vnd.bary', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bdo' => 'application/vnd.nato.bindingdataobject+xml', + 'bdoc' => 'application/bdoc', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'blb' => 'application/x-blorb', + 'blend' => 'application/x-blender', + 'blorb' => 'application/x-blorb', + 'bmi' => 'application/vnd.bmi', + 'bmml' => 'application/vnd.balsamiq.bmml+xml', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'bpmn' => 'application/octet-stream', + 'brush' => 'application/vnd.procreate.brush', + 'brushset' => 'application/vnd.procreate.brushset', + 'bsp' => 'model/vnd.valve.source.compiled-map', + 'btf' => 'image/prs.btif', + 'btif' => 'image/prs.btif', + 'buffer' => 'application/octet-stream', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'cab' => 'application/vnd.ms-cab-compressed', + 'caf' => 'audio/x-caf', + 'cap' => 'application/vnd.tcpdump.pcap', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cb7' => 'application/x-cbr', + 'cba' => 'application/x-cbr', + 'cbr' => 'application/x-cbr', + 'cbt' => 'application/x-cbr', + 'cbz' => 'application/x-cbr', + 'cc' => 'text/x-c', + 'cco' => 'application/x-cocoa', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdfx' => 'application/cdfx+xml', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfs' => 'application/x-cfs-compressed', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cjs' => 'application/node', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/java-vm', + 'cld' => 'model/vnd.cld', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'coffee' => 'text/coffeescript', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpl' => 'application/cpl+xml', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'crx' => 'application/x-chrome-extension', + 'cryptonote' => 'application/vnd.rig.cryptonote', + 'csh' => 'application/x-csh', + 'csl' => 'application/vnd.citationstyles.style+xml', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'csr' => 'application/octet-stream', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cwl' => 'application/cwl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dart' => 'application/vnd.dart', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dbf' => 'application/vnd.dbf', + 'dbk' => 'application/docbook+xml', + 'dcm' => 'application/dicom', + 'dcmp' => 'application/vnd.dcmp+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'ddf' => 'application/vnd.syncml.dmddf+xml', + 'dds' => 'image/vnd.ms-dds', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dgc' => 'application/x-dgc-compressed', + 'dib' => 'image/bmp', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'disposition-notification' => 'message/disposition-notification', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/octet-stream', + 'dmg' => 'application/x-apple-diskimage', + 'dmn' => 'application/octet-stream', + 'dmp' => 'application/vnd.tcpdump.pcap', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'dng' => 'image/x-adobe-dng', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.document.macroenabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dpx' => 'image/dpx', + 'dra' => 'audio/vnd.dra', + 'drle' => 'image/dicom-rle', + 'drm' => 'application/vnd.procreate.dream', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dst' => 'application/octet-stream', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvb' => 'video/vnd.dvb.file', + 'dvi' => 'application/x-dvi', + 'dwd' => 'application/atsc-dwd+xml', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ear' => 'application/java-archive', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'emf' => 'image/emf', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'emotionml' => 'application/emotionml+xml', + 'emz' => 'application/x-msmetafile', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es3' => 'application/vnd.eszigno3+xml', + 'esa' => 'application/vnd.osgi.subsystem', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'eva' => 'application/x-eva', + 'evy' => 'application/x-envoy', + 'exe' => 'application/octet-stream', + 'exi' => 'application/exi', + 'exp' => 'application/express', + 'exr' => 'image/aces', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/mp4', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'facti' => 'image/vnd.blockfact.facti', + 'fbs' => 'image/vnd.fastbidsheet', + 'fbx' => 'application/vnd.autodesk.fbx', + 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/fdf', + 'fdt' => 'application/fdt+xml', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'fits' => 'image/fits', + 'flac' => 'audio/x-flac', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'fo' => 'application/vnd.software602.filler.form+xml', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gam' => 'application/x-tads', + 'gbr' => 'application/rpki-ghostbusters', + 'gca' => 'application/x-gca-compressed', + 'gdl' => 'model/vnd.gdl', + 'gdoc' => 'application/vnd.google-apps.document', + 'gdraw' => 'application/vnd.google-apps.drawing', + 'ged' => 'text/vnd.familysearch.gedcom', + 'geo' => 'application/vnd.dynageo', + 'geojson' => 'application/geo+json', + 'gex' => 'application/vnd.geometry-explorer', + 'gform' => 'application/vnd.google-apps.form', + 'ggb' => 'application/vnd.geogebra.file', + 'ggs' => 'application/vnd.geogebra.slides', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'gjam' => 'application/vnd.google-apps.jam', + 'glb' => 'model/gltf-binary', + 'gltf' => 'model/gltf+json', + 'gmap' => 'application/vnd.google-apps.map', + 'gml' => 'application/gml+xml', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gph' => 'application/vnd.flographit', + 'gpx' => 'application/gpx+xml', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gramps' => 'application/x-gramps-xml', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gscript' => 'application/vnd.google-apps.script', + 'gsf' => 'application/x-font-ghostscript', + 'gsheet' => 'application/vnd.google-apps.spreadsheet', + 'gsite' => 'application/vnd.google-apps.site', + 'gslides' => 'application/vnd.google-apps.presentation', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxf' => 'application/gxf', + 'gxt' => 'application/vnd.geonext', + 'gz' => 'application/gzip', + 'gzip' => 'application/gzip', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hbs' => 'text/x-handlebars-template', + 'hdd' => 'application/x-virtualbox-hdd', + 'hdf' => 'application/x-hdf', + 'heic' => 'image/heic', + 'heics' => 'image/heic-sequence', + 'heif' => 'image/heif', + 'heifs' => 'image/heif-sequence', + 'hej2' => 'image/hej2k', + 'held' => 'application/atsc-held+xml', + 'hh' => 'text/x-c', + 'hjson' => 'application/hjson', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'htc' => 'text/x-component', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/vnd.microsoft.icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'img' => 'application/octet-stream', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'indd' => 'application/x-indesign', + 'ini' => 'text/plain', + 'ink' => 'application/inkml+xml', + 'inkml' => 'application/inkml+xml', + 'install' => 'application/x-install-instructions', + 'iota' => 'application/vnd.astraea-software.iota', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'ipynb' => 'application/x-ipynb+json', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/x-iso9660-image', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'its' => 'application/its+xml', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jade' => 'text/jade', + 'jaii' => 'image/jaii', + 'jais' => 'image/jais', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'jardiff' => 'application/x-java-archive-diff', + 'java' => 'text/x-java-source', + 'jfif' => 'image/jpeg', + 'jhc' => 'image/jphc', + 'jisp' => 'application/vnd.jisp', + 'jls' => 'image/jls', + 'jlt' => 'application/vnd.hp-jlyt', + 'jng' => 'image/x-jng', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jp2' => 'image/jp2', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpf' => 'image/jpx', + 'jpg' => 'image/jpeg', + 'jpg2' => 'image/jp2', + 'jpgm' => 'image/jpm', + 'jpgv' => 'video/jpeg', + 'jph' => 'image/jph', + 'jpm' => 'image/jpm', + 'jpx' => 'image/jpx', + 'js' => 'text/javascript', + 'json' => 'application/json', + 'json5' => 'application/json5', + 'jsonld' => 'application/ld+json', + 'jsonml' => 'application/jsonml+json', + 'jsx' => 'text/jsx', + 'jt' => 'model/jt', + 'jxl' => 'image/jxl', + 'jxr' => 'image/jxr', + 'jxra' => 'image/jxra', + 'jxrs' => 'image/jxrs', + 'jxs' => 'image/jxs', + 'jxsc' => 'image/jxsc', + 'jxsi' => 'image/jxsi', + 'jxss' => 'image/jxss', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kbl' => 'application/kbl+xml', + 'kdb' => 'application/octet-stream', + 'kdbx' => 'application/x-keepass2', + 'key' => 'application/vnd.apple.keynote', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'kpxx' => 'application/vnd.ds-keypoint', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktx2' => 'image/ktx2', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'less' => 'text/less', + 'lgr' => 'application/lgr+xml', + 'lha' => 'application/x-lzh-compressed', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'litcoffee' => 'text/coffeescript', + 'lnk' => 'application/x-ms-shortcut', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lottie' => 'application/zip+dotlottie', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lua' => 'text/x-lua', + 'luac' => 'application/x-lua-bytecode', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/x-lzh-compressed', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm1v' => 'video/mpeg', + 'm21' => 'application/mp21', + 'm2a' => 'audio/mpeg', + 'm2t' => 'video/mp2t', + 'm2ts' => 'video/mp2t', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'audio/x-mpegurl', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/mp4', + 'm4b' => 'audio/mp4', + 'm4p' => 'application/mp4', + 'm4s' => 'video/iso.segment', + 'm4u' => 'video/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'maei' => 'application/mmt-aei+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'manifest' => 'text/cache-manifest', + 'map' => 'application/json', + 'mar' => 'application/octet-stream', + 'markdown' => 'text/markdown', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'md' => 'text/markdown', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'mdx' => 'text/mdx', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'metalink' => 'application/metalink+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mft' => 'application/rpki-manifest', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mht' => 'message/rfc822', + 'mhtml' => 'message/rfc822', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mie' => 'application/x-mie', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mjs' => 'text/javascript', + 'mk3d' => 'video/matroska-3d', + 'mka' => 'audio/matroska', + 'mkd' => 'text/x-markdown', + 'mks' => 'video/x-matroska', + 'mkv' => 'video/matroska', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mml' => 'text/mathml', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mng' => 'video/x-mng', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp21' => 'application/mp21', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpd' => 'application/dash+xml', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpf' => 'application/media-policy-dataset+xml', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msg' => 'application/vnd.ms-outlook', + 'msh' => 'model/mesh', + 'msi' => 'application/octet-stream', + 'msix' => 'application/msix', + 'msixbundle' => 'application/msixbundle', + 'msl' => 'application/vnd.mobius.msl', + 'msm' => 'application/octet-stream', + 'msp' => 'application/octet-stream', + 'msty' => 'application/vnd.muvee.style', + 'mtl' => 'model/mtl', + 'mts' => 'video/mp2t', + 'mus' => 'application/vnd.musician', + 'musd' => 'application/mmt-usd+xml', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mvt' => 'application/vnd.mapbox-vector-tile', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxmf' => 'audio/mobile-xmf', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'ndjson' => 'application/x-ndjson', + 'nfo' => 'text/x-nfo', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nitf' => 'application/vnd.nitf', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nq' => 'application/n-quads', + 'nsc' => 'application/x-conference', + 'nsf' => 'application/vnd.lotus-notes', + 'nt' => 'application/n-triples', + 'ntf' => 'application/vnd.nitf', + 'numbers' => 'application/vnd.apple.numbers', + 'nzb' => 'application/x-nzb', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'obgx' => 'application/vnd.openblox.game+xml', + 'obj' => 'model/obj', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogex' => 'model/vnd.opengex', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'omdoc' => 'application/omdoc+xml', + 'one' => 'application/onenote', + 'onea' => 'application/onenote', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'opml' => 'text/x-opml', + 'oprc' => 'application/vnd.palm', + 'opus' => 'audio/ogg', + 'org' => 'application/vnd.lotus-organizer', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'osm' => 'application/vnd.openstreetmap.data+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'font/otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'ova' => 'application/x-virtualbox-ova', + 'ovf' => 'application/x-virtualbox-ovf', + 'owl' => 'application/rdf+xml', + 'oxps' => 'application/oxps', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p10' => 'application/pkcs10', + 'p12' => 'application/x-pkcs12', + 'p21' => 'model/step', + 'p7a' => 'application/x-pkcs7-signature', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7e' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'pac' => 'application/x-ns-proxy-autoconfig', + 'pages' => 'application/vnd.apple.pages', + 'parquet' => 'application/vnd.apache.parquet', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcap' => 'application/vnd.tcpdump.pcap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/vnd.zbrush.pcx', + 'pdb' => 'application/vnd.palm', + 'pde' => 'text/x-processing', + 'pdf' => 'application/pdf', + 'pem' => 'application/x-x509-user-cert', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp-encrypted', + 'phar' => 'application/octet-stream', + 'php' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'phtml' => 'application/x-httpd-php', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'pkpass' => 'application/vnd.apple.pkpass', + 'pl' => 'application/x-perl', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pm' => 'application/x-perl', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppa' => 'application/vnd.ms-powerpoint', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'model/prc', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'provx' => 'application/provenance+xml', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'image/vnd.adobe.photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'pti' => 'image/prs.pti', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pv' => 'application/octet-stream', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pxf' => 'application/octet-stream', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyo' => 'model/vnd.pytha.pyox', + 'pyox' => 'model/vnd.pytha.pyox', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'raml' => 'application/raml+yaml', + 'rapd' => 'application/route-apd+xml', + 'rar' => 'application/vnd.rar', + 'ras' => 'image/x-cmu-raster', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'relo' => 'application/p2p-overlay+xml', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'ris' => 'application/x-research-info-systems', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'application/vnd.rn-realmedia', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rmvb' => 'application/vnd.rn-realmedia-vbr', + 'rnc' => 'application/relax-ng-compact-syntax', + 'rng' => 'application/xml', + 'roa' => 'application/rpki-roa', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpm' => 'application/x-redhat-package-manager', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsa' => 'application/x-pkcs7', + 'rsat' => 'application/atsc-rsat+xml', + 'rsd' => 'application/rsd+xml', + 'rsheet' => 'application/urc-ressheet+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'text/rtf', + 'rtx' => 'text/richtext', + 'run' => 'application/x-makeself', + 'rusd' => 'application/route-usd+xml', + 'rv' => 'video/vnd.rn-realvideo', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sass' => 'text/x-sass', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scss' => 'text/x-scss', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'sea' => 'application/x-sea', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'senmlx' => 'application/senml+xml', + 'sensmlx' => 'application/sensml+xml', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sfv' => 'text/x-sfv', + 'sgi' => 'image/sgi', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shex' => 'text/shex', + 'shf' => 'application/shf+xml', + 'shtml' => 'text/html', + 'sid' => 'image/x-mrsid-image', + 'sieve' => 'application/sieve', + 'sig' => 'application/pgp-signature', + 'sil' => 'audio/silk', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'siv' => 'application/sieve', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slim' => 'text/slim', + 'slm' => 'text/slim', + 'sls' => 'application/route-s-tsid+xml', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil+xml', + 'smil' => 'application/smil+xml', + 'smv' => 'video/x-smv', + 'smzip' => 'application/vnd.stepmania.package', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spdx' => 'text/spdx', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'sql' => 'application/sql', + 'sqlite' => 'application/vnd.sqlite3', + 'sqlite3' => 'application/vnd.sqlite3', + 'src' => 'application/x-wais-source', + 'srt' => 'application/x-subrip', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'ssdl' => 'application/ssdl+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'sst' => 'application/octet-stream', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'step' => 'model/step', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'model/stl', + 'stp' => 'model/step', + 'stpnc' => 'model/step', + 'stpx' => 'model/step+xml', + 'stpxz' => 'model/step-xml+zip', + 'stpz' => 'model/step+zip', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'styl' => 'text/stylus', + 'stylus' => 'text/stylus', + 'sub' => 'image/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'swidtag' => 'application/swid+xml', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 'systemverify' => 'application/vnd.pp.systemverify+xml', + 't' => 'text/troff', + 't3' => 'application/x-t3vm-image', + 't38' => 'image/t38', + 'taglet' => 'application/vnd.mynfc', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tap' => 'image/vnd.tencent.tap', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'td' => 'application/urc-targetdesc+xml', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'tfx' => 'image/tiff-fx', + 'tga' => 'image/x-tga', + 'tgz' => 'application/gzip', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tk' => 'application/x-tcl', + 'tmo' => 'application/vnd.tmobile-livetv', + 'toml' => 'application/toml', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trig' => 'application/trig', + 'trm' => 'application/x-msterminal', + 'ts' => 'video/mp2t', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'font/collection', + 'ttf' => 'font/ttf', + 'ttl' => 'text/turtle', + 'ttml' => 'application/ttml+xml', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u32' => 'application/x-authorware-bin', + 'u3d' => 'model/u3d', + 'u8dsn' => 'message/global-delivery-status', + 'u8hdr' => 'message/global-headers', + 'u8mdn' => 'message/global-disposition-notification', + 'u8msg' => 'message/global', + 'ubj' => 'application/ubjson', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'ulx' => 'application/x-glulx', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uo' => 'application/vnd.uoml+xml', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'usda' => 'model/vnd.usda', + 'usdz' => 'model/vnd.usdz+zip', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvvz' => 'application/vnd.dece.zip', + 'uvx' => 'application/vnd.dece.unspecified', + 'uvz' => 'application/vnd.dece.zip', + 'vbox' => 'application/x-virtualbox-vbox', + 'vbox-extpack' => 'application/x-virtualbox-vbox-extpack', + 'vcard' => 'text/vcard', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vdi' => 'application/x-virtualbox-vdi', + 'vds' => 'model/vnd.sap.vds', + 'vdx' => 'application/vnd.ms-visio.viewer', + 'vec' => 'application/vec+xml', + 'vhd' => 'application/x-virtualbox-vhd', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vmdk' => 'application/x-virtualbox-vmdk', + 'vob' => 'video/x-ms-vob', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsdx' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtf' => 'image/vnd.valve.source.texture', + 'vtt' => 'text/vtt', + 'vtu' => 'model/vnd.vtu', + 'vtx' => 'application/vnd.visio', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wadl' => 'application/vnd.sun.wadl+xml', + 'war' => 'application/java-archive', + 'wasm' => 'application/wasm', + 'wav' => 'audio/wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wdp' => 'image/vnd.ms-photo', + 'weba' => 'audio/webm', + 'webapp' => 'application/x-web-app-manifest+json', + 'webm' => 'video/webm', + 'webmanifest' => 'application/manifest+json', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgsl' => 'text/wgsl', + 'wgt' => 'application/widget', + 'wif' => 'application/watcherinfo+xml', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'image/wmf', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-ms-wmz', + 'woff' => 'font/woff', + 'woff2' => 'font/woff2', + 'word' => 'application/msword', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsc' => 'message/vnd.wfa.wsc', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x32' => 'application/x-authorware-bin', + 'x3d' => 'model/x3d+xml', + 'x3db' => 'model/x3d+fastinfoset', + 'x3dbz' => 'model/x3d+binary', + 'x3dv' => 'model/x3d-vrml', + 'x3dvz' => 'model/x3d+vrml', + 'x3dz' => 'model/x3d+xml', + 'x_b' => 'model/vnd.parasolid.transmit.binary', + 'x_t' => 'model/vnd.parasolid.transmit.text', + 'xaml' => 'application/xaml+xml', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xav' => 'application/xcap-att+xml', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xca' => 'application/xcap-caps+xml', + 'xcs' => 'application/calendar+xml', + 'xdcf' => 'application/vnd.gov.sk.xmldatacontainer+xml', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xel' => 'application/xcap-el+xml', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtm' => 'application/vnd.pwg-xhtml-print+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xl' => 'application/vnd.ms-excel', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlf' => 'application/xliff+xml', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xm' => 'audio/xm', + 'xml' => 'application/xml', + 'xns' => 'application/xcap-ns+xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpl' => 'application/xproc+xml', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsd' => 'application/xml', + 'xsf' => 'application/prs.xsf+xml', + 'xsl' => 'application/xslt+xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'xz' => 'application/x-xz', + 'yaml' => 'text/yaml', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'yml' => 'text/yaml', + 'ymp' => 'text/x-suse-ymp', + 'z' => 'application/x-compress', + 'z1' => 'application/x-zmachine', + 'z2' => 'application/x-zmachine', + 'z3' => 'application/x-zmachine', + 'z4' => 'application/x-zmachine', + 'z5' => 'application/x-zmachine', + 'z6' => 'application/x-zmachine', + 'z7' => 'application/x-zmachine', + 'z8' => 'application/x-zmachine', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml', + 'zsh' => 'text/x-scriptzsh', + ]; + + /** + * Determines the MIME type of a file by looking at its extension. + * + * @see https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromFilename(string $filename): ?string + { + return self::fromExtension(pathinfo($filename, PATHINFO_EXTENSION)); + } + + /** + * Maps a file extension to a MIME type. + * + * @see https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromExtension(string $extension): ?string + { + return self::MIME_TYPES[Utils::asciiToLower($extension)] ?? null; + } +} diff --git a/vendor/guzzlehttp/psr7/src/MultipartStream.php b/vendor/guzzlehttp/psr7/src/MultipartStream.php new file mode 100644 index 0000000..cbf66ca --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MultipartStream.php @@ -0,0 +1,286 @@ +boundary = $boundary ?? bin2hex(random_bytes(20)); + $this->stream = $this->createStream($elements); + } + + public function getBoundary(): string + { + return $this->boundary; + } + + public function isWritable(): bool + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + * + * @param array $headers + */ + private function getHeaders(array $headers): string + { + $str = ''; + foreach ($headers as $key => $value) { + $key = (string) $key; + + self::validatePartHeaderName($key); + self::validatePartHeaderValue($key, $value); + + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n".rtrim($str, "\r\n")."\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements = []): StreamInterface + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + if (!is_array($element)) { + throw new \UnexpectedValueException('An array is expected'); + } + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element): void + { + foreach (['contents', 'name'] as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + if (!is_string($element['name']) && !is_int($element['name'])) { + throw new \InvalidArgumentException("The 'name' key must be a string or integer"); + } + + if (is_array($element['contents'])) { + if (array_key_exists('filename', $element) || array_key_exists('headers', $element)) { + throw new \InvalidArgumentException( + "The 'filename' and 'headers' options cannot be used when 'contents' is an array" + ); + } + + $this->addNestedElements($stream, $element['contents'], (string) $element['name']); + + return; + } + + $contents = $element['contents']; + if (is_scalar($contents) && !is_string($contents)) { + // Multipart field values are byte strings on the wire, so finite + // numeric and boolean field values are cast to string here rather + // than rejected by streamFor(). Non-finite floats cannot be + // represented and are rejected. + if (is_float($contents) && !is_finite($contents)) { + throw new \InvalidArgumentException('Cannot create a stream from a non-finite float.'); + } + + $contents = (string) $contents; + } + $element['contents'] = Utils::streamFor($contents); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if ($uri && \is_string($uri) && !str_starts_with($uri, 'php://') && !str_starts_with($uri, 'data://')) { + $element['filename'] = $uri; + } + } + + [$body, $headers] = $this->createElement( + (string) $element['name'], + $element['contents'], + $element['filename'] ?? null, + $element['headers'] ?? [] + ); + + $stream->addStream(Utils::streamFor($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(Utils::streamFor("\r\n")); + } + + /** + * Recursively expand array contents into multiple form fields. + * + * @param array $contents + */ + private function addNestedElements(AppendStream $stream, array $contents, string $root): void + { + foreach ($contents as $key => $value) { + $fieldName = $root === '' ? sprintf('[%s]', (string) $key) : sprintf('%s[%s]', $root, (string) $key); + + if (is_array($value)) { + $this->addNestedElements($stream, $value, $fieldName); + } else { + $this->addElement($stream, ['name' => $fieldName, 'contents' => $value]); + } + } + } + + /** + * @param array $headers + * + * @return array{0: StreamInterface, 1: array} + */ + private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array + { + $headers = self::normalizePartHeaders($headers); + + // Set a default content-disposition header if one was no provided + $disposition = self::getHeader($headers, 'content-disposition'); + if (!$disposition) { + $escapedName = self::escapeContentDispositionParameter($name); + $headers['Content-Disposition'] = ($filename === '0' || $filename) + ? sprintf( + 'form-data; name="%s"; filename="%s"', + $escapedName, + self::escapeContentDispositionParameter(basename($filename)) + ) + : sprintf('form-data; name="%s"', $escapedName); + } + + // Set a default Content-Type if one was not supplied + $type = self::getHeader($headers, 'content-type'); + if (!$type && ($filename === '0' || $filename)) { + $headers['Content-Type'] = MimeType::fromFilename($filename) ?? 'application/octet-stream'; + } + + return [$stream, $headers]; + } + + /** + * @param array $headers + */ + private static function getHeader(array $headers, string $key): ?string + { + $lowercaseHeader = Utils::asciiToLower($key); + foreach ($headers as $k => $v) { + if (Utils::asciiToLower((string) $k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } + + private static function validateBoundary(string $boundary): void + { + $length = strlen($boundary); + + if ($length < 1 || $length > 70 || $boundary[$length - 1] === ' ') { + throw new \InvalidArgumentException('Invalid multipart boundary.'); + } + + if (strspn($boundary, self::BOUNDARY_CHARS) !== $length) { + throw new \InvalidArgumentException('Invalid multipart boundary.'); + } + } + + /** + * @param array $headers + * + * @return array + */ + private static function normalizePartHeaders(array $headers): array + { + $normalized = []; + + foreach ($headers as $key => $value) { + $key = (string) $key; + + self::validatePartHeaderName($key); + + if (!is_string($value)) { + throw new \InvalidArgumentException('Multipart part header value must be a string.'); + } + + self::validatePartHeaderValue($key, $value); + + $normalized[$key] = $value; + } + + return $normalized; + } + + private static function validatePartHeaderName(string $name): void + { + if (!Rfc9110::isToken($name)) { + throw new \InvalidArgumentException(sprintf('Invalid multipart part header name: %s', DiagnosticValue::escape($name))); + } + } + + private static function validatePartHeaderValue(string $name, string $value): void + { + if (!Rfc9110::isFieldValue($value)) { + $reason = strpbrk($value, "\r\n") !== false + ? 'must not contain CR or LF characters' + : 'contains an invalid control character'; + + throw new \InvalidArgumentException(sprintf('Multipart part header "%s" %s.', DiagnosticValue::escape($name), $reason)); + } + } + + private static function escapeContentDispositionParameter(string $value): string + { + // Match WHATWG browser multipart/form-data behavior: escape CR, LF, and DQUOTE only. + return str_replace(["\r", "\n", '"'], ['%0D', '%0A', '%22'], $value); + } +} diff --git a/vendor/guzzlehttp/psr7/src/NoSeekStream.php b/vendor/guzzlehttp/psr7/src/NoSeekStream.php new file mode 100644 index 0000000..1611e32 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/NoSeekStream.php @@ -0,0 +1,28 @@ +source = $source; + $this->size = Integers::assertOptionalNonNegativeSize($options['size'] ?? null, 'Stream size'); + $this->metadata = $options['metadata'] ?? []; + $this->buffer = new BufferStream(); + } + + public function __unserialize(array $data): void + { + $this->source = null; + $this->size = null; + $this->tellPos = 0; + $this->metadata = []; + $this->buffer = new BufferStream(); + + throw new \LogicException(static::class.' should never be unserialized'); + } + + public function __toString(): string + { + return Utils::copyToString($this); + } + + public function close(): void + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = 0; + $this->source = null; + $this->buffer->close(); + + return null; + } + + public function getSize(): ?int + { + return $this->size; + } + + public function tell(): int + { + return $this->tellPos; + } + + public function eof(): bool + { + return $this->source === null; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable(): bool + { + return false; + } + + public function write(string $string): int + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable(): bool + { + return true; + } + + public function read(int $length): string + { + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + $bufferLength = $this->buffer->getSize() ?? 0; + + if ($length > $bufferLength) { + $this->pump($length - $bufferLength); + } + + $data = $this->buffer->read($length); + $this->tellPos = Integers::add($this->tellPos, strlen($data)); + + return $data; + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * @return mixed + */ + public function getMetadata(?string $key = null) + { + if ($key === null) { + return $this->metadata; + } + + return $this->metadata[$key] ?? null; + } + + private function pump(int $length): void + { + if ($this->source !== null) { + do { + /** @var string|false|null $data */ + $data = ($this->source)($length); + if ($data === false || $data === null) { + $this->source = null; + + return; + } + + if ($data === '') { + throw new \RuntimeException('PumpStream source returned an empty string'); + } + + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/Query.php b/vendor/guzzlehttp/psr7/src/Query.php new file mode 100644 index 0000000..c54c669 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Query.php @@ -0,0 +1,156 @@ + '1', 'foo[b]' => '2']`. + * + * @param string $str Query string to parse + * @param int|bool $urlEncoding How the query string is encoded + */ + public static function parse(string $str, $urlEncoding = true): array + { + $result = []; + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function (string $value): string { + return \rawurldecode(str_replace('+', ' ', $value)); + }; + } elseif ($urlEncoding === PHP_QUERY_RFC3986) { + $decoder = static function (string $value): string { + return \rawurldecode($value); + }; + } elseif ($urlEncoding === PHP_QUERY_RFC1738) { + $decoder = static function (string $value): string { + return \urldecode($value); + }; + } else { + $decoder = function (string $str): string { + return $str; + }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!array_key_exists($key, $result)) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = [$result[$key]]; + } + $result[$key][] = $value; + } + } + + return $result; + } + + /** + * Build a query string from an array of key-value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered, unlike `http_build_query()`. + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, + * PHP_QUERY_RFC3986 to encode using + * RFC3986, or PHP_QUERY_RFC1738 to + * encode using RFC1738. + * @param bool $treatBoolsAsInts Set to true to encode as 0/1, and + * false as false/true. + */ + public static function build(array $params, $encoding = PHP_QUERY_RFC3986, bool $treatBoolsAsInts = true): string + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function (string $str): string { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = static function (string $value): string { + return \rawurlencode($value); + }; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = static function (string $value): string { + return \urlencode($value); + }; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder((string) $k); + if (!is_array($v)) { + $qs .= $k; + $v = self::normalizeValue($v, $treatBoolsAsInts); + if ($v !== null) { + $qs .= '='.$encoder($v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + $vv = self::normalizeValue($vv, $treatBoolsAsInts); + if ($vv !== null) { + $qs .= '='.$encoder($vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; + } + + /** + * @param mixed $value + */ + private static function normalizeValue($value, bool $treatBoolsAsInts): ?string + { + if ($value === null) { + return null; + } + + if (is_bool($value)) { + return $treatBoolsAsInts ? (string) (int) $value : ($value ? 'true' : 'false'); + } + + if (is_float($value) && !is_finite($value)) { + throw new \InvalidArgumentException('Query string values must be finite; non-finite floats are not supported.'); + } + + if (is_scalar($value)) { + return (string) $value; + } + + if (is_object($value) && method_exists($value, '__toString')) { + return $value->__toString(); + } + + throw new \InvalidArgumentException('Query string values must be scalar, null, or stringable objects'); + } +} diff --git a/vendor/guzzlehttp/psr7/src/ReadFailureCapturingStream.php b/vendor/guzzlehttp/psr7/src/ReadFailureCapturingStream.php new file mode 100644 index 0000000..b3fe539 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/ReadFailureCapturingStream.php @@ -0,0 +1,61 @@ +capturing) { + return $this->stream->read($length); + } + + try { + return $this->stream->read($length); + } catch (\Exception $e) { + $this->readFailure = $e; + + return ''; + } + } + + public function stopCapturing(): void + { + $this->capturing = false; + $this->readFailure = null; + } + + public function hasReadFailure(): bool + { + return $this->readFailure !== null; + } + + public function takeReadFailure(): ?\Exception + { + $failure = $this->readFailure; + $this->readFailure = null; + + return $failure; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Request.php b/vendor/guzzlehttp/psr7/src/Request.php new file mode 100644 index 0000000..7f4e490 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Request.php @@ -0,0 +1,215 @@ +assertMethod($method); + $this->assertProtocolVersion($version); + + if (!$uri instanceof UriInterface) { + $uri = new Uri($uri); + } + self::getRequestTargetFromUri($uri); + + $this->method = $method; + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $version; + + if (!isset($this->headerNames['host'])) { + $this->updateHostFromUri(); + } + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + } + + public function getRequestTarget(): string + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + return self::getRequestTargetFromUri($this->uri); + } + + public function withRequestTarget(string $requestTarget): RequestInterface + { + self::assertRequestTarget($requestTarget); + + $new = clone $this; + $new->requestTarget = $requestTarget; + + return $new; + } + + public function getMethod(): string + { + return $this->method; + } + + public function withMethod(string $method): RequestInterface + { + $this->assertMethod($method); + $new = clone $this; + $new->method = $method; + + return $new; + } + + public function getUri(): UriInterface + { + return $this->uri; + } + + public function withUri(UriInterface $uri, bool $preserveHost = false): RequestInterface + { + $sameUri = $uri === $this->uri; + + if (!$sameUri && $this->requestTarget === null) { + self::getRequestTargetFromUri($uri); + } + + $currentHost = $this->getHeaderLine('Host'); + $host = null; + + if (!$preserveHost || $currentHost === '') { + $host = $this->getHostFromUri($uri); + } + + if ($sameUri && ($host === null || $currentHost === $host)) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if ($host !== null) { + $new->setHostHeader($host); + } + + return $new; + } + + private function updateHostFromUri(): void + { + $host = $this->getHostFromUri($this->uri); + + if ($host === null) { + return; + } + + $this->setHostHeader($host); + } + + private function getHostFromUri(UriInterface $uri): ?string + { + $host = $uri->getHost(); + + if ($host === '') { + return null; + } + + Uri::assertValidHost($host); + + // A Uri has already raised the deprecation for its own host. + if (!$uri instanceof Uri) { + Uri::deprecateNonAsciiHost($host); + } + + if (($port = $uri->getPort()) !== null) { + $host .= ':'.$port; + } + + $this->assertValue('Host', $host); + + return $host; + } + + private function setHostHeader(string $host): void + { + if (isset($this->headerNames['host'])) { + $header = $this->headerNames['host']; + } else { + $header = 'Host'; + $this->headerNames['host'] = 'Host'; + } + // Ensure Host is the first header. + // See: https://datatracker.ietf.org/doc/html/rfc9110#section-7.2 + $this->headers = [$header => [$host]] + $this->headers; + } + + private function assertMethod(string $method): void + { + if (!Rfc9110::isToken($method)) { + throw new InvalidArgumentException('Method must be a valid HTTP token.'); + } + } + + private static function getRequestTargetFromUri(UriInterface $uri): string + { + $target = self::normalizePathForOriginForm($uri->getPath()); + if ($target === '') { + $target = '/'; + } + if ($uri->getQuery() != '') { + $target .= '?'.$uri->getQuery(); + } + + self::assertRequestTarget($target); + + return $target; + } + + private static function assertRequestTarget(string $requestTarget): void + { + if (!Rfc9112::isValidRequestTarget($requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot be empty or contain whitespace or control characters' + ); + } + } + + private static function normalizePathForOriginForm(string $path): string + { + if (str_starts_with($path, '//')) { + return '/'.ltrim($path, '/'); + } + + return $path; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Response.php b/vendor/guzzlehttp/psr7/src/Response.php new file mode 100644 index 0000000..a4e8ff6 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Response.php @@ -0,0 +1,159 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable For Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 510 => 'Not Extended', + 511 => 'Network Authentication Required', + ]; + + private string $reasonPhrase; + + private int $statusCode; + + /** + * @param int $status Status code + * @param (string|string[])[] $headers Response headers + * @param string|resource|StreamInterface|null $body Response body + * @param string $version Protocol version + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) + */ + public function __construct( + int $status = 200, + array $headers = [], + $body = null, + string $version = '1.1', + ?string $reason = null + ) { + $this->assertStatusCodeRange($status); + $this->assertProtocolVersion($version); + + $this->statusCode = $status; + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + + $this->setHeaders($headers); + if ($reason == '' && isset(self::PHRASES[$this->statusCode])) { + $reasonPhrase = self::PHRASES[$this->statusCode]; + } else { + $reasonPhrase = (string) $reason; + } + + $this->assertReasonPhrase($reasonPhrase); + $this->reasonPhrase = $reasonPhrase; + + $this->protocol = $version; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getReasonPhrase(): string + { + return $this->reasonPhrase; + } + + public function withStatus(int $code, string $reasonPhrase = ''): ResponseInterface + { + $this->assertStatusCodeRange($code); + + $new = clone $this; + $new->statusCode = $code; + if ($reasonPhrase === '' && isset(self::PHRASES[$new->statusCode])) { + $reasonPhrase = self::PHRASES[$new->statusCode]; + } + $this->assertReasonPhrase($reasonPhrase); + $new->reasonPhrase = $reasonPhrase; + + return $new; + } + + private function assertStatusCodeRange(int $statusCode): void + { + if ($statusCode < 100 || $statusCode >= 600) { + throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); + } + } + + private function assertReasonPhrase(string $reasonPhrase): void + { + if (!Rfc9112::isValidReasonPhrase($reasonPhrase)) { + throw new \InvalidArgumentException('Reason phrase must not contain invalid control characters.'); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/Rfc3986.php b/vendor/guzzlehttp/psr7/src/Rfc3986.php new file mode 100644 index 0000000..d6cc92a --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Rfc3986.php @@ -0,0 +1,361 @@ + $word) { + if ($word !== 0) { + $start = -1; + continue; + } + if ($start === -1) { + $start = $i; + } + if ($i - $start + 1 > $bestLen) { + $bestStart = $start; + $bestLen = $i - $start + 1; + } + } + if ($bestLen < 2) { + $bestLen = 0; + } + + // RFC 5952 section 5: embedded IPv4 notation for IPv4-mapped + // (::ffff:0:0/96) and IPv4-compatible (::/96) addresses, the same + // condition BIND-derived inet_ntop() and curl use. bestStart must be + // zero: a five or six field zero run elsewhere is not an IPv4 prefix. + $mixed = $bestStart === 0 + && ($bestLen === 6 || ($bestLen === 5 && $words[5] === 0xFFFF)); + + $groups = []; + for ($i = 0, $n = $mixed ? 6 : 8; $i < $n; ++$i) { + $groups[] = dechex($words[$i]); + } + if ($mixed) { + $groups[] = sprintf( + '%d.%d.%d.%d', + $words[6] >> 8, + $words[6] & 0xFF, + $words[7] >> 8, + $words[7] & 0xFF + ); + } + + if ($bestLen === 0) { + return implode(':', $groups); + } + + return implode(':', array_slice($groups, 0, $bestStart)).'::'.implode(':', array_slice($groups, $bestStart + $bestLen)); + } + + private static function hasValidHostPercentEncoding(string $host): bool + { + // Mirror of the raw reg-name policy above for percent-encoded octets: + // reject malformed sequences (RFC 3986 requires "%" HEXDIG HEXDIG) and + // octets that decode to bytes the raw grammar rejects - C0 controls, + // SP, DEL, the delimiters / ? # @ \ [ ], the port colon, and % itself. + // Octets decoding to any other byte (unreserved, sub-delims, and + // non-ASCII UTF-8 data) remain accepted. + $invalidEncoding = preg_match( + '/%(?!'.self::HEX_OCTET.')|%(?:[01][0-9A-Fa-f]|2[035F]|3[AF]|40|5[BCD]|7F)/i', + $host + ); + + return $invalidEncoding === 0; + } + + private static function isValidIpLiteralHost(string $host): bool + { + if (!str_starts_with($host, '[') || !str_ends_with($host, ']')) { + return false; + } + + $address = substr($host, 1, -1); + if (\filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6) !== false) { + return true; + } + + // RFC 6874 IPv6 zone identifiers are intentionally not supported here. + // Bracketed hosts are validated as IPv6 or IPvFuture only. + return preg_match('/^v[0-9a-f]+\.['.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.':]+$/iD', $address) === 1; + } + + /** + * Parses a textual IPv6 address into its eight 16-bit words, or null + * when the text is not a structurally valid address. + * + * The grammar enforced here is the RFC 3986 `IPv6address` rule: one to four + * hexadecimal digits per field, at most one `::` eliding one or more zero + * fields, and an optional dotted-decimal tail of four octets (0-255, no + * leading zeros) as the final 32 bits. FILTER_VALIDATE_IP accepts exactly + * this grammar, so the filter guard in tryCanonicalizeIpv6() and this + * parser always agree and the null paths here can only fail closed. + * + * @return list|null + */ + private static function parseIpv6Words(string $address): ?array + { + // A dotted-decimal tail is only valid as the final 32 bits, after the + // final colon. Rewrite it into its two hexadecimal fields so the + // remainder of the parse handles hexadecimal fields only. + $dot = strpos($address, '.'); + if ($dot !== false) { + $colon = strrpos($address, ':'); + if ($colon === false || $colon > $dot) { + return null; + } + $octets = explode('.', substr($address, $colon + 1)); + if (count($octets) !== 4) { + return null; + } + $bytes = []; + foreach ($octets as $octet) { + if ($octet === '' || strlen($octet) > 3 || !ctype_digit($octet)) { + return null; + } + if ($octet[0] === '0' && $octet !== '0') { + return null; + } + $byte = (int) $octet; + if ($byte > 255) { + return null; + } + $bytes[] = $byte; + } + $address = substr($address, 0, $colon + 1) + .dechex(($bytes[0] << 8) | $bytes[1]) + .':' + .dechex(($bytes[2] << 8) | $bytes[3]); + } + + $halves = explode('::', $address); + if (count($halves) > 2) { + return null; + } + + $head = self::parseHexFields($halves[0]); + if ($head === null) { + return null; + } + + if (count($halves) === 1) { + return count($head) === 8 ? $head : null; + } + + $tail = self::parseHexFields($halves[1]); + if ($tail === null) { + return null; + } + + // The "::" must elide at least one zero field. + $elided = 8 - count($head) - count($tail); + if ($elided < 1) { + return null; + } + + return array_merge($head, array_fill(0, $elided, 0), $tail); + } + + /** + * Parses a colon-separated run of 16-bit hexadecimal fields, or null + * when a field is empty, longer than four digits, or not hexadecimal. + * + * @return list|null + */ + private static function parseHexFields(string $fields): ?array + { + if ($fields === '') { + return []; + } + + $words = []; + foreach (explode(':', $fields) as $field) { + if ($field === '' || strlen($field) > 4 || !ctype_xdigit($field)) { + return null; + } + $words[] = intval($field, 16); + } + + return $words; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Rfc9110.php b/vendor/guzzlehttp/psr7/src/Rfc9110.php new file mode 100644 index 0000000..c93b1b2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Rfc9110.php @@ -0,0 +1,41 @@ +@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m"; + public const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; + + public static function isValidProtocolVersion(string $version): bool + { + return preg_match('/^'.self::PROTOCOL_VERSION_PATTERN.'$/D', $version) === 1; + } + + public static function isValidRequestTarget(string $target): bool + { + return preg_match('/^'.self::REQUEST_TARGET_PATTERN.'$/D', $target) === 1; + } + + public static function isValidReasonPhrase(string $reasonPhrase): bool + { + return Rfc9110::isFieldValue($reasonPhrase); + } + + /** + * @return array{0: string, 1: int|null}|null + */ + public static function parseHostHeader(string $authority): ?array + { + if ($authority === '') { + return null; + } + + $host = $authority; + $port = null; + + if (str_starts_with($authority, '[')) { + $closingBracket = strpos($authority, ']'); + if ($closingBracket === false) { + return null; + } + + $host = substr($authority, 0, $closingBracket + 1); + $remainder = substr($authority, $closingBracket + 1); + if ($remainder !== '') { + if (!str_starts_with($remainder, ':')) { + return null; + } + + $port = self::parsePort(substr($remainder, 1)); + if ($port === null) { + return null; + } + } + } elseif (false !== ($colon = strpos($authority, ':'))) { + $host = substr($authority, 0, $colon); + $port = self::parsePort(substr($authority, $colon + 1)); + if ($port === null) { + return null; + } + } + + if ($host === '' || !Rfc3986::isValidHost($host)) { + return null; + } + + return [$host, $port]; + } + + public static function isAbsoluteFormRequestTarget(string $target): bool + { + return preg_match('/^[A-Za-z][A-Za-z0-9+.-]*:\/\//D', $target) === 1; + } + + public static function isAsteriskFormRequestTarget(string $method, string $target): bool + { + return $method === 'OPTIONS' && $target === '*'; + } + + public static function isConnectAuthorityFormRequestTarget(string $method, string $target): bool + { + return $method === 'CONNECT' && strpbrk($target, '/?#') === false; + } + + public static function parsePort(string $port): ?int + { + if (!Rfc3986::isValidPort($port)) { + return null; + } + + // A zero port is valid per RFC 3986 but meaningless for an HTTP + // authority, so reject it on top of the generic syntax check. + $parsed = (int) ltrim($port, '0'); + + return $parsed === 0 ? null : $parsed; + } +} diff --git a/vendor/guzzlehttp/psr7/src/ServerRequest.php b/vendor/guzzlehttp/psr7/src/ServerRequest.php new file mode 100644 index 0000000..adf1762 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/ServerRequest.php @@ -0,0 +1,234 @@ +serverParams = $serverParams; + + parent::__construct($method, $uri, $headers, $body, $version); + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files An array which respect $_FILES structure + * + * @throws InvalidArgumentException for unrecognized values + */ + public static function normalizeFiles(array $files): array + { + return UploadedFileNormalizer::normalize($files); + } + + /** + * Return a ServerRequest populated with superglobals: + * $_GET + * $_POST + * $_COOKIE + * $_FILES + * $_SERVER + */ + public static function fromGlobals(): ServerRequestInterface + { + return ServerRequestGlobalsFactory::fromArrays( + $_SERVER, + $_GET, + $_POST, + $_COOKIE, + $_FILES, + static function () { + if (!\function_exists('apache_request_headers')) { + return false; + } + + return \apache_request_headers(); + } + ); + } + + /** + * Get a Uri populated with values from $_SERVER. + */ + public static function getUriFromGlobals(): UriInterface + { + return ServerRequestGlobalsFactory::getUriFromServerParams($_SERVER); + } + + public function getServerParams(): array + { + return $this->serverParams; + } + + public function getUploadedFiles(): array + { + return $this->uploadedFiles; + } + + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface + { + $stack = [$uploadedFiles]; + + for ($i = 0; $i < \count($stack); ++$i) { + foreach ($stack[$i] as $uploadedFile) { + if ($uploadedFile instanceof UploadedFileInterface) { + continue; + } + + if (\is_array($uploadedFile)) { + $stack[] = $uploadedFile; + continue; + } + + throw new InvalidArgumentException(sprintf( + 'Invalid uploaded file tree; expected UploadedFileInterface instances but %s provided.', + \get_debug_type($uploadedFile) + )); + } + } + + $new = clone $this; + $new->uploadedFiles = $uploadedFiles; + + return $new; + } + + public function getCookieParams(): array + { + return $this->cookieParams; + } + + public function withCookieParams( + #[\SensitiveParameter] + array $cookies + ): ServerRequestInterface { + $new = clone $this; + $new->cookieParams = $cookies; + + return $new; + } + + public function getQueryParams(): array + { + return $this->queryParams; + } + + public function withQueryParams(array $query): ServerRequestInterface + { + $new = clone $this; + $new->queryParams = $query; + + return $new; + } + + /** + * @return array|object|null + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + public function withParsedBody($data): ServerRequestInterface + { + if ($data !== null && !\is_array($data) && !\is_object($data)) { + throw new InvalidArgumentException('Parsed body must be an array, object, or null.'); + } + + $new = clone $this; + $new->parsedBody = $data; + + return $new; + } + + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * @return mixed + */ + public function getAttribute(string $name, $default = null) + { + if (false === array_key_exists($name, $this->attributes)) { + return $default; + } + + return $this->attributes[$name]; + } + + public function withAttribute(string $name, $value): ServerRequestInterface + { + $new = clone $this; + $new->attributes[$name] = $value; + + return $new; + } + + public function withoutAttribute(string $name): ServerRequestInterface + { + if (false === array_key_exists($name, $this->attributes)) { + return $this; + } + + $new = clone $this; + unset($new->attributes[$name]); + + return $new; + } +} diff --git a/vendor/guzzlehttp/psr7/src/ServerRequestGlobalsFactory.php b/vendor/guzzlehttp/psr7/src/ServerRequestGlobalsFactory.php new file mode 100644 index 0000000..e88cb09 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/ServerRequestGlobalsFactory.php @@ -0,0 +1,523 @@ + $server Typically the $_SERVER superglobal + * @param array $query Typically the $_GET superglobal + * @param array $post Typically the $_POST superglobal + * @param array $cookies Typically the $_COOKIE superglobal + * @param array $files Typically the $_FILES superglobal + * @param (callable(): mixed)|null $headerProvider + */ + public static function fromArrays( + #[\SensitiveParameter] + array $server, + array $query, + array $post, + #[\SensitiveParameter] + array $cookies, + array $files, + ?callable $headerProvider = null + ): ServerRequestInterface { + $method = self::getRequestMethodFromServer($server); + $headers = self::removeInvalidHostHeader(self::getAllHeaders($server, $headerProvider)); + [$uri, $requestTarget] = self::getUriAndRequestTargetFromServer($server, $method); + $body = new CachingStream(new LazyOpenStream('php://input', 'r+')); + + $serverRequest = new ServerRequest($method, $uri, $headers, $body, self::getProtocolFromServer($server), $server); + if ($requestTarget !== null) { + /** @var ServerRequestInterface $serverRequest */ + $serverRequest = $serverRequest->withRequestTarget($requestTarget); + } + + return $serverRequest + ->withCookieParams($cookies) + ->withQueryParams($query) + ->withParsedBody($post) + ->withUploadedFiles(UploadedFileNormalizer::normalize($files)); + } + + /** + * @param array $server Typically the $_SERVER superglobal + */ + public static function getUriFromServerParams( + #[\SensitiveParameter] + array $server + ): UriInterface { + $method = self::getRequestMethodFromServer($server); + + return self::getUriAndRequestTargetFromServer($server, $method)[0]; + } + + /** + * @param array $server + * @param (callable(): mixed)|null $headerProvider + * + * @return array + */ + private static function getAllHeaders( + #[\SensitiveParameter] + array $server, + ?callable $headerProvider + ): array { + $headers = $headerProvider !== null ? $headerProvider() : false; + + if (!is_array($headers)) { + $headers = self::getHeadersFromServer($server); + } + + return self::normalizeHeaderValues($headers); + } + + /** + * @param array $headers + * + * @return array + */ + private static function normalizeHeaderValues( + #[\SensitiveParameter] + array $headers + ): array { + $normalized = []; + + foreach ($headers as $name => $value) { + if (is_scalar($value) || (is_object($value) && method_exists($value, '__toString'))) { + $normalized[$name] = (string) $value; + } + } + + return $normalized; + } + + /** + * @param array $server Typically the $_SERVER superglobal + * + * @return array + */ + private static function getHeadersFromServer(array $server): array + { + $headers = []; + + $copyServer = [ + 'CONTENT_TYPE' => 'Content-Type', + 'CONTENT_LENGTH' => 'Content-Length', + 'CONTENT_MD5' => 'Content-Md5', + ]; + + foreach ($server as $key => $value) { + if (!is_string($key) || !is_string($value)) { + continue; + } + + if (str_starts_with($key, 'HTTP_')) { + $header = substr($key, 5); + + if (isset($copyServer[$header], $server[$header]) && is_string($server[$header])) { + continue; + } + + $parts = explode(' ', Utils::asciiToLower(str_replace('_', ' ', $header))); + foreach ($parts as $i => $part) { + $parts[$i] = Utils::asciiUcFirst($part); + } + $header = implode('-', $parts); + $headers[$header] = $value; + + continue; + } + + if (isset($copyServer[$key])) { + $headers[$copyServer[$key]] = $value; + } + } + + if (!isset($headers['Authorization'])) { + if (isset($server['REDIRECT_HTTP_AUTHORIZATION']) && is_string($server['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $server['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($server['PHP_AUTH_USER']) && is_string($server['PHP_AUTH_USER'])) { + $password = isset($server['PHP_AUTH_PW']) && is_string($server['PHP_AUTH_PW']) + ? $server['PHP_AUTH_PW'] + : ''; + + $headers['Authorization'] = 'Basic '.base64_encode($server['PHP_AUTH_USER'].':'.$password); + } elseif (isset($server['PHP_AUTH_DIGEST']) && is_string($server['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $server['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + + /** + * @param array $headers + * + * @return array + */ + private static function removeInvalidHostHeader(array $headers): array + { + foreach ($headers as $name => $value) { + if (Utils::asciiToLower((string) $name) !== 'host') { + continue; + } + + [$host] = self::extractHostAndPortFromAuthority($value); + if ($host === null) { + unset($headers[$name]); + } + } + + return $headers; + } + + /** + * @param array $server + */ + private static function getServerParam(array $server, string $key): ?string + { + return isset($server[$key]) && is_string($server[$key]) ? $server[$key] : null; + } + + /** + * @param array $server + */ + private static function getRequestMethodFromServer(array $server): string + { + return Utils::asciiToUpper(self::getServerParam($server, 'REQUEST_METHOD') ?? 'GET'); + } + + /** + * @param array $server + */ + private static function getProtocolFromServer(array $server): string + { + $serverProtocol = self::getServerParam($server, 'SERVER_PROTOCOL'); + if ($serverProtocol === null) { + return '1.1'; + } + + return str_starts_with($serverProtocol, 'HTTP/') ? substr($serverProtocol, 5) : $serverProtocol; + } + + /** + * @return array{0: string|null, 1: int|null} + */ + private static function extractHostAndPortFromAuthority(string $authority): array + { + return Rfc9112::parseHostHeader($authority) ?? [null, null]; + } + + private static function parseServerPort(string $port): int + { + $parsed = Rfc9112::parsePort($port); + if ($parsed === null) { + throw new InvalidArgumentException('Invalid SERVER_PORT; expected an integer between 1 and 65535.'); + } + + return $parsed; + } + + private static function withHostFromServer(UriInterface $uri, ?string $host): ?UriInterface + { + if ($host === null) { + return null; + } + + try { + return self::withoutHostDeprecation(static function () use ($uri, $host): UriInterface { + return $uri->withHost($host); + }); + } catch (InvalidArgumentException $e) { + return null; + } + } + + /** + * @template T + * + * @param callable(): T $operation + * + * @return T + */ + private static function withoutHostDeprecation(callable $operation) + { + // A peer must not be able to raise the host deprecation. + return (new ErrorScope(\E_USER_DEPRECATED))->run($operation); + } + + /** + * @param array $server + */ + private static function getUriWithSchemeFromServer(array $server): UriInterface + { + $uri = new Uri(''); + + $https = self::getServerParam($server, 'HTTPS'); + + return $uri->withScheme(!empty($https) && $https !== 'off' ? 'https' : 'http'); + } + + /** + * @param array $server + */ + private static function getAuthorityUriFromServer( + #[\SensitiveParameter] + array $server + ): UriInterface { + $uri = self::getUriWithSchemeFromServer($server); + + $hasPort = false; + $hasHost = false; + $authority = self::getServerParam($server, 'HTTP_HOST'); + if ($authority !== null) { + [$host, $port] = self::extractHostAndPortFromAuthority($authority); + if ($host !== null) { + $hostUri = self::withHostFromServer($uri, $host); + if ($hostUri !== null) { + $uri = $hostUri; + $hasHost = true; + + if ($port !== null) { + $hasPort = true; + $uri = $uri->withPort($port); + } + } + } + } + + foreach (['SERVER_NAME', 'SERVER_ADDR'] as $serverParam) { + if ($hasHost) { + continue; + } + + $hostUri = self::withHostFromServer($uri, self::getServerParam($server, $serverParam)); + if ($hostUri !== null) { + $uri = $hostUri; + $hasHost = true; + } + } + + $serverPort = self::getServerParam($server, 'SERVER_PORT'); + if (!$hasPort && $serverPort !== null) { + $uri = $uri->withPort(self::parseServerPort($serverPort)); + } + + return $uri; + } + + /** + * @param array $server + * + * @return array{0: UriInterface, 1: string|null} + */ + private static function getUriAndRequestTargetFromServer( + #[\SensitiveParameter] + array $server, + string $method + ): array { + $requestUri = self::getServerParam($server, 'REQUEST_URI'); + $queryString = self::getServerParam($server, 'QUERY_STRING'); + + if ($requestUri !== null) { + $connectAuthority = self::parseConnectAuthorityFormRequestTarget($method, $requestUri); + if ($connectAuthority !== null) { + [$host, $port] = $connectAuthority; + $uri = self::withoutHostDeprecation(static function () use ($server, $host): UriInterface { + return self::getUriWithSchemeFromServer($server)->withHost($host); + }); + + return [ + $uri->withPort($port)->withPath('')->withQuery(''), + $requestUri, + ]; + } + + $absoluteForm = self::getAbsoluteFormUriAndRequestTarget($requestUri, $queryString); + if ($absoluteForm !== null) { + return $absoluteForm; + } + } + + $uri = self::getAuthorityUriFromServer($server); + + if ($requestUri === null) { + if ($queryString !== null) { + $uri = $uri->withQuery($queryString); + } + + return [$uri, null]; + } + + if (Rfc9112::isAsteriskFormRequestTarget($method, $requestUri)) { + return [$uri->withPath('')->withQuery(''), '*']; + } + + [$path, $query, $hasQuery] = self::splitRequestTargetQuery($requestUri); + $uri = $uri->withPath(self::normalizeOriginFormPathFromServer($path)); + + if ($hasQuery) { + $uri = $uri->withQuery($query); + } elseif ($queryString !== null) { + $uri = $uri->withQuery($queryString); + } + + return [$uri, null]; + } + + /** + * @return array{0: UriInterface, 1: string}|null + */ + private static function getAbsoluteFormUriAndRequestTarget( + #[\SensitiveParameter] + string $requestUri, + ?string $queryString + ): ?array { + if (!Rfc9112::isAbsoluteFormRequestTarget($requestUri)) { + return null; + } + + try { + $targetUri = self::withoutHostDeprecation(static function () use ($requestUri): UriInterface { + return new Uri($requestUri); + })->withFragment(''); + } catch (InvalidArgumentException $e) { + return null; + } + + if ($targetUri->getHost() === '') { + return null; + } + + $requestTarget = self::removeRequestTargetFragment($requestUri); + $requestTargetWithoutUserInfo = self::removeUserInfoFromAbsoluteFormRequestTarget($requestTarget); + if ($requestTargetWithoutUserInfo !== $requestTarget) { + $targetUri = $targetUri->withUserInfo(''); + $requestTarget = $requestTargetWithoutUserInfo; + } + + if (!str_contains($requestTarget, '?') && $queryString !== null && $queryString !== '') { + $targetUri = $targetUri->withQuery($queryString); + $requestTarget .= '?'.$queryString; + } + + // Preserve the received absolute-form target unless it cannot be used as + // a PSR-7 request target without normalization. + $normalizeRequestTarget = !Rfc9112::isValidRequestTarget($requestTarget) + || self::hasEmptyPortInAbsoluteFormRequestTarget($requestTarget); + + return [$targetUri, $normalizeRequestTarget ? (string) $targetUri : $requestTarget]; + } + + private static function removeUserInfoFromAbsoluteFormRequestTarget(string $target): string + { + $authorityStart = strpos($target, '://'); + if ($authorityStart === false) { + return $target; + } + + $authorityStart += 3; + $authorityLength = strcspn($target, '/?#', $authorityStart); + $authority = substr($target, $authorityStart, $authorityLength); + if ($authority === '') { + return $target; + } + + $lastAt = strrpos($authority, '@'); + if ($lastAt === false) { + return $target; + } + + $authorityEnd = $authorityStart + $authorityLength; + + return substr($target, 0, $authorityStart) + .substr($authority, $lastAt + 1) + .substr($target, $authorityEnd); + } + + private static function hasEmptyPortInAbsoluteFormRequestTarget(string $target): bool + { + $authorityStart = strpos($target, '://'); + if ($authorityStart === false) { + return false; + } + + $authorityStart += 3; + $authority = substr($target, $authorityStart, strcspn($target, '/?#', $authorityStart)); + if ($authority === '') { + return false; + } + + $lastAt = strrpos($authority, '@'); + if ($lastAt !== false) { + $authority = substr($authority, $lastAt + 1); + } + + if ($authority === '') { + return false; + } + + if (str_starts_with($authority, '[')) { + $closingBracket = strpos($authority, ']'); + + return $closingBracket !== false && substr($authority, $closingBracket + 1) === ':'; + } + + return str_ends_with($authority, ':'); + } + + /** + * @return array{0: string, 1: int}|null + */ + private static function parseConnectAuthorityFormRequestTarget(string $method, string $target): ?array + { + if (!Rfc9112::isConnectAuthorityFormRequestTarget($method, $target)) { + return null; + } + + [$host, $port] = self::extractHostAndPortFromAuthority($target); + if ($host === null || $port === null) { + return null; + } + + return [$host, $port]; + } + + private static function removeRequestTargetFragment(string $target): string + { + return explode('#', $target, 2)[0]; + } + + /** + * @return array{0: string, 1: string, 2: bool} + */ + private static function splitRequestTargetQuery(string $target): array + { + $parts = explode('?', $target, 2); + + return [$parts[0], $parts[1] ?? '', isset($parts[1])]; + } + + private static function normalizeOriginFormPathFromServer(string $path): string + { + if ($path === '' || str_starts_with($path, '/')) { + return $path; + } + + return '/'.$path; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Stream.php b/vendor/guzzlehttp/psr7/src/Stream.php new file mode 100644 index 0000000..4235993 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Stream.php @@ -0,0 +1,334 @@ +size = Integers::assertOptionalNonNegativeSize($options['size'] ?? null, 'Stream size'); + + $this->customMetadata = $options['metadata'] ?? []; + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = self::isReadableMode($meta['mode']); + $this->writable = self::isWritableMode($meta['mode']); + $this->uri = $meta['uri'] ?? null; + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString(): string + { + if ($this->isSeekable()) { + $this->seek(0); + } + + return $this->getContents(); + } + + public function getContents(): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + + return Utils::tryGetContents($this->stream); + } + + public function close(): void + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize(): ?int + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if ($stats === false) { + return null; + } + + $this->size = Integers::assertEngineInteger($stats['size'], 'Stream size'); + + return $this->size; + } + + public function isReadable(): bool + { + return $this->readable; + } + + public function isWritable(): bool + { + return $this->writable; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function eof(): bool + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + return feof($this->stream); + } + + public function tell(): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $result = ftell($this->stream); + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + $position = Integers::assertEngineInteger($result, 'Stream position'); + if ($position === null) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $position; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } + if (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + .$offset.' with whence '.var_export($whence, true)); + } + } + + public function read(int $length): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if (0 === $length) { + return ''; + } + + try { + $string = fread($this->stream, $length); + } catch (TimeoutException $e) { + throw $e; + } catch (\Exception $e) { + if ($this->timedOut()) { + throw new TimeoutException('Unable to read from stream: timed out', 0, $e); + } + + throw new \RuntimeException('Unable to read from stream', 0, $e); + } + + if (false === $string) { + if ($this->timedOut()) { + throw new TimeoutException('Unable to read from stream: timed out'); + } + + throw new \RuntimeException('Unable to read from stream'); + } + + if ($string === '' && $this->timedOut()) { + throw new TimeoutException('Unable to read from stream: timed out'); + } + + return $string; + } + + public function write(string $string): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + if ($string === '') { + return 0; + } + + // We can't know the size after writing anything + $this->size = null; + + try { + $result = fwrite($this->stream, $string); + } catch (TimeoutException $e) { + throw $e; + } catch (\Exception $e) { + if ($this->writeTimedOut()) { + throw new TimeoutException('Unable to write to stream: timed out', 0, $e); + } + + throw new \RuntimeException('Unable to write to stream', 0, $e); + } + + if ($result === false) { + if ($this->writeTimedOut()) { + throw new TimeoutException('Unable to write to stream: timed out'); + } + + throw new \RuntimeException('Unable to write to stream'); + } + + if ($result === 0 && $this->writeTimedOut()) { + throw new TimeoutException('Unable to write to stream: timed out'); + } + + return $result; + } + + /** + * @return mixed + */ + public function getMetadata(?string $key = null) + { + if (!isset($this->stream)) { + return $key === null ? [] : null; + } elseif ($key === null) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return $meta[$key] ?? null; + } + + /** + * @see https://www.php.net/manual/en/function.fopen.php + * @see https://www.php.net/manual/en/function.gzopen.php + */ + private static function isReadableMode(string $mode): bool + { + return str_starts_with($mode, 'r') || str_contains($mode, '+'); + } + + /** + * @see https://www.php.net/manual/en/function.fopen.php + * @see https://www.php.net/manual/en/function.gzopen.php + */ + private static function isWritableMode(string $mode): bool + { + return str_starts_with($mode, 'a') + || str_starts_with($mode, 'w') + || str_starts_with($mode, 'x') + || str_starts_with($mode, 'c') + || str_contains($mode, '+'); + } + + private function timedOut(): bool + { + return StreamTimeout::isResourceReadTimedOut($this->stream); + } + + private function writeTimedOut(): bool + { + return StreamTimeout::isResourceWriteTimedOut($this->stream); + } +} diff --git a/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 0000000..7b649a8 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,149 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + */ + public function __get(string $name): StreamInterface + { + if ($name === 'stream') { + $this->stream = $this->createStream(); + + return $this->stream; + } + + throw new \UnexpectedValueException(\sprintf('%s not found on class', DiagnosticValue::escape($name))); + } + + public function __toString(): string + { + if ($this->isSeekable()) { + $this->seek(0); + } + + return $this->getContents(); + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Allow decorators to implement custom methods + * + * @return mixed + */ + public function __call(string $method, array $args) + { + /** @var callable $callable */ + $callable = [$this->stream, $method]; + $result = ($callable)(...$args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close(): void + { + $this->stream->close(); + } + + /** + * @return mixed + */ + public function getMetadata(?string $key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize(): ?int + { + return $this->stream->getSize(); + } + + public function eof(): bool + { + return $this->stream->eof(); + } + + public function tell(): int + { + return $this->stream->tell(); + } + + public function isReadable(): bool + { + return $this->stream->isReadable(); + } + + public function isWritable(): bool + { + return $this->stream->isWritable(); + } + + public function isSeekable(): bool + { + return $this->stream->isSeekable(); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + $this->stream->seek($offset, $whence); + } + + public function read(int $length): string + { + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + return $this->stream->read($length); + } + + public function write(string $string): int + { + return $this->stream->write($string); + } + + /** + * Implement in subclasses to dynamically create streams when requested. + * + * @throws \BadMethodCallException + */ + protected function createStream(): StreamInterface + { + throw new \BadMethodCallException('Not implemented'); + } +} diff --git a/vendor/guzzlehttp/psr7/src/StreamTimeout.php b/vendor/guzzlehttp/psr7/src/StreamTimeout.php new file mode 100644 index 0000000..84a6b36 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/StreamTimeout.php @@ -0,0 +1,106 @@ +read($length); + } catch (TimeoutException $e) { + throw $e; + } catch (\RuntimeException $e) { + self::throwIfReadTimedOut($stream, $timeoutMessage, $e); + + throw $e; + } + + if ($buffer === '') { + self::throwIfReadTimedOut($stream, $timeoutMessage); + } + + return $buffer; + } + + public static function throwIfReadTimedOut( + StreamInterface $stream, + string $message, + ?\Throwable $previous = null + ): void { + if (self::isReadTimedOut($stream)) { + throw new TimeoutException($message, 0, $previous); + } + } + + public static function throwIfWriteTimedOut(StreamInterface $stream, ?\Throwable $previous = null): void + { + if (self::isWriteTimedOut($stream)) { + throw new TimeoutException('Unable to write to stream: timed out', 0, $previous); + } + } + + public static function isReadTimedOut(StreamInterface $stream): bool + { + try { + if ($stream->getMetadata('timed_out') !== true) { + return false; + } + + return !$stream->eof(); + } catch (\Throwable $e) { + return false; + } + } + + public static function isWriteTimedOut(StreamInterface $stream): bool + { + try { + return $stream->getMetadata('timed_out') === true; + } catch (\Throwable $e) { + return false; + } + } + + /** + * @param resource $resource + */ + public static function isResourceReadTimedOut($resource): bool + { + try { + /** @var array $metadata */ + $metadata = stream_get_meta_data($resource); + + return ($metadata['timed_out'] ?? false) === true && !feof($resource); + } catch (\Throwable $e) { + return false; + } + } + + /** + * @param resource $resource + */ + public static function isResourceWriteTimedOut($resource): bool + { + try { + /** @var array $metadata */ + $metadata = stream_get_meta_data($resource); + + return ($metadata['timed_out'] ?? false) === true; + } catch (\Throwable $e) { + return false; + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/StreamWrapper.php b/vendor/guzzlehttp/psr7/src/StreamWrapper.php new file mode 100644 index 0000000..2d254d2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/StreamWrapper.php @@ -0,0 +1,254 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + .'writable, or both.'); + } + + $resource = @fopen('guzzle://stream', $mode, false, self::createStreamContext($stream)); + + if ($resource === false) { + throw new \RuntimeException('Unable to create stream resource'); + } + + return $resource; + } + + /** + * Creates a stream context that can be used to open a stream as a php stream resource. + * + * @return resource + */ + public static function createStreamContext(StreamInterface $stream) + { + return stream_context_create([ + 'guzzle' => ['stream' => $stream], + ]); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register(): void + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open(string $path, string $mode, int $options, ?string &$opened_path = null): bool + { + $options = stream_context_get_options($this->context); + $stream = $options['guzzle']['stream'] ?? null; + + if (!$stream instanceof StreamInterface) { + return false; + } + + $this->mode = $mode; + $this->stream = $stream; + + return true; + } + + /** + * @return string|false + */ + public function stream_read(int $count) + { + try { + return $this->stream->read($count); + } catch (\RuntimeException $e) { + return false; + } + } + + public function stream_write(string $data): int + { + try { + return $this->stream->write($data); + } catch (\RuntimeException $e) { + return -1; + } + } + + public function stream_flush(): bool + { + return true; + } + + /** + * @return int|false + */ + public function stream_tell() + { + try { + return $this->stream->tell(); + } catch (\RuntimeException $e) { + return false; + } + } + + public function stream_eof(): bool + { + try { + return $this->stream->eof(); + } catch (\RuntimeException $e) { + return true; + } + } + + public function stream_seek(int $offset, int $whence): bool + { + try { + $this->stream->seek($offset, $whence); + } catch (\RuntimeException $e) { + return false; + } + + return true; + } + + /** + * @return resource|false + */ + public function stream_cast(int $cast_as) + { + try { + $stream = clone $this->stream; + $resource = $stream->detach(); + } catch (\RuntimeException $e) { + return false; + } + + return $resource ?? false; + } + + /** + * @return array{ + * dev: int, + * ino: int, + * mode: int, + * nlink: int, + * uid: int, + * gid: int, + * rdev: int, + * size: int, + * atime: int, + * mtime: int, + * ctime: int, + * blksize: int, + * blocks: int + * }|false + */ + public function stream_stat() + { + try { + $size = $this->stream->getSize(); + } catch (\RuntimeException $e) { + return false; + } + + if ($size === null) { + return false; + } + + static $modeMap = [ + 'r' => 33060, + 'rb' => 33060, + 'r+' => 33206, + 'w' => 33188, + 'wb' => 33188, + ]; + + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode] ?? 0, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $size, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0, + ]; + } + + /** + * @return array{ + * dev: int, + * ino: int, + * mode: int, + * nlink: int, + * uid: int, + * gid: int, + * rdev: int, + * size: int, + * atime: int, + * mtime: int, + * ctime: int, + * blksize: int, + * blocks: int + * } + */ + public function url_stat(string $path, int $flags): array + { + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => 0, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0, + ]; + } +} diff --git a/vendor/guzzlehttp/psr7/src/UploadedFile.php b/vendor/guzzlehttp/psr7/src/UploadedFile.php new file mode 100644 index 0000000..188bf52 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UploadedFile.php @@ -0,0 +1,188 @@ + 'UPLOAD_ERR_OK', + UPLOAD_ERR_INI_SIZE => 'UPLOAD_ERR_INI_SIZE', + UPLOAD_ERR_FORM_SIZE => 'UPLOAD_ERR_FORM_SIZE', + UPLOAD_ERR_PARTIAL => 'UPLOAD_ERR_PARTIAL', + UPLOAD_ERR_NO_FILE => 'UPLOAD_ERR_NO_FILE', + UPLOAD_ERR_NO_TMP_DIR => 'UPLOAD_ERR_NO_TMP_DIR', + UPLOAD_ERR_CANT_WRITE => 'UPLOAD_ERR_CANT_WRITE', + UPLOAD_ERR_EXTENSION => 'UPLOAD_ERR_EXTENSION', + ]; + + private ?string $clientFilename; + + private ?string $clientMediaType; + + private int $error; + + private ?string $file = null; + + private bool $moved = false; + + private ?int $size; + + private ?StreamInterface $stream = null; + + /** + * @param StreamInterface|string|resource $streamOrFile + */ + public function __construct( + $streamOrFile, + ?int $size, + int $errorStatus, + ?string $clientFilename = null, + ?string $clientMediaType = null + ) { + $this->setError($errorStatus); + $this->size = Integers::assertOptionalNonNegativeSize($size, 'Uploaded file size'); + $this->clientFilename = $clientFilename; + $this->clientMediaType = $clientMediaType; + + if ($this->isOk()) { + $this->setStreamOrFile($streamOrFile); + } + } + + /** + * Depending on the value set file or stream variable + * + * @param StreamInterface|string|resource $streamOrFile + * + * @throws InvalidArgumentException + */ + private function setStreamOrFile($streamOrFile): void + { + if (is_string($streamOrFile)) { + $this->file = $streamOrFile; + } elseif (is_resource($streamOrFile)) { + $this->stream = new Stream($streamOrFile); + } elseif ($streamOrFile instanceof StreamInterface) { + $this->stream = $streamOrFile; + } else { + throw new InvalidArgumentException( + 'Invalid stream or file provided for UploadedFile' + ); + } + } + + /** + * @throws InvalidArgumentException + */ + private function setError(int $error): void + { + if (!isset(UploadedFile::ERROR_MAP[$error])) { + throw new InvalidArgumentException( + 'Invalid error status for UploadedFile' + ); + } + + $this->error = $error; + } + + /** + * Return true if there is no upload error + */ + private function isOk(): bool + { + return $this->error === UPLOAD_ERR_OK; + } + + public function isMoved(): bool + { + return $this->moved; + } + + /** + * @throws RuntimeException if is moved or not ok + */ + private function validateActive(): void + { + if (false === $this->isOk()) { + throw new RuntimeException(\sprintf('Cannot retrieve stream due to upload error (%s)', self::ERROR_MAP[$this->error])); + } + + if ($this->isMoved()) { + throw new RuntimeException('Cannot retrieve stream after it has already been moved'); + } + } + + public function getStream(): StreamInterface + { + $this->validateActive(); + + if ($this->stream instanceof StreamInterface) { + return $this->stream; + } + + /** @var string $file */ + $file = $this->file; + + return new LazyOpenStream($file, 'r+'); + } + + public function moveTo(string $targetPath): void + { + $this->validateActive(); + + if ($targetPath === '') { + throw new InvalidArgumentException( + 'Invalid path provided for move operation; must be a non-empty string' + ); + } + + if ($this->file) { + $this->moved = PHP_SAPI === 'cli' + ? rename($this->file, $targetPath) + : move_uploaded_file($this->file, $targetPath); + } else { + $stream = $this->getStream(); + if ($stream->isSeekable()) { + $stream->rewind(); + } + + Utils::copyToStream( + $stream, + new LazyOpenStream($targetPath, 'w') + ); + + $this->moved = true; + } + + if (false === $this->moved) { + throw new RuntimeException(sprintf('Uploaded file could not be moved to %s', DiagnosticValue::escape($targetPath))); + } + } + + public function getSize(): ?int + { + return $this->size; + } + + public function getError(): int + { + return $this->error; + } + + public function getClientFilename(): ?string + { + return $this->clientFilename; + } + + public function getClientMediaType(): ?string + { + return $this->clientMediaType; + } +} diff --git a/vendor/guzzlehttp/psr7/src/UploadedFileNormalizer.php b/vendor/guzzlehttp/psr7/src/UploadedFileNormalizer.php new file mode 100644 index 0000000..968e418 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UploadedFileNormalizer.php @@ -0,0 +1,130 @@ + + */ +final class UploadedFileNormalizer +{ + private function __construct() + { + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files An array which respect $_FILES structure + * + * @return UploadedFileTree + * + * @throws InvalidArgumentException for unrecognized values + */ + public static function normalize(array $files): array + { + $normalized = []; + + foreach ($files as $key => $value) { + if ($value instanceof UploadedFileInterface) { + $normalized[$key] = $value; + } elseif (is_array($value) && array_key_exists('tmp_name', $value)) { + $normalized[$key] = self::createUploadedFileFromSpec($value); + } elseif (is_array($value)) { + $normalized[$key] = self::normalize($value); + continue; + } else { + throw new InvalidArgumentException('Invalid value in files specification'); + } + } + + return $normalized; + } + + /** + * Create and return an UploadedFile instance from a $_FILES specification. + * + * If the specification represents an array of values, this method will + * delegate to normalizeNestedFileSpec() and return that return value. + * + * @param array $value $_FILES struct + * + * @return UploadedFileInterface|UploadedFileTree + */ + private static function createUploadedFileFromSpec(array $value) + { + self::assertFileSpec($value); + + if (is_array($value['tmp_name'])) { + return self::normalizeNestedFileSpec($value); + } + + return new UploadedFile( + $value['tmp_name'], + Integers::assertNonNegativeInteger($value['size'], 'Uploaded file size'), + Integers::assertNonNegativeInteger($value['error'], 'Uploaded file error'), + $value['name'] ?? null, + $value['type'] ?? null + ); + } + + private static function assertFileSpec(array $value): void + { + if (!isset($value['tmp_name'], $value['size'], $value['error'])) { + throw new InvalidArgumentException('Invalid file specification; expected keys "tmp_name", "size", and "error".'); + } + } + + /** + * Normalize an array of file specifications. + * + * Loops through all nested files and returns a normalized array of + * UploadedFileInterface instances. + * + * @return UploadedFileTree + */ + private static function normalizeNestedFileSpec(array $files = []): array + { + self::assertNestedFileSpec($files); + + $normalizedFiles = []; + + foreach (array_keys($files['tmp_name']) as $key) { + if (!array_key_exists($key, $files['size']) || !array_key_exists($key, $files['error'])) { + throw new InvalidArgumentException('Invalid nested file specification; expected "tmp_name", "size", and "error" arrays to have matching keys.'); + } + + $spec = [ + 'tmp_name' => $files['tmp_name'][$key], + 'size' => $files['size'][$key], + 'error' => $files['error'][$key], + 'name' => $files['name'][$key] ?? null, + 'type' => $files['type'][$key] ?? null, + ]; + $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); + } + + return $normalizedFiles; + } + + private static function assertNestedFileSpec(array $files): void + { + foreach (['tmp_name', 'size', 'error'] as $key) { + if (!isset($files[$key]) || !is_array($files[$key])) { + throw new InvalidArgumentException('Invalid nested file specification; expected keys "tmp_name", "size", and "error" to be arrays.'); + } + } + + foreach (['name', 'type'] as $key) { + if (isset($files[$key]) && !is_array($files[$key])) { + throw new InvalidArgumentException(sprintf('Invalid nested file specification; expected key "%s" to be an array when present.', $key)); + } + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/Uri.php b/vendor/guzzlehttp/psr7/src/Uri.php new file mode 100644 index 0000000..231c2b6 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Uri.php @@ -0,0 +1,882 @@ + 80, + 'https' => 443, + 'ftp' => 21, + 'gopher' => 70, + 'nntp' => 119, + 'news' => 119, + 'telnet' => 23, + 'tn3270' => 23, + 'imap' => 143, + 'pop' => 110, + 'ldap' => 389, + 'ws' => 80, + 'wss' => 443, + ]; + + private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26', '+' => '%2B']; + + /** @var string Uri scheme. */ + private string $scheme = ''; + + /** @var string Uri user info. */ + private string $userInfo = ''; + + /** @var string Uri host. */ + private string $host = ''; + + /** @var int|null Uri port. */ + private ?int $port = null; + + /** @var string Uri path. */ + private string $path = ''; + + /** @var string Uri query string. */ + private string $query = ''; + + /** @var string Uri fragment. */ + private string $fragment = ''; + + public function __construct( + #[\SensitiveParameter] + string $uri = '' + ) { + if ($uri !== '') { + $parts = UriParser::parse($uri); + if ($parts === false) { + throw new MalformedUriException(\sprintf('Unable to parse URI: %s', UriRedactor::redactUriStringForMessage($uri))); + } + try { + $this->applyParts($parts); + } catch (MalformedUriException $e) { + throw $e; + } catch (\InvalidArgumentException $e) { + throw new MalformedUriException($e->getMessage(), 0, $e); + } + + if ($this->scheme === '' && $this->host !== '' && !str_starts_with($uri, '//')) { + \trigger_deprecation( + 'guzzlehttp/psr7', + '3.6', + 'Passing a URI string that starts with a host and port, such as "example.com:8080", is deprecated; guzzlehttp/psr7 4.0 rejects it. Start the string with a scheme or with "//".' + ); + } + } + } + + public function __toString(): string + { + return self::composeComponents( + $this->scheme, + $this->getAuthority(), + $this->path, + $this->query, + $this->fragment + ); + } + + /** + * Composes a URI reference string from its various components according to + * RFC 3986 Section 5.3. + * + * Usually this method does not need to be called manually but instead is + * used indirectly via `Psr\Http\Message\UriInterface::__toString`. + * + * PSR-7 UriInterface treats an empty component the same as a missing + * component as `getQuery()`, `getFragment()` etc. always return a string. + * This explains the slight difference to RFC 3986 Section 5.3. + * + * Another adjustment is that the authority separator is added even when the + * authority is missing/empty for the "file" scheme. This is because PHP + * stream functions like `file_get_contents` only work with `file:///myfile` + * but not with `file:/myfile` although they are equivalent according to RFC + * 3986. But `file:///` is the more common syntax for the file scheme anyway + * (Chrome for example redirects to that format). The separator is omitted + * when such a URI has a rootless or empty path: adding it would turn the + * first path segment into the authority of the composed URI, or compose the + * string `file://`, which cannot be parsed back into a URI. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3 + */ + public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string + { + $uri = ''; + + // weak type checks to also accept null until we can add scalar type hints + if ($scheme != '') { + $uri .= $scheme.':'; + } + + if ($authority != '' || ($scheme === 'file' && str_starts_with($path, '/'))) { + $uri .= '//'.$authority; + } + + if ($authority != '' && $path != '' && !str_starts_with($path, '/')) { + $path = '/'.$path; + } + + $uri .= $path; + + if ($query != '') { + $uri .= '?'.$query; + } + + if ($fragment != '') { + $uri .= '#'.$fragment; + } + + return $uri; + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard + * port. This method can be used independently of the implementation. + */ + public static function isDefaultPort(UriInterface $uri): bool + { + return $uri->getPort() === null + || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative + * reference. An absolute URI has a scheme. A relative reference is used to + * express a URI relative to another URI, the base URI. Relative references + * can be divided into several forms according to RFC 3986 Section 4.2: + * - network-path references, e.g. `//example.com/path` + * - absolute-path references, e.g. `/path` + * - relative-path references, e.g. `subpath` + * + * @see Uri::isNetworkPathReference + * @see Uri::isAbsolutePathReference + * @see Uri::isRelativePathReference + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isAbsolute(UriInterface $uri): bool + { + return $uri->getScheme() !== ''; + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed a + * network-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isNetworkPathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; + } + + /** + * Whether the URI is an absolute-path reference. + * + * A relative reference that begins with a single slash character is termed + * an absolute-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isAbsolutePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && isset($uri->getPath()[0]) + && $uri->getPath()[0] === '/'; + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed + * a relative-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isRelativePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its + * fragment component, identical to the base URI. When no base URI is given, + * only an empty URI reference (apart from its fragment) is considered a + * same-document reference. + * + * @param UriInterface $uri The URI to check + * @param UriInterface|null $base An optional base URI to compare against + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.4 + */ + public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null): bool + { + if ($base !== null) { + $uri = UriResolver::resolve($base, $uri); + + return ($uri->getScheme() === $base->getScheme()) + && ($uri->getAuthority() === $base->getAuthority()) + && (self::rawPath($uri) === self::rawPath($base)) + && ($uri->getQuery() === $base->getQuery()); + } + + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; + } + + /** + * Creates a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key to remove. + */ + public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. A value of null will + * set the query string key without a value, e.g. "key" instead of + * "key=value". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string|null $value Value to set + */ + public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + $result[] = self::generateQueryString($key, $value); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with multiple query string values. + * + * It has the same behavior as `withQueryValue()` but for an associative + * array of key => value. + * + * @param UriInterface $uri URI to use as a base. + * @param (string|null)[] $keyValueArray Associative array of key and values + */ + public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface + { + $result = self::getFilteredQueryString($uri, array_keys($keyValueArray)); + + foreach ($keyValueArray as $key => $value) { + self::assertStringOrNullQueryValue($value); + $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null); + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * @param mixed $value + */ + private static function assertStringOrNullQueryValue($value): void + { + if ($value !== null && !is_string($value)) { + throw new \InvalidArgumentException(\sprintf( + 'Query string values must be a string or null, %s given.', + \get_debug_type($value) + )); + } + } + + /** + * Creates a URI from a hash of `parse_url` components. + * + * @see https://www.php.net/manual/en/function.parse-url.php + * + * @throws MalformedUriException If the components do not form a valid URI. + */ + public static function fromParts( + #[\SensitiveParameter] + array $parts + ): UriInterface { + $uri = new self(); + try { + $uri->applyParts($parts); + $uri->validateState(); + } catch (MalformedUriException $e) { + throw $e; + } catch (\InvalidArgumentException $e) { + throw new MalformedUriException($e->getMessage(), 0, $e); + } + + return $uri; + } + + /** + * @throws \InvalidArgumentException If the host is invalid. + * + * @internal + */ + public static function assertValidHost(string $host): void + { + if (!Rfc3986::isValidHost($host)) { + throw new \InvalidArgumentException(sprintf('Invalid host: %s', DiagnosticValue::escape($host))); + } + } + + /** + * @internal + */ + public static function deprecateNonAsciiHost(string $host): void + { + if (preg_match('/[\x80-\xFF]|%[89A-Fa-f][0-9A-Fa-f]/', $host) === 1) { + \trigger_deprecation( + 'guzzlehttp/psr7', + '3.6', + 'Passing a URI host with non-ASCII data, raw or percent-encoded, is deprecated; guzzlehttp/psr7 4.0 requires URI hosts to be ASCII. Convert internationalized hosts with %s::toAscii() or %s::uriFor() first.', + Idna::class, + Idna::class + ); + } + } + + public function getScheme(): string + { + return $this->scheme; + } + + public function getAuthority(): string + { + $authority = $this->host; + if ($this->userInfo !== '') { + $authority = $this->userInfo.'@'.$authority; + } + + if ($this->port !== null) { + $authority .= ':'.$this->port; + } + + return $authority; + } + + public function getUserInfo(): string + { + return $this->userInfo; + } + + public function getHost(): string + { + return $this->host; + } + + public function getPort(): ?int + { + return $this->port; + } + + public function getPath(): string + { + if (str_starts_with($this->path, '//')) { + return '/'.ltrim($this->path, '/'); + } + + return $this->path; + } + + /** + * Returns the path as it appears within a URI's string form. + * + * getPath() collapses multiple leading slashes so that a path used in + * isolation cannot be mistaken for a protocol-relative URL. Whole-URI + * operations like reference resolution and normalization (RFC 3986 + * Sections 5 and 6) are defined on the URI string form, where the path + * stays verbatim, so they must read the path through this method instead. + * For direct instances of this class the path is derived from the stored + * components, including the leading slash the string form adds to a + * rootless path when an authority is present; for subclasses and other + * implementations the path is split from the string form per RFC 3986 + * Appendix B, without validating or decoding any other component. The + * scheme is only split off when the instance reports one, as a relative + * reference can begin with a segment containing a colon that the Appendix + * B expression would otherwise read as a scheme. + * + * @throws \RuntimeException If the path cannot be split from the string form. + * + * @internal + */ + public static function rawPath(UriInterface $uri): string + { + if (get_class($uri) === self::class) { + if ($uri->path !== '' && !str_starts_with($uri->path, '/') && $uri->getAuthority() !== '') { + // composeComponents() prepends a slash to a rootless path when + // an authority is present, so the string form uses this path. + return '/'.$uri->path; + } + + return $uri->path; + } + + $pattern = $uri->getScheme() === '' + ? '%^(?://[^/?#]*)?([^?#]*)%' + : '%^(?:[^:/?#]+:)?(?://[^/?#]*)?([^?#]*)%'; + $count = preg_match($pattern, (string) $uri, $matches); + + if ($count === false) { + throw new \RuntimeException('Unable to read the URI path: '.preg_last_error_msg()); + } + + return $matches[1] ?? ''; + } + + public function getQuery(): string + { + return $this->query; + } + + public function getFragment(): string + { + return $this->fragment; + } + + public function withScheme(string $scheme): UriInterface + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withUserInfo( + string $user, + #[\SensitiveParameter] + ?string $password = null + ): UriInterface { + $info = $this->filterUserInfoComponent($user); + if ($password !== null) { + $info .= ':'.$this->filterUserInfoComponent($password); + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + $new->validateState(); + + return $new; + } + + public function withHost(string $host): UriInterface + { + $host = $this->filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->validateState(); + + return $new; + } + + public function withPort(?int $port): UriInterface + { + $port = $this->filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withPath(string $path): UriInterface + { + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->validateState(); + + return $new; + } + + public function withQuery(string $query): UriInterface + { + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + + return $new; + } + + public function withFragment(string $fragment): UriInterface + { + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + + return $new; + } + + public function jsonSerialize(): string + { + return $this->__toString(); + } + + /** + * Apply parse_url parts to a URI. + * + * @param array $parts Array of parse_url parts to apply. + */ + private function applyParts( + #[\SensitiveParameter] + array $parts + ): void { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) + ? $this->filterUserInfoComponent($parts['user']) + : ''; + $this->host = isset($parts['host']) + ? $this->filterHost($parts['host']) + : ''; + $this->port = isset($parts['port']) + ? $this->filterPortPart($parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':'.$this->filterUserInfoComponent($parts['pass']); + } + + $this->removeDefaultPort(); + } + + /** + * @throws \InvalidArgumentException If the scheme is invalid. + */ + private function filterScheme(string $scheme): string + { + $scheme = Utils::asciiToLower($scheme); + + if (!Rfc3986::isValidScheme($scheme)) { + throw new \InvalidArgumentException(sprintf('Invalid scheme: %s', DiagnosticValue::escape($scheme))); + } + + return $scheme; + } + + /** + * @throws \InvalidArgumentException If the user info is invalid. + */ + private function filterUserInfoComponent( + #[\SensitiveParameter] + string $component + ): string { + return $this->filterComponent( + '/(?:[^%'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.']++|%(?!'.Rfc3986::HEX_OCTET.'))/', + $component, + 'Unable to filter URI user info' + ); + } + + /** + * @throws \InvalidArgumentException If the host is invalid. + */ + private function filterHost(string $host): string + { + $host = Utils::asciiToLower($host); + $filtered = \preg_replace_callback('/%'.Rfc3986::HEX_OCTET.'/', static function (array $m): string { + return Utils::asciiToUpper($m[0]); + }, $host); + if ($filtered === null) { + throw new \RuntimeException('Unable to normalize URI host percent-encoding: '.\preg_last_error_msg()); + } + self::assertValidHost($filtered); + self::deprecateNonAsciiHost($filtered); + + if (str_starts_with($filtered, '[') && !str_starts_with($filtered, '[v')) { + // assertValidHost() accepted this bracketed value with the same + // filter_var() predicate tryCanonicalizeIpv6() validates with, and + // its pure-PHP parse cannot fail on filter-accepted text, so the + // null guard is defense in depth only. + $canonical = Rfc3986::tryCanonicalizeIpv6(substr($filtered, 1, -1)); + if ($canonical !== null) { + $filtered = '['.$canonical.']'; + } + } + + return $filtered; + } + + /** + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort(?int $port): ?int + { + if ($port === null) { + return null; + } + + if (0 > $port || 0xFFFF < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 0 and 65535', $port) + ); + } + + return $port; + } + + /** + * @param mixed $port + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPortPart($port): ?int + { + if (\is_int($port)) { + return $this->filterPort($port); + } + + if (\is_string($port) && \ctype_digit($port)) { + // A zero port is accepted here; only Rfc9112::parsePort() rejects + // it for HTTP Host/authority parsing. + if (Rfc3986::isValidPort($port)) { + return (int) \ltrim($port, '0'); + } + + throw new \InvalidArgumentException(sprintf( + 'Invalid port: %s. Must be between 0 and 65535', + \ltrim($port, '0') + )); + } + + throw new \InvalidArgumentException(sprintf( + 'Invalid port: %s. Must be between 0 and 65535', + self::describeInvalidPort($port) + )); + } + + /** + * @param mixed $port + */ + private static function describeInvalidPort($port): string + { + if (\is_string($port)) { + return DiagnosticValue::escape($port); + } + + if (\is_int($port)) { + return (string) $port; + } + + if (\is_bool($port)) { + return $port ? 'true' : 'false'; + } + + if ($port === null) { + return 'null'; + } + + if (\is_float($port)) { + if (\is_nan($port)) { + return 'NAN'; + } + + if (\is_infinite($port)) { + return $port > 0 ? 'INF' : '-INF'; + } + + return \sprintf('%.14G', $port); + } + + return \get_debug_type($port); + } + + /** + * @param (string|int)[] $keys + * + * @return string[] + */ + private static function getFilteredQueryString(UriInterface $uri, array $keys): array + { + $current = $uri->getQuery(); + + if ($current === '') { + return []; + } + + $decodedKeys = array_map(function ($k): string { + return rawurldecode((string) $k); + }, $keys); + + return array_filter(explode('&', $current), static function (string $part) use ($decodedKeys): bool { + return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true); + }); + } + + private static function generateQueryString(string $key, ?string $value): string + { + // Query string separators ("=", "&") and literal plus signs ("+") within the + // key or value need to be encoded + // (while preventing double-encoding) before setting the query string. All other + // chars that need percent-encoding will be encoded by withQuery(). + $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT); + + if ($value !== null) { + $queryString .= '='.strtr($value, self::QUERY_SEPARATORS_REPLACEMENT); + } + + return $queryString; + } + + private function removeDefaultPort(): void + { + if ($this->port !== null && self::isDefaultPort($this)) { + $this->port = null; + } + } + + /** + * Filters the path of a URI + * + * @throws \InvalidArgumentException If the path is invalid. + */ + private function filterPath(string $path): string + { + return $this->filterComponent( + '/(?:[^'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.'%:@\/]++|%(?!'.Rfc3986::HEX_OCTET.'))/', + $path, + 'Unable to filter URI path' + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @throws \InvalidArgumentException If the query or fragment is invalid. + */ + private function filterQueryAndFragment(string $str): string + { + return $this->filterComponent( + '/(?:[^'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.'%:@\/\?]++|%(?!'.Rfc3986::HEX_OCTET.'))/', + $str, + 'Unable to filter URI query or fragment' + ); + } + + private function filterComponent( + string $pattern, + #[\SensitiveParameter] + string $component, + string $context + ): string { + $filtered = preg_replace_callback($pattern, [$this, 'rawurlencodeMatchZero'], $component); + + if ($filtered === null) { + throw new \RuntimeException($context.': '.preg_last_error_msg()); + } + + return $filtered; + } + + private function rawurlencodeMatchZero(array $match): string + { + return rawurlencode($match[0]); + } + + private function validateState(): void + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + $this->host = self::HTTP_DEFAULT_HOST; + } + + if ($this->getAuthority() === '') { + if (str_starts_with($this->path, '//')) { + throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"'); + } + if ($this->scheme === '' && str_contains(explode('/', $this->path, 2)[0], ':')) { + throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriComparator.php b/vendor/guzzlehttp/psr7/src/UriComparator.php new file mode 100644 index 0000000..8bd27bf --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriComparator.php @@ -0,0 +1,96 @@ +getScheme() !== $modified->getScheme()) { + return true; + } + + if (self::computePort($original) !== self::computePort($modified)) { + return true; + } + + return false; + } + + private static function normalizeHost(UriInterface $uri): string + { + $host = $uri->getHost(); + if (!str_starts_with($host, '[') || !str_ends_with($host, ']')) { + return $host; + } + + // Foreign UriInterface implementations may carry non-canonical IPv6 + // spellings; canonicalize what is unambiguously an IPv6 address so + // equivalent literals compare as same-origin, and leave IPvFuture, + // zone-identifier, and invalid text to the caseless textual + // comparison. Validation is platform-independent, so a spelling only + // some OS parsers accept, such as zero-padded dotted octets, is + // cross-origin everywhere instead of same-origin on some systems. + $canonical = Rfc3986::tryCanonicalizeIpv6(substr($host, 1, -1)); + if ($canonical === null) { + return $host; + } + + return '['.$canonical.']'; + } + + private static function computePort(UriInterface $uri): ?int + { + $port = $uri->getPort(); + + if (null !== $port) { + return $port; + } + + if (\in_array($uri->getScheme(), ['http', 'ws'], true)) { + return 80; + } + + if (\in_array($uri->getScheme(), ['https', 'wss'], true)) { + return 443; + } + + return null; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriNormalizer.php b/vendor/guzzlehttp/psr7/src/UriNormalizer.php new file mode 100644 index 0000000..d19a136 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriNormalizer.php @@ -0,0 +1,456 @@ +getPath() === '' + && ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') + ) { + $uri = $uri->withPath('/'); + } + + if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { + if ($uri->getUserInfo() === '' && $uri->getPort() === null) { + $path = Uri::rawPath($uri); + if (str_starts_with($path, '//')) { + // "/." keeps a "//" path unambiguous once the authority is gone + $uri = $uri->withPath('/.'.$path); + } + } + + $uri = $uri->withHost(''); + } + + if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { + $uri = $uri->withPort(null); + } + + $removeDotSegments = ($flags & self::REMOVE_DOT_SEGMENTS) && !Uri::isRelativePathReference($uri); + + if ($removeDotSegments || $flags & self::REMOVE_DUPLICATE_SLASHES) { + $path = Uri::rawPath($uri); + + if ($removeDotSegments) { + $path = UriResolver::removeDotSegments($path); + } + + if ($flags & self::REMOVE_DUPLICATE_SLASHES) { + $path = preg_replace('#//++#', '/', $path); + + if ($path === null) { + throw new \RuntimeException('Unable to remove duplicate slashes from URI path: '.preg_last_error_msg()); + } + } + + $uri = $uri->withPath(UriResolver::guardedPath($uri, $path)); + } + + if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { + $queryKeyValues = explode('&', $uri->getQuery()); + sort($queryKeyValues); + $uri = $uri->withQuery(implode('&', $queryKeyValues)); + } + + if ($flags & self::CANONICALIZE_IPV6_HOST) { + $uri = self::canonicalizeIpv6Host($uri); + } + + return $uri; + } + + /** + * Whether two URIs can be considered equivalent. + * + * Both URIs are normalized automatically before comparison with the given + * `$normalizations` bitmask. The method also accepts relative URI + * references and returns true when they are equivalent. This of course + * assumes they will be resolved against the same base URI. If this is not + * the case, determination of equivalence or difference of relative + * references does not mean anything. + * + * @param UriInterface $uri1 An URI to compare + * @param UriInterface $uri2 An URI to compare + * @param int $normalizations A bitmask of normalizations to apply, see constants + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-6.1 + */ + public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool + { + return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); + } + + private static function capitalizePercentEncoding(UriInterface $uri): UriInterface + { + $regex = '/(?:%'.Rfc3986::HEX_OCTET.')++/'; + + $callback = function (array $match): string { + return Utils::asciiToUpper($match[0]); + }; + + $uri = self::withNormalizedUserInfo($uri, $regex, $callback); + $uri = self::withNormalizedHost($uri, $regex, $callback); + + return self::withGuardedPath($uri, self::normalizePercentEncodingInComponent(Uri::rawPath($uri), $regex, $callback)) + ->withQuery(self::normalizePercentEncodingInComponent($uri->getQuery(), $regex, $callback)) + ->withFragment(self::normalizePercentEncodingInComponent($uri->getFragment(), $regex, $callback)); + } + + private static function decodeUnreservedCharacters(UriInterface $uri): UriInterface + { + $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; + + $callback = function (array $match): string { + return rawurldecode($match[0]); + }; + + // The host is case-insensitive and PSR-7 requires it to be lowercase, + // so decoded ALPHA octets (e.g. "%41") must land lowercase even for + // implementations whose withHost() does not normalize the case. + $hostCallback = function (array $match): string { + return Utils::asciiToLower(rawurldecode($match[0])); + }; + + $uri = self::withNormalizedUserInfo($uri, $regex, $callback); + $uri = self::withNormalizedHost($uri, $regex, $hostCallback); + + return self::withGuardedPath($uri, self::normalizePercentEncodingInComponent(Uri::rawPath($uri), $regex, $callback)) + ->withQuery(self::normalizePercentEncodingInComponent($uri->getQuery(), $regex, $callback)) + ->withFragment(self::normalizePercentEncodingInComponent($uri->getFragment(), $regex, $callback)); + } + + /** + * Writes the given path only when it differs from the current one, guarded + * so the write cannot throw. + */ + private static function withGuardedPath(UriInterface $uri, string $path): UriInterface + { + if ($path === Uri::rawPath($uri)) { + return $uri; + } + + return $uri->withPath(UriResolver::guardedPath($uri, $path)); + } + + /** + * @param callable(array): string $callback + */ + private static function withNormalizedUserInfo(UriInterface $uri, string $regex, callable $callback): UriInterface + { + $userInfo = $uri->getUserInfo(); + + if (!str_contains($userInfo, '%')) { + return $uri; + } + + $normalized = self::normalizePercentEncodingInComponent($userInfo, $regex, $callback); + + if ($normalized === $userInfo) { + return $uri; + } + + // Normalization cannot create a colon: decoding is confined to + // unreserved characters and capitalization keeps octets encoded. So + // splitting on the first colon preserves the user/password boundary. + $parts = explode(':', $normalized, 2); + + // PSR-7 defines withUserInfo('') as removing the userinfo, so a + // userinfo with an empty user segment (e.g. ":pass") cannot be + // expressed through the setter and is preserved as-is instead. + if ($parts[0] === '') { + return $uri; + } + + $candidate = $uri->withUserInfo($parts[0], $parts[1] ?? null); + + // Normalization must never lose or corrupt information, so verify the + // representation the setter returned and leave the component untouched + // when the implementation cannot represent the normalized form. + if ($candidate->getUserInfo() !== $normalized) { + return $uri; + } + + return $candidate; + } + + /** + * @param callable(array): string $callback + */ + private static function withNormalizedHost(UriInterface $uri, string $regex, callable $callback): UriInterface + { + $host = $uri->getHost(); + + // Bracketed IP-literal hosts are skipped as a legacy tolerance for + // nonstandard values other implementations may carry, such as a zone + // identifier in "[fe80::1%25eth0]"; that text was briefly valid URI + // syntax under RFC 6874, which RFC 9844 obsoleted and reverted. + if (str_starts_with($host, '[') || !str_contains($host, '%')) { + return $uri; + } + + $normalized = self::normalizePercentEncodingInComponent($host, $regex, $callback); + + if ($normalized === $host) { + return $uri; + } + + $candidate = $uri->withHost($normalized); + + // Normalization must never lose or corrupt information, so verify the + // representation the setter returned and leave the component untouched + // when the implementation cannot represent the normalized form. + if ($candidate->getHost() !== $normalized) { + return $uri; + } + + return $candidate; + } + + /** + * @param callable(array): string $callback + */ + private static function normalizePercentEncodingInComponent(string $component, string $regex, callable $callback): string + { + // Decoding a valid triplet that follows a dangling "%" would complete + // the malformed sequence into a new valid triplet ("example%6%31com" + // becomes "example%61com"), turning malformed text valid and breaking + // idempotence, so a component containing malformed percent syntax is + // returned unchanged. + $malformed = preg_match('/%(?!'.Rfc3986::HEX_OCTET.')/', $component); + + if ($malformed === false) { + throw new \RuntimeException('Unable to scan URI component percent-encoding: '.preg_last_error_msg()); + } + + if ($malformed === 1) { + return $component; + } + + $normalized = preg_replace_callback($regex, $callback, $component); + + if ($normalized === null) { + throw new \RuntimeException('Unable to normalize URI component percent-encoding: '.preg_last_error_msg()); + } + + return $normalized; + } + + private static function canonicalizeIpv6Host(UriInterface $uri): UriInterface + { + $host = $uri->getHost(); + if (!str_starts_with($host, '[') || !str_ends_with($host, ']')) { + return $uri; + } + + // Foreign UriInterface implementations may carry IPvFuture literals, + // IPv6 zone identifiers, uppercase text, or invalid spellings; + // tryCanonicalizeIpv6() canonicalizes only what is unambiguously an + // IPv6 address and leaves everything else untouched. + $canonical = Rfc3986::tryCanonicalizeIpv6(substr($host, 1, -1)); + if ($canonical === null || '['.$canonical.']' === $host) { + return $uri; + } + + $candidate = $uri->withHost('['.$canonical.']'); + // Normalization must never corrupt a component, so keep the original + // host when the implementation does not retain the canonical form. + if ($candidate->getHost() !== '['.$canonical.']') { + return $uri; + } + + return $candidate; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriParser.php b/vendor/guzzlehttp/psr7/src/UriParser.php new file mode 100644 index 0000000..53a09e2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriParser.php @@ -0,0 +1,173 @@ +getUserInfo() === '' ? $uri : $uri->withUserInfo('***'); + } + + /** + * Redacts the userinfo of a raw URI string wherever it appears in a + * subject string. + * + * The needle is taken verbatim from the raw URI rather than from parsed + * components, so credentials that URI normalization would rewrite, such + * as raw control bytes or unencoded reserved characters, are still found + * in text that embeds the URI exactly as given, for example transport + * error messages. A URI without "://" is treated as authority-form: a + * host and port with optional userinfo. + * + * A URI that does not parse has no trustworthy authority boundary, so + * everything between any scheme and its last "@" is redacted as a safe-side + * fallback. + * + * @param string $subject Text that may embed the URI + * @param string $uri Raw URI whose userinfo is redacted in the text + */ + public static function redactUserInfoInString(string $subject, string $uri): string + { + if (\strpos($uri, '@') === false) { + return $subject; + } + + $schemePosition = \strpos($uri, '://'); + $remainder = $schemePosition === false ? $uri : \substr($uri, $schemePosition + 3); + + if (\parse_url($schemePosition === false ? 'http://'.$uri : $uri) === false) { + // Raw '/', '?', or '#' separators may sit inside the credentials + // of a URI that defeats parse_url(), so the redaction cannot stop + // at the apparent authority. + $atPosition = \strrpos($remainder, '@'); + + if ($atPosition === false || $atPosition === 0) { + return $subject; + } + + return \str_replace(\substr($remainder, 0, $atPosition).'@', '***@', $subject); + } + + $authority = \substr($remainder, 0, \strcspn($remainder, '/?#')); + $atPosition = \strrpos($authority, '@'); + + if ($atPosition === false || $atPosition === 0) { + // A parseable URI with '@' only past its authority, or with an + // empty userinfo, carries no credentials to redact. + return $subject; + } + + return \str_replace(\substr($authority, 0, $atPosition).'@', '***@', $subject); + } + + /** + * Formats a URI for automatic diagnostics. + * + * The whole userinfo component is replaced by "***", and the query and + * fragment are removed. The scheme, host, port, and path are preserved. + * The returned string is diagnostic-escaped and the formatter never + * throws. + */ + public static function redactUriForMessage( + #[\SensitiveParameter] + UriInterface $uri + ): string { + try { + $raw = (string) $uri; + } catch (\Throwable $e) { + return '[unavailable URI]'; + } + + try { + if ($uri->getUserInfo() !== '') { + $uri = $uri->withUserInfo('***'); + } + + return DiagnosticValue::escape((string) $uri->withQuery('')->withFragment('')); + } catch (\Throwable $e) { + return self::redactUriStringForMessage($raw); + } + } + + /** + * Formats a raw URI for automatic diagnostics, including malformed input. + * + * The whole userinfo component is replaced by "***", and the query and + * fragment are removed. The scheme, host, port, and path are preserved + * where their boundaries can be determined safely. The returned string is + * diagnostic-escaped and the formatter never throws. + */ + public static function redactUriStringForMessage( + #[\SensitiveParameter] + string $uri + ): string { + try { + $uri = self::redactUserInfoInString($uri, $uri); + + return DiagnosticValue::escape(\substr($uri, 0, \strcspn($uri, '?#'))); + } catch (\Throwable $e) { + return '[unavailable URI]'; + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriResolver.php b/vendor/guzzlehttp/psr7/src/UriResolver.php new file mode 100644 index 0000000..ca0a556 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriResolver.php @@ -0,0 +1,309 @@ + $floor) { + array_pop($results); + } + } elseif ($segment !== '.') { + $results[] = $segment; + } + } + + $newPath = implode('/', $results); + + if (str_starts_with($path, '/') && !str_starts_with($newPath, '/')) { + // Re-add the leading slash if necessary for cases like "/.." + $newPath = '/'.$newPath; + } elseif ($newPath !== '' && ($segment === '.' || $segment === '..')) { + // Add the trailing slash if necessary + // If newPath is not empty, then $segment must be set and is the last segment from the foreach + $newPath .= '/'; + } + + return $newPath; + } + + /** + * Returns the path, prefixed with "/." or "./" when the URI could not + * otherwise hold it. + * + * A URI without an authority cannot hold a path beginning with "//" (RFC + * 3986 Section 3.3), but removeDotSegments() can produce one. The "/." + * prefix serializes such a path unambiguously, the same way the WHATWG URL + * Standard does, and resolves back to the same path. Hostless http and + * https Uri instances gain the default localhost host when the path is + * written, so the path cannot be mistaken for an authority and the prefix + * is not added. + * + * A relative-path reference cannot begin with a segment containing a colon + * (RFC 3986 Section 4.2), as it would be mistaken for a scheme name, but + * reference resolution and percent-encoding normalization can produce one. + * The "./" prefix the RFC prescribes resolves back to the same path. + * + * @see https://url.spec.whatwg.org/#url-serializing + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + * + * @internal + */ + public static function guardedPath(UriInterface $uri, string $path): string + { + if ($uri->getAuthority() !== '') { + return $path; + } + + if (str_starts_with($path, '//')) { + if ($uri instanceof Uri && ($uri->getScheme() === 'http' || $uri->getScheme() === 'https')) { + return $path; + } + + return '/.'.$path; + } + + if ($uri->getScheme() === '' && str_contains(explode('/', $path, 2)[0], ':')) { + return './'.$path; + } + + return $path; + } + + /** + * Converts the relative URI into a new URI that is resolved against the + * base URI. + * + * When the resolved path is a relative-path reference whose first segment + * contains a colon, which would be mistaken for a scheme name (RFC 3986 + * Section 4.2), it is prefixed with `./`, e.g. `./a:b`. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2 + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function resolve(UriInterface $base, UriInterface $rel): UriInterface + { + if ((string) $rel === '') { + // we can simply return the same base URI instance for this same-document reference + return $base; + } + + if ($rel->getScheme() != '') { + return $rel->withPath(self::guardedPath($rel, self::removeDotSegments(Uri::rawPath($rel)))); + } + + if ($rel->getAuthority() != '') { + return $rel + ->withScheme($base->getScheme()) + ->withPath(self::removeDotSegments(Uri::rawPath($rel))); + } + + $relPath = Uri::rawPath($rel); + + if ($relPath === '') { + // the base path is used as-is per RFC 3986 Section 5.2.2, so it must not be + // rewritten through a getPath()/withPath() round-trip + return $base + ->withQuery($rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery()) + ->withFragment($rel->getFragment()); + } + + if (str_starts_with($relPath, '/')) { + $targetPath = $relPath; + } else { + $basePath = Uri::rawPath($base); + if ($base->getAuthority() != '' && $basePath === '') { + $targetPath = '/'.$relPath; + } else { + $lastSlashPos = strrpos($basePath, '/'); + if ($lastSlashPos === false) { + $targetPath = $relPath; + } else { + $targetPath = substr($basePath, 0, $lastSlashPos + 1).$relPath; + } + } + } + $targetPath = self::removeDotSegments($targetPath); + + return $base + ->withPath(self::guardedPath($base, $targetPath)) + ->withQuery($rel->getQuery()) + ->withFragment($rel->getFragment()); + } + + /** + * Returns the target URI as a relative reference from the base URI. + * + * This method is the counterpart to `resolve()`: + * + * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) + * + * One use case is to use the current request URI as the base URI and then + * generate relative links in your documents to reduce the document size or + * offer self-contained downloadable document archives. + * + * $base = new Uri('http://example.com/a/b/'); + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. + * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. + * echo UriResolver::relativize($base, new Uri('http://example.com')); // prints '//example.com'. + * + * This method also accepts a target that is already relative and will try + * to relativize it further. Only a relative-path reference will be returned + * as-is. + * + * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well + */ + public static function relativize(UriInterface $base, UriInterface $target): UriInterface + { + if ($target->getScheme() !== '' + && ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') + ) { + return $target; + } + + if (Uri::isRelativePathReference($target)) { + // As the target is already highly relative we return it as-is. It would be possible to resolve + // the target with `$target = self::resolve($base, $target);` and then try make it more relative + // by removing a duplicate query. But let's not do that automatically. + return $target; + } + + if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { + return $target->withScheme(''); + } + + // A same-authority target with an empty path can only be expressed by a + // network-path reference (RFC 3986 Section 5.2.2). + if (self::needsNetworkPathReference($base, $target)) { + return $target->withScheme(''); + } + + // We must remove the path before removing the authority because if the path starts with two slashes, the URI + // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also + // invalid. + $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); + + if (Uri::rawPath($base) !== Uri::rawPath($target)) { + return $emptyPathUri->withPath(self::getRelativePath($base, $target)); + } + + if ($base->getQuery() === $target->getQuery() && ($target->getFragment() !== '' || $base->getFragment() === '')) { + // Only the target fragment is left. And it must be returned even if base and target fragment are the same. + return $emptyPathUri->withQuery(''); + } + + // If the base URI has a query or fragment that the target lacks, we cannot return an empty path + // reference as it would inherit that base component when resolving. + if ($target->getQuery() === '') { + $segments = explode('/', Uri::rawPath($target)); + /** @var string $lastSegment */ + $lastSegment = end($segments); + + // A reference to an empty last segment must be prefixed with "./". The same applies + // to a segment with a colon character, which would be mistaken for a scheme name. + if ($lastSegment === '' || str_contains($lastSegment, ':')) { + $lastSegment = "./$lastSegment"; + } + + return $emptyPathUri->withPath($lastSegment); + } + + return $emptyPathUri; + } + + /** + * Whether relativizing to $target requires a network-path reference. + * + * A same-authority target with an empty path is expressible by a shorter + * relative reference unless resolving one would inherit a base component + * the target lacks: the base path (kept by any empty-path reference), or + * the base query or fragment (inherited by the empty reference). + */ + private static function needsNetworkPathReference(UriInterface $base, UriInterface $target): bool + { + if ($target->getAuthority() === '' || Uri::rawPath($target) !== '') { + return false; + } + + return Uri::rawPath($base) !== '' + || ($base->getQuery() !== '' && $target->getQuery() === '') + || ($base->getFragment() !== '' && $target->getFragment() === '' && $base->getQuery() === $target->getQuery()); + } + + private static function getRelativePath(UriInterface $base, UriInterface $target): string + { + $sourceSegments = explode('/', Uri::rawPath($base)); + $targetSegments = explode('/', Uri::rawPath($target)); + array_pop($sourceSegments); + $targetLastSegment = array_pop($targetSegments); + foreach ($sourceSegments as $i => $segment) { + if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { + unset($sourceSegments[$i], $targetSegments[$i]); + } else { + break; + } + } + $targetSegments[] = $targetLastSegment; + $relativePath = str_repeat('../', count($sourceSegments)).implode('/', $targetSegments); + + // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. + if ($relativePath === '' || str_contains(explode('/', $relativePath, 2)[0], ':')) { + $relativePath = "./$relativePath"; + } elseif (str_starts_with($relativePath, '/')) { + if ($base->getAuthority() != '' && Uri::rawPath($base) === '') { + // In this case an extra slash is added by resolve() automatically. So we must not add one here. + $relativePath = ".$relativePath"; + } else { + $relativePath = "./$relativePath"; + } + } + + return $relativePath; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/psr7/src/Utils.php b/vendor/guzzlehttp/psr7/src/Utils.php new file mode 100644 index 0000000..f0b55de --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Utils.php @@ -0,0 +1,903 @@ + $keys + */ + public static function caselessRemove(array $keys, array $data): array + { + $result = []; + + foreach ($keys as &$key) { + $key = self::asciiToLower((string) $key); + } + + foreach ($data as $k => $v) { + if (!in_array(self::asciiToLower((string) $k), $keys)) { + $result[$k] = $v; + } + } + + return $result; + } + + /** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read, returning the number of bytes copied as an + * `int`. On 32-bit PHP, an unbounded copy larger than `PHP_INT_MAX` bytes + * cannot be represented by that return type. 64-bit PHP is not affected. + * + * The destination must accept writes that make positive progress. Streams + * that return 0 as a backpressure or drop signal (a `BufferStream` at its + * high water mark, or a full `DroppingStream`) will cause this method to + * throw. For full copies, use a normal writable stream such as a file or + * `php://temp` stream. + * + * Throws `TimeoutException` when PHP-style timeout metadata can be detected + * after a source read or destination write cannot make progress. + * + * When a source read times out, the bytes copied before it remain in the + * destination. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): int + { + $bufferSize = 8192; + $copied = 0; + + if ($maxLen === -1) { + while (!$source->eof()) { + $buf = StreamTimeout::read($source, $bufferSize, 'Unable to read from stream: timed out'); + if ($buf === '') { + break; + } + + self::writeAll($dest, $buf); + $copied = Integers::add($copied, strlen($buf)); + } + } else { + $remaining = $maxLen; + while ($remaining > 0 && !$source->eof()) { + $buf = StreamTimeout::read($source, min($bufferSize, $remaining), 'Unable to read from stream: timed out'); + $len = strlen($buf); + if (!$len) { + break; + } + $remaining -= $len; + self::writeAll($dest, $buf); + $copied = Integers::add($copied, $len); + } + } + + return $copied; + } + + private static function writeAll(StreamInterface $dest, string $buf): void + { + $written = 0; + $len = strlen($buf); + + while ($written < $len) { + try { + $result = $dest->write(substr($buf, $written)); + } catch (TimeoutException $e) { + throw $e; + } catch (\RuntimeException $e) { + StreamTimeout::throwIfWriteTimedOut($dest, $e); + + throw $e; + } + + if ($result <= 0) { + StreamTimeout::throwIfWriteTimedOut($dest); + + throw new \RuntimeException('Unable to write to stream'); + } + + $written += $result; + } + } + + /** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * Throws `TimeoutException` when PHP-style timeout metadata can be detected + * after a stream read cannot make progress. + * + * The bytes read before a timeout are discarded, so calling this method + * again does not return them. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToString(StreamInterface $stream, int $maxLen = -1): string + { + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = StreamTimeout::read($stream, 1048576, 'Unable to read from stream: timed out'); + if ($buf === '') { + break; + } + $buffer .= $buf; + } + + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = StreamTimeout::read($stream, $maxLen - $len, 'Unable to read from stream: timed out'); + if ($buf === '') { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; + } + + /** + * Calculate a hash of a stream. + * + * This method reads the entire stream to calculate a rolling hash, based on + * PHP's `hash_init` functions. + * + * Throws `TimeoutException` when PHP-style timeout metadata can be detected + * after a stream read cannot make progress. + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @throws \RuntimeException on error. + */ + public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string + { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + $buf = StreamTimeout::read($stream, 1048576, 'Unable to calculate stream hash: timed out'); + if ($buf === '') { + break; + } + + hash_update($ctx, $buf); + } + + $out = hash_final($ctx, $rawOutput); + $stream->seek($pos); + + return $out; + } + + /** + * Clone and modify a request with the given changes. + * + * This method is useful for reducing the number of clones needed to mutate + * a message. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. Values must be strings + * or non-empty arrays of strings. + * - remove_headers: (array) Remove the given headers. Values may be + * strings or integers. + * - body: (mixed) Sets the given body. Present non-null values are + * converted with self::streamFor(), including resources, streams, + * iterators, callable arrays, closures, invokable objects, and stringable + * objects. String inputs remain literal bodies. + * - uri: (UriInterface) Set the URI. When the URI contains a host, the + * Host header is updated from it, and combining this with an explicit + * Host entry in set_headers throws an InvalidArgumentException. Apply + * an intentional Host override separately with withHeader() afterwards. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array{ + * method?: string, + * set_headers?: array>, + * remove_headers?: array, + * body?: resource|string|StreamInterface|callable|\Iterator|\Stringable, + * uri?: UriInterface, + * query?: string, + * version?: string + * } $changes Changes to apply. + */ + public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface + { + if (!$changes) { + return $request; + } + + self::assertValidModifyRequestChanges($changes); + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + /** @var UriInterface */ + $uri = $changes['uri']; + + $host = $uri->getHost(); + if ($host !== '') { + Uri::assertValidHost($host); + + // A Uri has already raised the deprecation for its own host. + if (!$uri instanceof Uri) { + Uri::deprecateNonAsciiHost($host); + } + + if (isset($changes['set_headers']) && is_array($changes['set_headers'])) { + foreach (array_keys($changes['set_headers']) as $header) { + if (self::asciiToLower((string) $header) === 'host') { + throw new \InvalidArgumentException( + 'Cannot modify request with both a URI containing a host and an explicit Host header.' + ); + } + } + } + + $changes['set_headers']['Host'] = $host; + + $port = $uri->getPort(); + if ($port !== null) { + $standardPorts = ['http' => 80, 'https' => 443]; + $scheme = $uri->getScheme(); + if (!isset($standardPorts[$scheme]) || $port != $standardPorts[$scheme]) { + $changes['set_headers']['Host'] .= ':'.$port; + } + } + } + } + + if (!empty($changes['remove_headers'])) { + $headers = self::caselessRemove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + $hasHost = false; + foreach (array_keys($headers) as $header) { + if (self::asciiToLower((string) $header) === 'host') { + $hasHost = true; + break; + } + } + + // Match Request::__construct() by adding a Host header when one is not provided. + if (!$hasHost && $uri->getHost() !== '') { + $host = $uri->getHost(); + Uri::assertValidHost($host); + + // A Uri has already raised the deprecation for its own host. + if (!$uri instanceof Uri) { + Uri::deprecateNonAsciiHost($host); + } + + if (($port = $uri->getPort()) !== null) { + $host .= ':'.$port; + } + + $headers = ['Host' => [$host]] + $headers; + } + + $new = $request; + + if (isset($changes['method'])) { + $new = $new->withMethod($changes['method']); + } + + if (isset($changes['uri']) || isset($changes['query'])) { + $new = $new->withUri($uri, true); + } + + if ($headers !== $new->getHeaders()) { + foreach (array_keys($new->getHeaders()) as $header) { + /** @var RequestInterface */ + $new = $new->withoutHeader((string) $header); + } + + $addedHeaders = []; + foreach ($headers as $header => $value) { + $header = (string) $header; + $normalized = self::asciiToLower($header); + + if (isset($addedHeaders[$normalized])) { + /** @var RequestInterface */ + $new = $new->withAddedHeader($addedHeaders[$normalized], $value); + } else { + /** @var RequestInterface */ + $new = $new->withHeader($header, $value); + $addedHeaders[$normalized] = $header; + } + } + } + + if (isset($changes['body'])) { + /** @var RequestInterface */ + $new = $new->withBody(self::streamFor($changes['body'])); + } + + if (isset($changes['version'])) { + /** @var RequestInterface */ + $new = $new->withProtocolVersion($changes['version']); + } + + return $new; + } + + /** + * @param array $changes + */ + private static function assertValidModifyRequestChanges(array $changes): void + { + foreach (['method', 'query', 'version'] as $key) { + if (\array_key_exists($key, $changes) && !\is_string($changes[$key])) { + self::assertValidModifyRequestChange($key, 'string', $changes[$key]); + } + } + + if (\array_key_exists('uri', $changes) && !$changes['uri'] instanceof UriInterface) { + self::assertValidModifyRequestChange('uri', 'UriInterface', $changes['uri']); + } + + if (\array_key_exists('body', $changes) && $changes['body'] === null) { + self::assertValidModifyRequestChange('body', 'resource|string|StreamInterface|callable|\Iterator|\Stringable', $changes['body']); + } + + if (\array_key_exists('set_headers', $changes)) { + if (!\is_array($changes['set_headers'])) { + self::assertValidModifyRequestChange('set_headers', 'array>', $changes['set_headers']); + } else { + foreach ($changes['set_headers'] as $header => $value) { + $headerPath = \sprintf('set_headers.%s', (string) $header); + + if (\is_array($value)) { + if ($value === []) { + self::assertValidModifyRequestChange($headerPath, 'string|non-empty-array', $value); + + break; + } + + foreach ($value as $index => $item) { + if (!\is_string($item)) { + self::assertValidModifyRequestChange(\sprintf('%s.%s', $headerPath, (string) $index), 'string', $item); + + break 2; + } + } + } elseif (!\is_string($value)) { + self::assertValidModifyRequestChange($headerPath, 'string|non-empty-array', $value); + + break; + } + } + } + } + + if (!\array_key_exists('remove_headers', $changes)) { + return; + } + + if (!\is_array($changes['remove_headers'])) { + self::assertValidModifyRequestChange('remove_headers', 'array', $changes['remove_headers']); + + return; + } + + foreach ($changes['remove_headers'] as $index => $header) { + if (!\is_string($header) && !\is_int($header)) { + self::assertValidModifyRequestChange(\sprintf('remove_headers.%s', (string) $index), 'string|int', $header); + + return; + } + } + } + + /** + * @param mixed $value + */ + private static function assertValidModifyRequestChange(string $key, string $expected, $value): void + { + throw new \InvalidArgumentException(\sprintf('Utils::modifyRequest() change "%s" must be %s; %s provided.', DiagnosticValue::escape($key), $expected, \get_debug_type($value))); + } + + /** + * Read a line from the stream up to the maximum allowed buffer length. + * + * Throws `TimeoutException` when PHP-style timeout metadata can be detected + * after a stream read cannot make progress. + * + * The bytes read before a timeout are discarded, so calling this method + * again does not return them. + * + * @param StreamInterface $stream Stream to read from + * @param int|null $maxLength Maximum buffer length + */ + public static function readLine(StreamInterface $stream, ?int $maxLength = null): string + { + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + if ('' === ($byte = StreamTimeout::read($stream, 1, 'Unable to read line from stream: timed out'))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte === "\n" || ++$size === $maxLength - 1) { + break; + } + } + + return $buffer; + } + + /** + * Redact the user info part of a URI. + * + * Returns the URI with the whole userinfo component replaced by "***" + * when one is present, so neither the username nor the password survives + * into logs and diagnostics. A URI without userinfo is returned + * unchanged. + * + * @deprecated Utils::redactUserInfo() will be removed in + * guzzlehttp/psr7:4.0. Use UriRedactor::redactUserInfo() + * instead. + */ + public static function redactUserInfo( + #[\SensitiveParameter] + UriInterface $uri + ): UriInterface { + \trigger_deprecation( + 'guzzlehttp/psr7', + '3.4', + '%s() is deprecated and will be removed in 4.0. Use %s::redactUserInfo() instead.', + __METHOD__, + UriRedactor::class + ); + + return UriRedactor::redactUserInfo($uri); + } + + /** + * Redacts the userinfo of a raw URI string wherever it appears in a + * subject string. + * + * The needle is taken verbatim from the raw URI rather than from parsed + * components, so credentials that URI normalization would rewrite, such + * as raw control bytes or unencoded reserved characters, are still found + * in text that embeds the URI exactly as given, for example transport + * error messages. A URI without "://" is treated as authority-form: a + * host and port with optional userinfo. + * + * A URI that does not parse has no trustworthy authority boundary, so + * everything between any scheme and its last "@" is redacted as a safe-side + * fallback. + * + * @param string $subject Text that may embed the URI + * @param string $uri Raw URI whose userinfo is redacted in the text + * + * @deprecated Utils::redactUserInfoInString() will be removed in + * guzzlehttp/psr7:4.0. Use + * UriRedactor::redactUserInfoInString() instead. + */ + public static function redactUserInfoInString(string $subject, string $uri): string + { + \trigger_deprecation( + 'guzzlehttp/psr7', + '3.4', + '%s() is deprecated and will be removed in 4.0. Use %s::redactUserInfoInString() instead.', + __METHOD__, + UriRedactor::class + ); + + return UriRedactor::redactUserInfoInString($subject, $uri); + } + + /** + * Formats a URI for automatic diagnostics. + * + * The whole userinfo component is replaced by "***", and the query and + * fragment are removed. The scheme, host, port, and path are preserved. + * The returned string is diagnostic-escaped and the formatter never + * throws. + * + * @deprecated Utils::redactUriForMessage() will be removed in + * guzzlehttp/psr7:4.0. Use UriRedactor::redactUriForMessage() + * instead. + */ + public static function redactUriForMessage( + #[\SensitiveParameter] + UriInterface $uri + ): string { + \trigger_deprecation( + 'guzzlehttp/psr7', + '3.4', + '%s() is deprecated and will be removed in 4.0. Use %s::redactUriForMessage() instead.', + __METHOD__, + UriRedactor::class + ); + + return UriRedactor::redactUriForMessage($uri); + } + + /** + * Formats a raw URI for automatic diagnostics, including malformed input. + * + * The whole userinfo component is replaced by "***", and the query and + * fragment are removed. The scheme, host, port, and path are preserved + * where their boundaries can be determined safely. The returned string is + * diagnostic-escaped and the formatter never throws. + * + * @deprecated Utils::redactUriStringForMessage() will be removed in + * guzzlehttp/psr7:4.0. Use + * UriRedactor::redactUriStringForMessage() instead. + */ + public static function redactUriStringForMessage( + #[\SensitiveParameter] + string $uri + ): string { + \trigger_deprecation( + 'guzzlehttp/psr7', + '3.4', + '%s() is deprecated and will be removed in 4.0. Use %s::redactUriStringForMessage() instead.', + __METHOD__, + UriRedactor::class + ); + + return UriRedactor::redactUriStringForMessage($uri); + } + + /** + * Create a new stream based on the input type. + * + * Options are provided as an associative array that can contain the + * following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * This method accepts the following `$resource` types: + * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. + * - `string`: Creates a stream object that uses the given string as the + * contents. + * - `resource`: Creates a stream object that wraps the given PHP stream + * resource. + * - `Iterator`: If the provided value implements `Iterator`, then a + * read-only stream object will be created that wraps the given iterable. + * Each time the stream is read from, data from the iterator will fill a + * buffer and will be continuously called until the buffer is equal to the + * requested read size. Yielded strings, integers, finite floats, + * booleans, `null`, and stringable objects are converted to string + * chunks; non-finite floats and other values throw + * `UnexpectedValueException` when the stream is read. Values that + * stringify to an empty string are skipped while the iterator advances. + * Subsequent read calls will first read from the buffer and then call + * `next` on the underlying iterator until it is exhausted. + * - `object` with `__toString()`: If the object has the `__toString()` + * method, the object will be cast to a string and then a stream will be + * returned that uses the string value. + * - `NULL`: When `null` is passed, an empty stream object is returned. + * - `callable`: When a callable array, closure, or invokable object is + * passed and no earlier resource or object rule applies, a read-only + * stream object will be created that invokes the given callable. The + * callable is invoked with the suggested number of bytes to read. The + * callable can return fewer or more bytes than requested, but MUST return + * a non-empty string to provide data and MUST return `false` or `null` + * when there is no more data to return. Any additional bytes will be + * buffered and used in subsequent reads. String inputs are always treated + * as string bodies, even when they name callable functions. + * + * @param resource|string|StreamInterface|callable|\Iterator|\Stringable|null $resource Entity body data + * @param array{size?: int, metadata?: array} $options Additional options + * + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ + public static function streamFor($resource = '', array $options = []): StreamInterface + { + if (is_scalar($resource)) { + if (!is_string($resource)) { + throw new \InvalidArgumentException(\sprintf( + 'Cannot create a stream from %s; pass a string, resource, StreamInterface, Stringable, Iterator, callable, or null.', + \get_debug_type($resource) + )); + } + + $stream = self::tryFopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, $resource); + fseek($stream, 0); + } + + return new Stream($stream, $options); + } + + switch (gettype($resource)) { + case 'resource': + /* + * The 'php://input' is a special stream with quirks and inconsistencies. + * We avoid using that stream by reading it into php://temp + */ + + /** @var resource $resource */ + if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') { + $stream = self::tryFopen('php://temp', 'w+'); + stream_copy_to_stream($resource, $stream); + fseek($stream, 0); + $resource = $stream; + } + + return new Stream($resource, $options); + case 'object': + /** @var object $resource */ + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function (int $length) use ($resource) { + while ($resource->valid()) { + $result = $resource->current(); + $resource->next(); + + if (is_float($result) && !is_finite($result)) { + throw new \UnexpectedValueException('Iterator must not yield non-finite float values'); + } + + if ($result === null || is_scalar($result)) { + $data = (string) $result; + } elseif (is_object($result) && method_exists($result, '__toString')) { + $data = (string) $result; + } else { + throw new \UnexpectedValueException('Iterator must yield scalar, null, or stringable values'); + } + + if ($data !== '') { + return $data; + } + } + + return false; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return self::streamFor((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(self::tryFopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: '.\get_debug_type($resource)); + } + + /** + * Safely opens a PHP stream resource using a filename. + * + * When `fopen()` fails, PHP normally raises a warning. This function adds + * an error handler that checks for errors and throws an exception instead. + * Deprecations, and errors silenced inside the call with the `@` operator, + * are not failures and are passed on to the previously installed error + * handler. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * + * @throws \RuntimeException if the file cannot be opened + */ + public static function tryFopen(string $filename, string $mode) + { + $ex = null; + $scope = new ErrorScope(\E_ALL & ~\E_DEPRECATED & ~\E_USER_DEPRECATED, false); + $handle = $scope->run(static function () use ($filename, $mode, &$ex) { + try { + return fopen($filename, $mode); + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf('Unable to open %s using mode %s: %s', DiagnosticValue::escape($filename), DiagnosticValue::escape($mode), $e->getMessage()), 0, $e); + } + + return false; + }); + + if ($ex === null && $scope->getError() !== null) { + $ex = new \RuntimeException(sprintf('Unable to open %s using mode %s: %s', DiagnosticValue::escape($filename), DiagnosticValue::escape($mode), DiagnosticValue::escape($scope->getError()))); + } + + if ($ex) { + throw $ex; + } + + /** @var resource $handle */ + return $handle; + } + + /** + * Safely gets the contents of a given stream. + * + * When `stream_get_contents()` fails, PHP normally raises a warning. This + * function adds an error handler that checks for errors and throws an + * exception instead. Deprecations, and errors silenced inside the call with + * the `@` operator, are not failures and are passed on to the previously + * installed error handler. + * + * Throws `TimeoutException` when PHP-style timeout metadata can be detected + * after a stream read cannot make progress. + * + * The bytes read before a timeout are discarded, so calling this method + * again does not return them. + * + * @param resource $stream + * + * @throws \RuntimeException if the stream cannot be read + */ + public static function tryGetContents($stream): string + { + $ex = null; + $scope = new ErrorScope(\E_ALL & ~\E_DEPRECATED & ~\E_USER_DEPRECATED, false); + $contents = $scope->run(static function () use ($stream, &$ex) { + try { + /** @var string|false $contents */ + $contents = stream_get_contents($stream); + + if ($contents === false) { + $ex = StreamTimeout::isResourceReadTimedOut($stream) + ? new TimeoutException('Unable to read stream contents: timed out') + : new \RuntimeException('Unable to read stream contents'); + } elseif (StreamTimeout::isResourceReadTimedOut($stream)) { + $ex = new TimeoutException('Unable to read stream contents: timed out'); + } + + return $contents; + } catch (TimeoutException $e) { + $ex = $e; + } catch (\Throwable $e) { + $ex = StreamTimeout::isResourceReadTimedOut($stream) + ? new TimeoutException('Unable to read stream contents: timed out', 0, $e) + : new \RuntimeException(sprintf('Unable to read stream contents: %s', $e->getMessage()), 0, $e); + } + + return false; + }); + + if ($ex === null && $scope->getError() !== null) { + $ex = new \RuntimeException(sprintf('Unable to read stream contents: %s', DiagnosticValue::escape($scope->getError()))); + } + + if ($ex) { + /** @var \RuntimeException $ex */ + throw $ex; + } + + /** @var string $contents */ + return $contents; + } + + /** + * Returns a `UriInterface` for the given value. + * + * This function accepts a string or `UriInterface` and returns a + * `UriInterface` for the given value. If the value is already a + * `UriInterface`, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @throws \InvalidArgumentException + */ + public static function uriFor($uri): UriInterface + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/vendor/league/commonmark/.phpstorm.meta.php b/vendor/league/commonmark/.phpstorm.meta.php new file mode 100644 index 0000000..8d93c7c --- /dev/null +++ b/vendor/league/commonmark/.phpstorm.meta.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace PHPSTORM_META +{ + expectedArguments(\League\CommonMark\Util\HtmlElement::__construct(), 0, 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kdb', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr'); + + expectedArguments(\League\CommonMark\Extension\CommonMark\Node\Block\Heading::__construct(), 0, 1, 2, 3, 4, 5, 6); + expectedReturnValues(\League\CommonMark\Extension\CommonMark\Node\Block\Heading::getLevel(), 1, 2, 3, 4, 5, 6); + + registerArgumentsSet('league_commonmark_htmlblock_types', \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_1_CODE_CONTAINER, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_2_COMMENT, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_3, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_4, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_5_CDATA, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_6_BLOCK_ELEMENT, \League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::TYPE_7_MISC_ELEMENT); + expectedArguments(\League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::__construct(), 0, argumentsSet('league_commonmark_htmlblock_types')); + expectedArguments(\League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::setType(), 0, argumentsSet('league_commonmark_htmlblock_types')); + expectedReturnValues(\League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock::getType(), argumentsSet('league_commonmark_htmlblock_types')); + expectedArguments(\League\CommonMark\Util\RegexHelper::getHtmlBlockOpenRegex(), 0, argumentsSet('league_commonmark_htmlblock_types')); + expectedArguments(\League\CommonMark\Util\RegexHelper::getHtmlBlockCloseRegex(), 0, argumentsSet('league_commonmark_htmlblock_types')); + + registerArgumentsSet('league_commonmark_newline_types', \League\CommonMark\Node\Inline\Newline::HARDBREAK, \League\CommonMark\Node\Inline\Newline::SOFTBREAK); + expectedArguments(\League\CommonMark\Node\Inline\Newline::__construct(), 0, argumentsSet('league_commonmark_newline_types')); + expectedReturnValues(\League\CommonMark\Node\Inline\Newline::getType(), argumentsSet('league_commonmark_newline_types')); + + registerArgumentsSet('league_commonmark_options', + 'html_input', + 'allow_unsafe_links', + 'max_nesting_level', + 'max_delimiters_per_line', + 'renderer', + 'renderer/block_separator', + 'renderer/inner_separator', + 'renderer/soft_break', + 'xml', + 'xml/max_indentation_level', + 'commonmark', + 'commonmark/enable_em', + 'commonmark/enable_strong', + 'commonmark/use_asterisk', + 'commonmark/use_underscore', + 'commonmark/unordered_list_markers', + 'disallowed_raw_html', + 'disallowed_raw_html/disallowed_tags', + 'external_link', + 'external_link/html_class', + 'external_link/internal_hosts', + 'external_link/nofollow', + 'external_link/noopener', + 'external_link/noreferrer', + 'external_link/open_in_new_window', + 'footnote', + 'footnote/backref_class', + 'footnote/backref_symbol', + 'footnote/container_add_hr', + 'footnote/container_class', + 'footnote/ref_class', + 'footnote/ref_id_prefix', + 'footnote/footnote_class', + 'footnote/footnote_id_prefix', + 'heading_permalink', + 'heading_permalink/apply_id_to_heading', + 'heading_permalink/heading_class', + 'heading_permalink/html_class', + 'heading_permalink/fragment_prefix', + 'heading_permalink/id_prefix', + 'heading_permalink/inner_contents', + 'heading_permalink/insert', + 'heading_permalink/max_heading_level', + 'heading_permalink/min_heading_level', + 'heading_permalink/symbol', + 'heading_permalink/title', + 'mentions', + 'smartpunct/double_quote_closer', + 'smartpunct/double_quote_opener', + 'smartpunct/single_quote_closer', + 'smartpunct/single_quote_opener', + 'slug_normalizer', + 'slug_normalizer/instance', + 'slug_normalizer/max_length', + 'slug_normalizer/unique', + 'table', + 'table/wrap', + 'table/wrap/attributes', + 'table/wrap/enabled', + 'table/wrap/tag', + 'table/alignment_attributes', + 'table/alignment_attributes/left', + 'table/alignment_attributes/center', + 'table/alignment_attributes/right', + 'table/max_autocompleted_cells', + 'table_of_contents', + 'table_of_contents/html_class', + 'table_of_contents/max_heading_level', + 'table_of_contents/min_heading_level', + 'table_of_contents/normalize', + 'table_of_contents/placeholder', + 'table_of_contents/position', + 'table_of_contents/style', + ); + expectedArguments(\League\Config\ConfigurationInterface::get(), 0, argumentsSet('league_commonmark_options')); + expectedArguments(\League\Config\ConfigurationInterface::exists(), 0, argumentsSet('league_commonmark_options')); + expectedArguments(\League\Config\MutableConfigurationInterface::set(), 0, argumentsSet('league_commonmark_options')); +} diff --git a/vendor/league/commonmark/CHANGELOG.md b/vendor/league/commonmark/CHANGELOG.md new file mode 100644 index 0000000..cb4fce1 --- /dev/null +++ b/vendor/league/commonmark/CHANGELOG.md @@ -0,0 +1,946 @@ +# Change Log +All notable changes to this project will be documented in this file. +Updates should follow the [Keep a CHANGELOG](https://keepachangelog.com/) principles. + +**Upgrading from 1.x?** See for additional information. + +## [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 ` ['attributes' => [...], 'strict_callables' => true]]`. With `strict_callables` enabled, only closures and invokable objects are treated as callbacks, so strings and arrays are always used as literal attribute values. Callbacks written as string or array callables can be wrapped with `Closure::fromCallable()`. The original format - passing the node map directly - is still accepted, and defaults `strict_callables` to `false`. +- Added a new `slug_normalizer/reserved` option which treats the given slugs as already-used, so colliding headings receive an incremental numeric suffix just like duplicate headings do (#1080) + +### Changed +- Changed the `TableOfContents` extension to render the table of contents once and share it across all placeholders instead of cloning it into each one (#1134) + - A custom renderer registered for the `TableOfContents` node is no longer called once per placeholder, so it must return the same markup each time it is called for a given document (#1134) + - The first placeholder receives the table of contents itself, so a document still contains a `TableOfContents` node for listeners which locate and reposition it (#1143) +- `$environment->getConfiguration()->get('default_attributes')` now returns the normalized structure with `attributes` and `strict_callables` keys instead of the node map; read `default_attributes/attributes` to get the map. Configuration written in either format continues to work unchanged. + +### Deprecated +- Deprecated `RegexHelper::PARTIAL_LINK_TITLE` and `RegexHelper::REGEX_LINK_DESTINATION_BRACES`; use the unanchored variants with an explicit anchor instead +- Deprecated the `default_attributes` `strict_callables` option, which will be removed in 3.0 when only closures and invokable objects will ever be treated as callbacks. + +### Fixed +- Fixed `default_attributes` values which happen to match the name of a PHP function - such as `'class' => 'link'`, `'header'`, `'key'`, `'range'`, or `'current'` - being invoked as callbacks, producing errors like `link() expects exactly 2 arguments, 1 given`. Enable `strict_callables` to treat strings and arrays as literal attribute values (#1123) +- Fixed the `DefaultAttributesExtension` re-testing every configured value with `is_callable()` once per matching node, which asked the autoloader whether the first element of each array value named a real class every single time +- Fixed a `default_attributes` value which PHP treats as callable reporting its failure from inside whichever function it collided with; the error now names the attribute and node class responsible, and keeps the original error as its previous exception +- Fixed custom `UniqueSlugNormalizerInterface` implementations being wrapped by the built-in `UniqueSlugNormalizer` and never receiving the documented `clearHistory()` calls, which caused slug history to leak across documents when `slug_normalizer/unique` was set to `'document'` (#1080) + - Custom implementations are now trusted to enforce uniqueness themselves, per the interface contract; the extra deduplication layer the wrapper used to provide is no longer applied on top of them +- Fixed the `AttributesExtension` re-merging and re-filtering everything a node had already collected each time another attribute node was applied to it, causing long runs of distinctly-named attributes to be resolved in quadratic time, which could be abused to cause a denial of service - this completes the fix for GHSA-jjv6-8j6v-6j52, which covered only the `class` attribute (GHSA-8rr7-cvq3-gmfh) +- Fixed the `AttributesExtension` re-merging everything an attribute block had already collected on each of its continuation lines, causing long runs of distinctly-named attributes on consecutive lines to be resolved in quadratic time, which could be abused to cause a denial of service (GHSA-8rr7-cvq3-gmfh) + +## [2.9.2] - 2026-08-10 + +This release fixes a regression introduced in 2.9.0 which changed the behavior of `Cursor::match()` for certain regular expression patterns. + +### Changed +- Improved performance of reading single characters from multibyte lines +- Improved performance of locating the next non-space character on lines without tabs +- Optimized `Cursor::advanceToNextNonSpaceOrNewline()` to scan the line in place instead of copying everything left in the block on every call +- Optimized inline link destination parsing to scan the line in place, so its cost follows the length of the destination rather than the length of everything left in the block + +### Fixed +- Fixed a regression introduced in 2.9.0 where `Cursor::match()` treated text before the cursor as part of the match subject (#1145). Patterns were matched against the whole line at an offset, which silently changed the meaning of `\b`, `\B`, `\A`, lookbehinds, a `^` anywhere other than the very start of the pattern, and a leading `^` combined with the `m` modifier. `match()` once again matches against the remainder, exactly as it did in 2.8; the core parsers keep the optimized in-place matching via a new internal method with PCRE's native offset semantics, anchoring their patterns at the cursor with `\G` +- Fixed heading permalinks rendered with `aria-hidden="true"` remaining in the keyboard tab order; they are now also given `tabindex="-1"`, as a focusable element removed from the accessibility tree has no accessible name to announce when focused (WCAG 4.1.2) +- Fixed cloning a node breaking the link from the original node's children back to their parent, silently corrupting the document that node belonged to; detaching or inserting around those children afterwards could drop nodes from the tree +- Fixed cloned nodes sharing their `data` with the node they were cloned from, so that setting an attribute on either one also set it on the other + +## [2.9.1] - 2026-08-09 + +This is a **security release** to address multiple denial of service vulnerabilities and one cross-site scripting (XSS) vulnerability. + +### Changed +- Shortcut and collapsed reference links (`[label]` and `[label][]`) now apply the spec's 999-character link label limit when resolving the label, matching the limit already enforced when parsing reference definitions and when resolving the `[text][label]` form. A label longer than 999 characters which collapsed to a shorter, defined label once whitespace was normalized will no longer resolve; this matches cmark's behavior. + +### Fixed +- Fixed attribute names prefixed with a form feed (such as `{onclick="..."}`) bypassing both the `on*` event handler filter and the `allow_unsafe_links` protection, as browsers treat that byte as whitespace and parse the name as a genuine `onclick` or `href` (GHSA-f8fg-pg57-v4j8) +- Fixed catastrophic backtracking in the fenced code block start pattern, causing a single line of backticks to be scanned in quadratic time, which could be abused to cause a denial of service (GHSA-j8pm-gj4c-rq4x) +- Fixed shortcut reference link lookups normalizing arbitrarily long labels once a single reference definition is present, causing nested brackets to be resolved in quadratic time, which could be abused to cause a denial of service (GHSA-j8pm-gj4c-rq4x) +- Fixed delimiter processors keying the opener-search cache on the raw closer run length, leaving the cache key space unbounded and causing emphasis, strikethrough, and highlight runs to be processed in super-linear time, which could be abused to cause a denial of service (GHSA-j8pm-gj4c-rq4x) +- Fixed the `SmartPunctExtension` recopying the whole preceding text node when replacing each unpaired quote, causing documents with many apostrophes to be processed in quadratic time, which could be abused to cause a denial of service (GHSA-jjv6-8j6v-6j52) +- Fixed the `AttributesExtension` scanning the remaining siblings of every block-level attribute node, causing long runs of adjacent attribute blocks to be resolved in quadratic time, which could be abused to cause a denial of service - this completes the fix for GHSA-g2gp-3wwq-f4ph, which covered only inline attributes (GHSA-jjv6-8j6v-6j52) +- Fixed the `AttributesExtension` rebuilding the accumulated class list on every merge, causing long runs of `.class` attributes to be resolved in quadratic time, which could be abused to cause a denial of service (GHSA-jjv6-8j6v-6j52) + +## [2.9.0] - 2026-08-03 + +This is a **security release** to address five denial of service vulnerabilities and one cross-site scripting (XSS) vulnerability. + +### Added + +- Added a new `NormalizeHeadingsExtension` to constrain headings to a configured level range (#989) + - Rewrites headings that skip levels so the resulting HTML is valid (#1115) + - `normalize_headings/rebase_to_min_level` - rebases each document so its headings begin at `min_level` +- Added a new `footnote/enable_inline_footnotes` config option to disable the inline `^[Footnote text]` syntax (#1112) +- Added `Cursor::getBytePosition()` for obtaining the cursor's current byte offset within the line +- Added a new `xml/max_indentation_level` config option to control how far `XmlRenderer` indents nested elements (default: `16`; set to `0` for unindented output) + +### Changed + +- The `FootnoteExtension` now uses only the first definition of a footnote label, removing any duplicate definitions instead of rendering them in place +- `NumberFootnotesListener` now stores footnote backrefs under a single `footnote/backrefs` key in the document data instead of one key per footnote destination +- Optimized `Cursor` to translate character positions to byte offsets in constant time instead of re-decoding the line with `mb_substr()` +- Optimized `Cursor::match()` to match against the line at the cursor's byte offset instead of copying the remaining line on every call +- Optimized `InlineParserEngine` and `UrlAutolinkParser` to work with byte offsets directly + +### Fixed + +- Fixed quadratic parsing performance on lines containing multibyte characters, which could be abused to cause a denial of service (GHSA-2q4p-g7hv-5rgv) +- Fixed the unsafe link filter failing to detect dangerous schemes obfuscated with embedded tabs, newlines, or leading control characters (such as `javascript:`), which allowed the `allow_unsafe_links` protection to be bypassed via `href` and `src` attributes (GHSA-29pj-957v-52mc) +- Fixed duplicate footnote definitions each claiming the full list of backrefs for their label, causing a quadratic number of backrefs to be generated, which could be abused to cause a denial of service (GHSA-jfm3-95jq-q3rf) +- Fixed footnote labels being treated as `.`/`/`-delimited key paths when storing backrefs, which allowed distinct labels such as `[^a.b]` and `[^a/b]` to share a single backref list (GHSA-jfm3-95jq-q3rf) +- Fixed a fatal error when one footnote label was a prefix of another, such as `[^a]` and `[^a.b]` +- Fixed the unique slug normalizer restarting its suffix search from `1` on every collision, causing headings or inline footnotes which normalize to the same slug to be de-duplicated in quadratic time, which could be abused to cause a denial of service (GHSA-mh25-x5hq-wrqp) +- Fixed the `AttributesExtension` scanning the remaining siblings of an inline attribute which can only apply to its parent block, causing long runs of adjacent inline attributes to be resolved in quadratic time, which could be abused to cause a denial of service (GHSA-g2gp-3wwq-f4ph) +- Fixed `XmlRenderer` indenting every element by its full nesting depth without any upper bound, causing deeply-nested documents to render as quadratically-sized XML, which could be abused to cause a denial of service (GHSA-mj63-m3rc-8ppr) +- Fixed `MarkDelimiterProcessor` not being declared as a `CacheableDelimiterProcessorInterface`, preventing the delimiter stack from caching the opener search for `==` runs (#1133) + +## [2.8.3] - 2026-07-12 + +### Fixed +- Fixed tab-indented fenced code blocks inside list items losing the first character of each line and having their info string mangled (#981, #1130) +- Fixed the unsafe link filter incorrectly blocking safe URLs containing `vbscript:`, `file:`, or `data:` anywhere after the start (#1131) + +## [2.8.2] - 2026-03-19 + +This is a **security release** to address an issue where the `allowed_domains` setting for the `Embed` extension can be bypassed, resulting in a possible SSRF and XSS vulnerabilities. + +### Fixed +- Fixed `DomainFilteringAdapter` hostname boundary bypass where domains like `youtube.com.evil` could match an allowlist entry for `youtube.com` (GHSA-hh8v-hgvp-g3f5) + +## [2.8.1] - 2026-03-05 + +This is a **security release** to address an issue where `DisallowedRawHtml` can be bypassed, resulting in a possible cross-site scripting (XSS) vulnerability. + +### Fixed +- Fixed `DisallowedRawHtmlRenderer` not blocking raw HTML tags with trailing ASCII whitespace (GHSA-4v6x-c7xx-hw9f) +- Fixed PHP 8.5 deprecation (#1107) + +## [2.8.0] - 2025-11-26 + +### Added +- Added a new `HighlightExtension` for marking important text using `==` syntax (#1100) + +### Fixed +- Fixed `AutolinkExtension` incorrectly matching URLs after invalid `www.` prefix (#1095, #1103) + +## [2.7.1] - 2025-07-20 + +### Changed +- Optimized several regular expressions in `RegexHelper` to improve performance (#674, #1086) + +### Fixed +- `EmbedProcessor` no longer calls `updateEmbeds()` when there are no embeds to update (#1081) +- Fixed missing `benchmark.php` CSV path validation for non-existent files (#1068, #1085) + +## [2.7.0] - 2025-05-05 + +This is a **security release** to address a potential cross-site scripting (XSS) vulnerability when using the `AttributesExtension` with untrusted user input. + +### Added +- Added `attributes/allow` config option to specify which attributes users are allowed to set on elements (default allows virtually all attributes) + +### Changed +- The `AttributesExtension` blocks all attributes starting with `on` unless explicitly allowed via the `attributes/allow` config option +- The `allow_unsafe_links` option is now respected by the `AttributesExtension` when users specify `href` and `src` attributes + +## [2.6.2] - 2025-04-18 + +### Fixed + +- Fixed Attributes extension parsing regression (#1071) + +## [2.6.1] - 2024-12-29 + +### Fixed + +- Rendered list items should only add newlines around block-level children (#1059, #1061) + +## [2.6.0] - 2024-12-07 + +This is a **security release** to address potential denial of service attacks when parsing specially crafted, +malicious input from untrusted sources (like user input). + +### Added + +- Added `max_delimiters_per_line` config option to prevent denial of service attacks when parsing malicious input +- Added `table/max_autocompleted_cells` config option to prevent denial of service attacks when parsing large tables +- The `AttributesExtension` now supports attributes without values (#985, #986) +- The `AutolinkExtension` exposes two new configuration options to override the default behavior (#969, #987): + - `autolink/allowed_protocols` - an array of protocols to allow autolinking for + - `autolink/default_protocol` - the default protocol to use when none is specified +- Added `RegexHelper::isWhitespace()` method to check if a given character is an ASCII whitespace character +- Added `CacheableDelimiterProcessorInterface` to ensure linear complexity for dynamic delimiter processing +- Added `Bracket` delimiter type to optimize bracket parsing + +### Changed + +- `[` and `]` are no longer added as `Delimiter` objects on the stack; a new `Bracket` type with its own stack is used instead +- `UrlAutolinkParser` no longer parses URLs with more than 127 subdomains +- Expanded reference links can no longer exceed 100kb, or the size of the input document (whichever is greater) +- Delimiters should always provide a non-null value via `DelimiterInterface::getIndex()` + - We'll attempt to infer the index based on surrounding delimiters where possible +- The `DelimiterStack` now accepts integer positions for any `$stackBottom` argument +- Several small performance optimizations + +## [2.5.3] - 2024-08-16 + +### Changed + +- Made compatible with CommonMark spec 0.31.1, including: + - Remove `source`, add `search` to list of recognized block tags + +## [2.5.2] - 2024-08-14 + +### Changed + +- Boolean attributes now require an explicit `true` value (#1040) + +### Fixed + +- Fixed regression where text could be misinterpreted as an attribute (#1040) + +## [2.5.1] - 2024-07-24 + +### Fixed + +- Fixed attribute parsing incorrectly parsing mustache-like syntax (#1035) +- Fixed incorrect `Table` start line numbers (#1037) + +## [2.5.0] - 2024-07-22 + +### Added + +- The `AttributesExtension` now supports attributes without values (#985, #986) +- The `AutolinkExtension` exposes two new configuration options to override the default behavior (#969, #987): + - `autolink/allowed_protocols` - an array of protocols to allow autolinking for + - `autolink/default_protocol` - the default protocol to use when none is specified + +### Changed + +- Made compatible with CommonMark spec 0.31.0, including: + - Allow closing fence to be followed by tabs + - Remove restrictive limitation on inline comments + - Unicode symbols now treated like punctuation (for purposes of flankingness) + - Trailing tabs on the last line of indented code blocks will be excluded + - Improved HTML comment matching +- `Paragraph`s only containing link reference definitions will be kept in the AST until the `Document` is finalized + - (These were previously removed immediately after parsing the `Paragraph`) + +### Fixed + +- Fixed list tightness not being determined properly in some edge cases +- Fixed incorrect ending line numbers for several block types in various scenarios +- Fixed lowercase inline HTML declarations not being accepted + +## [2.4.4] - 2024-07-22 + +### Fixed + +- Fixed SmartPunct extension changing already-formatted quotation marks (#1030) + +## [2.4.3] - 2024-07-22 + +### Fixed + +- Fixed the Attributes extension not supporting CSS level 3 selectors (#1013) +- Fixed `UrlAutolinkParser` incorrectly parsing text containing `www` anywhere before an autolink (#1025) + + +## [2.4.2] - 2024-02-02 + +### Fixed + +- Fixed declaration parser being too strict +- `FencedCodeRenderer`: don't add `language-` to class if already prefixed + +### Deprecated + +- Returning dynamic values from `DelimiterProcessorInterface::getDelimiterUse()` is deprecated + - You should instead implement `CacheableDelimiterProcessorInterface` to help the engine perform caching to avoid performance issues. +- Failing to set a delimiter's index (or returning `null` from `DelimiterInterface::getIndex()`) is deprecated and will not be supported in 3.0 +- Deprecated `DelimiterInterface::isActive()` and `DelimiterInterface::setActive()`, as these are no longer used by the engine +- Deprecated `DelimiterStack::removeEarlierMatches()` and `DelimiterStack::searchByCharacter()`, as these are no longer used by the engine +- Passing a `DelimiterInterface` as the `$stackBottom` argument to `DelimiterStack::processDelimiters()` or `::removeAll()` is deprecated and will not be supported in 3.0; pass the integer position instead. + +### Fixed + +- Fixed NUL characters not being replaced in the input +- Fixed quadratic complexity parsing unclosed inline links +- Fixed quadratic complexity parsing emphasis and strikethrough delimiters +- Fixed issue where having 500,000+ delimiters could trigger a [known segmentation fault issue in PHP's garbage collection](https://bugs.php.net/bug.php?id=68606) +- Fixed quadratic complexity deactivating link openers +- Fixed quadratic complexity parsing long backtick code spans with no matching closers +- Fixed catastrophic backtracking when parsing link labels/titles + +## [2.4.1] - 2023-08-30 + +### Fixed + +- Fixed `ExternalLinkProcessor` not fully disabling the `rel` attribute when configured to do so (#992) + +## [2.4.0] - 2023-03-24 + +### Added + +- Added generic `CommonMarkException` marker interface for all exceptions thrown by the library +- Added several new specific exception types implementing that marker interface: + - `AlreadyInitializedException` + - `InvalidArgumentException` + - `IOException` + - `LogicException` + - `MissingDependencyException` + - `NoMatchingRendererException` + - `ParserLogicException` +- Added more configuration options to the Heading Permalinks extension (#939): + - `heading_permalink/apply_id_to_heading` - When `true`, the `id` attribute will be applied to the heading element itself instead of the `` tag + - `heading_permalink/heading_class` - class to apply to the heading element + - `heading_permalink/insert` - now accepts `none` to prevent the creation of the `` link +- Added new `table/alignment_attributes` configuration option to control how table cell alignment is rendered (#959) + +### Changed + +- Change several thrown exceptions from `RuntimeException` to `LogicException` (or something extending it), including: + - `CallbackGenerator`s that fail to set a URL or return an expected value + - `MarkdownParser` when deactivating the last block parser or attempting to get an active block parser when they've all been closed + - Adding items to an already-initialized `Environment` + - Rendering a `Node` when no renderer has been registered for it +- `HeadingPermalinkProcessor` now throws `InvalidConfigurationException` instead of `RuntimeException` when invalid config values are given. +- `HtmlElement::setAttribute()` no longer requires the second parameter for boolean attributes +- Several small micro-optimizations +- Changed Strikethrough to only allow 1 or 2 tildes per the updated GFM spec + +### Fixed + +- Fixed inaccurate `@throws` docblocks throughout the codebase, including `ConverterInterface`, `MarkdownConverter`, and `MarkdownConverterInterface`. + - These previously suggested that only `\RuntimeException`s were thrown, which was inaccurate as `\LogicException`s were also possible. + +## [2.3.9] - 2023-02-15 + +### Fixed + +- Fixed autolink extension not detecting some URIs with underscores (#956) + +## [2.3.8] - 2022-12-10 + +### Fixed + +- Fixed parsing issues when `mb_internal_encoding()` is set to something other than `UTF-8` (#951) + +## [2.3.7] - 2022-11-03 + +### Fixed + +- Fixed `TaskListItemMarkerRenderer` not including HTML attributes set on the node by other extensions (#947) + +## [2.3.6] - 2022-10-30 + +### Fixed + +- Fixed unquoted attribute parsing when closing curly brace is followed by certain characters (like a `.`) (#943) + +## [2.3.5] - 2022-07-29 + +### Fixed + +- Fixed error using `InlineParserEngine` when no inline parsers are registered in the `Environment` (#908) + +## [2.3.4] - 2022-07-17 + +### Changed + +- Made a number of small tweaks to the embed extension's parsing behavior to fix #898: + - Changed `EmbedStartParser` to always capture embed-like lines in container blocks, regardless of parent block type + - Changed `EmbedProcessor` to also remove `Embed` blocks that aren't direct children of the `Document` + - Increased the priority of `EmbedProcessor` to `1010` + +### Fixed + +- Fixed `EmbedExtension` not parsing embeds following a list block (#898) + +## [2.3.3] - 2022-06-07 + +### Fixed + +- Fixed `DomainFilteringAdapter` not reindexing the embed list (#884, #885) + +## [2.3.2] - 2022-06-03 + +### Fixed + +- Fixed FootnoteExtension stripping extra characters from tab-indented footnotes (#881) + +## [2.2.5] - 2022-06-03 + +### Fixed + +- Fixed FootnoteExtension stripping extra characters from tab-indented footnotes (#881) + +## [2.3.1] - 2022-05-14 + +### Fixed + +- Fixed AutolinkExtension not ignoring trailing strikethrough syntax (#867) + +## [2.2.4] - 2022-05-14 + +### Fixed + +- Fixed AutolinkExtension not ignoring trailing strikethrough syntax (#867) + +## [2.3.0] - 2022-04-07 + +### Added + +- Added new `EmbedExtension` (#805) +- Added `DocumentRendererInterface` as a replacement for the now-deprecated `MarkdownRendererInterface` + +### Deprecated + +- Deprecated `MarkdownRendererInterface`; use `DocumentRendererInterface` instead + +## [2.2.3] - 2022-02-26 + +### Fixed + +- Fixed front matter parsing with Windows line endings (#821) + +## [2.1.3] - 2022-02-26 + +### Fixed + +- Fixed front matter parsing with Windows line endings (#821) + +## [2.0.4] - 2022-02-26 + +### Fixed + +- Fixed front matter parsing with Windows line endings (#821) + +## [2.2.2] - 2022-02-13 + +### Fixed + +- Fixed double-escaping of image alt text (#806, #810) +- Fixed Psalm typehints for event class names + +## [2.2.1] - 2022-01-25 + +### Fixed + + - Fixed `symfony/deprecation-contracts` constraint + +### Removed + + - Removed deprecation trigger from `MarkdownConverterInterface` to reduce noise + +## [2.2.0] - 2022-01-22 + +### Added + + - Added new `ConverterInterface` + - Added new `MarkdownToXmlConverter` class + - Added new `HtmlDecorator` class which can wrap existing renderers with additional HTML tags + - Added new `table/wrap` config to apply an optional wrapping/container element around a table (#780) + +### Changed + + - `HtmlElement` contents can now consist of any `Stringable`, not just `HtmlElement` and `string` + +### Deprecated + + - Deprecated `MarkdownConverterInterface` and its `convertToHtml()` method; use `ConverterInterface` and `convert()` instead + +## [2.1.2] - 2022-02-13 + +### Fixed + +- Fixed double-escaping of image alt text (#806, #810) +- Fixed Psalm typehints for event class names + +## [2.1.1] - 2022-01-02 + +### Added + + - Added missing return type to `Environment::dispatch()` to fix deprecation warning (#778) + +## [2.1.0] - 2021-12-05 + +### Added + +- Added support for ext-yaml in FrontMatterExtension (#715) +- Added support for symfony/yaml v6.0 in FrontMatterExtension (#739) +- Added new `heading_permalink/aria_hidden` config option (#741) + +### Fixed + + - Fixed PHP 8.1 deprecation warning (#759, #762) + +## [2.0.3] - 2022-02-13 + +### Fixed + +- Fixed double-escaping of image alt text (#806, #810) +- Fixed Psalm typehints for event class names + +## [2.0.2] - 2021-08-14 + +### Changed + +- Bumped minimum version of league/config to support PHP 8.1 + +### Fixed + +- Fixed ability to register block parsers that identify lines starting with letters (#706) + +## [2.0.1] - 2021-07-31 + +### Fixed + +- Fixed nested autolinks (#689) +- Fixed description lists being parsed incorrectly (#692) +- Fixed Table of Contents not respecting Heading Permalink prefixes (#690) + +## [2.0.0] - 2021-07-24 + +No changes were introduced since the previous RC2 release. +See all entries below for a list of changes between 1.x and 2.0. + +## [2.0.0-rc2] - 2021-07-17 + +### Fixed + +- Fixed Mentions inside of links creating nested links against the spec's rules (#688) + +## [2.0.0-rc1] - 2021-07-10 + +No changes were introduced since the previous release. + +## [2.0.0-beta3] - 2021-07-03 + +### Changed + + - Any leading UTF-8 BOM will be stripped from the input + - The `getEnvironment()` method of `CommonMarkConverter` and `GithubFlavoredMarkdownConverter` will always return the concrete, configurable `Environment` for upgrading convenience + - Optimized AST iteration + - Lots of small micro-optimizations + +## [2.0.0-beta2] - 2021-06-27 + +### Added + +- Added new `Node::iterator()` method and `NodeIterator` class for faster AST iteration (#683, #684) + +### Changed + +- Made compatible with CommonMark spec 0.30.0 +- Optimized link label parsing +- Optimized AST iteration for a 50% performance boost in some event listeners (#683, #684) + +### Fixed + +- Fixed processing instructions with EOLs +- Fixed case-insensitive matching for HTML tag types +- Fixed type 7 HTML blocks incorrectly interrupting lazy paragraphs +- Fixed newlines in reference labels not collapsing into spaces +- Fixed link label normalization with escaped newlines +- Fixed unnecessary AST iteration when no default attributes are configured + +## [2.0.0-beta1] - 2021-06-20 + +### Added + + - **Added three new extensions:** + - `FrontMatterExtension` ([see documentation](https://commonmark.thephpleague.com/extensions/front-matter/)) + - `DescriptionListExtension` ([see documentation](https://commonmark.thephpleague.com/extensions/description-lists/)) + - `DefaultAttributesExtension` ([see documentation](https://commonmark.thephpleague.com/extensions/default-attributes/)) + - **Added new `XmlRenderer` to simplify AST debugging** ([see documentation](https://commonmark.thephpleague.com/xml/)) (#431) + - **Added the ability to configure disallowed raw HTML tags** (#507) + - **Added the ability for Mentions to use multiple characters for their symbol** (#514, #550) + - **Added the ability to delegate event dispatching to PSR-14 compliant event dispatcher libraries** + - **Added new configuration options:** + - Added `heading_permalink/min_heading_level` and `heading_permalink/max_heading_level` options to control which headings get permalinks (#519) + - Added `heading_permalink/fragment_prefix` to allow customizing the URL fragment prefix (#602) + - Added `footnote/backref_symbol` option for customizing backreference link appearance (#522) + - Added `slug_normalizer/max_length` option to control the maximum length of generated URL slugs + - Added `slug_normalizer/unique` option to control whether unique slugs should be generated per-document or per-environment + - **Added purity markers throughout the codebase** (verified with Psalm) + - Added `Query` class to simplify Node traversal when looking to take action on certain Nodes + - Added new `HtmlFilter` and `StringContainerHelper` utility classes + - Added new `AbstractBlockContinueParser` class to simplify the creation of custom block parsers + - Added several new classes and interfaces: + - `BlockContinue` + - `BlockContinueParserInterface` + - `BlockContinueParserWithInlinesInterface` + - `BlockStart` + - `BlockStartParserInterface` + - `ChildNodeRendererInterface` + - `ConfigurableExtensionInterface` + - `CursorState` + - `DashParser` (extracted from `PunctuationParser`) + - `DelimiterParser` + - `DocumentBlockParser` + - `DocumentPreRenderEvent` + - `DocumentRenderedEvent` + - `EllipsesParser` (extracted from `PunctuationParser`) + - `ExpressionInterface` + - `FallbackNodeXmlRenderer` + - `InlineParserEngineInterface` + - `InlineParserMatch` + - `MarkdownParserState` + - `MarkdownParserStateInterface` + - `MarkdownRendererInterface` + - `Query` + - `RawMarkupContainerInterface` + - `ReferenceableInterface` + - `RenderedContent` + - `RenderedContentInterface` + - `ReplaceUnpairedQuotesListener` + - `SpecReader` + - `TableOfContentsRenderer` + - `UniqueSlugNormalizer` + - `UniqueSlugNormalizerInterface` + - `XmlRenderer` + - `XmlNodeRendererInterface` + - Added several new methods: + - `Cursor::getCurrentCharacter()` + - `Environment::createDefaultConfiguration()` + - `Environment::setEventDispatcher()` + - `EnvironmentInterface::getExtensions()` + - `EnvironmentInterface::getInlineParsers()` + - `EnvironmentInterface::getSlugNormalizer()` + - `FencedCode::setInfo()` + - `Heading::setLevel()` + - `HtmlRenderer::renderDocument()` + - `InlineParserContext::getFullMatch()` + - `InlineParserContext::getFullMatchLength()` + - `InlineParserContext::getMatches()` + - `InlineParserContext::getSubMatches()` + - `LinkParserHelper::parsePartialLinkLabel()` + - `LinkParserHelper::parsePartialLinkTitle()` + - `Node::assertInstanceOf()` + - `RegexHelper::isLetter()` + - `StringContainerInterface::setLiteral()` + - `TableCell::getType()` + - `TableCell::setType()` + - `TableCell::getAlign()` + - `TableCell::setAlign()` + +### Changed + + - **Changed the converter return type** + - `CommonMarkConverter::convertToHtml()` now returns an instance of `RenderedContentInterface`. This can be cast to a string for backward compatibility with 1.x. + - **Table of Contents items are no longer wrapped with `

` tags** (#613) + - **Heading Permalinks now link to element IDs instead of using `name` attributes** (#602) + - **Heading Permalink IDs and URL fragments now have a `content` prefix by default** (#602) + - **Changes to configuration options:** + - `enable_em` has been renamed to `commonmark/enable_em` + - `enable_strong` has been renamed to `commonmark/enable_strong` + - `use_asterisk` has been renamed to `commonmark/use_asterisk` + - `use_underscore` has been renamed to `commonmark/use_underscore` + - `unordered_list_markers` has been renamed to `commonmark/unordered_list_markers` + - `mentions/*/symbol` has been renamed to `mentions/*/prefix` + - `mentions/*/regex` has been renamed to `mentions/*/pattern` and requires partial regular expressions (without delimiters or flags) + - `max_nesting_level` now defaults to `PHP_INT_MAX` and no longer supports floats + - `heading_permalink/slug_normalizer` has been renamed to `slug_normalizer/instance` + - **Event dispatching is now fully PSR-14 compliant** + - **Moved and renamed several classes** - [see the full list here](https://commonmark.thephpleague.com/2.0/upgrading/#classesnamespaces-renamed) + - The `HeadingPermalinkExtension` and `FootnoteExtension` were modified to ensure they never produce a slug which conflicts with slugs created by the other extension + - `SlugNormalizer::normalizer()` now supports optional prefixes and max length options passed in via the `$context` argument + - The `AbstractBlock::$data` and `AbstractInline::$data` arrays were replaced with a `Data` array-like object on the base `Node` class + - **Implemented a new approach to block parsing.** This was a massive change, so here are the highlights: + - Functionality previously found in block parsers and node elements has moved to block parser factories and block parsers, respectively ([more details](https://commonmark.thephpleague.com/2.0/upgrading/#new-block-parsing-approach)) + - `ConfigurableEnvironmentInterface::addBlockParser()` is now `EnvironmentBuilderInterface::addBlockParserFactory()` + - `ReferenceParser` was re-implemented and works completely different than before + - The paragraph parser no longer needs to be added manually to the environment + - **Implemented a new approach to inline parsing** where parsers can now specify longer strings or regular expressions they want to parse (instead of just single characters): + - `InlineParserInterface::getCharacters()` is now `getMatchDefinition()` and returns an instance of `InlineParserMatch` + - `InlineParserContext::__construct()` now requires the contents to be provided as a `Cursor` instead of a `string` + - **Implemented delimiter parsing as a special type of inline parser** (via the new `DelimiterParser` class) + - **Changed block and inline rendering to use common methods and interfaces** + - `BlockRendererInterface` and `InlineRendererInterface` were replaced by `NodeRendererInterface` with slightly different parameters. All core renderers now implement this interface. + - `ConfigurableEnvironmentInterface::addBlockRenderer()` and `addInlineRenderer()` were combined into `EnvironmentBuilderInterface::addRenderer()` + - `EnvironmentInterface::getBlockRenderersForClass()` and `getInlineRenderersForClass()` are now just `getRenderersForClass()` + - **Completely refactored the Configuration implementation** + - All configuration-specific classes have been moved into a new `league/config` package with a new namespace + - `Configuration` objects must now be configured with a schema and all options must match that schema - arbitrary keys are no longer permitted + - `Configuration::__construct()` no longer accepts the default configuration values - use `Configuration::merge()` instead + - `ConfigurationInterface` now only contains a `get(string $key)`; this method no longer allows arbitrary default values to be returned if the option is missing + - `ConfigurableEnvironmentInterface` was renamed to `EnvironmentBuilderInterface` + - `ExtensionInterface::register()` now requires an `EnvironmentBuilderInterface` param instead of `ConfigurableEnvironmentInterface` + - **Added missing return types to virtually every class and interface method** + - Re-implemented the GFM Autolink extension using the new inline parser approach instead of document processors + - `EmailAutolinkProcessor` is now `EmailAutolinkParser` + - `UrlAutolinkProcessor` is now `UrlAutolinkParser` + - `HtmlElement` can now properly handle array (i.e. `class`) and boolean (i.e. `checked`) attribute values + - `HtmlElement` automatically flattens any attributes with array values into space-separated strings, removing duplicate entries + - Combined separate classes/interfaces into one: + - `DisallowedRawHtmlRenderer` replaces `DisallowedRawHtmlBlockRenderer` and `DisallowedRawHtmlInlineRenderer` + - `NodeRendererInterface` replaces `BlockRendererInterface` and `InlineRendererInterface` + - Renamed the following methods: + - `Environment` and `ConfigurableEnvironmentInterface`: + - `addBlockParser()` is now `addBlockStartParser()` + - `ReferenceMap` and `ReferenceMapInterface`: + - `addReference()` is now `add()` + - `getReference()` is now `get()` + - `listReferences()` is now `getIterator()` + - Various node (block/inline) classes: + - `getContent()` is now `getLiteral()` + - `setContent()` is now `setLiteral()` + - Moved and renamed the following constants: + - `EnvironmentInterface::HTML_INPUT_ALLOW` is now `HtmlFilter::ALLOW` + - `EnvironmentInterface::HTML_INPUT_ESCAPE` is now `HtmlFilter::ESCAPE` + - `EnvironmentInterface::HTML_INPUT_STRIP` is now `HtmlFilter::STRIP` + - `TableCell::TYPE_HEAD` is now `TableCell::TYPE_HEADER` + - `TableCell::TYPE_BODY` is now `TableCell::TYPE_DATA` + - Changed the visibility of the following properties: + - `AttributesInline::$attributes` is now `private` + - `AttributesInline::$block` is now `private` + - `TableCell::$align` is now `private` + - `TableCell::$type` is now `private` + - `TableSection::$type` is now `private` + - Several methods which previously returned `$this` now return `void` + - `Delimiter::setPrevious()` + - `Node::replaceChildren()` + - `Context::setTip()` + - `Context::setContainer()` + - `Context::setBlocksParsed()` + - `AbstractStringContainer::setContent()` + - `AbstractWebResource::setUrl()` + - Several classes are now marked `final`: + - `ArrayCollection` + - `Emphasis` + - `FencedCode` + - `Heading` + - `HtmlBlock` + - `HtmlElement` + - `HtmlInline` + - `IndentedCode` + - `Newline` + - `Strikethrough` + - `Strong` + - `Text` + - `Heading` nodes no longer directly contain a copy of their inner text + - `StringContainerInterface` can now be used for inlines, not just blocks + - `ArrayCollection` only supports integer keys + - `HtmlElement` now implements `Stringable` + - `Cursor::saveState()` and `Cursor::restoreState()` now use `CursorState` objects instead of arrays + - `NodeWalker::next()` now enters, traverses any children, and leaves all elements which may have children (basically all blocks plus any inlines with children). Previously, it only did this for elements explicitly marked as "containers". + - `InvalidOptionException` was removed + - Anything with a `getReference(): ReferenceInterface` method now implements `ReferencableInterface` + - The `SmartPunct` extension now replaces all unpaired `Quote` elements with `Text` elements towards the end of parsing, making the `QuoteRenderer` unnecessary + - Several changes made to the Footnote extension: + - Footnote identifiers can no longer contain spaces + - Anonymous footnotes can now span subsequent lines + - Footnotes can now contain multiple lines of content, including sub-blocks, by indenting them + - Footnote event listeners now have numbered priorities (but still execute in the same order) + - Footnotes must now be separated from previous content by a blank line + - The line numbers (keys) returned via `MarkdownInput::getLines()` now start at 1 instead of 0 + - `DelimiterProcessorCollectionInterface` now extends `Countable` + - `RegexHelper::PARTIAL_` constants must always be used in case-insensitive contexts + - `HeadingPermalinkProcessor` no longer accepts text normalizers via the constructor - these must be provided via configuration instead + - Blocks which can't contain inlines will no longer be asked to render inlines + - `AnonymousFootnoteRefParser` and `HeadingPermalinkProcessor` now implement `EnvironmentAwareInterface` instead of `ConfigurationAwareInterface` + - The second argument to `TextNormalizerInterface::normalize()` must now be an array + - The `title` attribute for `Link` and `Image` nodes is now stored using a dedicated property instead of stashing it in `$data` + - `ListData::$delimiter` now returns either `ListBlock::DELIM_PERIOD` or `ListBlock::DELIM_PAREN` instead of the literal delimiter + +### Fixed + + - **Fixed parsing of footnotes without content** + - **Fixed rendering of orphaned footnotes and footnote refs** + - **Fixed some URL autolinks breaking too early** (#492) + - Fixed `AbstractStringContainer` not actually being `abstract` + +### Removed + + - **Removed support for PHP 7.1, 7.2, and 7.3** (#625, #671) + - **Removed all previously-deprecated functionality:** + - Removed the ability to pass custom `Environment` instances into the `CommonMarkConverter` and `GithubFlavoredMarkdownConverter` constructors + - Removed the `Converter` class and `ConverterInterface` + - Removed the `bin/commonmark` script + - Removed the `Html5Entities` utility class + - Removed the `InlineMentionParser` (use `MentionParser` instead) + - Removed `DefaultSlugGenerator` and `SlugGeneratorInterface` from the `Extension/HeadingPermalink/Slug` sub-namespace (use the new ones under `./SlugGenerator` instead) + - Removed the following `ArrayCollection` methods: + - `add()` + - `set()` + - `get()` + - `remove()` + - `isEmpty()` + - `contains()` + - `indexOf()` + - `containsKey()` + - `replaceWith()` + - `removeGaps()` + - Removed the `ConfigurableEnvironmentInterface::setConfig()` method + - Removed the `ListBlock::TYPE_UNORDERED` constant + - Removed the `CommonMarkConverter::VERSION` constant + - Removed the `HeadingPermalinkRenderer::DEFAULT_INNER_CONTENTS` constant + - Removed the `heading_permalink/inner_contents` configuration option + - **Removed now-unused classes:** + - `AbstractStringContainerBlock` + - `BlockRendererInterface` + - `Context` + - `ContextInterface` + - `Converter` + - `ConverterInterface` + - `InlineRendererInterface` + - `PunctuationParser` (was split into two classes: `DashParser` and `EllipsesParser`) + - `QuoteRenderer` + - `UnmatchedBlockCloser` + - Removed the following methods, properties, and constants: + - `AbstractBlock::$open` + - `AbstractBlock::$lastLineBlank` + - `AbstractBlock::isContainer()` + - `AbstractBlock::canContain()` + - `AbstractBlock::isCode()` + - `AbstractBlock::matchesNextLine()` + - `AbstractBlock::endsWithBlankLine()` + - `AbstractBlock::setLastLineBlank()` + - `AbstractBlock::shouldLastLineBeBlank()` + - `AbstractBlock::isOpen()` + - `AbstractBlock::finalize()` + - `AbstractBlock::getData()` + - `AbstractInline::getData()` + - `ConfigurableEnvironmentInterface::addBlockParser()` + - `ConfigurableEnvironmentInterface::mergeConfig()` + - `Delimiter::setCanClose()` + - `EnvironmentInterface::getConfig()` + - `EnvironmentInterface::getInlineParsersForCharacter()` + - `EnvironmentInterface::getInlineParserCharacterRegex()` + - `HtmlRenderer::renderBlock()` + - `HtmlRenderer::renderBlocks()` + - `HtmlRenderer::renderInline()` + - `HtmlRenderer::renderInlines()` + - `Node::isContainer()` + - `RegexHelper::matchAll()` (use the new `matchFirst()` method instead) + - `RegexHelper::REGEX_WHITESPACE` + - Removed the second `$contents` argument from the `Heading` constructor + +### Deprecated + +**The following things have been deprecated and will not be supported in v3.0:** + + - `Environment::mergeConfig()` (set configuration before instantiation instead) + - `Environment::createCommonMarkEnvironment()` and `Environment::createGFMEnvironment()` + - Alternative 1: Use `CommonMarkConverter` or `GithubFlavoredMarkdownConverter` if you don't need to customize the environment + - Alternative 2: Instantiate a new `Environment` and add the necessary extensions yourself + +[unreleased]: https://github.com/thephpleague/commonmark/compare/2.10.7...HEAD +[2.10.7]: https://github.com/thephpleague/commonmark/compare/2.10.6...2.10.7 +[2.10.6]: https://github.com/thephpleague/commonmark/compare/2.10.5...2.10.6 +[2.10.5]: https://github.com/thephpleague/commonmark/compare/2.10.4...2.10.5 +[2.10.4]: https://github.com/thephpleague/commonmark/compare/2.10.3...2.10.4 +[2.10.3]: https://github.com/thephpleague/commonmark/compare/2.10.2...2.10.3 +[2.10.2]: https://github.com/thephpleague/commonmark/compare/2.10.1...2.10.2 +[2.10.1]: https://github.com/thephpleague/commonmark/compare/2.10.0...2.10.1 +[2.10.0]: https://github.com/thephpleague/commonmark/compare/2.9.2...2.10.0 +[2.9.2]: https://github.com/thephpleague/commonmark/compare/2.9.1...2.9.2 +[2.9.1]: https://github.com/thephpleague/commonmark/compare/2.9.0...2.9.1 +[2.9.0]: https://github.com/thephpleague/commonmark/compare/2.8.3...2.9.0 +[2.8.3]: https://github.com/thephpleague/commonmark/compare/2.8.2...2.8.3 +[2.8.2]: https://github.com/thephpleague/commonmark/compare/2.8.1...2.8.2 +[2.8.1]: https://github.com/thephpleague/commonmark/compare/2.8.0...2.8.1 +[2.8.0]: https://github.com/thephpleague/commonmark/compare/2.7.1...2.8.0 +[2.7.1]: https://github.com/thephpleague/commonmark/compare/2.7.0...2.7.1 +[2.7.0]: https://github.com/thephpleague/commonmark/compare/2.6.2...2.7.0 +[2.6.2]: https://github.com/thephpleague/commonmark/compare/2.6.1...2.6.2 +[2.6.1]: https://github.com/thephpleague/commonmark/compare/2.6.0...2.6.1 +[2.6.0]: https://github.com/thephpleague/commonmark/compare/2.5.3...2.6.0 +[2.5.3]: https://github.com/thephpleague/commonmark/compare/2.5.2...2.5.3 +[2.5.2]: https://github.com/thephpleague/commonmark/compare/2.5.1...2.5.2 +[2.5.1]: https://github.com/thephpleague/commonmark/compare/2.5.0...2.5.1 +[2.5.0]: https://github.com/thephpleague/commonmark/compare/2.4.4...2.5.0 +[2.4.4]: https://github.com/thephpleague/commonmark/compare/2.4.3...2.4.4 +[2.4.3]: https://github.com/thephpleague/commonmark/compare/2.4.2...2.4.3 +[2.4.2]: https://github.com/thephpleague/commonmark/compare/2.4.1...2.4.2 +[2.4.1]: https://github.com/thephpleague/commonmark/compare/2.4.0...2.4.1 +[2.4.0]: https://github.com/thephpleague/commonmark/compare/2.3.9...2.4.0 +[2.3.9]: https://github.com/thephpleague/commonmark/compare/2.3.8...2.3.9 +[2.3.8]: https://github.com/thephpleague/commonmark/compare/2.3.7...2.3.8 +[2.3.7]: https://github.com/thephpleague/commonmark/compare/2.3.6...2.3.7 +[2.3.6]: https://github.com/thephpleague/commonmark/compare/2.3.5...2.3.6 +[2.3.5]: https://github.com/thephpleague/commonmark/compare/2.3.4...2.3.5 +[2.3.4]: https://github.com/thephpleague/commonmark/compare/2.3.3...2.3.4 +[2.3.3]: https://github.com/thephpleague/commonmark/compare/2.3.2...2.3.3 +[2.3.2]: https://github.com/thephpleague/commonmark/compare/2.3.2...main +[2.3.1]: https://github.com/thephpleague/commonmark/compare/2.3.0...2.3.1 +[2.3.0]: https://github.com/thephpleague/commonmark/compare/2.2.3...2.3.0 +[2.2.5]: https://github.com/thephpleague/commonmark/compare/2.2.4...2.2.5 +[2.2.4]: https://github.com/thephpleague/commonmark/compare/2.2.3...2.2.4 +[2.2.3]: https://github.com/thephpleague/commonmark/compare/2.2.2...2.2.3 +[2.2.2]: https://github.com/thephpleague/commonmark/compare/2.2.1...2.2.2 +[2.2.1]: https://github.com/thephpleague/commonmark/compare/2.2.0...2.2.1 +[2.2.0]: https://github.com/thephpleague/commonmark/compare/2.1.1...2.2.0 +[2.1.3]: https://github.com/thephpleague/commonmark/compare/2.1.2...2.1.3 +[2.1.2]: https://github.com/thephpleague/commonmark/compare/2.1.1...2.1.2 +[2.1.1]: https://github.com/thephpleague/commonmark/compare/2.0.2...2.1.1 +[2.1.0]: https://github.com/thephpleague/commonmark/compare/2.0.2...2.1.0 +[2.0.4]: https://github.com/thephpleague/commonmark/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/thephpleague/commonmark/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/thephpleague/commonmark/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/thephpleague/commonmark/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/thephpleague/commonmark/compare/2.0.0-rc2...2.0.0 +[2.0.0-rc2]: https://github.com/thephpleague/commonmark/compare/2.0.0-rc1...2.0.0-rc2 +[2.0.0-rc1]: https://github.com/thephpleague/commonmark/compare/2.0.0-beta3...2.0.0-rc1 +[2.0.0-beta3]: https://github.com/thephpleague/commonmark/compare/2.0.0-beta2...2.0.0-beta3 +[2.0.0-beta2]: https://github.com/thephpleague/commonmark/compare/2.0.0-beta1...2.0.0-beta2 +[2.0.0-beta1]: https://github.com/thephpleague/commonmark/compare/1.6...2.0.0-beta1 diff --git a/vendor/league/commonmark/LICENSE b/vendor/league/commonmark/LICENSE new file mode 100644 index 0000000..5f04fad --- /dev/null +++ b/vendor/league/commonmark/LICENSE @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2014-2022, Colin O'Dell. All rights reserved. Some code based on commonmark.js (copyright 2014-2018, John MacFarlane) and commonmark-java (copyright 2015-2016, Atlassian Pty Ltd) + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/league/commonmark/README.md b/vendor/league/commonmark/README.md new file mode 100644 index 0000000..fdc17db --- /dev/null +++ b/vendor/league/commonmark/README.md @@ -0,0 +1,226 @@ +# league/commonmark + +[![Latest Version](https://img.shields.io/packagist/v/league/commonmark.svg?style=flat-square)](https://packagist.org/packages/league/commonmark) +[![Total Downloads](https://img.shields.io/packagist/dt/league/commonmark.svg?style=flat-square)](https://packagist.org/packages/league/commonmark) +[![Software License](https://img.shields.io/badge/License-BSD--3-brightgreen.svg?style=flat-square)](LICENSE) +[![Build Status](https://img.shields.io/github/actions/workflow/status/thephpleague/commonmark/tests.yml?branch=main&style=flat-square)](https://github.com/thephpleague/commonmark/actions?query=workflow%3ATests+branch%3Amain) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/commonmark.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/commonmark/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/commonmark.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/commonmark) +[![Psalm Type Coverage](https://shepherd.dev/github/thephpleague/commonmark/coverage.svg)](https://shepherd.dev/github/thephpleague/commonmark) +[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/126/badge)](https://bestpractices.coreinfrastructure.org/projects/126) +[![Sponsor development of this project](https://img.shields.io/badge/sponsor%20this%20package-%E2%9D%A4-ff69b4.svg?style=flat-square)](https://www.colinodell.com/sponsor) + +![league/commonmark](commonmark-banner.png) + +**league/commonmark** is a highly-extensible PHP Markdown parser created by [Colin O'Dell][@colinodell] which supports the full [CommonMark] spec and [GitHub-Flavored Markdown]. It is based on the [CommonMark JS reference implementation][commonmark.js] by [John MacFarlane] \([@jgm]\). + +## 📦 Installation & Basic Usage + +This project requires PHP 7.4 or higher with the `mbstring` extension. To install it via [Composer] simply run: + +``` bash +$ composer require league/commonmark +``` + +The `CommonMarkConverter` class provides a simple wrapper for converting CommonMark to HTML: + +```php +use League\CommonMark\CommonMarkConverter; + +$converter = new CommonMarkConverter([ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, +]); + +echo $converter->convert('# Hello World!'); + +//

Hello World!

+``` + +Or if you want GitHub-Flavored Markdown, use the `GithubFlavoredMarkdownConverter` class instead: + +```php +use League\CommonMark\GithubFlavoredMarkdownConverter; + +$converter = new GithubFlavoredMarkdownConverter([ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, +]); + +echo $converter->convert('# Hello World!'); + +//

Hello World!

+``` + +Please note that only UTF-8 and ASCII encodings are supported. If your Markdown uses a different encoding please convert it to UTF-8 before running it through this library. + +> [!CAUTION] +> If you will be parsing untrusted input from users, please consider setting the `html_input` and `allow_unsafe_links` options per the example above. See for more details. If you also do choose to allow raw HTML input from untrusted users, consider using a library (like [HTML Purifier](https://github.com/ezyang/htmlpurifier)) to provide additional HTML filtering. + +## 📓 Documentation + +Full documentation on advanced usage, configuration, and customization can be found at [commonmark.thephpleague.com][docs]. + +## ⏫ Upgrading + +Information on how to upgrade to newer versions of this library can be found at . + +## 💻 GitHub-Flavored Markdown + +The `GithubFlavoredMarkdownConverter` shown earlier is a drop-in replacement for the `CommonMarkConverter` which adds additional features found in the GFM spec: + + - Autolinks + - Disallowed raw HTML + - Strikethrough + - Tables + - Task Lists + +See the [Extensions documentation](https://commonmark.thephpleague.com/customization/extensions/) for more details on how to include only certain GFM features if you don't want them all. + +## 🗃️ Related Packages + +### Integrations + +- [CakePHP 3](https://github.com/gourmet/common-mark) +- [Drupal](https://www.drupal.org/project/markdown) +- [Laravel 4+](https://github.com/GrahamCampbell/Laravel-Markdown) +- [Sculpin](https://github.com/bcremer/sculpin-commonmark-bundle) +- [Symfony 2 & 3](https://github.com/webuni/commonmark-bundle) +- [Symfony 4](https://github.com/avensome/commonmark-bundle) +- [Twig Markdown extension](https://github.com/twigphp/markdown-extension) +- [Twig filter and tag](https://github.com/aptoma/twig-markdown) +- [Laravel CommonMark Blog](https://github.com/spekulatius/laravel-commonmark-blog) + +### Included Extensions + +See [our extension documentation](https://commonmark.thephpleague.com/extensions/overview) for a full list of extensions bundled with this library. + +### Community Extensions + +Custom parsers/renderers can be bundled into extensions which extend CommonMark. Here are some that you may find interesting: + + - [Emoji extension](https://github.com/ElGigi/CommonMarkEmoji) - UTF-8 emoji extension with Github tag. + - [Sup Sub extensions](https://github.com/OWS/commonmark-sup-sub-extensions) - Adds support of superscript and subscript (`` and `` HTML tags). + - [YouTube iframe extension](https://github.com/zoonru/commonmark-ext-youtube-iframe) - Replaces youtube link with iframe. + - [Lazy Image extension](https://github.com/simonvomeyser/commonmark-ext-lazy-image) - Adds various options for lazy loading of images. + - [Marker Extension](https://github.com/noah1400/commonmark-marker-extension) - Adds support of highlighted text (`` HTML tag). + - [Pygments Highlighter extension](https://github.com/DanielEScherzer/commonmark-ext-pygments-highlighter) - Adds support for highlighting code with the Pygments library. + - [LatexRenderer extension](https://github.com/samwilson/commonmark-latex) - For rendering Markdown to LaTeX. + +Others can be found on [Packagist under the `commonmark-extension` package type](https://packagist.org/packages/league/commonmark?type=commonmark-extension). + +If you build your own, feel free to submit a PR to add it to this list! + +### Others + +Check out the other cool things people are doing with `league/commonmark`: + +## 🏷️ Versioning + +[SemVer](http://semver.org/) is followed closely. Minor and patch releases should not introduce breaking changes to the codebase; however, they might change the resulting AST or HTML output of parsed Markdown (due to bug fixes, spec changes, etc.) As a result, you might get slightly different HTML, but any custom code built onto this library should still function correctly. + +Any classes or methods marked `@internal` are not intended for use outside of this library and are subject to breaking changes at any time, so please avoid using them. + +## 🛠️ Maintenance & Support + +When a new **minor** version (e.g. `2.0` -> `2.1`) is released, the previous one (`2.0`) will continue to receive security and critical bug fixes for *at least* 3 months. + +When a new **major** version is released (e.g. `1.6` -> `2.0`), the previous one (`1.6`) will receive critical bug fixes for *at least* 3 months and security updates for 6 months after that new release comes out. + +(This policy may change in the future and exceptions may be made on a case-by-case basis.) + +**Professional support, including notification of new releases and security updates, is available through a [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-league-commonmark?utm_source=packagist-league-commonmark&utm_medium=referral&utm_campaign=readme).** + +## 👷‍♀️ Contributing + +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. + +Contributions to this library are **welcome**, especially ones that: + + * Improve usability or flexibility without compromising our ability to adhere to the [CommonMark spec] + * Mirror fixes made to the [reference implementation][commonmark.js] + * Optimize performance + * Fix issues with adhering to the [CommonMark spec] + +Major refactoring to core parsing logic should be avoided if possible so that we can easily follow updates made to [the reference implementation][commonmark.js]. That being said, we will absolutely consider changes which don't deviate too far from the reference spec or which are favored by other popular CommonMark implementations. + +Please see [CONTRIBUTING](https://github.com/thephpleague/commonmark/blob/main/.github/CONTRIBUTING.md) for additional details. + +## 🧪 Testing + +``` bash +$ composer test +``` + +This will also test league/commonmark against the latest supported spec. + +## 🚀 Performance Benchmarks + +You can compare the performance of **league/commonmark** to other popular parsers by running the included benchmark tool: + +``` bash +$ ./tests/benchmark/benchmark.php +``` + +## 👥 Credits & Acknowledgements + +This code was originally based on the [CommonMark JS reference implementation][commonmark.js] which is written, maintained, and copyrighted by [John MacFarlane]. This project simply wouldn't exist without his work. + +And a huge thanks to all of our amazing contributors: + +
+ + + +### Sponsors + +We'd also like to extend our sincere thanks the following sponsors who support ongoing development of this project: + + - [Tidelift](https://tidelift.com/subscription/pkg/packagist-league-commonmark?utm_source=packagist-league-commonmark&utm_medium=referral&utm_campaign=readme) for offering support to both the maintainers and end-users through their [professional support](https://tidelift.com/subscription/pkg/packagist-league-commonmark?utm_source=packagist-league-commonmark&utm_medium=referral&utm_campaign=readme) program + - [Blackfire](https://www.blackfire.io/) for providing an Open-Source Profiler subscription + - [JetBrains](https://www.jetbrains.com/) for supporting this project with complimentary [PhpStorm](https://www.jetbrains.com/phpstorm/) licenses + - [Anthropic](https://www.anthropic.com/) for providing complimentary access to Claude Max through their [Open Source Program](https://claude.com/contact-sales/claude-for-oss) + +Are you interested in sponsoring development of this project? See for a list of ways to contribute. + +## 📄 License + +**league/commonmark** is licensed under the BSD-3 license. See the [`LICENSE`](LICENSE) file for more details. + +## 🏛️ Governance + +This project is primarily maintained by [Colin O'Dell][@colinodell]. Members of the [PHP League] Leadership Team may occasionally assist with some of these duties. + +## 🗺️ Who Uses It? + +This project is used by [Drupal](https://www.drupal.org/project/markdown), [Laravel Framework](https://laravel.com/), [Cachet](https://cachethq.io/), [Firefly III](https://firefly-iii.org/), [Neos](https://www.neos.io/), [Daux.io](https://daux.io/), and [more](https://packagist.org/packages/league/commonmark/dependents)! + +--- + +
+ + Get professional support for league/commonmark with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +[CommonMark]: http://commonmark.org/ +[CommonMark spec]: http://spec.commonmark.org/ +[commonmark.js]: https://github.com/jgm/commonmark.js +[GitHub-Flavored Markdown]: https://github.github.com/gfm/ +[John MacFarlane]: http://johnmacfarlane.net +[docs]: https://commonmark.thephpleague.com/ +[docs-examples]: https://commonmark.thephpleague.com/customization/overview/#examples +[docs-example-twitter]: https://commonmark.thephpleague.com/customization/inline-parsing#example-1---twitter-handles +[docs-example-smilies]: https://commonmark.thephpleague.com/customization/inline-parsing#example-2---emoticons +[All Contributors]: https://github.com/thephpleague/commonmark/contributors +[@colinodell]: https://www.twitter.com/colinodell +[@jgm]: https://github.com/jgm +[jgm/stmd]: https://github.com/jgm/stmd +[Composer]: https://getcomposer.org/ +[PHP League]: https://thephpleague.com diff --git a/vendor/league/commonmark/composer.json b/vendor/league/commonmark/composer.json new file mode 100644 index 0000000..3d3834f --- /dev/null +++ b/vendor/league/commonmark/composer.json @@ -0,0 +1,129 @@ +{ + "name": "league/commonmark", + "type": "library", + "description": "Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)", + "keywords": ["markdown","parser","commonmark","gfm","github","flavored","github-flavored","md"], + "homepage": "https://commonmark.thephpleague.com", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "support": { + "docs": "https://commonmark.thephpleague.com/", + "forum": "https://github.com/thephpleague/commonmark/discussions", + "issues": "https://github.com/thephpleague/commonmark/issues", + "rss": "https://github.com/thephpleague/commonmark/releases.atom", + "source": "https://github.com/thephpleague/commonmark" + }, + "require": { + "php": "^7.4 || ^8.0", + "ext-mbstring": "*", + "league/config": "^1.1.1", + "psr/event-dispatcher": "^1.0", + "symfony/deprecation-contracts": "^2.1 || ^3.0", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "ext-json": "*", + "cebe/markdown": "^1.0", + "commonmark/cmark": "0.31.1", + "commonmark/commonmark.js": "0.31.1", + "composer/package-versions-deprecated": "^1.8", + "embed/embed": "^4.4", + "erusev/parsedown": "^1.0", + "github/gfm": "0.29.0", + "michelf/php-markdown": "^1.4 || ^2.0", + "nyholm/psr7": "^1.5", + "phpstan/phpstan": "^2.0.0", + "phpunit/phpunit": "^9.5.21 || ^10.5.9 || ^11.0.0 || ^12.0.0 || ^13.0.0", + "scrutinizer/ocular": "^1.8.1", + "symfony/finder": "^5.3 | ^6.0 | ^7.0 || ^8.0", + "symfony/process": "^5.4 | ^6.0 | ^7.0 || ^8.0", + "symfony/yaml": "^2.3 | ^3.0 | ^4.0 | ^5.0 | ^6.0 | ^7.0 || ^8.0", + "unleashedtech/php-coding-standard": "^3.1.1", + "vimeo/psalm": "^4.24.0 || ^5.0.0 || ^6.0.0" + }, + "minimum-stability": "beta", + "suggest": { + "symfony/yaml": "v2.3+ required if using the Front Matter extension" + }, + "repositories": [ + { + "type": "package", + "package": { + "name": "commonmark/commonmark.js", + "version": "0.31.1", + "dist": { + "url": "https://github.com/commonmark/commonmark.js/archive/0.31.1.zip", + "type": "zip" + } + } + }, + { + "type": "package", + "package": { + "name": "commonmark/cmark", + "version": "0.31.1", + "dist": { + "url": "https://github.com/commonmark/cmark/archive/0.31.1.zip", + "type": "zip" + } + } + }, + { + "type": "package", + "package": { + "name": "github/gfm", + "version": "0.29.0", + "dist": { + "url": "https://github.com/github/cmark-gfm/archive/0.29.0.gfm.13.zip", + "type": "zip" + } + } + } + ], + "autoload": { + "psr-4": { + "League\\CommonMark\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "League\\CommonMark\\Tests\\Unit\\": "tests/unit", + "League\\CommonMark\\Tests\\Functional\\": "tests/functional", + "League\\CommonMark\\Tests\\PHPStan\\": "tests/phpstan" + } + }, + "scripts": { + "phpcs": "phpcs", + "phpcbf": "phpcbf", + "phpstan": "phpstan analyse", + "phpunit": "phpunit --no-coverage", + "psalm": "psalm --stats", + "pathological": "tests/pathological/test.php", + "test": [ + "@phpcs", + "@phpstan", + "@psalm", + "@phpunit", + "@pathological" + ] + }, + "extra": { + "branch-alias": { + "dev-main": "2.11-dev" + } + }, + "config": { + "allow-plugins": { + "composer/package-versions-deprecated": true, + "dealerdirect/phpcodesniffer-composer-installer": true + }, + "sort-packages": true + } +} diff --git a/vendor/league/commonmark/src/CommonMarkConverter.php b/vendor/league/commonmark/src/CommonMarkConverter.php new file mode 100644 index 0000000..4d70053 --- /dev/null +++ b/vendor/league/commonmark/src/CommonMarkConverter.php @@ -0,0 +1,46 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Environment\Environment; +use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; + +/** + * Converts CommonMark-compatible Markdown to HTML. + */ +final class CommonMarkConverter extends MarkdownConverter +{ + /** + * Create a new Markdown converter pre-configured for CommonMark + * + * @param array $config + */ + public function __construct(array $config = []) + { + $environment = new Environment($config); + $environment->addExtension(new CommonMarkCoreExtension()); + + parent::__construct($environment); + } + + public function getEnvironment(): Environment + { + \assert($this->environment instanceof Environment); + + return $this->environment; + } +} diff --git a/vendor/league/commonmark/src/ConverterInterface.php b/vendor/league/commonmark/src/ConverterInterface.php new file mode 100644 index 0000000..8192b0f --- /dev/null +++ b/vendor/league/commonmark/src/ConverterInterface.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Output\RenderedContentInterface; +use League\Config\Exception\ConfigurationExceptionInterface; + +/** + * Interface for a service which converts content from one format (like Markdown) to another (like HTML). + */ +interface ConverterInterface +{ + /** + * @throws CommonMarkException + * @throws ConfigurationExceptionInterface + */ + public function convert(string $input): RenderedContentInterface; +} diff --git a/vendor/league/commonmark/src/Delimiter/Bracket.php b/vendor/league/commonmark/src/Delimiter/Bracket.php new file mode 100644 index 0000000..3a86859 --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/Bracket.php @@ -0,0 +1,83 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter; + +use League\CommonMark\Node\Node; + +final class Bracket +{ + private Node $node; + private ?Bracket $previous; + private bool $hasNext = false; + private int $position; + private bool $image; + private bool $active = true; + + public function __construct(Node $node, ?Bracket $previous, int $position, bool $image) + { + $this->node = $node; + $this->previous = $previous; + $this->position = $position; + $this->image = $image; + } + + public function getNode(): Node + { + return $this->node; + } + + public function getPrevious(): ?Bracket + { + return $this->previous; + } + + public function hasNext(): bool + { + return $this->hasNext; + } + + public function getPosition(): int + { + return $this->position; + } + + public function isImage(): bool + { + return $this->image; + } + + /** + * Only valid in the context of non-images (links) + */ + public function isActive(): bool + { + return $this->active; + } + + /** + * @internal + */ + public function setHasNext(bool $hasNext): void + { + $this->hasNext = $hasNext; + } + + /** + * @internal + */ + public function setActive(bool $active): void + { + $this->active = $active; + } +} diff --git a/vendor/league/commonmark/src/Delimiter/Delimiter.php b/vendor/league/commonmark/src/Delimiter/Delimiter.php new file mode 100644 index 0000000..2f04f24 --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/Delimiter.php @@ -0,0 +1,134 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter; + +use League\CommonMark\Node\Inline\AbstractStringContainer; + +final class Delimiter implements DelimiterInterface +{ + /** @psalm-readonly */ + private string $char; + + /** @psalm-readonly-allow-private-mutation */ + private int $length; + + /** @psalm-readonly */ + private int $originalLength; + + /** @psalm-readonly */ + private AbstractStringContainer $inlineNode; + + /** @psalm-readonly-allow-private-mutation */ + private ?DelimiterInterface $previous = null; + + /** @psalm-readonly-allow-private-mutation */ + private ?DelimiterInterface $next = null; + + /** @psalm-readonly */ + private bool $canOpen; + + /** @psalm-readonly */ + private bool $canClose; + + /** @psalm-readonly-allow-private-mutation */ + private bool $active; + + /** @psalm-readonly */ + private ?int $index = null; + + public function __construct(string $char, int $numDelims, AbstractStringContainer $node, bool $canOpen, bool $canClose, ?int $index = null) + { + $this->char = $char; + $this->length = $numDelims; + $this->originalLength = $numDelims; + $this->inlineNode = $node; + $this->canOpen = $canOpen; + $this->canClose = $canClose; + $this->active = true; + $this->index = $index; + } + + public function canClose(): bool + { + return $this->canClose; + } + + public function canOpen(): bool + { + return $this->canOpen; + } + + public function isActive(): bool + { + return $this->active; + } + + public function setActive(bool $active): void + { + $this->active = $active; + } + + public function getChar(): string + { + return $this->char; + } + + public function getIndex(): ?int + { + return $this->index; + } + + public function getNext(): ?DelimiterInterface + { + return $this->next; + } + + public function setNext(?DelimiterInterface $next): void + { + $this->next = $next; + } + + public function getLength(): int + { + return $this->length; + } + + public function setLength(int $length): void + { + $this->length = $length; + } + + public function getOriginalLength(): int + { + return $this->originalLength; + } + + public function getInlineNode(): AbstractStringContainer + { + return $this->inlineNode; + } + + public function getPrevious(): ?DelimiterInterface + { + return $this->previous; + } + + public function setPrevious(?DelimiterInterface $previous): void + { + $this->previous = $previous; + } +} diff --git a/vendor/league/commonmark/src/Delimiter/DelimiterInterface.php b/vendor/league/commonmark/src/Delimiter/DelimiterInterface.php new file mode 100644 index 0000000..0cefba7 --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/DelimiterInterface.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter; + +use League\CommonMark\Node\Inline\AbstractStringContainer; + +interface DelimiterInterface +{ + public function canClose(): bool; + + public function canOpen(): bool; + + /** + * @deprecated This method is no longer used internally and will be removed in 3.0 + */ + public function isActive(): bool; + + /** + * @deprecated This method is no longer used internally and will be removed in 3.0 + */ + public function setActive(bool $active): void; + + public function getChar(): string; + + public function getIndex(): ?int; + + public function getNext(): ?DelimiterInterface; + + public function setNext(?DelimiterInterface $next): void; + + public function getLength(): int; + + public function setLength(int $length): void; + + public function getOriginalLength(): int; + + public function getInlineNode(): AbstractStringContainer; + + public function getPrevious(): ?DelimiterInterface; + + public function setPrevious(?DelimiterInterface $previous): void; +} diff --git a/vendor/league/commonmark/src/Delimiter/DelimiterParser.php b/vendor/league/commonmark/src/Delimiter/DelimiterParser.php new file mode 100644 index 0000000..fdfe093 --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/DelimiterParser.php @@ -0,0 +1,106 @@ +collection = $collection; + } + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf(...$this->collection->getDelimiterCharacters()); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $character = $inlineContext->getFullMatch(); + $numDelims = 0; + $cursor = $inlineContext->getCursor(); + $processor = $this->collection->getDelimiterProcessor($character); + + \assert($processor !== null); // Delimiter processor should never be null here + + $charBefore = $cursor->peek(-1); + if ($charBefore === null) { + $charBefore = "\n"; + } + + while ($cursor->peek($numDelims) === $character) { + ++$numDelims; + } + + if ($numDelims < $processor->getMinLength()) { + return false; + } + + $cursor->advanceBy($numDelims); + + $charAfter = $cursor->getCurrentCharacter(); + if ($charAfter === null) { + $charAfter = "\n"; + } + + [$canOpen, $canClose] = self::determineCanOpenOrClose($charBefore, $charAfter, $character, $processor); + + if (! ($canOpen || $canClose)) { + $inlineContext->getContainer()->appendChild(new Text(\str_repeat($character, $numDelims))); + + return true; + } + + $node = new Text(\str_repeat($character, $numDelims), [ + 'delim' => true, + ]); + $inlineContext->getContainer()->appendChild($node); + + // Add entry to stack to this opener + $delimiter = new Delimiter($character, $numDelims, $node, $canOpen, $canClose, $inlineContext->getCursor()->getPosition()); + $inlineContext->getDelimiterStack()->push($delimiter); + + return true; + } + + /** + * @return bool[] + */ + private static function determineCanOpenOrClose(string $charBefore, string $charAfter, string $character, DelimiterProcessorInterface $delimiterProcessor): array + { + $afterIsWhitespace = \preg_match(RegexHelper::REGEX_UNICODE_WHITESPACE_CHAR, $charAfter); + $afterIsPunctuation = \preg_match(RegexHelper::REGEX_PUNCTUATION, $charAfter); + $beforeIsWhitespace = \preg_match(RegexHelper::REGEX_UNICODE_WHITESPACE_CHAR, $charBefore); + $beforeIsPunctuation = \preg_match(RegexHelper::REGEX_PUNCTUATION, $charBefore); + + $leftFlanking = ! $afterIsWhitespace && (! $afterIsPunctuation || $beforeIsWhitespace || $beforeIsPunctuation); + $rightFlanking = ! $beforeIsWhitespace && (! $beforeIsPunctuation || $afterIsWhitespace || $afterIsPunctuation); + + if ($character === '_') { + $canOpen = $leftFlanking && (! $rightFlanking || $beforeIsPunctuation); + $canClose = $rightFlanking && (! $leftFlanking || $afterIsPunctuation); + } else { + $canOpen = $leftFlanking && $character === $delimiterProcessor->getOpeningCharacter(); + $canClose = $rightFlanking && $character === $delimiterProcessor->getClosingCharacter(); + } + + return [$canOpen, $canClose]; + } +} diff --git a/vendor/league/commonmark/src/Delimiter/DelimiterStack.php b/vendor/league/commonmark/src/Delimiter/DelimiterStack.php new file mode 100644 index 0000000..542654d --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/DelimiterStack.php @@ -0,0 +1,396 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter; + +use League\CommonMark\Delimiter\Processor\CacheableDelimiterProcessorInterface; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorCollection; +use League\CommonMark\Node\Inline\AdjacentTextMerger; +use League\CommonMark\Node\Node; + +final class DelimiterStack +{ + /** @psalm-readonly-allow-private-mutation */ + private ?DelimiterInterface $top = null; + + /** @psalm-readonly-allow-private-mutation */ + private ?Bracket $brackets = null; + + /** + * @deprecated This property will be removed in 3.0 once all delimiters MUST have an index/position + * + * @var \SplObjectStorage|\WeakMap + */ + private $missingIndexCache; + + + private int $remainingDelimiters = 0; + + public function __construct(int $maximumStackSize = PHP_INT_MAX) + { + $this->remainingDelimiters = $maximumStackSize; + + if (\PHP_VERSION_ID >= 80000) { + /** @psalm-suppress PropertyTypeCoercion */ + $this->missingIndexCache = new \WeakMap(); // @phpstan-ignore-line + } else { + $this->missingIndexCache = new \SplObjectStorage(); + } + } + + public function push(DelimiterInterface $newDelimiter): void + { + if ($this->remainingDelimiters-- <= 0) { + return; + } + + $newDelimiter->setPrevious($this->top); + + if ($this->top !== null) { + $this->top->setNext($newDelimiter); + } + + $this->top = $newDelimiter; + } + + /** + * @internal + */ + public function addBracket(Node $node, int $index, bool $image): void + { + if ($this->brackets !== null) { + $this->brackets->setHasNext(true); + } + + $this->brackets = new Bracket($node, $this->brackets, $index, $image); + } + + /** + * @psalm-immutable + */ + public function getLastBracket(): ?Bracket + { + return $this->brackets; + } + + private function findEarliest(int $stackBottom): ?DelimiterInterface + { + // Move back to first relevant delim. + $delimiter = $this->top; + $lastChecked = null; + + while ($delimiter !== null && self::getIndex($delimiter) > $stackBottom) { + $lastChecked = $delimiter; + $delimiter = $delimiter->getPrevious(); + } + + return $lastChecked; + } + + /** + * @internal + */ + public function removeBracket(): void + { + if ($this->brackets === null) { + return; + } + + $this->brackets = $this->brackets->getPrevious(); + + if ($this->brackets !== null) { + $this->brackets->setHasNext(false); + } + } + + public function removeDelimiter(DelimiterInterface $delimiter): void + { + if ($delimiter->getPrevious() !== null) { + /** @psalm-suppress PossiblyNullReference */ + $delimiter->getPrevious()->setNext($delimiter->getNext()); + } + + if ($delimiter->getNext() === null) { + // top of stack + $this->top = $delimiter->getPrevious(); + } else { + /** @psalm-suppress PossiblyNullReference */ + $delimiter->getNext()->setPrevious($delimiter->getPrevious()); + } + + // Nullify all references from the removed delimiter to other delimiters. + // All references to this particular delimiter in the linked list should be gone, + // but it's possible we're still hanging on to other references to things that + // have been (or soon will be) removed, which may interfere with efficient + // garbage collection by the PHP runtime. + // Explicitly releasing these references should help to avoid possible + // segfaults like in https://bugs.php.net/bug.php?id=68606. + $delimiter->setPrevious(null); + $delimiter->setNext(null); + + // TODO: Remove the line below once PHP 7.4 support is dropped, as WeakMap won't hold onto the reference, making this unnecessary + unset($this->missingIndexCache[$delimiter]); + } + + private function removeDelimiterAndNode(DelimiterInterface $delimiter): void + { + $delimiter->getInlineNode()->detach(); + $this->removeDelimiter($delimiter); + } + + private function removeDelimitersBetween(DelimiterInterface $opener, DelimiterInterface $closer): void + { + $delimiter = $closer->getPrevious(); + $openerPosition = self::getIndex($opener); + while ($delimiter !== null && self::getIndex($delimiter) > $openerPosition) { + $previous = $delimiter->getPrevious(); + $this->removeDelimiter($delimiter); + $delimiter = $previous; + } + } + + /** + * @param DelimiterInterface|int|null $stackBottom + */ + public function removeAll($stackBottom = null): void + { + $stackBottomPosition = \is_int($stackBottom) ? $stackBottom : self::getIndex($stackBottom); + + while ($this->top && $this->getIndex($this->top) > $stackBottomPosition) { + $this->removeDelimiter($this->top); + } + } + + /** + * @deprecated This method is no longer used internally and will be removed in 3.0 + */ + public function removeEarlierMatches(string $character): void + { + $opener = $this->top; + while ($opener !== null) { + if ($opener->getChar() === $character) { + $opener->setActive(false); + } + + $opener = $opener->getPrevious(); + } + } + + /** + * @internal + */ + public function deactivateLinkOpeners(): void + { + $opener = $this->brackets; + while ($opener !== null && $opener->isActive()) { + $opener->setActive(false); + $opener = $opener->getPrevious(); + } + } + + /** + * @deprecated This method is no longer used internally and will be removed in 3.0 + * + * @param string|string[] $characters + */ + public function searchByCharacter($characters): ?DelimiterInterface + { + if (! \is_array($characters)) { + $characters = [$characters]; + } + + $opener = $this->top; + while ($opener !== null) { + if (\in_array($opener->getChar(), $characters, true)) { + break; + } + + $opener = $opener->getPrevious(); + } + + return $opener; + } + + /** + * @param DelimiterInterface|int|null $stackBottom + * + * @todo change $stackBottom to an int in 3.0 + */ + public function processDelimiters($stackBottom, DelimiterProcessorCollection $processors): void + { + /** @var array $openersBottom */ + $openersBottom = []; + + $stackBottomPosition = \is_int($stackBottom) ? $stackBottom : self::getIndex($stackBottom); + + // Find first closer above stackBottom + $closer = $this->findEarliest($stackBottomPosition); + + // Move forward, looking for closers, and handling each + while ($closer !== null) { + $closingDelimiterChar = $closer->getChar(); + + $delimiterProcessor = $processors->getDelimiterProcessor($closingDelimiterChar); + if (! $closer->canClose() || $delimiterProcessor === null) { + $closer = $closer->getNext(); + continue; + } + + if ($delimiterProcessor instanceof CacheableDelimiterProcessorInterface) { + $openersBottomCacheKey = $delimiterProcessor->getCacheKey($closer); + } else { + $openersBottomCacheKey = $closingDelimiterChar; + } + + $openingDelimiterChar = $delimiterProcessor->getOpeningCharacter(); + + $useDelims = 0; + $openerFound = false; + $potentialOpenerFound = false; + $opener = $closer->getPrevious(); + while ($opener !== null && ($openerPosition = self::getIndex($opener)) > $stackBottomPosition && $openerPosition >= ($openersBottom[$openersBottomCacheKey] ?? 0)) { + if ($opener->canOpen() && $opener->getChar() === $openingDelimiterChar) { + $potentialOpenerFound = true; + $useDelims = $delimiterProcessor->getDelimiterUse($opener, $closer); + if ($useDelims > 0) { + $openerFound = true; + break; + } + } + + $opener = $opener->getPrevious(); + } + + if (! $openerFound) { + // Set lower bound for future searches + // TODO: Remove this conditional check in 3.0. It only exists to prevent behavioral BC breaks in 2.x. + if ($potentialOpenerFound === false || $delimiterProcessor instanceof CacheableDelimiterProcessorInterface) { + $openersBottom[$openersBottomCacheKey] = self::getIndex($closer); + } + + if (! $potentialOpenerFound && ! $closer->canOpen()) { + // We can remove a closer that can't be an opener, + // once we've seen there's no matching opener. + $next = $closer->getNext(); + $this->removeDelimiter($closer); + $closer = $next; + } else { + $closer = $closer->getNext(); + } + + continue; + } + + \assert($opener !== null); + + $openerNode = $opener->getInlineNode(); + $closerNode = $closer->getInlineNode(); + + // Remove number of used delimiters from stack and inline nodes. + $opener->setLength($opener->getLength() - $useDelims); + $closer->setLength($closer->getLength() - $useDelims); + + $openerNode->setLiteral(\substr($openerNode->getLiteral(), 0, -$useDelims)); + $closerNode->setLiteral(\substr($closerNode->getLiteral(), 0, -$useDelims)); + + $this->removeDelimitersBetween($opener, $closer); + // The delimiter processor can re-parent the nodes between opener and closer, + // so make sure they're contiguous already. Exclusive because we want to keep opener/closer themselves. + AdjacentTextMerger::mergeTextNodesBetweenExclusive($openerNode, $closerNode); + $delimiterProcessor->process($openerNode, $closerNode, $useDelims); + + // No delimiter characters left to process, so we can remove delimiter and the now empty node. + if ($opener->getLength() === 0) { + $this->removeDelimiterAndNode($opener); + } + + // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($closer->getLength() === 0) { + $next = $closer->getNext(); + $this->removeDelimiterAndNode($closer); + $closer = $next; + } + } + + // Remove all delimiters + $this->removeAll($stackBottomPosition); + } + + /** + * @internal + */ + public function __destruct() + { + while ($this->top) { + $this->removeDelimiter($this->top); + } + + while ($this->brackets) { + $this->removeBracket(); + } + } + + /** + * @deprecated This method will be dropped in 3.0 once all delimiters MUST have an index/position + */ + private function getIndex(?DelimiterInterface $delimiter): int + { + if ($delimiter === null) { + return -1; + } + + if (($index = $delimiter->getIndex()) !== null) { + return $index; + } + + if (isset($this->missingIndexCache[$delimiter])) { + return $this->missingIndexCache[$delimiter]; + } + + $prev = $delimiter->getPrevious(); + $next = $delimiter->getNext(); + + $i = 0; + do { + $i++; + if ($prev === null) { + break; + } + + if ($prev->getIndex() !== null) { + return $this->missingIndexCache[$delimiter] = $prev->getIndex() + $i; + } + } while ($prev = $prev->getPrevious()); + + $j = 0; + do { + $j++; + if ($next === null) { + break; + } + + if ($next->getIndex() !== null) { + return $this->missingIndexCache[$delimiter] = $next->getIndex() - $j; + } + } while ($next = $next->getNext()); + + // No index was defined on this delimiter, and none could be guesstimated based on the stack. + return $this->missingIndexCache[$delimiter] = $this->getIndex($delimiter->getPrevious()) + 1; + } +} diff --git a/vendor/league/commonmark/src/Delimiter/Processor/CacheableDelimiterProcessorInterface.php b/vendor/league/commonmark/src/Delimiter/Processor/CacheableDelimiterProcessorInterface.php new file mode 100644 index 0000000..a2a9b7e --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/Processor/CacheableDelimiterProcessorInterface.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Delimiter\DelimiterInterface; + +/** + * Special marker interface for delimiter processors that return dynamic values from getDelimiterUse() + * + * In order to guarantee linear performance of delimiter processing, the delimiter stack must be able to + * cache the lower bound when searching for a matching opener. This gets complicated for delimiter processors + * that use a dynamic number of characters (like with emphasis and its "multiple of 3" rule). + */ +interface CacheableDelimiterProcessorInterface extends DelimiterProcessorInterface +{ + /** + * Returns a cache key of the factors that determine the number of characters to use. + * + * In order to guarantee linear performance of delimiter processing, the delimiter stack must be able to + * cache the lower bound when searching for a matching opener. This lower bound is usually quite simple; + * for example, with quotes, it's just the last opener with that characted. However, this gets complicated + * for delimiter processors that use a dynamic number of characters (like with emphasis and its "multiple + * of 3" rule), because the delimiter length being considered may change during processing because of that + * dynamic logic in getDelimiterUse(). Therefore, we cannot safely cache the lower bound for these dynamic + * processors without knowing the factors that determine the number of characters to use. + * + * At a minimum, this should include the delimiter character, plus any other factors used to determine + * the result of getDelimiterUse(). The format of the string is not important so long as it is unique + * (compared to other processors) and consistent for a given set of factors. + * + * If getDelimiterUse() always returns the same hard-coded value, this method should return just + * the delimiter character. + */ + public function getCacheKey(DelimiterInterface $closer): string; +} diff --git a/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollection.php b/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollection.php new file mode 100644 index 0000000..6e9f336 --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollection.php @@ -0,0 +1,89 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Exception\InvalidArgumentException; + +final class DelimiterProcessorCollection implements DelimiterProcessorCollectionInterface +{ + /** + * @var array|DelimiterProcessorInterface[] + * + * @psalm-readonly-allow-private-mutation + */ + private array $processorsByChar = []; + + public function add(DelimiterProcessorInterface $processor): void + { + $opening = $processor->getOpeningCharacter(); + $closing = $processor->getClosingCharacter(); + + if ($opening === $closing) { + $old = $this->processorsByChar[$opening] ?? null; + if ($old !== null && $old->getOpeningCharacter() === $old->getClosingCharacter()) { + $this->addStaggeredDelimiterProcessorForChar($opening, $old, $processor); + } else { + $this->addDelimiterProcessorForChar($opening, $processor); + } + } else { + $this->addDelimiterProcessorForChar($opening, $processor); + $this->addDelimiterProcessorForChar($closing, $processor); + } + } + + public function getDelimiterProcessor(string $char): ?DelimiterProcessorInterface + { + return $this->processorsByChar[$char] ?? null; + } + + /** + * @return string[] + */ + public function getDelimiterCharacters(): array + { + return \array_keys($this->processorsByChar); + } + + private function addDelimiterProcessorForChar(string $delimiterChar, DelimiterProcessorInterface $processor): void + { + if (isset($this->processorsByChar[$delimiterChar])) { + throw new InvalidArgumentException(\sprintf('Delim processor for character "%s" already exists', $processor->getOpeningCharacter())); + } + + $this->processorsByChar[$delimiterChar] = $processor; + } + + private function addStaggeredDelimiterProcessorForChar(string $opening, DelimiterProcessorInterface $old, DelimiterProcessorInterface $new): void + { + if ($old instanceof StaggeredDelimiterProcessor) { + $s = $old; + } else { + $s = new StaggeredDelimiterProcessor($opening, $old); + } + + $s->add($new); + $this->processorsByChar[$opening] = $s; + } + + public function count(): int + { + return \count($this->processorsByChar); + } +} diff --git a/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollectionInterface.php b/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollectionInterface.php new file mode 100644 index 0000000..fea3ddb --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorCollectionInterface.php @@ -0,0 +1,46 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Exception\InvalidArgumentException; + +interface DelimiterProcessorCollectionInterface extends \Countable +{ + /** + * Add the given delim processor to the collection + * + * @param DelimiterProcessorInterface $processor The delim processor to add + * + * @throws InvalidArgumentException Exception will be thrown if attempting to add multiple processors for the same character + */ + public function add(DelimiterProcessorInterface $processor): void; + + /** + * Returns the delim processor which handles the given character if one exists + */ + public function getDelimiterProcessor(string $char): ?DelimiterProcessorInterface; + + /** + * Returns an array of delimiter characters who have associated processors + * + * @return string[] + */ + public function getDelimiterCharacters(): array; +} diff --git a/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorInterface.php b/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorInterface.php new file mode 100644 index 0000000..5e88ddc --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/Processor/DelimiterProcessorInterface.php @@ -0,0 +1,81 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +/** + * Interface for a delimiter processor + */ +interface DelimiterProcessorInterface +{ + /** + * Returns the character that marks the beginning of a delimited node. + * + * This must not clash with any other processors being added to the environment. + */ + public function getOpeningCharacter(): string; + + /** + * Returns the character that marks the ending of a delimited node. + * + * This must not clash with any other processors being added to the environment. + * + * Note that for a symmetric delimiter such as "*", this is the same as the opening. + */ + public function getClosingCharacter(): string; + + /** + * Minimum number of delimiter characters that are needed to active this. + * + * Must be at least 1. + */ + public function getMinLength(): int; + + /** + * Determine how many (if any) of the delimiter characters should be used. + * + * This allows implementations to decide how many characters to be used + * based on the properties of the delimiter runs. An implementation can also + * return 0 when it doesn't want to allow this particular combination of + * delimiter runs. + * + * IMPORTANT: Unless this method returns the same hard-coded value in all cases, + * you MUST implement the CacheableDelimiterProcessorInterface interface instead. + * + * @param DelimiterInterface $opener The opening delimiter run + * @param DelimiterInterface $closer The closing delimiter run + */ + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int; + + /** + * Process the matched delimiters, e.g. by wrapping the nodes between opener + * and closer in a new node, or appending a new node after the opener. + * + * Note that removal of the delimiter from the delimiter nodes and detaching + * them is done by the caller. + * + * @param AbstractStringContainer $opener The node that contained the opening delimiter + * @param AbstractStringContainer $closer The node that contained the closing delimiter + * @param int $delimiterUse The number of delimiters that were used + */ + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void; +} diff --git a/vendor/league/commonmark/src/Delimiter/Processor/StaggeredDelimiterProcessor.php b/vendor/league/commonmark/src/Delimiter/Processor/StaggeredDelimiterProcessor.php new file mode 100644 index 0000000..7d33e83 --- /dev/null +++ b/vendor/league/commonmark/src/Delimiter/Processor/StaggeredDelimiterProcessor.php @@ -0,0 +1,111 @@ + + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Delimiter\Processor; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +/** + * An implementation of DelimiterProcessorInterface that dispatches all calls to two or more other DelimiterProcessors + * depending on the length of the delimiter run. All child DelimiterProcessors must have different minimum + * lengths. A given delimiter run is dispatched to the child with the largest acceptable minimum length. If no + * child is applicable, the one with the largest minimum length is chosen. + * + * @internal + */ +final class StaggeredDelimiterProcessor implements DelimiterProcessorInterface +{ + /** @psalm-readonly */ + private string $delimiterChar; + + /** @psalm-readonly-allow-private-mutation */ + private int $minLength = 0; + + /** + * @var array|DelimiterProcessorInterface[] + * + * @psalm-readonly-allow-private-mutation + */ + private array $processors = []; // keyed by minLength in reverse order + + public function __construct(string $char, DelimiterProcessorInterface $processor) + { + $this->delimiterChar = $char; + $this->add($processor); + } + + public function getOpeningCharacter(): string + { + return $this->delimiterChar; + } + + public function getClosingCharacter(): string + { + return $this->delimiterChar; + } + + public function getMinLength(): int + { + return $this->minLength; + } + + /** + * Adds the given processor to this staggered delimiter processor + * + * @throws InvalidArgumentException if attempting to add another processors for the same character and minimum length + */ + public function add(DelimiterProcessorInterface $processor): void + { + $len = $processor->getMinLength(); + + if (isset($this->processors[$len])) { + throw new InvalidArgumentException(\sprintf('Cannot add two delimiter processors for char "%s" and minimum length %d', $this->delimiterChar, $len)); + } + + $this->processors[$len] = $processor; + \krsort($this->processors); + + $this->minLength = \min($this->minLength, $len); + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + return $this->findProcessor($opener->getLength())->getDelimiterUse($opener, $closer); + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + $this->findProcessor($delimiterUse)->process($opener, $closer, $delimiterUse); + } + + private function findProcessor(int $len): DelimiterProcessorInterface + { + // Find the "longest" processor which can handle this length + foreach ($this->processors as $processor) { + if ($processor->getMinLength() <= $len) { + return $processor; + } + } + + // Just use the first one in our list + $first = \reset($this->processors); + \assert($first instanceof DelimiterProcessorInterface); + + return $first; + } +} diff --git a/vendor/league/commonmark/src/Environment/Environment.php b/vendor/league/commonmark/src/Environment/Environment.php new file mode 100644 index 0000000..80aa364 --- /dev/null +++ b/vendor/league/commonmark/src/Environment/Environment.php @@ -0,0 +1,454 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Environment; + +use League\CommonMark\Delimiter\DelimiterParser; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorCollection; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Event\ListenerData; +use League\CommonMark\Exception\AlreadyInitializedException; +use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Extension\GithubFlavoredMarkdownExtension; +use League\CommonMark\Normalizer\SlugNormalizer; +use League\CommonMark\Normalizer\TextNormalizerInterface; +use League\CommonMark\Normalizer\UniqueSlugNormalizer; +use League\CommonMark\Normalizer\UniqueSlugNormalizerInterface; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Block\SkipLinesStartingWithLettersParser; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlFilter; +use League\CommonMark\Util\PrioritizedList; +use League\Config\Configuration; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; +use Nette\Schema\Expect; +use Psr\EventDispatcher\EventDispatcherInterface; +use Psr\EventDispatcher\ListenerProviderInterface; +use Psr\EventDispatcher\StoppableEventInterface; + +final class Environment implements EnvironmentInterface, EnvironmentBuilderInterface, ListenerProviderInterface +{ + /** + * @var ExtensionInterface[] + * + * @psalm-readonly-allow-private-mutation + */ + private array $extensions = []; + + /** + * @var ExtensionInterface[] + * + * @psalm-readonly-allow-private-mutation + */ + private array $uninitializedExtensions = []; + + /** @psalm-readonly-allow-private-mutation */ + private bool $extensionsInitialized = false; + + /** + * @var PrioritizedList + * + * @psalm-readonly + */ + private PrioritizedList $blockStartParsers; + + /** + * @var PrioritizedList + * + * @psalm-readonly + */ + private PrioritizedList $inlineParsers; + + /** @psalm-readonly */ + private DelimiterProcessorCollection $delimiterProcessors; + + /** + * @var array> + * + * @psalm-readonly-allow-private-mutation + */ + private array $renderersByClass = []; + + /** + * @var PrioritizedList + * + * @psalm-readonly-allow-private-mutation + */ + private PrioritizedList $listenerData; + + private ?EventDispatcherInterface $eventDispatcher = null; + + /** @psalm-readonly */ + private Configuration $config; + + private ?TextNormalizerInterface $slugNormalizer = null; + + /** + * @param array $config + */ + public function __construct(array $config = []) + { + $this->config = self::createDefaultConfiguration(); + $this->config->merge($config); + + $this->blockStartParsers = new PrioritizedList(); + $this->inlineParsers = new PrioritizedList(); + $this->listenerData = new PrioritizedList(); + $this->delimiterProcessors = new DelimiterProcessorCollection(); + + // Performance optimization: always include a block "parser" that aborts parsing if a line starts with a letter + // and is therefore unlikely to match any lines as a block start. + $this->addBlockStartParser(new SkipLinesStartingWithLettersParser(), 249); + } + + public function getConfiguration(): ConfigurationInterface + { + return $this->config->reader(); + } + + /** + * @deprecated Environment::mergeConfig() is deprecated since league/commonmark v2.0 and will be removed in v3.0. Configuration should be set when instantiating the environment instead. + * + * @param array $config + */ + public function mergeConfig(array $config): void + { + @\trigger_error('Environment::mergeConfig() is deprecated since league/commonmark v2.0 and will be removed in v3.0. Configuration should be set when instantiating the environment instead.', \E_USER_DEPRECATED); + + $this->assertUninitialized('Failed to modify configuration.'); + + $this->config->merge($config); + } + + public function addBlockStartParser(BlockStartParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add block start parser.'); + + $this->blockStartParsers->add($parser, $priority); + $this->injectEnvironmentAndConfigurationIfNeeded($parser); + + return $this; + } + + public function addInlineParser(InlineParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add inline parser.'); + + $this->inlineParsers->add($parser, $priority); + $this->injectEnvironmentAndConfigurationIfNeeded($parser); + + return $this; + } + + public function addDelimiterProcessor(DelimiterProcessorInterface $processor): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add delimiter processor.'); + $this->delimiterProcessors->add($processor); + $this->injectEnvironmentAndConfigurationIfNeeded($processor); + + return $this; + } + + public function addRenderer(string $nodeClass, NodeRendererInterface $renderer, int $priority = 0): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add renderer.'); + + if (! isset($this->renderersByClass[$nodeClass])) { + $this->renderersByClass[$nodeClass] = new PrioritizedList(); + } + + $this->renderersByClass[$nodeClass]->add($renderer, $priority); + $this->injectEnvironmentAndConfigurationIfNeeded($renderer); + + return $this; + } + + /** + * {@inheritDoc} + */ + public function getBlockStartParsers(): iterable + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + return $this->blockStartParsers->getIterator(); + } + + public function getDelimiterProcessors(): DelimiterProcessorCollection + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + return $this->delimiterProcessors; + } + + /** + * {@inheritDoc} + */ + public function getRenderersForClass(string $nodeClass): iterable + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + // If renderers are defined for this specific class, return them immediately + if (isset($this->renderersByClass[$nodeClass])) { + return $this->renderersByClass[$nodeClass]; + } + + /** @psalm-suppress TypeDoesNotContainType -- Bug: https://github.com/vimeo/psalm/issues/3332 */ + while (\class_exists($parent ??= $nodeClass) && $parent = \get_parent_class($parent)) { + if (! isset($this->renderersByClass[$parent])) { + continue; + } + + // "Cache" this result to avoid future loops + return $this->renderersByClass[$nodeClass] = $this->renderersByClass[$parent]; + } + + return []; + } + + /** + * {@inheritDoc} + */ + public function getExtensions(): iterable + { + return $this->extensions; + } + + /** + * Add a single extension + * + * @return $this + */ + public function addExtension(ExtensionInterface $extension): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add extension.'); + + $this->extensions[] = $extension; + $this->uninitializedExtensions[] = $extension; + + if ($extension instanceof ConfigurableExtensionInterface) { + $extension->configureSchema($this->config); + } + + return $this; + } + + private function initializeExtensions(): void + { + // Initialize the slug normalizer + $this->getSlugNormalizer(); + + // Ask all extensions to register their components + while (\count($this->uninitializedExtensions) > 0) { + foreach ($this->uninitializedExtensions as $i => $extension) { + $extension->register($this); + unset($this->uninitializedExtensions[$i]); + } + } + + $this->extensionsInitialized = true; + + // Create the special delimiter parser if any processors were registered + if ($this->delimiterProcessors->count() > 0) { + $this->inlineParsers->add(new DelimiterParser($this->delimiterProcessors), PHP_INT_MIN); + } + } + + private function injectEnvironmentAndConfigurationIfNeeded(object $object): void + { + if ($object instanceof EnvironmentAwareInterface) { + $object->setEnvironment($this); + } + + if ($object instanceof ConfigurationAwareInterface) { + $object->setConfiguration($this->config->reader()); + } + } + + /** + * @deprecated Instantiate the environment and add the extension yourself + * + * @param array $config + */ + public static function createCommonMarkEnvironment(array $config = []): Environment + { + $environment = new self($config); + $environment->addExtension(new CommonMarkCoreExtension()); + + return $environment; + } + + /** + * @deprecated Instantiate the environment and add the extension yourself + * + * @param array $config + */ + public static function createGFMEnvironment(array $config = []): Environment + { + $environment = new self($config); + $environment->addExtension(new CommonMarkCoreExtension()); + $environment->addExtension(new GithubFlavoredMarkdownExtension()); + + return $environment; + } + + public function addEventListener(string $eventClass, callable $listener, int $priority = 0): EnvironmentBuilderInterface + { + $this->assertUninitialized('Failed to add event listener.'); + + $this->listenerData->add(new ListenerData($eventClass, $listener), $priority); + + if (\is_object($listener)) { + $this->injectEnvironmentAndConfigurationIfNeeded($listener); + } elseif (\is_array($listener) && \is_object($listener[0])) { + $this->injectEnvironmentAndConfigurationIfNeeded($listener[0]); + } + + return $this; + } + + public function dispatch(object $event): object + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + if ($this->eventDispatcher !== null) { + return $this->eventDispatcher->dispatch($event); + } + + foreach ($this->getListenersForEvent($event) as $listener) { + if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) { + return $event; + } + + $listener($event); + } + + return $event; + } + + public function setEventDispatcher(EventDispatcherInterface $dispatcher): void + { + $this->eventDispatcher = $dispatcher; + } + + /** + * {@inheritDoc} + * + * @return iterable + */ + public function getListenersForEvent(object $event): iterable + { + foreach ($this->listenerData as $listenerData) { + \assert($listenerData instanceof ListenerData); + + /** @psalm-suppress ArgumentTypeCoercion */ + if (! \is_a($event, $listenerData->getEvent())) { + continue; + } + + yield function (object $event) use ($listenerData) { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + return \call_user_func($listenerData->getListener(), $event); + }; + } + } + + /** + * @return iterable + */ + public function getInlineParsers(): iterable + { + if (! $this->extensionsInitialized) { + $this->initializeExtensions(); + } + + return $this->inlineParsers->getIterator(); + } + + public function getSlugNormalizer(): TextNormalizerInterface + { + if ($this->slugNormalizer === null) { + $normalizer = $this->config->get('slug_normalizer/instance'); + \assert($normalizer instanceof TextNormalizerInterface); + $this->injectEnvironmentAndConfigurationIfNeeded($normalizer); + + if ($this->config->get('slug_normalizer/unique') !== UniqueSlugNormalizerInterface::DISABLED && ! $normalizer instanceof UniqueSlugNormalizerInterface) { + /** @var string[] $reserved */ + $reserved = $this->config->get('slug_normalizer/reserved'); + $normalizer = new UniqueSlugNormalizer($normalizer, $reserved); + } + + if ($normalizer instanceof UniqueSlugNormalizerInterface) { + if ($this->config->get('slug_normalizer/unique') === UniqueSlugNormalizerInterface::PER_DOCUMENT) { + $this->addEventListener(DocumentParsedEvent::class, [$normalizer, 'clearHistory'], -1000); + } + } + + $this->slugNormalizer = $normalizer; + } + + return $this->slugNormalizer; + } + + /** + * @throws AlreadyInitializedException + */ + private function assertUninitialized(string $message): void + { + if ($this->extensionsInitialized) { + throw new AlreadyInitializedException($message . ' Extensions have already been initialized.'); + } + } + + public static function createDefaultConfiguration(): Configuration + { + return new Configuration([ + 'html_input' => Expect::anyOf(HtmlFilter::STRIP, HtmlFilter::ALLOW, HtmlFilter::ESCAPE)->default(HtmlFilter::ALLOW), + 'allow_unsafe_links' => Expect::bool(true), + 'max_nesting_level' => Expect::type('int')->default(PHP_INT_MAX), + 'max_delimiters_per_line' => Expect::type('int')->default(PHP_INT_MAX), + 'renderer' => Expect::structure([ + 'block_separator' => Expect::string("\n"), + 'inner_separator' => Expect::string("\n"), + 'soft_break' => Expect::string("\n"), + ]), + 'xml' => Expect::structure([ + 'max_indentation_level' => Expect::int()->min(0)->default(16), + ]), + 'slug_normalizer' => Expect::structure([ + 'instance' => Expect::type(TextNormalizerInterface::class)->default(new SlugNormalizer()), + 'max_length' => Expect::int()->min(0)->default(255), + 'unique' => Expect::anyOf(UniqueSlugNormalizerInterface::DISABLED, UniqueSlugNormalizerInterface::PER_ENVIRONMENT, UniqueSlugNormalizerInterface::PER_DOCUMENT)->default(UniqueSlugNormalizerInterface::PER_DOCUMENT), + 'reserved' => Expect::listOf('string')->default([]), + ]), + ]); + } +} diff --git a/vendor/league/commonmark/src/Environment/EnvironmentAwareInterface.php b/vendor/league/commonmark/src/Environment/EnvironmentAwareInterface.php new file mode 100644 index 0000000..44b9d3e --- /dev/null +++ b/vendor/league/commonmark/src/Environment/EnvironmentAwareInterface.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Environment; + +interface EnvironmentAwareInterface +{ + public function setEnvironment(EnvironmentInterface $environment): void; +} diff --git a/vendor/league/commonmark/src/Environment/EnvironmentBuilderInterface.php b/vendor/league/commonmark/src/Environment/EnvironmentBuilderInterface.php new file mode 100644 index 0000000..4df9761 --- /dev/null +++ b/vendor/league/commonmark/src/Environment/EnvironmentBuilderInterface.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Environment; + +use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface; +use League\CommonMark\Exception\AlreadyInitializedException; +use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Node\Node; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\Config\ConfigurationProviderInterface; + +/** + * Interface for building the Environment with any extensions, parsers, listeners, etc. that it may need + */ +interface EnvironmentBuilderInterface extends ConfigurationProviderInterface +{ + /** + * Registers the given extension with the Environment + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addExtension(ExtensionInterface $extension): EnvironmentBuilderInterface; + + /** + * Registers the given block start parser with the Environment + * + * @param BlockStartParserInterface $parser Block parser instance + * @param int $priority Priority (a higher number will be executed earlier) + * + * @return $this + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addBlockStartParser(BlockStartParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface; + + /** + * Registers the given inline parser with the Environment + * + * @param InlineParserInterface $parser Inline parser instance + * @param int $priority Priority (a higher number will be executed earlier) + * + * @return $this + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addInlineParser(InlineParserInterface $parser, int $priority = 0): EnvironmentBuilderInterface; + + /** + * Registers the given delimiter processor with the Environment + * + * @param DelimiterProcessorInterface $processor Delimiter processors instance + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addDelimiterProcessor(DelimiterProcessorInterface $processor): EnvironmentBuilderInterface; + + /** + * Registers the given node renderer with the Environment + * + * @param string $nodeClass The fully-qualified node element class name the renderer below should handle + * @param NodeRendererInterface $renderer The renderer responsible for rendering the type of element given above + * @param int $priority Priority (a higher number will be executed earlier) + * + * @psalm-param class-string $nodeClass + * + * @return $this + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addRenderer(string $nodeClass, NodeRendererInterface $renderer, int $priority = 0): EnvironmentBuilderInterface; + + /** + * Registers the given event listener + * + * @param class-string $eventClass Fully-qualified class name of the event this listener should respond to + * @param callable $listener Listener to be executed + * @param int $priority Priority (a higher number will be executed earlier) + * + * @return $this + * + * @throws AlreadyInitializedException if the Environment has already been initialized + */ + public function addEventListener(string $eventClass, callable $listener, int $priority = 0): EnvironmentBuilderInterface; +} diff --git a/vendor/league/commonmark/src/Environment/EnvironmentInterface.php b/vendor/league/commonmark/src/Environment/EnvironmentInterface.php new file mode 100644 index 0000000..8e19a52 --- /dev/null +++ b/vendor/league/commonmark/src/Environment/EnvironmentInterface.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Environment; + +use League\CommonMark\Delimiter\Processor\DelimiterProcessorCollection; +use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Node\Node; +use League\CommonMark\Normalizer\TextNormalizerInterface; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\Config\ConfigurationProviderInterface; +use Psr\EventDispatcher\EventDispatcherInterface; + +interface EnvironmentInterface extends ConfigurationProviderInterface, EventDispatcherInterface +{ + /** + * Get all registered extensions + * + * @return ExtensionInterface[] + */ + public function getExtensions(): iterable; + + /** + * @return iterable + */ + public function getBlockStartParsers(): iterable; + + /** + * @return iterable + */ + public function getInlineParsers(): iterable; + + public function getDelimiterProcessors(): DelimiterProcessorCollection; + + /** + * @psalm-param class-string $nodeClass + * + * @return iterable + */ + public function getRenderersForClass(string $nodeClass): iterable; + + public function getSlugNormalizer(): TextNormalizerInterface; +} diff --git a/vendor/league/commonmark/src/Event/AbstractEvent.php b/vendor/league/commonmark/src/Event/AbstractEvent.php new file mode 100644 index 0000000..8c83f92 --- /dev/null +++ b/vendor/league/commonmark/src/Event/AbstractEvent.php @@ -0,0 +1,54 @@ + + * + * Original code based on the Symfony EventDispatcher "Event" contract + * - (c) 2018-2019 Fabien Potencier + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Event; + +use Psr\EventDispatcher\StoppableEventInterface; + +/** + * Base class for classes containing event data. + * + * This class contains no event data. It is used by events that do not pass + * state information to an event handler when an event is raised. + * + * You can call the method stopPropagation() to abort the execution of + * further listeners in your event listener. + */ +abstract class AbstractEvent implements StoppableEventInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private bool $propagationStopped = false; + + /** + * Returns whether further event listeners should be triggered. + */ + final public function isPropagationStopped(): bool + { + return $this->propagationStopped; + } + + /** + * Stops the propagation of the event to further event listeners. + * + * If multiple event listeners are connected to the same event, no + * further event listener will be triggered once any trigger calls + * stopPropagation(). + */ + final public function stopPropagation(): void + { + $this->propagationStopped = true; + } +} diff --git a/vendor/league/commonmark/src/Event/DocumentParsedEvent.php b/vendor/league/commonmark/src/Event/DocumentParsedEvent.php new file mode 100644 index 0000000..04664c5 --- /dev/null +++ b/vendor/league/commonmark/src/Event/DocumentParsedEvent.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Event; + +use League\CommonMark\Node\Block\Document; + +/** + * Event dispatched when the document has been fully parsed + */ +final class DocumentParsedEvent extends AbstractEvent +{ + /** @psalm-readonly */ + private Document $document; + + public function __construct(Document $document) + { + $this->document = $document; + } + + public function getDocument(): Document + { + return $this->document; + } +} diff --git a/vendor/league/commonmark/src/Event/DocumentPreParsedEvent.php b/vendor/league/commonmark/src/Event/DocumentPreParsedEvent.php new file mode 100644 index 0000000..ad72512 --- /dev/null +++ b/vendor/league/commonmark/src/Event/DocumentPreParsedEvent.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Event; + +use League\CommonMark\Input\MarkdownInputInterface; +use League\CommonMark\Node\Block\Document; + +/** + * Event dispatched when the document is about to be parsed + */ +final class DocumentPreParsedEvent extends AbstractEvent +{ + /** @psalm-readonly */ + private Document $document; + + private MarkdownInputInterface $markdown; + + public function __construct(Document $document, MarkdownInputInterface $markdown) + { + $this->document = $document; + $this->markdown = $markdown; + } + + public function getDocument(): Document + { + return $this->document; + } + + public function getMarkdown(): MarkdownInputInterface + { + return $this->markdown; + } + + public function replaceMarkdown(MarkdownInputInterface $markdownInput): void + { + $this->markdown = $markdownInput; + } +} diff --git a/vendor/league/commonmark/src/Event/DocumentPreRenderEvent.php b/vendor/league/commonmark/src/Event/DocumentPreRenderEvent.php new file mode 100644 index 0000000..c569ca3 --- /dev/null +++ b/vendor/league/commonmark/src/Event/DocumentPreRenderEvent.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Event; + +use League\CommonMark\Node\Block\Document; + +/** + * Event dispatched just before rendering begins + */ +final class DocumentPreRenderEvent extends AbstractEvent +{ + /** @psalm-readonly */ + private Document $document; + + /** @psalm-readonly */ + private string $format; + + public function __construct(Document $document, string $format) + { + $this->document = $document; + $this->format = $format; + } + + public function getDocument(): Document + { + return $this->document; + } + + public function getFormat(): string + { + return $this->format; + } +} diff --git a/vendor/league/commonmark/src/Event/DocumentRenderedEvent.php b/vendor/league/commonmark/src/Event/DocumentRenderedEvent.php new file mode 100644 index 0000000..7e49d01 --- /dev/null +++ b/vendor/league/commonmark/src/Event/DocumentRenderedEvent.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Event; + +use League\CommonMark\Output\RenderedContentInterface; + +final class DocumentRenderedEvent extends AbstractEvent +{ + private RenderedContentInterface $output; + + public function __construct(RenderedContentInterface $output) + { + $this->output = $output; + } + + /** + * @psalm-mutation-free + */ + public function getOutput(): RenderedContentInterface + { + return $this->output; + } + + /** + * @psalm-external-mutation-free + */ + public function replaceOutput(RenderedContentInterface $output): void + { + $this->output = $output; + } +} diff --git a/vendor/league/commonmark/src/Event/ListenerData.php b/vendor/league/commonmark/src/Event/ListenerData.php new file mode 100644 index 0000000..4cf3b3a --- /dev/null +++ b/vendor/league/commonmark/src/Event/ListenerData.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Event; + +/** + * @internal + * + * @psalm-immutable + */ +final class ListenerData +{ + /** @var class-string */ + private string $event; + + /** @var callable */ + private $listener; + + /** + * @param class-string $event + */ + public function __construct(string $event, callable $listener) + { + $this->event = $event; + $this->listener = $listener; + } + + /** + * @return class-string + */ + public function getEvent(): string + { + return $this->event; + } + + public function getListener(): callable + { + return $this->listener; + } +} diff --git a/vendor/league/commonmark/src/Exception/AlreadyInitializedException.php b/vendor/league/commonmark/src/Exception/AlreadyInitializedException.php new file mode 100644 index 0000000..5faa6f8 --- /dev/null +++ b/vendor/league/commonmark/src/Exception/AlreadyInitializedException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class AlreadyInitializedException extends LogicException implements CommonMarkException +{ +} diff --git a/vendor/league/commonmark/src/Exception/CommonMarkException.php b/vendor/league/commonmark/src/Exception/CommonMarkException.php new file mode 100644 index 0000000..9fb349e --- /dev/null +++ b/vendor/league/commonmark/src/Exception/CommonMarkException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +/** + * Marker interface for all exceptions thrown by this library. + */ +interface CommonMarkException extends \Throwable +{ +} diff --git a/vendor/league/commonmark/src/Exception/IOException.php b/vendor/league/commonmark/src/Exception/IOException.php new file mode 100644 index 0000000..09a5578 --- /dev/null +++ b/vendor/league/commonmark/src/Exception/IOException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class IOException extends \RuntimeException implements CommonMarkException +{ +} diff --git a/vendor/league/commonmark/src/Exception/InvalidArgumentException.php b/vendor/league/commonmark/src/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..fc67ac4 --- /dev/null +++ b/vendor/league/commonmark/src/Exception/InvalidArgumentException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class InvalidArgumentException extends \InvalidArgumentException implements CommonMarkException +{ +} diff --git a/vendor/league/commonmark/src/Exception/LogicException.php b/vendor/league/commonmark/src/Exception/LogicException.php new file mode 100644 index 0000000..c1d00df --- /dev/null +++ b/vendor/league/commonmark/src/Exception/LogicException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class LogicException extends \LogicException implements CommonMarkException +{ +} diff --git a/vendor/league/commonmark/src/Exception/MissingDependencyException.php b/vendor/league/commonmark/src/Exception/MissingDependencyException.php new file mode 100644 index 0000000..b8eb841 --- /dev/null +++ b/vendor/league/commonmark/src/Exception/MissingDependencyException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +class MissingDependencyException extends \RuntimeException implements CommonMarkException +{ +} diff --git a/vendor/league/commonmark/src/Exception/UnexpectedEncodingException.php b/vendor/league/commonmark/src/Exception/UnexpectedEncodingException.php new file mode 100644 index 0000000..0f4e399 --- /dev/null +++ b/vendor/league/commonmark/src/Exception/UnexpectedEncodingException.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Exception; + +final class UnexpectedEncodingException extends \RuntimeException implements CommonMarkException +{ +} diff --git a/vendor/league/commonmark/src/Extension/Attributes/AttributesExtension.php b/vendor/league/commonmark/src/Extension/Attributes/AttributesExtension.php new file mode 100644 index 0000000..b29606d --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Attributes/AttributesExtension.php @@ -0,0 +1,44 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Attributes\Event\AttributesListener; +use League\CommonMark\Extension\Attributes\Parser\AttributesBlockStartParser; +use League\CommonMark\Extension\Attributes\Parser\AttributesInlineParser; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class AttributesExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('attributes', Expect::structure([ + 'allow' => Expect::arrayOf('string')->default([]), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $allowList = $environment->getConfiguration()->get('attributes.allow'); + $allowUnsafeLinks = $environment->getConfiguration()->get('allow_unsafe_links'); + + $environment->addBlockStartParser(new AttributesBlockStartParser()); + $environment->addInlineParser(new AttributesInlineParser()); + $environment->addEventListener(DocumentParsedEvent::class, [new AttributesListener($allowList, $allowUnsafeLinks), 'processDocument']); + } +} diff --git a/vendor/league/commonmark/src/Extension/Attributes/Event/AttributesListener.php b/vendor/league/commonmark/src/Extension/Attributes/Event/AttributesListener.php new file mode 100644 index 0000000..26d7fb0 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Attributes/Event/AttributesListener.php @@ -0,0 +1,406 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Attributes\Node\Attributes; +use League\CommonMark\Extension\Attributes\Node\AttributesInline; +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Node; + +/** + * @psalm-type PendingAttributes = array{node: Node, front: array, back: array, classFront: list, classBack: list, hasClass: bool, unfiltered: array} + * + * @phpstan-type PendingAttributes = array{node: Node, front: array, back: array, classFront: list, classBack: list, hasClass: bool, unfiltered: array} + */ +final class AttributesListener +{ + private const DIRECTION_PREFIX = 'prefix'; + private const DIRECTION_SUFFIX = 'suffix'; + + /** @var list */ + private array $allowList; + private bool $allowUnsafeLinks; + + /** + * @param list $allowList + */ + public function __construct(array $allowList = [], bool $allowUnsafeLinks = true) + { + $this->allowList = $allowList; + $this->allowUnsafeLinks = $allowUnsafeLinks; + } + + public function processDocument(DocumentParsedEvent $event): void + { + // Targets already worked out for attribute blocks we walked past; see findTargetAndDirection() + /** @var \SplObjectStorage> $resolved */ + $resolved = new \SplObjectStorage(); + + /** + * Attributes waiting to be written to their target, keyed by target object ID; see + * newPendingEntry() for the shape and contribute() for how each node is folded in. + * + * @var array $pending + */ + $pending = []; + + foreach ($event->getDocument()->iterator() as $node) { + if (! ($node instanceof Attributes || $node instanceof AttributesInline)) { + continue; + } + + [$target, $direction] = self::findTargetAndDirection($node, $resolved); + + if ($target instanceof Node) { + $parent = $target->parent(); + if ($parent instanceof ListItem && $parent->parent() instanceof ListBlock && $parent->parent()->isTight()) { + $target = $parent; + } + + $id = \spl_object_id($target); + if (! isset($pending[$id])) { + $pending[$id] = self::newPendingEntry($target); + } + + $this->contribute($pending[$id], $node->getAttributes(), $direction === self::DIRECTION_SUFFIX); + } + + $node->detach(); + } + + foreach ($pending as $entry) { + $entry['node']->data->set('attributes', self::assemble($entry)); + } + } + + /** + * Seed an accumulator from whatever the target already carries + * + * Anything another extension put there takes part in the merges, so it faces the filter too - + * but only once the first node has had its say, since whatever that node overwrites never + * reaches the filter at all. + * + * @return PendingAttributes + */ + private static function newPendingEntry(Node $target): array + { + /** @var array $existing */ + $existing = (array) $target->data->get('attributes'); + + $entry = ['node' => $target, 'front' => [], 'back' => [], 'classFront' => [], 'classBack' => [], 'hasClass' => false, 'unfiltered' => $existing]; + + foreach ($existing as $name => $value) { + if ($name === 'class') { + // mergeAttributes() builds the class list by appending to it, so a value with no + // classes in it - an empty string, or an empty array - never creates the key at + // all, and leaves the target with no class rather than an empty one + $classes = AttributesHelper::classList($value); + if ($classes === []) { + continue; + } + + $entry['classBack'] = $classes; + $entry['hasClass'] = true; + } + + $entry['back'][$name] = $value; + } + + return $entry; + } + + /** + * Fold one node's attributes into the accumulator in time proportional to that node's own + * size, reproducing what mergeAttributes() plus filterAttributes() would have produced had + * they been handed the whole accumulated dict. + * + * Both of those are O(size of the accumulator), so calling them once per node - as this used + * to - costs O(n^2) for a document that contributes a new key n times. + * + * @param PendingAttributes $entry + * @param array $attributes + * @param bool $suffix Whether the node's attributes lose conflicts to what is already accumulated + */ + private function contribute(array &$entry, array $attributes, bool $suffix): void + { + $class = $attributes['class'] ?? null; + unset($attributes['class']); + + // Keys whose value this node decides, and which therefore have yet to face the filter + $touched = []; + + if ($suffix) { + // mergeAttributes() rebuilds the class list before anything else, so merging over an + // accumulator that already has one moves it back to the front + if ($entry['hasClass']) { + self::moveToFront($entry, 'class'); + } elseif ($class !== null) { + $entry['back']['class'] = null; + } + + if ($class !== null) { + foreach (AttributesHelper::classList($class) as $c) { + $entry['classBack'][] = $c; + } + + $entry['hasClass'] = true; + $touched['class'] = $class; + } + + foreach ($attributes as $name => $value) { + // Overwriting leaves a key where it already sits, in front or behind + if (\array_key_exists($name, $entry['front'])) { + $entry['front'][$name] = $value; + } else { + $entry['back'][$name] = $value; + } + + $touched[$name] = $value; + } + + $this->filter($entry, $touched); + + return; + } + + // This node goes in front of everything accumulated so far. 'front' is kept in reverse, so + // the keys most recently moved there are the ones assemble() emits first. + if ($class === null && $entry['hasClass']) { + self::moveToFront($entry, 'class'); + } + + foreach (\array_reverse(\array_keys($attributes)) as $name) { + // A key this node shares with the accumulator takes its position from here, but keeps + // the value it already had + if (\array_key_exists($name, $entry['front']) || \array_key_exists($name, $entry['back'])) { + self::moveToFront($entry, $name); + + continue; + } + + $entry['front'][$name] = $attributes[$name]; + $touched[$name] = $attributes[$name]; + } + + if ($class !== null) { + self::moveToFront($entry, 'class'); + foreach (\array_reverse(AttributesHelper::classList($class)) as $c) { + $entry['classFront'][] = $c; + } + + $entry['hasClass'] = true; + $touched['class'] = $class; + } + + $this->filter($entry, $touched); + } + + /** + * Give a key the frontmost position, keeping whatever value it already had + * + * @param PendingAttributes $entry + */ + private static function moveToFront(array &$entry, string $name): void + { + $value = $entry['front'][$name] ?? $entry['back'][$name] ?? null; + unset($entry['front'][$name], $entry['back'][$name]); + + $entry['front'][$name] = $value; + } + + /** + * Drop whichever of the just-decided keys the filter rejects + * + * Everything else in the accumulator survived this same filter when it was decided, and the + * filter judges each name and value on its own, so re-examining any of it would be wasted. + * + * @param PendingAttributes $entry + * @param array $touched + */ + private function filter(array &$entry, array $touched): void + { + // Whatever the target arrived with has kept its value through this first merge, so it is + // being decided now too + foreach ($entry['unfiltered'] as $name => $value) { + if (\array_key_exists($name, $touched)) { + continue; + } + + $touched[$name] = $value; + } + + $entry['unfiltered'] = []; + + if ($touched === []) { + return; + } + + $kept = AttributesHelper::filterAttributes($touched, $this->allowList, $this->allowUnsafeLinks); + + foreach (\array_keys($touched) as $name) { + if (\array_key_exists($name, $kept)) { + continue; + } + + if ($name === 'class') { + $entry['classFront'] = $entry['classBack'] = []; + $entry['hasClass'] = false; + } + + // Forget where it sat as well as what it held, so a later node contributing the same + // name starts it over at the back + unset($entry['front'][$name], $entry['back'][$name]); + } + } + + /** + * @param PendingAttributes $entry + * + * @return array + */ + private static function assemble(array $entry): array + { + $attributes = \array_merge(\array_reverse($entry['front'], true), $entry['back']); + + if ($entry['hasClass']) { + $attributes['class'] = \implode(' ', \array_merge(\array_reverse($entry['classFront']), $entry['classBack'])); + } + + return $attributes; + } + + /** + * @param Attributes|AttributesInline $node + * @param \SplObjectStorage> $resolved + * + * @return array + */ + private static function findTargetAndDirection($node, \SplObjectStorage $resolved): array + { + if (isset($resolved[$node])) { + $result = $resolved[$node]; + // Each node is only ever resolved once, so don't keep it alive any longer + unset($resolved[$node]); + + return $result; + } + + $target = null; + $direction = null; + $previous = $next = $node; + /** @var list $shared */ + $shared = []; + while (true) { + $previous = self::getPrevious($previous); + $next = self::getNext($next); + + if ($previous === null && $next === null) { + if (! $node->parent() instanceof FencedCode) { + $target = $node->parent(); + $direction = self::DIRECTION_SUFFIX; + } + + break; + } + + if ($node instanceof AttributesInline && ($previous === null || ($previous instanceof AbstractInline && $node->isBlock()))) { + // Once this condition holds it holds for every remaining iteration, as walking + // further to the left can only ever yield another inline sibling or null. No + // sibling can therefore be chosen, so the target must be the parent; continuing + // to walk would only re-scan the remaining siblings for nothing. + if (! $node->parent() instanceof FencedCode) { + $target = $node->parent(); + $direction = self::DIRECTION_SUFFIX; + } + + break; + } + + if ($previous !== null && ! self::isAttributesNode($previous)) { + $target = $previous; + $direction = self::DIRECTION_SUFFIX; + + break; + } + + if ($next !== null && ! self::isAttributesNode($next)) { + $target = $next; + $direction = self::DIRECTION_PREFIX; + + break; + } + + // Only a TARGET_NEXT block can have a sibling block to walk past, so if that's what + // we're looking at then we are one too, which means getPrevious() already returned + // null for us and will keep doing so. Neither of us can therefore pick anything up on + // the left, and what is left of this walk is the whole of that block's own walk: it + // must end up with the same target we do. Remember that instead of re-scanning the + // chain once per block. + if (! ($next instanceof Attributes) || $next->getTarget() !== Attributes::TARGET_NEXT) { + continue; + } + + $shared[] = $next; + } + + /** @var array $result */ + $result = [$target, $direction]; + foreach ($shared as $sharedNode) { + $resolved[$sharedNode] = $result; + } + + return $result; + } + + /** + * Get any previous block (sibling or parent) this might apply to + */ + private static function getPrevious(?Node $node = null): ?Node + { + if ($node instanceof Attributes) { + if ($node->getTarget() === Attributes::TARGET_NEXT) { + return null; + } + + if ($node->getTarget() === Attributes::TARGET_PARENT) { + return $node->parent(); + } + } + + return $node instanceof Node ? $node->previous() : null; + } + + /** + * Get any previous block (sibling or parent) this might apply to + */ + private static function getNext(?Node $node = null): ?Node + { + if ($node instanceof Attributes && $node->getTarget() !== Attributes::TARGET_NEXT) { + return null; + } + + return $node instanceof Node ? $node->next() : null; + } + + private static function isAttributesNode(Node $node): bool + { + return $node instanceof Attributes || $node instanceof AttributesInline; + } +} diff --git a/vendor/league/commonmark/src/Extension/Attributes/Node/Attributes.php b/vendor/league/commonmark/src/Extension/Attributes/Node/Attributes.php new file mode 100644 index 0000000..096f04a --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Attributes/Node/Attributes.php @@ -0,0 +1,65 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class Attributes extends AbstractBlock +{ + public const TARGET_PARENT = 0; + public const TARGET_PREVIOUS = 1; + public const TARGET_NEXT = 2; + + /** @var array */ + private array $attributes; + + private int $target = self::TARGET_NEXT; + + /** + * @param array $attributes + */ + public function __construct(array $attributes) + { + parent::__construct(); + + $this->attributes = $attributes; + } + + /** + * @return array + */ + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * @param array $attributes + */ + public function setAttributes(array $attributes): void + { + $this->attributes = $attributes; + } + + public function getTarget(): int + { + return $this->target; + } + + public function setTarget(int $target): void + { + $this->target = $target; + } +} diff --git a/vendor/league/commonmark/src/Extension/Attributes/Node/AttributesInline.php b/vendor/league/commonmark/src/Extension/Attributes/Node/AttributesInline.php new file mode 100644 index 0000000..d8b0d08 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Attributes/Node/AttributesInline.php @@ -0,0 +1,57 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Node; + +use League\CommonMark\Node\Inline\AbstractInline; + +final class AttributesInline extends AbstractInline +{ + /** @var array */ + private array $attributes; + + private bool $block; + + /** + * @param array $attributes + */ + public function __construct(array $attributes, bool $block) + { + parent::__construct(); + + $this->attributes = $attributes; + $this->block = $block; + } + + /** + * @return array + */ + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * @param array $attributes + */ + public function setAttributes(array $attributes): void + { + $this->attributes = $attributes; + } + + public function isBlock(): bool + { + return $this->block; + } +} diff --git a/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockContinueParser.php b/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockContinueParser.php new file mode 100644 index 0000000..060c304 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockContinueParser.php @@ -0,0 +1,155 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Parser; + +use League\CommonMark\Extension\Attributes\Node\Attributes; +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class AttributesBlockContinueParser extends AbstractBlockContinueParser +{ + private Attributes $block; + + private AbstractBlock $container; + + private bool $hasSubsequentLine = false; + + /** + * Every attribute merged so far except the class list, which is accumulated separately and + * only takes the placeholder position recorded here. Re-merging the whole dict on every line + * would cost O(size of the dict) per line, so a document adding a key per line would be + * quadratic; folding each line in on its own is linear. + * + * @var array + */ + private array $attributes = []; + + /** @var list */ + private array $classes = []; + + private bool $hasClass = false; + + /** + * mergeAttributes() rebuilds the class list before anything else, so any line merged over an + * existing list moves it to the front of the result + */ + private bool $classFirst = false; + + /** + * @param array $attributes The attributes identified by the block start parser + * @param AbstractBlock $container The node we were in when these attributes were discovered + */ + public function __construct(array $attributes, AbstractBlock $container) + { + $this->block = new Attributes($attributes); + + $this->container = $container; + + $this->absorb($attributes); + } + + public function getBlock(): AbstractBlock + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + $this->hasSubsequentLine = true; + + $cursor->advanceToNextNonSpaceOrTab(); + + // Does this next line also have attributes? + $attributes = AttributesHelper::parseAttributes($cursor); + $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->isAtEnd() && $attributes !== []) { + // It does! Merge them into what we parsed previously + $this->classFirst = $this->classFirst || $this->hasClass; + + $this->absorb($attributes); + + // Tell the core parser we've consumed everything + return BlockContinue::at($cursor); + } + + // Okay, so there are no attributes on the next line + // If this next line is blank we know we can't target the next node, it must be a previous one + if ($cursor->isBlank()) { + $this->block->setTarget(Attributes::TARGET_PREVIOUS); + } + + return BlockContinue::none(); + } + + /** + * Fold one line's attributes into what we've accumulated, in time proportional to that line + * + * @param array $attributes + */ + private function absorb(array $attributes): void + { + foreach ($attributes as $name => $value) { + if ($name !== 'class') { + $this->attributes[$name] = $value; + + continue; + } + + foreach (AttributesHelper::classList($value) as $class) { + $this->classes[] = $class; + } + + if ($this->hasClass) { + continue; + } + + // Hold the spot the joined list will occupy; closeBlock() writes the value + $this->attributes['class'] = null; + $this->hasClass = true; + } + } + + public function closeBlock(): void + { + $attributes = $this->attributes; + if ($this->hasClass) { + $class = \implode(' ', $this->classes); + if ($this->classFirst) { + unset($attributes['class']); + $attributes = \array_merge(['class' => $class], $attributes); + } else { + $attributes['class'] = $class; + } + } + + $this->block->setAttributes($attributes); + + // Attributes appearing at the very end of the document won't have any last lines to check + // so we can make that determination here + if (! $this->hasSubsequentLine) { + $this->block->setTarget(Attributes::TARGET_PREVIOUS); + } + + // We know this block must apply to the "previous" block, but that could be a sibling or parent, + // so we check the containing block to see which one it might be. + if ($this->block->getTarget() === Attributes::TARGET_PREVIOUS && $this->block->parent() === $this->container) { + $this->block->setTarget(Attributes::TARGET_PARENT); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockStartParser.php b/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockStartParser.php new file mode 100644 index 0000000..299ccd4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesBlockStartParser.php @@ -0,0 +1,40 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Parser; + +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class AttributesBlockStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + $originalPosition = $cursor->getPosition(); + $attributes = AttributesHelper::parseAttributes($cursor); + + if ($attributes === [] && $originalPosition === $cursor->getPosition()) { + return BlockStart::none(); + } + + if ($cursor->getNextNonSpaceCharacter() !== null) { + return BlockStart::none(); + } + + return BlockStart::of(new AttributesBlockContinueParser($attributes, $parserState->getActiveBlockParser()->getBlock()))->at($cursor); + } +} diff --git a/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesInlineParser.php b/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesInlineParser.php new file mode 100644 index 0000000..26af3ca --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Attributes/Parser/AttributesInlineParser.php @@ -0,0 +1,54 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Parser; + +use League\CommonMark\Extension\Attributes\Node\AttributesInline; +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Node\StringContainerInterface; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class AttributesInlineParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string('{'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + $char = (string) $cursor->peek(-1); + + $attributes = AttributesHelper::parseAttributes($cursor); + if ($attributes === []) { + return false; + } + + if ($char === ' ' && ($prev = $inlineContext->getContainer()->lastChild()) instanceof StringContainerInterface) { + $prev->setLiteral(\rtrim($prev->getLiteral(), ' ')); + } + + if ($char === '') { + $cursor->advanceToNextNonSpaceOrNewline(); + } + + $node = new AttributesInline($attributes, $char === ' ' || $char === ''); + $inlineContext->getContainer()->appendChild($node); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/Attributes/Util/AttributesHelper.php b/vendor/league/commonmark/src/Extension/Attributes/Util/AttributesHelper.php new file mode 100644 index 0000000..79600ed --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Attributes/Util/AttributesHelper.php @@ -0,0 +1,207 @@ + + * (c) 2015 Martin Hasoň + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Attributes\Util; + +use League\CommonMark\Node\Node; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\RegexHelper; + +/** + * @internal + */ +final class AttributesHelper +{ + private const SINGLE_ATTRIBUTE = '\s*([.]-?[_a-z][^\s.}]*|[#][^\s}]+|' . RegexHelper::PARTIAL_ATTRIBUTENAME . RegexHelper::PARTIAL_ATTRIBUTEVALUESPEC . ')\s*'; + private const ATTRIBUTE_LIST = '/\G{:?(' . self::SINGLE_ATTRIBUTE . ')+}/i'; + + /** + * PCRE's `\s` matches the form feed that PHP's default trim charlist omits, so the + * separators SINGLE_ATTRIBUTE accepts must be trimmed with this list instead - otherwise + * that byte survives inside an attribute name, where a browser reads it as a separator. + */ + private const WHITESPACE = " \t\n\r\0\x0B\x0C"; + + /** + * @return array + */ + public static function parseAttributes(Cursor $cursor): array + { + $state = $cursor->saveState(); + $cursor->advanceToNextNonSpaceOrNewline(); + + // Quick check to see if we might have attributes + if ($cursor->getCharacter() !== '{') { + $cursor->restoreState($state); + + return []; + } + + // Attempt to match the entire attribute list expression + // While this is less performant than checking for '{' now and '}' later, it simplifies + // matching individual attributes since they won't need to look ahead for the closing '}' + // while dealing with the fact that attributes can technically contain curly braces. + // So we'll just match the start and end braces up front. + $attributeExpression = $cursor->matchInPlace(self::ATTRIBUTE_LIST); + if ($attributeExpression === null) { + $cursor->restoreState($state); + + return []; + } + + // Trim the leading '{' or '{:' and the trailing '}' + $attributeExpression = \ltrim(\substr($attributeExpression, 1, -1), ':'); + $attributeCursor = new Cursor($attributeExpression); + + /** @var array $attributes */ + $attributes = []; + while ($attribute = \trim((string) $attributeCursor->matchInPlace('/\G' . self::SINGLE_ATTRIBUTE . '/i'), self::WHITESPACE)) { + if ($attribute[0] === '#') { + $attributes['id'] = \substr($attribute, 1); + + continue; + } + + if ($attribute[0] === '.') { + $attributes['class'][] = \substr($attribute, 1); + + continue; + } + + /** @psalm-suppress PossiblyUndefinedArrayOffset */ + [$name, $value] = \explode('=', $attribute, 2); + + if ($value === 'true') { + $attributes[$name] = true; + continue; + } + + $first = $value[0]; + $last = \substr($value, -1); + if (($first === '"' && $last === '"') || ($first === "'" && $last === "'") && \strlen($value) > 1) { + $value = \substr($value, 1, -1); + } + + if (\strtolower(\trim($name, self::WHITESPACE)) === 'class') { + foreach (\array_filter(\explode(' ', \trim($value, self::WHITESPACE))) as $class) { + $attributes['class'][] = $class; + } + } else { + $attributes[\trim($name, self::WHITESPACE)] = \trim($value, self::WHITESPACE); + } + } + + if (isset($attributes['class'])) { + $attributes['class'] = \implode(' ', (array) $attributes['class']); + } + + return $attributes; + } + + /** + * @param Node|array $attributes1 + * @param Node|array $attributes2 + * + * @return array + */ + public static function mergeAttributes($attributes1, $attributes2): array + { + $attributes = []; + foreach ([$attributes1, $attributes2] as $arg) { + if ($arg instanceof Node) { + $arg = $arg->data->get('attributes'); + } + + /** @var array $arg */ + $arg = (array) $arg; + if (isset($arg['class'])) { + foreach (self::classList($arg['class']) as $class) { + $attributes['class'][] = $class; + } + + unset($arg['class']); + } + + $attributes = \array_merge($attributes, $arg); + } + + if (isset($attributes['class'])) { + $attributes['class'] = \implode(' ', $attributes['class']); + } + + return $attributes; + } + + /** + * Split a `class` attribute value into the individual classes it contributes to a merge + * + * @param mixed $class + * + * @return list + */ + public static function classList($class): array + { + if (\is_string($class)) { + return \array_values(\array_filter(\explode(' ', \trim($class)))); + } + + return \array_values((array) $class); + } + + /** + * @param array $attributes + * @param list $allowList + * + * @return array + */ + public static function filterAttributes(array $attributes, array $allowList, bool $allowUnsafeLinks): array + { + $allowList = \array_fill_keys($allowList, true); + + foreach ($attributes as $name => $value) { + // The checks below compare against literal names, and the renderer emits names + // without escaping them, so anything that isn't a well-formed attribute name + // would slip past both + if (\preg_match('/^' . RegexHelper::PARTIAL_ATTRIBUTENAME . '$/i', (string) $name) !== 1) { + unset($attributes[$name]); + continue; + } + + $attrNameLower = \strtolower((string) $name); + + // Remove any unsafe links + if (! $allowUnsafeLinks && ($attrNameLower === 'href' || $attrNameLower === 'src') && \is_string($value) && RegexHelper::isLinkPotentiallyUnsafe($value)) { + unset($attributes[$name]); + continue; + } + + // No allowlist? + if ($allowList === []) { + // Just remove JS event handlers + if (\str_starts_with($attrNameLower, 'on')) { + unset($attributes[$name]); + } + + continue; + } + + // Remove any attributes not in that allowlist (case-sensitive) + if (! isset($allowList[$name])) { + unset($attributes[$name]); + } + } + + return $attributes; + } +} diff --git a/vendor/league/commonmark/src/Extension/Autolink/AutolinkExtension.php b/vendor/league/commonmark/src/Extension/Autolink/AutolinkExtension.php new file mode 100644 index 0000000..54aafd4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Autolink/AutolinkExtension.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Autolink; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class AutolinkExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('autolink', Expect::structure([ + 'allowed_protocols' => Expect::listOf('string')->default(['http', 'https', 'ftp'])->mergeDefaults(false), + 'default_protocol' => Expect::string()->default('http'), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addInlineParser(new EmailAutolinkParser()); + $environment->addInlineParser(new UrlAutolinkParser( + $environment->getConfiguration()->get('autolink.allowed_protocols'), + $environment->getConfiguration()->get('autolink.default_protocol'), + )); + } +} diff --git a/vendor/league/commonmark/src/Extension/Autolink/EmailAutolinkParser.php b/vendor/league/commonmark/src/Extension/Autolink/EmailAutolinkParser.php new file mode 100644 index 0000000..15a7d34 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Autolink/EmailAutolinkParser.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Autolink; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class EmailAutolinkParser implements InlineParserInterface +{ + private const REGEX = '[A-Za-z0-9.\-_+]+@[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_.]+'; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex(self::REGEX); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $email = $inlineContext->getFullMatch(); + // The last character cannot be - or _ + if (\in_array(\substr($email, -1), ['-', '_'], true)) { + return false; + } + + // Does the URL end with punctuation that should be stripped? + if (\substr($email, -1) === '.') { + $email = \substr($email, 0, -1); + } + + $inlineContext->getCursor()->advanceBy(\strlen($email)); + $inlineContext->getContainer()->appendChild(new Link('mailto:' . $email, $email)); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php b/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php new file mode 100644 index 0000000..886d840 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php @@ -0,0 +1,155 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Autolink; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class UrlAutolinkParser implements InlineParserInterface +{ + private const ALLOWED_AFTER = [null, ' ', "\t", "\n", "\x0b", "\x0c", "\x0d", '*', '_', '~', '(']; + + // RegEx adapted from https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/Validator/Constraints/UrlValidator.php + private const REGEX = '~ + ( + # Must start with a supported scheme + auth, or "www" + (?: + (?:%s):// # protocol + (?:(?:(?:[\_\.\pL\pN-]|%%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%%[0-9A-Fa-f]{2})+)@)? # basic auth + |www\.) + (?: + (?: + (?:xn--[a-z0-9-]++\.)*+xn--[a-z0-9-]++ # a domain name using punycode + | + (?:[\pL\pN\pS\pM\-\_]++\.){1,127}[\pL\pN\pM]++ # a multi-level domain name; total length must be 253 bytes or less + | + [a-z0-9\-\_]++ # a single-level domain name + )\.? + | # or + \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address + | # or + \[ + (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::)))) + \] # an IPv6 address + ) + (?::[0-9]+)? # a port (optional) + (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%%[0-9A-Fa-f]{2})* )* # a path + (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a query (optional) + (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a fragment (optional) + )~ixuA'; + + /** + * @var string[] + * + * @psalm-readonly + */ + private array $prefixes = ['www.']; + + /** + * @psalm-var non-empty-string + * + * @psalm-readonly + */ + private string $finalRegex; + + private string $defaultProtocol; + + /** + * @param array $allowedProtocols + */ + public function __construct(array $allowedProtocols = ['http', 'https', 'ftp'], string $defaultProtocol = 'http') + { + /** + * @psalm-suppress PropertyTypeCoercion + */ + $this->finalRegex = \sprintf(self::REGEX, \implode('|', $allowedProtocols)); + + foreach ($allowedProtocols as $protocol) { + $this->prefixes[] = $protocol . '://'; + } + + $this->defaultProtocol = $defaultProtocol; + } + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf(...$this->prefixes); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + + // Autolinks can only come at the beginning of a line, after whitespace, or certain delimiting characters + $previousChar = $cursor->peek(-1); + if (! \in_array($previousChar, self::ALLOWED_AFTER, true)) { + return false; + } + + // Check if we have a valid URL. The regex is anchored (the "A" modifier) and matched + // against the full line at the current byte offset rather than against a fresh copy of + // the remaining text. This avoids re-allocating and re-validating (the "u" modifier) the + // entire remainder on every prefix occurrence, which would otherwise be quadratic. + if (! \preg_match($this->finalRegex, $cursor->getLine(), $matches, 0, $cursor->getBytePosition())) { + return false; + } + + // 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)) { + $url = $matches[1]; + } + + // Does the URL need unmatched parens chopped off? + if (\substr($url, -1) === ')' && ($diff = self::diffParens($url)) > 0) { + $url = \substr($url, 0, -$diff); + } + + $cursor->advanceBy(\mb_strlen($url, 'UTF-8')); + + // Auto-prefix 'http(s)://' onto 'www' URLs + if (\substr($url, 0, 4) === 'www.') { + $inlineContext->getContainer()->appendChild(new Link($this->defaultProtocol . '://' . $url, $url)); + + return true; + } + + $inlineContext->getContainer()->appendChild(new Link($url, $url)); + + return true; + } + + /** + * @psalm-pure + */ + private static function diffParens(string $content): int + { + // Scan the entire autolink for the total number of parentheses. + // If there is a greater number of closing parentheses than opening ones, + // we don’t consider ANY of the last characters as part of the autolink, + // in order to facilitate including an autolink inside a parenthesis. + \preg_match_all('/[()]/', $content, $matches); + + $charCount = ['(' => 0, ')' => 0]; + foreach ($matches[0] as $char) { + $charCount[$char]++; + } + + return $charCount[')'] - $charCount['(']; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/CommonMarkCoreExtension.php b/vendor/league/commonmark/src/Extension/CommonMark/CommonMarkCoreExtension.php new file mode 100644 index 0000000..91f7a22 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/CommonMarkCoreExtension.php @@ -0,0 +1,92 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\CommonMark\Delimiter\Processor\EmphasisDelimiterProcessor; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Node as CoreNode; +use League\CommonMark\Parser as CoreParser; +use League\CommonMark\Renderer as CoreRenderer; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class CommonMarkCoreExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('commonmark', Expect::structure([ + 'use_asterisk' => Expect::bool(true), + '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), + ])); + } + + // phpcs:disable Generic.Functions.FunctionCallArgumentSpacing.TooMuchSpaceAfterComma,Squiz.WhiteSpace.SemicolonSpacing.Incorrect + public function register(EnvironmentBuilderInterface $environment): void + { + $environment + ->addBlockStartParser(new Parser\Block\BlockQuoteStartParser(), 70) + ->addBlockStartParser(new Parser\Block\HeadingStartParser(), 60) + ->addBlockStartParser(new Parser\Block\FencedCodeStartParser(), 50) + ->addBlockStartParser(new Parser\Block\HtmlBlockStartParser(), 40) + ->addBlockStartParser(new Parser\Block\ThematicBreakStartParser(), 20) + ->addBlockStartParser(new Parser\Block\ListBlockStartParser(), 10) + ->addBlockStartParser(new Parser\Block\IndentedCodeStartParser(), -100) + + ->addInlineParser(new CoreParser\Inline\NewlineParser(), 200) + ->addInlineParser(new Parser\Inline\BacktickParser(), 150) + ->addInlineParser(new Parser\Inline\EscapableParser(), 80) + ->addInlineParser(new Parser\Inline\EntityParser(), 70) + ->addInlineParser(new Parser\Inline\AutolinkParser(), 50) + ->addInlineParser(new Parser\Inline\HtmlInlineParser(), 40) + ->addInlineParser(new Parser\Inline\CloseBracketParser(), 30) + ->addInlineParser(new Parser\Inline\OpenBracketParser(), 20) + ->addInlineParser(new Parser\Inline\BangParser(), 10) + + ->addRenderer(Node\Block\BlockQuote::class, new Renderer\Block\BlockQuoteRenderer(), 0) + ->addRenderer(CoreNode\Block\Document::class, new CoreRenderer\Block\DocumentRenderer(), 0) + ->addRenderer(Node\Block\FencedCode::class, new Renderer\Block\FencedCodeRenderer(), 0) + ->addRenderer(Node\Block\Heading::class, new Renderer\Block\HeadingRenderer(), 0) + ->addRenderer(Node\Block\HtmlBlock::class, new Renderer\Block\HtmlBlockRenderer(), 0) + ->addRenderer(Node\Block\IndentedCode::class, new Renderer\Block\IndentedCodeRenderer(), 0) + ->addRenderer(Node\Block\ListBlock::class, new Renderer\Block\ListBlockRenderer(), 0) + ->addRenderer(Node\Block\ListItem::class, new Renderer\Block\ListItemRenderer(), 0) + ->addRenderer(CoreNode\Block\Paragraph::class, new CoreRenderer\Block\ParagraphRenderer(), 0) + ->addRenderer(Node\Block\ThematicBreak::class, new Renderer\Block\ThematicBreakRenderer(), 0) + + ->addRenderer(Node\Inline\Code::class, new Renderer\Inline\CodeRenderer(), 0) + ->addRenderer(Node\Inline\Emphasis::class, new Renderer\Inline\EmphasisRenderer(), 0) + ->addRenderer(Node\Inline\HtmlInline::class, new Renderer\Inline\HtmlInlineRenderer(), 0) + ->addRenderer(Node\Inline\Image::class, new Renderer\Inline\ImageRenderer(), 0) + ->addRenderer(Node\Inline\Link::class, new Renderer\Inline\LinkRenderer(), 0) + ->addRenderer(CoreNode\Inline\Newline::class, new CoreRenderer\Inline\NewlineRenderer(), 0) + ->addRenderer(Node\Inline\Strong::class, new Renderer\Inline\StrongRenderer(), 0) + ->addRenderer(CoreNode\Inline\Text::class, new CoreRenderer\Inline\TextRenderer(), 0) + ; + + if ($environment->getConfiguration()->get('commonmark/use_asterisk')) { + $environment->addDelimiterProcessor(new EmphasisDelimiterProcessor('*')); + } + + if ($environment->getConfiguration()->get('commonmark/use_underscore')) { + $environment->addDelimiterProcessor(new EmphasisDelimiterProcessor('_')); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Delimiter/Processor/EmphasisDelimiterProcessor.php b/vendor/league/commonmark/src/Extension/CommonMark/Delimiter/Processor/EmphasisDelimiterProcessor.php new file mode 100644 index 0000000..49fff52 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Delimiter/Processor/EmphasisDelimiterProcessor.php @@ -0,0 +1,122 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Delimiter\Processor; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Delimiter\Processor\CacheableDelimiterProcessorInterface; +use League\CommonMark\Extension\CommonMark\Node\Inline\Emphasis; +use League\CommonMark\Extension\CommonMark\Node\Inline\Strong; +use League\CommonMark\Node\Inline\AbstractStringContainer; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class EmphasisDelimiterProcessor implements CacheableDelimiterProcessorInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly */ + private string $char; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param string $char The emphasis character to use (typically '*' or '_') + */ + public function __construct(string $char) + { + $this->char = $char; + } + + public function getOpeningCharacter(): string + { + return $this->char; + } + + public function getClosingCharacter(): string + { + return $this->char; + } + + public function getMinLength(): int + { + return 1; + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + // "Multiple of 3" rule for internal delimiter runs + if (($opener->canClose() || $closer->canOpen()) && $closer->getOriginalLength() % 3 !== 0 && ($opener->getOriginalLength() + $closer->getOriginalLength()) % 3 === 0) { + return 0; + } + + // Calculate actual number of delimiters used from this closer + if ($opener->getLength() >= 2 && $closer->getLength() >= 2) { + if ($this->config->get('commonmark/enable_strong')) { + return 2; + } + + return 0; + } + + if ($this->config->get('commonmark/enable_em')) { + return 1; + } + + return 0; + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + if ($delimiterUse === 1) { + $emphasis = new Emphasis($this->char); + } elseif ($delimiterUse === 2) { + $emphasis = new Strong($this->char . $this->char); + } else { + return; + } + + $next = $opener->next(); + while ($next !== null && $next !== $closer) { + $tmp = $next->next(); + $emphasis->appendChild($next); + $next = $tmp; + } + + $opener->insertAfter($emphasis); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getCacheKey(DelimiterInterface $closer): string + { + return \sprintf( + '%s-%s-%d-%d', + $this->char, + $closer->canOpen() ? 'canOpen' : 'cannotOpen', + $closer->getOriginalLength() % 3, + // getDelimiterUse() only ever asks whether the closer's length is >= 2, so lengths + // beyond that are interchangeable. Clamping keeps the key space bounded, which is + // what makes the delimiter stack's lower-bound cache amortize. + \min($closer->getLength(), 2), + ); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/BlockQuote.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/BlockQuote.php new file mode 100644 index 0000000..11094b9 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/BlockQuote.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +class BlockQuote extends AbstractBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/FencedCode.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/FencedCode.php new file mode 100644 index 0000000..b50b407 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/FencedCode.php @@ -0,0 +1,100 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\StringContainerInterface; + +final class FencedCode extends AbstractBlock implements StringContainerInterface +{ + private ?string $info = null; + + private string $literal = ''; + + private int $length; + + private string $char; + + private int $offset; + + public function __construct(int $length, string $char, int $offset) + { + parent::__construct(); + + $this->length = $length; + $this->char = $char; + $this->offset = $offset; + } + + public function getInfo(): ?string + { + return $this->info; + } + + /** + * @return string[] + */ + public function getInfoWords(): array + { + return \preg_split('/\s+/', $this->info ?? '') ?: []; + } + + public function setInfo(string $info): void + { + $this->info = $info; + } + + public function getLiteral(): string + { + return $this->literal; + } + + public function setLiteral(string $literal): void + { + $this->literal = $literal; + } + + public function getChar(): string + { + return $this->char; + } + + public function setChar(string $char): void + { + $this->char = $char; + } + + public function getLength(): int + { + return $this->length; + } + + public function setLength(int $length): void + { + $this->length = $length; + } + + public function getOffset(): int + { + return $this->offset; + } + + public function setOffset(int $offset): void + { + $this->offset = $offset; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/Heading.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/Heading.php new file mode 100644 index 0000000..1cf1184 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/Heading.php @@ -0,0 +1,41 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class Heading extends AbstractBlock +{ + private int $level; + + public function __construct(int $level) + { + parent::__construct(); + + $this->level = $level; + } + + public function getLevel(): int + { + return $this->level; + } + + public function setLevel(int $level): void + { + $this->level = $level; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/HtmlBlock.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/HtmlBlock.php new file mode 100644 index 0000000..9879a89 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/HtmlBlock.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\RawMarkupContainerInterface; + +final class HtmlBlock extends AbstractBlock implements RawMarkupContainerInterface +{ + // Any changes to these constants should be reflected in .phpstorm.meta.php + public const TYPE_1_CODE_CONTAINER = 1; + public const TYPE_2_COMMENT = 2; + public const TYPE_3 = 3; + public const TYPE_4 = 4; + public const TYPE_5_CDATA = 5; + public const TYPE_6_BLOCK_ELEMENT = 6; + public const TYPE_7_MISC_ELEMENT = 7; + + /** + * @psalm-var self::TYPE_* $type + * @phpstan-var self::TYPE_* $type + */ + private int $type; + + private string $literal = ''; + + /** + * @psalm-param self::TYPE_* $type + * + * @phpstan-param self::TYPE_* $type + */ + public function __construct(int $type) + { + parent::__construct(); + + $this->type = $type; + } + + /** + * @psalm-return self::TYPE_* + * + * @phpstan-return self::TYPE_* + */ + public function getType(): int + { + return $this->type; + } + + /** + * @psalm-param self::TYPE_* $type + * + * @phpstan-param self::TYPE_* $type + */ + public function setType(int $type): void + { + $this->type = $type; + } + + public function getLiteral(): string + { + return $this->literal; + } + + public function setLiteral(string $literal): void + { + $this->literal = $literal; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/IndentedCode.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/IndentedCode.php new file mode 100644 index 0000000..d18be15 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/IndentedCode.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\StringContainerInterface; + +final class IndentedCode extends AbstractBlock implements StringContainerInterface +{ + private string $literal = ''; + + public function getLiteral(): string + { + return $this->literal; + } + + public function setLiteral(string $literal): void + { + $this->literal = $literal; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListBlock.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListBlock.php new file mode 100644 index 0000000..504a38a --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListBlock.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\TightBlockInterface; + +class ListBlock extends AbstractBlock implements TightBlockInterface +{ + public const TYPE_BULLET = 'bullet'; + public const TYPE_ORDERED = 'ordered'; + + public const DELIM_PERIOD = 'period'; + public const DELIM_PAREN = 'paren'; + + protected bool $tight = false; // TODO Make lists tight by default in v3 + + /** @psalm-readonly */ + protected ListData $listData; + + public function __construct(ListData $listData) + { + parent::__construct(); + + $this->listData = $listData; + } + + public function getListData(): ListData + { + return $this->listData; + } + + public function isTight(): bool + { + return $this->tight; + } + + public function setTight(bool $tight): void + { + $this->tight = $tight; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListData.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListData.php new file mode 100644 index 0000000..7108a93 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListData.php @@ -0,0 +1,47 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +class ListData +{ + public ?int $start = null; + + public int $padding = 0; + + /** + * @psalm-var ListBlock::TYPE_* + * @phpstan-var ListBlock::TYPE_* + */ + public string $type; + + /** + * @psalm-var ListBlock::DELIM_*|null + * @phpstan-var ListBlock::DELIM_*|null + */ + public ?string $delimiter = null; + + public ?string $bulletChar = null; + + public int $markerOffset; + + public function equals(ListData $data): bool + { + return $this->type === $data->type && + $this->delimiter === $data->delimiter && + $this->bulletChar === $data->bulletChar; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListItem.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListItem.php new file mode 100644 index 0000000..f136b7e --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ListItem.php @@ -0,0 +1,37 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +class ListItem extends AbstractBlock +{ + /** @psalm-readonly */ + protected ListData $listData; + + public function __construct(ListData $listData) + { + parent::__construct(); + + $this->listData = $listData; + } + + public function getListData(): ListData + { + return $this->listData; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ThematicBreak.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ThematicBreak.php new file mode 100644 index 0000000..bb6cea0 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Block/ThematicBreak.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +class ThematicBreak extends AbstractBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/AbstractWebResource.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/AbstractWebResource.php new file mode 100644 index 0000000..dc0ed0a --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/AbstractWebResource.php @@ -0,0 +1,41 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractInline; + +abstract class AbstractWebResource extends AbstractInline +{ + protected string $url; + + public function __construct(string $url) + { + parent::__construct(); + + $this->url = $url; + } + + public function getUrl(): string + { + return $this->url; + } + + public function setUrl(string $url): void + { + $this->url = $url; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Code.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Code.php new file mode 100644 index 0000000..3a6aca2 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Code.php @@ -0,0 +1,23 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractStringContainer; + +class Code extends AbstractStringContainer +{ +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Emphasis.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Emphasis.php new file mode 100644 index 0000000..fab6869 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Emphasis.php @@ -0,0 +1,42 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Inline\DelimitedInterface; + +final class Emphasis extends AbstractInline implements DelimitedInterface +{ + private string $delimiter; + + public function __construct(string $delimiter = '_') + { + parent::__construct(); + + $this->delimiter = $delimiter; + } + + public function getOpeningDelimiter(): string + { + return $this->delimiter; + } + + public function getClosingDelimiter(): string + { + return $this->delimiter; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/HtmlInline.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/HtmlInline.php new file mode 100644 index 0000000..8594a06 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/HtmlInline.php @@ -0,0 +1,24 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractStringContainer; +use League\CommonMark\Node\RawMarkupContainerInterface; + +final class HtmlInline extends AbstractStringContainer implements RawMarkupContainerInterface +{ +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Image.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Image.php new file mode 100644 index 0000000..20e3f87 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Image.php @@ -0,0 +1,49 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\Text; + +class Image extends AbstractWebResource +{ + protected ?string $title = null; + + public function __construct(string $url, ?string $label = null, ?string $title = null) + { + parent::__construct($url); + + if ($label !== null && $label !== '') { + $this->appendChild(new Text($label)); + } + + $this->title = $title; + } + + public function getTitle(): ?string + { + if ($this->title === '') { + return null; + } + + return $this->title; + } + + public function setTitle(?string $title): void + { + $this->title = $title; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Link.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Link.php new file mode 100644 index 0000000..76d5609 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Link.php @@ -0,0 +1,49 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\Text; + +class Link extends AbstractWebResource +{ + protected ?string $title = null; + + public function __construct(string $url, ?string $label = null, ?string $title = null) + { + parent::__construct($url); + + if ($label !== null && $label !== '') { + $this->appendChild(new Text($label)); + } + + $this->title = $title; + } + + public function getTitle(): ?string + { + if ($this->title === '') { + return null; + } + + return $this->title; + } + + public function setTitle(?string $title): void + { + $this->title = $title; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Strong.php b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Strong.php new file mode 100644 index 0000000..827960f --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Node/Inline/Strong.php @@ -0,0 +1,42 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Node\Inline; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Inline\DelimitedInterface; + +final class Strong extends AbstractInline implements DelimitedInterface +{ + private string $delimiter; + + public function __construct(string $delimiter = '**') + { + parent::__construct(); + + $this->delimiter = $delimiter; + } + + public function getOpeningDelimiter(): string + { + return $this->delimiter; + } + + public function getClosingDelimiter(): string + { + return $this->delimiter; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteParser.php new file mode 100644 index 0000000..78db6c5 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteParser.php @@ -0,0 +1,60 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\BlockQuote; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class BlockQuoteParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private BlockQuote $block; + + public function __construct() + { + $this->block = new BlockQuote(); + } + + public function getBlock(): BlockQuote + { + return $this->block; + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return true; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if (! $cursor->isIndented() && $cursor->getNextNonSpaceCharacter() === '>') { + $cursor->advanceToNextNonSpaceOrTab(); + $cursor->advanceBy(1); + $cursor->advanceBySpaceOrTab(); + + return BlockContinue::at($cursor); + } + + return BlockContinue::none(); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteStartParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteStartParser.php new file mode 100644 index 0000000..de9a6bc --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/BlockQuoteStartParser.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class BlockQuoteStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented()) { + return BlockStart::none(); + } + + if ($cursor->getNextNonSpaceCharacter() !== '>') { + return BlockStart::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + $cursor->advanceBy(1); + $cursor->advanceBySpaceOrTab(); + + return BlockStart::of(new BlockQuoteParser())->at($cursor); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeParser.php new file mode 100644 index 0000000..6e605d4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeParser.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\ArrayCollection; +use League\CommonMark\Util\RegexHelper; + +final class FencedCodeParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private FencedCode $block; + + /** @var ArrayCollection */ + private ArrayCollection $strings; + + public function __construct(int $fenceLength, string $fenceChar, int $fenceOffset) + { + $this->block = new FencedCode($fenceLength, $fenceChar, $fenceOffset); + $this->strings = new ArrayCollection(); + } + + public function getBlock(): FencedCode + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + // Check for closing code fence + if (! $cursor->isIndented() && $cursor->getNextNonSpaceCharacter() === $this->block->getChar()) { + $match = RegexHelper::matchFirst('/^(?:`{3,}|~{3,})(?=[ \t]*$)/', $cursor->getLine(), $cursor->getNextNonSpacePosition()); + if ($match !== null && \strlen($match[0]) >= $this->block->getLength()) { + // closing fence - we're at end of line, so we can finalize now + return BlockContinue::finished(); + } + } + + // Skip optional spaces of fence offset, counting columns instead of characters + // so that tabs are only partially consumed when needed + $fenceOffset = $this->block->getOffset(); + while ($fenceOffset > 0 && $cursor->advanceBySpaceOrTab()) { + $fenceOffset--; + } + + return BlockContinue::at($cursor); + } + + public function addLine(string $line): void + { + $this->strings[] = $line; + } + + public function closeBlock(): void + { + // first line becomes info string + $firstLine = $this->strings->first(); + if ($firstLine === false) { + $firstLine = ''; + } + + $this->block->setInfo(RegexHelper::unescape(\trim($firstLine))); + + if ($this->strings->count() === 1) { + $this->block->setLiteral(''); + } else { + $this->block->setLiteral(\implode("\n", $this->strings->slice(1)) . "\n"); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeStartParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeStartParser.php new file mode 100644 index 0000000..7f5996e --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/FencedCodeStartParser.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class FencedCodeStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || ! \in_array($cursor->getNextNonSpaceCharacter(), ['`', '~'], true)) { + return BlockStart::none(); + } + + $indent = $cursor->getIndent(); + $fence = $cursor->matchInPlace('/\G[ \t]*(?:`{3,}+(?!.*`)|~{3,})/'); + if ($fence === null) { + return BlockStart::none(); + } + + // fenced code block + $fence = \ltrim($fence, " \t"); + + return BlockStart::of(new FencedCodeParser(\strlen($fence), $fence[0], $indent))->at($cursor); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingParser.php new file mode 100644 index 0000000..c3e3108 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingParser.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockContinueParserWithInlinesInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\InlineParserEngineInterface; + +final class HeadingParser extends AbstractBlockContinueParser implements BlockContinueParserWithInlinesInterface +{ + /** @psalm-readonly */ + private Heading $block; + + private string $content; + + public function __construct(int $level, string $content) + { + $this->block = new Heading($level); + $this->content = $content; + } + + public function getBlock(): Heading + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::none(); + } + + public function parseInlines(InlineParserEngineInterface $inlineParser): void + { + $inlineParser->parse($this->content, $this->block); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingStartParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingStartParser.php new file mode 100644 index 0000000..404f403 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HeadingStartParser.php @@ -0,0 +1,80 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; + +class HeadingStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || ! \in_array($cursor->getNextNonSpaceCharacter(), ['#', '-', '='], true)) { + return BlockStart::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + + if ($atxHeading = self::getAtxHeader($cursor)) { + return BlockStart::of($atxHeading)->at($cursor); + } + + $setextHeadingLevel = self::getSetextHeadingLevel($cursor); + if ($setextHeadingLevel > 0) { + $content = $parserState->getParagraphContent(); + if ($content !== null) { + $cursor->advanceToEnd(); + + return BlockStart::of(new HeadingParser($setextHeadingLevel, $content)) + ->at($cursor) + ->replaceActiveBlockParser(); + } + } + + return BlockStart::none(); + } + + private static function getAtxHeader(Cursor $cursor): ?HeadingParser + { + $match = RegexHelper::matchFirst('/^#{1,6}(?:[ \t]+|$)/', $cursor->getRemainder()); + if (! $match) { + return null; + } + + $cursor->advanceToNextNonSpaceOrTab(); + $cursor->advanceBy(\strlen($match[0])); + + $level = \strlen(\trim($match[0])); + $str = $cursor->getRemainder(); + $str = \preg_replace('/^[ \t]*#+[ \t]*$/', '', $str); + \assert(\is_string($str)); + $str = \preg_replace('/[ \t]+#+[ \t]*$/', '', $str); + \assert(\is_string($str)); + + return new HeadingParser($level, $str); + } + + private static function getSetextHeadingLevel(Cursor $cursor): int + { + $match = RegexHelper::matchFirst('/^(?:=+|-+)[ \t]*$/', $cursor->getRemainder()); + if ($match === null) { + return 0; + } + + return $match[0][0] === '=' ? 1 : 2; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockParser.php new file mode 100644 index 0000000..6778676 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockParser.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\RegexHelper; + +final class HtmlBlockParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private HtmlBlock $block; + + private string $content = ''; + + private bool $finished = false; + + /** + * @psalm-param HtmlBlock::TYPE_* $blockType + * + * @phpstan-param HtmlBlock::TYPE_* $blockType + */ + public function __construct(int $blockType) + { + $this->block = new HtmlBlock($blockType); + } + + public function getBlock(): HtmlBlock + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($this->finished) { + return BlockContinue::none(); + } + + if ($cursor->isBlank() && \in_array($this->block->getType(), [HtmlBlock::TYPE_6_BLOCK_ELEMENT, HtmlBlock::TYPE_7_MISC_ELEMENT], true)) { + return BlockContinue::none(); + } + + return BlockContinue::at($cursor); + } + + public function addLine(string $line): void + { + if ($this->content !== '') { + $this->content .= "\n"; + } + + $this->content .= $line; + + // Check for end condition + // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($this->block->getType() <= HtmlBlock::TYPE_5_CDATA) { + if (\preg_match(RegexHelper::getHtmlBlockCloseRegex($this->block->getType()), $line) === 1) { + $this->finished = true; + } + } + } + + public function closeBlock(): void + { + $this->block->setLiteral($this->content); + $this->content = ''; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockStartParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockStartParser.php new file mode 100644 index 0000000..bcef0af --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/HtmlBlockStartParser.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; + +final class HtmlBlockStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || $cursor->getNextNonSpaceCharacter() !== '<') { + return BlockStart::none(); + } + + $tmpCursor = clone $cursor; + $tmpCursor->advanceToNextNonSpaceOrTab(); + $line = $tmpCursor->getRemainder(); + + for ($blockType = 1; $blockType <= 7; $blockType++) { + /** @psalm-var HtmlBlock::TYPE_* $blockType */ + /** @phpstan-var HtmlBlock::TYPE_* $blockType */ + $match = RegexHelper::matchAt( + RegexHelper::getHtmlBlockOpenRegex($blockType), + $line + ); + + if ($match !== null && ($blockType < 7 || $this->isType7BlockAllowed($cursor, $parserState))) { + return BlockStart::of(new HtmlBlockParser($blockType))->at($cursor); + } + } + + return BlockStart::none(); + } + + private function isType7BlockAllowed(Cursor $cursor, MarkdownParserStateInterface $parserState): bool + { + // Type 7 blocks can't interrupt paragraphs + if ($parserState->getLastMatchedBlockParser()->getBlock() instanceof Paragraph) { + return false; + } + + // Even lazy ones + return ! $parserState->getActiveBlockParser()->canHaveLazyContinuationLines(); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeParser.php new file mode 100644 index 0000000..ac6406f --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeParser.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\IndentedCode; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\ArrayCollection; + +final class IndentedCodeParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private IndentedCode $block; + + /** @var ArrayCollection */ + private ArrayCollection $strings; + + public function __construct() + { + $this->block = new IndentedCode(); + $this->strings = new ArrayCollection(); + } + + public function getBlock(): IndentedCode + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isIndented()) { + $cursor->advanceBy(Cursor::INDENT_LEVEL, true); + + return BlockContinue::at($cursor); + } + + if ($cursor->isBlank()) { + $cursor->advanceToNextNonSpaceOrTab(); + + return BlockContinue::at($cursor); + } + + return BlockContinue::none(); + } + + public function addLine(string $line): void + { + $this->strings[] = $line; + } + + public function closeBlock(): void + { + $lines = $this->strings->toArray(); + + // Note that indented code block cannot be empty, so $lines will always have at least one non-empty element + while (\preg_match('/^[ \t]*$/', \end($lines))) { // @phpstan-ignore-line + \array_pop($lines); + } + + $this->block->setLiteral(\implode("\n", $lines) . "\n"); + $this->block->setEndLine($this->block->getStartLine() + \count($lines) - 1); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeStartParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeStartParser.php new file mode 100644 index 0000000..bea4bde --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/IndentedCodeStartParser.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class IndentedCodeStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if (! $cursor->isIndented()) { + return BlockStart::none(); + } + + if ($parserState->getActiveBlockParser()->getBlock() instanceof Paragraph) { + return BlockStart::none(); + } + + if ($cursor->isBlank()) { + return BlockStart::none(); + } + + $cursor->advanceBy(Cursor::INDENT_LEVEL, true); + + return BlockStart::of(new IndentedCodeParser())->at($cursor); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockParser.php new file mode 100644 index 0000000..5a7ee45 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockParser.php @@ -0,0 +1,93 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListData; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class ListBlockParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private ListBlock $block; + + public function __construct(ListData $listData) + { + $this->block = new ListBlock($listData); + } + + public function getBlock(): ListBlock + { + return $this->block; + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return $childBlock instanceof ListItem; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + // List blocks themselves don't have any markers, only list items. So try to stay in the list. + // If there is a block start other than list item, canContain makes sure that this list is closed. + return BlockContinue::at($cursor); + } + + public function closeBlock(): void + { + $item = $this->block->firstChild(); + while ($item instanceof AbstractBlock) { + // check for non-final list item ending with blank line: + if ($item->next() !== null && self::endsWithBlankLine($item)) { + $this->block->setTight(false); + break; + } + + // recurse into children of list item, to see if there are spaces between any of them + $subitem = $item->firstChild(); + while ($subitem instanceof AbstractBlock) { + if ($subitem->next() && self::endsWithBlankLine($subitem)) { + $this->block->setTight(false); + break 2; + } + + $subitem = $subitem->next(); + } + + $item = $item->next(); + } + + $lastChild = $this->block->lastChild(); + if ($lastChild instanceof AbstractBlock) { + $this->block->setEndLine($lastChild->getEndLine()); + } + } + + private static function endsWithBlankLine(AbstractBlock $block): bool + { + $next = $block->next(); + + return $next instanceof AbstractBlock && $block->getEndLine() !== $next->getStartLine() - 1; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php new file mode 100644 index 0000000..28977b2 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php @@ -0,0 +1,154 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListData; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class ListBlockStartParser implements BlockStartParserInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ?ConfigurationInterface $config = null; + + /** + * @psalm-var non-empty-string|null + * + * @psalm-readonly-allow-private-mutation + */ + private ?string $listMarkerRegex = null; + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented()) { + return BlockStart::none(); + } + + $listData = $this->parseList($cursor, $parserState->getParagraphContent() !== null); + if ($listData === null) { + return BlockStart::none(); + } + + $listItemParser = new ListItemParser($listData); + + // prepend the list block if needed + $matched = $parserState->getLastMatchedBlockParser(); + if (! ($matched instanceof ListBlockParser) || ! $listData->equals($matched->getBlock()->getListData())) { + $listBlockParser = new ListBlockParser($listData); + // We start out with assuming a list is tight. If we find a blank line, we set it to loose later. + // TODO for 3.0: Just make them tight by default in the block so we can remove this call + $listBlockParser->getBlock()->setTight(true); + + return BlockStart::of($listBlockParser, $listItemParser)->at($cursor); + } + + return BlockStart::of($listItemParser)->at($cursor); + } + + private function parseList(Cursor $cursor, bool $inParagraph): ?ListData + { + $indent = $cursor->getIndent(); + + $tmpCursor = clone $cursor; + $tmpCursor->advanceToNextNonSpaceOrTab(); + $rest = $tmpCursor->getRemainder(); + + if (\preg_match($this->listMarkerRegex ?? $this->generateListMarkerRegex(), $rest) === 1) { + $data = new ListData(); + $data->markerOffset = $indent; + $data->type = ListBlock::TYPE_BULLET; + $data->delimiter = null; + $data->bulletChar = $rest[0]; + $markerLength = 1; + } elseif (($matches = RegexHelper::matchFirst('/^(\d{1,9})([.)])/', $rest)) && (! $inParagraph || $matches[1] === '1')) { + $data = new ListData(); + $data->markerOffset = $indent; + $data->type = ListBlock::TYPE_ORDERED; + $data->start = (int) $matches[1]; + $data->delimiter = $matches[2] === '.' ? ListBlock::DELIM_PERIOD : ListBlock::DELIM_PAREN; + $data->bulletChar = null; + $markerLength = \strlen($matches[0]); + } else { + return null; + } + + // Make sure we have spaces after + $nextChar = $tmpCursor->peek($markerLength); + if (! ($nextChar === null || $nextChar === "\t" || $nextChar === ' ')) { + return null; + } + + // If it interrupts paragraph, make sure first line isn't blank + if ($inParagraph && ! RegexHelper::matchAt(RegexHelper::REGEX_NON_SPACE, $rest, $markerLength)) { + return null; + } + + $cursor->advanceToNextNonSpaceOrTab(); // to start of marker + $cursor->advanceBy($markerLength, true); // to end of marker + $data->padding = self::calculateListMarkerPadding($cursor, $markerLength); + + return $data; + } + + private static function calculateListMarkerPadding(Cursor $cursor, int $markerLength): int + { + $start = $cursor->saveState(); + $spacesStartCol = $cursor->getColumn(); + + while ($cursor->getColumn() - $spacesStartCol < 5) { + if (! $cursor->advanceBySpaceOrTab()) { + break; + } + } + + $blankItem = $cursor->isAtEnd(); + $spacesAfterMarker = $cursor->getColumn() - $spacesStartCol; + + if ($spacesAfterMarker >= 5 || $spacesAfterMarker < 1 || $blankItem) { + $cursor->restoreState($start); + $cursor->advanceBySpaceOrTab(); + + return $markerLength + 1; + } + + return $markerLength + $spacesAfterMarker; + } + + /** + * @psalm-return non-empty-string + */ + private function generateListMarkerRegex(): string + { + // No configuration given - use the defaults + if ($this->config === null) { + return $this->listMarkerRegex = '/^[*+-]/'; + } + + $markers = $this->config->get('commonmark/unordered_list_markers'); + \assert(\is_array($markers)); + + return $this->listMarkerRegex = '/^[' . \preg_quote(\implode('', $markers), '/') . ']/'; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListItemParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListItemParser.php new file mode 100644 index 0000000..739eefc --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListItemParser.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListData; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class ListItemParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private ListItem $block; + + public function __construct(ListData $listData) + { + $this->block = new ListItem($listData); + } + + public function getBlock(): ListItem + { + return $this->block; + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return ! $childBlock instanceof ListItem; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + if ($this->block->firstChild() === null) { + // Blank line after empty list item + return BlockContinue::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + + return BlockContinue::at($cursor); + } + + $contentIndent = $this->block->getListData()->markerOffset + $this->getBlock()->getListData()->padding; + if ($cursor->getIndent() >= $contentIndent) { + $cursor->advanceBy($contentIndent, true); + + return BlockContinue::at($cursor); + } + + // Note: We'll hit this case for lazy continuation lines, they will get added later. + return BlockContinue::none(); + } + + public function closeBlock(): void + { + if (($lastChild = $this->block->lastChild()) instanceof AbstractBlock) { + $this->block->setEndLine($lastChild->getEndLine()); + } else { + // Empty list item + $this->block->setEndLine($this->block->getStartLine()); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakParser.php new file mode 100644 index 0000000..fb46637 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakParser.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ThematicBreak; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class ThematicBreakParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private ThematicBreak $block; + + public function __construct() + { + $this->block = new ThematicBreak(); + } + + public function getBlock(): ThematicBreak + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + // a horizontal rule can never container > 1 line, so fail to match + return BlockContinue::none(); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakStartParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakStartParser.php new file mode 100644 index 0000000..ba7ddf3 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ThematicBreakStartParser.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; + +final class ThematicBreakStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented()) { + return BlockStart::none(); + } + + $match = RegexHelper::matchAt(RegexHelper::REGEX_THEMATIC_BREAK, $cursor->getLine(), $cursor->getNextNonSpacePosition()); + if ($match === null) { + return BlockStart::none(); + } + + // Advance to the end of the string, consuming the entire line (of the thematic break) + $cursor->advanceToEnd(); + + return BlockStart::of(new ThematicBreakParser())->at($cursor); + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/AutolinkParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/AutolinkParser.php new file mode 100644 index 0000000..810769d --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/AutolinkParser.php @@ -0,0 +1,54 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\UrlEncoder; + +final class AutolinkParser implements InlineParserInterface +{ + private const EMAIL_REGEX = '<([a-zA-Z0-9.!#$%&\'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>'; + private const OTHER_LINK_REGEX = '<([A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*)>'; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex(self::EMAIL_REGEX . '|' . self::OTHER_LINK_REGEX); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + $matches = $inlineContext->getMatches(); + + if ($matches[1] !== '') { + $inlineContext->getContainer()->appendChild(new Link('mailto:' . UrlEncoder::unescapeAndEncode($matches[1]), $matches[1])); + + return true; + } + + if ($matches[2] !== '') { + $inlineContext->getContainer()->appendChild(new Link(UrlEncoder::unescapeAndEncode($matches[2]), $matches[2])); + + return true; + } + + return false; // This should never happen + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BacktickParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BacktickParser.php new file mode 100644 index 0000000..92aaf77 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BacktickParser.php @@ -0,0 +1,132 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Code; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class BacktickParser implements InlineParserInterface +{ + /** + * Max bound for backtick code span delimiters. + * + * @see https://github.com/commonmark/cmark/commit/8ed5c9d + */ + private const MAX_BACKTICKS = 1000; + + /** @var \WeakReference|null */ + private ?\WeakReference $lastCursor = null; + private bool $lastCursorScanned = false; + + /** @var array backtick count => position of known ender */ + private array $seenBackticks = []; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('`+'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $ticks = $inlineContext->getFullMatch(); + $cursor = $inlineContext->getCursor(); + $cursor->advanceBy($inlineContext->getFullMatchLength()); + + $currentPosition = $cursor->getPosition(); + $previousState = $cursor->saveState(); + + if ($this->findMatchingTicks(\strlen($ticks), $cursor)) { + $code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks)); + + $c = \str_replace("\n", ' ', $code); + + if ( + $c !== '' && + $c[0] === ' ' && + \substr($c, -1, 1) === ' ' && + \strspn($c, ' ') !== \strlen($c) + ) { + $c = \substr($c, 1, -1); + } + + $inlineContext->getContainer()->appendChild(new Code($c)); + + return true; + } + + // If we got here, we didn't match a closing backtick sequence + $cursor->restoreState($previousState); + $inlineContext->getContainer()->appendChild(new Text($ticks)); + + return true; + } + + /** + * Locates the matching closer for a backtick code span. + * + * Leverages some caching to avoid traversing the same cursor multiple times when + * we've already seen all the potential backtick closers. + * + * @see https://github.com/commonmark/cmark/commit/8ed5c9d + * + * @param int $openTickLength Number of backticks in the opening sequence + * @param Cursor $cursor Cursor to scan + * + * @return bool True if a matching closer was found, false otherwise + */ + private function findMatchingTicks(int $openTickLength, Cursor $cursor): bool + { + // Reset the seenBackticks cache if this is a new cursor + if ($this->lastCursor === null || $this->lastCursor->get() !== $cursor) { + $this->seenBackticks = []; + $this->lastCursor = \WeakReference::create($cursor); + $this->lastCursorScanned = false; + } + + if ($openTickLength > self::MAX_BACKTICKS) { + return false; + } + + // Return if we already know there's no closer + if ($this->lastCursorScanned && isset($this->seenBackticks[$openTickLength]) && $this->seenBackticks[$openTickLength] <= $cursor->getPosition()) { + return false; + } + + while ($ticks = $cursor->matchInPlace('/`{1,' . self::MAX_BACKTICKS . '}/')) { + $numTicks = \strlen($ticks); + + // Did we find the closer? + if ($numTicks === $openTickLength) { + return true; + } + + // Store position of closer + if ($numTicks <= self::MAX_BACKTICKS) { + $this->seenBackticks[$numTicks] = $cursor->getPosition() - $numTicks; + } + } + + // Got through whole input without finding closer + $this->lastCursorScanned = true; + + return false; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BangParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BangParser.php new file mode 100644 index 0000000..cbf6ca3 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/BangParser.php @@ -0,0 +1,44 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class BangParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string('!['); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + $cursor->advanceBy(2); + + $node = new Text('![', ['delim' => true]); + $inlineContext->getContainer()->appendChild($node); + + // Add entry to stack for this opener + $inlineContext->getDelimiterStack()->addBracket($node, $cursor->getPosition(), true); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/CloseBracketParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/CloseBracketParser.php new file mode 100644 index 0000000..34fabfa --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/CloseBracketParser.php @@ -0,0 +1,224 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Delimiter\Bracket; +use League\CommonMark\Environment\EnvironmentAwareInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Extension\CommonMark\Node\Inline\AbstractWebResource; +use League\CommonMark\Extension\CommonMark\Node\Inline\Image; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Extension\Mention\Mention; +use League\CommonMark\Node\Inline\AdjacentTextMerger; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceMapInterface; +use League\CommonMark\Util\LinkParserHelper; +use League\CommonMark\Util\RegexHelper; + +final class CloseBracketParser implements InlineParserInterface, EnvironmentAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private EnvironmentInterface $environment; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string(']'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + // Look through stack of delimiters for a [ or ! + $opener = $inlineContext->getDelimiterStack()->getLastBracket(); + if ($opener === null) { + return false; + } + + if (! $opener->isImage() && ! $opener->isActive()) { + // no matched opener; remove from stack + $inlineContext->getDelimiterStack()->removeBracket(); + + return false; + } + + $cursor = $inlineContext->getCursor(); + + $startPos = $cursor->getPosition(); + $previousState = $cursor->saveState(); + + $cursor->advanceBy(1); + + // Check to see if we have a link/image + + // Inline link? + if ($result = $this->tryParseInlineLinkAndTitle($cursor)) { + $link = $result; + } elseif ($link = $this->tryParseReference($cursor, $inlineContext->getReferenceMap(), $opener, $startPos)) { + $reference = $link; + $link = ['url' => $link->getDestination(), 'title' => $link->getTitle()]; + } else { + // No match; remove this opener from stack + $inlineContext->getDelimiterStack()->removeBracket(); + $cursor->restoreState($previousState); + + return false; + } + + $inline = $this->createInline($link['url'], $link['title'], $opener->isImage(), $reference ?? null); + $opener->getNode()->replaceWith($inline); + while (($label = $inline->next()) !== null) { + // Is there a Mention or Link contained within this link? + // CommonMark does not allow nested links, so we'll restore the original text. + if ($label instanceof Mention) { + $label->replaceWith($replacement = new Text($label->getPrefix() . $label->getIdentifier())); + $inline->appendChild($replacement); + } elseif ($label instanceof Link) { + foreach ($label->children() as $child) { + $label->insertBefore($child); + } + + $label->detach(); + } else { + $inline->appendChild($label); + } + } + + // Process delimiters such as emphasis inside link/image + $delimiterStack = $inlineContext->getDelimiterStack(); + $stackBottom = $opener->getPosition(); + $delimiterStack->processDelimiters($stackBottom, $this->environment->getDelimiterProcessors()); + $delimiterStack->removeBracket(); + $delimiterStack->removeAll($stackBottom); + + // Merge any adjacent Text nodes together + AdjacentTextMerger::mergeChildNodes($inline); + + // processEmphasis will remove this and later delimiters. + // Now, for a link, we also remove earlier link openers (no links in links) + if (! $opener->isImage()) { + $inlineContext->getDelimiterStack()->deactivateLinkOpeners(); + } + + return true; + } + + public function setEnvironment(EnvironmentInterface $environment): void + { + $this->environment = $environment; + } + + /** + * @return array|null + */ + private function tryParseInlineLinkAndTitle(Cursor $cursor): ?array + { + if ($cursor->getCurrentCharacter() !== '(') { + return null; + } + + $previousState = $cursor->saveState(); + + $cursor->advanceBy(1); + $cursor->advanceToNextNonSpaceOrNewline(); + if (($dest = LinkParserHelper::parseLinkDestination($cursor)) === null) { + $cursor->restoreState($previousState); + + return null; + } + + $cursor->advanceToNextNonSpaceOrNewline(); + $previousCharacter = $cursor->peek(-1); + // We know from previous lines that we've advanced at least one space so far, so this next call should never be null + \assert(\is_string($previousCharacter)); + + $title = ''; + // make sure there's a space before the title: + if (\preg_match(RegexHelper::REGEX_WHITESPACE_CHAR, $previousCharacter)) { + $title = LinkParserHelper::parseLinkTitle($cursor) ?? ''; + } + + $cursor->advanceToNextNonSpaceOrNewline(); + + if ($cursor->getCurrentCharacter() !== ')') { + $cursor->restoreState($previousState); + + return null; + } + + $cursor->advanceBy(1); + + return ['url' => $dest, 'title' => $title]; + } + + private function tryParseReference(Cursor $cursor, ReferenceMapInterface $referenceMap, Bracket $opener, int $startPos): ?ReferenceInterface + { + $savePos = $cursor->saveState(); + $beforeLabel = $cursor->getPosition(); + $n = LinkParserHelper::parseLinkLabel($cursor); + if ($n > 2) { + $start = $beforeLabel + 1; + $length = $n - 2; + } elseif (! $opener->hasNext()) { + // Empty or missing second label means to use the first label as the reference. + // The reference must not contain a bracket. If we know there's a bracket, we don't even bother checking it. + $start = $opener->getPosition(); + $length = $startPos - $start; + + // spec: A link label can have at most 999 characters inside the square brackets. + // ReferenceParser::parseLabel() enforces that when storing definitions, so a longer + // span here cannot possibly match one. Rejecting it up-front - before copying and + // normalizing the span - is what keeps deeply-nested brackets from being quadratic. + if ($length > 999) { + $cursor->restoreState($savePos); + + return null; + } + } else { + $cursor->restoreState($savePos); + + return null; + } + + $referenceLabel = $cursor->getSubstring($start, $length); + + if ($n === 0) { + // If shortcut reference link, rewind before spaces we skipped + $cursor->restoreState($savePos); + } + + return $referenceMap->get($referenceLabel); + } + + private function createInline(string $url, string $title, bool $isImage, ?ReferenceInterface $reference = null): AbstractWebResource + { + if ($isImage) { + $inline = new Image($url, null, $title); + } else { + $inline = new Link($url, null, $title); + } + + if ($reference) { + $inline->data->set('reference', $reference); + } + + return $inline; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EntityParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EntityParser.php new file mode 100644 index 0000000..4122ff7 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EntityParser.php @@ -0,0 +1,42 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\Html5EntityDecoder; +use League\CommonMark\Util\RegexHelper; + +final class EntityParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex(RegexHelper::PARTIAL_ENTITY); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $entity = $inlineContext->getFullMatch(); + + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + $inlineContext->getContainer()->appendChild(new Text(Html5EntityDecoder::decode($entity))); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EscapableParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EscapableParser.php new file mode 100644 index 0000000..64e6fab --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/EscapableParser.php @@ -0,0 +1,57 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\RegexHelper; + +final class EscapableParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string('\\'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + $nextChar = $cursor->peek(); + + if ($nextChar === "\n") { + $cursor->advanceBy(2); + $inlineContext->getContainer()->appendChild(new Newline(Newline::HARDBREAK)); + + return true; + } + + if ($nextChar !== null && RegexHelper::isEscapable($nextChar)) { + $cursor->advanceBy(2); + $inlineContext->getContainer()->appendChild(new Text($nextChar)); + + return true; + } + + $cursor->advanceBy(1); + $inlineContext->getContainer()->appendChild(new Text('\\')); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/HtmlInlineParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/HtmlInlineParser.php new file mode 100644 index 0000000..f38db13 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/HtmlInlineParser.php @@ -0,0 +1,41 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\RegexHelper; + +final class HtmlInlineParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex(RegexHelper::PARTIAL_HTMLTAG)->caseSensitive(); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inline = $inlineContext->getFullMatch(); + + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + $inlineContext->getContainer()->appendChild(new HtmlInline($inline)); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/OpenBracketParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/OpenBracketParser.php new file mode 100644 index 0000000..1ba8c13 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Inline/OpenBracketParser.php @@ -0,0 +1,42 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Parser\Inline; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class OpenBracketParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::string('['); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy(1); + $node = new Text('[', ['delim' => true]); + $inlineContext->getContainer()->appendChild($node); + + // Add entry to stack for this opener + $inlineContext->getDelimiterStack()->addBracket($node, $inlineContext->getCursor()->getPosition(), false); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/BlockQuoteRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/BlockQuoteRenderer.php new file mode 100644 index 0000000..4a59bd3 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/BlockQuoteRenderer.php @@ -0,0 +1,70 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\BlockQuote; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class BlockQuoteRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param BlockQuote $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + BlockQuote::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $filling = $childRenderer->renderNodes($node->children()); + $innerSeparator = $childRenderer->getInnerSeparator(); + if ($filling === '') { + return new HtmlElement('blockquote', $attrs, $innerSeparator); + } + + return new HtmlElement( + 'blockquote', + $attrs, + $innerSeparator . $filling . $innerSeparator + ); + } + + public function getXmlTagName(Node $node): string + { + return 'block_quote'; + } + + /** + * @param BlockQuote $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/FencedCodeRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/FencedCodeRenderer.php new file mode 100644 index 0000000..8df9a40 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/FencedCodeRenderer.php @@ -0,0 +1,81 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\Xml; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class FencedCodeRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param FencedCode $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + FencedCode::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + + $infoWords = $node->getInfoWords(); + if (\count($infoWords) !== 0 && $infoWords[0] !== '') { + $class = $infoWords[0]; + if (! \str_starts_with($class, 'language-')) { + $class = 'language-' . $class; + } + + $attrs->append('class', $class); + } + + return new HtmlElement( + 'pre', + [], + new HtmlElement('code', $attrs->export(), Xml::escape($node->getLiteral())) + ); + } + + public function getXmlTagName(Node $node): string + { + return 'code_block'; + } + + /** + * @param FencedCode $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + FencedCode::assertInstanceOf($node); + + if (($info = $node->getInfo()) === null || $info === '') { + return []; + } + + return ['info' => $info]; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HeadingRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HeadingRenderer.php new file mode 100644 index 0000000..8718b8c --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HeadingRenderer.php @@ -0,0 +1,64 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class HeadingRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Heading $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Heading::assertInstanceOf($node); + + $tag = 'h' . $node->getLevel(); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement($tag, $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'heading'; + } + + /** + * @param Heading $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + Heading::assertInstanceOf($node); + + return ['level' => $node->getLevel()]; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HtmlBlockRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HtmlBlockRenderer.php new file mode 100644 index 0000000..63a1907 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/HtmlBlockRenderer.php @@ -0,0 +1,66 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlFilter; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class HtmlBlockRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param HtmlBlock $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + HtmlBlock::assertInstanceOf($node); + + $htmlInput = $this->config->get('html_input'); + + return HtmlFilter::filter($node->getLiteral(), $htmlInput); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'html_block'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/IndentedCodeRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/IndentedCodeRenderer.php new file mode 100644 index 0000000..c4bd4eb --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/IndentedCodeRenderer.php @@ -0,0 +1,61 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\IndentedCode; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\Xml; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class IndentedCodeRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param IndentedCode $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + IndentedCode::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement( + 'pre', + [], + new HtmlElement('code', $attrs, Xml::escape($node->getLiteral())) + ); + } + + public function getXmlTagName(Node $node): string + { + return 'code_block'; + } + + /** + * @return array + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListBlockRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListBlockRenderer.php new file mode 100644 index 0000000..f79b44d --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListBlockRenderer.php @@ -0,0 +1,86 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class ListBlockRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param ListBlock $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + ListBlock::assertInstanceOf($node); + + $listData = $node->getListData(); + + $tag = $listData->type === ListBlock::TYPE_BULLET ? 'ul' : 'ol'; + + $attrs = $node->data->get('attributes'); + + if ($listData->start !== null && $listData->start !== 1) { + $attrs['start'] = (string) $listData->start; + } + + $innerSeparator = $childRenderer->getInnerSeparator(); + + return new HtmlElement($tag, $attrs, $innerSeparator . $childRenderer->renderNodes($node->children()) . $innerSeparator); + } + + public function getXmlTagName(Node $node): string + { + return 'list'; + } + + /** + * @param ListBlock $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + ListBlock::assertInstanceOf($node); + + $data = $node->getListData(); + + if ($data->type === ListBlock::TYPE_BULLET) { + return [ + 'type' => $data->type, + 'tight' => $node->isTight() ? 'true' : 'false', + ]; + } + + return [ + 'type' => $data->type, + 'start' => $data->start ?? 1, + 'tight' => $node->isTight(), + 'delimiter' => $data->delimiter ?? ListBlock::DELIM_PERIOD, + ]; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListItemRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListItemRenderer.php new file mode 100644 index 0000000..543baad --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ListItemRenderer.php @@ -0,0 +1,80 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Block\TightBlockInterface; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class ListItemRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param ListItem $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + ListItem::assertInstanceOf($node); + + $contents = $childRenderer->renderNodes($node->children()); + + $inTightList = ($parent = $node->parent()) && $parent instanceof TightBlockInterface && $parent->isTight(); + + if ($this->needsBlockSeparator($node->firstChild(), $inTightList)) { + $contents = "\n" . $contents; + } + + if ($this->needsBlockSeparator($node->lastChild(), $inTightList)) { + $contents .= "\n"; + } + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('li', $attrs, $contents); + } + + public function getXmlTagName(Node $node): string + { + return 'item'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } + + private function needsBlockSeparator(?Node $child, bool $inTightList): bool + { + if ($child instanceof Paragraph && $inTightList) { + return false; + } + + return $child instanceof AbstractBlock; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ThematicBreakRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ThematicBreakRenderer.php new file mode 100644 index 0000000..392bfee --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Block/ThematicBreakRenderer.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Block; + +use League\CommonMark\Extension\CommonMark\Node\Block\ThematicBreak; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class ThematicBreakRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param ThematicBreak $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + ThematicBreak::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('hr', $attrs, '', true); + } + + public function getXmlTagName(Node $node): string + { + return 'thematic_break'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/CodeRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/CodeRenderer.php new file mode 100644 index 0000000..de030e8 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/CodeRenderer.php @@ -0,0 +1,57 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Code; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\Xml; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class CodeRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Code $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Code::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('code', $attrs, Xml::escape($node->getLiteral())); + } + + public function getXmlTagName(Node $node): string + { + return 'code'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/EmphasisRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/EmphasisRenderer.php new file mode 100644 index 0000000..41169c4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/EmphasisRenderer.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Emphasis; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class EmphasisRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Emphasis $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Emphasis::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('em', $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'emph'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/HtmlInlineRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/HtmlInlineRenderer.php new file mode 100644 index 0000000..69f0fd5 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/HtmlInlineRenderer.php @@ -0,0 +1,66 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlFilter; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class HtmlInlineRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param HtmlInline $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + HtmlInline::assertInstanceOf($node); + + $htmlInput = $this->config->get('html_input'); + + return HtmlFilter::filter($node->getLiteral(), $htmlInput); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'html_inline'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/ImageRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/ImageRenderer.php new file mode 100644 index 0000000..7bf09ac --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/ImageRenderer.php @@ -0,0 +1,107 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Image; +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\Node; +use League\CommonMark\Node\NodeIterator; +use League\CommonMark\Node\StringContainerInterface; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\RegexHelper; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class ImageRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param Image $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Image::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $forbidUnsafeLinks = ! $this->config->get('allow_unsafe_links'); + if ($forbidUnsafeLinks && RegexHelper::isLinkPotentiallyUnsafe($node->getUrl())) { + $attrs['src'] = ''; + } else { + $attrs['src'] = $node->getUrl(); + } + + $attrs['alt'] = $this->getAltText($node); + + if (($title = $node->getTitle()) !== null) { + $attrs['title'] = $title; + } + + return new HtmlElement('img', $attrs, '', true); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'image'; + } + + /** + * @param Image $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + Image::assertInstanceOf($node); + + return [ + 'destination' => $node->getUrl(), + 'title' => $node->getTitle() ?? '', + ]; + } + + private function getAltText(Image $node): string + { + $altText = ''; + + foreach ((new NodeIterator($node)) as $n) { + if ($n instanceof StringContainerInterface) { + $altText .= $n->getLiteral(); + } elseif ($n instanceof Newline) { + $altText .= "\n"; + } + } + + return $altText; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/LinkRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/LinkRenderer.php new file mode 100644 index 0000000..4ef9645 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/LinkRenderer.php @@ -0,0 +1,89 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Util\RegexHelper; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class LinkRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + /** + * @param Link $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Link::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $forbidUnsafeLinks = ! $this->config->get('allow_unsafe_links'); + if (! ($forbidUnsafeLinks && RegexHelper::isLinkPotentiallyUnsafe($node->getUrl()))) { + $attrs['href'] = $node->getUrl(); + } + + if (($title = $node->getTitle()) !== null) { + $attrs['title'] = $title; + } + + if (isset($attrs['target']) && $attrs['target'] === '_blank' && ! isset($attrs['rel'])) { + $attrs['rel'] = 'noopener noreferrer'; + } + + return new HtmlElement('a', $attrs, $childRenderer->renderNodes($node->children())); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'link'; + } + + /** + * @param Link $node + * + * @return array + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + Link::assertInstanceOf($node); + + return [ + 'destination' => $node->getUrl(), + 'title' => $node->getTitle() ?? '', + ]; + } +} diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/StrongRenderer.php b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/StrongRenderer.php new file mode 100644 index 0000000..f0bb8f9 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/CommonMark/Renderer/Inline/StrongRenderer.php @@ -0,0 +1,56 @@ + + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\CommonMark\Renderer\Inline; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Strong; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class StrongRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Strong $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Strong::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('strong', $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'strong'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/ConfigurableExtensionInterface.php b/vendor/league/commonmark/src/Extension/ConfigurableExtensionInterface.php new file mode 100644 index 0000000..63e467c --- /dev/null +++ b/vendor/league/commonmark/src/Extension/ConfigurableExtensionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension; + +use League\Config\ConfigurationBuilderInterface; + +interface ConfigurableExtensionInterface extends ExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void; +} diff --git a/vendor/league/commonmark/src/Extension/DefaultAttributes/ApplyDefaultAttributesProcessor.php b/vendor/league/commonmark/src/Extension/DefaultAttributes/ApplyDefaultAttributesProcessor.php new file mode 100644 index 0000000..fcc8758 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DefaultAttributes/ApplyDefaultAttributesProcessor.php @@ -0,0 +1,151 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DefaultAttributes; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Node\Node; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; +use League\Config\Exception\InvalidConfigurationException; + +final class ApplyDefaultAttributesProcessor implements ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + /** + * Configured attributes with every callback already resolved to a `Closure`, keyed by node FQCN. + * + * @var array>|null + */ + private ?array $resolved = null; + + public function onDocumentParsed(DocumentParsedEvent $event): void + { + if ($this->resolved === null) { + $this->resolved = $this->resolveConfiguredAttributes(); + } + + $map = $this->resolved; + + // Don't bother iterating if no default attributes are configured + if (! $map) { + return; + } + + foreach ($event->getDocument()->iterator() as $node) { + // Check to see if any default attributes were defined + if (($attributesToApply = $map[\get_class($node)] ?? []) === []) { + continue; + } + + $newAttributes = []; + foreach ($attributesToApply as $name => $value) { + if ($value instanceof \Closure) { + $value = $value($node); + // Callables are allowed to return `null` indicating that no changes should be made + if ($value !== null) { + $newAttributes[$name] = $value; + } + } else { + $newAttributes[$name] = $value; + } + } + + // Merge these attributes into the node + if (\count($newAttributes) > 0) { + $node->data->set('attributes', AttributesHelper::mergeAttributes($node, $newAttributes)); + } + } + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + /** + * @return array> + */ + private function resolveConfiguredAttributes(): array + { + /** @var array> $map */ + $map = $this->config->get('default_attributes/attributes'); + $strict = (bool) $this->config->get('default_attributes/strict_callables'); + + $resolved = []; + foreach ($map as $class => $attributes) { + foreach ($attributes as $name => $value) { + $resolved[$class][$name] = self::resolveValue($class, $name, $value, $strict); + } + } + + return $resolved; + } + + /** + * @param mixed $value + * + * @return mixed A `Closure` if the value is a callback, otherwise the literal attribute value + */ + private static function resolveValue(string $class, string $name, $value, bool $strict) + { + if ($value instanceof \Closure) { + return $value; + } + + if (\is_string($value) || \is_array($value)) { + // Strings and arrays are how literal attribute values are written, and plenty of them also + // name a real function - PHP has a global `link()`, for example + if ($strict) { + return $value; + } + + if (! \is_callable($value)) { + return $value; + } + + return self::wrapCallable($class, $name, $value, \Closure::fromCallable($value)); + } + + return \is_callable($value) ? \Closure::fromCallable($value) : $value; + } + + /** + * Invoke the callable, replacing a failure with one which names the configuration responsible. + * + * A value like `'link'` is otherwise invoked and fails deep inside whichever function it collided + * with, reporting an argument count the user never wrote. + * + * @param string|mixed[] $value The callable as it was written in the configuration + */ + private static function wrapCallable(string $class, string $name, $value, \Closure $callback): \Closure + { + return static function (Node $node) use ($callback, $class, $name, $value) { + try { + return $callback($node); + } catch (\TypeError $e) { + throw new InvalidConfigurationException(\sprintf( + 'The "%s" attribute configured for %s is %s, which PHP also treats as a callable, so it was ' + . 'called with the node and failed: %s. If it was meant to be a literal attribute value instead, ' + . 'set "default_attributes/strict_callables" to true.', + $name, + $class, + \is_string($value) ? \sprintf('the string "%s"', $value) : 'an array', + $e->getMessage() + ), 0, $e); + } + }; + } +} diff --git a/vendor/league/commonmark/src/Extension/DefaultAttributes/DefaultAttributesExtension.php b/vendor/league/commonmark/src/Extension/DefaultAttributes/DefaultAttributesExtension.php new file mode 100644 index 0000000..bb381c4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DefaultAttributes/DefaultAttributesExtension.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DefaultAttributes; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class DefaultAttributesExtension implements ConfigurableExtensionInterface +{ + /** + * Keys belonging to this extension's own settings rather than to a node class + */ + private const RESERVED_KEYS = ['attributes' => 0, 'strict_callables' => 0]; + + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('default_attributes', Expect::structure([ + 'attributes' => Expect::arrayOf( + Expect::arrayOf( + Expect::type('string|string[]|bool|callable'), // attribute value(s) + 'string' // attribute name + ), + 'string' // node FQCN + )->default([]), + // @deprecated This option will be removed in 3.0, when only closures and invokable objects + // will ever be treated as callbacks. + 'strict_callables' => Expect::bool()->default(true), + ])->before(static function ($value) { + if (! \is_array($value)) { + return $value; + } + + $canonical = \array_intersect_key($value, self::RESERVED_KEYS); + $legacy = \array_diff_key($value, self::RESERVED_KEYS); + + if ($legacy === []) { + return $value; + } + + // Nothing can be merged into an `attributes` which isn't an array; hand it to the schema + // as-is so it reports the same validation error it would without the node classes present + if (isset($canonical['attributes']) && ! \is_array($canonical['attributes'])) { + return $canonical; + } + + $canonical['attributes'] = \array_merge($legacy, $canonical['attributes'] ?? []); + + // The flat shape predates this option, so it stays on the legacy callable handling + // unless it opts in explicitly. + if (! \array_key_exists('strict_callables', $canonical)) { + $canonical['strict_callables'] = false; + } + + return $canonical; + })); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentParsedEvent::class, [new ApplyDefaultAttributesProcessor(), 'onDocumentParsed']); + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/DescriptionListExtension.php b/vendor/league/commonmark/src/Extension/DescriptionList/DescriptionListExtension.php new file mode 100644 index 0000000..9ddd2a8 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/DescriptionListExtension.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\DescriptionList\Event\ConsecutiveDescriptionListMerger; +use League\CommonMark\Extension\DescriptionList\Event\LooseDescriptionHandler; +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Extension\DescriptionList\Parser\DescriptionStartParser; +use League\CommonMark\Extension\DescriptionList\Renderer\DescriptionListRenderer; +use League\CommonMark\Extension\DescriptionList\Renderer\DescriptionRenderer; +use League\CommonMark\Extension\DescriptionList\Renderer\DescriptionTermRenderer; +use League\CommonMark\Extension\ExtensionInterface; + +final class DescriptionListExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addBlockStartParser(new DescriptionStartParser()); + + $environment->addEventListener(DocumentParsedEvent::class, new LooseDescriptionHandler(), 1001); + $environment->addEventListener(DocumentParsedEvent::class, new ConsecutiveDescriptionListMerger(), 1000); + + $environment->addRenderer(DescriptionList::class, new DescriptionListRenderer()); + $environment->addRenderer(DescriptionTerm::class, new DescriptionTermRenderer()); + $environment->addRenderer(Description::class, new DescriptionRenderer()); + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Event/ConsecutiveDescriptionListMerger.php b/vendor/league/commonmark/src/Extension/DescriptionList/Event/ConsecutiveDescriptionListMerger.php new file mode 100644 index 0000000..15210e7 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Event/ConsecutiveDescriptionListMerger.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Node\NodeIterator; + +final class ConsecutiveDescriptionListMerger +{ + public function __invoke(DocumentParsedEvent $event): void + { + foreach ($event->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof DescriptionList) { + continue; + } + + if (! ($prev = $node->previous()) instanceof DescriptionList) { + continue; + } + + // There's another description list behind this one; merge the current one into that + foreach ($node->children() as $child) { + $prev->appendChild($child); + } + + $node->detach(); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Event/LooseDescriptionHandler.php b/vendor/league/commonmark/src/Extension/DescriptionList/Event/LooseDescriptionHandler.php new file mode 100644 index 0000000..a8823fa --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Event/LooseDescriptionHandler.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\NodeIterator; + +final class LooseDescriptionHandler +{ + public function __invoke(DocumentParsedEvent $event): void + { + foreach ($event->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $description) { + if (! $description instanceof Description) { + continue; + } + + // Does this description need to be added to a list? + if (! $description->parent() instanceof DescriptionList) { + $list = new DescriptionList(); + // Taking any preceding paragraphs with it + if (($paragraph = $description->previous()) instanceof Paragraph) { + $list->appendChild($paragraph); + } + + $description->replaceWith($list); + $list->appendChild($description); + } + + // Is this description preceded by a paragraph that should really be a term? + if (! (($paragraph = $description->previous()) instanceof Paragraph)) { + continue; + } + + // Convert the paragraph into one or more terms + $term = new DescriptionTerm(); + $paragraph->replaceWith($term); + + foreach ($paragraph->children() as $child) { + if ($child instanceof Newline) { + $newTerm = new DescriptionTerm(); + $term->insertAfter($newTerm); + $term = $newTerm; + continue; + } + + $term->appendChild($child); + } + } + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Node/Description.php b/vendor/league/commonmark/src/Extension/DescriptionList/Node/Description.php new file mode 100644 index 0000000..ccef962 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Node/Description.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Node; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\TightBlockInterface; + +class Description extends AbstractBlock implements TightBlockInterface +{ + private bool $tight; + + public function __construct(bool $tight = false) + { + parent::__construct(); + + $this->tight = $tight; + } + + public function isTight(): bool + { + return $this->tight; + } + + public function setTight(bool $tight): void + { + $this->tight = $tight; + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionList.php b/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionList.php new file mode 100644 index 0000000..90d026c --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionList.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +class DescriptionList extends AbstractBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionTerm.php b/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionTerm.php new file mode 100644 index 0000000..b13ec75 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Node/DescriptionTerm.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +class DescriptionTerm extends AbstractBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionContinueParser.php b/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionContinueParser.php new file mode 100644 index 0000000..0cdd9d5 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionContinueParser.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\DescriptionList\Parser; + +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class DescriptionContinueParser extends AbstractBlockContinueParser +{ + private Description $block; + + private int $indentation; + + public function __construct(bool $tight, int $indentation) + { + $this->block = new Description($tight); + $this->indentation = $indentation; + } + + public function getBlock(): Description + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + if ($this->block->firstChild() === null) { + // Blank line after empty item + return BlockContinue::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + + return BlockContinue::at($cursor); + } + + if ($cursor->getIndent() >= $this->indentation) { + $cursor->advanceBy($this->indentation, true); + + return BlockContinue::at($cursor); + } + + return BlockContinue::none(); + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionListContinueParser.php b/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionListContinueParser.php new file mode 100644 index 0000000..1d446a7 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionListContinueParser.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\DescriptionList\Parser; + +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +final class DescriptionListContinueParser extends AbstractBlockContinueParser +{ + private DescriptionList $block; + + public function __construct() + { + $this->block = new DescriptionList(); + } + + public function getBlock(): DescriptionList + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::at($cursor); + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return $childBlock instanceof DescriptionTerm || $childBlock instanceof Description; + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionStartParser.php b/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionStartParser.php new file mode 100644 index 0000000..04762e7 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionStartParser.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\DescriptionList\Parser; + +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class DescriptionStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented()) { + return BlockStart::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->matchInPlace('/\G:[ \t]+/') === null) { + return BlockStart::none(); + } + + $terms = $parserState->getParagraphContent(); + + $activeBlock = $parserState->getActiveBlockParser()->getBlock(); + + if ($terms !== null && $terms !== '') { + // New description; tight; term(s) sitting in pending block that we will replace + return BlockStart::of(...[new DescriptionListContinueParser()], ...self::splitTerms($terms), ...[new DescriptionContinueParser(true, $cursor->getPosition())]) + ->at($cursor) + ->replaceActiveBlockParser(); + } + + if ($activeBlock instanceof Paragraph && $activeBlock->parent() instanceof Description) { + // Additional description in the same list as the parent description + return BlockStart::of(new DescriptionContinueParser(true, $cursor->getPosition()))->at($cursor); + } + + if ($activeBlock->lastChild() instanceof Paragraph) { + // New description; loose; term(s) sitting in previous closed paragraph block + return BlockStart::of(new DescriptionContinueParser(false, $cursor->getPosition()))->at($cursor); + } + + // No preceding terms + return BlockStart::none(); + } + + /** + * @return array + */ + private static function splitTerms(string $terms): array + { + $ret = []; + foreach (\explode("\n", $terms) as $term) { + $ret[] = new DescriptionTermContinueParser($term); + } + + return $ret; + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionTermContinueParser.php b/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionTermContinueParser.php new file mode 100644 index 0000000..7b43882 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Parser/DescriptionTermContinueParser.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Parser; + +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockContinueParserWithInlinesInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\InlineParserEngineInterface; + +final class DescriptionTermContinueParser extends AbstractBlockContinueParser implements BlockContinueParserWithInlinesInterface +{ + private DescriptionTerm $block; + + private string $term; + + public function __construct(string $term) + { + $this->block = new DescriptionTerm(); + $this->term = $term; + } + + public function getBlock(): DescriptionTerm + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::finished(); + } + + public function parseInlines(InlineParserEngineInterface $inlineParser): void + { + if ($this->term !== '') { + $inlineParser->parse($this->term, $this->block); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionListRenderer.php b/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionListRenderer.php new file mode 100644 index 0000000..7723038 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionListRenderer.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Renderer; + +use League\CommonMark\Extension\DescriptionList\Node\DescriptionList; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; + +final class DescriptionListRenderer implements NodeRendererInterface +{ + /** + * @param DescriptionList $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): HtmlElement + { + DescriptionList::assertInstanceOf($node); + + $separator = $childRenderer->getBlockSeparator(); + + return new HtmlElement('dl', [], $separator . $childRenderer->renderNodes($node->children()) . $separator); + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionRenderer.php b/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionRenderer.php new file mode 100644 index 0000000..5fcffd6 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionRenderer.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Renderer; + +use League\CommonMark\Extension\DescriptionList\Node\Description; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; + +final class DescriptionRenderer implements NodeRendererInterface +{ + /** + * @param Description $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Description::assertInstanceOf($node); + + return new HtmlElement('dd', [], $childRenderer->renderNodes($node->children())); + } +} diff --git a/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionTermRenderer.php b/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionTermRenderer.php new file mode 100644 index 0000000..ce8a1c4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DescriptionList/Renderer/DescriptionTermRenderer.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DescriptionList\Renderer; + +use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; + +final class DescriptionTermRenderer implements NodeRendererInterface +{ + /** + * @param DescriptionTerm $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + DescriptionTerm::assertInstanceOf($node); + + return new HtmlElement('dt', [], $childRenderer->renderNodes($node->children())); + } +} diff --git a/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlExtension.php b/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlExtension.php new file mode 100644 index 0000000..0ece0c2 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlExtension.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DisallowedRawHtml; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; +use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline; +use League\CommonMark\Extension\CommonMark\Renderer\Block\HtmlBlockRenderer; +use League\CommonMark\Extension\CommonMark\Renderer\Inline\HtmlInlineRenderer; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class DisallowedRawHtmlExtension implements ConfigurableExtensionInterface +{ + private const DEFAULT_DISALLOWED_TAGS = [ + 'title', + 'textarea', + 'style', + 'xmp', + 'iframe', + 'noembed', + 'noframes', + 'script', + 'plaintext', + ]; + + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('disallowed_raw_html', Expect::structure([ + 'disallowed_tags' => Expect::listOf('string')->default(self::DEFAULT_DISALLOWED_TAGS)->mergeDefaults(false), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addRenderer(HtmlBlock::class, new DisallowedRawHtmlRenderer(new HtmlBlockRenderer()), 50); + $environment->addRenderer(HtmlInline::class, new DisallowedRawHtmlRenderer(new HtmlInlineRenderer()), 50); + } +} diff --git a/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php b/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php new file mode 100644 index 0000000..2b852e9 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\DisallowedRawHtml; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class DisallowedRawHtmlRenderer implements NodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly */ + private NodeRendererInterface $innerRenderer; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function __construct(NodeRendererInterface $innerRenderer) + { + $this->innerRenderer = $innerRenderer; + } + + public function render(Node $node, ChildNodeRendererInterface $childRenderer): ?string + { + $rendered = (string) $this->innerRenderer->render($node, $childRenderer); + + if ($rendered === '') { + return ''; + } + + $tags = (array) $this->config->get('disallowed_raw_html/disallowed_tags'); + if (\count($tags) === 0) { + return $rendered; + } + + // 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/> <title /> <title + return \preg_replace($regex, '<$1', $rendered); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + + if ($this->innerRenderer instanceof ConfigurationAwareInterface) { + $this->innerRenderer->setConfiguration($configuration); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/Embed/Bridge/OscaroteroEmbedAdapter.php b/vendor/league/commonmark/src/Extension/Embed/Bridge/OscaroteroEmbedAdapter.php new file mode 100644 index 0000000..06b8190 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/Bridge/OscaroteroEmbedAdapter.php @@ -0,0 +1,50 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed\Bridge; + +use Embed\Embed as EmbedLib; +use League\CommonMark\Exception\MissingDependencyException; +use League\CommonMark\Extension\Embed\Embed; +use League\CommonMark\Extension\Embed\EmbedAdapterInterface; + +final class OscaroteroEmbedAdapter implements EmbedAdapterInterface +{ + private EmbedLib $embedLib; + + public function __construct(?EmbedLib $embed = null) + { + if ($embed === null) { + if (! \class_exists(EmbedLib::class)) { + throw new MissingDependencyException('The embed/embed package is not installed. Please install it with Composer to use this adapter.'); + } + + $embed = new EmbedLib(); + } + + $this->embedLib = $embed; + } + + /** + * {@inheritDoc} + */ + public function updateEmbeds(array $embeds): void + { + $extractors = $this->embedLib->getMulti(...\array_map(static fn (Embed $embed) => $embed->getUrl(), $embeds)); + foreach ($extractors as $i => $extractor) { + if ($extractor->code !== null) { + $embeds[$i]->setEmbedCode($extractor->code->html); + } + } + } +} diff --git a/vendor/league/commonmark/src/Extension/Embed/DomainFilteringAdapter.php b/vendor/league/commonmark/src/Extension/Embed/DomainFilteringAdapter.php new file mode 100644 index 0000000..b00b028 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/DomainFilteringAdapter.php @@ -0,0 +1,62 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +class DomainFilteringAdapter implements EmbedAdapterInterface +{ + private EmbedAdapterInterface $decorated; + + /** @var string[] */ + private array $allowedDomains; + + /** + * @param string[] $allowedDomains + */ + public function __construct(EmbedAdapterInterface $decorated, array $allowedDomains) + { + $this->decorated = $decorated; + $this->allowedDomains = \array_map('strtolower', $allowedDomains); + } + + /** + * {@inheritDoc} + */ + public function updateEmbeds(array $embeds): void + { + $this->decorated->updateEmbeds(\array_values(\array_filter($embeds, [$this, 'isAllowed']))); + } + + private function isAllowed(Embed $embed): bool + { + $url = $embed->getUrl(); + $scheme = \parse_url($url, \PHP_URL_SCHEME); + if ($scheme === null || $scheme === false) { + // Bare domain (no scheme) - assume https:// so parse_url can extract the host + $url = 'https://' . $url; + } elseif (\strtolower($scheme) !== 'http' && \strtolower($scheme) !== 'https') { + return false; + } + + $host = \parse_url($url, \PHP_URL_HOST); + $host = \strtolower(\rtrim((string) $host, '.')); + + foreach ($this->allowedDomains as $domain) { + if ($host === $domain || \str_ends_with($host, '.' . $domain)) { + return true; + } + } + + return false; + } +} diff --git a/vendor/league/commonmark/src/Extension/Embed/Embed.php b/vendor/league/commonmark/src/Extension/Embed/Embed.php new file mode 100644 index 0000000..94c1980 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/Embed.php @@ -0,0 +1,50 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class Embed extends AbstractBlock +{ + private string $url; + private ?string $embedCode; + + public function __construct(string $url, ?string $embedCode = null) + { + parent::__construct(); + + $this->url = $url; + $this->embedCode = $embedCode; + } + + public function getUrl(): string + { + return $this->url; + } + + public function setUrl(string $url): void + { + $this->url = $url; + } + + public function getEmbedCode(): ?string + { + return $this->embedCode; + } + + public function setEmbedCode(?string $embedCode): void + { + $this->embedCode = $embedCode; + } +} diff --git a/vendor/league/commonmark/src/Extension/Embed/EmbedAdapterInterface.php b/vendor/league/commonmark/src/Extension/Embed/EmbedAdapterInterface.php new file mode 100644 index 0000000..9880a43 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/EmbedAdapterInterface.php @@ -0,0 +1,25 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +/** + * Interface for a service which updates the embed code(s) for the given array of embeds + */ +interface EmbedAdapterInterface +{ + /** + * @param Embed[] $embeds + */ + public function updateEmbeds(array $embeds): void; +} diff --git a/vendor/league/commonmark/src/Extension/Embed/EmbedExtension.php b/vendor/league/commonmark/src/Extension/Embed/EmbedExtension.php new file mode 100644 index 0000000..babf048 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/EmbedExtension.php @@ -0,0 +1,48 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class EmbedExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('embed', Expect::structure([ + 'adapter' => Expect::type(EmbedAdapterInterface::class), + 'allowed_domains' => Expect::arrayOf('string')->default([]), + 'fallback' => Expect::anyOf('link', 'remove')->default('link'), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $adapter = $environment->getConfiguration()->get('embed.adapter'); + \assert($adapter instanceof EmbedAdapterInterface); + + $allowedDomains = $environment->getConfiguration()->get('embed.allowed_domains'); + if ($allowedDomains !== []) { + $adapter = new DomainFilteringAdapter($adapter, $allowedDomains); + } + + $environment + ->addBlockStartParser(new EmbedStartParser(), 300) + ->addEventListener(DocumentParsedEvent::class, new EmbedProcessor($adapter, $environment->getConfiguration()->get('embed.fallback')), 1010) + ->addRenderer(Embed::class, new EmbedRenderer()); + } +} diff --git a/vendor/league/commonmark/src/Extension/Embed/EmbedParser.php b/vendor/league/commonmark/src/Extension/Embed/EmbedParser.php new file mode 100644 index 0000000..e957caf --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/EmbedParser.php @@ -0,0 +1,62 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; + +class EmbedParser implements BlockContinueParserInterface +{ + private Embed $embed; + + public function __construct(string $url) + { + $this->embed = new Embed($url); + } + + public function getBlock(): AbstractBlock + { + return $this->embed; + } + + public function isContainer(): bool + { + return false; + } + + public function canHaveLazyContinuationLines(): bool + { + return false; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return false; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::none(); + } + + public function addLine(string $line): void + { + } + + public function closeBlock(): void + { + } +} diff --git a/vendor/league/commonmark/src/Extension/Embed/EmbedProcessor.php b/vendor/league/commonmark/src/Extension/Embed/EmbedProcessor.php new file mode 100644 index 0000000..035b583 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/EmbedProcessor.php @@ -0,0 +1,72 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Node\NodeIterator; + +final class EmbedProcessor +{ + public const FALLBACK_REMOVE = 'remove'; + public const FALLBACK_LINK = 'link'; + + private EmbedAdapterInterface $adapter; + private string $fallback; + + public function __construct(EmbedAdapterInterface $adapter, string $fallback = self::FALLBACK_REMOVE) + { + $this->adapter = $adapter; + $this->fallback = $fallback; + } + + public function __invoke(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + $embeds = []; + foreach (new NodeIterator($document) as $node) { + if (! ($node instanceof Embed)) { + continue; + } + + if ($node->parent() !== $document) { + $replacement = new Paragraph(); + $replacement->appendChild(new Text($node->getUrl())); + $node->replaceWith($replacement); + } else { + $embeds[] = $node; + } + } + + if ($embeds) { + $this->adapter->updateEmbeds($embeds); + } + + foreach ($embeds as $embed) { + if ($embed->getEmbedCode() !== null) { + continue; + } + + if ($this->fallback === self::FALLBACK_REMOVE) { + $embed->detach(); + } elseif ($this->fallback === self::FALLBACK_LINK) { + $paragraph = new Paragraph(); + $paragraph->appendChild(new Link($embed->getUrl(), $embed->getUrl())); + $embed->replaceWith($paragraph); + } + } + } +} diff --git a/vendor/league/commonmark/src/Extension/Embed/EmbedRenderer.php b/vendor/league/commonmark/src/Extension/Embed/EmbedRenderer.php new file mode 100644 index 0000000..91655d8 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/EmbedRenderer.php @@ -0,0 +1,35 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; + +class EmbedRenderer implements NodeRendererInterface +{ + /** + * @param Embed $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + Embed::assertInstanceOf($node); + + return $node->getEmbedCode() ?? ''; + } +} diff --git a/vendor/league/commonmark/src/Extension/Embed/EmbedStartParser.php b/vendor/league/commonmark/src/Extension/Embed/EmbedStartParser.php new file mode 100644 index 0000000..5ff3808 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Embed/EmbedStartParser.php @@ -0,0 +1,53 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Embed; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\LinkParserHelper; + +class EmbedStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || $parserState->getParagraphContent() !== null || ! ($parserState->getActiveBlockParser()->isContainer())) { + return BlockStart::none(); + } + + // 0-3 leading spaces are okay + $cursor->advanceToNextNonSpaceOrTab(); + + // The line must begin with "https://" + if (! str_starts_with($cursor->getRemainder(), 'https://')) { + return BlockStart::none(); + } + + // A valid link must be found next + if (($dest = LinkParserHelper::parseLinkDestination($cursor)) === null) { + return BlockStart::none(); + } + + // Skip any trailing whitespace + $cursor->advanceToNextNonSpaceOrTab(); + + // We must be at the end of the line; otherwise, this link was not by itself + if (! $cursor->isAtEnd()) { + return BlockStart::none(); + } + + return BlockStart::of(new EmbedParser($dest))->at($cursor); + } +} diff --git a/vendor/league/commonmark/src/Extension/ExtensionInterface.php b/vendor/league/commonmark/src/Extension/ExtensionInterface.php new file mode 100644 index 0000000..01a9f2e --- /dev/null +++ b/vendor/league/commonmark/src/Extension/ExtensionInterface.php @@ -0,0 +1,24 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; + +interface ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void; +} diff --git a/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkExtension.php b/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkExtension.php new file mode 100644 index 0000000..df0079c --- /dev/null +++ b/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkExtension.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\ExternalLink; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class ExternalLinkExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $applyOptions = [ + ExternalLinkProcessor::APPLY_NONE, + ExternalLinkProcessor::APPLY_ALL, + ExternalLinkProcessor::APPLY_INTERNAL, + ExternalLinkProcessor::APPLY_EXTERNAL, + ]; + + $builder->addSchema('external_link', Expect::structure([ + 'internal_hosts' => Expect::type('string|string[]'), + 'open_in_new_window' => Expect::bool(false), + 'html_class' => Expect::string()->default(''), + 'nofollow' => Expect::anyOf(...$applyOptions)->default(ExternalLinkProcessor::APPLY_NONE), + 'noopener' => Expect::anyOf(...$applyOptions)->default(ExternalLinkProcessor::APPLY_EXTERNAL), + 'noreferrer' => Expect::anyOf(...$applyOptions)->default(ExternalLinkProcessor::APPLY_EXTERNAL), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentParsedEvent::class, new ExternalLinkProcessor($environment->getConfiguration()), -50); + } +} diff --git a/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php b/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php new file mode 100644 index 0000000..6d98ad9 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php @@ -0,0 +1,141 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\ExternalLink; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\Config\ConfigurationInterface; + +final class ExternalLinkProcessor +{ + public const APPLY_NONE = ''; + public const APPLY_ALL = 'all'; + public const APPLY_EXTERNAL = 'external'; + public const APPLY_INTERNAL = 'internal'; + + /** @psalm-readonly */ + private ConfigurationInterface $config; + + public function __construct(ConfigurationInterface $config) + { + $this->config = $config; + } + + public function __invoke(DocumentParsedEvent $e): void + { + $internalHosts = $this->config->get('external_link/internal_hosts'); + $openInNewWindow = $this->config->get('external_link/open_in_new_window'); + $classes = $this->config->get('external_link/html_class'); + + foreach ($e->getDocument()->iterator() as $link) { + if (! ($link instanceof Link)) { + continue; + } + + $host = self::getHost($link->getUrl()); + if ($host === null) { + // Relative links and non-network schemes like mailto: have no host to compare + continue; + } + + if (self::hostMatches($host, $internalHosts)) { + $link->data->set('external', false); + $this->applyRelAttribute($link, false); + continue; + } + + // Host does not match our list + $this->markLinkAsExternal($link, $openInNewWindow, $classes); + } + } + + private function markLinkAsExternal(Link $link, bool $openInNewWindow, string $classes): void + { + $link->data->set('external', true); + $this->applyRelAttribute($link, true); + + if ($openInNewWindow) { + $link->data->set('attributes/target', '_blank'); + } + + if ($classes !== '') { + $link->data->append('attributes/class', $classes); + } + } + + private function applyRelAttribute(Link $link, bool $isExternal): void + { + $options = [ + 'nofollow' => $this->config->get('external_link/nofollow'), + 'noopener' => $this->config->get('external_link/noopener'), + 'noreferrer' => $this->config->get('external_link/noreferrer'), + ]; + + foreach ($options as $type => $option) { + switch (true) { + case $option === self::APPLY_ALL: + case $isExternal && $option === self::APPLY_EXTERNAL: + case ! $isExternal && $option === self::APPLY_INTERNAL: + $link->data->append('attributes/rel', $type); + } + } + + // No rel attributes? Mark the attribute as 'false' so LinkRenderer doesn't add defaults + if (! $link->data->has('attributes/rel')) { + $link->data->set('attributes/rel', false); + } + } + + /** + * 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! + * + * @param non-empty-string|list<non-empty-string> $compareTo + */ + public static function hostMatches(string $host, $compareTo): bool + { + foreach ((array) $compareTo as $c) { + if (\strpos($c, '/') === 0) { + if (\preg_match($c, $host)) { + return true; + } + } elseif ($c === $host) { + return true; + } + } + + return false; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Event/AnonymousFootnotesListener.php b/vendor/league/commonmark/src/Extension/Footnote/Event/AnonymousFootnotesListener.php new file mode 100644 index 0000000..401613a --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Event/AnonymousFootnotesListener.php @@ -0,0 +1,62 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Reference\Reference; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class AnonymousFootnotesListener implements ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + foreach ($document->iterator() as $node) { + if (! $node instanceof FootnoteRef || ($text = $node->getContent()) === null) { + continue; + } + + // Anonymous footnote needs to create a footnote from its content + $existingReference = $node->getReference(); + $newReference = new Reference( + $existingReference->getLabel(), + '#' . $this->config->get('footnote/ref_id_prefix') . $existingReference->getLabel(), + $existingReference->getTitle() + ); + + $paragraph = new Paragraph(); + $paragraph->appendChild(new Text($text)); + $paragraph->appendChild(new FootnoteBackref($newReference)); + + $footnote = new Footnote($newReference); + $footnote->appendChild($paragraph); + + $document->appendChild($footnote); + } + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Event/FixOrphanedFootnotesAndRefsListener.php b/vendor/league/commonmark/src/Extension/Footnote/Event/FixOrphanedFootnotesAndRefsListener.php new file mode 100644 index 0000000..a0295b5 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Event/FixOrphanedFootnotesAndRefsListener.php @@ -0,0 +1,68 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Inline\Text; + +final class FixOrphanedFootnotesAndRefsListener +{ + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + $map = $this->buildMapOfKnownFootnotesAndRefs($document); + + foreach ($map['_flat'] as $node) { + if ($node instanceof FootnoteRef && ! isset($map[Footnote::class][$node->getReference()->getLabel()])) { + // Found an orphaned FootnoteRef without a corresponding Footnote + // Restore the original footnote ref text + $node->replaceWith(new Text(\sprintf('[^%s]', $node->getReference()->getLabel()))); + } + + // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($node instanceof Footnote && ! isset($map[FootnoteRef::class][$node->getReference()->getLabel()])) { + // Found an orphaned Footnote without a corresponding FootnoteRef + // Remove the footnote + $node->detach(); + } + } + } + + /** @phpstan-ignore-next-line */ + private function buildMapOfKnownFootnotesAndRefs(Document $document): array // @phpcs:ignore + { + $map = [ + Footnote::class => [], + FootnoteRef::class => [], + '_flat' => [], + ]; + + foreach ($document->iterator() as $node) { + if ($node instanceof Footnote) { + $map[Footnote::class][$node->getReference()->getLabel()] = true; + + $map['_flat'][] = $node; + } elseif ($node instanceof FootnoteRef) { + $map[FootnoteRef::class][$node->getReference()->getLabel()] = true; + + $map['_flat'][] = $node; + } + } + + return $map; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Event/GatherFootnotesListener.php b/vendor/league/commonmark/src/Extension/Footnote/Event/GatherFootnotesListener.php new file mode 100644 index 0000000..5a205ea --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Event/GatherFootnotesListener.php @@ -0,0 +1,138 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; +use League\CommonMark\Extension\Footnote\Node\FootnoteContainer; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\NodeIterator; +use League\CommonMark\Reference\Reference; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class GatherFootnotesListener implements ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + $footnotes = []; + $definitions = []; + $discarded = []; + + /** @var array<string, Reference[]> $backrefs */ + $backrefs = $document->data->get('footnote/backrefs', []); + + /* + * A label may be defined more than once. Only the first definition is used, matching how + * duplicate link reference definitions are resolved; the rest are discarded below. + * + * Keeping just one definition per label is also what bounds the work done here: every + * definition sharing a label claims that label's entire backref list, so N duplicate + * definitions of a label referenced M times would otherwise produce M * N backrefs - a + * denial of service vector, since both are attacker-controlled. + * + * Nodes are collected rather than detached here because detaching mid-iteration would + * truncate the walk. + */ + foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof Footnote) { + continue; + } + + $label = $node->getReference()->getLabel(); + if (isset($definitions[$label])) { + $discarded[] = $node; + + continue; + } + + $definitions[$label] = $node; + } + + foreach ($definitions as $node) { + // Look for existing reference with footnote label + $ref = $document->getReferenceMap()->get($node->getReference()->getLabel()); + if ($ref !== null) { + // Use numeric title to get footnotes order + $footnotes[(int) $ref->getTitle()] = $node; + } else { + // Footnote call is missing, append footnote at the end + $footnotes[\PHP_INT_MAX] = $node; + } + + $key = '#' . $this->config->get('footnote/footnote_id_prefix') . $node->getReference()->getDestination(); + if (isset($backrefs[$key])) { + $this->createBackrefs($node, $backrefs[$key]); + } + } + + foreach ($discarded as $duplicate) { + $duplicate->detach(); + } + + // Only add a footnote container if there are any + if (\count($footnotes) === 0) { + return; + } + + $container = $this->getFootnotesContainer($document); + + \ksort($footnotes); + foreach ($footnotes as $footnote) { + $container->appendChild($footnote); + } + } + + private function getFootnotesContainer(Document $document): FootnoteContainer + { + $footnoteContainer = new FootnoteContainer(); + $document->appendChild($footnoteContainer); + + return $footnoteContainer; + } + + /** + * Look for all footnote refs pointing to this footnote and create each footnote backrefs. + * + * @param Footnote $node The target footnote + * @param Reference[] $backrefs References to create backrefs for + */ + private function createBackrefs(Footnote $node, array $backrefs): void + { + // Backrefs should be added to the child paragraph + $target = $node->lastChild(); + if ($target === null) { + // This should never happen, but you never know + $target = $node; + } + + foreach ($backrefs as $backref) { + $target->appendChild(new FootnoteBackref(new Reference( + $backref->getLabel(), + '#' . $this->config->get('footnote/ref_id_prefix') . $backref->getLabel(), + $backref->getTitle() + ))); + } + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Event/NumberFootnotesListener.php b/vendor/league/commonmark/src/Extension/Footnote/Event/NumberFootnotesListener.php new file mode 100644 index 0000000..7917f3c --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Event/NumberFootnotesListener.php @@ -0,0 +1,83 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Event; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Reference\Reference; + +final class NumberFootnotesListener +{ + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + $nextCounter = 1; + $usedLabels = []; + $usedCounters = []; + $backrefs = []; + + foreach ($document->iterator() as $node) { + if (! $node instanceof FootnoteRef) { + continue; + } + + $existingReference = $node->getReference(); + $label = $existingReference->getLabel(); + $counter = $nextCounter; + $canIncrementCounter = true; + + if (\array_key_exists($label, $usedLabels)) { + /* + * Reference is used again, we need to point + * to the same footnote. But with a different ID + */ + $counter = $usedCounters[$label]; + $label .= '__' . ++$usedLabels[$label]; + $canIncrementCounter = false; + } + + // rewrite reference title to use a numeric link + $newReference = new Reference( + $label, + $existingReference->getDestination(), + (string) $counter + ); + + // Override reference with numeric link + $node->setReference($newReference); + $document->getReferenceMap()->add($newReference); + + /* + * Store created references for creating FootnoteBackrefs. + * + * These are collected into a plain array keyed by the exact destination rather than + * written straight into $document->data: destinations are built from user-supplied + * labels, and Data treats both "." and "/" as key path delimiters. Using them as + * paths would let distinct labels collapse onto a shared entry, or nest one label's + * entry inside another's. + */ + $backrefs[$existingReference->getDestination()][] = $newReference; + + $usedLabels[$label] = 1; + $usedCounters[$label] = $nextCounter; + + if ($canIncrementCounter) { + $nextCounter++; + } + } + + $document->data->set('footnote/backrefs', $backrefs); + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/FootnoteExtension.php b/vendor/league/commonmark/src/Extension/Footnote/FootnoteExtension.php new file mode 100644 index 0000000..d3daf36 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/FootnoteExtension.php @@ -0,0 +1,74 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Extension\Footnote\Event\AnonymousFootnotesListener; +use League\CommonMark\Extension\Footnote\Event\FixOrphanedFootnotesAndRefsListener; +use League\CommonMark\Extension\Footnote\Event\GatherFootnotesListener; +use League\CommonMark\Extension\Footnote\Event\NumberFootnotesListener; +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; +use League\CommonMark\Extension\Footnote\Node\FootnoteContainer; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Extension\Footnote\Parser\AnonymousFootnoteRefParser; +use League\CommonMark\Extension\Footnote\Parser\FootnoteRefParser; +use League\CommonMark\Extension\Footnote\Parser\FootnoteStartParser; +use League\CommonMark\Extension\Footnote\Renderer\FootnoteBackrefRenderer; +use League\CommonMark\Extension\Footnote\Renderer\FootnoteContainerRenderer; +use League\CommonMark\Extension\Footnote\Renderer\FootnoteRefRenderer; +use League\CommonMark\Extension\Footnote\Renderer\FootnoteRenderer; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class FootnoteExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('footnote', Expect::structure([ + 'backref_class' => Expect::string('footnote-backref'), + 'backref_symbol' => Expect::string('↩'), + 'container_add_hr' => Expect::bool(true), + 'container_class' => Expect::string('footnotes'), + 'enable_inline_footnotes' => Expect::bool(true), + 'ref_class' => Expect::string('footnote-ref'), + 'ref_id_prefix' => Expect::string('fnref:'), + 'footnote_class' => Expect::string('footnote'), + 'footnote_id_prefix' => Expect::string('fn:'), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + if ($environment->getConfiguration()->get('footnote/enable_inline_footnotes')) { + $environment->addInlineParser(new AnonymousFootnoteRefParser(), 35); + $environment->addEventListener(DocumentParsedEvent::class, [new AnonymousFootnotesListener(), 'onDocumentParsed'], 40); + } + + $environment->addBlockStartParser(new FootnoteStartParser(), 51); + $environment->addInlineParser(new FootnoteRefParser(), 51); + + $environment->addRenderer(FootnoteContainer::class, new FootnoteContainerRenderer()); + $environment->addRenderer(Footnote::class, new FootnoteRenderer()); + $environment->addRenderer(FootnoteRef::class, new FootnoteRefRenderer()); + $environment->addRenderer(FootnoteBackref::class, new FootnoteBackrefRenderer()); + + $environment->addEventListener(DocumentParsedEvent::class, [new FixOrphanedFootnotesAndRefsListener(), 'onDocumentParsed'], 30); + $environment->addEventListener(DocumentParsedEvent::class, [new NumberFootnotesListener(), 'onDocumentParsed'], 20); + $environment->addEventListener(DocumentParsedEvent::class, [new GatherFootnotesListener(), 'onDocumentParsed'], 10); + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Node/Footnote.php b/vendor/league/commonmark/src/Extension/Footnote/Node/Footnote.php new file mode 100644 index 0000000..c3f77ca --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Node/Footnote.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Node; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceableInterface; + +final class Footnote extends AbstractBlock implements ReferenceableInterface +{ + /** @psalm-readonly */ + private ReferenceInterface $reference; + + public function __construct(ReferenceInterface $reference) + { + parent::__construct(); + + $this->reference = $reference; + } + + public function getReference(): ReferenceInterface + { + return $this->reference; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteBackref.php b/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteBackref.php new file mode 100644 index 0000000..f56daa5 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteBackref.php @@ -0,0 +1,40 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Node; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceableInterface; + +/** + * Link from the footnote on the bottom of the document back to the reference + */ +final class FootnoteBackref extends AbstractInline implements ReferenceableInterface +{ + /** @psalm-readonly */ + private ReferenceInterface $reference; + + public function __construct(ReferenceInterface $reference) + { + parent::__construct(); + + $this->reference = $reference; + } + + public function getReference(): ReferenceInterface + { + return $this->reference; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteContainer.php b/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteContainer.php new file mode 100644 index 0000000..af4ee35 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteContainer.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class FootnoteContainer extends AbstractBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteRef.php b/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteRef.php new file mode 100644 index 0000000..429a1dc --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Node/FootnoteRef.php @@ -0,0 +1,57 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Node; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceableInterface; + +final class FootnoteRef extends AbstractInline implements ReferenceableInterface +{ + private ReferenceInterface $reference; + + /** @psalm-readonly */ + private ?string $content = null; + + /** + * @param array<mixed> $data + */ + public function __construct(ReferenceInterface $reference, ?string $content = null, array $data = []) + { + parent::__construct(); + + $this->reference = $reference; + $this->content = $content; + + if (\count($data) > 0) { + $this->data->import($data); + } + } + + public function getReference(): ReferenceInterface + { + return $this->reference; + } + + public function setReference(ReferenceInterface $reference): void + { + $this->reference = $reference; + } + + public function getContent(): ?string + { + return $this->content; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Parser/AnonymousFootnoteRefParser.php b/vendor/league/commonmark/src/Extension/Footnote/Parser/AnonymousFootnoteRefParser.php new file mode 100644 index 0000000..4ed93da --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Parser/AnonymousFootnoteRefParser.php @@ -0,0 +1,66 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Parser; + +use League\CommonMark\Environment\EnvironmentAwareInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Normalizer\TextNormalizerInterface; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Reference\Reference; +use League\Config\ConfigurationInterface; + +final class AnonymousFootnoteRefParser implements InlineParserInterface, EnvironmentAwareInterface +{ + private ConfigurationInterface $config; + + /** @psalm-readonly-allow-private-mutation */ + private TextNormalizerInterface $slugNormalizer; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('\^\[([^\]]+)\]'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + + [$label] = $inlineContext->getSubMatches(); + $reference = $this->createReference($label); + $inlineContext->getContainer()->appendChild(new FootnoteRef($reference, $label)); + + return true; + } + + private function createReference(string $label): Reference + { + $refLabel = $this->slugNormalizer->normalize($label, ['length' => 20]); + + return new Reference( + $refLabel, + '#' . $this->config->get('footnote/footnote_id_prefix') . $refLabel, + $label + ); + } + + public function setEnvironment(EnvironmentInterface $environment): void + { + $this->config = $environment->getConfiguration(); + $this->slugNormalizer = $environment->getSlugNormalizer(); + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteParser.php b/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteParser.php new file mode 100644 index 0000000..2192546 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteParser.php @@ -0,0 +1,68 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Parser; + +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Reference\ReferenceInterface; + +final class FootnoteParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private Footnote $block; + + /** @psalm-readonly-allow-private-mutation */ + private ?int $indentation = null; + + public function __construct(ReferenceInterface $reference) + { + $this->block = new Footnote($reference); + } + + public function getBlock(): Footnote + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + return BlockContinue::at($cursor); + } + + if ($cursor->isIndented()) { + $this->indentation ??= $cursor->getIndent(); + $cursor->advanceBy($this->indentation, true); + + return BlockContinue::at($cursor); + } + + return BlockContinue::none(); + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteRefParser.php b/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteRefParser.php new file mode 100644 index 0000000..4032abd --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteRefParser.php @@ -0,0 +1,57 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Parser; + +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Reference\Reference; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteRefParser implements InlineParserInterface, ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('\[\^([^\s\]]+)\]'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + + [$label] = $inlineContext->getSubMatches(); + $inlineContext->getContainer()->appendChild(new FootnoteRef($this->createReference($label))); + + return true; + } + + private function createReference(string $label): Reference + { + return new Reference( + $label, + '#' . $this->config->get('footnote/footnote_id_prefix') . $label, + $label + ); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteStartParser.php b/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteStartParser.php new file mode 100644 index 0000000..734e678 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Parser/FootnoteStartParser.php @@ -0,0 +1,56 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Parser; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Reference\Reference; +use League\CommonMark\Util\RegexHelper; + +final class FootnoteStartParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if ($cursor->isIndented() || $parserState->getLastMatchedBlockParser()->canHaveLazyContinuationLines()) { + return BlockStart::none(); + } + + $match = RegexHelper::matchFirst( + '/^\[\^([^\s^\]]+)\]\:(?:\s|$)/', + $cursor->getLine(), + $cursor->getNextNonSpacePosition() + ); + + if (! $match) { + return BlockStart::none(); + } + + $cursor->advanceToNextNonSpaceOrTab(); + $cursor->advanceBy(\strlen($match[0])); + $str = $cursor->getRemainder(); + \preg_replace('/^\[\^([^\s^\]]+)\]\:(?:\s|$)/', '', $str); + + if (\preg_match('/^\[\^([^\s^\]]+)\]\:(?:\s|$)/', $match[0], $matches) !== 1) { + return BlockStart::none(); + } + + $reference = new Reference($matches[1], $matches[1], $matches[1]); + $footnoteParser = new FootnoteParser($reference); + + return BlockStart::of($footnoteParser)->at($cursor); + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php new file mode 100644 index 0000000..8bd501b --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php @@ -0,0 +1,87 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Renderer; + +use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteBackrefRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + public const DEFAULT_SYMBOL = '↩'; + + private ConfigurationInterface $config; + + /** + * @param FootnoteBackref $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + FootnoteBackref::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + + $attrs->append('class', $this->config->get('footnote/backref_class')); + $attrs->set('rev', 'footnote'); + // 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'); + \assert(\is_string($symbol)); + + return ' ' . new HtmlElement('a', $attrs->export(), \htmlspecialchars($symbol), true); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'footnote_backref'; + } + + /** + * @param FootnoteBackref $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + FootnoteBackref::assertInstanceOf($node); + + return [ + 'reference' => $node->getReference()->getLabel(), + ]; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteContainerRenderer.php b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteContainerRenderer.php new file mode 100644 index 0000000..74d35ef --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteContainerRenderer.php @@ -0,0 +1,71 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Renderer; + +use League\CommonMark\Extension\Footnote\Node\FootnoteContainer; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteContainerRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + /** + * @param FootnoteContainer $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + FootnoteContainer::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + + $attrs->append('class', $this->config->get('footnote/container_class')); + $attrs->set('role', 'doc-endnotes'); + + $contents = new HtmlElement('ol', [], $childRenderer->renderNodes($node->children())); + if ($this->config->get('footnote/container_add_hr')) { + $contents = [new HtmlElement('hr', [], null, true), $contents]; + } + + return new HtmlElement('div', $attrs->export(), $contents); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'footnote_container'; + } + + /** + * @return array<string, scalar> + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php new file mode 100644 index 0000000..e5af10c --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php @@ -0,0 +1,93 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Renderer; + +use League\CommonMark\Extension\Footnote\Node\FootnoteRef; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteRefRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + /** + * @param FootnoteRef $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + FootnoteRef::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + $attrs->append('class', $this->config->get('footnote/ref_class')); + // 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'); + + return new HtmlElement( + 'sup', + [ + 'id' => $idPrefix . \mb_strtolower($node->getReference()->getLabel(), 'UTF-8'), + ], + new HtmlElement( + 'a', + $attrs->export(), + $node->getReference()->getTitle() + ), + true + ); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'footnote_ref'; + } + + /** + * @param FootnoteRef $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + FootnoteRef::assertInstanceOf($node); + + return [ + 'reference' => $node->getReference()->getLabel(), + ]; + } +} diff --git a/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRenderer.php b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRenderer.php new file mode 100644 index 0000000..cdd027e --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRenderer.php @@ -0,0 +1,80 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * (c) Rezo Zero / Ambroise Maupate + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\Footnote\Renderer; + +use League\CommonMark\Extension\Footnote\Node\Footnote; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class FootnoteRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + private ConfigurationInterface $config; + + /** + * @param Footnote $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Footnote::assertInstanceOf($node); + + $attrs = $node->data->getData('attributes'); + + $attrs->append('class', $this->config->get('footnote/footnote_class')); + $attrs->set('id', $this->config->get('footnote/footnote_id_prefix') . \mb_strtolower($node->getReference()->getLabel(), 'UTF-8')); + $attrs->set('role', 'doc-endnote'); + + return new HtmlElement( + 'li', + $attrs->export(), + $childRenderer->renderNodes($node->children()), + true + ); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + public function getXmlTagName(Node $node): string + { + return 'footnote'; + } + + /** + * @param Footnote $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + Footnote::assertInstanceOf($node); + + return [ + 'reference' => $node->getReference()->getLabel(), + ]; + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/Data/FrontMatterDataParserInterface.php b/vendor/league/commonmark/src/Extension/FrontMatter/Data/FrontMatterDataParserInterface.php new file mode 100644 index 0000000..6e9db40 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/Data/FrontMatterDataParserInterface.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter\Data; + +use League\CommonMark\Extension\FrontMatter\Exception\InvalidFrontMatterException; + +interface FrontMatterDataParserInterface +{ + /** + * @return mixed|null The parsed data (which may be null, if the input represents a null value) + * + * @throws InvalidFrontMatterException if parsing fails + */ + public function parse(string $frontMatter); +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/Data/LibYamlFrontMatterParser.php b/vendor/league/commonmark/src/Extension/FrontMatter/Data/LibYamlFrontMatterParser.php new file mode 100644 index 0000000..b7194f4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/Data/LibYamlFrontMatterParser.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter\Data; + +use League\CommonMark\Exception\MissingDependencyException; +use League\CommonMark\Extension\FrontMatter\Exception\InvalidFrontMatterException; + +final class LibYamlFrontMatterParser implements FrontMatterDataParserInterface +{ + public static function capable(): ?LibYamlFrontMatterParser + { + if (! \extension_loaded('yaml')) { + return null; + } + + return new LibYamlFrontMatterParser(); + } + + /** + * {@inheritDoc} + */ + public function parse(string $frontMatter) + { + if (! \extension_loaded('yaml')) { + throw new MissingDependencyException('Failed to parse yaml: "ext-yaml" extension is missing'); + } + + $result = @\yaml_parse($frontMatter); + + if ($result === false) { + throw new InvalidFrontMatterException('Failed to parse front matter'); + } + + return $result; + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/Data/SymfonyYamlFrontMatterParser.php b/vendor/league/commonmark/src/Extension/FrontMatter/Data/SymfonyYamlFrontMatterParser.php new file mode 100644 index 0000000..8d99d33 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/Data/SymfonyYamlFrontMatterParser.php @@ -0,0 +1,39 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter\Data; + +use League\CommonMark\Exception\MissingDependencyException; +use League\CommonMark\Extension\FrontMatter\Exception\InvalidFrontMatterException; +use Symfony\Component\Yaml\Exception\ParseException; +use Symfony\Component\Yaml\Yaml; + +final class SymfonyYamlFrontMatterParser implements FrontMatterDataParserInterface +{ + /** + * {@inheritDoc} + */ + public function parse(string $frontMatter) + { + if (! \class_exists(Yaml::class)) { + throw new MissingDependencyException('Failed to parse yaml: "symfony/yaml" library is missing'); + } + + try { + /** @psalm-suppress ReservedWord */ + return Yaml::parse($frontMatter); + } catch (ParseException $ex) { + throw InvalidFrontMatterException::wrap($ex); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/Exception/InvalidFrontMatterException.php b/vendor/league/commonmark/src/Extension/FrontMatter/Exception/InvalidFrontMatterException.php new file mode 100644 index 0000000..ffe0c28 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/Exception/InvalidFrontMatterException.php @@ -0,0 +1,24 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Exception; + +use League\CommonMark\Exception\CommonMarkException; + +class InvalidFrontMatterException extends \RuntimeException implements CommonMarkException +{ + public static function wrap(\Throwable $t): self + { + return new InvalidFrontMatterException('Failed to parse front matter: ' . $t->getMessage(), 0, $t); + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterExtension.php b/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterExtension.php new file mode 100644 index 0000000..019ecb4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterExtension.php @@ -0,0 +1,46 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentPreParsedEvent; +use League\CommonMark\Event\DocumentRenderedEvent; +use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Extension\FrontMatter\Data\FrontMatterDataParserInterface; +use League\CommonMark\Extension\FrontMatter\Data\LibYamlFrontMatterParser; +use League\CommonMark\Extension\FrontMatter\Data\SymfonyYamlFrontMatterParser; +use League\CommonMark\Extension\FrontMatter\Listener\FrontMatterPostRenderListener; +use League\CommonMark\Extension\FrontMatter\Listener\FrontMatterPreParser; + +final class FrontMatterExtension implements ExtensionInterface +{ + /** @psalm-readonly */ + private FrontMatterParserInterface $frontMatterParser; + + public function __construct(?FrontMatterDataParserInterface $dataParser = null) + { + $this->frontMatterParser = new FrontMatterParser($dataParser ?? LibYamlFrontMatterParser::capable() ?? new SymfonyYamlFrontMatterParser()); + } + + public function getFrontMatterParser(): FrontMatterParserInterface + { + return $this->frontMatterParser; + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentPreParsedEvent::class, new FrontMatterPreParser($this->frontMatterParser)); + $environment->addEventListener(DocumentRenderedEvent::class, new FrontMatterPostRenderListener(), -500); + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParser.php b/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParser.php new file mode 100644 index 0000000..12a0c9a --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParser.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\FrontMatter; + +use League\CommonMark\Extension\FrontMatter\Data\FrontMatterDataParserInterface; +use League\CommonMark\Extension\FrontMatter\Exception\InvalidFrontMatterException; +use League\CommonMark\Extension\FrontMatter\Input\MarkdownInputWithFrontMatter; +use League\CommonMark\Parser\Cursor; + +final class FrontMatterParser implements FrontMatterParserInterface +{ + /** @psalm-readonly */ + private FrontMatterDataParserInterface $frontMatterParser; + + private const REGEX_FRONT_MATTER = '/\G---\\R.*?\\R---\\R/s'; + + public function __construct(FrontMatterDataParserInterface $frontMatterParser) + { + $this->frontMatterParser = $frontMatterParser; + } + + /** + * @throws InvalidFrontMatterException if the front matter cannot be parsed + */ + public function parse(string $markdownContent): MarkdownInputWithFrontMatter + { + $cursor = new Cursor($markdownContent); + + // Locate the front matter + $frontMatter = $cursor->matchInPlace(self::REGEX_FRONT_MATTER); + if ($frontMatter === null) { + return new MarkdownInputWithFrontMatter($markdownContent); + } + + // Trim the last line (ending ---s and newline) + $frontMatter = \preg_replace('/---\R$/', '', $frontMatter); + if ($frontMatter === null) { + return new MarkdownInputWithFrontMatter($markdownContent); + } + + // Parse the resulting YAML data + $data = $this->frontMatterParser->parse($frontMatter); + + // Advance through any remaining newlines which separated the front matter from the Markdown text + $trailingNewlines = $cursor->matchInPlace('/\G\R+/'); + + // Calculate how many lines the Markdown is offset from the front matter by counting the number of newlines + // Don't forget to add 1 because we stripped one out when trimming the trailing delims + $lineOffset = \preg_match_all('/\R/', $frontMatter . $trailingNewlines) + 1; + + return new MarkdownInputWithFrontMatter($cursor->getRemainder(), $lineOffset, $data); + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParserInterface.php b/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParserInterface.php new file mode 100644 index 0000000..197a33b --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterParserInterface.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter; + +use League\CommonMark\Extension\FrontMatter\Input\MarkdownInputWithFrontMatter; + +interface FrontMatterParserInterface +{ + public function parse(string $markdownContent): MarkdownInputWithFrontMatter; +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterProviderInterface.php b/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterProviderInterface.php new file mode 100644 index 0000000..b5a7278 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/FrontMatterProviderInterface.php @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter; + +interface FrontMatterProviderInterface +{ + /** + * @return mixed|null + */ + public function getFrontMatter(); +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/Input/MarkdownInputWithFrontMatter.php b/vendor/league/commonmark/src/Extension/FrontMatter/Input/MarkdownInputWithFrontMatter.php new file mode 100644 index 0000000..86c982b --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/Input/MarkdownInputWithFrontMatter.php @@ -0,0 +1,43 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Input; + +use League\CommonMark\Extension\FrontMatter\FrontMatterProviderInterface; +use League\CommonMark\Input\MarkdownInput; + +final class MarkdownInputWithFrontMatter extends MarkdownInput implements FrontMatterProviderInterface +{ + /** @var mixed|null */ + private $frontMatter; + + /** + * @param string $content Markdown content without the raw front matter + * @param int $lineOffset Line offset (based on number of front matter lines removed) + * @param mixed|null $frontMatter Parsed front matter + */ + public function __construct(string $content, int $lineOffset = 0, $frontMatter = null) + { + parent::__construct($content, $lineOffset); + + $this->frontMatter = $frontMatter; + } + + /** + * {@inheritDoc} + */ + public function getFrontMatter() + { + return $this->frontMatter; + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPostRenderListener.php b/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPostRenderListener.php new file mode 100644 index 0000000..14b7191 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPostRenderListener.php @@ -0,0 +1,35 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Listener; + +use League\CommonMark\Event\DocumentRenderedEvent; +use League\CommonMark\Extension\FrontMatter\Output\RenderedContentWithFrontMatter; + +final class FrontMatterPostRenderListener +{ + public function __invoke(DocumentRenderedEvent $event): void + { + if ($event->getOutput()->getDocument()->data->get('front_matter', null) === null) { + return; + } + + $frontMatter = $event->getOutput()->getDocument()->data->get('front_matter'); + + $event->replaceOutput(new RenderedContentWithFrontMatter( + $event->getOutput()->getDocument(), + $event->getOutput()->getContent(), + $frontMatter + )); + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPreParser.php b/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPreParser.php new file mode 100644 index 0000000..b0afbee --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/Listener/FrontMatterPreParser.php @@ -0,0 +1,37 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Listener; + +use League\CommonMark\Event\DocumentPreParsedEvent; +use League\CommonMark\Extension\FrontMatter\FrontMatterParserInterface; + +final class FrontMatterPreParser +{ + private FrontMatterParserInterface $parser; + + public function __construct(FrontMatterParserInterface $parser) + { + $this->parser = $parser; + } + + public function __invoke(DocumentPreParsedEvent $event): void + { + $content = $event->getMarkdown()->getContent(); + + $parsed = $this->parser->parse($content); + + $event->getDocument()->data->set('front_matter', $parsed->getFrontMatter()); + $event->replaceMarkdown($parsed); + } +} diff --git a/vendor/league/commonmark/src/Extension/FrontMatter/Output/RenderedContentWithFrontMatter.php b/vendor/league/commonmark/src/Extension/FrontMatter/Output/RenderedContentWithFrontMatter.php new file mode 100644 index 0000000..efaa342 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/FrontMatter/Output/RenderedContentWithFrontMatter.php @@ -0,0 +1,51 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Extension\FrontMatter\Output; + +use League\CommonMark\Extension\FrontMatter\FrontMatterProviderInterface; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Output\RenderedContent; + +/** + * @psalm-immutable + */ +final class RenderedContentWithFrontMatter extends RenderedContent implements FrontMatterProviderInterface +{ + /** + * @var mixed + * + * @psalm-readonly + */ + private $frontMatter; + + /** + * @param Document $document The parsed Document object + * @param string $content The final HTML + * @param mixed|null $frontMatter Any parsed front matter + */ + public function __construct(Document $document, string $content, $frontMatter) + { + parent::__construct($document, $content); + + $this->frontMatter = $frontMatter; + } + + /** + * {@inheritDoc} + */ + public function getFrontMatter() + { + return $this->frontMatter; + } +} diff --git a/vendor/league/commonmark/src/Extension/GithubFlavoredMarkdownExtension.php b/vendor/league/commonmark/src/Extension/GithubFlavoredMarkdownExtension.php new file mode 100644 index 0000000..b3920aa --- /dev/null +++ b/vendor/league/commonmark/src/Extension/GithubFlavoredMarkdownExtension.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\Autolink\AutolinkExtension; +use League\CommonMark\Extension\DisallowedRawHtml\DisallowedRawHtmlExtension; +use League\CommonMark\Extension\Strikethrough\StrikethroughExtension; +use League\CommonMark\Extension\Table\TableExtension; +use League\CommonMark\Extension\TaskList\TaskListExtension; + +final class GithubFlavoredMarkdownExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addExtension(new AutolinkExtension()); + $environment->addExtension(new DisallowedRawHtmlExtension()); + $environment->addExtension(new StrikethroughExtension()); + $environment->addExtension(new TableExtension()); + $environment->addExtension(new TaskListExtension()); + } +} diff --git a/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalink.php b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalink.php new file mode 100644 index 0000000..df9bded --- /dev/null +++ b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalink.php @@ -0,0 +1,37 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\HeadingPermalink; + +use League\CommonMark\Node\Inline\AbstractInline; + +/** + * Represents an anchor link within a heading + */ +final class HeadingPermalink extends AbstractInline +{ + /** @psalm-readonly */ + private string $slug; + + public function __construct(string $slug) + { + parent::__construct(); + + $this->slug = $slug; + } + + public function getSlug(): string + { + return $this->slug; + } +} diff --git a/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkExtension.php b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkExtension.php new file mode 100644 index 0000000..96473a2 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkExtension.php @@ -0,0 +1,49 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\HeadingPermalink; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +/** + * Extension which automatically anchor links to heading elements + */ +final class HeadingPermalinkExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('heading_permalink', Expect::structure([ + 'min_heading_level' => Expect::int()->min(1)->max(6)->default(1), + 'max_heading_level' => Expect::int()->min(1)->max(6)->default(6), + 'insert' => Expect::anyOf(HeadingPermalinkProcessor::INSERT_BEFORE, HeadingPermalinkProcessor::INSERT_AFTER, HeadingPermalinkProcessor::INSERT_NONE)->default(HeadingPermalinkProcessor::INSERT_BEFORE), + 'id_prefix' => Expect::string()->default('content'), + 'apply_id_to_heading' => Expect::bool()->default(false), + 'heading_class' => Expect::string()->default(''), + 'fragment_prefix' => Expect::string()->default('content'), + 'html_class' => Expect::string()->default('heading-permalink'), + 'title' => Expect::string()->default('Permalink'), + 'symbol' => Expect::string()->default(HeadingPermalinkRenderer::DEFAULT_SYMBOL), + 'aria_hidden' => Expect::bool()->default(true), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentParsedEvent::class, new HeadingPermalinkProcessor(), -100); + $environment->addRenderer(HeadingPermalink::class, new HeadingPermalinkRenderer()); + } +} diff --git a/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php new file mode 100644 index 0000000..def1e22 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php @@ -0,0 +1,105 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\HeadingPermalink; + +use League\CommonMark\Environment\EnvironmentAwareInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Node\NodeIterator; +use League\CommonMark\Node\RawMarkupContainerInterface; +use League\CommonMark\Node\StringContainerHelper; +use League\CommonMark\Normalizer\TextNormalizerInterface; +use League\Config\ConfigurationInterface; +use League\Config\Exception\InvalidConfigurationException; + +/** + * Searches the Document for Heading elements and adds HeadingPermalinks to each one + */ +final class HeadingPermalinkProcessor implements EnvironmentAwareInterface +{ + public const INSERT_BEFORE = 'before'; + public const INSERT_AFTER = 'after'; + public const INSERT_NONE = 'none'; + + /** @psalm-readonly-allow-private-mutation */ + private TextNormalizerInterface $slugNormalizer; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function setEnvironment(EnvironmentInterface $environment): void + { + $this->config = $environment->getConfiguration(); + $this->slugNormalizer = $environment->getSlugNormalizer(); + } + + public function __invoke(DocumentParsedEvent $e): void + { + $min = (int) $this->config->get('heading_permalink/min_heading_level'); + $max = (int) $this->config->get('heading_permalink/max_heading_level'); + $applyToHeading = (bool) $this->config->get('heading_permalink/apply_id_to_heading'); + $idPrefix = (string) $this->config->get('heading_permalink/id_prefix'); + $slugLength = (int) $this->config->get('slug_normalizer/max_length'); + $headingClass = (string) $this->config->get('heading_permalink/heading_class'); + + if ($idPrefix !== '') { + $idPrefix .= '-'; + } + + foreach ($e->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if ($node instanceof Heading && $node->getLevel() >= $min && $node->getLevel() <= $max) { + $this->addHeadingLink($node, $slugLength, $idPrefix, $applyToHeading, $headingClass); + } + } + } + + private function addHeadingLink(Heading $heading, int $slugLength, string $idPrefix, bool $applyToHeading, string $headingClass): void + { + $text = StringContainerHelper::getChildText($heading, [RawMarkupContainerInterface::class]); + $slug = $this->slugNormalizer->normalize($text, [ + 'node' => $heading, + 'length' => $slugLength, + ]); + + if ($applyToHeading) { + if ($heading->data->has('attributes/id')) { + $slug = $heading->data->get('attributes/id'); + } + + $heading->data->set('attributes/id', $idPrefix . $slug); + } + + if ($headingClass !== '') { + $heading->data->append('attributes/class', $headingClass); + } + + $headingLinkAnchor = new HeadingPermalink($slug); + + switch ($this->config->get('heading_permalink/insert')) { + case self::INSERT_BEFORE: + $heading->prependChild($headingLinkAnchor); + + return; + case self::INSERT_AFTER: + $heading->appendChild($headingLinkAnchor); + + return; + case self::INSERT_NONE: + return; + default: + throw new InvalidConfigurationException("Invalid configuration value for heading_permalink/insert; expected 'before', 'after', or 'none'"); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkRenderer.php b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkRenderer.php new file mode 100644 index 0000000..ba2d6f8 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkRenderer.php @@ -0,0 +1,109 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\HeadingPermalink; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +/** + * Renders the HeadingPermalink elements + */ +final class HeadingPermalinkRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + public const DEFAULT_SYMBOL = '¶'; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + /** + * @param HeadingPermalink $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + HeadingPermalink::assertInstanceOf($node); + + $slug = $node->getSlug(); + + $fragmentPrefix = (string) $this->config->get('heading_permalink/fragment_prefix'); + if ($fragmentPrefix !== '') { + $fragmentPrefix .= '-'; + } + + $attrs = $node->data->getData('attributes'); + $appendId = ! $this->config->get('heading_permalink/apply_id_to_heading'); + + if ($appendId) { + $idPrefix = (string) $this->config->get('heading_permalink/id_prefix'); + + if ($idPrefix !== '') { + $idPrefix .= '-'; + } + + $attrs->set('id', $idPrefix . $slug); + } + + $attrs->set('href', '#' . $fragmentPrefix . $slug); + $attrs->append('class', $this->config->get('heading_permalink/html_class')); + + $hidden = $this->config->get('heading_permalink/aria_hidden'); + if ($hidden) { + $attrs->set('aria-hidden', 'true'); + // A focusable element removed from the accessibility tree is a WCAG 4.1.2 failure, + // so the link must also be taken out of the tab order + $attrs->set('tabindex', '-1'); + } + + $attrs->set('title', $this->config->get('heading_permalink/title')); + + $symbol = $this->config->get('heading_permalink/symbol'); + \assert(\is_string($symbol)); + + return new HtmlElement('a', $attrs->export(), \htmlspecialchars($symbol), false); + } + + public function getXmlTagName(Node $node): string + { + return 'heading_permalink'; + } + + /** + * @param HeadingPermalink $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + HeadingPermalink::assertInstanceOf($node); + + return [ + 'slug' => $node->getSlug(), + ]; + } +} diff --git a/vendor/league/commonmark/src/Extension/Highlight/HighlightExtension.php b/vendor/league/commonmark/src/Extension/Highlight/HighlightExtension.php new file mode 100644 index 0000000..ec24458 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Highlight/HighlightExtension.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Highlight; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ExtensionInterface; + +class HighlightExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addDelimiterProcessor(new MarkDelimiterProcessor()); + $environment->addRenderer(Mark::class, new MarkRenderer()); + } +} diff --git a/vendor/league/commonmark/src/Extension/Highlight/Mark.php b/vendor/league/commonmark/src/Extension/Highlight/Mark.php new file mode 100644 index 0000000..c5e226b --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Highlight/Mark.php @@ -0,0 +1,39 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Highlight; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Inline\DelimitedInterface; + +final class Mark extends AbstractInline implements DelimitedInterface +{ + private string $delimiter; + + public function __construct(string $delimiter = '==') + { + parent::__construct(); + + $this->delimiter = $delimiter; + } + + public function getOpeningDelimiter(): string + { + return $this->delimiter; + } + + public function getClosingDelimiter(): string + { + return $this->delimiter; + } +} diff --git a/vendor/league/commonmark/src/Extension/Highlight/MarkDelimiterProcessor.php b/vendor/league/commonmark/src/Extension/Highlight/MarkDelimiterProcessor.php new file mode 100644 index 0000000..6773172 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Highlight/MarkDelimiterProcessor.php @@ -0,0 +1,73 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Highlight; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Delimiter\Processor\CacheableDelimiterProcessorInterface; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +class MarkDelimiterProcessor implements CacheableDelimiterProcessorInterface +{ + public function getOpeningCharacter(): string + { + return '='; + } + + public function getClosingCharacter(): string + { + return '='; + } + + public function getMinLength(): int + { + return 2; + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + if ($opener->getLength() > 2 && $closer->getLength() > 2) { + return 0; + } + + if ($opener->getLength() !== $closer->getLength()) { + return 0; + } + + // $opener and $closer are the same length so we just return one of them + return $opener->getLength(); + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + $mark = new Mark(\str_repeat('=', $delimiterUse)); + + $next = $opener->next(); + while ($next !== null && $next !== $closer) { + $tmp = $next->next(); + $mark->appendChild($next); + $next = $tmp; + } + + $opener->insertAfter($mark); + } + + public function getCacheKey(DelimiterInterface $closer): string + { + // getDelimiterUse() returns 0 for every possible opener once the closer exceeds 2 + // characters, so all longer closers behave identically and can share a bucket. + // Clamping keeps the key space bounded, which is what makes the delimiter stack's + // lower-bound cache amortize. + return '=' . \min($closer->getLength(), 3); + } +} diff --git a/vendor/league/commonmark/src/Extension/Highlight/MarkRenderer.php b/vendor/league/commonmark/src/Extension/Highlight/MarkRenderer.php new file mode 100644 index 0000000..59c6bf3 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Highlight/MarkRenderer.php @@ -0,0 +1,50 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Highlight; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class MarkRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Mark $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Mark::assertInstanceOf($node); + + return new HtmlElement('mark', $node->data->get('attributes'), $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'mark'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/InlinesOnly/ChildRenderer.php b/vendor/league/commonmark/src/Extension/InlinesOnly/ChildRenderer.php new file mode 100644 index 0000000..403e948 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/InlinesOnly/ChildRenderer.php @@ -0,0 +1,35 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\InlinesOnly; + +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; + +/** + * Simply renders child elements as-is, adding newlines as needed. + */ +final class ChildRenderer implements NodeRendererInterface +{ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + $out = $childRenderer->renderNodes($node->children()); + if (! $node instanceof Document) { + $out .= $childRenderer->getBlockSeparator(); + } + + return $out; + } +} diff --git a/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php b/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php new file mode 100644 index 0000000..f85fad5 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php @@ -0,0 +1,74 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\InlinesOnly; + +use League\CommonMark as Core; +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\CommonMark; +use League\CommonMark\Extension\CommonMark\Delimiter\Processor\EmphasisDelimiterProcessor; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class InlinesOnlyExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('commonmark', Expect::structure([ + 'use_asterisk' => Expect::bool(true), + '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), + ])); + } + + // phpcs:disable Generic.Functions.FunctionCallArgumentSpacing.TooMuchSpaceAfterComma,Squiz.WhiteSpace.SemicolonSpacing.Incorrect + public function register(EnvironmentBuilderInterface $environment): void + { + $childRenderer = new ChildRenderer(); + + $environment + ->addInlineParser(new Core\Parser\Inline\NewlineParser(), 200) + ->addInlineParser(new CommonMark\Parser\Inline\BacktickParser(), 150) + ->addInlineParser(new CommonMark\Parser\Inline\EscapableParser(), 80) + ->addInlineParser(new CommonMark\Parser\Inline\EntityParser(), 70) + ->addInlineParser(new CommonMark\Parser\Inline\AutolinkParser(), 50) + ->addInlineParser(new CommonMark\Parser\Inline\HtmlInlineParser(), 40) + ->addInlineParser(new CommonMark\Parser\Inline\CloseBracketParser(), 30) + ->addInlineParser(new CommonMark\Parser\Inline\OpenBracketParser(), 20) + ->addInlineParser(new CommonMark\Parser\Inline\BangParser(), 10) + + ->addRenderer(Core\Node\Block\Document::class, $childRenderer, 0) + ->addRenderer(Core\Node\Block\Paragraph::class, $childRenderer, 0) + + ->addRenderer(CommonMark\Node\Inline\Code::class, new CommonMark\Renderer\Inline\CodeRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\Emphasis::class, new CommonMark\Renderer\Inline\EmphasisRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\HtmlInline::class, new CommonMark\Renderer\Inline\HtmlInlineRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\Image::class, new CommonMark\Renderer\Inline\ImageRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\Link::class, new CommonMark\Renderer\Inline\LinkRenderer(), 0) + ->addRenderer(Core\Node\Inline\Newline::class, new Core\Renderer\Inline\NewlineRenderer(), 0) + ->addRenderer(CommonMark\Node\Inline\Strong::class, new CommonMark\Renderer\Inline\StrongRenderer(), 0) + ->addRenderer(Core\Node\Inline\Text::class, new Core\Renderer\Inline\TextRenderer(), 0) + ; + + if ($environment->getConfiguration()->get('commonmark/use_asterisk')) { + $environment->addDelimiterProcessor(new EmphasisDelimiterProcessor('*')); + } + + if ($environment->getConfiguration()->get('commonmark/use_underscore')) { + $environment->addDelimiterProcessor(new EmphasisDelimiterProcessor('_')); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/Mention/Generator/CallbackGenerator.php b/vendor/league/commonmark/src/Extension/Mention/Generator/CallbackGenerator.php new file mode 100644 index 0000000..e607c7d --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Mention/Generator/CallbackGenerator.php @@ -0,0 +1,54 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention\Generator; + +use League\CommonMark\Exception\LogicException; +use League\CommonMark\Extension\Mention\Mention; +use League\CommonMark\Node\Inline\AbstractInline; + +final class CallbackGenerator implements MentionGeneratorInterface +{ + /** + * A callback function which sets the URL on the passed mention and returns the mention, return a new AbstractInline based object or null if the mention is not a match + * + * @var callable(Mention): ?AbstractInline + */ + private $callback; + + public function __construct(callable $callback) + { + $this->callback = $callback; + } + + /** + * @throws LogicException + */ + public function generateMention(Mention $mention): ?AbstractInline + { + $result = \call_user_func($this->callback, $mention); + if ($result === null) { + return null; + } + + if ($result instanceof Mention) { + if ($result->hasUrl()) { + return $mention; + } + } elseif ($result instanceof AbstractInline) { + return $result; + } + + throw new LogicException('CallbackGenerator callable must set the URL on the passed mention and return the mention, return a new AbstractInline based object or null if the mention is not a match'); + } +} diff --git a/vendor/league/commonmark/src/Extension/Mention/Generator/MentionGeneratorInterface.php b/vendor/league/commonmark/src/Extension/Mention/Generator/MentionGeneratorInterface.php new file mode 100644 index 0000000..30d4a51 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Mention/Generator/MentionGeneratorInterface.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention\Generator; + +use League\CommonMark\Extension\Mention\Mention; +use League\CommonMark\Node\Inline\AbstractInline; + +interface MentionGeneratorInterface +{ + public function generateMention(Mention $mention): ?AbstractInline; +} diff --git a/vendor/league/commonmark/src/Extension/Mention/Generator/StringTemplateLinkGenerator.php b/vendor/league/commonmark/src/Extension/Mention/Generator/StringTemplateLinkGenerator.php new file mode 100644 index 0000000..5d92897 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Mention/Generator/StringTemplateLinkGenerator.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention\Generator; + +use League\CommonMark\Extension\Mention\Mention; +use League\CommonMark\Node\Inline\AbstractInline; + +final class StringTemplateLinkGenerator implements MentionGeneratorInterface +{ + private string $urlTemplate; + + public function __construct(string $urlTemplate) + { + $this->urlTemplate = $urlTemplate; + } + + public function generateMention(Mention $mention): ?AbstractInline + { + $mention->setUrl(\sprintf($this->urlTemplate, $mention->getIdentifier())); + + return $mention; + } +} diff --git a/vendor/league/commonmark/src/Extension/Mention/Mention.php b/vendor/league/commonmark/src/Extension/Mention/Mention.php new file mode 100644 index 0000000..74eaee4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Mention/Mention.php @@ -0,0 +1,93 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention; + +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Node\Inline\Text; + +class Mention extends Link +{ + private string $name; + + private string $prefix; + + private string $identifier; + + public function __construct(string $name, string $prefix, string $identifier, ?string $label = null) + { + $this->name = $name; + $this->prefix = $prefix; + $this->identifier = $identifier; + + parent::__construct('', $label ?? \sprintf('%s%s', $prefix, $identifier)); + } + + public function getLabel(): ?string + { + if (($labelNode = $this->findLabelNode()) === null) { + return null; + } + + return $labelNode->getLiteral(); + } + + public function getIdentifier(): string + { + return $this->identifier; + } + + public function getName(): ?string + { + return $this->name; + } + + public function getPrefix(): string + { + return $this->prefix; + } + + public function hasUrl(): bool + { + return $this->url !== ''; + } + + /** + * @return $this + */ + public function setLabel(string $label): self + { + if (($labelNode = $this->findLabelNode()) === null) { + $labelNode = new Text(); + $this->prependChild($labelNode); + } + + $labelNode->setLiteral($label); + + return $this; + } + + private function findLabelNode(): ?Text + { + foreach ($this->children() as $child) { + if ($child instanceof Text) { + return $child; + } + } + + return null; + } +} diff --git a/vendor/league/commonmark/src/Extension/Mention/MentionExtension.php b/vendor/league/commonmark/src/Extension/Mention/MentionExtension.php new file mode 100644 index 0000000..c848c26 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Mention/MentionExtension.php @@ -0,0 +1,61 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Extension\Mention\Generator\MentionGeneratorInterface; +use League\Config\ConfigurationBuilderInterface; +use League\Config\Exception\InvalidConfigurationException; +use Nette\Schema\Expect; + +final class MentionExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $isAValidPartialRegex = static function (string $regex): bool { + $regex = '/' . $regex . '/i'; + + return @\preg_match($regex, '') !== false; + }; + + $builder->addSchema('mentions', Expect::arrayOf( + Expect::structure([ + 'prefix' => Expect::string()->required(), + 'pattern' => Expect::string()->assert($isAValidPartialRegex, 'Pattern must not include starting/ending delimiters (like "/")')->required(), + 'generator' => Expect::anyOf( + Expect::type(MentionGeneratorInterface::class), + Expect::string(), + Expect::type('callable') + )->required(), + ]) + )); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $mentions = $environment->getConfiguration()->get('mentions'); + foreach ($mentions as $name => $mention) { + if ($mention['generator'] instanceof MentionGeneratorInterface) { + $environment->addInlineParser(new MentionParser($name, $mention['prefix'], $mention['pattern'], $mention['generator'])); + } elseif (\is_string($mention['generator'])) { + $environment->addInlineParser(MentionParser::createWithStringTemplate($name, $mention['prefix'], $mention['pattern'], $mention['generator'])); + } elseif (\is_callable($mention['generator'])) { + $environment->addInlineParser(MentionParser::createWithCallback($name, $mention['prefix'], $mention['pattern'], $mention['generator'])); + } else { + throw new InvalidConfigurationException(\sprintf('The "generator" provided for the "%s" MentionParser configuration must be a string template, callable, or an object that implements %s.', $name, MentionGeneratorInterface::class)); + } + } + } +} diff --git a/vendor/league/commonmark/src/Extension/Mention/MentionParser.php b/vendor/league/commonmark/src/Extension/Mention/MentionParser.php new file mode 100644 index 0000000..a81c787 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Mention/MentionParser.php @@ -0,0 +1,87 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Mention; + +use League\CommonMark\Extension\Mention\Generator\CallbackGenerator; +use League\CommonMark\Extension\Mention\Generator\MentionGeneratorInterface; +use League\CommonMark\Extension\Mention\Generator\StringTemplateLinkGenerator; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class MentionParser implements InlineParserInterface +{ + /** @psalm-readonly */ + private string $name; + + /** @psalm-readonly */ + private string $prefix; + + /** @psalm-readonly */ + private string $identifierPattern; + + /** @psalm-readonly */ + private MentionGeneratorInterface $mentionGenerator; + + public function __construct(string $name, string $prefix, string $identifierPattern, MentionGeneratorInterface $mentionGenerator) + { + $this->name = $name; + $this->prefix = $prefix; + $this->identifierPattern = $identifierPattern; + $this->mentionGenerator = $mentionGenerator; + } + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::join( + InlineParserMatch::string($this->prefix), + InlineParserMatch::regex($this->identifierPattern) + ); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $cursor = $inlineContext->getCursor(); + + // The prefix must not have any other characters immediately prior + $previousChar = $cursor->peek(-1); + if ($previousChar !== null && \preg_match('/\w/', $previousChar)) { + // peek() doesn't modify the cursor, so no need to restore state first + return false; + } + + [$prefix, $identifier] = $inlineContext->getSubMatches(); + + $mention = $this->mentionGenerator->generateMention(new Mention($this->name, $prefix, $identifier)); + + if ($mention === null) { + return false; + } + + $cursor->advanceBy($inlineContext->getFullMatchLength()); + $inlineContext->getContainer()->appendChild($mention); + + return true; + } + + public static function createWithStringTemplate(string $name, string $prefix, string $mentionRegex, string $urlTemplate): MentionParser + { + return new self($name, $prefix, $mentionRegex, new StringTemplateLinkGenerator($urlTemplate)); + } + + public static function createWithCallback(string $name, string $prefix, string $mentionRegex, callable $callback): MentionParser + { + return new self($name, $prefix, $mentionRegex, new CallbackGenerator($callback)); + } +} diff --git a/vendor/league/commonmark/src/Extension/NormalizeHeadings/NormalizeHeadingsExtension.php b/vendor/league/commonmark/src/Extension/NormalizeHeadings/NormalizeHeadingsExtension.php new file mode 100644 index 0000000..27eba31 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/NormalizeHeadings/NormalizeHeadingsExtension.php @@ -0,0 +1,44 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\NormalizeHeadings; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class NormalizeHeadingsExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('normalize_headings', Expect::structure([ + 'min_level' => Expect::int()->min(1)->max(6)->default(1), + 'max_level' => Expect::int()->min(1)->max(6)->default(6), + 'rebase_to_min_level' => Expect::bool()->default(false), + ])->assert( + static function (\stdClass $config): bool { + $headingLevels = (array) $config; + + return $headingLevels['min_level'] <= $headingLevels['max_level']; + }, + '"min_level" must be less than or equal to "max_level"' + )); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addEventListener(DocumentParsedEvent::class, new NormalizeHeadingsProcessor(), -99); + } +} diff --git a/vendor/league/commonmark/src/Extension/NormalizeHeadings/NormalizeHeadingsProcessor.php b/vendor/league/commonmark/src/Extension/NormalizeHeadings/NormalizeHeadingsProcessor.php new file mode 100644 index 0000000..aff5933 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/NormalizeHeadings/NormalizeHeadingsProcessor.php @@ -0,0 +1,78 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\NormalizeHeadings; + +use League\CommonMark\Environment\EnvironmentAwareInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Node\NodeIterator; +use League\Config\ConfigurationInterface; + +final class NormalizeHeadingsProcessor implements EnvironmentAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function setEnvironment(EnvironmentInterface $environment): void + { + $this->config = $environment->getConfiguration(); + } + + public function __invoke(DocumentParsedEvent $event): void + { + $minLevel = (int) $this->config->get('normalize_headings/min_level'); + $maxLevel = (int) $this->config->get('normalize_headings/max_level'); + $rebaseToMinLevel = (bool) $this->config->get('normalize_headings/rebase_to_min_level'); + + /** + * The headings the current one is nested within, tracked by both their original level (which + * determines that nesting) and their new level (which limits how far the current one may descend) + * + * @var array<int, array{original: int, output: int}> $ancestors + */ + $ancestors = []; + + foreach ($event->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof Heading) { + continue; + } + + $level = $node->getLevel(); + + // Pop any headings this one isn't nested within - they're siblings or cousins, not ancestors + $parent = \end($ancestors); + while ($parent !== false && $level <= $parent['original']) { + \array_pop($ancestors); + $parent = \end($ancestors); + } + + if ($parent === false) { + $newLevel = $rebaseToMinLevel ? $minLevel : self::clamp($level, $minLevel, $maxLevel); + } else { + // Place this heading exactly one level below its parent, regardless of the level it was + // written at - unless that would exceed the maximum, in which case it becomes a sibling + $newLevel = \min($parent['output'] + 1, $maxLevel); + } + + $node->setLevel($newLevel); + $ancestors[] = ['original' => $level, 'output' => $newLevel]; + } + } + + private static function clamp(int $level, int $minLevel, int $maxLevel): int + { + return \max($minLevel, \min($level, $maxLevel)); + } +} diff --git a/vendor/league/commonmark/src/Extension/SmartPunct/DashParser.php b/vendor/league/commonmark/src/Extension/SmartPunct/DashParser.php new file mode 100644 index 0000000..cf0e1af --- /dev/null +++ b/vendor/league/commonmark/src/Extension/SmartPunct/DashParser.php @@ -0,0 +1,59 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class DashParser implements InlineParserInterface +{ + private const EN_DASH = '–'; + private const EM_DASH = '—'; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('(?<!-)(-{2,})'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $count = $inlineContext->getFullMatchLength(); + $inlineContext->getCursor()->advanceBy($count); + + $enCount = 0; + $emCount = 0; + if ($count % 3 === 0) { // If divisible by 3, use all em dashes + $emCount = (int) ($count / 3); + } elseif ($count % 2 === 0) { // If divisible by 2, use all en dashes + $enCount = (int) ($count / 2); + } elseif ($count % 3 === 2) { // If 2 extra dashes, use en dash for last 2; em dashes for rest + $emCount = (int) (($count - 2) / 3); + $enCount = 1; + } else { // Use en dashes for last 4 hyphens; em dashes for rest + $emCount = (int) (($count - 4) / 3); + $enCount = 2; + } + + $inlineContext->getContainer()->appendChild(new Text( + \str_repeat(self::EM_DASH, $emCount) . \str_repeat(self::EN_DASH, $enCount) + )); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/SmartPunct/EllipsesParser.php b/vendor/league/commonmark/src/Extension/SmartPunct/EllipsesParser.php new file mode 100644 index 0000000..9f5b3bd --- /dev/null +++ b/vendor/league/commonmark/src/Extension/SmartPunct/EllipsesParser.php @@ -0,0 +1,38 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; + +final class EllipsesParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf('...', '. . .'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength()); + $inlineContext->getContainer()->appendChild(new Text('…')); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/SmartPunct/Quote.php b/vendor/league/commonmark/src/Extension/SmartPunct/Quote.php new file mode 100644 index 0000000..dee9759 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/SmartPunct/Quote.php @@ -0,0 +1,30 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Node\Inline\AbstractStringContainer; + +final class Quote extends AbstractStringContainer +{ + public const DOUBLE_QUOTE = '"'; + public const DOUBLE_QUOTE_OPENER = '“'; + public const DOUBLE_QUOTE_CLOSER = '”'; + + public const SINGLE_QUOTE = "'"; + public const SINGLE_QUOTE_OPENER = '‘'; + public const SINGLE_QUOTE_CLOSER = '’'; +} diff --git a/vendor/league/commonmark/src/Extension/SmartPunct/QuoteParser.php b/vendor/league/commonmark/src/Extension/SmartPunct/QuoteParser.php new file mode 100644 index 0000000..31ba8c7 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/SmartPunct/QuoteParser.php @@ -0,0 +1,98 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Delimiter\Delimiter; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Parser\Inline\InlineParserMatch; +use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\RegexHelper; + +final class QuoteParser implements InlineParserInterface +{ + /** + * @deprecated This constant is no longer used and will be removed in a future major release + */ + public const DOUBLE_QUOTES = [Quote::DOUBLE_QUOTE, Quote::DOUBLE_QUOTE_OPENER, Quote::DOUBLE_QUOTE_CLOSER]; + + /** + * @deprecated This constant is no longer used and will be removed in a future major release + */ + public const SINGLE_QUOTES = [Quote::SINGLE_QUOTE, Quote::SINGLE_QUOTE_OPENER, Quote::SINGLE_QUOTE_CLOSER]; + + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf(Quote::SINGLE_QUOTE, Quote::DOUBLE_QUOTE); + } + + /** + * Normalizes any quote characters found and manually adds them to the delimiter stack + */ + public function parse(InlineParserContext $inlineContext): bool + { + $char = $inlineContext->getFullMatch(); + $cursor = $inlineContext->getCursor(); + $index = $cursor->getPosition(); + + $charBefore = $cursor->peek(-1); + if ($charBefore === null) { + $charBefore = "\n"; + } + + $cursor->advance(); + + $charAfter = $cursor->getCurrentCharacter(); + if ($charAfter === null) { + $charAfter = "\n"; + } + + [$leftFlanking, $rightFlanking] = $this->determineFlanking($charBefore, $charAfter); + $canOpen = $leftFlanking && ! $rightFlanking; + $canClose = $rightFlanking; + + $node = new Quote($char, ['delim' => true]); + $inlineContext->getContainer()->appendChild($node); + + // Add entry to stack to this opener + $inlineContext->getDelimiterStack()->push(new Delimiter($char, 1, $node, $canOpen, $canClose, $index)); + + return true; + } + + /** + * @return bool[] + */ + private function determineFlanking(string $charBefore, string $charAfter): array + { + $afterIsWhitespace = \preg_match('/\pZ|\s/u', $charAfter); + $afterIsPunctuation = \preg_match(RegexHelper::REGEX_PUNCTUATION, $charAfter); + $beforeIsWhitespace = \preg_match('/\pZ|\s/u', $charBefore); + $beforeIsPunctuation = \preg_match(RegexHelper::REGEX_PUNCTUATION, $charBefore); + + $leftFlanking = ! $afterIsWhitespace && + ! ($afterIsPunctuation && + ! $beforeIsWhitespace && + ! $beforeIsPunctuation); + + $rightFlanking = ! $beforeIsWhitespace && + ! ($beforeIsPunctuation && + ! $afterIsWhitespace && + ! $afterIsPunctuation); + + return [$leftFlanking, $rightFlanking]; + } +} diff --git a/vendor/league/commonmark/src/Extension/SmartPunct/QuoteProcessor.php b/vendor/league/commonmark/src/Extension/SmartPunct/QuoteProcessor.php new file mode 100644 index 0000000..1fc30d4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/SmartPunct/QuoteProcessor.php @@ -0,0 +1,82 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Delimiter\Processor\DelimiterProcessorInterface; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +final class QuoteProcessor implements DelimiterProcessorInterface +{ + /** @psalm-readonly */ + private string $normalizedCharacter; + + /** @psalm-readonly */ + private string $openerCharacter; + + /** @psalm-readonly */ + private string $closerCharacter; + + private function __construct(string $char, string $opener, string $closer) + { + $this->normalizedCharacter = $char; + $this->openerCharacter = $opener; + $this->closerCharacter = $closer; + } + + public function getOpeningCharacter(): string + { + return $this->normalizedCharacter; + } + + public function getClosingCharacter(): string + { + return $this->normalizedCharacter; + } + + public function getMinLength(): int + { + return 1; + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + return 1; + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + $opener->insertAfter(new Quote($this->openerCharacter)); + $closer->insertBefore(new Quote($this->closerCharacter)); + } + + /** + * Create a double-quote processor + */ + public static function createDoubleQuoteProcessor(string $opener = Quote::DOUBLE_QUOTE_OPENER, string $closer = Quote::DOUBLE_QUOTE_CLOSER): self + { + return new self(Quote::DOUBLE_QUOTE, $opener, $closer); + } + + /** + * Create a single-quote processor + */ + public static function createSingleQuoteProcessor(string $opener = Quote::SINGLE_QUOTE_OPENER, string $closer = Quote::SINGLE_QUOTE_CLOSER): self + { + return new self(Quote::SINGLE_QUOTE, $opener, $closer); + } +} diff --git a/vendor/league/commonmark/src/Extension/SmartPunct/ReplaceUnpairedQuotesListener.php b/vendor/league/commonmark/src/Extension/SmartPunct/ReplaceUnpairedQuotesListener.php new file mode 100644 index 0000000..3536452 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/SmartPunct/ReplaceUnpairedQuotesListener.php @@ -0,0 +1,43 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Node\Inline\AdjacentTextMerger; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Node\Query; + +/** + * Identifies any lingering Quote nodes that were missing pairs and converts them into Text nodes + */ +final class ReplaceUnpairedQuotesListener +{ + public function __invoke(DocumentParsedEvent $event): void + { + $query = (new Query())->where(Query::type(Quote::class)); + foreach ($query->findAll($event->getDocument()) as $quote) { + \assert($quote instanceof Quote); + + $literal = $quote->getLiteral(); + if ($literal === Quote::SINGLE_QUOTE) { + $literal = Quote::SINGLE_QUOTE_CLOSER; + } elseif ($literal === Quote::DOUBLE_QUOTE) { + $literal = Quote::DOUBLE_QUOTE_OPENER; + } + + $quote->replaceWith($new = new Text($literal)); + AdjacentTextMerger::mergeWithDirectlyAdjacentNodes($new); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/SmartPunct/SmartPunctExtension.php b/vendor/league/commonmark/src/Extension/SmartPunct/SmartPunctExtension.php new file mode 100644 index 0000000..8524ca1 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/SmartPunct/SmartPunctExtension.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\SmartPunct; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Renderer\Block as CoreBlockRenderer; +use League\CommonMark\Renderer\Inline as CoreInlineRenderer; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class SmartPunctExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('smartpunct', Expect::structure([ + 'double_quote_opener' => Expect::string(Quote::DOUBLE_QUOTE_OPENER), + 'double_quote_closer' => Expect::string(Quote::DOUBLE_QUOTE_CLOSER), + 'single_quote_opener' => Expect::string(Quote::SINGLE_QUOTE_OPENER), + 'single_quote_closer' => Expect::string(Quote::SINGLE_QUOTE_CLOSER), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $environment + ->addInlineParser(new QuoteParser(), 10) + ->addInlineParser(new DashParser(), 0) + ->addInlineParser(new EllipsesParser(), 0) + + ->addDelimiterProcessor(QuoteProcessor::createDoubleQuoteProcessor( + $environment->getConfiguration()->get('smartpunct/double_quote_opener'), + $environment->getConfiguration()->get('smartpunct/double_quote_closer') + )) + ->addDelimiterProcessor(QuoteProcessor::createSingleQuoteProcessor( + $environment->getConfiguration()->get('smartpunct/single_quote_opener'), + $environment->getConfiguration()->get('smartpunct/single_quote_closer') + )) + + ->addEventListener(DocumentParsedEvent::class, new ReplaceUnpairedQuotesListener()) + + ->addRenderer(Document::class, new CoreBlockRenderer\DocumentRenderer(), 0) + ->addRenderer(Paragraph::class, new CoreBlockRenderer\ParagraphRenderer(), 0) + ->addRenderer(Text::class, new CoreInlineRenderer\TextRenderer(), 0); + } +} diff --git a/vendor/league/commonmark/src/Extension/Strikethrough/Strikethrough.php b/vendor/league/commonmark/src/Extension/Strikethrough/Strikethrough.php new file mode 100644 index 0000000..20ad161 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Strikethrough/Strikethrough.php @@ -0,0 +1,39 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> and uAfrica.com (http://uafrica.com) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Strikethrough; + +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Inline\DelimitedInterface; + +final class Strikethrough extends AbstractInline implements DelimitedInterface +{ + private string $delimiter; + + public function __construct(string $delimiter = '~~') + { + parent::__construct(); + + $this->delimiter = $delimiter; + } + + public function getOpeningDelimiter(): string + { + return $this->delimiter; + } + + public function getClosingDelimiter(): string + { + return $this->delimiter; + } +} diff --git a/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughDelimiterProcessor.php b/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughDelimiterProcessor.php new file mode 100644 index 0000000..020ae86 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughDelimiterProcessor.php @@ -0,0 +1,73 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> and uAfrica.com (http://uafrica.com) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Strikethrough; + +use League\CommonMark\Delimiter\DelimiterInterface; +use League\CommonMark\Delimiter\Processor\CacheableDelimiterProcessorInterface; +use League\CommonMark\Node\Inline\AbstractStringContainer; + +final class StrikethroughDelimiterProcessor implements CacheableDelimiterProcessorInterface +{ + public function getOpeningCharacter(): string + { + return '~'; + } + + public function getClosingCharacter(): string + { + return '~'; + } + + public function getMinLength(): int + { + return 1; + } + + public function getDelimiterUse(DelimiterInterface $opener, DelimiterInterface $closer): int + { + if ($opener->getLength() > 2 && $closer->getLength() > 2) { + return 0; + } + + if ($opener->getLength() !== $closer->getLength()) { + return 0; + } + + // $opener and $closer are the same length so we just return one of them + return $opener->getLength(); + } + + public function process(AbstractStringContainer $opener, AbstractStringContainer $closer, int $delimiterUse): void + { + $strikethrough = new Strikethrough(\str_repeat('~', $delimiterUse)); + + $tmp = $opener->next(); + while ($tmp !== null && $tmp !== $closer) { + $next = $tmp->next(); + $strikethrough->appendChild($tmp); + $tmp = $next; + } + + $opener->insertAfter($strikethrough); + } + + public function getCacheKey(DelimiterInterface $closer): string + { + // getDelimiterUse() returns 0 for every possible opener once the closer exceeds 2 + // characters, so all longer closers behave identically and can share a bucket. + // Clamping keeps the key space bounded, which is what makes the delimiter stack's + // lower-bound cache amortize. + return '~' . \min($closer->getLength(), 3); + } +} diff --git a/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughExtension.php b/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughExtension.php new file mode 100644 index 0000000..96ffe7a --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughExtension.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> and uAfrica.com (http://uafrica.com) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Strikethrough; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ExtensionInterface; + +final class StrikethroughExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addDelimiterProcessor(new StrikethroughDelimiterProcessor()); + $environment->addRenderer(Strikethrough::class, new StrikethroughRenderer()); + } +} diff --git a/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughRenderer.php b/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughRenderer.php new file mode 100644 index 0000000..a50b895 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Strikethrough/StrikethroughRenderer.php @@ -0,0 +1,50 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> and uAfrica.com (http://uafrica.com) + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Strikethrough; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class StrikethroughRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Strikethrough $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Strikethrough::assertInstanceOf($node); + + return new HtmlElement('del', $node->data->get('attributes'), $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'strikethrough'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/Table.php b/vendor/league/commonmark/src/Extension/Table/Table.php new file mode 100644 index 0000000..2fe441d --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/Table.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class Table extends AbstractBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableCell.php b/vendor/league/commonmark/src/Extension/Table/TableCell.php new file mode 100644 index 0000000..6ed359a --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableCell.php @@ -0,0 +1,99 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class TableCell extends AbstractBlock +{ + public const TYPE_HEADER = 'header'; + public const TYPE_DATA = 'data'; + + public const ALIGN_LEFT = 'left'; + public const ALIGN_RIGHT = 'right'; + public const ALIGN_CENTER = 'center'; + + /** + * @psalm-var self::TYPE_* + * @phpstan-var self::TYPE_* + * + * @psalm-readonly-allow-private-mutation + */ + private string $type = self::TYPE_DATA; + + /** + * @psalm-var self::ALIGN_*|null + * @phpstan-var self::ALIGN_*|null + * + * @psalm-readonly-allow-private-mutation + */ + private ?string $align = null; + + /** + * @psalm-param self::TYPE_* $type + * @psalm-param self::ALIGN_*|null $align + * + * @phpstan-param self::TYPE_* $type + * @phpstan-param self::ALIGN_*|null $align + */ + public function __construct(string $type = self::TYPE_DATA, ?string $align = null) + { + parent::__construct(); + + $this->type = $type; + $this->align = $align; + } + + /** + * @psalm-return self::TYPE_* + * + * @phpstan-return self::TYPE_* + */ + public function getType(): string + { + return $this->type; + } + + /** + * @psalm-param self::TYPE_* $type + * + * @phpstan-param self::TYPE_* $type + */ + public function setType(string $type): void + { + $this->type = $type; + } + + /** + * @psalm-return self::ALIGN_*|null + * + * @phpstan-return self::ALIGN_*|null + */ + public function getAlign(): ?string + { + return $this->align; + } + + /** + * @psalm-param self::ALIGN_*|null $align + * + * @phpstan-param self::ALIGN_*|null $align + */ + public function setAlign(?string $align): void + { + $this->align = $align; + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableCellRenderer.php b/vendor/league/commonmark/src/Extension/Table/TableCellRenderer.php new file mode 100644 index 0000000..99512c3 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableCellRenderer.php @@ -0,0 +1,89 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Extension\Attributes\Util\AttributesHelper; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableCellRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + private const DEFAULT_ATTRIBUTES = [ + TableCell::ALIGN_LEFT => ['align' => 'left'], + TableCell::ALIGN_CENTER => ['align' => 'center'], + TableCell::ALIGN_RIGHT => ['align' => 'right'], + ]; + + /** @var array<TableCell::ALIGN_*, array<string, string|string[]|bool>> */ + private array $alignmentAttributes; + + /** + * @param array<TableCell::ALIGN_*, array<string, string|string[]|bool>> $alignmentAttributes + */ + public function __construct(array $alignmentAttributes = self::DEFAULT_ATTRIBUTES) + { + $this->alignmentAttributes = $alignmentAttributes; + } + + /** + * @param TableCell $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + TableCell::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + if (($alignment = $node->getAlign()) !== null) { + $attrs = AttributesHelper::mergeAttributes($attrs, $this->alignmentAttributes[$alignment]); + } + + $tag = $node->getType() === TableCell::TYPE_HEADER ? 'th' : 'td'; + + return new HtmlElement($tag, $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'table_cell'; + } + + /** + * @param TableCell $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + TableCell::assertInstanceOf($node); + + $ret = ['type' => $node->getType()]; + + if (($align = $node->getAlign()) !== null) { + $ret['align'] = $align; + } + + return $ret; + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableExtension.php b/vendor/league/commonmark/src/Extension/Table/TableExtension.php new file mode 100644 index 0000000..0a8db3e --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableExtension.php @@ -0,0 +1,63 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Renderer\HtmlDecorator; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class TableExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $attributeArraySchema = Expect::arrayOf( + Expect::type('string|string[]|bool'), // attribute value(s) + 'string' // attribute name + )->mergeDefaults(false); + + $builder->addSchema('table', Expect::structure([ + 'wrap' => Expect::structure([ + 'enabled' => Expect::bool()->default(false), + 'tag' => Expect::string()->default('div'), + 'attributes' => Expect::arrayOf(Expect::string()), + ]), + 'alignment_attributes' => Expect::structure([ + 'left' => (clone $attributeArraySchema)->default(['align' => 'left']), + 'center' => (clone $attributeArraySchema)->default(['align' => 'center']), + 'right' => (clone $attributeArraySchema)->default(['align' => 'right']), + ]), + 'max_autocompleted_cells' => Expect::int()->min(0)->default(TableParser::DEFAULT_MAX_AUTOCOMPLETED_CELLS), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $tableRenderer = new TableRenderer(); + if ($environment->getConfiguration()->get('table/wrap/enabled')) { + $tableRenderer = new HtmlDecorator($tableRenderer, $environment->getConfiguration()->get('table/wrap/tag'), $environment->getConfiguration()->get('table/wrap/attributes')); + } + + $environment + ->addBlockStartParser(new TableStartParser($environment->getConfiguration()->get('table/max_autocompleted_cells'))) + + ->addRenderer(Table::class, $tableRenderer) + ->addRenderer(TableSection::class, new TableSectionRenderer()) + ->addRenderer(TableRow::class, new TableRowRenderer()) + ->addRenderer(TableCell::class, new TableCellRenderer($environment->getConfiguration()->get('table/alignment_attributes'))); + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableParser.php b/vendor/league/commonmark/src/Extension/Table/TableParser.php new file mode 100644 index 0000000..56d2d72 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableParser.php @@ -0,0 +1,227 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockContinueParserWithInlinesInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\InlineParserEngineInterface; +use League\CommonMark\Util\ArrayCollection; + +final class TableParser extends AbstractBlockContinueParser implements BlockContinueParserWithInlinesInterface +{ + /** + * @internal + */ + public const DEFAULT_MAX_AUTOCOMPLETED_CELLS = 10_000; + + /** @psalm-readonly */ + private Table $block; + + /** + * @var ArrayCollection<string> + * + * @psalm-readonly-allow-private-mutation + */ + private ArrayCollection $bodyLines; + + /** + * @var array<int, string|null> + * @psalm-var array<int, TableCell::ALIGN_*|null> + * @phpstan-var array<int, TableCell::ALIGN_*|null> + * + * @psalm-readonly + */ + private array $columns; + + /** + * @var array<int, string> + * + * @psalm-readonly-allow-private-mutation + */ + private array $headerCells; + + /** @psalm-readonly-allow-private-mutation */ + private bool $nextIsSeparatorLine = true; + + 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 + * + * @psalm-param array<int, TableCell::ALIGN_*|null> $columns + * + * @phpstan-param array<int, TableCell::ALIGN_*|null> $columns + */ + public function __construct(array $columns, array $headerCells, int $remainingAutocompletedCells = self::DEFAULT_MAX_AUTOCOMPLETED_CELLS) + { + $this->block = new Table(); + $this->bodyLines = new ArrayCollection(); + $this->columns = $columns; + $this->headerCells = $headerCells; + $this->remainingAutocompletedCells = $remainingAutocompletedCells; + } + + public function canHaveLazyContinuationLines(): bool + { + return $this->canHaveLazyContinuationLines; + } + + public function getBlock(): Table + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + // 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(); + } + + return BlockContinue::at($cursor); + } + + public function addLine(string $line): void + { + $this->canHaveLazyContinuationLines = false; + + if ($this->nextIsSeparatorLine) { + $this->nextIsSeparatorLine = false; + } else { + $this->bodyLines[] = $line; + } + } + + public function parseInlines(InlineParserEngineInterface $inlineParser): void + { + $headerColumns = \count($this->headerCells); + + $head = new TableSection(TableSection::TYPE_HEAD); + $this->block->appendChild($head); + + $headerRow = new TableRow(); + $head->appendChild($headerRow); + for ($i = 0; $i < $headerColumns; $i++) { + $cell = $this->headerCells[$i]; + $tableCell = $this->parseCell($cell, $i, $inlineParser); + $tableCell->setType(TableCell::TYPE_HEADER); + $headerRow->appendChild($tableCell); + } + + $body = null; + foreach ($this->bodyLines as $rowLine) { + $cells = self::split($rowLine); + $row = new TableRow(); + + // Body can not have more columns than head + for ($i = 0; $i < $headerColumns; $i++) { + // It can have less columns though, in which case we'll autocomplete the empty ones (up to some limit) + if (! isset($cells[$i]) && $this->remainingAutocompletedCells-- <= 0) { + // Too many cells were auto-completed, so we'll just stop here + return; + } + + $cell = $cells[$i] ?? ''; + $tableCell = $this->parseCell($cell, $i, $inlineParser); + $row->appendChild($tableCell); + } + + if ($body === null) { + // It's valid to have a table without body. In that case, don't add an empty TableBody node. + $body = new TableSection(); + $this->block->appendChild($body); + } + + $body->appendChild($row); + } + } + + private function parseCell(string $cell, int $column, InlineParserEngineInterface $inlineParser): TableCell + { + $tableCell = new TableCell(TableCell::TYPE_DATA, $this->columns[$column] ?? null); + + if ($cell !== '') { + $inlineParser->parse(\trim($cell), $tableCell); + } + + return $tableCell; + } + + /** + * @internal + * + * @return array<int, string> + */ + public static function split(string $line): array + { + // 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); + + $i = 0; + if ($length > 0 && $line[0] === '|') { + $i = 1; + } + + $cells = []; + $sb = ''; + + for (; $i < $length; $i++) { + switch ($c = $line[$i]) { + case '\\': + 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 .= '|'; + $i++; + } else { + // Preserve backslash before other characters or at end of line. + $sb .= '\\'; + } + + break; + case '|': + $cells[] = $sb; + $sb = ''; + break; + default: + $sb .= $c; + } + } + + if ($sb !== '') { + $cells[] = $sb; + } + + return $cells; + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableRenderer.php b/vendor/league/commonmark/src/Extension/Table/TableRenderer.php new file mode 100644 index 0000000..7799e22 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableRenderer.php @@ -0,0 +1,58 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Table $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + Table::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $separator = $childRenderer->getInnerSeparator(); + + $children = $childRenderer->renderNodes($node->children()); + + return new HtmlElement('table', $attrs, $separator . \trim($children) . $separator); + } + + public function getXmlTagName(Node $node): string + { + return 'table'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableRow.php b/vendor/league/commonmark/src/Extension/Table/TableRow.php new file mode 100644 index 0000000..cd6ac99 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableRow.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class TableRow extends AbstractBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableRowRenderer.php b/vendor/league/commonmark/src/Extension/Table/TableRowRenderer.php new file mode 100644 index 0000000..dee72d2 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableRowRenderer.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableRowRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param TableRow $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + TableRow::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + + $separator = $childRenderer->getInnerSeparator(); + + return new HtmlElement('tr', $attrs, $separator . $childRenderer->renderNodes($node->children()) . $separator); + } + + public function getXmlTagName(Node $node): string + { + return 'table_row'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableSection.php b/vendor/league/commonmark/src/Extension/Table/TableSection.php new file mode 100644 index 0000000..9edd63b --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableSection.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class TableSection extends AbstractBlock +{ + public const TYPE_HEAD = 'head'; + public const TYPE_BODY = 'body'; + + /** + * @psalm-var self::TYPE_* + * @phpstan-var self::TYPE_* + * + * @psalm-readonly + */ + private string $type; + + /** + * @psalm-param self::TYPE_* $type + * + * @phpstan-param self::TYPE_* $type + */ + public function __construct(string $type = self::TYPE_BODY) + { + parent::__construct(); + + $this->type = $type; + } + + /** + * @psalm-return self::TYPE_* + * + * @phpstan-return self::TYPE_* + */ + public function getType(): string + { + return $this->type; + } + + public function isHead(): bool + { + return $this->type === self::TYPE_HEAD; + } + + public function isBody(): bool + { + return $this->type === self::TYPE_BODY; + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableSectionRenderer.php b/vendor/league/commonmark/src/Extension/Table/TableSectionRenderer.php new file mode 100644 index 0000000..cccf06c --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableSectionRenderer.php @@ -0,0 +1,70 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableSectionRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param TableSection $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + TableSection::assertInstanceOf($node); + + if (! $node->hasChildren()) { + return ''; + } + + $attrs = $node->data->get('attributes'); + + $separator = $childRenderer->getInnerSeparator(); + + $tag = $node->getType() === TableSection::TYPE_HEAD ? 'thead' : 'tbody'; + + return new HtmlElement($tag, $attrs, $separator . $childRenderer->renderNodes($node->children()) . $separator); + } + + public function getXmlTagName(Node $node): string + { + return 'table_section'; + } + + /** + * @param TableSection $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + TableSection::assertInstanceOf($node); + + return [ + 'type' => $node->getType(), + ]; + } +} diff --git a/vendor/league/commonmark/src/Extension/Table/TableStartParser.php b/vendor/league/commonmark/src/Extension/Table/TableStartParser.php new file mode 100644 index 0000000..87b037a --- /dev/null +++ b/vendor/league/commonmark/src/Extension/Table/TableStartParser.php @@ -0,0 +1,177 @@ +<?php + +declare(strict_types=1); + +/* + * This is part of the league/commonmark package. + * + * (c) Martin Hasoň <martin.hason@gmail.com> + * (c) Webuni s.r.o. <info@webuni.cz> + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\Table; + +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Block\ParagraphParser; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +final class TableStartParser implements BlockStartParserInterface +{ + private int $maxAutocompletedCells; + + public function __construct(int $maxAutocompletedCells = TableParser::DEFAULT_MAX_AUTOCOMPLETED_CELLS) + { + $this->maxAutocompletedCells = $maxAutocompletedCells; + } + + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + $paragraph = $parserState->getParagraphContent(); + 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(); + } + + $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)) { + return BlockStart::none(); + } + + $cursor->advanceToEnd(); + + $parsers = []; + + if ($lastLineBreak !== false) { + $p = new ParagraphParser(); + $p->addLine(\substr($paragraph, 0, $lastLineBreak)); + $parsers[] = $p; + } + + $parsers[] = new TableParser($columns, $headerCells, $this->maxAutocompletedCells); + + return BlockStart::of(...$parsers) + ->at($cursor) + ->replaceActiveBlockParser(); + } + + /** + * @return array<int, string|null> + * + * @psalm-return array<int, TableCell::ALIGN_*|null> + * + * @phpstan-return array<int, TableCell::ALIGN_*|null> + */ + 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; + + for ($i = 0; $i < $length;) { + switch ($c = $line[$i]) { + case '|': + $i++; + $pipes++; + if ($pipes > 1) { + // More than one adjacent pipe not allowed + return []; + } + + // Need at least one pipe, even for a one-column table + $valid = true; + break; + case '-': + case ':': + if ($pipes === 0 && \count($columns) > 0) { + // Need a pipe after the first column (first column doesn't need to start with one) + return []; + } + + $left = false; + $right = false; + if ($c === ':') { + $left = true; + $i++; + } + + $dashes = \strspn($line, '-', $i); + if ($dashes === 0) { + // Need at least one dash + return []; + } + + $i += $dashes; + + if ($i < $length && $line[$i] === ':') { + $right = true; + $i++; + } + + $columns[] = self::getAlignment($left, $right); + // Next, need another pipe + $pipes = 0; + break; + case ' ': + case "\t": + // White space is allowed between pipes and columns + $i += \strspn($line, " \t", $i); + break; + default: + // Any other character is invalid + return []; + } + } + + if (! $valid) { + return []; + } + + return $columns; + } + + /** + * @psalm-return TableCell::ALIGN_*|null + * + * @phpstan-return TableCell::ALIGN_*|null + * + * @psalm-pure + */ + private static function getAlignment(bool $left, bool $right): ?string + { + if ($left && $right) { + return TableCell::ALIGN_CENTER; + } + + if ($left) { + return TableCell::ALIGN_LEFT; + } + + if ($right) { + return TableCell::ALIGN_RIGHT; + } + + return null; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContents.php b/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContents.php new file mode 100644 index 0000000..e040d86 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContents.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Node; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; + +final class TableOfContents extends ListBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsPlaceholder.php b/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsPlaceholder.php new file mode 100644 index 0000000..6d6db10 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsPlaceholder.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class TableOfContentsPlaceholder extends AbstractBlock +{ +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsReference.php b/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsReference.php new file mode 100644 index 0000000..4566d52 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsReference.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Node; + +use League\CommonMark\Extension\TableOfContents\TableOfContentsRenderCache; +use League\CommonMark\Node\Block\AbstractBlock; + +/** + * Lightweight stand-in for a placeholder which references the shared table of contents instead of holding a full copy + */ +final class TableOfContentsReference extends AbstractBlock +{ + /** @psalm-readonly */ + private TableOfContents $tableOfContents; + + /** @psalm-readonly */ + private TableOfContentsRenderCache $renderCache; + + public function __construct(TableOfContents $tableOfContents, TableOfContentsRenderCache $renderCache) + { + parent::__construct(); + + $this->tableOfContents = $tableOfContents; + $this->renderCache = $renderCache; + } + + public function getTableOfContents(): TableOfContents + { + return $this->tableOfContents; + } + + public function getRenderCache(): TableOfContentsRenderCache + { + return $this->renderCache; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/AsIsNormalizerStrategy.php b/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/AsIsNormalizerStrategy.php new file mode 100644 index 0000000..f5bb9a4 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/AsIsNormalizerStrategy.php @@ -0,0 +1,72 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Normalizer; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; + +final class AsIsNormalizerStrategy implements NormalizerStrategyInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ListBlock $parentListBlock; + + /** @psalm-readonly-allow-private-mutation */ + private int $parentLevel = 1; + + /** @psalm-readonly-allow-private-mutation */ + private ?ListItem $lastListItem = null; + + public function __construct(TableOfContents $toc) + { + $this->parentListBlock = $toc; + } + + public function addItem(int $level, ListItem $listItemToAdd): void + { + while ($level > $this->parentLevel) { + // Descend downwards, creating new ListBlocks if needed, until we reach the correct depth + if ($this->lastListItem === null) { + $this->lastListItem = new ListItem($this->parentListBlock->getListData()); + $this->parentListBlock->appendChild($this->lastListItem); + } + + $newListBlock = new ListBlock($this->parentListBlock->getListData()); + $newListBlock->setStartLine($listItemToAdd->getStartLine()); + $newListBlock->setEndLine($listItemToAdd->getEndLine()); + $this->lastListItem->appendChild($newListBlock); + $this->parentListBlock = $newListBlock; + $this->lastListItem = null; + + $this->parentLevel++; + } + + while ($level < $this->parentLevel) { + // Search upwards for the previous parent list block + $search = $this->parentListBlock; + while ($search = $search->parent()) { + if ($search instanceof ListBlock) { + $this->parentListBlock = $search; + break; + } + } + + $this->parentLevel--; + } + + $this->parentListBlock->appendChild($listItemToAdd); + + $this->lastListItem = $listItemToAdd; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/FlatNormalizerStrategy.php b/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/FlatNormalizerStrategy.php new file mode 100644 index 0000000..8e805ae --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/FlatNormalizerStrategy.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Normalizer; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; + +final class FlatNormalizerStrategy implements NormalizerStrategyInterface +{ + /** @psalm-readonly */ + private TableOfContents $toc; + + public function __construct(TableOfContents $toc) + { + $this->toc = $toc; + } + + public function addItem(int $level, ListItem $listItemToAdd): void + { + $this->toc->appendChild($listItemToAdd); + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/NormalizerStrategyInterface.php b/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/NormalizerStrategyInterface.php new file mode 100644 index 0000000..f30afb1 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/NormalizerStrategyInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Normalizer; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; + +interface NormalizerStrategyInterface +{ + public function addItem(int $level, ListItem $listItemToAdd): void; +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/RelativeNormalizerStrategy.php b/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/RelativeNormalizerStrategy.php new file mode 100644 index 0000000..1b2197f --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/Normalizer/RelativeNormalizerStrategy.php @@ -0,0 +1,67 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents\Normalizer; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; + +final class RelativeNormalizerStrategy implements NormalizerStrategyInterface +{ + /** @psalm-readonly */ + private TableOfContents $toc; + + /** + * @var array<int, ListItem> + * + * @psalm-readonly-allow-private-mutation + */ + private array $listItemStack = []; + + public function __construct(TableOfContents $toc) + { + $this->toc = $toc; + } + + public function addItem(int $level, ListItem $listItemToAdd): void + { + $previousLevel = \array_key_last($this->listItemStack); + + // Pop the stack if we're too deep + while ($previousLevel !== null && $level < $previousLevel) { + \array_pop($this->listItemStack); + $previousLevel = \array_key_last($this->listItemStack); + } + + $lastListItem = \end($this->listItemStack); + + // Need to go one level deeper? Add that level + if ($lastListItem !== false && $level > $previousLevel) { + $targetListBlock = new ListBlock($lastListItem->getListData()); + $targetListBlock->setStartLine($listItemToAdd->getStartLine()); + $targetListBlock->setEndLine($listItemToAdd->getEndLine()); + $lastListItem->appendChild($targetListBlock); + // Otherwise we're at the right level + // If there's no stack we're adding this item directly to the TOC element + } elseif ($lastListItem === false) { + $targetListBlock = $this->toc; + // Otherwise add it to the last list item + } else { + $targetListBlock = $lastListItem->parent(); + } + + $targetListBlock->appendChild($listItemToAdd); + $this->listItemStack[$level] = $listItemToAdd; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsBuilder.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsBuilder.php new file mode 100644 index 0000000..d77e0e9 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsBuilder.php @@ -0,0 +1,159 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Event\DocumentPreRenderEvent; +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\HeadingPermalink\HeadingPermalink; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsReference; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\NodeIterator; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; +use League\Config\Exception\InvalidConfigurationException; + +final class TableOfContentsBuilder implements ConfigurationAwareInterface +{ + public const POSITION_TOP = 'top'; + public const POSITION_BEFORE_HEADINGS = 'before-headings'; + public const POSITION_PLACEHOLDER = 'placeholder'; + + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function onDocumentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + + $generator = new TableOfContentsGenerator( + (string) $this->config->get('table_of_contents/style'), + (string) $this->config->get('table_of_contents/normalize'), + (int) $this->config->get('table_of_contents/min_heading_level'), + (int) $this->config->get('table_of_contents/max_heading_level'), + (string) $this->config->get('heading_permalink/fragment_prefix'), + ); + + $toc = $generator->generate($document); + if ($toc === null) { + // No linkable headers exist, so no TOC could be generated + return; + } + + // Add custom CSS class(es), if defined + $class = $this->config->get('table_of_contents/html_class'); + if ($class !== null) { + $toc->data->append('attributes/class', $class); + } + + // Add the TOC to the Document + $position = $this->config->get('table_of_contents/position'); + if ($position === self::POSITION_TOP) { + $document->prependChild($toc); + } elseif ($position === self::POSITION_BEFORE_HEADINGS) { + $this->insertBeforeFirstLinkedHeading($document, $toc); + } elseif ($position === self::POSITION_PLACEHOLDER) { + $this->replacePlaceholders($document, $toc); + } else { + throw InvalidConfigurationException::forConfigOption('table_of_contents/position', $position); + } + } + + private function insertBeforeFirstLinkedHeading(Document $document, TableOfContents $toc): void + { + foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof Heading) { + continue; + } + + foreach ($node->children() as $child) { + if ($child instanceof HeadingPermalink) { + $node->insertBefore($toc); + + return; + } + } + } + } + + private function replacePlaceholders(Document $document, TableOfContents $toc): void + { + $maxEntries = $this->config->get('table_of_contents/max_placeholder_entries'); + \assert(\is_int($maxEntries) || $maxEntries === null); + $perCopy = $maxEntries === null ? 0 : self::countEntries($toc); + $cache = new TableOfContentsRenderCache(); + $entries = 0; + $anchored = false; + + foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + // Add the block once we find a placeholder + if (! $node instanceof TableOfContentsPlaceholder) { + continue; + } + + // Leave any remaining placeholders as-is once the entry budget is spent + if ($maxEntries !== null && $entries + $perCopy > $maxEntries) { + continue; + } + + // The first placeholder receives the table of contents itself, so that it remains + // part of the document; the rest share the single result of rendering it + if ($anchored) { + $node->replaceWith(new TableOfContentsReference($toc, $cache)); + } else { + $node->replaceWith($toc); + $anchored = true; + } + + $entries += $perCopy; + } + } + + public function onDocumentPreRender(DocumentPreRenderEvent $event): void + { + // The shared references are an HTML rendering optimization; other formats + // (like XML) walk the node tree directly and expect complete copies + if ($event->getFormat() === 'html') { + return; + } + + foreach ($event->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof TableOfContentsReference) { + continue; + } + + $node->replaceWith(clone $node->getTableOfContents()); + } + } + + private static function countEntries(TableOfContents $toc): int + { + $count = 0; + foreach ($toc->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if ($node instanceof ListItem) { + $count++; + } + } + + return $count; + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsExtension.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsExtension.php new file mode 100644 index 0000000..5fab819 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsExtension.php @@ -0,0 +1,62 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Event\DocumentPreRenderEvent; +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Renderer\Block\ListBlockRenderer; +use League\CommonMark\Extension\ConfigurableExtensionInterface; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsReference; +use League\Config\ConfigurationBuilderInterface; +use Nette\Schema\Expect; + +final class TableOfContentsExtension implements ConfigurableExtensionInterface +{ + public function configureSchema(ConfigurationBuilderInterface $builder): void + { + $builder->addSchema('table_of_contents', Expect::structure([ + 'position' => Expect::anyOf(TableOfContentsBuilder::POSITION_BEFORE_HEADINGS, TableOfContentsBuilder::POSITION_PLACEHOLDER, TableOfContentsBuilder::POSITION_TOP)->default(TableOfContentsBuilder::POSITION_TOP), + 'style' => Expect::anyOf(ListBlock::TYPE_BULLET, ListBlock::TYPE_ORDERED)->default(ListBlock::TYPE_BULLET), + 'normalize' => Expect::anyOf(TableOfContentsGenerator::NORMALIZE_RELATIVE, TableOfContentsGenerator::NORMALIZE_FLAT, TableOfContentsGenerator::NORMALIZE_DISABLED)->default(TableOfContentsGenerator::NORMALIZE_RELATIVE), + 'min_heading_level' => Expect::int()->min(1)->max(6)->default(1), + 'max_heading_level' => Expect::int()->min(1)->max(6)->default(6), + 'html_class' => Expect::string()->default('table-of-contents'), + 'placeholder' => Expect::anyOf(Expect::string(), Expect::null())->default(null), + 'max_placeholder_entries' => Expect::anyOf(Expect::int()->min(0), Expect::null())->default(null), + ])); + } + + public function register(EnvironmentBuilderInterface $environment): void + { + $builder = new TableOfContentsBuilder(); + + $environment->addRenderer(TableOfContents::class, new TableOfContentsRenderer(new ListBlockRenderer())); + $environment->addEventListener(DocumentParsedEvent::class, [$builder, 'onDocumentParsed'], -150); + + // phpcs:ignore SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($environment->getConfiguration()->get('table_of_contents/position') === TableOfContentsBuilder::POSITION_PLACEHOLDER) { + $environment->addBlockStartParser(TableOfContentsPlaceholderParser::blockStartParser(), 200); + // If a placeholder cannot be replaced with a TOC element this renderer will ensure the parser won't error out + $environment->addRenderer(TableOfContentsPlaceholder::class, new TableOfContentsPlaceholderRenderer()); + // Placeholders become lightweight references to a single shared TOC which is only rendered once + $environment->addRenderer(TableOfContentsReference::class, new TableOfContentsReferenceRenderer()); + // Non-HTML formats walk the node tree directly, so expand the references back into complete copies there + $environment->addEventListener(DocumentPreRenderEvent::class, [$builder, 'onDocumentPreRender']); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGenerator.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGenerator.php new file mode 100644 index 0000000..6d98f45 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGenerator.php @@ -0,0 +1,164 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Extension\CommonMark\Node\Block\Heading; +use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock; +use League\CommonMark\Extension\CommonMark\Node\Block\ListData; +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; +use League\CommonMark\Extension\HeadingPermalink\HeadingPermalink; +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; +use League\CommonMark\Extension\TableOfContents\Normalizer\AsIsNormalizerStrategy; +use League\CommonMark\Extension\TableOfContents\Normalizer\FlatNormalizerStrategy; +use League\CommonMark\Extension\TableOfContents\Normalizer\NormalizerStrategyInterface; +use League\CommonMark\Extension\TableOfContents\Normalizer\RelativeNormalizerStrategy; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\NodeIterator; +use League\CommonMark\Node\RawMarkupContainerInterface; +use League\CommonMark\Node\StringContainerHelper; +use League\Config\Exception\InvalidConfigurationException; + +final class TableOfContentsGenerator implements TableOfContentsGeneratorInterface +{ + public const STYLE_BULLET = ListBlock::TYPE_BULLET; + public const STYLE_ORDERED = ListBlock::TYPE_ORDERED; + + public const NORMALIZE_DISABLED = 'as-is'; + public const NORMALIZE_RELATIVE = 'relative'; + public const NORMALIZE_FLAT = 'flat'; + + /** @psalm-readonly */ + private string $style; + + /** @psalm-readonly */ + private string $normalizationStrategy; + + /** @psalm-readonly */ + private int $minHeadingLevel; + + /** @psalm-readonly */ + private int $maxHeadingLevel; + + /** @psalm-readonly */ + private string $fragmentPrefix; + + public function __construct(string $style, string $normalizationStrategy, int $minHeadingLevel, int $maxHeadingLevel, string $fragmentPrefix) + { + $this->style = $style; + $this->normalizationStrategy = $normalizationStrategy; + $this->minHeadingLevel = $minHeadingLevel; + $this->maxHeadingLevel = $maxHeadingLevel; + $this->fragmentPrefix = $fragmentPrefix === '' ? '' : $fragmentPrefix . '-'; + } + + public function generate(Document $document): ?TableOfContents + { + $toc = $this->createToc($document); + + $normalizer = $this->getNormalizer($toc); + + $firstHeading = null; + + foreach ($this->getHeadingLinks($document) as $headingLink) { + $heading = $headingLink->parent(); + // Make sure this is actually tied to a heading + if (! $heading instanceof Heading) { + continue; + } + + // Skip any headings outside the configured min/max levels + if ($heading->getLevel() < $this->minHeadingLevel || $heading->getLevel() > $this->maxHeadingLevel) { + continue; + } + + // Keep track of the first heading we see - we might need this later + $firstHeading ??= $heading; + + // Keep track of the start and end lines + $toc->setStartLine($firstHeading->getStartLine()); + $toc->setEndLine($heading->getEndLine()); + + // Create the new link + $link = new Link('#' . $this->fragmentPrefix . $headingLink->getSlug(), StringContainerHelper::getChildText($heading, [RawMarkupContainerInterface::class])); + + $listItem = new ListItem($toc->getListData()); + $listItem->setStartLine($heading->getStartLine()); + $listItem->setEndLine($heading->getEndLine()); + $listItem->appendChild($link); + + // Add it to the correct place + $normalizer->addItem($heading->getLevel(), $listItem); + } + + // Don't add the TOC if no headings were present + if (! $toc->hasChildren() || $firstHeading === null) { + return null; + } + + return $toc; + } + + private function createToc(Document $document): TableOfContents + { + $listData = new ListData(); + + if ($this->style === self::STYLE_BULLET) { + $listData->type = ListBlock::TYPE_BULLET; + } elseif ($this->style === self::STYLE_ORDERED) { + $listData->type = ListBlock::TYPE_ORDERED; + } else { + throw new InvalidConfigurationException(\sprintf('Invalid table of contents list style: "%s"', $this->style)); + } + + $toc = new TableOfContents($listData); + + $toc->setStartLine($document->getStartLine()); + $toc->setEndLine($document->getEndLine()); + + return $toc; + } + + /** + * @return iterable<HeadingPermalink> + */ + private function getHeadingLinks(Document $document): iterable + { + foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) { + if (! $node instanceof Heading) { + continue; + } + + foreach ($node->children() as $child) { + if ($child instanceof HeadingPermalink) { + yield $child; + } + } + } + } + + private function getNormalizer(TableOfContents $toc): NormalizerStrategyInterface + { + switch ($this->normalizationStrategy) { + case self::NORMALIZE_DISABLED: + return new AsIsNormalizerStrategy($toc); + case self::NORMALIZE_RELATIVE: + return new RelativeNormalizerStrategy($toc); + case self::NORMALIZE_FLAT: + return new FlatNormalizerStrategy($toc); + default: + throw new InvalidConfigurationException(\sprintf('Invalid table of contents normalization strategy: "%s"', $this->normalizationStrategy)); + } + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGeneratorInterface.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGeneratorInterface.php new file mode 100644 index 0000000..64ecb8e --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsGeneratorInterface.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Extension\TableOfContents\Node\TableOfContents; +use League\CommonMark\Node\Block\Document; + +interface TableOfContentsGeneratorInterface +{ + public function generate(Document $document): ?TableOfContents; +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderParser.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderParser.php new file mode 100644 index 0000000..3271e51 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderParser.php @@ -0,0 +1,74 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder; +use League\CommonMark\Parser\Block\AbstractBlockContinueParser; +use League\CommonMark\Parser\Block\BlockContinue; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class TableOfContentsPlaceholderParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private TableOfContentsPlaceholder $block; + + public function __construct() + { + $this->block = new TableOfContentsPlaceholder(); + } + + public function getBlock(): TableOfContentsPlaceholder + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::none(); + } + + public static function blockStartParser(): BlockStartParserInterface + { + return new class () implements BlockStartParserInterface, ConfigurationAwareInterface { + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + $placeholder = $this->config->get('table_of_contents/placeholder'); + if ($placeholder === null) { + return BlockStart::none(); + } + + // The placeholder must be the only thing on the line + if ($cursor->matchInPlace('/\G' . \preg_quote($placeholder, '/') . '$/') === null) { + return BlockStart::none(); + } + + return BlockStart::of(new TableOfContentsPlaceholderParser())->at($cursor); + } + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + }; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderRenderer.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderRenderer.php new file mode 100644 index 0000000..0366cb9 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsPlaceholderRenderer.php @@ -0,0 +1,40 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableOfContentsPlaceholderRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + return '<!-- table of contents -->'; + } + + public function getXmlTagName(Node $node): string + { + return 'table_of_contents_placeholder'; + } + + /** + * @return array<string, scalar> + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsReferenceRenderer.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsReferenceRenderer.php new file mode 100644 index 0000000..34b102c --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsReferenceRenderer.php @@ -0,0 +1,44 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsReference; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; + +final class TableOfContentsReferenceRenderer implements NodeRendererInterface +{ + /** + * @param TableOfContentsReference $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + TableOfContentsReference::assertInstanceOf($node); + + $cache = $node->getRenderCache(); + + $html = $cache->getHtml(); + if ($html === null) { + $html = $childRenderer->renderNodes([$node->getTableOfContents()]); + $cache->setHtml($html); + } + + return $html; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderCache.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderCache.php new file mode 100644 index 0000000..fb86aaa --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderCache.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +/** + * Caches the rendered HTML of a document's table of contents so all placeholders can share a single render + * + * @internal + */ +final class TableOfContentsRenderCache +{ + private ?string $html = null; + + public function getHtml(): ?string + { + return $this->html; + } + + public function setHtml(string $html): void + { + $this->html = $html; + } +} diff --git a/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderer.php b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderer.php new file mode 100644 index 0000000..da1b698 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TableOfContents/TableOfContentsRenderer.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TableOfContents; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TableOfContentsRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** @var NodeRendererInterface&XmlNodeRendererInterface */ + private $innerRenderer; + + /** + * @psalm-param NodeRendererInterface&XmlNodeRendererInterface $innerRenderer + * + * @phpstan-param NodeRendererInterface&XmlNodeRendererInterface $innerRenderer + */ + public function __construct(NodeRendererInterface $innerRenderer) + { + $this->innerRenderer = $innerRenderer; + } + + /** + * {@inheritDoc} + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + return $this->innerRenderer->render($node, $childRenderer); + } + + public function getXmlTagName(Node $node): string + { + return 'table_of_contents'; + } + + /** + * @return array<string, scalar> + */ + public function getXmlAttributes(Node $node): array + { + return $this->innerRenderer->getXmlAttributes($node); + } +} diff --git a/vendor/league/commonmark/src/Extension/TaskList/TaskListExtension.php b/vendor/league/commonmark/src/Extension/TaskList/TaskListExtension.php new file mode 100644 index 0000000..bf4b0d2 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TaskList/TaskListExtension.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TaskList; + +use League\CommonMark\Environment\EnvironmentBuilderInterface; +use League\CommonMark\Extension\ExtensionInterface; + +final class TaskListExtension implements ExtensionInterface +{ + public function register(EnvironmentBuilderInterface $environment): void + { + $environment->addInlineParser(new TaskListItemMarkerParser(), 35); + $environment->addRenderer(TaskListItemMarker::class, new TaskListItemMarkerRenderer()); + } +} diff --git a/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarker.php b/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarker.php new file mode 100644 index 0000000..125ae40 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarker.php @@ -0,0 +1,39 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TaskList; + +use League\CommonMark\Node\Inline\AbstractInline; + +final class TaskListItemMarker extends AbstractInline +{ + /** @psalm-readonly-allow-private-mutation */ + private bool $checked; + + public function __construct(bool $isCompleted) + { + parent::__construct(); + + $this->checked = $isCompleted; + } + + public function isChecked(): bool + { + return $this->checked; + } + + public function setChecked(bool $checked): void + { + $this->checked = $checked; + } +} diff --git a/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php b/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php new file mode 100644 index 0000000..0d92a12 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php @@ -0,0 +1,58 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TaskList; + +use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; +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 +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::oneOf('[ ]', '[x]'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $container = $inlineContext->getContainer(); + + // Checkbox must come at the beginning of the first paragraph of the list item + if ($container->hasChildren() || ! ($container instanceof Paragraph && $container->parent() && $container->parent() instanceof ListItem)) { + return false; + } + + $cursor = $inlineContext->getCursor(); + $oldState = $cursor->saveState(); + + $cursor->advanceBy(3); + + // 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; + } + + $isChecked = $inlineContext->getFullMatch() !== '[ ]'; + + $container->appendChild(new TaskListItemMarker($isChecked)); + + return true; + } +} diff --git a/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerRenderer.php b/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerRenderer.php new file mode 100644 index 0000000..a1eb745 --- /dev/null +++ b/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerRenderer.php @@ -0,0 +1,70 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Extension\TaskList; + +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TaskListItemMarkerRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param TaskListItemMarker $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable + { + TaskListItemMarker::assertInstanceOf($node); + + $attrs = $node->data->get('attributes'); + $checkbox = new HtmlElement('input', $attrs, '', true); + + if ($node->isChecked()) { + $checkbox->setAttribute('checked', ''); + } + + $checkbox->setAttribute('disabled', ''); + $checkbox->setAttribute('type', 'checkbox'); + + return $checkbox; + } + + public function getXmlTagName(Node $node): string + { + return 'task_list_item_marker'; + } + + /** + * @param TaskListItemMarker $node + * + * @return array<string, scalar> + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlAttributes(Node $node): array + { + TaskListItemMarker::assertInstanceOf($node); + + if ($node->isChecked()) { + return ['checked' => 'checked']; + } + + return []; + } +} diff --git a/vendor/league/commonmark/src/GithubFlavoredMarkdownConverter.php b/vendor/league/commonmark/src/GithubFlavoredMarkdownConverter.php new file mode 100644 index 0000000..f2524b2 --- /dev/null +++ b/vendor/league/commonmark/src/GithubFlavoredMarkdownConverter.php @@ -0,0 +1,45 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Environment\Environment; +use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; +use League\CommonMark\Extension\GithubFlavoredMarkdownExtension; + +/** + * Converts GitHub Flavored Markdown to HTML. + */ +final class GithubFlavoredMarkdownConverter extends MarkdownConverter +{ + /** + * Create a new Markdown converter pre-configured for GFM + * + * @param array<string, mixed> $config + */ + public function __construct(array $config = []) + { + $environment = new Environment($config); + $environment->addExtension(new CommonMarkCoreExtension()); + $environment->addExtension(new GithubFlavoredMarkdownExtension()); + + parent::__construct($environment); + } + + public function getEnvironment(): Environment + { + \assert($this->environment instanceof Environment); + + return $this->environment; + } +} diff --git a/vendor/league/commonmark/src/Input/MarkdownInput.php b/vendor/league/commonmark/src/Input/MarkdownInput.php new file mode 100644 index 0000000..bbe1618 --- /dev/null +++ b/vendor/league/commonmark/src/Input/MarkdownInput.php @@ -0,0 +1,102 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Input; + +use League\CommonMark\Exception\UnexpectedEncodingException; + +class MarkdownInput implements MarkdownInputInterface +{ + /** + * @var array<int, string>|null + * + * @psalm-readonly-allow-private-mutation + */ + private ?array $lines = null; + + /** @psalm-readonly-allow-private-mutation */ + private string $content; + + /** @psalm-readonly-allow-private-mutation */ + private ?int $lineCount = null; + + /** @psalm-readonly */ + private int $lineOffset; + + public function __construct(string $content, int $lineOffset = 0) + { + if (! \mb_check_encoding($content, 'UTF-8')) { + throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected'); + } + + // Strip any leading UTF-8 BOM + if (\substr($content, 0, 3) === "\xEF\xBB\xBF") { + $content = \substr($content, 3); + } + + $this->content = $content; + $this->lineOffset = $lineOffset; + } + + public function getContent(): string + { + return $this->content; + } + + /** + * {@inheritDoc} + */ + public function getLines(): iterable + { + $this->splitLinesIfNeeded(); + + \assert($this->lines !== null); + + /** @psalm-suppress PossiblyNullIterator */ + foreach ($this->lines as $i => $line) { + yield $this->lineOffset + $i + 1 => $line; + } + } + + public function getLineCount(): int + { + $this->splitLinesIfNeeded(); + + \assert($this->lineCount !== null); + + return $this->lineCount; + } + + private function splitLinesIfNeeded(): void + { + if ($this->lines !== null) { + return; + } + + $lines = \preg_split('/\r\n|\n|\r/', $this->content); + if ($lines === false) { + throw new UnexpectedEncodingException('Failed to split Markdown content by line'); + } + + $this->lines = $lines; + + // Remove any newline which appears at the very end of the string. + // We've already split the document by newlines, so we can simply drop + // any empty element which appears on the end. + if (\end($this->lines) === '') { + \array_pop($this->lines); + } + + $this->lineCount = \count($this->lines); + } +} diff --git a/vendor/league/commonmark/src/Input/MarkdownInputInterface.php b/vendor/league/commonmark/src/Input/MarkdownInputInterface.php new file mode 100644 index 0000000..bb8d6f1 --- /dev/null +++ b/vendor/league/commonmark/src/Input/MarkdownInputInterface.php @@ -0,0 +1,26 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Input; + +interface MarkdownInputInterface +{ + public function getContent(): string; + + /** + * @return iterable<int, string> + */ + public function getLines(): iterable; + + public function getLineCount(): int; +} diff --git a/vendor/league/commonmark/src/MarkdownConverter.php b/vendor/league/commonmark/src/MarkdownConverter.php new file mode 100644 index 0000000..037ecff --- /dev/null +++ b/vendor/league/commonmark/src/MarkdownConverter.php @@ -0,0 +1,93 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Output\RenderedContentInterface; +use League\CommonMark\Parser\MarkdownParser; +use League\CommonMark\Parser\MarkdownParserInterface; +use League\CommonMark\Renderer\HtmlRenderer; +use League\CommonMark\Renderer\MarkdownRendererInterface; + +class MarkdownConverter implements ConverterInterface, MarkdownConverterInterface +{ + /** @psalm-readonly */ + protected EnvironmentInterface $environment; + + /** @psalm-readonly */ + protected MarkdownParserInterface $markdownParser; + + /** @psalm-readonly */ + protected MarkdownRendererInterface $htmlRenderer; + + public function __construct(EnvironmentInterface $environment) + { + $this->environment = $environment; + + $this->markdownParser = new MarkdownParser($environment); + $this->htmlRenderer = new HtmlRenderer($environment); + } + + public function getEnvironment(): EnvironmentInterface + { + return $this->environment; + } + + /** + * Converts Markdown to HTML. + * + * @param string $input The Markdown to convert + * + * @return RenderedContentInterface Rendered HTML + * + * @throws CommonMarkException + */ + public function convert(string $input): RenderedContentInterface + { + $documentAST = $this->markdownParser->parse($input); + + return $this->htmlRenderer->renderDocument($documentAST); + } + + /** + * Converts Markdown to HTML. + * + * @deprecated since 2.2; use {@link convert()} instead + * + * @param string $markdown The Markdown to convert + * + * @return RenderedContentInterface Rendered HTML + * + * @throws CommonMarkException + */ + public function convertToHtml(string $markdown): RenderedContentInterface + { + \trigger_deprecation('league/commonmark', '2.2.0', 'Calling "convertToHtml()" on a %s class is deprecated, use "convert()" instead.', self::class); + + return $this->convert($markdown); + } + + /** + * Converts CommonMark to HTML. + * + * @see MarkdownConverter::convert() + * + * @throws CommonMarkException + */ + public function __invoke(string $markdown): RenderedContentInterface + { + return $this->convert($markdown); + } +} diff --git a/vendor/league/commonmark/src/MarkdownConverterInterface.php b/vendor/league/commonmark/src/MarkdownConverterInterface.php new file mode 100644 index 0000000..a52a286 --- /dev/null +++ b/vendor/league/commonmark/src/MarkdownConverterInterface.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark; + +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Output\RenderedContentInterface; + +/** + * Interface for a service which converts Markdown to HTML. + * + * @deprecated since 2.2; use {@link ConverterInterface} instead + */ +interface MarkdownConverterInterface +{ + /** + * Converts Markdown to HTML. + * + * @deprecated since 2.2; use {@link ConverterInterface::convert()} instead + * + * @throws CommonMarkException + */ + public function convertToHtml(string $markdown): RenderedContentInterface; +} diff --git a/vendor/league/commonmark/src/Node/Block/AbstractBlock.php b/vendor/league/commonmark/src/Node/Block/AbstractBlock.php new file mode 100644 index 0000000..417f89b --- /dev/null +++ b/vendor/league/commonmark/src/Node/Block/AbstractBlock.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Block; + +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Node; + +/** + * Block-level element + * + * @method parent() ?AbstractBlock + */ +abstract class AbstractBlock extends Node +{ + protected ?int $startLine = null; + + protected ?int $endLine = null; + + protected function setParent(?Node $node = null): void + { + if ($node && ! $node instanceof self) { + throw new InvalidArgumentException('Parent of block must also be block (cannot be inline)'); + } + + parent::setParent($node); + } + + public function setStartLine(?int $startLine): void + { + $this->startLine = $startLine; + if ($this->endLine === null) { + $this->endLine = $startLine; + } + } + + public function getStartLine(): ?int + { + return $this->startLine; + } + + public function setEndLine(?int $endLine): void + { + $this->endLine = $endLine; + } + + public function getEndLine(): ?int + { + return $this->endLine; + } +} diff --git a/vendor/league/commonmark/src/Node/Block/Document.php b/vendor/league/commonmark/src/Node/Block/Document.php new file mode 100644 index 0000000..ee7ee44 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Block/Document.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Reference\ReferenceMap; +use League\CommonMark\Reference\ReferenceMapInterface; + +class Document extends AbstractBlock +{ + /** @psalm-readonly */ + protected ReferenceMapInterface $referenceMap; + + public function __construct(?ReferenceMapInterface $referenceMap = null) + { + parent::__construct(); + + $this->setStartLine(1); + + $this->referenceMap = $referenceMap ?? new ReferenceMap(); + } + + public function getReferenceMap(): ReferenceMapInterface + { + return $this->referenceMap; + } + + public function canContain(AbstractBlock $block): bool + { + return true; + } + + public function isCode(): bool + { + return false; + } + + public function matchesNextLine(Cursor $cursor): bool + { + return true; + } +} diff --git a/vendor/league/commonmark/src/Node/Block/Paragraph.php b/vendor/league/commonmark/src/Node/Block/Paragraph.php new file mode 100644 index 0000000..d06d84e --- /dev/null +++ b/vendor/league/commonmark/src/Node/Block/Paragraph.php @@ -0,0 +1,23 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Block; + +class Paragraph extends AbstractBlock +{ + /** @internal */ + public bool $onlyContainsLinkReferenceDefinitions = false; +} diff --git a/vendor/league/commonmark/src/Node/Block/TightBlockInterface.php b/vendor/league/commonmark/src/Node/Block/TightBlockInterface.php new file mode 100644 index 0000000..21a5868 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Block/TightBlockInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Block; + +interface TightBlockInterface +{ + public function isTight(): bool; + + public function setTight(bool $tight): void; +} diff --git a/vendor/league/commonmark/src/Node/Inline/AbstractInline.php b/vendor/league/commonmark/src/Node/Inline/AbstractInline.php new file mode 100644 index 0000000..d3705b4 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Inline/AbstractInline.php @@ -0,0 +1,23 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +use League\CommonMark\Node\Node; + +abstract class AbstractInline extends Node +{ +} diff --git a/vendor/league/commonmark/src/Node/Inline/AbstractStringContainer.php b/vendor/league/commonmark/src/Node/Inline/AbstractStringContainer.php new file mode 100644 index 0000000..f0aab84 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Inline/AbstractStringContainer.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +use League\CommonMark\Node\StringContainerInterface; + +abstract class AbstractStringContainer extends AbstractInline implements StringContainerInterface +{ + protected string $literal = ''; + + /** + * @param array<string, mixed> $data + */ + public function __construct(string $contents = '', array $data = []) + { + parent::__construct(); + + $this->literal = $contents; + if (\count($data) > 0) { + $this->data->import($data); + } + } + + public function getLiteral(): string + { + return $this->literal; + } + + public function setLiteral(string $literal): void + { + $this->literal = $literal; + } +} diff --git a/vendor/league/commonmark/src/Node/Inline/AdjacentTextMerger.php b/vendor/league/commonmark/src/Node/Inline/AdjacentTextMerger.php new file mode 100644 index 0000000..7d82e63 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Inline/AdjacentTextMerger.php @@ -0,0 +1,101 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Additional emphasis processing code based on commonmark-java (https://github.com/atlassian/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +use League\CommonMark\Node\Node; + +/** + * @internal + */ +final class AdjacentTextMerger +{ + public static function mergeChildNodes(Node $node): void + { + // No children or just one child node, no need for merging + if ($node->firstChild() === $node->lastChild() || $node->firstChild() === null || $node->lastChild() === null) { + return; + } + + /** @psalm-suppress PossiblyNullArgument */ + self::mergeTextNodesInclusive($node->firstChild(), $node->lastChild()); + } + + public static function mergeTextNodesBetweenExclusive(Node $fromNode, Node $toNode): void + { + // No nodes between them + if ($fromNode === $toNode || $fromNode->next() === $toNode || $fromNode->next() === null || $toNode->previous() === null) { + return; + } + + /** @psalm-suppress PossiblyNullArgument */ + self::mergeTextNodesInclusive($fromNode->next(), $toNode->previous()); + } + + public static function mergeWithDirectlyAdjacentNodes(Text $node): void + { + $start = ($previous = $node->previous()) instanceof Text ? $previous : $node; + $end = ($next = $node->next()) instanceof Text ? $next : $node; + + self::mergeIfNeeded($start, $end); + } + + private static function mergeTextNodesInclusive(Node $fromNode, Node $toNode): void + { + $first = null; + $last = null; + + $node = $fromNode; + while ($node !== null) { + if ($node instanceof Text) { + if ($first === null) { + $first = $node; + } + + $last = $node; + } else { + self::mergeIfNeeded($first, $last); + $first = null; + $last = null; + } + + if ($node === $toNode) { + break; + } + + $node = $node->next(); + } + + self::mergeIfNeeded($first, $last); + } + + private static function mergeIfNeeded(?Text $first, ?Text $last): void + { + if ($first === null || $last === null || $first === $last) { + // No merging needed + return; + } + + $node = $first->next(); + $stop = $last->next(); + while ($node !== $stop && $node instanceof Text) { + $first->append($node->getLiteral()); + $unlink = $node; + $node = $node->next(); + $unlink->detach(); + } + } +} diff --git a/vendor/league/commonmark/src/Node/Inline/DelimitedInterface.php b/vendor/league/commonmark/src/Node/Inline/DelimitedInterface.php new file mode 100644 index 0000000..89773fa --- /dev/null +++ b/vendor/league/commonmark/src/Node/Inline/DelimitedInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +interface DelimitedInterface +{ + public function getOpeningDelimiter(): string; + + public function getClosingDelimiter(): string; +} diff --git a/vendor/league/commonmark/src/Node/Inline/Newline.php b/vendor/league/commonmark/src/Node/Inline/Newline.php new file mode 100644 index 0000000..68790de --- /dev/null +++ b/vendor/league/commonmark/src/Node/Inline/Newline.php @@ -0,0 +1,40 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +final class Newline extends AbstractInline +{ + // Any changes to these constants should be reflected in .phpstorm.meta.php + public const HARDBREAK = 0; + public const SOFTBREAK = 1; + + /** @psalm-readonly */ + private int $type; + + public function __construct(int $breakType = self::HARDBREAK) + { + parent::__construct(); + + $this->type = $breakType; + } + + /** @psalm-immutable */ + public function getType(): int + { + return $this->type; + } +} diff --git a/vendor/league/commonmark/src/Node/Inline/Text.php b/vendor/league/commonmark/src/Node/Inline/Text.php new file mode 100644 index 0000000..31387f9 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Inline/Text.php @@ -0,0 +1,25 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Inline; + +final class Text extends AbstractStringContainer +{ + public function append(string $literal): void + { + $this->literal .= $literal; + } +} diff --git a/vendor/league/commonmark/src/Node/Node.php b/vendor/league/commonmark/src/Node/Node.php new file mode 100644 index 0000000..1481150 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Node.php @@ -0,0 +1,266 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +use Dflydev\DotAccessData\Data; +use League\CommonMark\Exception\InvalidArgumentException; + +abstract class Node +{ + /** @psalm-readonly-allow-private-mutation */ + public Data $data; + + /** @psalm-readonly-allow-private-mutation */ + protected int $depth = 0; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $parent = null; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $previous = null; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $next = null; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $firstChild = null; + + /** @psalm-readonly-allow-private-mutation */ + protected ?Node $lastChild = null; + + public function __construct() + { + $this->data = new Data([ + 'attributes' => [], + ]); + } + + public function previous(): ?Node + { + return $this->previous; + } + + public function next(): ?Node + { + return $this->next; + } + + public function parent(): ?Node + { + return $this->parent; + } + + protected function setParent(?Node $node = null): void + { + $this->parent = $node; + $this->depth = $node === null ? 0 : $node->depth + 1; + } + + /** + * Inserts the $sibling node after $this + */ + public function insertAfter(Node $sibling): void + { + $sibling->detach(); + $sibling->next = $this->next; + + if ($sibling->next) { + $sibling->next->previous = $sibling; + } + + $sibling->previous = $this; + $this->next = $sibling; + $sibling->setParent($this->parent); + + if (! $sibling->next && $sibling->parent) { + $sibling->parent->lastChild = $sibling; + } + } + + /** + * Inserts the $sibling node before $this + */ + public function insertBefore(Node $sibling): void + { + $sibling->detach(); + $sibling->previous = $this->previous; + + if ($sibling->previous) { + $sibling->previous->next = $sibling; + } + + $sibling->next = $this; + $this->previous = $sibling; + $sibling->setParent($this->parent); + + if (! $sibling->previous && $sibling->parent) { + $sibling->parent->firstChild = $sibling; + } + } + + public function replaceWith(Node $replacement): void + { + $replacement->detach(); + $this->insertAfter($replacement); + $this->detach(); + } + + public function detach(): void + { + if ($this->previous) { + $this->previous->next = $this->next; + } elseif ($this->parent) { + $this->parent->firstChild = $this->next; + } + + if ($this->next) { + $this->next->previous = $this->previous; + } elseif ($this->parent) { + $this->parent->lastChild = $this->previous; + } + + $this->parent = null; + $this->next = null; + $this->previous = null; + $this->depth = 0; + } + + public function hasChildren(): bool + { + return $this->firstChild !== null; + } + + public function firstChild(): ?Node + { + return $this->firstChild; + } + + public function lastChild(): ?Node + { + return $this->lastChild; + } + + /** + * @return Node[] + */ + public function children(): iterable + { + $children = []; + for ($current = $this->firstChild; $current !== null; $current = $current->next) { + $children[] = $current; + } + + return $children; + } + + public function appendChild(Node $child): void + { + if ($this->lastChild) { + $this->lastChild->insertAfter($child); + } else { + $child->detach(); + $child->setParent($this); + $this->lastChild = $this->firstChild = $child; + } + } + + /** + * Adds $child as the very first child of $this + */ + public function prependChild(Node $child): void + { + if ($this->firstChild) { + $this->firstChild->insertBefore($child); + } else { + $child->detach(); + $child->setParent($this); + $this->lastChild = $this->firstChild = $child; + } + } + + /** + * Detaches all child nodes of given node + */ + public function detachChildren(): void + { + foreach ($this->children() as $children) { + $children->setParent(null); + } + + $this->firstChild = $this->lastChild = null; + } + + /** + * Replace all children of given node with collection of another + * + * @param iterable<Node> $children + */ + public function replaceChildren(iterable $children): void + { + $this->detachChildren(); + foreach ($children as $item) { + $this->appendChild($item); + } + } + + public function getDepth(): int + { + return $this->depth; + } + + public function walker(): NodeWalker + { + return new NodeWalker($this); + } + + public function iterator(int $flags = 0): NodeIterator + { + return new NodeIterator($this, $flags); + } + + /** + * Clone the current node and its children + * + * WARNING: This is a recursive function and should not be called on deeply-nested node trees! + */ + public function __clone() + { + // Cloned nodes are detached from their parents, siblings, and children + $this->parent = null; + $this->previous = null; + $this->next = null; + // But save a copy of the children since we'll need that in a moment. + // Those children still belong to the node being cloned, so only this copy's own links may be dropped. + $children = $this->children(); + $this->firstChild = $this->lastChild = null; + + // The original children get cloned and re-added + foreach ($children as $child) { + $this->appendChild(clone $child); + } + + // The data belongs to a single node, so the two nodes each need their own copy + $this->data = clone $this->data; + } + + public static function assertInstanceOf(Node $node): void + { + if (! $node instanceof static) { + throw new InvalidArgumentException(\sprintf('Incompatible node type: expected %s, got %s', static::class, \get_class($node))); + } + } +} diff --git a/vendor/league/commonmark/src/Node/NodeIterator.php b/vendor/league/commonmark/src/Node/NodeIterator.php new file mode 100644 index 0000000..3d295ef --- /dev/null +++ b/vendor/league/commonmark/src/Node/NodeIterator.php @@ -0,0 +1,58 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +/** + * @implements \IteratorAggregate<int, Node> + */ +final class NodeIterator implements \IteratorAggregate +{ + public const FLAG_BLOCKS_ONLY = 1; + + private Node $node; + private bool $blocksOnly; + + public function __construct(Node $node, int $flags = 0) + { + $this->node = $node; + $this->blocksOnly = ($flags & self::FLAG_BLOCKS_ONLY) === self::FLAG_BLOCKS_ONLY; + } + + /** + * @return \Generator<int, Node> + */ + public function getIterator(): \Generator + { + $stack = [$this->node]; + $index = 0; + + while ($stack) { + $node = \array_pop($stack); + + yield $index++ => $node; + + // Push all children onto the stack in reverse order + $child = $node->lastChild(); + while ($child !== null) { + if (! $this->blocksOnly || $child instanceof AbstractBlock) { + $stack[] = $child; + } + + $child = $child->previous(); + } + } + } +} diff --git a/vendor/league/commonmark/src/Node/NodeWalker.php b/vendor/league/commonmark/src/Node/NodeWalker.php new file mode 100644 index 0000000..6f922e8 --- /dev/null +++ b/vendor/league/commonmark/src/Node/NodeWalker.php @@ -0,0 +1,80 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +use League\CommonMark\Node\Block\AbstractBlock; + +final class NodeWalker +{ + /** @psalm-readonly */ + private Node $root; + + /** @psalm-readonly-allow-private-mutation */ + private ?Node $current = null; + + /** @psalm-readonly-allow-private-mutation */ + private bool $entering; + + public function __construct(Node $root) + { + $this->root = $root; + $this->current = $this->root; + $this->entering = true; + } + + /** + * Returns an event which contains node and entering flag + * (entering is true when we enter a Node from a parent or sibling, + * and false when we reenter it from child) + */ + public function next(): ?NodeWalkerEvent + { + $current = $this->current; + $entering = $this->entering; + if ($current === null) { + return null; + } + + if ($entering && ($current instanceof AbstractBlock || $current->hasChildren())) { + if ($current->firstChild()) { + $this->current = $current->firstChild(); + $this->entering = true; + } else { + $this->entering = false; + } + } elseif ($current === $this->root) { + $this->current = null; + } elseif ($current->next() === null) { + $this->current = $current->parent(); + $this->entering = false; + } else { + $this->current = $current->next(); + $this->entering = true; + } + + return new NodeWalkerEvent($current, $entering); + } + + /** + * Resets the iterator to resume at the specified node + */ + public function resumeAt(Node $node, bool $entering = true): void + { + $this->current = $node; + $this->entering = $entering; + } +} diff --git a/vendor/league/commonmark/src/Node/NodeWalkerEvent.php b/vendor/league/commonmark/src/Node/NodeWalkerEvent.php new file mode 100644 index 0000000..773ec3a --- /dev/null +++ b/vendor/league/commonmark/src/Node/NodeWalkerEvent.php @@ -0,0 +1,42 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +final class NodeWalkerEvent +{ + /** @psalm-readonly */ + private Node $node; + + /** @psalm-readonly */ + private bool $isEntering; + + public function __construct(Node $node, bool $isEntering = true) + { + $this->node = $node; + $this->isEntering = $isEntering; + } + + public function getNode(): Node + { + return $this->node; + } + + public function isEntering(): bool + { + return $this->isEntering; + } +} diff --git a/vendor/league/commonmark/src/Node/Query.php b/vendor/league/commonmark/src/Node/Query.php new file mode 100644 index 0000000..7e76fe3 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Query.php @@ -0,0 +1,139 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +use League\CommonMark\Node\Query\AndExpr; +use League\CommonMark\Node\Query\OrExpr; + +final class Query +{ + /** @var callable(Node): bool $condition */ + private $condition; + + public function __construct() + { + $this->condition = new AndExpr(); + } + + public function where(callable ...$conditions): self + { + return $this->andWhere(...$conditions); + } + + public function andWhere(callable ...$conditions): self + { + if ($this->condition instanceof AndExpr) { + foreach ($conditions as $condition) { + $this->condition->add($condition); + } + } else { + $this->condition = new AndExpr($this->condition, ...$conditions); + } + + return $this; + } + + public function orWhere(callable ...$conditions): self + { + if ($this->condition instanceof OrExpr) { + foreach ($conditions as $condition) { + $this->condition->add($condition); + } + } else { + $this->condition = new OrExpr($this->condition, ...$conditions); + } + + return $this; + } + + public function findOne(Node $node): ?Node + { + foreach ($node->iterator() as $n) { + if (\call_user_func($this->condition, $n)) { + return $n; + } + } + + return null; + } + + /** + * @return iterable<Node> + */ + public function findAll(Node $node, ?int $limit = PHP_INT_MAX): iterable + { + $resultCount = 0; + + foreach ($node->iterator() as $n) { + if ($resultCount >= $limit) { + break; + } + + if (! \call_user_func($this->condition, $n)) { + continue; + } + + ++$resultCount; + + yield $n; + } + } + + /** + * @return callable(Node): bool + */ + public static function type(string $class): callable + { + return static fn (Node $node): bool => $node instanceof $class; + } + + /** + * @psalm-param ?callable(Node): bool $condition + * + * @return callable(Node): bool + */ + public static function hasChild(?callable $condition = null): callable + { + return static function (Node $node) use ($condition): bool { + foreach ($node->children() as $child) { + if ($condition === null || $condition($child)) { + return true; + } + } + + return false; + }; + } + + /** + * @psalm-param ?callable(Node): bool $condition + * + * @return callable(Node): bool + */ + public static function hasParent(?callable $condition = null): callable + { + return static function (Node $node) use ($condition): bool { + $parent = $node->parent(); + if ($parent === null) { + return false; + } + + if ($condition === null) { + return true; + } + + return $condition($parent); + }; + } +} diff --git a/vendor/league/commonmark/src/Node/Query/AndExpr.php b/vendor/league/commonmark/src/Node/Query/AndExpr.php new file mode 100644 index 0000000..d2cd615 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Query/AndExpr.php @@ -0,0 +1,55 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Query; + +use League\CommonMark\Node\Node; + +/** + * @internal + */ +final class AndExpr implements ExpressionInterface +{ + /** + * @var callable[] + * @psalm-var list<callable(Node): bool> + */ + private array $conditions; + + /** + * @psalm-param callable(Node): bool $expressions + */ + public function __construct(callable ...$expressions) + { + $this->conditions = \array_values($expressions); + } + + /** + * @param callable(Node): bool $expression + */ + public function add(callable $expression): void + { + $this->conditions[] = $expression; + } + + public function __invoke(Node $node): bool + { + foreach ($this->conditions as $condition) { + if (! $condition($node)) { + return false; + } + } + + return true; + } +} diff --git a/vendor/league/commonmark/src/Node/Query/ExpressionInterface.php b/vendor/league/commonmark/src/Node/Query/ExpressionInterface.php new file mode 100644 index 0000000..2bbbc7f --- /dev/null +++ b/vendor/league/commonmark/src/Node/Query/ExpressionInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Query; + +use League\CommonMark\Node\Node; + +interface ExpressionInterface +{ + public function __invoke(Node $node): bool; +} diff --git a/vendor/league/commonmark/src/Node/Query/OrExpr.php b/vendor/league/commonmark/src/Node/Query/OrExpr.php new file mode 100644 index 0000000..b0baad8 --- /dev/null +++ b/vendor/league/commonmark/src/Node/Query/OrExpr.php @@ -0,0 +1,55 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node\Query; + +use League\CommonMark\Node\Node; + +/** + * @internal + */ +final class OrExpr implements ExpressionInterface +{ + /** + * @var callable[] + * @psalm-var list<callable(Node): bool> + */ + private array $conditions; + + /** + * @psalm-param callable(Node): bool $expressions + */ + public function __construct(callable ...$expressions) + { + $this->conditions = \array_values($expressions); + } + + /** + * @param callable(Node): bool $expression + */ + public function add(callable $expression): void + { + $this->conditions[] = $expression; + } + + public function __invoke(Node $node): bool + { + foreach ($this->conditions as $condition) { + if ($condition($node)) { + return true; + } + } + + return false; + } +} diff --git a/vendor/league/commonmark/src/Node/RawMarkupContainerInterface.php b/vendor/league/commonmark/src/Node/RawMarkupContainerInterface.php new file mode 100644 index 0000000..1545285 --- /dev/null +++ b/vendor/league/commonmark/src/Node/RawMarkupContainerInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +/** + * Interface for a node which contains raw, unprocessed markup (like HTML) + */ +interface RawMarkupContainerInterface extends StringContainerInterface +{ +} diff --git a/vendor/league/commonmark/src/Node/StringContainerHelper.php b/vendor/league/commonmark/src/Node/StringContainerHelper.php new file mode 100644 index 0000000..8e1ec34 --- /dev/null +++ b/vendor/league/commonmark/src/Node/StringContainerHelper.php @@ -0,0 +1,54 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +final class StringContainerHelper +{ + /** + * Extract text literals from all descendant nodes + * + * @param Node $node Parent node + * @param array<string> $excludeTypes Optional list of node class types to exclude + * + * @return string Concatenated literals + */ + public static function getChildText(Node $node, array $excludeTypes = []): string + { + $text = ''; + + foreach ($node->iterator() as $child) { + if ($child instanceof StringContainerInterface && ! self::isOneOf($child, $excludeTypes)) { + $text .= $child->getLiteral(); + } + } + + return $text; + } + + /** + * @param string[] $classesOrInterfacesToCheck + * + * @psalm-pure + */ + private static function isOneOf(object $object, array $classesOrInterfacesToCheck): bool + { + foreach ($classesOrInterfacesToCheck as $type) { + if ($object instanceof $type) { + return true; + } + } + + return false; + } +} diff --git a/vendor/league/commonmark/src/Node/StringContainerInterface.php b/vendor/league/commonmark/src/Node/StringContainerInterface.php new file mode 100644 index 0000000..23564ae --- /dev/null +++ b/vendor/league/commonmark/src/Node/StringContainerInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Node; + +/** + * Interface for a node which directly contains line(s) of text + */ +interface StringContainerInterface +{ + public function setLiteral(string $literal): void; + + public function getLiteral(): string; +} diff --git a/vendor/league/commonmark/src/Normalizer/SlugNormalizer.php b/vendor/league/commonmark/src/Normalizer/SlugNormalizer.php new file mode 100644 index 0000000..7cfb960 --- /dev/null +++ b/vendor/league/commonmark/src/Normalizer/SlugNormalizer.php @@ -0,0 +1,57 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Normalizer; + +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +/** + * Creates URL-friendly strings based on the given string input + */ +final class SlugNormalizer implements TextNormalizerInterface, ConfigurationAwareInterface +{ + /** @psalm-allow-private-mutation */ + private int $defaultMaxLength = 255; + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->defaultMaxLength = $configuration->get('slug_normalizer/max_length'); + } + + /** + * {@inheritDoc} + * + * @psalm-immutable + */ + public function normalize(string $text, array $context = []): string + { + // Add any requested prefix + $slug = ($context['prefix'] ?? '') . $text; + // Trim whitespace + $slug = \trim($slug); + // Convert to lowercase + $slug = \mb_strtolower($slug, 'UTF-8'); + // Try replacing whitespace with a dash + $slug = \preg_replace('/\s+/u', '-', $slug) ?? $slug; + // Try removing characters other than letters, numbers, and marks. + $slug = \preg_replace('/[^\p{L}\p{Nd}\p{Nl}\p{M}-]+/u', '', $slug) ?? $slug; + // Trim to requested length if given + if ($length = $context['length'] ?? $this->defaultMaxLength) { + $slug = \mb_substr($slug, 0, $length, 'UTF-8'); + } + + // @phpstan-ignore-next-line Because it thinks mb_substr() returns false on PHP 7.4 + return $slug; + } +} diff --git a/vendor/league/commonmark/src/Normalizer/TextNormalizer.php b/vendor/league/commonmark/src/Normalizer/TextNormalizer.php new file mode 100644 index 0000000..43eb117 --- /dev/null +++ b/vendor/league/commonmark/src/Normalizer/TextNormalizer.php @@ -0,0 +1,44 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Normalizer; + +/*** + * Normalize text input using the steps given by the CommonMark spec to normalize labels + * + * @see https://spec.commonmark.org/0.29/#matches + * + * @psalm-immutable + */ +final class TextNormalizer implements TextNormalizerInterface +{ + /** + * {@inheritDoc} + * + * @psalm-pure + */ + public function normalize(string $text, array $context = []): string + { + // Collapse internal whitespace to single space and remove + // leading/trailing whitespace + $text = \preg_replace('/[ \t\r\n]+/', ' ', \trim($text)); + \assert(\is_string($text)); + + // Is it strictly ASCII? If so, we can use strtolower() instead (faster) + if (\mb_check_encoding($text, 'ASCII')) { + return \strtolower($text); + } + + return \mb_convert_case($text, \MB_CASE_FOLD, 'UTF-8'); + } +} diff --git a/vendor/league/commonmark/src/Normalizer/TextNormalizerInterface.php b/vendor/league/commonmark/src/Normalizer/TextNormalizerInterface.php new file mode 100644 index 0000000..f476234 --- /dev/null +++ b/vendor/league/commonmark/src/Normalizer/TextNormalizerInterface.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Normalizer; + +/** + * Creates a normalized version of the given input text + */ +interface TextNormalizerInterface +{ + /** + * @param string $text The text to normalize + * @param array<string, mixed> $context Additional context about the text being normalized (optional) + * + * $context may include (but is not required to include) the following: + * - `prefix` - A string prefix to prepend to each normalized result + * - `length` - The requested maximum length + * - `node` - The node we're normalizing text for + * + * Implementations do not have to use or respect any information within that $context + */ + public function normalize(string $text, array $context = []): string; +} diff --git a/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizer.php b/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizer.php new file mode 100644 index 0000000..fe3635b --- /dev/null +++ b/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizer.php @@ -0,0 +1,83 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Normalizer; + +// phpcs:disable Squiz.Strings.DoubleQuoteUsage.ContainsVar +final class UniqueSlugNormalizer implements UniqueSlugNormalizerInterface +{ + private TextNormalizerInterface $innerNormalizer; + + /** + * Slugs claimed by the surrounding page (in final, normalized form), seeded as if they'd + * already been handed out once, so the first colliding slug gets a "-1" suffix. + * Unlike regular history, these survive clearHistory(). + * + * @var array<string, int> + */ + private array $reserved = []; + + /** + * Every slug we've handed out, mapped to the next numeric suffix to try for it + * + * @var array<string, int> + */ + private array $alreadyUsed; + + /** + * @param iterable<string> $reservedSlugs + */ + public function __construct(TextNormalizerInterface $innerNormalizer, iterable $reservedSlugs = []) + { + $this->innerNormalizer = $innerNormalizer; + + foreach ($reservedSlugs as $slug) { + $this->reserved[$slug] = 1; + } + + $this->alreadyUsed = $this->reserved; + } + + public function clearHistory(): void + { + $this->alreadyUsed = $this->reserved; + } + + /** + * {@inheritDoc} + * + * @psalm-allow-private-mutation + */ + public function normalize(string $text, array $context = []): string + { + $normalized = $this->innerNormalizer->normalize($text, $context); + + // If it's not unique, add an incremental number to the end until we get a unique version. + // Suffixes are handed out in ascending order and are never given back, so we can pick up + // where the previous collision left off instead of re-checking suffixes we know are taken. + if (isset($this->alreadyUsed[$normalized])) { + $suffix = $this->alreadyUsed[$normalized]; + while (isset($this->alreadyUsed["$normalized-$suffix"])) { + ++$suffix; + } + + $this->alreadyUsed[$normalized] = $suffix + 1; + + $normalized = "$normalized-$suffix"; + } + + $this->alreadyUsed[$normalized] = 1; + + return $normalized; + } +} diff --git a/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizerInterface.php b/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizerInterface.php new file mode 100644 index 0000000..642edeb --- /dev/null +++ b/vendor/league/commonmark/src/Normalizer/UniqueSlugNormalizerInterface.php @@ -0,0 +1,28 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Normalizer; + +interface UniqueSlugNormalizerInterface extends TextNormalizerInterface +{ + public const DISABLED = false; + public const PER_ENVIRONMENT = 'environment'; + public const PER_DOCUMENT = 'document'; + + /** + * Called by the Environment whenever the configured scope changes + * + * Currently, this will only be called PER_DOCUMENT. + */ + public function clearHistory(): void; +} diff --git a/vendor/league/commonmark/src/Output/RenderedContent.php b/vendor/league/commonmark/src/Output/RenderedContent.php new file mode 100644 index 0000000..4bf612d --- /dev/null +++ b/vendor/league/commonmark/src/Output/RenderedContent.php @@ -0,0 +1,49 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Output; + +use League\CommonMark\Node\Block\Document; + +class RenderedContent implements RenderedContentInterface, \Stringable +{ + /** @psalm-readonly */ + private Document $document; + + /** @psalm-readonly */ + private string $content; + + public function __construct(Document $document, string $content) + { + $this->document = $document; + $this->content = $content; + } + + public function getDocument(): Document + { + return $this->document; + } + + public function getContent(): string + { + return $this->content; + } + + /** + * @psalm-mutation-free + */ + public function __toString(): string + { + return $this->content; + } +} diff --git a/vendor/league/commonmark/src/Output/RenderedContentInterface.php b/vendor/league/commonmark/src/Output/RenderedContentInterface.php new file mode 100644 index 0000000..2179b1b --- /dev/null +++ b/vendor/league/commonmark/src/Output/RenderedContentInterface.php @@ -0,0 +1,29 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Output; + +use League\CommonMark\Node\Block\Document; + +interface RenderedContentInterface extends \Stringable +{ + /** + * @psalm-mutation-free + */ + public function getDocument(): Document; + + /** + * @psalm-mutation-free + */ + public function getContent(): string; +} diff --git a/vendor/league/commonmark/src/Parser/Block/AbstractBlockContinueParser.php b/vendor/league/commonmark/src/Parser/Block/AbstractBlockContinueParser.php new file mode 100644 index 0000000..889532e --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/AbstractBlockContinueParser.php @@ -0,0 +1,47 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\AbstractBlock; + +/** + * Base class for a block parser + * + * Slightly more convenient to extend from vs. implementing the interface + */ +abstract class AbstractBlockContinueParser implements BlockContinueParserInterface +{ + public function isContainer(): bool + { + return false; + } + + public function canHaveLazyContinuationLines(): bool + { + return false; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return false; + } + + public function addLine(string $line): void + { + } + + public function closeBlock(): void + { + } +} diff --git a/vendor/league/commonmark/src/Parser/Block/BlockContinue.php b/vendor/league/commonmark/src/Parser/Block/BlockContinue.php new file mode 100644 index 0000000..4b5f37d --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/BlockContinue.php @@ -0,0 +1,73 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\CursorState; + +/** + * Result object for continuing parsing of a block; see static methods for constructors. + * + * @psalm-immutable + */ +final class BlockContinue +{ + /** @psalm-readonly */ + private ?CursorState $cursorState = null; + + /** @psalm-readonly */ + private bool $finalize; + + private function __construct(?CursorState $cursorState = null, bool $finalize = false) + { + $this->cursorState = $cursorState; + $this->finalize = $finalize; + } + + public function getCursorState(): ?CursorState + { + return $this->cursorState; + } + + public function isFinalize(): bool + { + return $this->finalize; + } + + /** + * Signal that we cannot continue here + * + * @return null + */ + public static function none(): ?self + { + return null; + } + + /** + * Signal that we're continuing at the given position + */ + public static function at(Cursor $cursor): self + { + return new self($cursor->saveState(), false); + } + + /** + * Signal that we want to finalize and close the block + */ + public static function finished(): self + { + return new self(null, true); + } +} diff --git a/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php b/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php new file mode 100644 index 0000000..d0508a4 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php @@ -0,0 +1,68 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Parser\Cursor; + +/** + * Interface for a block continuation parser + * + * A block continue parser can only handle a single block instance. The current block being parsed is stored within this parser and + * can be returned once parsing has completed. If you need to parse multiple block continuations, instantiate a new parser for each one. + */ +interface BlockContinueParserInterface +{ + /** + * Return the current block being parsed by this parser + */ + public function getBlock(): AbstractBlock; + + /** + * Return whether we are parsing a container block + */ + public function isContainer(): bool; + + /** + * 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; + + /** + * Determine whether the current block being parsed can contain the given child block + */ + public function canContain(AbstractBlock $childBlock): bool; + + /** + * Attempt to parse the given line + */ + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue; + + /** + * Add the given line of text to the current block + */ + public function addLine(string $line): void; + + /** + * Close and finalize the current block + */ + public function closeBlock(): void; +} diff --git a/vendor/league/commonmark/src/Parser/Block/BlockContinueParserWithInlinesInterface.php b/vendor/league/commonmark/src/Parser/Block/BlockContinueParserWithInlinesInterface.php new file mode 100644 index 0000000..6f826c9 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/BlockContinueParserWithInlinesInterface.php @@ -0,0 +1,24 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\InlineParserEngineInterface; + +interface BlockContinueParserWithInlinesInterface extends BlockContinueParserInterface +{ + /** + * Parse any inlines inside of the current block + */ + public function parseInlines(InlineParserEngineInterface $inlineParser): void; +} diff --git a/vendor/league/commonmark/src/Parser/Block/BlockStart.php b/vendor/league/commonmark/src/Parser/Block/BlockStart.php new file mode 100644 index 0000000..5576622 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/BlockStart.php @@ -0,0 +1,124 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\CursorState; + +/** + * Result object for starting parsing of a block; see static methods for constructors + */ +final class BlockStart +{ + /** + * @var BlockContinueParserInterface[] + * + * @psalm-readonly + */ + private array $blockParsers; + + /** @psalm-readonly-allow-private-mutation */ + private ?CursorState $cursorState = null; + + /** @psalm-readonly-allow-private-mutation */ + private bool $replaceActiveBlockParser = false; + + private bool $isAborting = false; + + private function __construct(BlockContinueParserInterface ...$blockParsers) + { + $this->blockParsers = $blockParsers; + } + + /** + * @return BlockContinueParserInterface[] + */ + public function getBlockParsers(): iterable + { + return $this->blockParsers; + } + + public function getCursorState(): ?CursorState + { + return $this->cursorState; + } + + public function isReplaceActiveBlockParser(): bool + { + return $this->replaceActiveBlockParser; + } + + /** + * @internal + */ + public function isAborting(): bool + { + return $this->isAborting; + } + + /** + * Signal that we want to parse at the given cursor position + * + * @return $this + */ + public function at(Cursor $cursor): self + { + $this->cursorState = $cursor->saveState(); + + return $this; + } + + /** + * Signal that we want to replace the active block parser with this one + * + * @return $this + */ + public function replaceActiveBlockParser(): self + { + $this->replaceActiveBlockParser = true; + + return $this; + } + + /** + * Signal that we cannot parse whatever is here + * + * @return null + */ + public static function none(): ?self + { + return null; + } + + /** + * Signal that we'd like to register the given parser(s) so they can parse the current block + */ + public static function of(BlockContinueParserInterface ...$blockParsers): self + { + return new self(...$blockParsers); + } + + /** + * Signal that the block parsing process should be aborted (no other block starts should be checked) + * + * @internal + */ + public static function abort(): self + { + $ret = new self(); + $ret->isAborting = true; + + return $ret; + } +} diff --git a/vendor/league/commonmark/src/Parser/Block/BlockStartParserInterface.php b/vendor/league/commonmark/src/Parser/Block/BlockStartParserInterface.php new file mode 100644 index 0000000..90ed781 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/BlockStartParserInterface.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; + +/** + * Interface for a block parser which identifies block starts. + */ +interface BlockStartParserInterface +{ + /** + * Check whether we should handle the block at the current position + * + * @param Cursor $cursor A cloned copy of the cursor at the current parsing location + * @param MarkdownParserStateInterface $parserState Additional information about the state of the Markdown parser + * + * @return BlockStart|null The BlockStart that has been identified, or null if the block doesn't match here + */ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart; +} diff --git a/vendor/league/commonmark/src/Parser/Block/DocumentBlockParser.php b/vendor/league/commonmark/src/Parser/Block/DocumentBlockParser.php new file mode 100644 index 0000000..c03c24e --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/DocumentBlockParser.php @@ -0,0 +1,80 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Reference\ReferenceMapInterface; + +/** + * Parser implementation which ensures everything is added to the root-level Document + */ +final class DocumentBlockParser extends AbstractBlockContinueParser +{ + /** @psalm-readonly */ + private Document $document; + + public function __construct(ReferenceMapInterface $referenceMap) + { + $this->document = new Document($referenceMap); + } + + public function getBlock(): Document + { + return $this->document; + } + + public function isContainer(): bool + { + return true; + } + + public function canContain(AbstractBlock $childBlock): bool + { + return true; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + return BlockContinue::at($cursor); + } + + public function closeBlock(): void + { + $this->removeLinkReferenceDefinitions(); + } + + private function removeLinkReferenceDefinitions(): void + { + $emptyNodes = []; + + $walker = $this->document->walker(); + while ($event = $walker->next()) { + $node = $event->getNode(); + // TODO for v3: It would be great if we could find an alternate way to identify such paragraphs. + // Unfortunately, we can't simply check for empty paragraphs here because inlines haven't been processed yet, + // meaning all paragraphs will appear blank here, and we don't have a way to check the status of the reference parser + // which is attached to the (already-closed) paragraph parser. + if ($event->isEntering() && $node instanceof Paragraph && $node->onlyContainsLinkReferenceDefinitions) { + $emptyNodes[] = $node; + } + } + + foreach ($emptyNodes as $node) { + $node->detach(); + } + } +} diff --git a/vendor/league/commonmark/src/Parser/Block/ParagraphParser.php b/vendor/league/commonmark/src/Parser/Block/ParagraphParser.php new file mode 100644 index 0000000..f9312be --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/ParagraphParser.php @@ -0,0 +1,85 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\InlineParserEngineInterface; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceParser; + +final class ParagraphParser extends AbstractBlockContinueParser implements BlockContinueParserWithInlinesInterface +{ + /** @psalm-readonly */ + private Paragraph $block; + + /** @psalm-readonly */ + private ReferenceParser $referenceParser; + + public function __construct() + { + $this->block = new Paragraph(); + $this->referenceParser = new ReferenceParser(); + } + + public function canHaveLazyContinuationLines(): bool + { + return true; + } + + public function getBlock(): Paragraph + { + return $this->block; + } + + public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue + { + if ($cursor->isBlank()) { + return BlockContinue::none(); + } + + return BlockContinue::at($cursor); + } + + public function addLine(string $line): void + { + $this->referenceParser->parse($line); + } + + public function closeBlock(): void + { + $this->block->onlyContainsLinkReferenceDefinitions = $this->referenceParser->hasReferences() && $this->referenceParser->getParagraphContent() === ''; + } + + public function parseInlines(InlineParserEngineInterface $inlineParser): void + { + $content = $this->getContentString(); + if ($content !== '') { + $inlineParser->parse($content, $this->block); + } + } + + public function getContentString(): string + { + return $this->referenceParser->getParagraphContent(); + } + + /** + * @return ReferenceInterface[] + */ + public function getReferences(): iterable + { + return $this->referenceParser->getReferences(); + } +} diff --git a/vendor/league/commonmark/src/Parser/Block/SkipLinesStartingWithLettersParser.php b/vendor/league/commonmark/src/Parser/Block/SkipLinesStartingWithLettersParser.php new file mode 100644 index 0000000..95d8bd2 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Block/SkipLinesStartingWithLettersParser.php @@ -0,0 +1,45 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Block; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Parser\MarkdownParserStateInterface; +use League\CommonMark\Util\RegexHelper; + +/** + * @internal + * + * This "parser" is actually a performance optimization. + * + * Most lines in a typical Markdown document probably won't match a block start. This is especially true for lines starting + * with letters - nothing in the core CommonMark spec or our supported extensions will match those lines as blocks. Therefore, + * if we can identify those lines and skip block start parsing, we can optimize performance by ~10%. + * + * Previously this optimization was hard-coded in the MarkdownParser but did not allow users to override this behavior. + * By implementing this optimization as a block parser instead, users wanting custom blocks starting with letters + * can instead register their block parser with a higher priority to ensure their parser is always called first. + */ +final class SkipLinesStartingWithLettersParser implements BlockStartParserInterface +{ + public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart + { + if (! $cursor->isIndented() && RegexHelper::isLetter($cursor->getNextNonSpaceCharacter())) { + $cursor->advanceToNextNonSpaceOrTab(); + + return BlockStart::abort(); + } + + return BlockStart::none(); + } +} diff --git a/vendor/league/commonmark/src/Parser/Cursor.php b/vendor/league/commonmark/src/Parser/Cursor.php new file mode 100644 index 0000000..22967cf --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Cursor.php @@ -0,0 +1,744 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Exception\UnexpectedEncodingException; + +class Cursor +{ + public const INDENT_LEVEL = 4; + + /** + * Interval (in characters) between recorded byte-offset checkpoints on multibyte lines. + * A larger interval uses less memory but makes random lookups walk further; a smaller one + * costs more memory but speeds random lookups. Sequential access is O(1) regardless, via the + * last-resolved-position cache, so this only trades memory against the cost of random jumps + * (backwards peeks, saveState/restoreState). + */ + private const BYTE_OFFSET_CHECKPOINT_INTERVAL = 16; + + /** @psalm-readonly */ + private string $line; + + /** @psalm-readonly */ + private int $length; + + /** + * @var int + * + * It's possible for this to be 1 char past the end, meaning we've parsed all chars and have + * reached the end. In this state, any character-returning method MUST return null. + */ + private int $currentPosition = 0; + + private int $column = 0; + + private int $indent = 0; + + private int $previousPosition = 0; + + private ?int $nextNonSpaceCache = null; + + private bool $partiallyConsumedTab = false; + + /** + * @var int|false + * + * @psalm-readonly + */ + private $lastTabPosition; + + /** @psalm-readonly */ + private bool $isMultibyte; + + /** + * Sparse lookup table mapping a checkpoint index (character index divided by + * BYTE_OFFSET_CHECKPOINT_INTERVAL) to the byte offset at which that character begins within + * $line. Only populated for multibyte lines, and only ever extended forwards. Recording one + * offset per interval - rather than one per character - bounds this map to O(n / interval) + * memory, so it can never become the dominant allocation on a long line. A lookup walks at most + * `interval` bytes from the nearest checkpoint (or O(1) from the last-resolved position for the + * sequential access that dominates parsing); this is what keeps character<->byte translation - + * and therefore every substring accessor - linear rather than O(n^2) on multibyte lines. + * + * @var array<int, int> + */ + private array $byteOffsetCheckpoints = []; + + /** Character index of the most recently resolved byte offset (paired with $lastByteOffset). */ + private int $lastByteOffsetPosition = 0; + + /** Byte offset of the most recently resolved character index (paired with $lastByteOffsetPosition). */ + private int $lastByteOffset = 0; + + /** + * Small cache of individually-read single characters on multibyte lines, keyed by + * character index. Only populated for characters actually read one-at-a-time (e.g. + * repeated peek() during delimiter scanning), so it stays tiny; substring accessors + * bypass it entirely. Avoids re-slicing the same character on every lookup. + * + * @var array<int, string> + */ + private array $charCache = []; + + /** + * @param string $line The line being parsed (ASCII or UTF-8) + */ + public function __construct(string $line) + { + if (! \mb_check_encoding($line, 'UTF-8')) { + throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected'); + } + + $this->line = $line; + $this->length = \mb_strlen($line, 'UTF-8') ?: 0; + $this->isMultibyte = $this->length !== \strlen($line); + $this->lastTabPosition = $this->isMultibyte ? \mb_strrpos($line, "\t", 0, 'UTF-8') : \strrpos($line, "\t"); + + if (! $this->isMultibyte) { + return; + } + + // Seed the checkpoint map with the start of the line; it is extended on demand (see byteOffset()). + $this->byteOffsetCheckpoints = [0]; + } + + /** + * Translate a character index into its byte offset within $line. + * + * The scan starts from the closest known reference point - the last-resolved position when it + * sits between the target and the nearest earlier checkpoint (the common sequential case, O(1)), + * otherwise that checkpoint (at most `interval` characters away). It then walks forwards one + * character at a time, skipping UTF-8 continuation bytes (0b10xxxxxx) and recording a checkpoint + * every `interval` characters. Sequential access is therefore amortized O(1) and any random + * lookup is bounded by O(interval), all while the map itself stays O(n / interval) in memory. + */ + private function byteOffset(int $index): int + { + if ($index === $this->lastByteOffsetPosition) { + return $this->lastByteOffset; + } + + // Start from the checkpoint at or before $index, or - if we've not scanned that far yet - + // from the furthest checkpoint recorded so far. + $checkpoint = \intdiv($index, self::BYTE_OFFSET_CHECKPOINT_INTERVAL); + if (! isset($this->byteOffsetCheckpoints[$checkpoint])) { + $checkpoint = \count($this->byteOffsetCheckpoints) - 1; + } + + $position = $checkpoint * self::BYTE_OFFSET_CHECKPOINT_INTERVAL; + $byte = $this->byteOffsetCheckpoints[$checkpoint]; + + // Prefer the last-resolved position when it is a closer starting point (ahead of the chosen + // checkpoint but not past the target). This makes sequential forward access O(1). + if ($this->lastByteOffsetPosition > $position && $this->lastByteOffsetPosition <= $index) { + $position = $this->lastByteOffsetPosition; + $byte = $this->lastByteOffset; + } + + $lineBytes = \strlen($this->line); + while ($position < $index) { + $byte++; + while ($byte < $lineBytes && (\ord($this->line[$byte]) & 0xC0) === 0x80) { + $byte++; + } + + $position++; + if ($position % self::BYTE_OFFSET_CHECKPOINT_INTERVAL === 0) { + $this->byteOffsetCheckpoints[\intdiv($position, self::BYTE_OFFSET_CHECKPOINT_INTERVAL)] = $byte; + } + } + + $this->lastByteOffsetPosition = $index; + $this->lastByteOffset = $byte; + + return $byte; + } + + /** + * Return the single multibyte character at $index, caching the sliced string so + * repeated reads of the same position (common during delimiter scanning) don't + * re-slice. Callers must ensure 0 <= $index < $length. + * + * Only call this when $isMultibyte is true. On a single-byte line the character is + * already reachable as $this->line[$index], which costs less than the byte-offset + * translation below; every caller guards on that flag for exactly that reason. + */ + private function charAt(int $index): string + { + if (isset($this->charCache[$index])) { + return $this->charCache[$index]; + } + + $startByte = $this->byteOffset($index); + + // The line is known to be valid UTF-8 (the constructor rejects anything else), so the + // lead byte alone gives the character's width. Deriving it here avoids a second + // byteOffset() walk just to locate where the next character begins. + $lead = \ord($this->line[$startByte]); + $width = $lead < 0x80 ? 1 : ($lead < 0xE0 ? 2 : ($lead < 0xF0 ? 3 : 4)); + + return $this->charCache[$index] = \substr($this->line, $startByte, $width); + } + + /** + * Returns the position of the next character which is not a space (or tab) + */ + public function getNextNonSpacePosition(): int + { + if ($this->nextNonSpaceCache !== null) { + return $this->nextNonSpaceCache; + } + + if ($this->currentPosition >= $this->length) { + return $this->length; + } + + $cols = $this->column; + + // Spaces (0x20) and tabs (0x09) are single-byte ASCII characters which can + // never appear inside a multibyte UTF-8 sequence, so the leading run of + // spaces/tabs is always scanned at the byte level. For multibyte lines this + // avoids calling mb_substr() once per character - each such call decodes from + // the start of the string (O(i)), making the scan O(n^2) over a long run of + // leading whitespace. Because every character in the run occupies exactly one + // byte, the character index and byte offset advance together. + $byteOffset = $this->isMultibyte ? $this->byteOffset($this->currentPosition) : $this->currentPosition; + + // Past the last tab (or on a line with none) every whitespace character is a space worth + // exactly one column, so the run length is both the character count and the indent, and + // strspn() can measure it in one call instead of a per-character loop. + if ($this->lastTabPosition === false || $this->currentPosition > $this->lastTabPosition) { + $this->indent = \strspn($this->line, ' ', $byteOffset); + + return $this->nextNonSpaceCache = $this->currentPosition + $this->indent; + } + + for ($i = $this->currentPosition; $i < $this->length; $i++, $byteOffset++) { + $c = $this->line[$byteOffset]; + + if ($c === ' ') { + $cols++; + } elseif ($c === "\t") { + $cols += 4 - ($cols % 4); + } else { + break; + } + } + + $this->indent = $cols - $this->column; + + return $this->nextNonSpaceCache = $i; + } + + /** + * Returns the next character which isn't a space (or tab) + */ + public function getNextNonSpaceCharacter(): ?string + { + $index = $this->getNextNonSpacePosition(); + if ($index >= $this->length) { + return null; + } + + if ($this->isMultibyte) { + return $this->charAt($index); + } + + return $this->line[$index]; + } + + /** + * Calculates the current indent (number of spaces after current position) + */ + public function getIndent(): int + { + if ($this->nextNonSpaceCache === null) { + $this->getNextNonSpacePosition(); + } + + return $this->indent; + } + + /** + * Whether the cursor is indented to INDENT_LEVEL + */ + public function isIndented(): bool + { + if ($this->nextNonSpaceCache === null) { + $this->getNextNonSpacePosition(); + } + + return $this->indent >= self::INDENT_LEVEL; + } + + public function getCharacter(?int $index = null): ?string + { + if ($index === null) { + $index = $this->currentPosition; + } + + // Index out-of-bounds, or we're at the end + if ($index < 0 || $index >= $this->length) { + return null; + } + + if ($this->isMultibyte) { + return $this->charAt($index); + } + + return $this->line[$index]; + } + + /** + * Slightly-optimized version of getCurrent(null) + */ + public function getCurrentCharacter(): ?string + { + if ($this->currentPosition >= $this->length) { + return null; + } + + if ($this->isMultibyte) { + return $this->charAt($this->currentPosition); + } + + return $this->line[$this->currentPosition]; + } + + /** + * Returns the next character (or null, if none) without advancing forwards + */ + public function peek(int $offset = 1): ?string + { + return $this->getCharacter($this->currentPosition + $offset); + } + + /** + * Whether the remainder is blank + */ + public function isBlank(): bool + { + return $this->nextNonSpaceCache === $this->length || $this->getNextNonSpacePosition() === $this->length; + } + + /** + * Move the cursor forwards + */ + public function advance(): void + { + $this->advanceBy(1); + } + + /** + * Move the cursor forwards + * + * @param int $characters Number of characters to advance by + * @param bool $advanceByColumns Whether to advance by columns instead of spaces + */ + public function advanceBy(int $characters, bool $advanceByColumns = false): void + { + $this->previousPosition = $this->currentPosition; + $this->nextNonSpaceCache = null; + + if ($this->currentPosition >= $this->length || $characters === 0) { + return; + } + + // Optimization to avoid tab handling logic if we have no tabs + if ($this->lastTabPosition === false || $this->currentPosition > $this->lastTabPosition) { + $length = \min($characters, $this->length - $this->currentPosition); + $this->partiallyConsumedTab = false; + $this->currentPosition += $length; + $this->column += $length; + + return; + } + + if ($this->isMultibyte) { + $startByte = $this->byteOffset($this->currentPosition); + $endByte = $this->byteOffset(\min($this->currentPosition + $characters, $this->length)); + $nextFewChars = \substr($this->line, $startByte, $endByte - $startByte); + } else { + $nextFewChars = \substr($this->line, $this->currentPosition, $characters); + } + + if ($characters === 1) { + $asArray = [$nextFewChars]; + } elseif ($this->isMultibyte) { + /** @var list<string> $asArray */ + $asArray = \mb_str_split($nextFewChars, 1, 'UTF-8'); + } else { + $asArray = \str_split($nextFewChars); + } + + foreach ($asArray as $c) { + if ($c === "\t") { + $charsToTab = 4 - ($this->column % 4); + if ($advanceByColumns) { + $this->partiallyConsumedTab = $charsToTab > $characters; + $charsToAdvance = $charsToTab > $characters ? $characters : $charsToTab; + $this->column += $charsToAdvance; + $this->currentPosition += $this->partiallyConsumedTab ? 0 : 1; + $characters -= $charsToAdvance; + } else { + $this->partiallyConsumedTab = false; + $this->column += $charsToTab; + $this->currentPosition++; + $characters--; + } + } else { + $this->partiallyConsumedTab = false; + $this->currentPosition++; + $this->column++; + $characters--; + } + + if ($characters <= 0) { + break; + } + } + } + + /** + * Advances the cursor by a single space or tab, if present + */ + public function advanceBySpaceOrTab(): bool + { + $character = $this->getCurrentCharacter(); + + if ($character === ' ' || $character === "\t") { + $this->advanceBy(1, true); + + return true; + } + + return false; + } + + /** + * Parse zero or more space/tab characters + * + * @return int Number of positions moved + */ + public function advanceToNextNonSpaceOrTab(): int + { + $newPosition = $this->nextNonSpaceCache ?? $this->getNextNonSpacePosition(); + if ($newPosition === $this->currentPosition) { + return 0; + } + + $this->advanceBy($newPosition - $this->currentPosition); + $this->partiallyConsumedTab = false; + + // We've just advanced to where that non-space is, + // so any subsequent calls to find the next one will + // always return the current position. + $this->nextNonSpaceCache = $this->currentPosition; + $this->indent = 0; + + return $this->currentPosition - $this->previousPosition; + } + + /** + * Parse zero or more space characters, including at most one newline. + * + * Tab characters are not parsed with this function. + * + * @return int Number of positions moved + */ + public function advanceToNextNonSpaceOrNewline(): int + { + $currentCharacter = $this->getCurrentCharacter(); + + // Optimization: Avoid the regex if we know there are no spaces or newlines + if ($currentCharacter !== ' ' && $currentCharacter !== "\n") { + $this->previousPosition = $this->currentPosition; + + return 0; + } + + // A partially-consumed tab leaves the cursor sitting on the tab itself, which the check + // above has already returned on, so only real spaces and newlines reach this point and no + // tab expansion is needed. + // + // Spaces and newlines are single-byte ASCII characters which can never appear inside a + // multibyte UTF-8 sequence, so the run is measured at the byte level and each byte + // consumed is exactly one character. Scanning the line in place keeps the cost of each + // call proportional to the run it consumes, rather than to the length of everything left + // in the block, which is what building the remainder first charged for. + $byteOffset = $this->isMultibyte ? $this->byteOffset($this->currentPosition) : $this->currentPosition; + + $increment = \strspn($this->line, ' ', $byteOffset); + if (($this->line[$byteOffset + $increment] ?? '') === "\n") { + $increment++; + $increment += \strspn($this->line, ' ', $byteOffset + $increment); + } + + $this->advanceBy($increment); + + return $this->currentPosition - $this->previousPosition; + } + + /** + * Move the position to the very end of the line + * + * @return int The number of characters moved + */ + public function advanceToEnd(): int + { + $this->previousPosition = $this->currentPosition; + $this->nextNonSpaceCache = null; + + $this->currentPosition = $this->length; + + return $this->currentPosition - $this->previousPosition; + } + + public function getRemainder(): string + { + if ($this->currentPosition >= $this->length) { + return ''; + } + + $prefix = ''; + $position = $this->currentPosition; + if ($this->partiallyConsumedTab) { + $position++; + $charsToTab = 4 - ($this->column % 4); + $prefix = \str_repeat(' ', $charsToTab); + } + + $subString = $this->isMultibyte ? + \substr($this->line, $this->byteOffset($position)) : + \substr($this->line, $position); + + return $prefix . $subString; + } + + public function getLine(): string + { + return $this->line; + } + + public function isAtEnd(): bool + { + return $this->currentPosition >= $this->length; + } + + /** + * Try to match a regular expression against the remainder of the line + * + * The subject begins at the cursor: text before the cursor is invisible to the pattern, + * so "^" and "\A" anchor at the cursor, and constructs which examine what precedes the + * match position (lookbehinds, "\b", "\B") see the start of a subject there rather than + * the characters actually preceding the cursor. + * + * Returns the matching text and advances to the end of that match + * + * @psalm-param non-empty-string $regex + */ + public function match(string $regex): ?string + { + $subject = $this->getRemainder(); + + if (! \preg_match($regex, $subject, $matches, \PREG_OFFSET_CAPTURE)) { + return null; + } + + // $matches[0][0] contains the matched text; $matches[0][1] is its byte offset in the subject. + if ($this->isMultibyte) { + $offset = \mb_strlen(\substr($subject, 0, $matches[0][1]), 'UTF-8'); + $matchLength = \mb_strlen($matches[0][0], 'UTF-8'); + } else { + $offset = $matches[0][1]; + $matchLength = \strlen($matches[0][0]); + } + + $advance = $offset + $matchLength; + + // The remainder we matched against had any partially-consumed tab expanded into spaces, + // so those columns must be advanced by column instead of by character. + if ($this->partiallyConsumedTab) { + $charsToTab = 4 - ($this->column % 4); + if ($advance < $charsToTab) { + $this->advanceBy($advance, true); + + return $matches[0][0]; + } + + $this->advanceBy($charsToTab, true); + $advance -= $charsToTab; + } + + $this->advanceBy($advance); + + return $matches[0][0]; + } + + /** + * Try to match a regular expression at the cursor's position within the line, without + * copying the remainder + * + * Matches with PCRE's native offset semantics: the whole line is the subject, and matching + * starts at the cursor. "\G" anchors at the cursor; "^" anchors at the true start of the + * line (or after newlines under the "m" modifier); lookbehinds, "\b", and "\B" see the + * characters actually preceding the cursor. This differs from match(), whose subject begins + * at the cursor - a pattern written for match() migrates by replacing its leading "^" (or + * "\A") with "\G". + * + * Because no copy of the remainder is made, repeated calls stay linear: match() copies + * everything left in the line on every call, so scanning loops (such as the backtick closer + * search) would otherwise cost O(n^2). + * + * When a tab has been partially consumed, no position within the line can represent the + * cursor, so this falls back to matching the remainder with the leftover tab expanded into + * spaces; "\G" still anchors at the cursor there, but the line content before it is not + * visible in that case. + * + * @psalm-param non-empty-string $regex + */ + public function matchInPlace(string $regex): ?string + { + // A partially-consumed tab means the remainder differs from the underlying line (the + // leftover tab expands into spaces), so no byte offset can represent the cursor. + if ($this->partiallyConsumedTab) { + return $this->match($regex); + } + + $bytePosition = $this->isMultibyte ? $this->byteOffset($this->currentPosition) : $this->currentPosition; + + if (! \preg_match($regex, $this->line, $matches, \PREG_OFFSET_CAPTURE, $bytePosition)) { + return null; + } + + // $matches[0][0] contains the matched text; $matches[0][1] is its absolute byte offset in the line. + if ($this->isMultibyte) { + // Convert the byte offset to a character advance relative to the cursor. The scanned gap + // is only the distance from the cursor to the match (zero for anchored patterns), never + // the whole line, so this stays linear across repeated calls. + $offset = \mb_strlen(\substr($this->line, $bytePosition, $matches[0][1] - $bytePosition), 'UTF-8'); + $matchLength = \mb_strlen($matches[0][0], 'UTF-8'); + } else { + $offset = $matches[0][1] - $this->currentPosition; + $matchLength = \strlen($matches[0][0]); + } + + $this->advanceBy($offset + $matchLength); + + return $matches[0][0]; + } + + /** + * Encapsulates the current state of this cursor in case you need to rollback later. + * + * WARNING: Do not parse or use the return value for ANYTHING except for + * passing it back into restoreState(), as the number of values and their + * contents may change in any future release without warning. + */ + public function saveState(): CursorState + { + return new CursorState([ + $this->currentPosition, + $this->previousPosition, + $this->nextNonSpaceCache, + $this->indent, + $this->column, + $this->partiallyConsumedTab, + ]); + } + + /** + * Restore the cursor to a previous state. + * + * Pass in the value previously obtained by calling saveState(). + */ + public function restoreState(CursorState $state): void + { + [ + $this->currentPosition, + $this->previousPosition, + $this->nextNonSpaceCache, + $this->indent, + $this->column, + $this->partiallyConsumedTab, + ] = $state->toArray(); + } + + public function getPosition(): int + { + return $this->currentPosition; + } + + /** + * Returns the byte offset of the current position within the line. + * + * For single-byte lines this is identical to getPosition(). For multibyte + * lines the offset comes from the lazily-built character->byte map, which + * makes this an amortized-O(1) lookup rather than O(position) per call. + */ + public function getBytePosition(): int + { + if (! $this->isMultibyte) { + return $this->currentPosition; + } + + return $this->byteOffset($this->currentPosition); + } + + public function getPreviousText(): string + { + if ($this->isMultibyte) { + $startByte = $this->byteOffset($this->previousPosition); + + return \substr($this->line, $startByte, $this->byteOffset($this->currentPosition) - $startByte); + } + + return \substr($this->line, $this->previousPosition, $this->currentPosition - $this->previousPosition); + } + + public function getSubstring(int $start, ?int $length = null): string + { + if ($this->isMultibyte) { + // Negative offsets/lengths are rare (and never used internally); defer to mb_substr + // so its exact semantics are preserved. + if ($start < 0 || ($length !== null && $length < 0)) { + return \mb_substr($this->line, $start, $length, 'UTF-8'); + } + + if ($start >= $this->length) { + return ''; + } + + $startByte = $this->byteOffset($start); + + if ($length === null) { + return \substr($this->line, $startByte); + } + + return \substr($this->line, $startByte, $this->byteOffset($start + \min($length, $this->length - $start)) - $startByte); + } + + if ($length !== null) { + return \substr($this->line, $start, $length); + } + + return \substr($this->line, $start); + } + + public function getColumn(): int + { + return $this->column; + } +} diff --git a/vendor/league/commonmark/src/Parser/CursorState.php b/vendor/league/commonmark/src/Parser/CursorState.php new file mode 100644 index 0000000..4a6c2d9 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/CursorState.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +/** + * Encapsulates the current state of a cursor in case you need to rollback later. + * + * WARNING: Do not attempt to use this class for ANYTHING except for + * type hinting and passing this object back into restoreState(). + * The constructor, methods, and inner contents may change in any + * future release without warning! + * + * @internal + * + * @psalm-immutable + */ +final class CursorState +{ + /** + * @var array<int, mixed> + * + * @psalm-readonly + */ + private array $state; + + /** + * @internal + * + * @param array<int, mixed> $state + */ + public function __construct(array $state) + { + $this->state = $state; + } + + /** + * @internal + * + * @return array<int, mixed> + */ + public function toArray(): array + { + return $this->state; + } +} diff --git a/vendor/league/commonmark/src/Parser/Inline/InlineParserInterface.php b/vendor/league/commonmark/src/Parser/Inline/InlineParserInterface.php new file mode 100644 index 0000000..fd13435 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Inline/InlineParserInterface.php @@ -0,0 +1,23 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Inline; + +use League\CommonMark\Parser\InlineParserContext; + +interface InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch; + + public function parse(InlineParserContext $inlineContext): bool; +} diff --git a/vendor/league/commonmark/src/Parser/Inline/InlineParserMatch.php b/vendor/league/commonmark/src/Parser/Inline/InlineParserMatch.php new file mode 100644 index 0000000..e433ed2 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Inline/InlineParserMatch.php @@ -0,0 +1,87 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Inline; + +use League\CommonMark\Exception\InvalidArgumentException; + +final class InlineParserMatch +{ + private string $regex; + + private bool $caseSensitive; + + private function __construct(string $regex, bool $caseSensitive = false) + { + $this->regex = $regex; + $this->caseSensitive = $caseSensitive; + } + + public function caseSensitive(): self + { + $this->caseSensitive = true; + + return $this; + } + + /** + * @internal + * + * @psalm-return non-empty-string + */ + public function getRegex(): string + { + return '/' . $this->regex . '/' . ($this->caseSensitive ? '' : 'i'); + } + + /** + * Match the given string (case-insensitive) + */ + public static function string(string $str): self + { + return new self(\preg_quote($str, '/')); + } + + /** + * Match any of the given strings (case-insensitive) + */ + public static function oneOf(string ...$str): self + { + return new self(\implode('|', \array_map(static fn (string $str): string => \preg_quote($str, '/'), $str))); + } + + /** + * Match a partial regular expression without starting/ending delimiters, anchors, or flags + */ + public static function regex(string $regex): self + { + return new self($regex); + } + + public static function join(self ...$definitions): self + { + $regex = ''; + $caseSensitive = null; + foreach ($definitions as $definition) { + $regex .= '(' . $definition->regex . ')'; + + if ($caseSensitive === null) { + $caseSensitive = $definition->caseSensitive; + } elseif ($caseSensitive !== $definition->caseSensitive) { + throw new InvalidArgumentException('Case-sensitive and case-insensitive definitions cannot be combined'); + } + } + + return new self($regex, $caseSensitive ?? false); + } +} diff --git a/vendor/league/commonmark/src/Parser/Inline/NewlineParser.php b/vendor/league/commonmark/src/Parser/Inline/NewlineParser.php new file mode 100644 index 0000000..eb10d91 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/Inline/NewlineParser.php @@ -0,0 +1,53 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser\Inline; + +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\InlineParserContext; + +final class NewlineParser implements InlineParserInterface +{ + public function getMatchDefinition(): InlineParserMatch + { + return InlineParserMatch::regex('\\n'); + } + + public function parse(InlineParserContext $inlineContext): bool + { + $inlineContext->getCursor()->advanceBy(1); + + // Check previous inline for trailing spaces + $spaces = 0; + $lastInline = $inlineContext->getContainer()->lastChild(); + if ($lastInline instanceof Text) { + $trimmed = \rtrim($lastInline->getLiteral(), ' '); + $spaces = \strlen($lastInline->getLiteral()) - \strlen($trimmed); + if ($spaces) { + $lastInline->setLiteral($trimmed); + } + } + + if ($spaces >= 2) { + $inlineContext->getContainer()->appendChild(new Newline(Newline::HARDBREAK)); + } else { + $inlineContext->getContainer()->appendChild(new Newline(Newline::SOFTBREAK)); + } + + return true; + } +} diff --git a/vendor/league/commonmark/src/Parser/InlineParserContext.php b/vendor/league/commonmark/src/Parser/InlineParserContext.php new file mode 100644 index 0000000..9372904 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/InlineParserContext.php @@ -0,0 +1,120 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Delimiter\DelimiterStack; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Reference\ReferenceMapInterface; + +final class InlineParserContext +{ + /** @psalm-readonly */ + private AbstractBlock $container; + + /** @psalm-readonly */ + private ReferenceMapInterface $referenceMap; + + /** @psalm-readonly */ + private Cursor $cursor; + + /** @psalm-readonly */ + private DelimiterStack $delimiterStack; + + /** + * @var string[] + * @psalm-var non-empty-array<string> + * + * @psalm-readonly-allow-private-mutation + */ + private array $matches; + + public function __construct(Cursor $contents, AbstractBlock $container, ReferenceMapInterface $referenceMap, int $maxDelimitersPerLine = PHP_INT_MAX) + { + $this->referenceMap = $referenceMap; + $this->container = $container; + $this->cursor = $contents; + $this->delimiterStack = new DelimiterStack($maxDelimitersPerLine); + } + + public function getContainer(): AbstractBlock + { + return $this->container; + } + + public function getReferenceMap(): ReferenceMapInterface + { + return $this->referenceMap; + } + + public function getCursor(): Cursor + { + return $this->cursor; + } + + public function getDelimiterStack(): DelimiterStack + { + return $this->delimiterStack; + } + + /** + * @return string The full text that matched the InlineParserMatch definition + */ + public function getFullMatch(): string + { + return $this->matches[0]; + } + + /** + * @return int The length of the full match (in characters, not bytes) + */ + public function getFullMatchLength(): int + { + return \mb_strlen($this->matches[0], 'UTF-8'); + } + + /** + * @return string[] Similar to preg_match(), index 0 will contain the full match, and any other array elements will be captured sub-matches + * + * @psalm-return non-empty-array<string> + */ + public function getMatches(): array + { + return $this->matches; + } + + /** + * @return string[] + */ + public function getSubMatches(): array + { + return \array_slice($this->matches, 1); + } + + /** + * @param string[] $matches + * + * @psalm-param non-empty-array<string> $matches + */ + public function withMatches(array $matches): InlineParserContext + { + $ctx = clone $this; + + $ctx->matches = $matches; + + return $ctx; + } +} diff --git a/vendor/league/commonmark/src/Parser/InlineParserEngine.php b/vendor/league/commonmark/src/Parser/InlineParserEngine.php new file mode 100644 index 0000000..5c0e30c --- /dev/null +++ b/vendor/league/commonmark/src/Parser/InlineParserEngine.php @@ -0,0 +1,182 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Inline\AdjacentTextMerger; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Parser\Inline\InlineParserInterface; +use League\CommonMark\Reference\ReferenceMapInterface; + +/** + * @internal + */ +final class InlineParserEngine implements InlineParserEngineInterface +{ + /** @psalm-readonly */ + private EnvironmentInterface $environment; + + /** @psalm-readonly */ + private ReferenceMapInterface $referenceMap; + + /** + * @var array<int, InlineParserInterface|string|bool> + * @psalm-var list<array{0: InlineParserInterface, 1: non-empty-string, 2: bool}> + * @phpstan-var array<int, array{0: InlineParserInterface, 1: non-empty-string, 2: bool}> + */ + private array $parsers = []; + + public function __construct(EnvironmentInterface $environment, ReferenceMapInterface $referenceMap) + { + $this->environment = $environment; + $this->referenceMap = $referenceMap; + + foreach ($environment->getInlineParsers() as $parser) { + \assert($parser instanceof InlineParserInterface); + $regex = $parser->getMatchDefinition()->getRegex(); + + $this->parsers[] = [$parser, $regex, \strlen($regex) !== \mb_strlen($regex, 'UTF-8')]; + } + } + + public function parse(string $contents, AbstractBlock $block): void + { + $contents = \trim($contents); + $cursor = new Cursor($contents); + + $inlineParserContext = new InlineParserContext($cursor, $block, $this->referenceMap, $this->environment->getConfiguration()->get('max_delimiters_per_line')); + + // Have all parsers look at the line to determine what they might want to parse and what positions they exist at + foreach ($this->matchParsers($contents) as $matchPosition => $parsers) { + $currentPosition = $cursor->getPosition(); + // We've already gone past this point + if ($currentPosition > $matchPosition) { + continue; + } + + // We've skipped over some uninteresting text that should be added as a plain text node + if ($currentPosition < $matchPosition) { + $cursor->advanceBy($matchPosition - $currentPosition); + $this->addPlainText($cursor->getPreviousText(), $block); + } + + // We're now at a potential start - see which of the current parsers can handle it + $parsed = false; + foreach ($parsers as [$parser, $matches]) { + if ($parser->parse($inlineParserContext->withMatches($matches))) { + // A parser has successfully handled the text at the given position; don't consider any others at this position + $parsed = true; + break; + } + } + + if ($parsed) { + continue; + } + + // Despite potentially being interested, nothing actually parsed text here, so add the current character and continue onwards + $this->addPlainText((string) $cursor->getCurrentCharacter(), $block); + $cursor->advance(); + } + + // Add any remaining text that wasn't parsed + if (! $cursor->isAtEnd()) { + $this->addPlainText($cursor->getRemainder(), $block); + } + + // Process any delimiters that were found + $delimiterStack = $inlineParserContext->getDelimiterStack(); + $delimiterStack->processDelimiters(null, $this->environment->getDelimiterProcessors()); + $delimiterStack->removeAll(); + + // Combine adjacent text notes into one + AdjacentTextMerger::mergeChildNodes($block); + } + + private function addPlainText(string $text, AbstractBlock $container): void + { + $lastInline = $container->lastChild(); + if ($lastInline instanceof Text && ! $lastInline->data->has('delim')) { + $lastInline->append($text); + } else { + $container->appendChild(new Text($text)); + } + } + + /** + * Given the current line, ask all the parsers which parts of the text they would be interested in parsing. + * + * The resulting array provides a list of character positions, which parsers are interested in trying to parse + * the text at those points, and (for convenience/optimization) what the matching text happened to be. + * + * @return array<array<int, InlineParserInterface|string>> + * + * @psalm-return array<int, list<array{0: InlineParserInterface, 1: non-empty-array<string>}>> + * + * @phpstan-return array<int, array<int, array{0: InlineParserInterface, 1: non-empty-array<string>}>> + */ + private function matchParsers(string $contents): array + { + $contents = \trim($contents); + $isMultibyte = ! \mb_check_encoding($contents, 'ASCII'); + + $ret = []; + + foreach ($this->parsers as [$parser, $regex, $isRegexMultibyte]) { + if ($isMultibyte || $isRegexMultibyte) { + $regex .= 'u'; + } + + // See if the parser's InlineParserMatch regex matched against any part of the string + if (! \preg_match_all($regex, $contents, $matches, \PREG_OFFSET_CAPTURE | \PREG_SET_ORDER)) { + continue; + } + + // For each part that matched... + $lastByteOffset = 0; + $lastCharOffset = 0; + foreach ($matches as $match) { + if ($isMultibyte) { + // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying. + // Matches are returned in ascending order, so convert incrementally from the previous position + // instead of re-scanning from the start of the line for every match (which would be quadratic). + $lastCharOffset += \mb_strlen(\substr($contents, $lastByteOffset, $match[0][1] - $lastByteOffset), 'UTF-8'); + $lastByteOffset = $match[0][1]; + $offset = $lastCharOffset; + } else { + $offset = \intval($match[0][1]); + } + + // Remove the offsets, keeping only the matched text + $m = \array_column($match, 0); + + if ($m === []) { + continue; + } + + // Add this match to the list of character positions to stop at + $ret[$offset][] = [$parser, $m]; + } + } + + // Sort matches by position so we visit them in order + \ksort($ret); + + return $ret; + } +} diff --git a/vendor/league/commonmark/src/Parser/InlineParserEngineInterface.php b/vendor/league/commonmark/src/Parser/InlineParserEngineInterface.php new file mode 100644 index 0000000..8a0986d --- /dev/null +++ b/vendor/league/commonmark/src/Parser/InlineParserEngineInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Node\Block\AbstractBlock; + +/** + * Parser for inline content (text, links, emphasized text, etc). + */ +interface InlineParserEngineInterface +{ + /** + * Parse the given contents as inlines and insert them into the given block + */ + public function parse(string $contents, AbstractBlock $block): void; +} diff --git a/vendor/league/commonmark/src/Parser/MarkdownParser.php b/vendor/league/commonmark/src/Parser/MarkdownParser.php new file mode 100644 index 0000000..904c7c4 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/MarkdownParser.php @@ -0,0 +1,356 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * Additional code based on commonmark-java (https://github.com/commonmark/commonmark-java) + * - (c) Atlassian Pty Ltd + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Event\DocumentPreParsedEvent; +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Input\MarkdownInput; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\BlockContinueParserWithInlinesInterface; +use League\CommonMark\Parser\Block\BlockStart; +use League\CommonMark\Parser\Block\BlockStartParserInterface; +use League\CommonMark\Parser\Block\DocumentBlockParser; +use League\CommonMark\Parser\Block\ParagraphParser; +use League\CommonMark\Reference\MemoryLimitedReferenceMap; +use League\CommonMark\Reference\ReferenceInterface; +use League\CommonMark\Reference\ReferenceMap; + +final class MarkdownParser implements MarkdownParserInterface +{ + /** @psalm-readonly */ + private EnvironmentInterface $environment; + + /** @psalm-readonly-allow-private-mutation */ + private int $maxNestingLevel; + + /** @psalm-readonly-allow-private-mutation */ + private ReferenceMap $referenceMap; + + /** @psalm-readonly-allow-private-mutation */ + private int $lineNumber = 0; + + /** @psalm-readonly-allow-private-mutation */ + private Cursor $cursor; + + /** + * @var array<int, BlockContinueParserInterface> + * + * @psalm-readonly-allow-private-mutation + */ + private array $activeBlockParsers = []; + + /** + * @var array<int, BlockContinueParserWithInlinesInterface> + * + * @psalm-readonly-allow-private-mutation + */ + private array $closedBlockParsers = []; + + public function __construct(EnvironmentInterface $environment) + { + $this->environment = $environment; + } + + private function initialize(): void + { + $this->referenceMap = new ReferenceMap(); + $this->lineNumber = 0; + $this->activeBlockParsers = []; + $this->closedBlockParsers = []; + + $this->maxNestingLevel = $this->environment->getConfiguration()->get('max_nesting_level'); + } + + /** + * @throws CommonMarkException + */ + public function parse(string $input): Document + { + $this->initialize(); + + $documentParser = new DocumentBlockParser($this->referenceMap); + $this->activateBlockParser($documentParser); + + $preParsedEvent = new DocumentPreParsedEvent($documentParser->getBlock(), new MarkdownInput($input)); + $this->environment->dispatch($preParsedEvent); + $markdownInput = $preParsedEvent->getMarkdown(); + + foreach ($markdownInput->getLines() as $lineNumber => $line) { + $this->lineNumber = $lineNumber; + $this->parseLine($line); + } + + // finalizeAndProcess + $this->closeBlockParsers(\count($this->activeBlockParsers), $this->lineNumber); + $this->processInlines(\strlen($input)); + + $this->environment->dispatch(new DocumentParsedEvent($documentParser->getBlock())); + + return $documentParser->getBlock(); + } + + /** + * Analyze a line of text and update the document appropriately. We parse markdown text by calling this on each + * line of input, then finalizing the document. + */ + private function parseLine(string $line): void + { + // replace NUL characters for security + $line = \str_replace("\0", "\u{FFFD}", $line); + + $this->cursor = new Cursor($line); + + $matches = $this->parseBlockContinuation(); + if ($matches === null) { + return; + } + + $unmatchedBlocks = \count($this->activeBlockParsers) - $matches; + $blockParser = $this->activeBlockParsers[$matches - 1]; + $startedNewBlock = false; + + // Unless last matched container is a code block, try new container starts, + // adding children to the last matched container: + $tryBlockStarts = $blockParser->getBlock() instanceof Paragraph || $blockParser->isContainer(); + while ($tryBlockStarts) { + // this is a little performance optimization + if ($this->cursor->isBlank()) { + $this->cursor->advanceToEnd(); + break; + } + + if ($blockParser->getBlock()->getDepth() >= $this->maxNestingLevel) { + break; + } + + $blockStart = $this->findBlockStart($blockParser); + if ($blockStart === null || $blockStart->isAborting()) { + $this->cursor->advanceToNextNonSpaceOrTab(); + break; + } + + if (($state = $blockStart->getCursorState()) !== null) { + $this->cursor->restoreState($state); + } + + $startedNewBlock = true; + + // We're starting a new block. If we have any previous blocks that need to be closed, we need to do it now. + if ($unmatchedBlocks > 0) { + $this->closeBlockParsers($unmatchedBlocks, $this->lineNumber - 1); + $unmatchedBlocks = 0; + } + + $oldBlockLineStart = null; + if ($blockStart->isReplaceActiveBlockParser()) { + $oldBlockLineStart = $this->prepareActiveBlockParserForReplacement(); + } + + foreach ($blockStart->getBlockParsers() as $newBlockParser) { + $blockParser = $this->addChild($newBlockParser, $oldBlockLineStart); + $tryBlockStarts = $newBlockParser->isContainer(); + } + } + + // What remains at the offset is a text line. Add the text to the appropriate block. + + // First check for a lazy paragraph continuation: + if (! $startedNewBlock && ! $this->cursor->isBlank() && $this->getActiveBlockParser()->canHaveLazyContinuationLines()) { + $this->getActiveBlockParser()->addLine($this->cursor->getRemainder()); + } else { + // finalize any blocks not matched + if ($unmatchedBlocks > 0) { + $this->closeBlockParsers($unmatchedBlocks, $this->lineNumber - 1); + } + + if (! $blockParser->isContainer()) { + $this->getActiveBlockParser()->addLine($this->cursor->getRemainder()); + } elseif (! $this->cursor->isBlank()) { + $this->addChild(new ParagraphParser()); + $this->getActiveBlockParser()->addLine($this->cursor->getRemainder()); + } + } + } + + private function parseBlockContinuation(): ?int + { + // For each containing block, try to parse the associated line start. + // The document will always match, so we can skip the first block parser and start at 1 matches + $matches = 1; + for ($i = 1; $i < \count($this->activeBlockParsers); $i++) { + $blockParser = $this->activeBlockParsers[$i]; + $blockContinue = $blockParser->tryContinue(clone $this->cursor, $this->getActiveBlockParser()); + if ($blockContinue === null) { + break; + } + + if ($blockContinue->isFinalize()) { + $this->closeBlockParsers(\count($this->activeBlockParsers) - $i, $this->lineNumber); + + return null; + } + + if (($state = $blockContinue->getCursorState()) !== null) { + $this->cursor->restoreState($state); + } + + $matches++; + } + + return $matches; + } + + private function findBlockStart(BlockContinueParserInterface $lastMatchedBlockParser): ?BlockStart + { + $matchedBlockParser = new MarkdownParserState($this->getActiveBlockParser(), $lastMatchedBlockParser); + + foreach ($this->environment->getBlockStartParsers() as $blockStartParser) { + \assert($blockStartParser instanceof BlockStartParserInterface); + if (($result = $blockStartParser->tryStart(clone $this->cursor, $matchedBlockParser)) !== null) { + return $result; + } + } + + return null; + } + + private function closeBlockParsers(int $count, int $endLineNumber): void + { + for ($i = 0; $i < $count; $i++) { + $blockParser = $this->deactivateBlockParser(); + $this->finalize($blockParser, $endLineNumber); + + // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed + if ($blockParser instanceof BlockContinueParserWithInlinesInterface) { + // Remember for inline parsing + $this->closedBlockParsers[] = $blockParser; + } + } + } + + /** + * Finalize a block. Close it and do any necessary postprocessing, e.g. creating string_content from strings, + * setting the 'tight' or 'loose' status of a list, and parsing the beginnings of paragraphs for reference + * definitions. + */ + private function finalize(BlockContinueParserInterface $blockParser, int $endLineNumber): void + { + if ($blockParser instanceof ParagraphParser) { + $this->updateReferenceMap($blockParser->getReferences()); + } + + $blockParser->getBlock()->setEndLine($endLineNumber); + $blockParser->closeBlock(); + } + + /** + * Walk through a block & children recursively, parsing string content into inline content where appropriate. + */ + private function processInlines(int $inputSize): void + { + $p = new InlineParserEngine($this->environment, new MemoryLimitedReferenceMap($this->referenceMap, $inputSize)); + + foreach ($this->closedBlockParsers as $blockParser) { + $blockParser->parseInlines($p); + } + } + + /** + * Add block of type tag as a child of the tip. If the tip can't accept children, close and finalize it and try + * its parent, and so on til we find a block that can accept children. + */ + private function addChild(BlockContinueParserInterface $blockParser, ?int $startLineNumber = null): BlockContinueParserInterface + { + $blockParser->getBlock()->setStartLine($startLineNumber ?? $this->lineNumber); + + while (! $this->getActiveBlockParser()->canContain($blockParser->getBlock())) { + $this->closeBlockParsers(1, ($startLineNumber ?? $this->lineNumber) - 1); + } + + $this->getActiveBlockParser()->getBlock()->appendChild($blockParser->getBlock()); + $this->activateBlockParser($blockParser); + + return $blockParser; + } + + private function activateBlockParser(BlockContinueParserInterface $blockParser): void + { + $this->activeBlockParsers[] = $blockParser; + } + + /** + * @throws ParserLogicException + */ + private function deactivateBlockParser(): BlockContinueParserInterface + { + $popped = \array_pop($this->activeBlockParsers); + if ($popped === null) { + throw new ParserLogicException('The last block parser should not be deactivated'); + } + + return $popped; + } + + /** + * @return int|null The line number where the old block started + */ + private function prepareActiveBlockParserForReplacement(): ?int + { + // Note that we don't want to parse inlines or finalize this block, as it's getting replaced. + $old = $this->deactivateBlockParser(); + + if ($old instanceof ParagraphParser) { + $this->updateReferenceMap($old->getReferences()); + } + + $old->getBlock()->detach(); + + return $old->getBlock()->getStartLine(); + } + + /** + * @param ReferenceInterface[] $references + */ + private function updateReferenceMap(iterable $references): void + { + foreach ($references as $reference) { + if (! $this->referenceMap->contains($reference->getLabel())) { + $this->referenceMap->add($reference); + } + } + } + + /** + * @throws ParserLogicException + */ + public function getActiveBlockParser(): BlockContinueParserInterface + { + $active = \end($this->activeBlockParsers); + if ($active === false) { + throw new ParserLogicException('No active block parsers are available'); + } + + return $active; + } +} diff --git a/vendor/league/commonmark/src/Parser/MarkdownParserInterface.php b/vendor/league/commonmark/src/Parser/MarkdownParserInterface.php new file mode 100644 index 0000000..e0a6be4 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/MarkdownParserInterface.php @@ -0,0 +1,25 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Node\Block\Document; + +interface MarkdownParserInterface +{ + /** + * @throws CommonMarkException + */ + public function parse(string $input): Document; +} diff --git a/vendor/league/commonmark/src/Parser/MarkdownParserState.php b/vendor/league/commonmark/src/Parser/MarkdownParserState.php new file mode 100644 index 0000000..79abd42 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/MarkdownParserState.php @@ -0,0 +1,57 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Parser\Block\BlockContinueParserInterface; +use League\CommonMark\Parser\Block\ParagraphParser; + +/** + * @internal You should rely on the interface instead + */ +final class MarkdownParserState implements MarkdownParserStateInterface +{ + /** @psalm-readonly */ + private BlockContinueParserInterface $activeBlockParser; + + /** @psalm-readonly */ + private BlockContinueParserInterface $lastMatchedBlockParser; + + public function __construct(BlockContinueParserInterface $activeBlockParser, BlockContinueParserInterface $lastMatchedBlockParser) + { + $this->activeBlockParser = $activeBlockParser; + $this->lastMatchedBlockParser = $lastMatchedBlockParser; + } + + public function getActiveBlockParser(): BlockContinueParserInterface + { + return $this->activeBlockParser; + } + + public function getLastMatchedBlockParser(): BlockContinueParserInterface + { + return $this->lastMatchedBlockParser; + } + + public function getParagraphContent(): ?string + { + if (! $this->lastMatchedBlockParser instanceof ParagraphParser) { + return null; + } + + $paragraphParser = $this->lastMatchedBlockParser; + $content = $paragraphParser->getContentString(); + + return $content === '' ? null : $content; + } +} diff --git a/vendor/league/commonmark/src/Parser/MarkdownParserStateInterface.php b/vendor/league/commonmark/src/Parser/MarkdownParserStateInterface.php new file mode 100644 index 0000000..21a9d3a --- /dev/null +++ b/vendor/league/commonmark/src/Parser/MarkdownParserStateInterface.php @@ -0,0 +1,36 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Parser\Block\BlockContinueParserInterface; + +interface MarkdownParserStateInterface +{ + /** + * Returns the deepest open block parser + */ + public function getActiveBlockParser(): BlockContinueParserInterface; + + /** + * Open block parser that was last matched during the continue phase. This is different from the currently active + * block parser, as an unmatched block is only closed when a new block is started. + */ + public function getLastMatchedBlockParser(): BlockContinueParserInterface; + + /** + * Returns the current content of the paragraph if the matched block is a paragraph. The content can be multiple + * lines separated by newlines. + */ + public function getParagraphContent(): ?string; +} diff --git a/vendor/league/commonmark/src/Parser/ParserLogicException.php b/vendor/league/commonmark/src/Parser/ParserLogicException.php new file mode 100644 index 0000000..592b1a2 --- /dev/null +++ b/vendor/league/commonmark/src/Parser/ParserLogicException.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Parser; + +use League\CommonMark\Exception\CommonMarkException; + +class ParserLogicException extends \LogicException implements CommonMarkException +{ +} diff --git a/vendor/league/commonmark/src/Reference/MemoryLimitedReferenceMap.php b/vendor/league/commonmark/src/Reference/MemoryLimitedReferenceMap.php new file mode 100644 index 0000000..d47bd6a --- /dev/null +++ b/vendor/league/commonmark/src/Reference/MemoryLimitedReferenceMap.php @@ -0,0 +1,68 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +final class MemoryLimitedReferenceMap implements ReferenceMapInterface +{ + private ReferenceMapInterface $decorated; + + private const MINIMUM_SIZE = 100_000; + + private int $remaining; + + public function __construct(ReferenceMapInterface $decorated, int $maxSize) + { + $this->decorated = $decorated; + $this->remaining = \max(self::MINIMUM_SIZE, $maxSize); + } + + public function add(ReferenceInterface $reference): void + { + $this->decorated->add($reference); + } + + public function contains(string $label): bool + { + return $this->decorated->contains($label); + } + + public function get(string $label): ?ReferenceInterface + { + $reference = $this->decorated->get($label); + if ($reference === null) { + return null; + } + + // Check for expansion limit + $this->remaining -= \strlen($reference->getDestination()) + \strlen($reference->getTitle()); + if ($this->remaining < 0) { + return null; + } + + return $reference; + } + + /** + * @return \Traversable<string, ReferenceInterface> + */ + public function getIterator(): \Traversable + { + return $this->decorated->getIterator(); + } + + public function count(): int + { + return $this->decorated->count(); + } +} diff --git a/vendor/league/commonmark/src/Reference/Reference.php b/vendor/league/commonmark/src/Reference/Reference.php new file mode 100644 index 0000000..a0d571d --- /dev/null +++ b/vendor/league/commonmark/src/Reference/Reference.php @@ -0,0 +1,54 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +/** + * @psalm-immutable + */ +final class Reference implements ReferenceInterface +{ + /** @psalm-readonly */ + private string $label; + + /** @psalm-readonly */ + private string $destination; + + /** @psalm-readonly */ + private string $title; + + public function __construct(string $label, string $destination, string $title) + { + $this->label = $label; + $this->destination = $destination; + $this->title = $title; + } + + public function getLabel(): string + { + return $this->label; + } + + public function getDestination(): string + { + return $this->destination; + } + + public function getTitle(): string + { + return $this->title; + } +} diff --git a/vendor/league/commonmark/src/Reference/ReferenceInterface.php b/vendor/league/commonmark/src/Reference/ReferenceInterface.php new file mode 100644 index 0000000..244b354 --- /dev/null +++ b/vendor/league/commonmark/src/Reference/ReferenceInterface.php @@ -0,0 +1,29 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +/** + * Link reference + */ +interface ReferenceInterface +{ + public function getLabel(): string; + + public function getDestination(): string; + + public function getTitle(): string; +} diff --git a/vendor/league/commonmark/src/Reference/ReferenceMap.php b/vendor/league/commonmark/src/Reference/ReferenceMap.php new file mode 100644 index 0000000..97a167d --- /dev/null +++ b/vendor/league/commonmark/src/Reference/ReferenceMap.php @@ -0,0 +1,85 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +use League\CommonMark\Normalizer\TextNormalizer; + +/** + * A collection of references, indexed by label + */ +final class ReferenceMap implements ReferenceMapInterface +{ + /** @psalm-readonly */ + private TextNormalizer $normalizer; + + /** + * @var array<string, ReferenceInterface> + * + * @psalm-readonly-allow-private-mutation + */ + private array $references = []; + + public function __construct() + { + $this->normalizer = new TextNormalizer(); + } + + public function add(ReferenceInterface $reference): void + { + // Normalize the key + $key = $this->normalizer->normalize($reference->getLabel()); + // Store the reference + $this->references[$key] = $reference; + } + + public function contains(string $label): bool + { + if ($this->references === []) { + return false; + } + + $label = $this->normalizer->normalize($label); + + return isset($this->references[$label]); + } + + public function get(string $label): ?ReferenceInterface + { + if ($this->references === []) { + return null; + } + + $label = $this->normalizer->normalize($label); + + return $this->references[$label] ?? null; + } + + /** + * @return \Traversable<string, ReferenceInterface> + */ + public function getIterator(): \Traversable + { + foreach ($this->references as $normalizedLabel => $reference) { + yield $normalizedLabel => $reference; + } + } + + public function count(): int + { + return \count($this->references); + } +} diff --git a/vendor/league/commonmark/src/Reference/ReferenceMapInterface.php b/vendor/league/commonmark/src/Reference/ReferenceMapInterface.php new file mode 100644 index 0000000..71daa19 --- /dev/null +++ b/vendor/league/commonmark/src/Reference/ReferenceMapInterface.php @@ -0,0 +1,31 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +/** + * A collection of references + * + * @phpstan-extends \IteratorAggregate<ReferenceInterface> + */ +interface ReferenceMapInterface extends \IteratorAggregate, \Countable +{ + public function add(ReferenceInterface $reference): void; + + public function contains(string $label): bool; + + public function get(string $label): ?ReferenceInterface; +} diff --git a/vendor/league/commonmark/src/Reference/ReferenceParser.php b/vendor/league/commonmark/src/Reference/ReferenceParser.php new file mode 100644 index 0000000..62cf259 --- /dev/null +++ b/vendor/league/commonmark/src/Reference/ReferenceParser.php @@ -0,0 +1,334 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Reference; + +use League\CommonMark\Parser\Cursor; +use League\CommonMark\Util\LinkParserHelper; + +final class ReferenceParser +{ + // Looking for the start of a definition, i.e. `[` + private const START_DEFINITION = 0; + // Looking for and parsing the label, i.e. `[foo]` within `[foo]` + private const LABEL = 1; + // Parsing the destination, i.e. `/url` in `[foo]: /url` + private const DESTINATION = 2; + // Looking for the start of a title, i.e. the first `"` in `[foo]: /url "title"` + private const START_TITLE = 3; + // Parsing the content of the title, i.e. `title` in `[foo]: /url "title"` + private const TITLE = 4; + // End state, no matter what kind of lines we add, they won't be references + private const PARAGRAPH = 5; + + /** @psalm-readonly-allow-private-mutation */ + private string $paragraph = ''; + + /** + * @var array<int, ReferenceInterface> + * + * @psalm-readonly-allow-private-mutation + */ + private array $references = []; + + /** @psalm-readonly-allow-private-mutation */ + private int $state = self::START_DEFINITION; + + /** @psalm-readonly-allow-private-mutation */ + private ?string $label = null; + + /** @psalm-readonly-allow-private-mutation */ + private ?string $destination = null; + + /** + * @var string string + * + * @psalm-readonly-allow-private-mutation + */ + private string $title = ''; + + /** @psalm-readonly-allow-private-mutation */ + private ?string $titleDelimiter = null; + + /** @psalm-readonly-allow-private-mutation */ + private bool $referenceValid = false; + + public function getParagraphContent(): string + { + return $this->paragraph; + } + + /** + * @return ReferenceInterface[] + */ + 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; + } + + public function hasReferences(): bool + { + return $this->references !== []; + } + + public function parse(string $line): void + { + if ($this->paragraph !== '') { + $this->paragraph .= "\n"; + } + + $this->paragraph .= $line; + + $cursor = new Cursor($line); + while (! $cursor->isAtEnd()) { + $result = false; + switch ($this->state) { + case self::PARAGRAPH: + // We're in a paragraph now. Link reference definitions can only appear at the beginning, so once + // we're in a paragraph, there's no going back. + return; + case self::START_DEFINITION: + $result = $this->parseStartDefinition($cursor); + break; + case self::LABEL: + $result = $this->parseLabel($cursor); + break; + case self::DESTINATION: + $result = $this->parseDestination($cursor); + break; + case self::START_TITLE: + $result = $this->parseStartTitle($cursor); + break; + case self::TITLE: + $result = $this->parseTitle($cursor); + break; + default: + // this should never happen + break; + } + + if (! $result) { + $this->state = self::PARAGRAPH; + + return; + } + } + } + + private function parseStartDefinition(Cursor $cursor): bool + { + $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->isAtEnd() || $cursor->getCurrentCharacter() !== '[') { + return false; + } + + $this->state = self::LABEL; + $this->label = ''; + + $cursor->advance(); + if ($cursor->isAtEnd()) { + $this->label .= "\n"; + } + + return true; + } + + private function parseLabel(Cursor $cursor): bool + { + $cursor->advanceToNextNonSpaceOrTab(); + + $partialLabel = LinkParserHelper::parsePartialLinkLabel($cursor); + if ($partialLabel === null) { + return false; + } + + \assert($this->label !== null); + $this->label .= $partialLabel; + + if ($cursor->isAtEnd()) { + // label might continue on next line + $this->label .= "\n"; + + return true; + } + + if ($cursor->getCurrentCharacter() !== ']') { + return false; + } + + $cursor->advance(); + + // end of label + if ($cursor->getCurrentCharacter() !== ':') { + return false; + } + + $cursor->advance(); + + // spec: A link label can have at most 999 characters inside the square brackets + if (\mb_strlen($this->label, 'UTF-8') > 999) { + return false; + } + + // spec: A link label must contain at least one non-whitespace character + if (\trim($this->label) === '') { + return false; + } + + $cursor->advanceToNextNonSpaceOrTab(); + + $this->state = self::DESTINATION; + + return true; + } + + private function parseDestination(Cursor $cursor): bool + { + $cursor->advanceToNextNonSpaceOrTab(); + + $destination = LinkParserHelper::parseLinkDestination($cursor); + if ($destination === null) { + return false; + } + + $this->destination = $destination; + + $advanced = $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->isAtEnd()) { + // Destination was at end of line, so this is a valid reference for sure (and maybe a title). + // If not at end of line, wait for title to be valid first. + $this->referenceValid = true; + $this->paragraph = ''; + } elseif ($advanced === 0) { + // spec: The title must be separated from the link destination by whitespace + return false; + } + + $this->state = self::START_TITLE; + + return true; + } + + private function parseStartTitle(Cursor $cursor): bool + { + $cursor->advanceToNextNonSpaceOrTab(); + if ($cursor->isAtEnd()) { + $this->state = self::START_DEFINITION; + + return true; + } + + $this->titleDelimiter = null; + switch ($c = $cursor->getCurrentCharacter()) { + case '"': + case "'": + $this->titleDelimiter = $c; + break; + case '(': + $this->titleDelimiter = ')'; + break; + default: + // no title delimter found + break; + } + + if ($this->titleDelimiter !== null) { + $this->state = self::TITLE; + $cursor->advance(); + if ($cursor->isAtEnd()) { + $this->title .= "\n"; + } + } else { + $this->finishReference(); + // There might be another reference instead, try that for the same character. + $this->state = self::START_DEFINITION; + } + + return true; + } + + private function parseTitle(Cursor $cursor): bool + { + \assert($this->titleDelimiter !== null); + $title = LinkParserHelper::parsePartialLinkTitle($cursor, $this->titleDelimiter); + + if ($title === null) { + // Invalid title, stop. The title collected so far must not be used. + $this->title = ''; + + return false; + } + + // Did we find the end delimiter? + $endDelimiterFound = false; + if (\substr($title, -1) === $this->titleDelimiter) { + $endDelimiterFound = true; + // Chop it off + $title = \substr($title, 0, -1); + } + + $this->title .= $title; + + if (! $endDelimiterFound && $cursor->isAtEnd()) { + // Title still going, continue on next line + $this->title .= "\n"; + + return true; + } + + // We either hit the end delimiter or some extra whitespace + $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; + } + + $this->referenceValid = true; + $this->finishReference(); + $this->paragraph = ''; + + // See if there's another definition + $this->state = self::START_DEFINITION; + + return true; + } + + private function finishReference(): void + { + if (! $this->referenceValid) { + return; + } + + /** @psalm-suppress PossiblyNullArgument -- these can't possibly be null if we're in this state */ + $this->references[] = new Reference($this->label, $this->destination, $this->title); + + $this->label = null; + $this->referenceValid = false; + $this->destination = null; + $this->title = ''; + $this->titleDelimiter = null; + } +} diff --git a/vendor/league/commonmark/src/Reference/ReferenceableInterface.php b/vendor/league/commonmark/src/Reference/ReferenceableInterface.php new file mode 100644 index 0000000..b45f379 --- /dev/null +++ b/vendor/league/commonmark/src/Reference/ReferenceableInterface.php @@ -0,0 +1,19 @@ +<?php + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace League\CommonMark\Reference; + +interface ReferenceableInterface +{ + public function getReference(): ReferenceInterface; +} diff --git a/vendor/league/commonmark/src/Renderer/Block/DocumentRenderer.php b/vendor/league/commonmark/src/Renderer/Block/DocumentRenderer.php new file mode 100644 index 0000000..3262691 --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/Block/DocumentRenderer.php @@ -0,0 +1,57 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer\Block; + +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class DocumentRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Document $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + Document::assertInstanceOf($node); + + $wholeDoc = $childRenderer->renderNodes($node->children()); + + return $wholeDoc === '' ? '' : $wholeDoc . "\n"; + } + + public function getXmlTagName(Node $node): string + { + return 'document'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return [ + 'xmlns' => 'http://commonmark.org/xml/1.0', + ]; + } +} diff --git a/vendor/league/commonmark/src/Renderer/Block/ParagraphRenderer.php b/vendor/league/commonmark/src/Renderer/Block/ParagraphRenderer.php new file mode 100644 index 0000000..934eac2 --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/Block/ParagraphRenderer.php @@ -0,0 +1,74 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer\Block; + +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Block\TightBlockInterface; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\HtmlElement; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class ParagraphRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Paragraph $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + Paragraph::assertInstanceOf($node); + + if ($this->inTightList($node)) { + return $childRenderer->renderNodes($node->children()); + } + + $attrs = $node->data->get('attributes'); + + return new HtmlElement('p', $attrs, $childRenderer->renderNodes($node->children())); + } + + public function getXmlTagName(Node $node): string + { + return 'paragraph'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } + + private function inTightList(Paragraph $node): bool + { + // Only check up to two (2) levels above this for tightness + $i = 2; + while (($node = $node->parent()) && $i--) { + if ($node instanceof TightBlockInterface) { + return $node->isTight(); + } + } + + return false; + } +} diff --git a/vendor/league/commonmark/src/Renderer/ChildNodeRendererInterface.php b/vendor/league/commonmark/src/Renderer/ChildNodeRendererInterface.php new file mode 100644 index 0000000..8e866b5 --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/ChildNodeRendererInterface.php @@ -0,0 +1,31 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Node\Node; + +/** + * Renders multiple nodes by delegating to the individual node renderers and adding spacing where needed + */ +interface ChildNodeRendererInterface +{ + /** + * @param Node[] $nodes + */ + public function renderNodes(iterable $nodes): string; + + public function getBlockSeparator(): string; + + public function getInnerSeparator(): string; +} diff --git a/vendor/league/commonmark/src/Renderer/DocumentRendererInterface.php b/vendor/league/commonmark/src/Renderer/DocumentRendererInterface.php new file mode 100644 index 0000000..dd34dd6 --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/DocumentRendererInterface.php @@ -0,0 +1,28 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Output\RenderedContentInterface; + +/** + * Renders a parsed Document AST + */ +interface DocumentRendererInterface extends MarkdownRendererInterface +{ + /** + * Render the given Document node (and all of its children) + */ + public function renderDocument(Document $document): RenderedContentInterface; +} diff --git a/vendor/league/commonmark/src/Renderer/HtmlDecorator.php b/vendor/league/commonmark/src/Renderer/HtmlDecorator.php new file mode 100644 index 0000000..46a38d9 --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/HtmlDecorator.php @@ -0,0 +1,45 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Node\Node; +use League\CommonMark\Util\HtmlElement; + +final class HtmlDecorator implements NodeRendererInterface +{ + private NodeRendererInterface $inner; + private string $tag; + /** @var array<string, string|string[]|bool> */ + private array $attributes; + private bool $selfClosing; + + /** + * @param array<string, string|string[]|bool> $attributes + */ + public function __construct(NodeRendererInterface $inner, string $tag, array $attributes = [], bool $selfClosing = false) + { + $this->inner = $inner; + $this->tag = $tag; + $this->attributes = $attributes; + $this->selfClosing = $selfClosing; + } + + /** + * {@inheritDoc} + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer) + { + return new HtmlElement($this->tag, $this->attributes, $this->inner->render($node, $childRenderer), $this->selfClosing); + } +} diff --git a/vendor/league/commonmark/src/Renderer/HtmlRenderer.php b/vendor/league/commonmark/src/Renderer/HtmlRenderer.php new file mode 100644 index 0000000..2e05cfb --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/HtmlRenderer.php @@ -0,0 +1,100 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentPreRenderEvent; +use League\CommonMark\Event\DocumentRenderedEvent; +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Output\RenderedContent; +use League\CommonMark\Output\RenderedContentInterface; + +final class HtmlRenderer implements DocumentRendererInterface, ChildNodeRendererInterface +{ + /** @psalm-readonly */ + private EnvironmentInterface $environment; + + public function __construct(EnvironmentInterface $environment) + { + $this->environment = $environment; + } + + public function renderDocument(Document $document): RenderedContentInterface + { + $this->environment->dispatch(new DocumentPreRenderEvent($document, 'html')); + + $output = new RenderedContent($document, (string) $this->renderNode($document)); + + $event = new DocumentRenderedEvent($output); + $this->environment->dispatch($event); + + return $event->getOutput(); + } + + /** + * {@inheritDoc} + */ + public function renderNodes(iterable $nodes): string + { + $output = ''; + + $isFirstItem = true; + + foreach ($nodes as $node) { + if (! $isFirstItem && $node instanceof AbstractBlock) { + $output .= $this->getBlockSeparator(); + } + + $output .= $this->renderNode($node); + + $isFirstItem = false; + } + + return $output; + } + + /** + * @return \Stringable|string + * + * @throws NoMatchingRendererException + */ + private function renderNode(Node $node) + { + $renderers = $this->environment->getRenderersForClass(\get_class($node)); + + foreach ($renderers as $renderer) { + \assert($renderer instanceof NodeRendererInterface); + if (($result = $renderer->render($node, $this)) !== null) { + return $result; + } + } + + throw new NoMatchingRendererException('Unable to find corresponding renderer for node type ' . \get_class($node)); + } + + public function getBlockSeparator(): string + { + return $this->environment->getConfiguration()->get('renderer/block_separator'); + } + + public function getInnerSeparator(): string + { + return $this->environment->getConfiguration()->get('renderer/inner_separator'); + } +} diff --git a/vendor/league/commonmark/src/Renderer/Inline/NewlineRenderer.php b/vendor/league/commonmark/src/Renderer/Inline/NewlineRenderer.php new file mode 100644 index 0000000..f64cc58 --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/Inline/NewlineRenderer.php @@ -0,0 +1,76 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer\Inline; + +use League\CommonMark\Node\Inline\Newline; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Xml\XmlNodeRendererInterface; +use League\Config\ConfigurationAwareInterface; +use League\Config\ConfigurationInterface; + +final class NewlineRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface +{ + /** @psalm-readonly-allow-private-mutation */ + private ConfigurationInterface $config; + + public function setConfiguration(ConfigurationInterface $configuration): void + { + $this->config = $configuration; + } + + /** + * @param Newline $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + Newline::assertInstanceOf($node); + + if ($node->getType() === Newline::HARDBREAK) { + return "<br />\n"; + } + + return $this->config->get('renderer/soft_break'); + } + + /** + * @param Newline $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function getXmlTagName(Node $node): string + { + Newline::assertInstanceOf($node); + + return $node->getType() === Newline::SOFTBREAK ? 'softbreak' : 'linebreak'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Renderer/Inline/TextRenderer.php b/vendor/league/commonmark/src/Renderer/Inline/TextRenderer.php new file mode 100644 index 0000000..40ad02a --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/Inline/TextRenderer.php @@ -0,0 +1,54 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer\Inline; + +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use League\CommonMark\Util\Xml; +use League\CommonMark\Xml\XmlNodeRendererInterface; + +final class TextRenderer implements NodeRendererInterface, XmlNodeRendererInterface +{ + /** + * @param Text $node + * + * {@inheritDoc} + * + * @psalm-suppress MoreSpecificImplementedParamType + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer): string + { + Text::assertInstanceOf($node); + + return Xml::escape($node->getLiteral()); + } + + public function getXmlTagName(Node $node): string + { + return 'text'; + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + return []; + } +} diff --git a/vendor/league/commonmark/src/Renderer/MarkdownRendererInterface.php b/vendor/league/commonmark/src/Renderer/MarkdownRendererInterface.php new file mode 100644 index 0000000..83af8cd --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/MarkdownRendererInterface.php @@ -0,0 +1,30 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Output\RenderedContentInterface; + +/** + * Renders a parsed Document AST + * + * @deprecated since 2.3; use {@link DocumentRendererInterface} instead + */ +interface MarkdownRendererInterface +{ + /** + * Render the given Document node (and all of its children) + */ + public function renderDocument(Document $document): RenderedContentInterface; +} diff --git a/vendor/league/commonmark/src/Renderer/NoMatchingRendererException.php b/vendor/league/commonmark/src/Renderer/NoMatchingRendererException.php new file mode 100644 index 0000000..14fe493 --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/NoMatchingRendererException.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Exception\LogicException; + +class NoMatchingRendererException extends LogicException +{ +} diff --git a/vendor/league/commonmark/src/Renderer/NodeRendererInterface.php b/vendor/league/commonmark/src/Renderer/NodeRendererInterface.php new file mode 100644 index 0000000..5d40582 --- /dev/null +++ b/vendor/league/commonmark/src/Renderer/NodeRendererInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Renderer; + +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Node; + +interface NodeRendererInterface +{ + /** + * @return \Stringable|string|null + * + * @throws InvalidArgumentException if the wrong type of Node is provided + */ + public function render(Node $node, ChildNodeRendererInterface $childRenderer); +} diff --git a/vendor/league/commonmark/src/Util/ArrayCollection.php b/vendor/league/commonmark/src/Util/ArrayCollection.php new file mode 100644 index 0000000..eae9f99 --- /dev/null +++ b/vendor/league/commonmark/src/Util/ArrayCollection.php @@ -0,0 +1,175 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +/** + * Array collection + * + * Provides a wrapper around a standard PHP array. + * + * @internal + * + * @phpstan-template T + * @phpstan-implements \IteratorAggregate<int, T> + * @phpstan-implements \ArrayAccess<int, T> + */ +final class ArrayCollection implements \IteratorAggregate, \Countable, \ArrayAccess +{ + /** + * @var array<int, mixed> + * @phpstan-var array<int, T> + */ + private array $elements; + + /** + * Constructor + * + * @param array<int|string, mixed> $elements + * + * @phpstan-param array<int, T> $elements + */ + public function __construct(array $elements = []) + { + $this->elements = $elements; + } + + /** + * @return mixed|false + * + * @phpstan-return T|false + */ + public function first() + { + return \reset($this->elements); + } + + /** + * @return mixed|false + * + * @phpstan-return T|false + */ + public function last() + { + return \end($this->elements); + } + + /** + * Retrieve an external iterator + * + * @return \ArrayIterator<int, mixed> + * + * @phpstan-return \ArrayIterator<int, T> + */ + #[\ReturnTypeWillChange] + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->elements); + } + + /** + * Count elements of an object + * + * @return int The count as an integer. + */ + public function count(): int + { + return \count($this->elements); + } + + /** + * Whether an offset exists + * + * {@inheritDoc} + * + * @phpstan-param int $offset + */ + public function offsetExists($offset): bool + { + return \array_key_exists($offset, $this->elements); + } + + /** + * Offset to retrieve + * + * {@inheritDoc} + * + * @phpstan-param int $offset + * + * @return mixed|null + * + * @phpstan-return T|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->elements[$offset] ?? null; + } + + /** + * Offset to set + * + * {@inheritDoc} + * + * @phpstan-param int|null $offset + * @phpstan-param T $value + */ + #[\ReturnTypeWillChange] + public function offsetSet($offset, $value): void + { + if ($offset === null) { + $this->elements[] = $value; + } else { + $this->elements[$offset] = $value; + } + } + + /** + * Offset to unset + * + * {@inheritDoc} + * + * @phpstan-param int $offset + */ + #[\ReturnTypeWillChange] + public function offsetUnset($offset): void + { + if (! \array_key_exists($offset, $this->elements)) { + return; + } + + unset($this->elements[$offset]); + } + + /** + * Returns a subset of the array + * + * @return array<int, mixed> + * + * @phpstan-return array<int, T> + */ + public function slice(int $offset, ?int $length = null): array + { + return \array_slice($this->elements, $offset, $length, true); + } + + /** + * @return array<int, mixed> + * + * @phpstan-return array<int, T> + */ + public function toArray(): array + { + return $this->elements; + } +} diff --git a/vendor/league/commonmark/src/Util/Html5EntityDecoder.php b/vendor/league/commonmark/src/Util/Html5EntityDecoder.php new file mode 100644 index 0000000..52550a0 --- /dev/null +++ b/vendor/league/commonmark/src/Util/Html5EntityDecoder.php @@ -0,0 +1,75 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +/** + * @psalm-immutable + */ +final class Html5EntityDecoder +{ + /** + * @psalm-pure + */ + public static function decode(string $entity): string + { + if (\substr($entity, -1) !== ';') { + return $entity; + } + + if (\substr($entity, 0, 2) === '&#') { + if (\strtolower(\substr($entity, 2, 1)) === 'x') { + return self::fromHex(\substr($entity, 3, -1)); + } + + return self::fromDecimal(\substr($entity, 2, -1)); + } + + return \html_entity_decode($entity, \ENT_QUOTES | \ENT_HTML5, 'UTF-8'); + } + + /** + * @param mixed $number + * + * @psalm-pure + */ + private static function fromDecimal($number): string + { + // Only convert code points within planes 0-2, excluding NULL + // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found + if (empty($number) || $number > 0x2FFFF) { + return self::fromHex('fffd'); + } + + $entity = '&#' . $number . ';'; + + $converted = \mb_decode_numericentity($entity, [0x0, 0x2FFFF, 0, 0xFFFF], 'UTF-8'); + + if ($converted === $entity) { + return self::fromHex('fffd'); + } + + return $converted; + } + + /** + * @psalm-pure + */ + private static function fromHex(string $hexChars): string + { + return self::fromDecimal(\hexdec($hexChars)); + } +} diff --git a/vendor/league/commonmark/src/Util/HtmlElement.php b/vendor/league/commonmark/src/Util/HtmlElement.php new file mode 100644 index 0000000..9bfb6a0 --- /dev/null +++ b/vendor/league/commonmark/src/Util/HtmlElement.php @@ -0,0 +1,160 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +final class HtmlElement implements \Stringable +{ + /** @psalm-readonly */ + private string $tagName; + + /** @var array<string, string|bool> */ + private array $attributes = []; + + /** @var \Stringable|\Stringable[]|string */ + private $contents; + + /** @psalm-readonly */ + private bool $selfClosing; + + /** + * @param string $tagName Name of the HTML tag + * @param array<string, string|string[]|bool> $attributes Array of attributes (values should be unescaped) + * @param \Stringable|\Stringable[]|string|null $contents Inner contents, pre-escaped if needed + * @param bool $selfClosing Whether the tag is self-closing + */ + public function __construct(string $tagName, array $attributes = [], $contents = '', bool $selfClosing = false) + { + $this->tagName = $tagName; + $this->selfClosing = $selfClosing; + + foreach ($attributes as $name => $value) { + $this->setAttribute($name, $value); + } + + $this->setContents($contents ?? ''); + } + + /** @psalm-immutable */ + public function getTagName(): string + { + return $this->tagName; + } + + /** + * @return array<string, string|bool> + * + * @psalm-immutable + */ + public function getAllAttributes(): array + { + return $this->attributes; + } + + /** + * @return string|bool|null + * + * @psalm-immutable + */ + public function getAttribute(string $key) + { + return $this->attributes[$key] ?? null; + } + + /** + * @param string|string[]|bool $value + */ + public function setAttribute(string $key, $value = true): self + { + if (\is_array($value)) { + $this->attributes[$key] = \implode(' ', \array_unique($value)); + } else { + $this->attributes[$key] = $value; + } + + return $this; + } + + /** + * @return \Stringable|\Stringable[]|string + * + * @psalm-immutable + */ + public function getContents(bool $asString = true) + { + if (! $asString) { + return $this->contents; + } + + return $this->getContentsAsString(); + } + + /** + * Sets the inner contents of the tag (must be pre-escaped if needed) + * + * @param \Stringable|\Stringable[]|string $contents + * + * @return $this + */ + public function setContents($contents): self + { + $this->contents = $contents ?? ''; + + return $this; + } + + /** @psalm-immutable */ + public function __toString(): string + { + $result = '<' . $this->tagName; + + foreach ($this->attributes as $key => $value) { + if ($value === true) { + $result .= ' ' . $key; + } elseif ($value === false) { + continue; + } else { + $result .= ' ' . $key . '="' . Xml::escape($value) . '"'; + } + } + + if ($this->contents !== '') { + $result .= '>' . $this->getContentsAsString() . '</' . $this->tagName . '>'; + } elseif ($this->selfClosing && $this->tagName === 'input') { + $result .= '>'; + } elseif ($this->selfClosing) { + $result .= ' />'; + } else { + $result .= '></' . $this->tagName . '>'; + } + + return $result; + } + + /** @psalm-immutable */ + private function getContentsAsString(): string + { + if (\is_string($this->contents)) { + return $this->contents; + } + + if (\is_array($this->contents)) { + return \implode('', $this->contents); + } + + return (string) $this->contents; + } +} diff --git a/vendor/league/commonmark/src/Util/HtmlFilter.php b/vendor/league/commonmark/src/Util/HtmlFilter.php new file mode 100644 index 0000000..b1e0555 --- /dev/null +++ b/vendor/league/commonmark/src/Util/HtmlFilter.php @@ -0,0 +1,55 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Exception\InvalidArgumentException; + +/** + * @psalm-immutable + */ +final class HtmlFilter +{ + // Return the entire string as-is + public const ALLOW = 'allow'; + // Escape the entire string so any HTML/JS won't be interpreted as such + public const ESCAPE = 'escape'; + // Return an empty string + public const STRIP = 'strip'; + + /** + * Runs the given HTML through the given filter + * + * @param string $html HTML input to be filtered + * @param string $filter One of the HtmlFilter constants + * + * @return string Filtered HTML + * + * @throws InvalidArgumentException when an invalid $filter is given + * + * @psalm-pure + */ + public static function filter(string $html, string $filter): string + { + switch ($filter) { + case self::STRIP: + return ''; + case self::ESCAPE: + return \htmlspecialchars($html, \ENT_NOQUOTES); + case self::ALLOW: + return $html; + default: + throw new InvalidArgumentException(\sprintf('Invalid filter provided: "%s"', $filter)); + } + } +} diff --git a/vendor/league/commonmark/src/Util/LinkParserHelper.php b/vendor/league/commonmark/src/Util/LinkParserHelper.php new file mode 100644 index 0000000..3c1a900 --- /dev/null +++ b/vendor/league/commonmark/src/Util/LinkParserHelper.php @@ -0,0 +1,174 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Parser\Cursor; + +/** + * @psalm-immutable + */ +final class LinkParserHelper +{ + /** + * Attempt to parse link destination + * + * @return string|null The string, or null if no match + */ + public static function parseLinkDestination(Cursor $cursor): ?string + { + if ($cursor->getCurrentCharacter() === '<') { + return self::parseDestinationBraces($cursor); + } + + $destination = self::manuallyParseLinkDestination($cursor); + if ($destination === null) { + return null; + } + + return UrlEncoder::unescapeAndEncode( + RegexHelper::unescape($destination) + ); + } + + public static function parseLinkLabel(Cursor $cursor): int + { + $match = $cursor->matchInPlace('/\G\[(?:[^\\\\\[\]]|\\\\.){0,1000}\]/'); + if ($match === null) { + return 0; + } + + $length = \mb_strlen($match, 'UTF-8'); + + if ($length > 1001) { + return 0; + } + + return $length; + } + + public static function parsePartialLinkLabel(Cursor $cursor): ?string + { + return $cursor->matchInPlace('/\G(?:[^\\\\\[\]]++|\\\\.?)*+/'); + } + + /** + * Attempt to parse link title (sans quotes) + * + * @return string|null The string, or null if no match + */ + public static function parseLinkTitle(Cursor $cursor): ?string + { + if ($title = $cursor->matchInPlace('/\G' . RegexHelper::PARTIAL_LINK_TITLE_UNANCHORED . '/')) { + // Chop off quotes from title and unescape + return RegexHelper::unescape(\substr($title, 1, -1)); + } + + return null; + } + + 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, $excluded, $endDelimiter); + if (($partialTitle = $cursor->matchInPlace($regex)) === null) { + return null; + } + + return RegexHelper::unescape($partialTitle); + } + + private static function manuallyParseLinkDestination(Cursor $cursor): ?string + { + // The destination always ends at the first whitespace or unbalanced ")", so scan the line + // in place from the cursor rather than materializing the remainder: the cost of finding it + // should follow the length of the destination, not the length of everything left in the + // block. A partially-consumed tab needs no special handling - getRemainder() would expand + // it into leading spaces and the scan would stop on the first one, exactly as it stops on + // the tab itself here. + $line = $cursor->getLine(); + $start = $cursor->getBytePosition(); + $openParens = 0; + $len = \strlen($line) - $start; + for ($i = 0; $i < $len; $i++) { + $c = $line[$start + $i]; + if ($c === '\\' && $i + 1 < $len && RegexHelper::isEscapable($line[$start + $i + 1])) { + $i++; + } elseif ($c === '(') { + $openParens++; + // Limit to 32 nested parens for pathological cases + if ($openParens > 32) { + return null; + } + } elseif ($c === ')') { + if ($openParens < 1) { + break; + } + + $openParens--; + } elseif (\ord($c) <= 32 && RegexHelper::isWhitespace($c)) { + break; + } + } + + if ($openParens !== 0) { + return null; + } + + if ($i === 0 && (! isset($c) || $c !== ')')) { + return null; + } + + $destination = \substr($line, $start, $i); + $cursor->advanceBy(\mb_strlen($destination, 'UTF-8')); + + return $destination; + } + + /** @var \WeakReference<Cursor>|null */ + private static ?\WeakReference $lastCursor = null; + private static bool $lastCursorLacksClosingBrace = false; + + private static function parseDestinationBraces(Cursor $cursor): ?string + { + // Optimization: If we've previously parsed this cursor and returned `null`, we know + // that no closing brace exists, so we can skip the regex entirely. This helps avoid + // certain pathological cases where the regex engine can take a very long time to + // determine that no match exists. + if (self::$lastCursor !== null && self::$lastCursor->get() === $cursor) { + if (self::$lastCursorLacksClosingBrace) { + return null; + } + } else { + self::$lastCursor = \WeakReference::create($cursor); + } + + if ($res = $cursor->matchInPlace('/\G' . RegexHelper::PARTIAL_LINK_DESTINATION_BRACES . '/')) { + self::$lastCursorLacksClosingBrace = false; + + // Chop off surrounding <..>: + return UrlEncoder::unescapeAndEncode( + RegexHelper::unescape(\substr($res, 1, -1)) + ); + } + + self::$lastCursorLacksClosingBrace = true; + + return null; + } +} diff --git a/vendor/league/commonmark/src/Util/PrioritizedList.php b/vendor/league/commonmark/src/Util/PrioritizedList.php new file mode 100644 index 0000000..77ec24a --- /dev/null +++ b/vendor/league/commonmark/src/Util/PrioritizedList.php @@ -0,0 +1,73 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +/** + * @internal + * + * @phpstan-template T + * @phpstan-implements \IteratorAggregate<T> + */ +final class PrioritizedList implements \IteratorAggregate +{ + /** + * @var array<int, array<mixed>> + * @phpstan-var array<int, array<T>> + */ + private array $list = []; + + /** + * @var \Traversable<mixed>|null + * @phpstan-var \Traversable<T>|null + */ + private ?\Traversable $optimized = null; + + /** + * @param mixed $item + * + * @phpstan-param T $item + */ + public function add($item, int $priority): void + { + $this->list[$priority][] = $item; + $this->optimized = null; + } + + /** + * @return \Traversable<int, mixed> + * + * @phpstan-return \Traversable<int, T> + */ + #[\ReturnTypeWillChange] + public function getIterator(): \Traversable + { + if ($this->optimized === null) { + \krsort($this->list); + + $sorted = []; + foreach ($this->list as $group) { + foreach ($group as $item) { + $sorted[] = $item; + } + } + + $this->optimized = new \ArrayIterator($sorted); + } + + return $this->optimized; + } +} diff --git a/vendor/league/commonmark/src/Util/RegexHelper.php b/vendor/league/commonmark/src/Util/RegexHelper.php new file mode 100644 index 0000000..3918647 --- /dev/null +++ b/vendor/league/commonmark/src/Util/RegexHelper.php @@ -0,0 +1,260 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock; + +/** + * Provides regular expressions and utilities for parsing Markdown + * + * All of the PARTIAL_ regex constants assume that they'll be used in case-insensitive searches + * All other complete regexes provided by this class (either via constants or methods) will have case-insensitivity enabled. + * + * @phpcs:disable Generic.Strings.UnnecessaryStringConcat.Found + * + * @psalm-immutable + */ +final class RegexHelper +{ + // Partial regular expressions (wrap with `/` on each side and add the case-insensitive `i` flag before use) + public const PARTIAL_ENTITY = '&(?>#x[a-f0-9]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,31});'; + public const PARTIAL_ESCAPABLE = '[!"#$%&\'()*+,.\/:;<=>?@[\\\\\]^_`{|}~-]'; + public const PARTIAL_ESCAPED_CHAR = '\\\\' . self::PARTIAL_ESCAPABLE; + public const PARTIAL_IN_DOUBLE_QUOTES = '"(' . self::PARTIAL_ESCAPED_CHAR . '|[^"\x00])*"'; + public const PARTIAL_IN_SINGLE_QUOTES = '\'(' . self::PARTIAL_ESCAPED_CHAR . '|[^\'\x00])*\''; + 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-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-Za-z_:][A-Za-z0-9:._-]*'; + public const PARTIAL_UNQUOTEDVALUE = '[^"\'=<>`\x00-\x20]+'; + public const PARTIAL_SINGLEQUOTEDVALUE = '\'[^\']*\''; + public const PARTIAL_DOUBLEQUOTEDVALUE = '"[^"]*"'; + public const PARTIAL_ATTRIBUTEVALUE = '(?:' . self::PARTIAL_UNQUOTEDVALUE . '|' . self::PARTIAL_SINGLEQUOTEDVALUE . '|' . self::PARTIAL_DOUBLEQUOTEDVALUE . ')'; + public const PARTIAL_ATTRIBUTEVALUESPEC = '(?:' . '\s*=' . '\s*' . self::PARTIAL_ATTRIBUTEVALUE . ')'; + public const PARTIAL_ATTRIBUTE = '(?:' . '\s+' . self::PARTIAL_ATTRIBUTENAME . self::PARTIAL_ATTRIBUTEVALUESPEC . '?)'; + public const PARTIAL_OPENTAG = '<' . self::PARTIAL_TAGNAME . self::PARTIAL_ATTRIBUTE . '*+' . '\s*+\/?+>'; + public const PARTIAL_CLOSETAG = '<\/' . self::PARTIAL_TAGNAME . '\s*+[>]'; + public const PARTIAL_OPENBLOCKTAG = '<' . self::PARTIAL_BLOCKTAGNAME . self::PARTIAL_ATTRIBUTE . '*+' . '\s*+\/?+>'; + public const PARTIAL_CLOSEBLOCKTAG = '<\/' . self::PARTIAL_BLOCKTAGNAME . '\s*+[>]'; + public const PARTIAL_HTMLCOMMENT = '(?:<!-->|<!--->|<!--[\s\S]*?-->)'; + public const PARTIAL_PROCESSINGINSTRUCTION = '[<][?][\s\S]*?[?][>]'; + public const PARTIAL_DECLARATION = '<![A-Za-z]+' . '[^>]*>'; + public const PARTIAL_CDATA = '<!\[CDATA\[[\s\S]*?]\]>'; + public const PARTIAL_HTMLTAG = '(?:' . self::PARTIAL_OPENTAG . '|' . self::PARTIAL_CLOSETAG . '|' . self::PARTIAL_HTMLCOMMENT . '|' . + self::PARTIAL_PROCESSINGINSTRUCTION . '|' . self::PARTIAL_DECLARATION . '|' . self::PARTIAL_CDATA . ')'; + public const PARTIAL_HTMLBLOCKOPEN = '<(?:' . self::PARTIAL_BLOCKTAGNAME . '(?:[\s\/>]|$)' . '|' . + '\/' . self::PARTIAL_BLOCKTAGNAME . '(?:[\s>]|$)' . '|' . '[?!])'; + /** + * Unanchored so each call site can supply its own anchor: "^" against a detached string, + * or "\G" at a cursor position (see Cursor::matchInPlace()). + */ + public const PARTIAL_LINK_TITLE_UNANCHORED = '(?:"(' . self::PARTIAL_ESCAPED_CHAR . '|[^"\x00])*+"' . + '|' . '\'(' . self::PARTIAL_ESCAPED_CHAR . '|[^\'\x00])*+\'' . + '|' . '\((' . self::PARTIAL_ESCAPED_CHAR . '|[^()\x00])*+\))'; + /** @deprecated since 2.10; use {@link RegexHelper::PARTIAL_LINK_TITLE_UNANCHORED} with an explicit anchor instead */ + public const PARTIAL_LINK_TITLE = '^' . self::PARTIAL_LINK_TITLE_UNANCHORED; + + public const REGEX_PUNCTUATION = '/^[\p{P}\p{S}]/u'; + public const REGEX_UNSAFE_PROTOCOL = '/^(?:javascript|vbscript|file|data):/i'; + public const REGEX_SAFE_DATA_PROTOCOL = '/^data:image\/(?:png|gif|jpeg|webp)/i'; + public const REGEX_NON_SPACE = '/[^ \t\f\v\r\n]/'; + + public const REGEX_WHITESPACE_CHAR = '/^[ \t\n\x0b\x0c\x0d]/'; + public const REGEX_UNICODE_WHITESPACE_CHAR = '/^\pZ|\s/u'; + public const REGEX_THEMATIC_BREAK = '/^(?:(?:\*[ \t]*){3,}|(?:_[ \t]*){3,}|(?:-[ \t]*){3,})$/'; + /** + * Unanchored so each call site can supply its own anchor: "^" against a detached string, + * or "\G" at a cursor position (see Cursor::matchInPlace()). + */ + public const PARTIAL_LINK_DESTINATION_BRACES = '(?:<(?:[^<>\\n\\\\\\x00]|\\\\.)*>)'; + /** @deprecated since 2.10; use {@link RegexHelper::PARTIAL_LINK_DESTINATION_BRACES} with an explicit anchor instead */ + public const REGEX_LINK_DESTINATION_BRACES = '/^' . self::PARTIAL_LINK_DESTINATION_BRACES . '/'; + + /** + * @psalm-pure + */ + public static function isEscapable(string $character): bool + { + return \preg_match('/' . self::PARTIAL_ESCAPABLE . '/', $character) === 1; + } + + public static function isWhitespace(string $character): bool + { + /** @psalm-suppress InvalidLiteralArgument */ + return $character !== '' && \strpos(" \t\n\x0b\x0c\x0d", $character) !== false; + } + + /** + * @psalm-pure + */ + public static function isLetter(?string $character): bool + { + if ($character === null) { + return false; + } + + return \preg_match('/[\pL]/u', $character) === 1; + } + + /** + * Attempt to match a regex in string s at offset offset + * + * @psalm-param non-empty-string $regex + * + * @return int|null Index of match, or null + * + * @psalm-pure + */ + public static function matchAt(string $regex, string $string, int $offset = 0): ?int + { + $matches = []; + $string = \mb_substr($string, $offset, null, 'UTF-8'); + if (! \preg_match($regex, $string, $matches, \PREG_OFFSET_CAPTURE)) { + return null; + } + + // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying + $charPos = \mb_strlen(\mb_strcut($string, 0, $matches[0][1], 'UTF-8'), 'UTF-8'); + + return $offset + $charPos; + } + + /** + * Functional wrapper around preg_match_all which only returns the first set of matches + * + * @psalm-param non-empty-string $pattern + * + * @return string[]|null + * + * @psalm-pure + */ + public static function matchFirst(string $pattern, string $subject, int $offset = 0): ?array + { + if ($offset !== 0) { + $subject = \substr($subject, $offset); + } + + \preg_match_all($pattern, $subject, $matches, \PREG_SET_ORDER); + + if ($matches === []) { + return null; + } + + return $matches[0] ?: null; + } + + /** + * Replace backslash escapes with literal characters + * + * @psalm-pure + */ + public static function unescape(string $string): string + { + $allEscapedChar = '/\\\\(' . self::PARTIAL_ESCAPABLE . ')/'; + + $escaped = \preg_replace($allEscapedChar, '$1', $string); + \assert(\is_string($escaped)); + + return \preg_replace_callback('/' . self::PARTIAL_ENTITY . '/i', static fn ($e) => Html5EntityDecoder::decode($e[0]), $escaped); + } + + /** + * @internal + * + * @param int $type HTML block type + * + * @psalm-param HtmlBlock::TYPE_* $type + * + * @phpstan-param HtmlBlock::TYPE_* $type + * + * @psalm-return non-empty-string + * + * @throws InvalidArgumentException if an invalid type is given + * + * @psalm-pure + */ + public static function getHtmlBlockOpenRegex(int $type): string + { + switch ($type) { + case HtmlBlock::TYPE_1_CODE_CONTAINER: + return '/^<(?:script|pre|textarea|style)(?:\s|>|$)/i'; + case HtmlBlock::TYPE_2_COMMENT: + return '/^<!--/'; + case HtmlBlock::TYPE_3: + return '/^<[?]/'; + case HtmlBlock::TYPE_4: + return '/^<![A-Z]/i'; + case HtmlBlock::TYPE_5_CDATA: + return '/^<!\[CDATA\[/i'; + case HtmlBlock::TYPE_6_BLOCK_ELEMENT: + return '%^</?+(?: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|h[123456]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s++|[/]?+[>]|$)%i'; + case HtmlBlock::TYPE_7_MISC_ELEMENT: + return '/^(?:' . self::PARTIAL_OPENTAG . '|' . self::PARTIAL_CLOSETAG . ')\\s*$/i'; + default: + throw new InvalidArgumentException('Invalid HTML block type'); + } + } + + /** + * @internal + * + * @param int $type HTML block type + * + * @psalm-param HtmlBlock::TYPE_* $type + * + * @phpstan-param HtmlBlock::TYPE_* $type + * + * @psalm-return non-empty-string + * + * @throws InvalidArgumentException if an invalid type is given + * + * @psalm-pure + */ + public static function getHtmlBlockCloseRegex(int $type): string + { + switch ($type) { + case HtmlBlock::TYPE_1_CODE_CONTAINER: + return '%<\/(?:script|pre|textarea|style)>%i'; + case HtmlBlock::TYPE_2_COMMENT: + return '/-->/'; + case HtmlBlock::TYPE_3: + return '/\?>/'; + case HtmlBlock::TYPE_4: + return '/>/'; + case HtmlBlock::TYPE_5_CDATA: + return '/\]\]>/'; + default: + throw new InvalidArgumentException('Invalid HTML block type'); + } + } + + /** + * @psalm-pure + */ + public static function isLinkPotentiallyUnsafe(string $url): bool + { + // Browsers discard these bytes before resolving the scheme (see the WHATWG URL Standard's + // "basic URL parser", steps 1 and 3), so `java<TAB>script:` and `<0x01>javascript:` reach + // the user as `javascript:` and must be treated as such here too + $url = \ltrim(\str_replace(["\t", "\n", "\r"], '', $url), "\x00..\x20"); + + return \preg_match(self::REGEX_UNSAFE_PROTOCOL, $url) !== 0 && \preg_match(self::REGEX_SAFE_DATA_PROTOCOL, $url) === 0; + } +} diff --git a/vendor/league/commonmark/src/Util/SpecReader.php b/vendor/league/commonmark/src/Util/SpecReader.php new file mode 100644 index 0000000..faee204 --- /dev/null +++ b/vendor/league/commonmark/src/Util/SpecReader.php @@ -0,0 +1,72 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Exception\IOException; + +/** + * Reads in a CommonMark spec document and extracts the input/output examples for testing against them + */ +final class SpecReader +{ + private function __construct() + { + } + + /** + * @return iterable<string, array{input: string, output: string, type: string, section: string, number: int}> + */ + public static function read(string $data): iterable + { + // Normalize newlines for platform independence + $data = \preg_replace('/\r\n?/', "\n", $data); + \assert($data !== null); + $data = \preg_replace('/<!-- END TESTS -->.*$/', '', $data); + \assert($data !== null); + \preg_match_all('/^`{32} (example ?\w*)\n([\s\S]*?)^\.\n([\s\S]*?)^`{32}$|^#{1,6} *(.*)$/m', $data, $matches, PREG_SET_ORDER); + + $currentSection = 'Example'; + $exampleNumber = 0; + + foreach ($matches as $match) { + \assert(isset($match[1], $match[2], $match[3])); + if (isset($match[4])) { + $currentSection = $match[4]; + continue; + } + + yield \trim($currentSection . ' #' . $exampleNumber) => [ + 'input' => \str_replace('→', "\t", $match[2]), + 'output' => \str_replace('→', "\t", $match[3]), + 'type' => $match[1], + 'section' => $currentSection, + 'number' => $exampleNumber++, + ]; + } + } + + /** + * @return iterable<string, array{input: string, output: string, type: string, section: string, number: int}> + * + * @throws IOException if the file cannot be loaded + */ + public static function readFile(string $filename): iterable + { + if (($data = \file_get_contents($filename)) === false) { + throw new IOException(\sprintf('Failed to load spec from %s', $filename)); + } + + return self::read($data); + } +} diff --git a/vendor/league/commonmark/src/Util/UrlEncoder.php b/vendor/league/commonmark/src/Util/UrlEncoder.php new file mode 100644 index 0000000..f4aabda --- /dev/null +++ b/vendor/league/commonmark/src/Util/UrlEncoder.php @@ -0,0 +1,69 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +use League\CommonMark\Exception\UnexpectedEncodingException; + +/** + * @psalm-immutable + */ +final class UrlEncoder +{ + private const ENCODE_CACHE = ['%00', '%01', '%02', '%03', '%04', '%05', '%06', '%07', '%08', '%09', '%0A', '%0B', '%0C', '%0D', '%0E', '%0F', '%10', '%11', '%12', '%13', '%14', '%15', '%16', '%17', '%18', '%19', '%1A', '%1B', '%1C', '%1D', '%1E', '%1F', '%20', '!', '%22', '#', '$', '%25', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '%3C', '=', '%3E', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '%5B', '%5C', '%5D', '%5E', '_', '%60', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '%7B', '%7C', '%7D', '~', '%7F']; + + /** + * @throws UnexpectedEncodingException if a non-UTF-8-compatible encoding is used + * + * @psalm-pure + */ + public static function unescapeAndEncode(string $uri): string + { + // Optimization: if the URL only includes characters we know will be kept as-is, then just return the URL as-is. + if (\preg_match('/^[A-Za-z0-9~!@#$&*()\-_=+;:,.\/?]+$/', $uri)) { + return $uri; + } + + if (! \mb_check_encoding($uri, 'UTF-8')) { + throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected'); + } + + $result = ''; + + $chars = \mb_str_split($uri, 1, 'UTF-8'); + + $l = \count($chars); + for ($i = 0; $i < $l; $i++) { + $code = $chars[$i]; + if ($code === '%' && $i + 2 < $l) { + if (\preg_match('/^[0-9a-f]{2}$/i', $chars[$i + 1] . $chars[$i + 2]) === 1) { + $result .= '%' . $chars[$i + 1] . $chars[$i + 2]; + $i += 2; + continue; + } + } + + if (\strlen($code) === 1 && \ord($code) < 128) { + $result .= self::ENCODE_CACHE[\ord($code)]; + continue; + } + + $result .= \rawurlencode($code); + } + + return $result; + } +} diff --git a/vendor/league/commonmark/src/Util/Xml.php b/vendor/league/commonmark/src/Util/Xml.php new file mode 100644 index 0000000..8f9e84d --- /dev/null +++ b/vendor/league/commonmark/src/Util/Xml.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) + * - (c) John MacFarlane + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Util; + +/** + * Utility class for handling/generating XML and HTML + * + * @psalm-immutable + */ +final class Xml +{ + /** + * @psalm-pure + */ + public static function escape(string $string): string + { + return \str_replace(['&', '<', '>', '"'], ['&', '<', '>', '"'], $string); + } +} diff --git a/vendor/league/commonmark/src/Xml/FallbackNodeXmlRenderer.php b/vendor/league/commonmark/src/Xml/FallbackNodeXmlRenderer.php new file mode 100644 index 0000000..48aa3c8 --- /dev/null +++ b/vendor/league/commonmark/src/Xml/FallbackNodeXmlRenderer.php @@ -0,0 +1,85 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Xml; + +use League\CommonMark\Node\Block\AbstractBlock; +use League\CommonMark\Node\Inline\AbstractInline; +use League\CommonMark\Node\Node; + +/** + * @internal + */ +final class FallbackNodeXmlRenderer implements XmlNodeRendererInterface +{ + /** + * @var array<string, string> + * + * @psalm-allow-private-mutation + */ + private array $classCache = []; + + /** + * @psalm-allow-private-mutation + */ + public function getXmlTagName(Node $node): string + { + $className = \get_class($node); + if (isset($this->classCache[$className])) { + return $this->classCache[$className]; + } + + $type = $node instanceof AbstractBlock ? 'block' : 'inline'; + $shortName = \strtolower((new \ReflectionClass($node))->getShortName()); + + return $this->classCache[$className] = \sprintf('custom_%s_%s', $type, $shortName); + } + + /** + * {@inheritDoc} + */ + public function getXmlAttributes(Node $node): array + { + $attrs = []; + foreach ($node->data->export() as $k => $v) { + if (self::isValueUsable($v)) { + $attrs[$k] = $v; + } + } + + $reflClass = new \ReflectionClass($node); + foreach ($reflClass->getProperties() as $property) { + if (\in_array($property->getDeclaringClass()->getName(), [Node::class, AbstractBlock::class, AbstractInline::class], true)) { + continue; + } + + $property->setAccessible(true); + $value = $property->getValue($node); + if (self::isValueUsable($value)) { + $attrs[$property->getName()] = $value; + } + } + + return $attrs; + } + + /** + * @param mixed $var + * + * @psalm-pure + */ + private static function isValueUsable($var): bool + { + return \is_string($var) || \is_int($var) || \is_float($var) || \is_bool($var); + } +} diff --git a/vendor/league/commonmark/src/Xml/MarkdownToXmlConverter.php b/vendor/league/commonmark/src/Xml/MarkdownToXmlConverter.php new file mode 100644 index 0000000..538ad98 --- /dev/null +++ b/vendor/league/commonmark/src/Xml/MarkdownToXmlConverter.php @@ -0,0 +1,59 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Xml; + +use League\CommonMark\ConverterInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Exception\CommonMarkException; +use League\CommonMark\Output\RenderedContentInterface; +use League\CommonMark\Parser\MarkdownParser; +use League\CommonMark\Parser\MarkdownParserInterface; +use League\CommonMark\Renderer\DocumentRendererInterface; + +final class MarkdownToXmlConverter implements ConverterInterface +{ + /** @psalm-readonly */ + private MarkdownParserInterface $parser; + + /** @psalm-readonly */ + private DocumentRendererInterface $renderer; + + public function __construct(EnvironmentInterface $environment) + { + $this->parser = new MarkdownParser($environment); + $this->renderer = new XmlRenderer($environment); + } + + /** + * Converts Markdown to XML + * + * @throws CommonMarkException + */ + public function convert(string $input): RenderedContentInterface + { + return $this->renderer->renderDocument($this->parser->parse($input)); + } + + /** + * Converts CommonMark to HTML. + * + * @see MarkdownToXmlConverter::convert() + * + * @throws CommonMarkException + */ + public function __invoke(string $input): RenderedContentInterface + { + return $this->convert($input); + } +} diff --git a/vendor/league/commonmark/src/Xml/XmlNodeRendererInterface.php b/vendor/league/commonmark/src/Xml/XmlNodeRendererInterface.php new file mode 100644 index 0000000..aafc9f1 --- /dev/null +++ b/vendor/league/commonmark/src/Xml/XmlNodeRendererInterface.php @@ -0,0 +1,28 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/commonmark package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\CommonMark\Xml; + +use League\CommonMark\Node\Node; + +interface XmlNodeRendererInterface +{ + public function getXmlTagName(Node $node): string; + + /** + * @return array<string, string|int|float|bool> + * + * @psalm-return array<string, scalar> + */ + public function getXmlAttributes(Node $node): array; +} diff --git a/vendor/league/commonmark/src/Xml/XmlRenderer.php b/vendor/league/commonmark/src/Xml/XmlRenderer.php new file mode 100644 index 0000000..e008001 --- /dev/null +++ b/vendor/league/commonmark/src/Xml/XmlRenderer.php @@ -0,0 +1,143 @@ +<?php + +declare(strict_types=1); + +namespace League\CommonMark\Xml; + +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentPreRenderEvent; +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Node\StringContainerInterface; +use League\CommonMark\Output\RenderedContent; +use League\CommonMark\Output\RenderedContentInterface; +use League\CommonMark\Renderer\DocumentRendererInterface; +use League\CommonMark\Util\Xml; + +final class XmlRenderer implements DocumentRendererInterface +{ + private const INDENTATION = ' '; + + private EnvironmentInterface $environment; + + private XmlNodeRendererInterface $fallbackRenderer; + + /** @var array<class-string, XmlNodeRendererInterface> */ + private array $rendererCache = []; + + public function __construct(EnvironmentInterface $environment) + { + $this->environment = $environment; + $this->fallbackRenderer = new FallbackNodeXmlRenderer(); + } + + public function renderDocument(Document $document): RenderedContentInterface + { + $this->environment->dispatch(new DocumentPreRenderEvent($document, 'xml')); + + // Indentation is purely cosmetic, so it's capped to keep the output size linear + // (rather than quadratic) with respect to the depth of the document. + $maxIndent = $this->getMaxIndentationLevel(); + + $xml = '<?xml version="1.0" encoding="UTF-8"?>'; + + $indent = 0; + $walker = $document->walker(); + while ($event = $walker->next()) { + $node = $event->getNode(); + + $closeImmediately = ! $node->hasChildren(); + $selfClosing = $closeImmediately && ! $node instanceof StringContainerInterface; + + $renderer = $this->findXmlRenderer($node); + $tagName = $renderer->getXmlTagName($node); + + if ($event->isEntering()) { + $attrs = $renderer->getXmlAttributes($node); + + $xml .= "\n" . \str_repeat(self::INDENTATION, \min($indent, $maxIndent)); + $xml .= self::tag($tagName, $attrs, $selfClosing); + + if ($node instanceof StringContainerInterface) { + $xml .= Xml::escape($node->getLiteral()); + } + + if ($closeImmediately && ! $selfClosing) { + $xml .= self::tag('/' . $tagName); + } + + if (! $closeImmediately) { + $indent++; + } + } elseif (! $closeImmediately) { + $indent--; + $xml .= "\n" . \str_repeat(self::INDENTATION, \min($indent, $maxIndent)); + $xml .= self::tag('/' . $tagName); + } + } + + return new RenderedContent($document, $xml . "\n"); + } + + private function getMaxIndentationLevel(): int + { + return $this->environment->getConfiguration()->get('xml/max_indentation_level'); + } + + /** + * @param array<string, string|int|float|bool> $attrs + */ + private static function tag(string $name, array $attrs = [], bool $selfClosing = false): string + { + $result = '<' . $name; + foreach ($attrs as $key => $value) { + $result .= \sprintf(' %s="%s"', $key, self::convertAndEscape($value)); + } + + if ($selfClosing) { + $result .= ' /'; + } + + $result .= '>'; + + return $result; + } + + /** + * @param string|int|float|bool $value + */ + private static function convertAndEscape($value): string + { + if (\is_string($value)) { + return Xml::escape($value); + } + + if (\is_int($value) || \is_float($value)) { + return (string) $value; + } + + if (\is_bool($value)) { + return $value ? 'true' : 'false'; + } + + throw new InvalidArgumentException('$value must be a string, int, float, or bool'); + } + + private function findXmlRenderer(Node $node): XmlNodeRendererInterface + { + $class = \get_class($node); + + if (\array_key_exists($class, $this->rendererCache)) { + return $this->rendererCache[$class]; + } + + foreach ($this->environment->getRenderersForClass($class) as $renderer) { + if ($renderer instanceof XmlNodeRendererInterface) { + return $this->rendererCache[$class] = $renderer; + } + } + + return $this->rendererCache[$class] = $this->fallbackRenderer; + } +} diff --git a/vendor/league/config/CHANGELOG.md b/vendor/league/config/CHANGELOG.md new file mode 100644 index 0000000..9a7813a --- /dev/null +++ b/vendor/league/config/CHANGELOG.md @@ -0,0 +1,42 @@ +# Change Log +All notable changes to this project will be documented in this file. +Updates should follow the [Keep a CHANGELOG](https://keepachangelog.com/) principles. + +## [Unreleased][unreleased] + +## [1.2.0] - 2022-12-11 + +### Changed + +- Values can now be set prior to the corresponding schema being registered. +- `exists()` and `get()` now only trigger validation for the relevant schema, not the entire config at once. + +## [1.1.1] - 2021-08-14 + +### Changed + + - Bumped the minimum version of dflydev/dot-access-data for PHP 8.1 support + +## [1.1.0] - 2021-06-19 + +### Changed + +- Bumped the minimum PHP version to 7.4+ +- Bumped the minimum version of nette/schema to 1.2.0 + +## [1.0.1] - 2021-05-31 + +### Fixed + +- Fixed the `ConfigurationExceptionInterface` marker interface not extending `Throwable` (#2) + +## [1.0.0] - 2021-05-31 + +Initial release! 🎉 + +[unreleased]: https://github.com/thephpleague/config/compare/v1.2.0...main +[1.2.0]: https://github.com/thephpleague/config/compare/v1.1.1...v.1.2.0 +[1.1.1]: https://github.com/thephpleague/config/compare/v1.1.0...v1.1.1 +[1.1.0]: https://github.com/thephpleague/config/compare/v1.0.1...v1.1.0 +[1.0.1]: https://github.com/thephpleague/config/compare/v1.0.0...v1.0.1 +[1.0.0]: https://github.com/thephpleague/config/releases/tag/v1.0.0 diff --git a/vendor/league/config/LICENSE.md b/vendor/league/config/LICENSE.md new file mode 100644 index 0000000..1a444a1 --- /dev/null +++ b/vendor/league/config/LICENSE.md @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2022, Colin O'Dell. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/league/config/README.md b/vendor/league/config/README.md new file mode 100644 index 0000000..2304746 --- /dev/null +++ b/vendor/league/config/README.md @@ -0,0 +1,153 @@ +# league/config + +[![Latest Version](https://img.shields.io/packagist/v/league/config.svg?style=flat-square)](https://packagist.org/packages/league/config) +[![Total Downloads](https://img.shields.io/packagist/dt/league/config.svg?style=flat-square)](https://packagist.org/packages/league/config) +[![Software License](https://img.shields.io/badge/License-BSD--3-brightgreen.svg?style=flat-square)](LICENSE) +[![Build Status](https://img.shields.io/github/workflow/status/thephpleague/config/Tests/main.svg?style=flat-square)](https://github.com/thephpleague/config/actions?query=workflow%3ATests+branch%3Amain) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/config.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/config/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/config.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/config) +[![Sponsor development of this project](https://img.shields.io/badge/sponsor%20this%20package-%E2%9D%A4-ff69b4.svg?style=flat-square)](https://www.colinodell.com/sponsor) + +**league/config** helps you define nested configuration arrays with strict schemas and access configuration values with dot notation. It was created by [Colin O'Dell][@colinodell]. + +## 📦 Installation + +This project requires PHP 7.4 or higher. To install it via [Composer] simply run: + +```bash +composer require league/config +``` + +## 🧰️ Basic Usage + +The `Configuration` class provides everything you need to define the configuration structure and fetch values: + +```php +use League\Config\Configuration; +use Nette\Schema\Expect; + +// Define your configuration schema +$config = new Configuration([ + 'database' => Expect::structure([ + 'driver' => Expect::anyOf('mysql', 'postgresql', 'sqlite')->required(), + 'host' => Expect::string()->default('localhost'), + 'port' => Expect::int()->min(1)->max(65535), + 'ssl' => Expect::bool(), + 'database' => Expect::string()->required(), + 'username' => Expect::string()->required(), + 'password' => Expect::string()->nullable(), + ]), + 'logging' => Expect::structure([ + 'enabled' => Expect::bool()->default($_ENV['DEBUG'] == true), + 'file' => Expect::string()->deprecated("use logging.path instead"), + 'path' => Expect::string()->assert(function ($path) { return \is_writeable($path); })->required(), + ]), +]); + +// Set the values, either all at once with `merge()`: +$config->merge([ + 'database' => [ + 'driver' => 'mysql', + 'port' => 3306, + 'database' => 'mydb', + 'username' => 'user', + 'password' => 'secret', + ], +]); + +// Or one-at-a-time with `set()`: +$config->set('logging.path', '/var/log/myapp.log'); + +// You can now retrieve those values with `get()`. +// Validation and defaults will be applied for you automatically +$config->get('database'); // Fetches the entire "database" section as an array +$config->get('database.driver'); // Fetch a specific nested value with dot notation +$config->get('database/driver'); // Fetch a specific nested value with slash notation +$config->get('database.host'); // Returns the default value "localhost" +$config->get('logging.path'); // Guaranteed to be writeable thanks to the assertion in the schema + +// If validation fails an `InvalidConfigurationException` will be thrown: +$config->set('database.driver', 'mongodb'); +$config->get('database.driver'); // InvalidConfigurationException + +// Attempting to fetch a non-existent key will result in an `InvalidConfigurationException` +$config->get('foo.bar'); + +// You could avoid this by checking whether that item exists: +$config->exists('foo.bar'); // Returns `false` +``` + +## 📓 Documentation + +Full documentation can be found at [config.thephpleague.com][docs]. + +## 💭 Philosophy + +This library aims to provide a **simple yet opinionated** approach to configuration with the following goals: + +- The configuration should operate on **arrays with nested values** which are easily accessible +- The configuration structure should be **defined with strict schemas** defining the overall structure, allowed types, and allowed values +- Schemas should be defined using a **simple, fluent interface** +- You should be able to **add and combine schemas but never modify existing ones** +- Both the configuration values and the schema should be **defined and managed with PHP code** +- Schemas should be **immutable**; they should never change once they are set +- Configuration values should never define or influence the schemas + +As a result, this library will likely **never** support features like: + +- Loading and/or exporting configuration values or schemas using YAML, XML, or other files +- Parsing configuration values from a command line or other user interface +- Dynamically changing the schema, allowed values, or default values based on other configuration values + +If you need that functionality you should check out other libraries like: + +- [symfony/config] +- [symfony/options-resolver] +- [hassankhan/config] +- [consolidation/config] +- [laminas/laminas-config] + +## 🏷️ Versioning + +[SemVer](http://semver.org/) is followed closely. Minor and patch releases should not introduce breaking changes to the codebase. + +Any classes or methods marked `@internal` are not intended for use outside this library and are subject to breaking changes at any time, so please avoid using them. + +## 🛠️ Maintenance & Support + +When a new **minor** version (e.g. `1.0` -> `1.1`) is released, the previous one (`1.0`) will continue to receive security and critical bug fixes for *at least* 3 months. + +When a new **major** version is released (e.g. `1.1` -> `2.0`), the previous one (`1.1`) will receive critical bug fixes for *at least* 3 months and security updates for 6 months after that new release comes out. + +(This policy may change in the future and exceptions may be made on a case-by-case basis.) + +## 👷‍️ Contributing + +Contributions to this library are **welcome**! We only ask that you adhere to our [contributor guidelines] and avoid making changes that conflict with our Philosophy above. + +## 🧪 Testing + +```bash +composer test +``` + +## 📄 License + +**league/config** is licensed under the BSD-3 license. See the [`LICENSE.md`][license] file for more details. + +## 🗺️ Who Uses It? + +This project is used by [league/commonmark][league-commonmark]. + +[docs]: https://config.thephpleague.com/ +[@colinodell]: https://www.twitter.com/colinodell +[Composer]: https://getcomposer.org/ +[PHP League]: https://thephpleague.com +[symfony/config]: https://symfony.com/doc/current/components/config.html +[symfony/options-resolver]: https://symfony.com/doc/current/components/options_resolver.html +[hassankhan/config]: https://github.com/hassankhan/config +[consolidation/config]: https://github.com/consolidation/config +[laminas/laminas-config]: https://docs.laminas.dev/laminas-config/ +[contributor guidelines]: https://github.com/thephpleague/config/blob/main/.github/CONTRIBUTING.md +[license]: https://github.com/thephpleague/config/blob/main/LICENSE.md +[league-commonmark]: https://commonmark.thephpleague.com diff --git a/vendor/league/config/composer.json b/vendor/league/config/composer.json new file mode 100644 index 0000000..3cd8d87 --- /dev/null +++ b/vendor/league/config/composer.json @@ -0,0 +1,69 @@ +{ + "name": "league/config", + "type": "library", + "description": "Define configuration arrays with strict schemas and access values with dot notation", + "keywords": ["configuration","config","schema","array","nested","dot","dot-access"], + "homepage": "https://config.thephpleague.com", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "support": { + "docs": "https://config.thephpleague.com/", + "issues": "https://github.com/thephpleague/config/issues", + "rss": "https://github.com/thephpleague/config/releases.atom", + "source": "https://github.com/thephpleague/config" + }, + "require": { + "php": "^7.4 || ^8.0", + "dflydev/dot-access-data": "^3.0.1", + "nette/schema": "^1.2" + }, + "require-dev": { + "phpstan/phpstan": "^1.8.2", + "phpunit/phpunit": "^9.5.5", + "scrutinizer/ocular": "^1.8.1", + "unleashedtech/php-coding-standard": "^3.1", + "vimeo/psalm": "^4.7.3" + }, + "minimum-stability": "dev", + "prefer-stable": true, + "autoload": { + "psr-4": { + "League\\Config\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "League\\Config\\Tests\\": "tests" + } + }, + "scripts": { + "phpcs": "phpcs", + "phpstan": "phpstan analyse", + "phpunit": "phpunit --no-coverage", + "psalm": "psalm", + "test": [ + "@phpcs", + "@phpstan", + "@psalm", + "@phpunit" + ] + }, + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + } + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } +} diff --git a/vendor/league/config/src/Configuration.php b/vendor/league/config/src/Configuration.php new file mode 100644 index 0000000..6294367 --- /dev/null +++ b/vendor/league/config/src/Configuration.php @@ -0,0 +1,255 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +use Dflydev\DotAccessData\Data; +use Dflydev\DotAccessData\DataInterface; +use Dflydev\DotAccessData\Exception\DataException; +use Dflydev\DotAccessData\Exception\InvalidPathException; +use Dflydev\DotAccessData\Exception\MissingPathException; +use League\Config\Exception\UnknownOptionException; +use League\Config\Exception\ValidationException; +use Nette\Schema\Expect; +use Nette\Schema\Processor; +use Nette\Schema\Schema; +use Nette\Schema\ValidationException as NetteValidationException; + +final class Configuration implements ConfigurationBuilderInterface, ConfigurationInterface +{ + /** @psalm-readonly */ + private Data $userConfig; + + /** + * @var array<string, Schema> + * + * @psalm-allow-private-mutation + */ + private array $configSchemas = []; + + /** @psalm-allow-private-mutation */ + private Data $finalConfig; + + /** + * @var array<string, mixed> + * + * @psalm-allow-private-mutation + */ + private array $cache = []; + + /** @psalm-readonly */ + private ConfigurationInterface $reader; + + /** + * @param array<string, Schema> $baseSchemas + */ + public function __construct(array $baseSchemas = []) + { + $this->configSchemas = $baseSchemas; + $this->userConfig = new Data(); + $this->finalConfig = new Data(); + + $this->reader = new ReadOnlyConfiguration($this); + } + + /** + * Registers a new configuration schema at the given top-level key + * + * @psalm-allow-private-mutation + */ + public function addSchema(string $key, Schema $schema): void + { + $this->invalidate(); + + $this->configSchemas[$key] = $schema; + } + + /** + * {@inheritDoc} + * + * @psalm-allow-private-mutation + */ + public function merge(array $config = []): void + { + $this->invalidate(); + + $this->userConfig->import($config, DataInterface::REPLACE); + } + + /** + * {@inheritDoc} + * + * @psalm-allow-private-mutation + */ + public function set(string $key, $value): void + { + $this->invalidate(); + + try { + $this->userConfig->set($key, $value); + } catch (DataException $ex) { + throw new UnknownOptionException($ex->getMessage(), $key, (int) $ex->getCode(), $ex); + } + } + + /** + * {@inheritDoc} + * + * @psalm-external-mutation-free + */ + public function get(string $key) + { + if (\array_key_exists($key, $this->cache)) { + return $this->cache[$key]; + } + + try { + $this->build(self::getTopLevelKey($key)); + + return $this->cache[$key] = $this->finalConfig->get($key); + } catch (InvalidPathException | MissingPathException $ex) { + throw new UnknownOptionException($ex->getMessage(), $key, (int) $ex->getCode(), $ex); + } + } + + /** + * {@inheritDoc} + * + * @psalm-external-mutation-free + */ + public function exists(string $key): bool + { + if (\array_key_exists($key, $this->cache)) { + return true; + } + + try { + $this->build(self::getTopLevelKey($key)); + + return $this->finalConfig->has($key); + } catch (InvalidPathException | UnknownOptionException $ex) { + return false; + } + } + + /** + * @psalm-mutation-free + */ + public function reader(): ConfigurationInterface + { + return $this->reader; + } + + /** + * @psalm-external-mutation-free + */ + private function invalidate(): void + { + $this->cache = []; + $this->finalConfig = new Data(); + } + + /** + * Applies the schema against the configuration to return the final configuration + * + * @throws ValidationException|UnknownOptionException|InvalidPathException + * + * @psalm-allow-private-mutation + */ + private function build(string $topLevelKey): void + { + if ($this->finalConfig->has($topLevelKey)) { + return; + } + + if (! isset($this->configSchemas[$topLevelKey])) { + throw new UnknownOptionException(\sprintf('Missing config schema for "%s"', $topLevelKey), $topLevelKey); + } + + try { + $userData = [$topLevelKey => $this->userConfig->get($topLevelKey)]; + } catch (DataException $ex) { + $userData = []; + } + + try { + $schema = $this->configSchemas[$topLevelKey]; + $processor = new Processor(); + + $processed = $processor->process(Expect::structure([$topLevelKey => $schema]), $userData); + + $this->raiseAnyDeprecationNotices($processor->getWarnings()); + + $this->finalConfig->import((array) self::convertStdClassesToArrays($processed)); + } catch (NetteValidationException $ex) { + throw new ValidationException($ex); + } + } + + /** + * Recursively converts stdClass instances to arrays + * + * @phpstan-template T + * + * @param T $data + * + * @return mixed + * + * @phpstan-return ($data is \stdClass ? array<string, mixed> : T) + * + * @psalm-pure + */ + private static function convertStdClassesToArrays($data) + { + if ($data instanceof \stdClass) { + $data = (array) $data; + } + + if (\is_array($data)) { + foreach ($data as $k => $v) { + $data[$k] = self::convertStdClassesToArrays($v); + } + } + + return $data; + } + + /** + * @param string[] $warnings + */ + private function raiseAnyDeprecationNotices(array $warnings): void + { + foreach ($warnings as $warning) { + @\trigger_error($warning, \E_USER_DEPRECATED); + } + } + + /** + * @throws InvalidPathException + */ + private static function getTopLevelKey(string $path): string + { + if (\strlen($path) === 0) { + throw new InvalidPathException('Path cannot be an empty string'); + } + + $path = \str_replace(['.', '/'], '.', $path); + + $firstDelimiter = \strpos($path, '.'); + if ($firstDelimiter === false) { + return $path; + } + + return \substr($path, 0, $firstDelimiter); + } +} diff --git a/vendor/league/config/src/ConfigurationAwareInterface.php b/vendor/league/config/src/ConfigurationAwareInterface.php new file mode 100644 index 0000000..ec5d7b3 --- /dev/null +++ b/vendor/league/config/src/ConfigurationAwareInterface.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +/** + * Implement this class to facilitate setter injection of the configuration where needed + */ +interface ConfigurationAwareInterface +{ + public function setConfiguration(ConfigurationInterface $configuration): void; +} diff --git a/vendor/league/config/src/ConfigurationBuilderInterface.php b/vendor/league/config/src/ConfigurationBuilderInterface.php new file mode 100644 index 0000000..e9c5ed6 --- /dev/null +++ b/vendor/league/config/src/ConfigurationBuilderInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +/** + * An interface that provides the ability to set both the schema and configuration values + */ +interface ConfigurationBuilderInterface extends MutableConfigurationInterface, SchemaBuilderInterface +{ +} diff --git a/vendor/league/config/src/ConfigurationInterface.php b/vendor/league/config/src/ConfigurationInterface.php new file mode 100644 index 0000000..534bd9f --- /dev/null +++ b/vendor/league/config/src/ConfigurationInterface.php @@ -0,0 +1,46 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +use League\Config\Exception\UnknownOptionException; +use League\Config\Exception\ValidationException; + +/** + * Interface for reading configuration values + */ +interface ConfigurationInterface +{ + /** + * @param string $key Configuration option path/key + * + * @psalm-param non-empty-string $key + * + * @return mixed + * + * @throws ValidationException if the schema failed to validate the given input + * @throws UnknownOptionException if the requested key does not exist or is malformed + */ + public function get(string $key); + + /** + * @param string $key Configuration option path/key + * + * @psalm-param non-empty-string $key + * + * @return bool Whether the given option exists + * + * @throws ValidationException if the schema failed to validate the given input + */ + public function exists(string $key): bool; +} diff --git a/vendor/league/config/src/ConfigurationProviderInterface.php b/vendor/league/config/src/ConfigurationProviderInterface.php new file mode 100644 index 0000000..7af6148 --- /dev/null +++ b/vendor/league/config/src/ConfigurationProviderInterface.php @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +/** + * Interface for a service which provides a readable configuration object + */ +interface ConfigurationProviderInterface +{ + public function getConfiguration(): ConfigurationInterface; +} diff --git a/vendor/league/config/src/Exception/ConfigurationExceptionInterface.php b/vendor/league/config/src/Exception/ConfigurationExceptionInterface.php new file mode 100644 index 0000000..db9ee78 --- /dev/null +++ b/vendor/league/config/src/Exception/ConfigurationExceptionInterface.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config\Exception; + +/** + * Marker interface for any/all exceptions thrown by this library + */ +interface ConfigurationExceptionInterface extends \Throwable +{ +} diff --git a/vendor/league/config/src/Exception/InvalidConfigurationException.php b/vendor/league/config/src/Exception/InvalidConfigurationException.php new file mode 100644 index 0000000..f2a6b69 --- /dev/null +++ b/vendor/league/config/src/Exception/InvalidConfigurationException.php @@ -0,0 +1,46 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config\Exception; + +class InvalidConfigurationException extends \UnexpectedValueException implements ConfigurationExceptionInterface +{ + /** + * @param string $option Name/path of the option + * @param mixed $valueGiven The invalid option that was provided + * @param ?string $description Additional text describing the issue (optional) + */ + public static function forConfigOption(string $option, $valueGiven, ?string $description = null): self + { + $message = \sprintf('Invalid config option for "%s": %s', $option, self::getDebugValue($valueGiven)); + if ($description !== null) { + $message .= \sprintf(' (%s)', $description); + } + + return new self($message); + } + + /** + * @param mixed $value + * + * @psalm-pure + */ + private static function getDebugValue($value): string + { + if (\is_object($value)) { + return \get_class($value); + } + + return \print_r($value, true); + } +} diff --git a/vendor/league/config/src/Exception/UnknownOptionException.php b/vendor/league/config/src/Exception/UnknownOptionException.php new file mode 100644 index 0000000..5afba12 --- /dev/null +++ b/vendor/league/config/src/Exception/UnknownOptionException.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config\Exception; + +use Throwable; + +final class UnknownOptionException extends \InvalidArgumentException implements ConfigurationExceptionInterface +{ + private string $path; + + public function __construct(string $message, string $path, int $code = 0, ?Throwable $previous = null) + { + parent::__construct($message, $code, $previous); + + $this->path = $path; + } + + public function getPath(): string + { + return $this->path; + } +} diff --git a/vendor/league/config/src/Exception/ValidationException.php b/vendor/league/config/src/Exception/ValidationException.php new file mode 100644 index 0000000..b43e2f5 --- /dev/null +++ b/vendor/league/config/src/Exception/ValidationException.php @@ -0,0 +1,37 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config\Exception; + +use Nette\Schema\ValidationException as NetteException; + +final class ValidationException extends InvalidConfigurationException +{ + /** @var string[] */ + private array $messages; + + public function __construct(NetteException $innerException) + { + parent::__construct($innerException->getMessage(), (int) $innerException->getCode(), $innerException); + + $this->messages = $innerException->getMessages(); + } + + /** + * @return string[] + */ + public function getMessages(): array + { + return $this->messages; + } +} diff --git a/vendor/league/config/src/MutableConfigurationInterface.php b/vendor/league/config/src/MutableConfigurationInterface.php new file mode 100644 index 0000000..2d4b2ee --- /dev/null +++ b/vendor/league/config/src/MutableConfigurationInterface.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +use League\Config\Exception\UnknownOptionException; + +/** + * Interface for setting/merging user-defined configuration values into the configuration object + */ +interface MutableConfigurationInterface +{ + /** + * @param mixed $value + * + * @throws UnknownOptionException if $key contains a nested path which doesn't point to an array value + */ + public function set(string $key, $value): void; + + /** + * @param array<string, mixed> $config + */ + public function merge(array $config = []): void; +} diff --git a/vendor/league/config/src/ReadOnlyConfiguration.php b/vendor/league/config/src/ReadOnlyConfiguration.php new file mode 100644 index 0000000..58e6171 --- /dev/null +++ b/vendor/league/config/src/ReadOnlyConfiguration.php @@ -0,0 +1,40 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +/** + * Provides read-only access to a given Configuration object + */ +final class ReadOnlyConfiguration implements ConfigurationInterface +{ + private Configuration $config; + + public function __construct(Configuration $config) + { + $this->config = $config; + } + + /** + * {@inheritDoc} + */ + public function get(string $key) + { + return $this->config->get($key); + } + + public function exists(string $key): bool + { + return $this->config->exists($key); + } +} diff --git a/vendor/league/config/src/SchemaBuilderInterface.php b/vendor/league/config/src/SchemaBuilderInterface.php new file mode 100644 index 0000000..3a19807 --- /dev/null +++ b/vendor/league/config/src/SchemaBuilderInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +/* + * This file is part of the league/config package. + * + * (c) Colin O'Dell <colinodell@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace League\Config; + +use Nette\Schema\Schema; + +/** + * Interface that allows new schemas to be added to a configuration + */ +interface SchemaBuilderInterface +{ + /** + * Registers a new configuration schema at the given top-level key + */ + public function addSchema(string $key, Schema $schema): void; +} diff --git a/vendor/league/oauth2-client/LICENSE b/vendor/league/oauth2-client/LICENSE new file mode 100644 index 0000000..9c8958a --- /dev/null +++ b/vendor/league/oauth2-client/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2023 Alex Bilbie <hello@alexbilbie.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/league/oauth2-client/README.md b/vendor/league/oauth2-client/README.md new file mode 100644 index 0000000..c54ecaa --- /dev/null +++ b/vendor/league/oauth2-client/README.md @@ -0,0 +1,54 @@ +# OAuth 2.0 Client + +This package provides a base for integrating with [OAuth 2.0](http://oauth.net/2/) service providers. + +[![Gitter Chat](https://img.shields.io/badge/gitter-join_chat-brightgreen.svg?style=flat-square)](https://gitter.im/thephpleague/oauth2-client) +[![Source Code](https://img.shields.io/badge/source-thephpleague/oauth2--client-blue.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client) +[![Latest Version](https://img.shields.io/github/release/thephpleague/oauth2-client.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client/blob/master/LICENSE) +[![Build Status](https://img.shields.io/github/actions/workflow/status/thephpleague/oauth2-client/continuous-integration.yml?label=CI&logo=github&style=flat-square)](https://github.com/thephpleague/oauth2-client/actions?query=workflow%3ACI) +[![Codecov Code Coverage](https://img.shields.io/codecov/c/gh/thephpleague/oauth2-client?label=codecov&logo=codecov&style=flat-square)](https://codecov.io/gh/thephpleague/oauth2-client) +[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth2-client.svg?style=flat-square)](https://packagist.org/packages/league/oauth2-client) + +--- + +The OAuth 2.0 login flow, seen commonly around the web in the form of "Connect with Facebook/Google/etc." buttons, is a common integration added to web applications, but it can be tricky and tedious to do right. To help, we've created the `league/oauth2-client` package, which provides a base for integrating with various OAuth 2.0 providers, without overburdening your application with the concerns of [RFC 6749](http://tools.ietf.org/html/rfc6749). + +This OAuth 2.0 client library will work with any OAuth 2.0 provider that conforms to the OAuth 2.0 Authorization Framework. Out-of-the-box, we provide a `GenericProvider` class to connect to any service provider that uses [Bearer tokens](http://tools.ietf.org/html/rfc6750). See our [basic usage guide](https://oauth2-client.thephpleague.com/usage/) for examples using `GenericProvider`. + +Many service providers provide additional functionality above and beyond the OAuth 2.0 specification. For this reason, you may extend and wrap this library to support additional behavior. There are already many [official](https://oauth2-client.thephpleague.com/providers/league/) and [third-party](https://oauth2-client.thephpleague.com/providers/thirdparty/) provider clients available (e.g., Facebook, GitHub, Google, Instagram, LinkedIn, etc.). If your provider isn't in the list, feel free to add it. + +This package is compliant with [PSR-1][], [PSR-2][], [PSR-4][], and [PSR-7][]. If you notice compliance oversights, please send a patch via pull request. If you're interested in contributing to this library, please take a look at our [contributing guidelines](https://github.com/thephpleague/oauth2-client/blob/master/CONTRIBUTING.md). + +## Requirements + +We support the following versions of PHP: + +- PHP 8.6 +- PHP 8.5 +- PHP 8.4 +- PHP 8.3 +- PHP 8.2 + +## Provider Clients + +We provide a list of [official PHP League provider clients](https://oauth2-client.thephpleague.com/providers/league/), as well as [third-party provider clients](https://oauth2-client.thephpleague.com/providers/thirdparty/). + +To build your own provider client, please refer to "[Implementing a Provider Client](https://oauth2-client.thephpleague.com/providers/implementing/)." + +## Usage + +For usage and code examples, check out our [basic usage guide](https://oauth2-client.thephpleague.com/usage/). + +## Contributing + +Please see [our contributing guidelines](https://github.com/thephpleague/oauth2-client/blob/master/CONTRIBUTING.md) for details. + +## License + +The MIT License (MIT). Please see [LICENSE](https://github.com/thephpleague/oauth2-client/blob/master/LICENSE) for more information. + +[PSR-1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md +[PSR-2]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md +[PSR-4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md +[PSR-7]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-7-http-message.md diff --git a/vendor/league/oauth2-client/composer.json b/vendor/league/oauth2-client/composer.json new file mode 100644 index 0000000..1036364 --- /dev/null +++ b/vendor/league/oauth2-client/composer.json @@ -0,0 +1,58 @@ +{ + "name": "league/oauth2-client", + "description": "OAuth 2.0 Client Library", + "license": "MIT", + "config": { + "sort-packages": true + }, + "require": { + "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", + "ext-json": "*", + "guzzlehttp/guzzle": "^8.5.2", + "guzzlehttp/psr7": "^3.5.1" + }, + "require-dev": { + "mockery/mockery": "^1.6.15", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpunit/phpunit": "^11.5.58", + "squizlabs/php_codesniffer": "^4.0.4" + }, + "keywords": [ + "oauth", + "oauth2", + "authorization", + "authentication", + "idp", + "identity", + "sso", + "single sign on" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Woody Gilk", + "homepage": "https://github.com/shadowhand", + "role": "Contributor" + }, + { + "name": "Andrew Millington", + "homepage": "https://github.com/sephster", + "role": "Developer" + } + ], + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\OAuth2\\Client\\Test\\": "test/src/" + } + } +} diff --git a/vendor/league/oauth2-client/phpunit.xml.dist b/vendor/league/oauth2-client/phpunit.xml.dist new file mode 100644 index 0000000..e63822b --- /dev/null +++ b/vendor/league/oauth2-client/phpunit.xml.dist @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" + bootstrap="./vendor/autoload.php" + colors="true" + cacheDirectory="build/phpunit"> + + <coverage> + <report> + <clover outputFile="build/logs/clover.xml"/> + <html outputDirectory="build/coverage"/> + <text outputFile="php://stdout"/> + </report> + </coverage> + + <testsuites> + <testsuite name="all"> + <directory>test</directory> + </testsuite> + </testsuites> + + <logging> + <junit outputFile="build/report.junit.xml"/> + </logging> + + <source> + <include> + <directory suffix=".php">src</directory> + </include> + </source> + + <php> + <env name="XDEBUG_MODE" value="coverage"/> + </php> + +</phpunit> diff --git a/vendor/league/oauth2-client/src/Grant/AbstractGrant.php b/vendor/league/oauth2-client/src/Grant/AbstractGrant.php new file mode 100644 index 0000000..2c0244b --- /dev/null +++ b/vendor/league/oauth2-client/src/Grant/AbstractGrant.php @@ -0,0 +1,80 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +use League\OAuth2\Client\Tool\RequiredParameterTrait; + +/** + * Represents a type of authorization grant. + * + * An authorization grant is a credential representing the resource + * owner's authorization (to access its protected resources) used by the + * client to obtain an access token. OAuth 2.0 defines four + * grant types -- authorization code, implicit, resource owner password + * credentials, and client credentials -- as well as an extensibility + * mechanism for defining additional types. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3 Authorization Grant (RFC 6749, §1.3) + */ +abstract class AbstractGrant +{ + use RequiredParameterTrait; + + /** + * Returns the name of this grant, eg. 'grant_name', which is used as the + * grant type when encoding URL query parameters. + * + * @return string + */ + abstract protected function getName(); + + /** + * Returns a list of all required request parameters. + * + * @return array + */ + abstract protected function getRequiredRequestParameters(); + + /** + * Returns this grant's name as its string representation. This allows for + * string interpolation when building URL query parameters. + * + * @return string + */ + public function __toString() + { + return $this->getName(); + } + + /** + * Prepares an access token request's parameters by checking that all + * required parameters are set, then merging with any given defaults. + * + * @param array $defaults + * @param array $options + * @return array + */ + public function prepareRequestParameters(array $defaults, array $options) + { + $defaults['grant_type'] = $this->getName(); + + $required = $this->getRequiredRequestParameters(); + $provided = array_merge($defaults, $options); + + $this->checkRequiredParameters($required, $provided); + + return $provided; + } +} diff --git a/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php b/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php new file mode 100644 index 0000000..c49460c --- /dev/null +++ b/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php @@ -0,0 +1,41 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents an authorization code grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.1 Authorization Code (RFC 6749, §1.3.1) + */ +class AuthorizationCode extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'authorization_code'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'code', + ]; + } +} diff --git a/vendor/league/oauth2-client/src/Grant/ClientCredentials.php b/vendor/league/oauth2-client/src/Grant/ClientCredentials.php new file mode 100644 index 0000000..dc78c4f --- /dev/null +++ b/vendor/league/oauth2-client/src/Grant/ClientCredentials.php @@ -0,0 +1,39 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a client credentials grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.4 Client Credentials (RFC 6749, §1.3.4) + */ +class ClientCredentials extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'client_credentials'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return []; + } +} diff --git a/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php b/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php new file mode 100644 index 0000000..c3c4e67 --- /dev/null +++ b/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php @@ -0,0 +1,26 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant\Exception; + +use InvalidArgumentException; + +/** + * Exception thrown if the grant does not extend from AbstractGrant. + * + * @see League\OAuth2\Client\Grant\AbstractGrant + */ +class InvalidGrantException extends InvalidArgumentException +{ +} diff --git a/vendor/league/oauth2-client/src/Grant/GrantFactory.php b/vendor/league/oauth2-client/src/Grant/GrantFactory.php new file mode 100644 index 0000000..71990e8 --- /dev/null +++ b/vendor/league/oauth2-client/src/Grant/GrantFactory.php @@ -0,0 +1,104 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +use League\OAuth2\Client\Grant\Exception\InvalidGrantException; + +/** + * Represents a factory used when retrieving an authorization grant type. + */ +class GrantFactory +{ + /** + * @var array + */ + protected $registry = []; + + /** + * Defines a grant singleton in the registry. + * + * @param string $name + * @param AbstractGrant $grant + * @return self + */ + public function setGrant($name, AbstractGrant $grant) + { + $this->registry[$name] = $grant; + + return $this; + } + + /** + * Returns a grant singleton by name. + * + * If the grant has not be registered, a default grant will be loaded. + * + * @param string $name + * @return AbstractGrant + */ + public function getGrant($name) + { + if (empty($this->registry[$name])) { + $this->registerDefaultGrant($name); + } + + return $this->registry[$name]; + } + + /** + * Registers a default grant singleton by name. + * + * @param string $name + * @return self + */ + protected function registerDefaultGrant($name) + { + // PascalCase the grant. E.g: 'authorization_code' becomes 'AuthorizationCode' + $class = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $name))); + $class = 'League\\OAuth2\\Client\\Grant\\' . $class; + + $this->checkGrant($class); + + return $this->setGrant($name, new $class); + } + + /** + * Determines if a variable is a valid grant. + * + * @param mixed $class + * @return boolean + */ + public function isGrant($class) + { + return is_subclass_of($class, AbstractGrant::class); + } + + /** + * Checks if a variable is a valid grant. + * + * @throws InvalidGrantException + * @param mixed $class + * @return void + */ + public function checkGrant($class) + { + if (!$this->isGrant($class)) { + throw new InvalidGrantException(sprintf( + 'Grant "%s" must extend AbstractGrant', + is_object($class) ? get_class($class) : $class + )); + } + } +} diff --git a/vendor/league/oauth2-client/src/Grant/Password.php b/vendor/league/oauth2-client/src/Grant/Password.php new file mode 100644 index 0000000..6543b2e --- /dev/null +++ b/vendor/league/oauth2-client/src/Grant/Password.php @@ -0,0 +1,42 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a resource owner password credentials grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.3 Resource Owner Password Credentials (RFC 6749, §1.3.3) + */ +class Password extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'password'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'username', + 'password', + ]; + } +} diff --git a/vendor/league/oauth2-client/src/Grant/RefreshToken.php b/vendor/league/oauth2-client/src/Grant/RefreshToken.php new file mode 100644 index 0000000..8192182 --- /dev/null +++ b/vendor/league/oauth2-client/src/Grant/RefreshToken.php @@ -0,0 +1,41 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a refresh token grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-6 Refreshing an Access Token (RFC 6749, §6) + */ +class RefreshToken extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'refresh_token'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'refresh_token', + ]; + } +} diff --git a/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php b/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php new file mode 100644 index 0000000..3da4065 --- /dev/null +++ b/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php @@ -0,0 +1,42 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +use InvalidArgumentException; + +/** + * Add http basic auth into access token request options + * @link https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +class HttpBasicAuthOptionProvider extends PostAuthOptionProvider +{ + /** + * @inheritdoc + */ + public function getAccessTokenOptions($method, array $params) + { + if (empty($params['client_id']) || empty($params['client_secret'])) { + throw new InvalidArgumentException('clientId and clientSecret are required for http basic auth'); + } + + $encodedCredentials = base64_encode(sprintf('%s:%s', $params['client_id'], $params['client_secret'])); + unset($params['client_id'], $params['client_secret']); + + $options = parent::getAccessTokenOptions($method, $params); + $options['headers']['Authorization'] = 'Basic ' . $encodedCredentials; + + return $options; + } +} diff --git a/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php b/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php new file mode 100644 index 0000000..1126d25 --- /dev/null +++ b/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php @@ -0,0 +1,30 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +/** + * Interface for access token options provider + */ +interface OptionProviderInterface +{ + /** + * Builds request options used for requesting an access token. + * + * @param string $method + * @param array $params + * @return array + */ + public function getAccessTokenOptions($method, array $params); +} diff --git a/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php b/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php new file mode 100644 index 0000000..12d920e --- /dev/null +++ b/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php @@ -0,0 +1,51 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +use League\OAuth2\Client\Provider\AbstractProvider; +use League\OAuth2\Client\Tool\QueryBuilderTrait; + +/** + * Provide options for access token + */ +class PostAuthOptionProvider implements OptionProviderInterface +{ + use QueryBuilderTrait; + + /** + * @inheritdoc + */ + public function getAccessTokenOptions($method, array $params) + { + $options = ['headers' => ['content-type' => 'application/x-www-form-urlencoded']]; + + if ($method === AbstractProvider::METHOD_POST) { + $options['body'] = $this->getAccessTokenBody($params); + } + + return $options; + } + + /** + * Returns the request body for requesting an access token. + * + * @param array $params + * @return string + */ + protected function getAccessTokenBody(array $params) + { + return $this->buildQueryString($params); + } +} diff --git a/vendor/league/oauth2-client/src/Provider/AbstractProvider.php b/vendor/league/oauth2-client/src/Provider/AbstractProvider.php new file mode 100644 index 0000000..eb62417 --- /dev/null +++ b/vendor/league/oauth2-client/src/Provider/AbstractProvider.php @@ -0,0 +1,961 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +use GuzzleHttp\Client as HttpClient; +use GuzzleHttp\ClientInterface as HttpClientInterface; +use GuzzleHttp\Exception\BadResponseException; +use GuzzleHttp\Exception\GuzzleException; +use InvalidArgumentException; +use League\OAuth2\Client\Grant\AbstractGrant; +use League\OAuth2\Client\Grant\GrantFactory; +use League\OAuth2\Client\OptionProvider\OptionProviderInterface; +use League\OAuth2\Client\OptionProvider\PostAuthOptionProvider; +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Token\AccessTokenInterface; +use League\OAuth2\Client\Tool\ArrayAccessorTrait; +use League\OAuth2\Client\Tool\GuardedPropertyTrait; +use League\OAuth2\Client\Tool\QueryBuilderTrait; +use League\OAuth2\Client\Tool\RequestFactory; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; +use UnexpectedValueException; + +/** + * Represents a service provider (authorization server). + * + * @link http://tools.ietf.org/html/rfc6749#section-1.1 Roles (RFC 6749, §1.1) + */ +abstract class AbstractProvider +{ + use ArrayAccessorTrait; + use GuardedPropertyTrait; + use QueryBuilderTrait; + + /** + * @var string|null Key used in a token response to identify the resource owner. + */ + const ACCESS_TOKEN_RESOURCE_OWNER_ID = null; + + /** + * @var string HTTP method used to fetch access tokens. + */ + const METHOD_GET = 'GET'; + + /** + * @var string HTTP method used to fetch access tokens. + */ + const METHOD_POST = 'POST'; + + /** + * @var string PKCE method used to fetch authorization token. + * The PKCE code challenge will be hashed with sha256 (recommended). + */ + const PKCE_METHOD_S256 = 'S256'; + + /** + * @var string PKCE method used to fetch authorization token. + * The PKCE code challenge will be sent as plain text, this is NOT recommended. + * Only use `plain` if no other option is possible. + */ + const PKCE_METHOD_PLAIN = 'plain'; + + /** + * @var string + */ + protected $clientId; + + /** + * @var string + */ + protected $clientSecret; + + /** + * @var string + */ + protected $redirectUri; + + /** + * @var string + */ + protected $state; + + /** + * @var string|null + */ + protected $pkceCode = null; + + /** + * @var GrantFactory + */ + protected $grantFactory; + + /** + * @var RequestFactory + */ + protected $requestFactory; + + /** + * @var HttpClientInterface + */ + protected $httpClient; + + /** + * @var OptionProviderInterface + */ + protected $optionProvider; + + /** + * Constructs an OAuth 2.0 service provider. + * + * @param array $options An array of options to set on this provider. + * Options include `clientId`, `clientSecret`, `redirectUri`, and `state`. + * Individual providers may introduce more options, as needed. + * @param array $collaborators An array of collaborators that may be used to + * override this provider's default behavior. Collaborators include + * `grantFactory`, `requestFactory`, and `httpClient`. + * Individual providers may introduce more collaborators, as needed. + */ + public function __construct(array $options = [], array $collaborators = []) + { + // We'll let the GuardedPropertyTrait handle mass assignment of incoming + // options, skipping any blacklisted properties defined in the provider + $this->fillProperties($options); + + if (empty($collaborators['grantFactory'])) { + $collaborators['grantFactory'] = new GrantFactory(); + } + $this->setGrantFactory($collaborators['grantFactory']); + + if (empty($collaborators['requestFactory'])) { + $collaborators['requestFactory'] = new RequestFactory(); + } + $this->setRequestFactory($collaborators['requestFactory']); + + if (empty($collaborators['httpClient'])) { + $client_options = $this->getAllowedClientOptions($options); + + $collaborators['httpClient'] = new HttpClient( + array_intersect_key($options, array_flip($client_options)) + ); + } + $this->setHttpClient($collaborators['httpClient']); + + if (empty($collaborators['optionProvider'])) { + $collaborators['optionProvider'] = new PostAuthOptionProvider(); + } + $this->setOptionProvider($collaborators['optionProvider']); + } + + /** + * Returns the list of options that can be passed to the HttpClient + * + * @param array $options An array of options to set on this provider. + * Options include `clientId`, `clientSecret`, `redirectUri`, and `state`. + * Individual providers may introduce more options, as needed. + * @return array The options to pass to the HttpClient constructor + */ + protected function getAllowedClientOptions(array $options) + { + $client_options = ['timeout', 'proxy']; + + // Only allow turning off ssl verification if it's for a proxy + if (!empty($options['proxy'])) { + $client_options[] = 'verify'; + } + + return $client_options; + } + + /** + * Sets the grant factory instance. + * + * @param GrantFactory $factory + * @return self + */ + public function setGrantFactory(GrantFactory $factory) + { + $this->grantFactory = $factory; + + return $this; + } + + /** + * Returns the current grant factory instance. + * + * @return GrantFactory + */ + public function getGrantFactory() + { + return $this->grantFactory; + } + + /** + * Sets the request factory instance. + * + * @param RequestFactory $factory + * @return self + */ + public function setRequestFactory(RequestFactory $factory) + { + $this->requestFactory = $factory; + + return $this; + } + + /** + * Returns the request factory instance. + * + * @return RequestFactory + */ + public function getRequestFactory() + { + return $this->requestFactory; + } + + /** + * Sets the HTTP client instance. + * + * @param HttpClientInterface $client + * @return self + */ + public function setHttpClient(HttpClientInterface $client) + { + $this->httpClient = $client; + + return $this; + } + + /** + * Returns the HTTP client instance. + * + * @return HttpClientInterface + */ + public function getHttpClient() + { + return $this->httpClient; + } + + /** + * Sets the option provider instance. + * + * @param OptionProviderInterface $provider + * @return self + */ + public function setOptionProvider(OptionProviderInterface $provider) + { + $this->optionProvider = $provider; + + return $this; + } + + /** + * Returns the option provider instance. + * + * @return OptionProviderInterface + */ + public function getOptionProvider() + { + return $this->optionProvider; + } + + /** + * Returns the current value of the state parameter. + * + * This can be accessed by the redirect handler during authorization. + * + * @return string + */ + public function getState() + { + return $this->state; + } + + /** + * Set the value of the pkceCode parameter. + * + * When using PKCE this should be set before requesting an access token. + * + * @param string $pkceCode + * @return self + */ + public function setPkceCode($pkceCode) + { + $this->pkceCode = $pkceCode; + return $this; + } + + /** + * Returns the current value of the pkceCode parameter. + * + * This can be accessed by the redirect handler during authorization. + * + * @return string|null + */ + public function getPkceCode() + { + return $this->pkceCode; + } + + /** + * Returns the base URL for authorizing a client. + * + * Eg. https://oauth.service.com/authorize + * + * @return string + */ + abstract public function getBaseAuthorizationUrl(); + + /** + * Returns the base URL for requesting an access token. + * + * Eg. https://oauth.service.com/token + * + * @param array $params + * @return string + */ + abstract public function getBaseAccessTokenUrl(array $params); + + /** + * Returns the URL for requesting the resource owner's details. + * + * @param AccessToken $token + * @return string + */ + abstract public function getResourceOwnerDetailsUrl(AccessToken $token); + + /** + * Returns a new random string to use as the state parameter in an + * authorization flow. + * + * @param int $length Length of the random string to be generated. + * @return string + */ + protected function getRandomState($length = 32) + { + // Converting bytes to hex will always double length. Hence, we can reduce + // the amount of bytes by half to produce the correct length. + return bin2hex(random_bytes($length / 2)); + } + + /** + * Returns a new random string to use as PKCE code_verifier and + * hashed as code_challenge parameters in an authorization flow. + * Must be between 43 and 128 characters long. + * + * @param int $length Length of the random string to be generated. + * @return string + */ + protected function getRandomPkceCode($length = 64) + { + return substr( + strtr( + base64_encode(random_bytes($length)), + '+/', + '-_' + ), + 0, + $length + ); + } + + /** + * Returns the default scopes used by this provider. + * + * This should only be the scopes that are required to request the details + * of the resource owner, rather than all the available scopes. + * + * @return array + */ + abstract protected function getDefaultScopes(); + + /** + * Returns the string that should be used to separate scopes when building + * the URL for requesting an access token. + * + * @return string Scope separator, defaults to ',' + */ + protected function getScopeSeparator() + { + return ','; + } + + /** + * @return string|null + */ + protected function getPkceMethod() + { + return null; + } + + /** + * Returns authorization parameters based on provided options. + * + * @param array $options + * @return array Authorization parameters + * @throws InvalidArgumentException + */ + protected function getAuthorizationParameters(array $options) + { + if (empty($options['state'])) { + $options['state'] = $this->getRandomState(); + } + + if (empty($options['scope'])) { + $options['scope'] = $this->getDefaultScopes(); + } + + $options += [ + 'response_type' => 'code', + 'approval_prompt' => 'auto' + ]; + + if (is_array($options['scope'])) { + $separator = $this->getScopeSeparator(); + $options['scope'] = implode($separator, $options['scope']); + } + + // Store the state as it may need to be accessed later on. + $this->state = $options['state']; + + $pkceMethod = $this->getPkceMethod(); + if (!empty($pkceMethod)) { + $this->pkceCode = $this->getRandomPkceCode(); + if ($pkceMethod === static::PKCE_METHOD_S256) { + $options['code_challenge'] = trim( + strtr( + base64_encode(hash('sha256', $this->pkceCode, true)), + '+/', + '-_' + ), + '=' + ); + } elseif ($pkceMethod === static::PKCE_METHOD_PLAIN) { + $options['code_challenge'] = $this->pkceCode; + } else { + throw new InvalidArgumentException('Unknown PKCE method "' . $pkceMethod . '".'); + } + $options['code_challenge_method'] = $pkceMethod; + } + + // Business code layer might set a different redirect_uri parameter + // depending on the context, leave it as-is + if (!isset($options['redirect_uri'])) { + $options['redirect_uri'] = $this->redirectUri; + } + + $options['client_id'] = $this->clientId; + + return $options; + } + + /** + * Builds the authorization URL's query string. + * + * @param array $params Query parameters + * @return string Query string + */ + protected function getAuthorizationQuery(array $params) + { + return $this->buildQueryString($params); + } + + /** + * Builds the authorization URL. + * + * @param array $options + * @return string Authorization URL + * @throws InvalidArgumentException + */ + public function getAuthorizationUrl(array $options = []) + { + $base = $this->getBaseAuthorizationUrl(); + $params = $this->getAuthorizationParameters($options); + $query = $this->getAuthorizationQuery($params); + + return $this->appendQuery($base, $query); + } + + /** + * Redirects the client for authorization. + * + * @param array $options + * @param callable|null $redirectHandler + * @return mixed + * @throws InvalidArgumentException + */ + public function authorize( + array $options = [], + ?callable $redirectHandler = null + ) { + $url = $this->getAuthorizationUrl($options); + if ($redirectHandler) { + return $redirectHandler($url, $this); + } + + // @codeCoverageIgnoreStart + header('Location: ' . $url); + exit; + // @codeCoverageIgnoreEnd + } + + /** + * Appends a query string to a URL. + * + * @param string $url The URL to append the query to + * @param string $query The HTTP query string + * @return string The resulting URL + */ + protected function appendQuery($url, $query) + { + $query = trim($query, '?&'); + + if ($query) { + $glue = strstr($url, '?') === false ? '?' : '&'; + return $url . $glue . $query; + } + + return $url; + } + + /** + * Returns the method to use when requesting an access token. + * + * @return string HTTP method + */ + protected function getAccessTokenMethod() + { + return self::METHOD_POST; + } + + /** + * Returns the key used in the access token response to identify the resource owner. + * + * @return string|null Resource owner identifier key + */ + protected function getAccessTokenResourceOwnerId() + { + return static::ACCESS_TOKEN_RESOURCE_OWNER_ID; + } + + /** + * Builds the access token URL's query string. + * + * @param array $params Query parameters + * @return string Query string + */ + protected function getAccessTokenQuery(array $params) + { + return $this->buildQueryString($params); + } + + /** + * Checks that a provided grant is valid, or attempts to produce one if the + * provided grant is a string. + * + * @param AbstractGrant|string $grant + * @return AbstractGrant + */ + protected function verifyGrant($grant) + { + if (is_string($grant)) { + return $this->grantFactory->getGrant($grant); + } + + $this->grantFactory->checkGrant($grant); + return $grant; + } + + /** + * Returns the full URL to use when requesting an access token. + * + * @param array $params Query parameters + * @return string + */ + protected function getAccessTokenUrl(array $params) + { + $url = $this->getBaseAccessTokenUrl($params); + + if ($this->getAccessTokenMethod() === self::METHOD_GET) { + $query = $this->getAccessTokenQuery($params); + return $this->appendQuery($url, $query); + } + + return $url; + } + + /** + * Returns a prepared request for requesting an access token. + * + * @param array $params Query string parameters + * @return RequestInterface + */ + protected function getAccessTokenRequest(array $params) + { + $method = $this->getAccessTokenMethod(); + $url = $this->getAccessTokenUrl($params); + $options = $this->optionProvider->getAccessTokenOptions($this->getAccessTokenMethod(), $params); + + return $this->getRequest($method, $url, $options); + } + + /** + * Requests an access token using a specified grant and option set. + * + * @param mixed $grant + * @param array<string, mixed> $options + * @return AccessTokenInterface + * @throws IdentityProviderException + * @throws UnexpectedValueException + * @throws GuzzleException + */ + public function getAccessToken($grant, array $options = []) + { + $grant = $this->verifyGrant($grant); + + if (isset($options['scope']) && is_array($options['scope'])) { + $separator = $this->getScopeSeparator(); + $options['scope'] = implode($separator, $options['scope']); + } + + $params = [ + 'client_id' => $this->clientId, + 'client_secret' => $this->clientSecret, + 'redirect_uri' => $this->redirectUri, + ]; + + if (!empty($this->pkceCode)) { + $params['code_verifier'] = $this->pkceCode; + } + + $params = $grant->prepareRequestParameters($params, $options); + $request = $this->getAccessTokenRequest($params); + $response = $this->getParsedResponse($request); + if (false === is_array($response)) { + throw new UnexpectedValueException( + 'Invalid response received from Authorization Server. Expected JSON.' + ); + } + $prepared = $this->prepareAccessTokenResponse($response); + $token = $this->createAccessToken($prepared, $grant); + + return $token; + } + + /** + * Returns a PSR-7 request instance that is not authenticated. + * + * @param string $method + * @param string $url + * @param array $options + * @return RequestInterface + */ + public function getRequest($method, $url, array $options = []) + { + return $this->createRequest($method, $url, null, $options); + } + + /** + * Returns an authenticated PSR-7 request instance. + * + * @param string $method + * @param string $url + * @param AccessTokenInterface|string|null $token + * @param array $options Any of "headers", "body", and "protocolVersion". + * @return RequestInterface + */ + public function getAuthenticatedRequest($method, $url, $token, array $options = []) + { + return $this->createRequest($method, $url, $token, $options); + } + + /** + * Creates a PSR-7 request instance. + * + * @param string $method + * @param string $url + * @param AccessTokenInterface|string|null $token + * @param array $options + * @return RequestInterface + */ + protected function createRequest($method, $url, $token, array $options) + { + $defaults = [ + 'headers' => $this->getHeaders($token), + ]; + + $options = array_merge_recursive($defaults, $options); + $factory = $this->getRequestFactory(); + + return $factory->getRequestWithOptions($method, $url, $options); + } + + /** + * Sends a request instance and returns a response instance. + * + * WARNING: This method does not attempt to catch exceptions caused by HTTP + * errors! It is recommended to wrap this method in a try/catch block. + * + * @param RequestInterface $request + * @return ResponseInterface + * @throws GuzzleException + */ + public function getResponse(RequestInterface $request) + { + return $this->getHttpClient()->send($request); + } + + /** + * Sends a request and returns the parsed response. + * + * @param RequestInterface $request + * @return mixed + * @throws IdentityProviderException + * @throws UnexpectedValueException + * @throws GuzzleException + */ + public function getParsedResponse(RequestInterface $request) + { + try { + $response = $this->getResponse($request); + } catch (BadResponseException $e) { + $response = $e->getResponse(); + } + + $parsed = $this->parseResponse($response); + + $this->checkResponse($response, $parsed); + + return $parsed; + } + + /** + * Attempts to parse a JSON response. + * + * @param string $content JSON content from response body + * @return array Parsed JSON data + * @throws UnexpectedValueException if the content could not be parsed + */ + protected function parseJson($content) + { + $content = json_decode($content, true); + + if (json_last_error() !== JSON_ERROR_NONE) { + throw new UnexpectedValueException(sprintf( + "Failed to parse JSON response: %s", + json_last_error_msg() + )); + } + + return $content; + } + + /** + * Returns the content type header of a response. + * + * @param ResponseInterface $response + * @return string Semi-colon separated join of content-type headers. + */ + protected function getContentType(ResponseInterface $response) + { + return implode(';', $response->getHeader('content-type')); + } + + /** + * Parses the response according to its content-type header. + * + * @throws UnexpectedValueException + * @param ResponseInterface $response + * @return array + */ + protected function parseResponse(ResponseInterface $response) + { + $content = (string) $response->getBody(); + $type = $this->getContentType($response); + + if (strpos($type, 'urlencoded') !== false) { + parse_str($content, $parsed); + return $parsed; + } + + // Attempt to parse the string as JSON regardless of content type, + // since some providers use non-standard content types. Only throw an + // exception if the JSON could not be parsed when it was expected to. + try { + return $this->parseJson($content); + } catch (UnexpectedValueException $e) { + if (strpos($type, 'json') !== false) { + throw $e; + } + + if ($response->getStatusCode() == 500) { + throw new UnexpectedValueException( + 'An OAuth server error was encountered that did not contain a JSON body', + 0, + $e + ); + } + + return $content; + } + } + + /** + * Checks a provider response for errors. + * + * @throws IdentityProviderException + * @param ResponseInterface $response + * @param array|string $data Parsed response data + * @return void + */ + abstract protected function checkResponse(ResponseInterface $response, $data); + + /** + * Prepares an parsed access token response for a grant. + * + * Custom mapping of expiration, etc should be done here. Always call the + * parent method when overloading this method. + * + * @param array<string, mixed> $result + * @return array + */ + protected function prepareAccessTokenResponse(array $result) + { + if ($this->getAccessTokenResourceOwnerId() !== null) { + $result['resource_owner_id'] = $this->getValueByKey( + $result, + $this->getAccessTokenResourceOwnerId() + ); + } + return $result; + } + + /** + * Creates an access token from a response. + * + * The grant that was used to fetch the response can be used to provide + * additional context. + * + * @param array $response + * @param AbstractGrant $grant + * @return AccessTokenInterface + */ + protected function createAccessToken(array $response, AbstractGrant $grant) + { + return new AccessToken($response); + } + + /** + * Generates a resource owner object from a successful resource owner + * details request. + * + * @param array $response + * @param AccessToken $token + * @return ResourceOwnerInterface + */ + abstract protected function createResourceOwner(array $response, AccessToken $token); + + /** + * Requests and returns the resource owner of given access token. + * + * @param AccessToken $token + * @return ResourceOwnerInterface + * @throws IdentityProviderException + * @throws UnexpectedValueException + * @throws GuzzleException + */ + public function getResourceOwner(AccessToken $token) + { + $response = $this->fetchResourceOwnerDetails($token); + + return $this->createResourceOwner($response, $token); + } + + /** + * Requests resource owner details. + * + * @param AccessToken $token + * @return mixed + * @throws IdentityProviderException + * @throws UnexpectedValueException + * @throws GuzzleException + */ + protected function fetchResourceOwnerDetails(AccessToken $token) + { + $url = $this->getResourceOwnerDetailsUrl($token); + + $request = $this->getAuthenticatedRequest(self::METHOD_GET, $url, $token); + + $response = $this->getParsedResponse($request); + + if (false === is_array($response)) { + throw new UnexpectedValueException( + 'Invalid response received from Authorization Server. Expected JSON.' + ); + } + + return $response; + } + + /** + * Returns the default headers used by this provider. + * + * Typically this is used to set 'Accept' or 'Content-Type' headers. + * + * @return array + */ + protected function getDefaultHeaders() + { + return []; + } + + /** + * Returns the authorization headers used by this provider. + * + * Typically this is "Bearer" or "MAC". For more information see: + * http://tools.ietf.org/html/rfc6749#section-7.1 + * + * No default is provided, providers must overload this method to activate + * authorization headers. + * + * @param mixed|null $token Either a string or an access token instance + * @return array + */ + protected function getAuthorizationHeaders($token = null) + { + return []; + } + + /** + * Returns all headers used by this provider for a request. + * + * The request will be authenticated if an access token is provided. + * + * @param mixed|null $token object or string + * @return array + */ + public function getHeaders($token = null) + { + if ($token) { + return array_merge( + $this->getDefaultHeaders(), + $this->getAuthorizationHeaders($token) + ); + } + + return $this->getDefaultHeaders(); + } +} diff --git a/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php b/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php new file mode 100644 index 0000000..55cb438 --- /dev/null +++ b/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php @@ -0,0 +1,48 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider\Exception; + +/** + * Exception thrown if the provider response contains errors. + */ +class IdentityProviderException extends \Exception +{ + /** + * @var mixed + */ + protected $response; + + /** + * @param string $message + * @param int $code + * @param mixed $response The response body + */ + public function __construct($message, $code, $response) + { + $this->response = $response; + + parent::__construct($message, $code); + } + + /** + * Returns the exception's response body. + * + * @return mixed + */ + public function getResponseBody() + { + return $this->response; + } +} diff --git a/vendor/league/oauth2-client/src/Provider/GenericProvider.php b/vendor/league/oauth2-client/src/Provider/GenericProvider.php new file mode 100644 index 0000000..0fc95f2 --- /dev/null +++ b/vendor/league/oauth2-client/src/Provider/GenericProvider.php @@ -0,0 +1,247 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +use InvalidArgumentException; +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Tool\BearerAuthorizationTrait; +use Psr\Http\Message\ResponseInterface; + +/** + * Represents a generic service provider that may be used to interact with any + * OAuth 2.0 service provider, using Bearer token authentication. + */ +class GenericProvider extends AbstractProvider +{ + use BearerAuthorizationTrait; + + /** + * @var string + */ + private $urlAuthorize; + + /** + * @var string + */ + private $urlAccessToken; + + /** + * @var string + */ + private $urlResourceOwnerDetails; + + /** + * @var string + */ + private $accessTokenMethod; + + /** + * @var string + */ + private $accessTokenResourceOwnerId; + + /** + * @var array|null + */ + private $scopes = null; + + /** + * @var string + */ + private $scopeSeparator; + + /** + * @var string + */ + private $responseError = 'error'; + + /** + * @var string + */ + private $responseCode; + + /** + * @var string + */ + private $responseResourceOwnerId = 'id'; + + /** + * @var string|null + */ + private $pkceMethod = null; + + /** + * @param array $options + * @param array $collaborators + */ + public function __construct(array $options = [], array $collaborators = []) + { + $this->assertRequiredOptions($options); + + $possible = $this->getConfigurableOptions(); + $configured = array_intersect_key($options, array_flip($possible)); + + foreach ($configured as $key => $value) { + $this->$key = $value; + } + + // Remove all options that are only used locally + $options = array_diff_key($options, $configured); + + parent::__construct($options, $collaborators); + } + + /** + * Returns all options that can be configured. + * + * @return array + */ + protected function getConfigurableOptions() + { + return array_merge($this->getRequiredOptions(), [ + 'accessTokenMethod', + 'accessTokenResourceOwnerId', + 'scopeSeparator', + 'responseError', + 'responseCode', + 'responseResourceOwnerId', + 'scopes', + 'pkceMethod', + ]); + } + + /** + * Returns all options that are required. + * + * @return array + */ + protected function getRequiredOptions() + { + return [ + 'urlAuthorize', + 'urlAccessToken', + 'urlResourceOwnerDetails', + ]; + } + + /** + * Verifies that all required options have been passed. + * + * @param array $options + * @return void + * @throws InvalidArgumentException + */ + private function assertRequiredOptions(array $options) + { + $missing = array_diff_key(array_flip($this->getRequiredOptions()), $options); + + if (!empty($missing)) { + throw new InvalidArgumentException( + 'Required options not defined: ' . implode(', ', array_keys($missing)) + ); + } + } + + /** + * @inheritdoc + */ + public function getBaseAuthorizationUrl() + { + return $this->urlAuthorize; + } + + /** + * @inheritdoc + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->urlAccessToken; + } + + /** + * @inheritdoc + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->urlResourceOwnerDetails; + } + + /** + * @inheritdoc + */ + public function getDefaultScopes() + { + return $this->scopes; + } + + /** + * @inheritdoc + */ + protected function getAccessTokenMethod() + { + return $this->accessTokenMethod ?: parent::getAccessTokenMethod(); + } + + /** + * @inheritdoc + */ + protected function getAccessTokenResourceOwnerId() + { + return $this->accessTokenResourceOwnerId ?: parent::getAccessTokenResourceOwnerId(); + } + + /** + * @inheritdoc + */ + protected function getScopeSeparator() + { + return $this->scopeSeparator ?: parent::getScopeSeparator(); + } + + /** + * @inheritdoc + */ + protected function getPkceMethod() + { + return $this->pkceMethod ?: parent::getPkceMethod(); + } + + /** + * @inheritdoc + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if (!empty($data[$this->responseError])) { + $error = $data[$this->responseError]; + if (!is_string($error)) { + $error = var_export($error, true); + } + $code = $this->responseCode && !empty($data[$this->responseCode])? $data[$this->responseCode] : 0; + if (!is_int($code)) { + $code = intval($code); + } + throw new IdentityProviderException($error, $code, $data); + } + } + + /** + * @inheritdoc + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new GenericResourceOwner($response, $this->responseResourceOwnerId); + } +} diff --git a/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php b/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php new file mode 100644 index 0000000..f876614 --- /dev/null +++ b/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php @@ -0,0 +1,61 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +/** + * Represents a generic resource owner for use with the GenericProvider. + */ +class GenericResourceOwner implements ResourceOwnerInterface +{ + /** + * @var array + */ + protected $response; + + /** + * @var string + */ + protected $resourceOwnerId; + + /** + * @param array $response + * @param string $resourceOwnerId + */ + public function __construct(array $response, $resourceOwnerId) + { + $this->response = $response; + $this->resourceOwnerId = $resourceOwnerId; + } + + /** + * Returns the identifier of the authorized resource owner. + * + * @return mixed + */ + public function getId() + { + return $this->response[$this->resourceOwnerId]; + } + + /** + * Returns the raw resource owner response. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php b/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php new file mode 100644 index 0000000..8284424 --- /dev/null +++ b/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php @@ -0,0 +1,36 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +/** + * Classes implementing `ResourceOwnerInterface` may be used to represent + * the resource owner authenticated with a service provider. + */ +interface ResourceOwnerInterface +{ + /** + * Returns the identifier of the authorized resource owner. + * + * @return mixed + */ + public function getId(); + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray(); +} diff --git a/vendor/league/oauth2-client/src/Token/AccessToken.php b/vendor/league/oauth2-client/src/Token/AccessToken.php new file mode 100644 index 0000000..331b0ac --- /dev/null +++ b/vendor/league/oauth2-client/src/Token/AccessToken.php @@ -0,0 +1,251 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +use InvalidArgumentException; +use RuntimeException; + +/** + * Represents an access token. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.4 Access Token (RFC 6749, §1.4) + */ +class AccessToken implements AccessTokenInterface, ResourceOwnerAccessTokenInterface, SettableRefreshTokenInterface +{ + /** + * @var string + */ + protected $accessToken; + + /** + * @var int + */ + protected $expires; + + /** + * @var string + */ + protected $refreshToken; + + /** + * @var string + */ + protected $resourceOwnerId; + + /** + * @var array + */ + protected $values = []; + + /** + * @var int + */ + private static $timeNow; + + /** + * Set the time now. This should only be used for testing purposes. + * + * @param int $timeNow the time in seconds since epoch + * @return void + */ + public static function setTimeNow($timeNow) + { + self::$timeNow = $timeNow; + } + + /** + * Reset the time now if it was set for test purposes. + * + * @return void + */ + public static function resetTimeNow() + { + self::$timeNow = null; + } + + /** + * @return int + */ + public function getTimeNow() + { + return self::$timeNow ? self::$timeNow : time(); + } + + /** + * Constructs an access token. + * + * @param array $options An array of options returned by the service provider + * in the access token request. The `access_token` option is required. + * @throws InvalidArgumentException if `access_token` is not provided in `$options`. + */ + public function __construct(array $options = []) + { + if (empty($options['access_token'])) { + throw new InvalidArgumentException('Required option not passed: "access_token"'); + } + + $this->accessToken = $options['access_token']; + + if (!empty($options['resource_owner_id'])) { + $this->resourceOwnerId = $options['resource_owner_id']; + } + + if (!empty($options['refresh_token'])) { + $this->refreshToken = $options['refresh_token']; + } + + // We need to know when the token expires. Show preference to + // 'expires_in' since it is defined in RFC6749 Section 5.1. + // Defer to 'expires' if it is provided instead. + if (isset($options['expires_in'])) { + if (!is_numeric($options['expires_in'])) { + throw new \InvalidArgumentException('expires_in value must be an integer'); + } + + $this->expires = $options['expires_in'] != 0 ? $this->getTimeNow() + $options['expires_in'] : 0; + } elseif (!empty($options['expires'])) { + // Some providers supply the seconds until expiration rather than + // the exact timestamp. Take a best guess at which we received. + $expires = (int) $options['expires']; + + if (!$this->isExpirationTimestamp($expires)) { + $expires += $this->getTimeNow(); + } + + $this->expires = $expires; + } + + // Capture any additional values that might exist in the token but are + // not part of the standard response. Vendors will sometimes pass + // additional user data this way. + $this->values = array_diff_key($options, array_flip([ + 'access_token', + 'resource_owner_id', + 'refresh_token', + 'expires_in', + 'expires', + ])); + } + + /** + * Check if a value is an expiration timestamp or second value. + * + * @param integer $value + * @return bool + */ + protected function isExpirationTimestamp($value) + { + // If the given value is larger than the original OAuth 2 draft date, + // assume that it is meant to be a (possible expired) timestamp. + $oauth2InceptionDate = 1349067600; // 2012-10-01 + return ($value > $oauth2InceptionDate); + } + + /** + * @inheritdoc + */ + public function getToken() + { + return $this->accessToken; + } + + /** + * @inheritdoc + */ + public function getRefreshToken() + { + return $this->refreshToken; + } + + /** + * @inheritdoc + */ + public function setRefreshToken($refreshToken) + { + $this->refreshToken = $refreshToken; + } + + /** + * @inheritdoc + */ + public function getExpires() + { + return $this->expires; + } + + /** + * @inheritdoc + */ + public function getResourceOwnerId() + { + return $this->resourceOwnerId; + } + + /** + * @inheritdoc + */ + public function hasExpired() + { + $expires = $this->getExpires(); + + if (empty($expires)) { + throw new RuntimeException('"expires" is not set on the token'); + } + + return $expires < $this->getTimeNow(); + } + + /** + * @inheritdoc + */ + public function getValues() + { + return $this->values; + } + + /** + * @inheritdoc + */ + public function __toString() + { + return (string) $this->getToken(); + } + + /** + * @inheritdoc + */ + public function jsonSerialize() + { + $parameters = $this->values; + + if ($this->accessToken) { + $parameters['access_token'] = $this->accessToken; + } + + if ($this->refreshToken) { + $parameters['refresh_token'] = $this->refreshToken; + } + + if ($this->expires) { + $parameters['expires'] = $this->expires; + } + + if ($this->resourceOwnerId) { + $parameters['resource_owner_id'] = $this->resourceOwnerId; + } + + return $parameters; + } +} diff --git a/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php b/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php new file mode 100644 index 0000000..5fd219f --- /dev/null +++ b/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php @@ -0,0 +1,74 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +use JsonSerializable; +use ReturnTypeWillChange; +use RuntimeException; + +interface AccessTokenInterface extends JsonSerializable +{ + /** + * Returns the access token string of this instance. + * + * @return string + */ + public function getToken(); + + /** + * Returns the refresh token, if defined. + * + * @return string|null + */ + public function getRefreshToken(); + + /** + * Returns the expiration timestamp in seconds, if defined. + * + * @return integer|null + */ + public function getExpires(); + + /** + * Checks if this token has expired. + * + * @return boolean true if the token has expired, false otherwise. + * @throws RuntimeException if 'expires' is not set on the token. + */ + public function hasExpired(); + + /** + * Returns additional vendor values stored in the token. + * + * @return array + */ + public function getValues(); + + /** + * Returns a string representation of the access token + * + * @return string + */ + public function __toString(); + + /** + * Returns an array of parameters to serialize when this is serialized with + * json_encode(). + * + * @return array + */ + #[ReturnTypeWillChange] + public function jsonSerialize(); +} diff --git a/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php b/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php new file mode 100644 index 0000000..51e4ce4 --- /dev/null +++ b/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php @@ -0,0 +1,25 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +interface ResourceOwnerAccessTokenInterface extends AccessTokenInterface +{ + /** + * Returns the resource owner identifier, if defined. + * + * @return string|null + */ + public function getResourceOwnerId(); +} diff --git a/vendor/league/oauth2-client/src/Token/SettableRefreshTokenInterface.php b/vendor/league/oauth2-client/src/Token/SettableRefreshTokenInterface.php new file mode 100644 index 0000000..491bee9 --- /dev/null +++ b/vendor/league/oauth2-client/src/Token/SettableRefreshTokenInterface.php @@ -0,0 +1,26 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +interface SettableRefreshTokenInterface +{ + /** + * Sets or replaces the refresh token with the provided refresh token. + * + * @param string $refreshToken + * @return void + */ + public function setRefreshToken($refreshToken); +} diff --git a/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php b/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php new file mode 100644 index 0000000..a18198c --- /dev/null +++ b/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php @@ -0,0 +1,52 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides generic array navigation tools. + */ +trait ArrayAccessorTrait +{ + /** + * Returns a value by key using dot notation. + * + * @param array $data + * @param string $key + * @param mixed|null $default + * @return mixed + */ + private function getValueByKey(array $data, $key, $default = null) + { + if (!is_string($key) || empty($key) || !count($data)) { + return $default; + } + + if (strpos($key, '.') !== false) { + $keys = explode('.', $key); + + foreach ($keys as $innerKey) { + if (!is_array($data) || !array_key_exists($innerKey, $data)) { + return $default; + } + + $data = $data[$innerKey]; + } + + return $data; + } + + return array_key_exists($key, $data) ? $data[$key] : $default; + } +} diff --git a/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php b/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php new file mode 100644 index 0000000..081c7c8 --- /dev/null +++ b/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php @@ -0,0 +1,36 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use League\OAuth2\Client\Token\AccessTokenInterface; + +/** + * Enables `Bearer` header authorization for providers. + * + * @link http://tools.ietf.org/html/rfc6750 Bearer Token Usage (RFC 6750) + */ +trait BearerAuthorizationTrait +{ + /** + * Returns authorization headers for the 'bearer' grant. + * + * @param AccessTokenInterface|string|null $token Either a string or an access token instance + * @return array + */ + protected function getAuthorizationHeaders($token = null) + { + return ['Authorization' => 'Bearer ' . $token]; + } +} diff --git a/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php b/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php new file mode 100644 index 0000000..02c9ba5 --- /dev/null +++ b/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php @@ -0,0 +1,70 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides support for blacklisting explicit properties from the + * mass assignment behavior. + */ +trait GuardedPropertyTrait +{ + /** + * The properties that aren't mass assignable. + * + * @var array + */ + protected $guarded = []; + + /** + * Attempts to mass assign the given options to explicitly defined properties, + * skipping over any properties that are defined in the guarded array. + * + * @param array $options + * @return mixed + */ + protected function fillProperties(array $options = []) + { + if (isset($options['guarded'])) { + unset($options['guarded']); + } + + foreach ($options as $option => $value) { + if (property_exists($this, $option) && !$this->isGuarded($option)) { + $this->{$option} = $value; + } + } + } + + /** + * Returns current guarded properties. + * + * @return array + */ + public function getGuarded() + { + return $this->guarded; + } + + /** + * Determines if the given property is guarded. + * + * @param string $property + * @return bool + */ + public function isGuarded($property) + { + return in_array($property, $this->getGuarded()); + } +} diff --git a/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php b/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php new file mode 100644 index 0000000..f8dcd77 --- /dev/null +++ b/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php @@ -0,0 +1,83 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Token\AccessTokenInterface; + +/** + * Enables `MAC` header authorization for providers. + * + * @link http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05 Message Authentication Code (MAC) Tokens + */ +trait MacAuthorizationTrait +{ + /** + * Returns the id of this token for MAC generation. + * + * @param AccessToken $token + * @return string + */ + abstract protected function getTokenId(AccessToken $token); + + /** + * Returns the MAC signature for the current request. + * + * @param string $id + * @param integer $ts + * @param string $nonce + * @return string + */ + abstract protected function getMacSignature($id, $ts, $nonce); + + /** + * Returns a new random string to use as the state parameter in an + * authorization flow. + * + * @param int $length Length of the random string to be generated. + * @return string + */ + abstract protected function getRandomState($length = 32); + + /** + * Returns the authorization headers for the 'mac' grant. + * + * @param AccessTokenInterface|string|null $token Either a string or an access token instance + * @return array + * @codeCoverageIgnore + * + * @todo This is currently untested and provided only as an example. If you + * complete the implementation, please create a pull request for + * https://github.com/thephpleague/oauth2-client + */ + protected function getAuthorizationHeaders($token = null) + { + if ($token === null) { + return []; + } + + $ts = time(); + $id = $this->getTokenId($token); + $nonce = $this->getRandomState(16); + $mac = $this->getMacSignature($id, $ts, $nonce); + + $parts = []; + foreach (compact('id', 'ts', 'nonce', 'mac') as $key => $value) { + $parts[] = sprintf('%s="%s"', $key, $value); + } + + return ['Authorization' => 'MAC ' . implode(', ', $parts)]; + } +} diff --git a/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php b/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php new file mode 100644 index 0000000..f81b511 --- /dev/null +++ b/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php @@ -0,0 +1,122 @@ +<?php + +namespace League\OAuth2\Client\Tool; + +use GuzzleHttp\Exception\BadResponseException; +use GuzzleHttp\Psr7\Uri; +use InvalidArgumentException; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + +trait ProviderRedirectTrait +{ + /** + * Maximum number of times to follow provider initiated redirects + * + * @var integer + */ + protected $redirectLimit = 2; + + /** + * Retrieves a response for a given request and retrieves subsequent + * responses, with authorization headers, if a redirect is detected. + * + * @param RequestInterface $request + * @return ResponseInterface + * @throws BadResponseException + */ + protected function followRequestRedirects(RequestInterface $request) + { + $response = null; + $attempts = 0; + + while ($attempts < $this->redirectLimit) { + $attempts++; + $response = $this->getHttpClient()->send($request, [ + 'allow_redirects' => false + ]); + + if ($this->isRedirect($response)) { + $redirectUrl = new Uri($response->getHeader('Location')[0]); + $request = $request->withUri($redirectUrl); + } else { + break; + } + } + + return $response; + } + + /** + * Returns the HTTP client instance. + * + * @return GuzzleHttp\ClientInterface + */ + abstract public function getHttpClient(); + + /** + * Retrieves current redirect limit. + * + * @return integer + */ + public function getRedirectLimit() + { + return $this->redirectLimit; + } + + /** + * Determines if a given response is a redirect. + * + * @param ResponseInterface $response + * + * @return boolean + */ + protected function isRedirect(ResponseInterface $response) + { + $statusCode = $response->getStatusCode(); + + return $statusCode > 300 && $statusCode < 400 && $response->hasHeader('Location'); + } + + /** + * Sends a request instance and returns a response instance. + * + * WARNING: This method does not attempt to catch exceptions caused by HTTP + * errors! It is recommended to wrap this method in a try/catch block. + * + * @param RequestInterface $request + * @return ResponseInterface + */ + public function getResponse(RequestInterface $request) + { + try { + $response = $this->followRequestRedirects($request); + } catch (BadResponseException $e) { + $response = $e->getResponse(); + } + + return $response; + } + + /** + * Updates the redirect limit. + * + * @param integer $limit + * @return League\OAuth2\Client\Provider\AbstractProvider + * @throws InvalidArgumentException + */ + public function setRedirectLimit($limit) + { + if (!is_int($limit)) { + throw new InvalidArgumentException('redirectLimit must be an integer.'); + } + + if ($limit < 1) { + throw new InvalidArgumentException('redirectLimit must be greater than or equal to one.'); + } + + $this->redirectLimit = $limit; + + return $this; + } +} diff --git a/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php b/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php new file mode 100644 index 0000000..bdda3e7 --- /dev/null +++ b/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php @@ -0,0 +1,33 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides a standard way to generate query strings. + */ +trait QueryBuilderTrait +{ + /** + * Build a query string from an array. + * + * @param array $params + * + * @return string + */ + protected function buildQueryString(array $params) + { + return http_build_query($params, '', '&', \PHP_QUERY_RFC3986); + } +} diff --git a/vendor/league/oauth2-client/src/Tool/RequestFactory.php b/vendor/league/oauth2-client/src/Tool/RequestFactory.php new file mode 100644 index 0000000..1af4342 --- /dev/null +++ b/vendor/league/oauth2-client/src/Tool/RequestFactory.php @@ -0,0 +1,87 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use GuzzleHttp\Psr7\Request; + +/** + * Used to produce PSR-7 Request instances. + * + * @link https://github.com/guzzle/guzzle/pull/1101 + */ +class RequestFactory +{ + /** + * Creates a PSR-7 Request instance. + * + * @param null|string $method HTTP method for the request. + * @param null|string $uri URI for the request. + * @param array $headers Headers for the message. + * @param string|resource|StreamInterface $body Message body. + * @param string $version HTTP protocol version. + * + * @return Request + */ + public function getRequest( + $method, + $uri, + array $headers = [], + $body = null, + $version = '1.1' + ) { + return new Request($method, $uri, $headers, $body, $version); + } + + /** + * Parses simplified options. + * + * @param array $options Simplified options. + * + * @return array Extended options for use with getRequest. + */ + protected function parseOptions(array $options) + { + // Should match default values for getRequest + $defaults = [ + 'headers' => [], + 'body' => null, + 'version' => '1.1', + ]; + + return array_merge($defaults, $options); + } + + /** + * Creates a request using a simplified array of options. + * + * @param null|string $method + * @param null|string $uri + * @param array $options + * + * @return Request + */ + public function getRequestWithOptions($method, $uri, array $options = []) + { + $options = $this->parseOptions($options); + + return $this->getRequest( + $method, + $uri, + $options['headers'], + $options['body'], + $options['version'] + ); + } +} diff --git a/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php b/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php new file mode 100644 index 0000000..47da977 --- /dev/null +++ b/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php @@ -0,0 +1,56 @@ +<?php +/** + * This file is part of the league/oauth2-client library + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com> + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use BadMethodCallException; + +/** + * Provides functionality to check for required parameters. + */ +trait RequiredParameterTrait +{ + /** + * Checks for a required parameter in a hash. + * + * @throws BadMethodCallException + * @param string $name + * @param array $params + * @return void + */ + private function checkRequiredParameter($name, array $params) + { + if (!isset($params[$name])) { + throw new BadMethodCallException(sprintf( + 'Required parameter not passed: "%s"', + $name + )); + } + } + + /** + * Checks for multiple required parameters in a hash. + * + * @throws InvalidArgumentException + * @param array $names + * @param array $params + * @return void + */ + private function checkRequiredParameters(array $names, array $params) + { + foreach ($names as $name) { + $this->checkRequiredParameter($name, $params); + } + } +} diff --git a/vendor/monolog/monolog/CHANGELOG.md b/vendor/monolog/monolog/CHANGELOG.md new file mode 100644 index 0000000..19ceb86 --- /dev/null +++ b/vendor/monolog/monolog/CHANGELOG.md @@ -0,0 +1,864 @@ +### 3.13.0 (2026-11-16) + + * Security: Fixed `LineFormatter` replacing placeholders found inside logged values, so a message or context value containing e.g. `%context.` could pull other fields into the line or strip everything up to the next `%`, often the whole context (#2099) + * Security: Fixed `RedactingFormatter` not redacting sensitive keys inside objects (public properties or `jsonSerialize()` output), nor secrets written with unicode/slash JSON escaping or with their line breaks replaced by `LineFormatter` (#2100) + * Security: Fixed `SyslogFormatter` writing line breaks in messages as-is, letting a message start what line-based consumers read as a second record, they are now replaced with spaces unless `includeStacktraces()` is enabled (#2098) + * BC Warning: `SyslogUdpHandler` now writes RFC 3164 timestamps in the record's timezone (the `Logger`'s) instead of UTC, as receivers read them as local time, set the `Logger` timezone to UTC to keep the previous output (#2101) + * Added Psalm taint analysis annotations marking the `StreamHandler` path and the `SocketHandler` connection string as sinks (#2086) + * Fixed `SocketHandler` throwing "Write timed-out" on every write after a single failed one until the process restarted, it now reconnects (#2089) + * Fixed `RotatingFileHandler` treating `[`, `*` and `?` in the log path as glob characters, which kept old files from being pruned and could delete matching files in another directory (#2094) + * Fixed `RotatingFileHandler` hourly date formats only rotating at midnight, for `FILE_PER_HOUR`, for variants like `YmdH`, and after switching formats with `setFilenameFormat()` (#2076, #2096) + * Fixed `JsonFormatter` dropping the trailing newline of every following record once formatting a batch had failed, which glued log lines together in long-running processes (#2083) + * Fixed `HtmlFormatter` dropping the message, context keys or values that are not valid UTF-8, e.g. in the emails of mail handlers (#2095) + * Fixed `JsonFormatter` encoding `INF` and `NaN` as `0` (#2078) + * Fixed `FilterHandler` not applying its own processors to records passed in a batch, e.g. when a `BufferHandler` or `FingersCrossedHandler` flushes into it (#2079) + * Fixed `ChromePHPHandler::handleBatch()` ignoring the handler level and sending every record (#2077) + * Fixed `PsrLogMessageProcessor` ignoring the given date format for dates that have `__toString()`, such as Monolog's own and Carbon dates (#2097) + * Fixed `SyslogUdpHandler` zero-padding the day in RFC 3164 timestamps (`Aug 07` instead of `Aug 7`) (#2084) + +### 3.12.1 (2026-09-29) + + * Fixed `Logger` silently dropping every record for the rest of the process once the infinite loop guard aborted a nested logging cycle, which could hit long-running workers (#2072) + * Fixed `RedactingFormatter` letting secrets containing `&`, `<` or `>` through when wrapping an `HtmlFormatter` (#2069) + * Fixed `SocketHandler` throwing the writing timeout immediately when the first write made no progress, instead of waiting for the configured timeout (#2071) + * Fixed `RotatingFileHandler` computing the first rotation in the default timezone instead of the `$timezone` passed to the constructor (#2070) + +### 3.12.0 (2026-09-09) + + * Added support for reading the timestamp of new records from a PSR-20 clock, via a new `$clock` constructor param and `Logger::setClock()` (#2065) + * Added support for `#[WithMonologChannel]` on constructor/method parameters, so a channel can be bound to a single argument instead of the whole class (#2068) + * Fixed `TelegramBotHandler` breaking HTML markup when truncating or splitting long messages, open tags are now closed at the end of a chunk and reopened in the next one (#2066) + * Fixed `RedactingFormatter` not redacting secrets nested inside array values of sensitive keys (#2067) + +### 3.11.0 (2026-09-02) + + * Security: Fixed potential XSS in `BrowserConsoleHandler` when logging user provided content + * Added `RedactingFormatter` to automatically redact sensitive data from records, based on key names, `#[SensitiveParameter]` constructor params and/or regex patterns (#2041) + * Added `FrankenPhpHandler` to log records via FrankenPHP's frankenphp_log() function (#2056) + * Added `LogMonsterHandler` which complains if the code did not log enough records before the process/request ends, like a dead man's switch for logs (#2039) + * Added `FILE_PER_HOUR` rotation mode to `RotatingFileHandler` (#2040) + * Added `ErrorHandler::captureStackTraces()` to attach the stack trace of PHP errors to the records it generates (#2060) + * Added `NormalizerFormatter::setMaxTraceLength()` to limit how many stack trace frames are included when normalizing exceptions (#2015) + * Added extension points to `TelegramBotHandler` to change the API URL (e.g. for a self-hosted Bot API server) and to send extra curl headers (#2029) + * Added ability to override `IntrospectionProcessor`'s `SKIP_FUNCTIONS` in subclasses (#2050) + * Added `$maxLength` param to `SyslogUdpHandler`/`UdpSocket` to keep datagrams below the path MTU, as fragmented UDP packets are often dropped (#2049) + * Fixed `StreamHandler` truncating writes on non-blocking streams, it now loops until the whole record is written (#2016) + * Fixed stack trace frames without file/line being skipped, they are now reported as `internal[function]` entries so traces are not truncated or empty (#2061) + * Fixed `RotatingFileHandler` cleanup not finding files behind stream wrappers (e.g. private://) as glob() cannot see through those (#2058) + * Fixed `RotatingFileHandler` not using the configured timezone when computing the next rotation time (#2022) + * Fixed scalars being replaced by the "Over N levels deep" message instead of being output when the max normalization depth is reached (#2042) + * Fixed `DeduplicationHandler` failing with an undefined array key error when the store file is written to concurrently (#2020) + * Fixed `TelegramBotHandler` swallowing errors when the API returns a non-JSON response (#2030) + * Fixed `AbstractProcessingHandler::handle()` reading `$bubble` directly instead of calling `getBubble()`, so overrides of it were ignored (#2031) + * Fixed warning on PHP 8.5 when `ErrorHandler` sets the HTTP response code and a status line was already registered (#2027) + +### 3.10.0 (2026-01-02) + + * Added automatic directory cleanup in RotatingFileHandler (#2000) + * Added timezone-aware file rotation to RotatingFileHandler (#1982) + * Added support for mongodb/mongodb 2.0+ (#1998) + * Added NoDiscard attribute to TestHandler methods to ensure the result is used (#2013) + * Fixed JsonFormatter crashing if __toString throws while normalizing data (#1968) + * Fixed PHP 8.5 deprecation warnings (#1997, #2009) + * Fixed DeduplicatingHandler collecting duplicate logs if the file cannot be locked (2e97231) + * Fixed GelfMessageFormatter to use integers instead of bool for gelf 1.1 support (#1973) + * Fixed empty stack traces being output anyway (#1979) + * Fixed StreamHandler not reopening the file if the inode changed (#1963) + * Fixed TelegramBotHandler sending empty messages (#1992) + * Fixed file paths in stack traces containing backslashes on windows, always using / now to unify logs (#1980) + * Fixed RotatingFileHandler unlink errors not being suppressed correctly (#1999) + +### 3.9.0 (2025-03-24) + + * BC Warning: Fixed SendGridHandler to use the V3 API as V2 is now shut down, but this requires a new API key (#1952) + * Deprecated Monolog\Test\TestCase in favor of Monolog\Test\MonologTestCase (#1953) + * Added extension point for NativeMailerHandler::mail (#1948) + * Added setHandler method to BufferHandler to modify the nested handler at runtime (#1946) + * Fixed date format in ElasticsearchFormatter to use +00:00 vs +0000 tz identifiers (#1942) + * Fixed GelfMessageFormatter handling numeric context/extra keys (#1932) + +### 3.8.1 (2024-12-05) + + * Deprecated Monolog\DateTimeImmutable in favor of Monolog\JsonSerializableDateTimeImmutable (#1928) + * Fixed gelf keys not being valid when context/extra data keys have spaces in them (#1927) + * Fixed empty lines appearing in the stack traces when a custom formatter returned null (#1925) + +### 3.8.0 (2024-11-12) + + * Added `$fileOpenMode` param to `StreamHandler` to define a custom fopen mode to open the log file (#1913) + * Fixed PHP 8.4 deprecation notices (#1903) + * Added ability to extend/override `IntrospectionProcessor` (#1899) + * Added `$timeout` param to `ProcessHandler` to configure the stream_select() timeout to avoid blocking too long (default is 1.0 sec) (#1916) + * Fixed JsonFormatter batch handling to normalize records individually to make sure they look the same as if they were handled one by one (#1906) + * Fixed `StreamHandler` handling of write failures so that it now closes/reopens the stream and retries the write once before failing (#1882) + * Fixed `StreamHandler` error handler causing issues if a stream handler triggers an error (#1866) + * Fixed `StreamHandler::reset` not closing the stream, so that it would fail to write in some cases with long running processes (#1862) + * Fixed `RotatingFileHandler` issue where rotation does not happen in some long running processes (#1905) + * Fixed `JsonFormatter` handling of incomplete classes (#1834) + * Fixed `RotatingFileHandler` bug where rotation could sometimes not happen correctly (#1905) + +### 3.7.0 (2024-06-28) + + * Added `NormalizerFormatter->setBasePath(...)` (and `JsonFormatter` by extension) that allows removing the project's path from the stack trace output (47e301d3e) + * Fixed JsonFormatter handling of incomplete classes (#1834) + * Fixed private error handlers causing problems with custom StreamHandler implementations (#1866) + +### 3.6.0 (2024-04-12) + + * Added `LineFormatter->setBasePath(...)` that allows removing the project's path from the stack trace output (#1873) + * Added `$includeExtra` option in `PsrHandler` to also use extra data to replace placeholder values in the message (#1852) + * Added ability to customize what is a duplicated message by extending the `DeduplicationHandler` (#1879) + * Added handling for using `GelfMessageFormatter` together with the `AmqpHandler` (#1869) + * Added ability to extend `GoogleCloudLoggingFormatter` (#1859) + * Fixed `__toString` failures in context data crashing the normalization process (#1868) + * Fixed PHP 8.4 deprecation warnings (#1874) + +### 3.5.0 (2023-10-27) + + * Added ability to indent stack traces in LineFormatter via e.g. `indentStacktraces(' ')` (#1835) + * Added ability to configure a max level name length in LineFormatter via e.g. `setMaxLevelNameLength(3)` (#1850) + * Added support for indexed arrays (i.e. `[]` and not `{}` arrays once json serialized) containing inline linebreaks in LineFormatter (#1818) + * Added `WithMonologChannel` attribute for integrators to use to configure autowiring (#1847) + * Fixed log record `extra` data leaking between handlers that have handler-specific processors set (#1819) + * Fixed LogglyHandler issue with record level filtering (#1841) + * Fixed display_errors parsing in ErrorHandler which did not support string values (#1804) + * Fixed bug where the previous error handler would not be restored in some cases where StreamHandler fails (#1815) + * Fixed normalization error when normalizing incomplete classes (#1833) + +### 3.4.0 (2023-06-21) + + * Added `LoadAverageProcessor` to track one of the 1, 5 or 15min load averages (#1803) + * Added support for priority to the `AsMonologProcessor` attribute (#1797) + * Added `TelegramBotHandler` `topic`/`message_thread_id` support (#1802) + * Fixed `FingersCrossedHandler` passthruLevel checking (#1801) + * Fixed support of yearly and monthly rotation log file to rotate only once a month/year (#1805) + * Fixed `TestHandler` method docs (#1794) + * Fixed handling of falsey `display_errors` string values (#1804) + +### 3.3.1 (2023-02-06) + + * Fixed Logger not being serializable anymore (#1792) + +### 3.3.0 (2023-02-06) + + * Deprecated FlowdockHandler & Formatter as the flowdock service was shutdown (#1748) + * Added `ClosureContextProcessor` to allow delaying the creation of context data by setting a Closure in context which is called when the log record is used (#1745) + * Added an ElasticsearchHandler option to set the `op_type` to `create` instead of the default `index` (#1766) + * Added support for enum context values in PsrLogMessageProcessor (#1773) + * Added graylog2/gelf-php 2.x support (#1747) + * Improved `BrowserConsoleHandler` logging to use more appropriate methods than just console.log in the browser (#1739) + * Fixed GitProcessor not filtering correctly based on Level (#1749) + * Fixed `WhatFailureGroupHandler` not catching errors happening inside `close()` (#1791) + * Fixed datetime field in `GoogleCloudLoggingFormatter` (#1758) + * Fixed infinite loop detection within Fibers (#1753) + * Fixed `AmqpHandler->setExtraAttributes` not working with buffering handler wrappers (#1781) + +### 3.2.0 (2022-07-24) + + * Deprecated `CubeHandler` and `PHPConsoleHandler` as both projects are abandoned and those should not be used anymore (#1734) + * Marked `Logger` `@final` as it should not be extended, prefer composition or talk to us if you are missing something + * Added RFC 5424 level (`7` to `0`) support to `Logger::log` and `Logger::addRecord` to increase interoperability (#1723) + * Added `SyslogFormatter` to output syslog-like files which can be consumed by tools like [lnav](https://lnav.org/) (#1689) + * Added support for `__toString` for objects which are not json serializable in `JsonFormatter` (#1733) + * Added `GoogleCloudLoggingFormatter` (#1719) + * Added support for Predis 2.x (#1732) + * Added `AmqpHandler->setExtraAttributes` to allow configuring attributes when using an AMQPExchange (#1724) + * Fixed serialization/unserialization of handlers to make sure private properties are included (#1727) + * Fixed allowInlineLineBreaks in LineFormatter causing issues with windows paths containing `\n` or `\r` sequences (#1720) + * Fixed max normalization depth not being taken into account when formatting exceptions with a deep chain of previous exceptions (#1726) + * Fixed PHP 8.2 deprecation warnings (#1722) + * Fixed rare race condition or filesystem issue where StreamHandler is unable to create the directory the log should go into yet it exists already (#1678) + +### 3.1.0 (2022-06-09) + + * Added `$datetime` parameter to `Logger::addRecord` as low level API to allow logging into the past or future (#1682) + * Added `Logger::useLoggingLoopDetection` to allow disabling cyclic logging detection in concurrent frameworks (#1681) + * Fixed handling of fatal errors if callPrevious is disabled in ErrorHandler (#1670) + * Fixed interop issue by removing the need for a return type in ProcessorInterface (#1680) + * Marked the reusable `Monolog\Test\TestCase` class as `@internal` to make sure PHPStorm does not show it above PHPUnit, you may still use it to test your own handlers/etc though (#1677) + * Fixed RotatingFileHandler issue when the date format contained slashes (#1671) + +### 3.0.0 (2022-05-10) + +Changes from RC1 + +- The `Monolog\LevelName` enum does not exist anymore, use `Monolog\Level->getName()` instead. + +### 3.0.0-RC1 (2022-05-08) + +This is mostly a cleanup release offering stronger type guarantees for integrators with the +array->object/enum changes, but there is no big new feature for end users. + +See [UPGRADE notes](UPGRADE.md#300) for details on all breaking changes especially if you are extending/implementing Monolog classes/interfaces. + +Noteworthy BC Breaks: + +- The minimum supported PHP version is now `8.1.0`. +- Log records have been converted from an array to a [`Monolog\LogRecord` object](src/Monolog/LogRecord.php) + with public (and mostly readonly) properties. e.g. instead of doing + `$record['context']` use `$record->context`. + In formatters or handlers if you rather need an array to work with you can use `$record->toArray()` + to get back a Monolog 1/2 style record array. This will contain the enum values instead of enum cases + in the `level` and `level_name` keys to be more backwards compatible and use simpler data types. +- `FormatterInterface`, `HandlerInterface`, `ProcessorInterface`, etc. changed to contain `LogRecord $record` + instead of `array $record` parameter types. If you want to support multiple Monolog versions this should + be possible by type-hinting nothing, or `array|LogRecord` if you support PHP 8.0+. You can then code + against the $record using Monolog 2 style as LogRecord implements ArrayAccess for BC. + The interfaces do not require a `LogRecord` return type even where it would be applicable, but if you only + support Monolog 3 in integration code I would recommend you use `LogRecord` return types wherever fitting + to ensure forward compatibility as it may be added in Monolog 4. +- Log levels are now enums [`Monolog\Level`](src/Monolog/Level.php) and [`Monolog\LevelName`](src/Monolog/LevelName.php) +- Removed deprecated SwiftMailerHandler, migrate to SymfonyMailerHandler instead. +- `ResettableInterface::reset()` now requires a void return type. +- All properties have had types added, which may require you to do so as well if you extended + a Monolog class and declared the same property. + +New deprecations: + +- `Logger::DEBUG`, `Logger::ERROR`, etc. are now deprecated in favor of the `Monolog\Level` enum. + e.g. instead of `Logger::WARNING` use `Level::Warning` if you need to pass the enum case + to Monolog or one of its handlers, or `Level::Warning->value` if you need the integer + value equal to what `Logger::WARNING` was giving you. +- `Logger::getLevelName()` is now deprecated. + +### 2.10.0 (2024-11-12) + + * Added `$fileOpenMode` to `StreamHandler` to define a custom fopen mode to open the log file (#1913) + * Fixed `StreamHandler` handling of write failures so that it now closes/reopens the stream and retries the write once before failing (#1882) + * Fixed `StreamHandler` error handler causing issues if a stream handler triggers an error (#1866) + * Fixed `JsonFormatter` handling of incomplete classes (#1834) + * Fixed `RotatingFileHandler` bug where rotation could sometimes not happen correctly (#1905) + +### 2.9.3 (2024-04-12) + + * Fixed PHP 8.4 deprecation warnings (#1874) + +### 2.9.2 (2023-10-27) + + * Fixed display_errors parsing in ErrorHandler which did not support string values (#1804) + * Fixed bug where the previous error handler would not be restored in some cases where StreamHandler fails (#1815) + * Fixed normalization error when normalizing incomplete classes (#1833) + +### 2.9.1 (2023-02-06) + + * Fixed Logger not being serializable anymore (#1792) + +### 2.9.0 (2023-02-05) + + * Deprecated FlowdockHandler & Formatter as the flowdock service was shutdown (#1748) + * Added support for enum context values in PsrLogMessageProcessor (#1773) + * Added graylog2/gelf-php 2.x support (#1747) + * Improved `BrowserConsoleHandler` logging to use more appropriate methods than just console.log in the browser (#1739) + * Fixed `WhatFailureGroupHandler` not catching errors happening inside `close()` (#1791) + * Fixed datetime field in `GoogleCloudLoggingFormatter` (#1758) + * Fixed infinite loop detection within Fibers (#1753) + * Fixed `AmqpHandler->setExtraAttributes` not working with buffering handler wrappers (#1781) + +### 2.8.0 (2022-07-24) + + * Deprecated `CubeHandler` and `PHPConsoleHandler` as both projects are abandoned and those should not be used anymore (#1734) + * Added RFC 5424 level (`7` to `0`) support to `Logger::log` and `Logger::addRecord` to increase interoperability (#1723) + * Added support for `__toString` for objects which are not json serializable in `JsonFormatter` (#1733) + * Added `GoogleCloudLoggingFormatter` (#1719) + * Added support for Predis 2.x (#1732) + * Added `AmqpHandler->setExtraAttributes` to allow configuring attributes when using an AMQPExchange (#1724) + * Fixed serialization/unserialization of handlers to make sure private properties are included (#1727) + * Fixed allowInlineLineBreaks in LineFormatter causing issues with windows paths containing `\n` or `\r` sequences (#1720) + * Fixed max normalization depth not being taken into account when formatting exceptions with a deep chain of previous exceptions (#1726) + * Fixed PHP 8.2 deprecation warnings (#1722) + * Fixed rare race condition or filesystem issue where StreamHandler is unable to create the directory the log should go into yet it exists already (#1678) + +### 2.7.0 (2022-06-09) + + * Added `$datetime` parameter to `Logger::addRecord` as low level API to allow logging into the past or future (#1682) + * Added `Logger::useLoggingLoopDetection` to allow disabling cyclic logging detection in concurrent frameworks (#1681) + * Fixed handling of fatal errors if callPrevious is disabled in ErrorHandler (#1670) + * Marked the reusable `Monolog\Test\TestCase` class as `@internal` to make sure PHPStorm does not show it above PHPUnit, you may still use it to test your own handlers/etc though (#1677) + * Fixed RotatingFileHandler issue when the date format contained slashes (#1671) + +### 2.6.0 (2022-05-10) + + * Deprecated `SwiftMailerHandler`, use `SymfonyMailerHandler` instead + * Added `SymfonyMailerHandler` (#1663) + * Added ElasticSearch 8.x support to the ElasticsearchHandler (#1662) + * Added a way to filter/modify stack traces in LineFormatter (#1665) + * Fixed UdpSocket not being able to reopen/reconnect after close() + * Fixed infinite loops if a Handler is triggering logging while handling log records + +### 2.5.0 (2022-04-08) + + * Added `callType` to IntrospectionProcessor (#1612) + * Fixed AsMonologProcessor syntax to be compatible with PHP 7.2 (#1651) + +### 2.4.0 (2022-03-14) + + * Added [`Monolog\LogRecord`](src/Monolog/LogRecord.php) interface that can be used to type-hint records like `array|\Monolog\LogRecord $record` to be forward compatible with the upcoming Monolog 3 changes + * Added `includeStacktraces` constructor params to LineFormatter & JsonFormatter (#1603) + * Added `persistent`, `timeout`, `writingTimeout`, `connectionTimeout`, `chunkSize` constructor params to SocketHandler and derivatives (#1600) + * Added `AsMonologProcessor` PHP attribute which can help autowiring / autoconfiguration of processors if frameworks / integrations decide to make use of it. This is useless when used purely with Monolog (#1637) + * Added support for keeping native BSON types as is in MongoDBFormatter (#1620) + * Added support for a `user_agent` key in WebProcessor, disabled by default but you can use it by configuring the $extraFields you want (#1613) + * Added support for username/userIcon in SlackWebhookHandler (#1617) + * Added extension points to BrowserConsoleHandler (#1593) + * Added record message/context/extra info to exceptions thrown when a StreamHandler cannot open its stream to avoid completely losing the data logged (#1630) + * Fixed error handler signature to accept a null $context which happens with internal PHP errors (#1614) + * Fixed a few setter methods not returning `self` (#1609) + * Fixed handling of records going over the max Telegram message length (#1616) + +### 2.3.5 (2021-10-01) + + * Fixed regression in StreamHandler since 2.3.3 on systems with the memory_limit set to >=20GB (#1592) + +### 2.3.4 (2021-09-15) + + * Fixed support for psr/log 3.x (#1589) + +### 2.3.3 (2021-09-14) + + * Fixed memory usage when using StreamHandler and calling stream_get_contents on the resource you passed to it (#1578, #1577) + * Fixed support for psr/log 2.x (#1587) + * Fixed some type annotations + +### 2.3.2 (2021-07-23) + + * Fixed compatibility with PHP 7.2 - 7.4 when experiencing PCRE errors (#1568) + +### 2.3.1 (2021-07-14) + + * Fixed Utils::getClass handling of anonymous classes not being fully compatible with PHP 8 (#1563) + * Fixed some `@inheritDoc` annotations having the wrong case + +### 2.3.0 (2021-07-05) + + * Added a ton of PHPStan type annotations as well as type aliases on Monolog\Logger for Record, Level and LevelName that you can import (#1557) + * Added ability to customize date format when using JsonFormatter (#1561) + * Fixed FilterHandler not calling reset on its internal handler when reset() is called on it (#1531) + * Fixed SyslogUdpHandler not setting the timezone correctly on DateTimeImmutable instances (#1540) + * Fixed StreamHandler thread safety - chunk size set to 2GB now to avoid interlacing when doing concurrent writes (#1553) + +### 2.2.0 (2020-12-14) + + * Added JSON_PARTIAL_OUTPUT_ON_ERROR to default json encoding flags, to avoid dropping entire context data or even records due to an invalid subset of it somewhere + * Added setDateFormat to NormalizerFormatter (and Line/Json formatters by extension) to allow changing this after object creation + * Added RedisPubSubHandler to log records to a Redis channel using PUBLISH + * Added support for Elastica 7, and deprecated the $type argument of ElasticaFormatter which is not in use anymore as of Elastica 7 + * Added support for millisecond write timeouts in SocketHandler, you can now pass floats to setWritingTimeout, e.g. 0.2 is 200ms + * Added support for unix sockets in SyslogUdpHandler (set $port to 0 to make the $host a unix socket) + * Added handleBatch support for TelegramBotHandler + * Added RFC5424e extended date format including milliseconds to SyslogUdpHandler + * Added support for configuring handlers with numeric level values in strings (coming from e.g. env vars) + * Fixed Wildfire/FirePHP/ChromePHP handling of unicode characters + * Fixed PHP 8 issues in SyslogUdpHandler + * Fixed internal type error when mbstring is missing + +### 2.1.1 (2020-07-23) + + * Fixed removing of json encoding options + * Fixed type hint of $level not accepting strings in SendGridHandler and OverflowHandler + * Fixed SwiftMailerHandler not accepting email templates with an empty subject + * Fixed array access on null in RavenHandler + * Fixed unique_id in WebProcessor not being disableable + +### 2.1.0 (2020-05-22) + + * Added `JSON_INVALID_UTF8_SUBSTITUTE` to default json flags, so that invalid UTF8 characters now get converted to [�](https://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character) instead of being converted from ISO-8859-15 to UTF8 as it was before, which was hardly a comprehensive solution + * Added `$ignoreEmptyContextAndExtra` option to JsonFormatter to skip empty context/extra entirely from the output + * Added `$parseMode`, `$disableWebPagePreview` and `$disableNotification` options to TelegramBotHandler + * Added tentative support for PHP 8 + * NormalizerFormatter::addJsonEncodeOption and removeJsonEncodeOption are now public to allow modifying default json flags + * Fixed GitProcessor type error when there is no git repo present + * Fixed normalization of SoapFault objects containing deeply nested objects as "detail" + * Fixed support for relative paths in RotatingFileHandler + +### 2.0.2 (2019-12-20) + + * Fixed ElasticsearchHandler swallowing exceptions details when failing to index log records + * Fixed normalization of SoapFault objects containing non-strings as "detail" in LineFormatter + * Fixed formatting of resources in JsonFormatter + * Fixed RedisHandler failing to use MULTI properly when passed a proxied Redis instance (e.g. in Symfony with lazy services) + * Fixed FilterHandler triggering a notice when handleBatch was filtering all records passed to it + * Fixed Turkish locale messing up the conversion of level names to their constant values + +### 2.0.1 (2019-11-13) + + * Fixed normalization of Traversables to avoid traversing them as not all of them are rewindable + * Fixed setFormatter/getFormatter to forward to the nested handler in FilterHandler, FingersCrossedHandler, BufferHandler, OverflowHandler and SamplingHandler + * Fixed BrowserConsoleHandler formatting when using multiple styles + * Fixed normalization of exception codes to be always integers even for PDOException which have them as numeric strings + * Fixed normalization of SoapFault objects containing non-strings as "detail" + * Fixed json encoding across all handlers to always attempt recovery of non-UTF-8 strings instead of failing the whole encoding + * Fixed ChromePHPHandler to avoid sending more data than latest Chrome versions allow in headers (4KB down from 256KB). + * Fixed type error in BrowserConsoleHandler when the context array of log records was not associative. + +### 2.0.0 (2019-08-30) + + * BC Break: This is a major release, see [UPGRADE.md](UPGRADE.md) for details if you are coming from a 1.x release + * BC Break: Logger methods log/debug/info/notice/warning/error/critical/alert/emergency now have explicit void return types + * Added FallbackGroupHandler which works like the WhatFailureGroupHandler but stops dispatching log records as soon as one handler accepted it + * Fixed support for UTF-8 when cutting strings to avoid cutting a multibyte-character in half + * Fixed normalizers handling of exception backtraces to avoid serializing arguments in some cases + * Fixed date timezone handling in SyslogUdpHandler + +### 2.0.0-beta2 (2019-07-06) + + * BC Break: This is a major release, see [UPGRADE.md](UPGRADE.md) for details if you are coming from a 1.x release + * BC Break: PHP 7.2 is now the minimum required PHP version. + * BC Break: Removed SlackbotHandler, RavenHandler and HipChatHandler, see [UPGRADE.md](UPGRADE.md) for details + * Added OverflowHandler which will only flush log records to its nested handler when reaching a certain amount of logs (i.e. only pass through when things go really bad) + * Added TelegramBotHandler to log records to a [Telegram](https://core.telegram.org/bots/api) bot account + * Added support for JsonSerializable when normalizing exceptions + * Added support for RFC3164 (outdated BSD syslog protocol) to SyslogUdpHandler + * Added SoapFault details to formatted exceptions + * Fixed DeduplicationHandler silently failing to start when file could not be opened + * Fixed issue in GroupHandler and WhatFailureGroupHandler where setting multiple processors would duplicate records + * Fixed GelfFormatter losing some data when one attachment was too long + * Fixed issue in SignalHandler restarting syscalls functionality + * Improved performance of LogglyHandler when sending multiple logs in a single request + +### 2.0.0-beta1 (2018-12-08) + + * BC Break: This is a major release, see [UPGRADE.md](UPGRADE.md) for details if you are coming from a 1.x release + * BC Break: PHP 7.1 is now the minimum required PHP version. + * BC Break: Quite a few interface changes, only relevant if you implemented your own handlers/processors/formatters + * BC Break: Removed non-PSR-3 methods to add records, all the `add*` (e.g. `addWarning`) methods as well as `emerg`, `crit`, `err` and `warn` + * BC Break: The record timezone is now set per Logger instance and not statically anymore + * BC Break: There is no more default handler configured on empty Logger instances + * BC Break: ElasticSearchHandler renamed to ElasticaHandler + * BC Break: Various handler-specific breaks, see [UPGRADE.md](UPGRADE.md) for details + * Added scalar type hints and return hints in all the places it was possible. Switched strict_types on for more reliability. + * Added DateTimeImmutable support, all record datetime are now immutable, and will toString/json serialize with the correct date format, including microseconds (unless disabled) + * Added timezone and microseconds to the default date format + * Added SendGridHandler to use the SendGrid API to send emails + * Added LogmaticHandler to use the Logmatic.io API to store log records + * Added SqsHandler to send log records to an AWS SQS queue + * Added ElasticsearchHandler to send records via the official ES library. Elastica users should now use ElasticaHandler instead of ElasticSearchHandler + * Added NoopHandler which is similar to the NullHandle but does not prevent the bubbling of log records to handlers further down the configuration, useful for temporarily disabling a handler in configuration files + * Added ProcessHandler to write log output to the STDIN of a given process + * Added HostnameProcessor that adds the machine's hostname to log records + * Added a `$dateFormat` option to the PsrLogMessageProcessor which lets you format DateTime instances nicely + * Added support for the PHP 7.x `mongodb` extension in the MongoDBHandler + * Fixed many minor issues in various handlers, and probably added a few regressions too + +### 1.26.1 (2021-05-28) + + * Fixed PHP 8.1 deprecation warning + +### 1.26.0 (2020-12-14) + + * Added $dateFormat and $removeUsedContextFields arguments to PsrLogMessageProcessor (backport from 2.x) + +### 1.25.5 (2020-07-23) + + * Fixed array access on null in RavenHandler + * Fixed unique_id in WebProcessor not being disableable + +### 1.25.4 (2020-05-22) + + * Fixed GitProcessor type error when there is no git repo present + * Fixed normalization of SoapFault objects containing deeply nested objects as "detail" + * Fixed support for relative paths in RotatingFileHandler + +### 1.25.3 (2019-12-20) + + * Fixed formatting of resources in JsonFormatter + * Fixed RedisHandler failing to use MULTI properly when passed a proxied Redis instance (e.g. in Symfony with lazy services) + * Fixed FilterHandler triggering a notice when handleBatch was filtering all records passed to it + * Fixed Turkish locale messing up the conversion of level names to their constant values + +### 1.25.2 (2019-11-13) + + * Fixed normalization of Traversables to avoid traversing them as not all of them are rewindable + * Fixed setFormatter/getFormatter to forward to the nested handler in FilterHandler, FingersCrossedHandler, BufferHandler and SamplingHandler + * Fixed BrowserConsoleHandler formatting when using multiple styles + * Fixed normalization of exception codes to be always integers even for PDOException which have them as numeric strings + * Fixed normalization of SoapFault objects containing non-strings as "detail" + * Fixed json encoding across all handlers to always attempt recovery of non-UTF-8 strings instead of failing the whole encoding + +### 1.25.1 (2019-09-06) + + * Fixed forward-compatible interfaces to be compatible with Monolog 1.x too. + +### 1.25.0 (2019-09-06) + + * Deprecated SlackbotHandler, use SlackWebhookHandler or SlackHandler instead + * Deprecated RavenHandler, use sentry/sentry 2.x and their Sentry\Monolog\Handler instead + * Deprecated HipChatHandler, migrate to Slack and use SlackWebhookHandler or SlackHandler instead + * Added forward-compatible interfaces and traits FormattableHandlerInterface, FormattableHandlerTrait, ProcessableHandlerInterface, ProcessableHandlerTrait. If you use modern PHP and want to make code compatible with Monolog 1 and 2 this can help. You will have to require at least Monolog 1.25 though. + * Added support for RFC3164 (outdated BSD syslog protocol) to SyslogUdpHandler + * Fixed issue in GroupHandler and WhatFailureGroupHandler where setting multiple processors would duplicate records + * Fixed issue in SignalHandler restarting syscalls functionality + * Fixed normalizers handling of exception backtraces to avoid serializing arguments in some cases + * Fixed ZendMonitorHandler to work with the latest Zend Server versions + * Fixed ChromePHPHandler to avoid sending more data than latest Chrome versions allow in headers (4KB down from 256KB). + +### 1.24.0 (2018-11-05) + + * BC Notice: If you are extending any of the Monolog's Formatters' `normalize` method, make sure you add the new `$depth = 0` argument to your function signature to avoid strict PHP warnings. + * Added a `ResettableInterface` in order to reset/reset/clear/flush handlers and processors + * Added a `ProcessorInterface` as an optional way to label a class as being a processor (mostly useful for autowiring dependency containers) + * Added a way to log signals being received using Monolog\SignalHandler + * Added ability to customize error handling at the Logger level using Logger::setExceptionHandler + * Added InsightOpsHandler to migrate users of the LogEntriesHandler + * Added protection to NormalizerFormatter against circular and very deep structures, it now stops normalizing at a depth of 9 + * Added capture of stack traces to ErrorHandler when logging PHP errors + * Added RavenHandler support for a `contexts` context or extra key to forward that to Sentry's contexts + * Added forwarding of context info to FluentdFormatter + * Added SocketHandler::setChunkSize to override the default chunk size in case you must send large log lines to rsyslog for example + * Added ability to extend/override BrowserConsoleHandler + * Added SlackWebhookHandler::getWebhookUrl and SlackHandler::getToken to enable class extensibility + * Added SwiftMailerHandler::getSubjectFormatter to enable class extensibility + * Dropped official support for HHVM in test builds + * Fixed normalization of exception traces when call_user_func is used to avoid serializing objects and the data they contain + * Fixed naming of fields in Slack handler, all field names are now capitalized in all cases + * Fixed HipChatHandler bug where slack dropped messages randomly + * Fixed normalization of objects in Slack handlers + * Fixed support for PHP7's Throwable in NewRelicHandler + * Fixed race bug when StreamHandler sometimes incorrectly reported it failed to create a directory + * Fixed table row styling issues in HtmlFormatter + * Fixed RavenHandler dropping the message when logging exception + * Fixed WhatFailureGroupHandler skipping processors when using handleBatch + and implement it where possible + * Fixed display of anonymous class names + +### 1.23.0 (2017-06-19) + + * Improved SyslogUdpHandler's support for RFC5424 and added optional `$ident` argument + * Fixed GelfHandler truncation to be per field and not per message + * Fixed compatibility issue with PHP <5.3.6 + * Fixed support for headless Chrome in ChromePHPHandler + * Fixed support for latest Aws SDK in DynamoDbHandler + * Fixed support for SwiftMailer 6.0+ in SwiftMailerHandler + +### 1.22.1 (2017-03-13) + + * Fixed lots of minor issues in the new Slack integrations + * Fixed support for allowInlineLineBreaks in LineFormatter when formatting exception backtraces + +### 1.22.0 (2016-11-26) + + * Added SlackbotHandler and SlackWebhookHandler to set up Slack integration more easily + * Added MercurialProcessor to add mercurial revision and branch names to log records + * Added support for AWS SDK v3 in DynamoDbHandler + * Fixed fatal errors occurring when normalizing generators that have been fully consumed + * Fixed RollbarHandler to include a level (rollbar level), monolog_level (original name), channel and datetime (unix) + * Fixed RollbarHandler not flushing records automatically, calling close() explicitly is not necessary anymore + * Fixed SyslogUdpHandler to avoid sending empty frames + * Fixed a few PHP 7.0 and 7.1 compatibility issues + +### 1.21.0 (2016-07-29) + + * Break: Reverted the addition of $context when the ErrorHandler handles regular php errors from 1.20.0 as it was causing issues + * Added support for more formats in RotatingFileHandler::setFilenameFormat as long as they have Y, m and d in order + * Added ability to format the main line of text the SlackHandler sends by explicitly setting a formatter on the handler + * Added information about SoapFault instances in NormalizerFormatter + * Added $handleOnlyReportedErrors option on ErrorHandler::registerErrorHandler (default true) to allow logging of all errors no matter the error_reporting level + +### 1.20.0 (2016-07-02) + + * Added FingersCrossedHandler::activate() to manually trigger the handler regardless of the activation policy + * Added StreamHandler::getUrl to retrieve the stream's URL + * Added ability to override addRow/addTitle in HtmlFormatter + * Added the $context to context information when the ErrorHandler handles a regular php error + * Deprecated RotatingFileHandler::setFilenameFormat to only support 3 formats: Y, Y-m and Y-m-d + * Fixed WhatFailureGroupHandler to work with PHP7 throwables + * Fixed a few minor bugs + +### 1.19.0 (2016-04-12) + + * Break: StreamHandler will not close streams automatically that it does not own. If you pass in a stream (not a path/url), then it will not close it for you. You can retrieve those using getStream() if needed + * Added DeduplicationHandler to remove duplicate records from notifications across multiple requests, useful for email or other notifications on errors + * Added ability to use `%message%` and other LineFormatter replacements in the subject line of emails sent with NativeMailHandler and SwiftMailerHandler + * Fixed HipChatHandler handling of long messages + +### 1.18.2 (2016-04-02) + + * Fixed ElasticaFormatter to use more precise dates + * Fixed GelfMessageFormatter sending too long messages + +### 1.18.1 (2016-03-13) + + * Fixed SlackHandler bug where slack dropped messages randomly + * Fixed RedisHandler issue when using with the PHPRedis extension + * Fixed AmqpHandler content-type being incorrectly set when using with the AMQP extension + * Fixed BrowserConsoleHandler regression + +### 1.18.0 (2016-03-01) + + * Added optional reduction of timestamp precision via `Logger->useMicrosecondTimestamps(false)`, disabling it gets you a bit of performance boost but reduces the precision to the second instead of microsecond + * Added possibility to skip some extra stack frames in IntrospectionProcessor if you have some library wrapping Monolog that is always adding frames + * Added `Logger->withName` to clone a logger (keeping all handlers) with a new name + * Added FluentdFormatter for the Fluentd unix socket protocol + * Added HandlerWrapper base class to ease the creation of handler wrappers, just extend it and override as needed + * Added support for replacing context sub-keys using `%context.*%` in LineFormatter + * Added support for `payload` context value in RollbarHandler + * Added setRelease to RavenHandler to describe the application version, sent with every log + * Added support for `fingerprint` context value in RavenHandler + * Fixed JSON encoding errors that would gobble up the whole log record, we now handle those more gracefully by dropping chars as needed + * Fixed write timeouts in SocketHandler and derivatives, set to 10sec by default, lower it with `setWritingTimeout()` + * Fixed PHP7 compatibility with regard to Exception/Throwable handling in a few places + +### 1.17.2 (2015-10-14) + + * Fixed ErrorHandler compatibility with non-Monolog PSR-3 loggers + * Fixed SlackHandler handling to use slack functionalities better + * Fixed SwiftMailerHandler bug when sending multiple emails they all had the same id + * Fixed 5.3 compatibility regression + +### 1.17.1 (2015-08-31) + + * Fixed RollbarHandler triggering PHP notices + +### 1.17.0 (2015-08-30) + + * Added support for `checksum` and `release` context/extra values in RavenHandler + * Added better support for exceptions in RollbarHandler + * Added UidProcessor::getUid + * Added support for showing the resource type in NormalizedFormatter + * Fixed IntrospectionProcessor triggering PHP notices + +### 1.16.0 (2015-08-09) + + * Added IFTTTHandler to notify ifttt.com triggers + * Added Logger::setHandlers() to allow setting/replacing all handlers + * Added $capSize in RedisHandler to cap the log size + * Fixed StreamHandler creation of directory to only trigger when the first log write happens + * Fixed bug in the handling of curl failures + * Fixed duplicate logging of fatal errors when both error and fatal error handlers are registered in monolog's ErrorHandler + * Fixed missing fatal errors records with handlers that need to be closed to flush log records + * Fixed TagProcessor::addTags support for associative arrays + +### 1.15.0 (2015-07-12) + + * Added addTags and setTags methods to change a TagProcessor + * Added automatic creation of directories if they are missing for a StreamHandler to open a log file + * Added retry functionality to Loggly, Cube and Mandrill handlers so they retry up to 5 times in case of network failure + * Fixed process exit code being incorrectly reset to 0 if ErrorHandler::registerExceptionHandler was used + * Fixed HTML/JS escaping in BrowserConsoleHandler + * Fixed JSON encoding errors being silently suppressed (PHP 5.5+ only) + +### 1.14.0 (2015-06-19) + + * Added PHPConsoleHandler to send record to Chrome's PHP Console extension and library + * Added support for objects implementing __toString in the NormalizerFormatter + * Added support for HipChat's v2 API in HipChatHandler + * Added Logger::setTimezone() to initialize the timezone monolog should use in case date.timezone isn't correct for your app + * Added an option to send formatted message instead of the raw record on PushoverHandler via ->useFormattedMessage(true) + * Fixed curl errors being silently suppressed + +### 1.13.1 (2015-03-09) + + * Fixed regression in HipChat requiring a new token to be created + +### 1.13.0 (2015-03-05) + + * Added Registry::hasLogger to check for the presence of a logger instance + * Added context.user support to RavenHandler + * Added HipChat API v2 support in the HipChatHandler + * Added NativeMailerHandler::addParameter to pass params to the mail() process + * Added context data to SlackHandler when $includeContextAndExtra is true + * Added ability to customize the Swift_Message per-email in SwiftMailerHandler + * Fixed SwiftMailerHandler to lazily create message instances if a callback is provided + * Fixed serialization of INF and NaN values in Normalizer and LineFormatter + +### 1.12.0 (2014-12-29) + + * Break: HandlerInterface::isHandling now receives a partial record containing only a level key. This was always the intent and does not break any Monolog handler but is strictly speaking a BC break and you should check if you relied on any other field in your own handlers. + * Added PsrHandler to forward records to another PSR-3 logger + * Added SamplingHandler to wrap around a handler and include only every Nth record + * Added MongoDBFormatter to support better storage with MongoDBHandler (it must be enabled manually for now) + * Added exception codes in the output of most formatters + * Added LineFormatter::includeStacktraces to enable exception stack traces in logs (uses more than one line) + * Added $useShortAttachment to SlackHandler to minify attachment size and $includeExtra to append extra data + * Added $host to HipChatHandler for users of private instances + * Added $transactionName to NewRelicHandler and support for a transaction_name context value + * Fixed MandrillHandler to avoid outputting API call responses + * Fixed some non-standard behaviors in SyslogUdpHandler + +### 1.11.0 (2014-09-30) + + * Break: The NewRelicHandler extra and context data are now prefixed with extra_ and context_ to avoid clashes. Watch out if you have scripts reading those from the API and rely on names + * Added WhatFailureGroupHandler to suppress any exception coming from the wrapped handlers and avoid chain failures if a logging service fails + * Added MandrillHandler to send emails via the Mandrillapp.com API + * Added SlackHandler to log records to a Slack.com account + * Added FleepHookHandler to log records to a Fleep.io account + * Added LogglyHandler::addTag to allow adding tags to an existing handler + * Added $ignoreEmptyContextAndExtra to LineFormatter to avoid empty [] at the end + * Added $useLocking to StreamHandler and RotatingFileHandler to enable flock() while writing + * Added support for PhpAmqpLib in the AmqpHandler + * Added FingersCrossedHandler::clear and BufferHandler::clear to reset them between batches in long running jobs + * Added support for adding extra fields from $_SERVER in the WebProcessor + * Fixed support for non-string values in PrsLogMessageProcessor + * Fixed SwiftMailer messages being sent with the wrong date in long running scripts + * Fixed minor PHP 5.6 compatibility issues + * Fixed BufferHandler::close being called twice + +### 1.10.0 (2014-06-04) + + * Added Logger::getHandlers() and Logger::getProcessors() methods + * Added $passthruLevel argument to FingersCrossedHandler to let it always pass some records through even if the trigger level is not reached + * Added support for extra data in NewRelicHandler + * Added $expandNewlines flag to the ErrorLogHandler to create multiple log entries when a message has multiple lines + +### 1.9.1 (2014-04-24) + + * Fixed regression in RotatingFileHandler file permissions + * Fixed initialization of the BufferHandler to make sure it gets flushed after receiving records + * Fixed ChromePHPHandler and FirePHPHandler's activation strategies to be more conservative + +### 1.9.0 (2014-04-20) + + * Added LogEntriesHandler to send logs to a LogEntries account + * Added $filePermissions to tweak file mode on StreamHandler and RotatingFileHandler + * Added $useFormatting flag to MemoryProcessor to make it send raw data in bytes + * Added support for table formatting in FirePHPHandler via the table context key + * Added a TagProcessor to add tags to records, and support for tags in RavenHandler + * Added $appendNewline flag to the JsonFormatter to enable using it when logging to files + * Added sound support to the PushoverHandler + * Fixed multi-threading support in StreamHandler + * Fixed empty headers issue when ChromePHPHandler received no records + * Fixed default format of the ErrorLogHandler + +### 1.8.0 (2014-03-23) + + * Break: the LineFormatter now strips newlines by default because this was a bug, set $allowInlineLineBreaks to true if you need them + * Added BrowserConsoleHandler to send logs to any browser's console via console.log() injection in the output + * Added FilterHandler to filter records and only allow those of a given list of levels through to the wrapped handler + * Added FlowdockHandler to send logs to a Flowdock account + * Added RollbarHandler to send logs to a Rollbar account + * Added HtmlFormatter to send prettier log emails with colors for each log level + * Added GitProcessor to add the current branch/commit to extra record data + * Added a Monolog\Registry class to allow easier global access to pre-configured loggers + * Added support for the new official graylog2/gelf-php lib for GelfHandler, upgrade if you can by replacing the mlehner/gelf-php requirement + * Added support for HHVM + * Added support for Loggly batch uploads + * Added support for tweaking the content type and encoding in NativeMailerHandler + * Added $skipClassesPartials to tweak the ignored classes in the IntrospectionProcessor + * Fixed batch request support in GelfHandler + +### 1.7.0 (2013-11-14) + + * Added ElasticSearchHandler to send logs to an Elastic Search server + * Added DynamoDbHandler and ScalarFormatter to send logs to Amazon's Dynamo DB + * Added SyslogUdpHandler to send logs to a remote syslogd server + * Added LogglyHandler to send logs to a Loggly account + * Added $level to IntrospectionProcessor so it only adds backtraces when needed + * Added $version to LogstashFormatter to allow using the new v1 Logstash format + * Added $appName to NewRelicHandler + * Added configuration of Pushover notification retries/expiry + * Added $maxColumnWidth to NativeMailerHandler to change the 70 chars default + * Added chainability to most setters for all handlers + * Fixed RavenHandler batch processing so it takes the message from the record with highest priority + * Fixed HipChatHandler batch processing so it sends all messages at once + * Fixed issues with eAccelerator + * Fixed and improved many small things + +### 1.6.0 (2013-07-29) + + * Added HipChatHandler to send logs to a HipChat chat room + * Added ErrorLogHandler to send logs to PHP's error_log function + * Added NewRelicHandler to send logs to NewRelic's service + * Added Monolog\ErrorHandler helper class to register a Logger as exception/error/fatal handler + * Added ChannelLevelActivationStrategy for the FingersCrossedHandler to customize levels by channel + * Added stack traces output when normalizing exceptions (json output & co) + * Added Monolog\Logger::API constant (currently 1) + * Added support for ChromePHP's v4.0 extension + * Added support for message priorities in PushoverHandler, see $highPriorityLevel and $emergencyLevel + * Added support for sending messages to multiple users at once with the PushoverHandler + * Fixed RavenHandler's support for batch sending of messages (when behind a Buffer or FingersCrossedHandler) + * Fixed normalization of Traversables with very large data sets, only the first 1000 items are shown now + * Fixed issue in RotatingFileHandler when an open_basedir restriction is active + * Fixed minor issues in RavenHandler and bumped the API to Raven 0.5.0 + * Fixed SyslogHandler issue when many were used concurrently with different facilities + +### 1.5.0 (2013-04-23) + + * Added ProcessIdProcessor to inject the PID in log records + * Added UidProcessor to inject a unique identifier to all log records of one request/run + * Added support for previous exceptions in the LineFormatter exception serialization + * Added Monolog\Logger::getLevels() to get all available levels + * Fixed ChromePHPHandler so it avoids sending headers larger than Chrome can handle + +### 1.4.1 (2013-04-01) + + * Fixed exception formatting in the LineFormatter to be more minimalistic + * Fixed RavenHandler's handling of context/extra data, requires Raven client >0.1.0 + * Fixed log rotation in RotatingFileHandler to work with long running scripts spanning multiple days + * Fixed WebProcessor array access so it checks for data presence + * Fixed Buffer, Group and FingersCrossed handlers to make use of their processors + +### 1.4.0 (2013-02-13) + + * Added RedisHandler to log to Redis via the Predis library or the phpredis extension + * Added ZendMonitorHandler to log to the Zend Server monitor + * Added the possibility to pass arrays of handlers and processors directly in the Logger constructor + * Added `$useSSL` option to the PushoverHandler which is enabled by default + * Fixed ChromePHPHandler and FirePHPHandler issue when multiple instances are used simultaneously + * Fixed header injection capability in the NativeMailHandler + +### 1.3.1 (2013-01-11) + + * Fixed LogstashFormatter to be usable with stream handlers + * Fixed GelfMessageFormatter levels on Windows + +### 1.3.0 (2013-01-08) + + * Added PSR-3 compliance, the `Monolog\Logger` class is now an instance of `Psr\Log\LoggerInterface` + * Added PsrLogMessageProcessor that you can selectively enable for full PSR-3 compliance + * Added LogstashFormatter (combine with SocketHandler or StreamHandler to send logs to Logstash) + * Added PushoverHandler to send mobile notifications + * Added CouchDBHandler and DoctrineCouchDBHandler + * Added RavenHandler to send data to Sentry servers + * Added support for the new MongoClient class in MongoDBHandler + * Added microsecond precision to log records' timestamps + * Added `$flushOnOverflow` param to BufferHandler to flush by batches instead of losing + the oldest entries + * Fixed normalization of objects with cyclic references + +### 1.2.1 (2012-08-29) + + * Added new $logopts arg to SyslogHandler to provide custom openlog options + * Fixed fatal error in SyslogHandler + +### 1.2.0 (2012-08-18) + + * Added AmqpHandler (for use with AMQP servers) + * Added CubeHandler + * Added NativeMailerHandler::addHeader() to send custom headers in mails + * Added the possibility to specify more than one recipient in NativeMailerHandler + * Added the possibility to specify float timeouts in SocketHandler + * Added NOTICE and EMERGENCY levels to conform with RFC 5424 + * Fixed the log records to use the php default timezone instead of UTC + * Fixed BufferHandler not being flushed properly on PHP fatal errors + * Fixed normalization of exotic resource types + * Fixed the default format of the SyslogHandler to avoid duplicating datetimes in syslog + +### 1.1.0 (2012-04-23) + + * Added Monolog\Logger::isHandling() to check if a handler will + handle the given log level + * Added ChromePHPHandler + * Added MongoDBHandler + * Added GelfHandler (for use with Graylog2 servers) + * Added SocketHandler (for use with syslog-ng for example) + * Added NormalizerFormatter + * Added the possibility to change the activation strategy of the FingersCrossedHandler + * Added possibility to show microseconds in logs + * Added `server` and `referer` to WebProcessor output + +### 1.0.2 (2011-10-24) + + * Fixed bug in IE with large response headers and FirePHPHandler + +### 1.0.1 (2011-08-25) + + * Added MemoryPeakUsageProcessor and MemoryUsageProcessor + * Added Monolog\Logger::getName() to get a logger's channel name + +### 1.0.0 (2011-07-06) + + * Added IntrospectionProcessor to get info from where the logger was called + * Fixed WebProcessor in CLI + +### 1.0.0-RC1 (2011-07-01) + + * Initial release diff --git a/vendor/monolog/monolog/LICENSE b/vendor/monolog/monolog/LICENSE new file mode 100644 index 0000000..aa2a042 --- /dev/null +++ b/vendor/monolog/monolog/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2020 Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/monolog/monolog/README.md b/vendor/monolog/monolog/README.md new file mode 100644 index 0000000..52cf8c7 --- /dev/null +++ b/vendor/monolog/monolog/README.md @@ -0,0 +1,136 @@ +<p align="center"><img src="logo.png" alt="Monolog" width="400"></p> + +# Monolog - Logging for PHP [![Continuous Integration](https://github.com/Seldaek/monolog/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/Seldaek/monolog/actions) + +[![Total Downloads](https://img.shields.io/packagist/dt/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog) +[![Latest Stable Version](https://img.shields.io/packagist/v/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog) + +>**Note** This is the **documentation for Monolog 3.x**, if you are using older releases +>see the documentation for [Monolog 2.x](https://github.com/Seldaek/monolog/blob/2.x/README.md) or [Monolog 1.x](https://github.com/Seldaek/monolog/blob/1.x/README.md) + +Monolog sends your logs to files, sockets, inboxes, databases and various +web services. See the complete list of handlers below. Special handlers +allow you to build advanced logging strategies. + +This library implements the [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +interface that you can type-hint against in your own libraries to keep +a maximum of interoperability. You can also use it in your applications to +make sure you can always use another compatible logger at a later time. +As of 1.11.0 Monolog public APIs will also accept PSR-3 log levels. +Internally Monolog still uses its own level scheme since it predates PSR-3. + +<div align="center"> + <hr> + <sup><b>Sponsored by:</b></sup> + <br> + <a href="https://betterstack.com"> + <div> + <img src="https://github.com/Seldaek/monolog/assets/183678/7de58ce0-2fa2-45c0-b3e8-e60cebb3c4cf" width="200" alt="Better Stack"> + </div> + <div> + Better Stack lets you centralize, search, and visualize your logs. + </div> + </a> + <br> + <hr> +</div> + +## Installation + +Install the latest version with + +```bash +composer require monolog/monolog +``` + +## Basic Usage + +```php +<?php + +use Monolog\Level; +use Monolog\Logger; +use Monolog\Handler\StreamHandler; + +// create a log channel +$log = new Logger('name'); +$log->pushHandler(new StreamHandler('path/to/your.log', Level::Warning)); + +// add records to the log +$log->warning('Foo'); +$log->error('Bar'); +``` + +## Documentation + +- [Usage Instructions](doc/01-usage.md) +- [Handlers, Formatters and Processors](doc/02-handlers-formatters-processors.md) +- [Utility Classes](doc/03-utilities.md) +- [Extending Monolog](doc/04-extending.md) +- [Log Record Structure](doc/message-structure.md) + +## Support Monolog Financially + +Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=enterprise) or via [GitHub sponsorship](https://github.com/sponsors/Seldaek). + +Tidelift delivers commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. + +## Third Party Packages + +Third party handlers, formatters and processors are +[listed in the wiki](https://github.com/Seldaek/monolog/wiki/Third-Party-Packages). You +can also add your own there if you publish one. + +## About + +### Requirements + +- Monolog `^3.0` works with PHP 8.1 or above. +- Monolog `^2.5` works with PHP 7.2 or above. +- Monolog `^1.25` works with PHP 5.3 up to 8.1, but is not very maintained anymore and will not receive PHP support fixes anymore. + +### Support + +Monolog 1.x support is somewhat limited at this point and only important fixes will be done. You should migrate to Monolog 2 or 3 where possible to benefit from all the latest features and fixes. + +### Submitting bugs and feature requests + +Bugs and feature request are tracked on [GitHub](https://github.com/Seldaek/monolog/issues) + +### Framework Integrations + +- Frameworks and libraries using [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) + can be used very easily with Monolog since it implements the interface. +- [Symfony](http://symfony.com) comes out of the box with Monolog. +- [Laravel](http://laravel.com/) comes out of the box with Monolog. +- [Lumen](http://lumen.laravel.com/) comes out of the box with Monolog. +- [PPI](https://github.com/ppi/framework) comes out of the box with Monolog. +- [CakePHP](http://cakephp.org/) is usable with Monolog via the [cakephp-monolog](https://github.com/jadb/cakephp-monolog) plugin. +- [XOOPS 2.6](http://xoops.org/) comes out of the box with Monolog. +- [Aura.Web_Project](https://github.com/auraphp/Aura.Web_Project) comes out of the box with Monolog. +- [Nette Framework](http://nette.org/en/) is usable with Monolog via the [contributte/monolog](https://github.com/contributte/monolog) or [orisai/nette-monolog](https://github.com/orisai/nette-monolog) extensions. +- [Proton Micro Framework](https://github.com/alexbilbie/Proton) comes out of the box with Monolog. +- [FuelPHP](http://fuelphp.com/) comes out of the box with Monolog. +- [Equip Framework](https://github.com/equip/framework) comes out of the box with Monolog. +- [Yii 2](http://www.yiiframework.com/) is usable with Monolog via the [yii2-monolog](https://github.com/merorafael/yii2-monolog) or [yii2-psr-log-target](https://github.com/samdark/yii2-psr-log-target) plugins. +- [Hawkbit Micro Framework](https://github.com/HawkBitPhp/hawkbit) comes out of the box with Monolog. +- [SilverStripe 4](https://www.silverstripe.org/) comes out of the box with Monolog. +- [Drupal](https://www.drupal.org/) is usable with Monolog via the [monolog](https://www.drupal.org/project/monolog) module. +- [Aimeos ecommerce framework](https://aimeos.org/) is usable with Monolog via the [ai-monolog](https://github.com/aimeos/ai-monolog) extension. +- [Magento](https://magento.com/) comes out of the box with Monolog. +- [Spiral Framework](https://spiral.dev) comes out of the box with Monolog bridge. +- [WebFramework](https://web-framework.com/) comes out of the box with Monolog. + +### Author + +Jordi Boggiano - <j.boggiano@seld.be> - <http://twitter.com/seldaek><br /> +See also the list of [contributors](https://github.com/Seldaek/monolog/contributors) who participated in this project. + +### License + +Monolog is licensed under the MIT License - see the [LICENSE](LICENSE) file for details + +### Acknowledgements + +This library is heavily inspired by Python's [Logbook](https://logbook.readthedocs.io/en/stable/) +library, although most concepts have been adjusted to fit to the PHP world. diff --git a/vendor/monolog/monolog/composer.json b/vendor/monolog/monolog/composer.json new file mode 100644 index 0000000..a547ea0 --- /dev/null +++ b/vendor/monolog/monolog/composer.json @@ -0,0 +1,84 @@ +{ + "name": "monolog/monolog", + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "keywords": ["log", "logging", "psr-3"], + "homepage": "https://github.com/Seldaek/monolog", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "https://seld.be" + } + ], + "require": { + "php": ">=8.1", + "psr/log": "^2.0 || ^3.0" + }, + "require-dev": { + "ext-json": "*", + "aws/aws-sdk-php": "^3.0", + "doctrine/couchdb": "~1.0@dev", + "elasticsearch/elasticsearch": "^7 || ^8", + "graylog2/gelf-php": "^1.4.2 || ^2.0", + "guzzlehttp/guzzle": "^7.4.5", + "guzzlehttp/psr7": "^2.2", + "mongodb/mongodb": "^1.8 || ^2.0", + "php-amqplib/php-amqplib": "~2.4 || ^3", + "php-console/php-console": "^3.1.8", + "phpstan/phpstan": "^2", + "phpstan/phpstan-deprecation-rules": "^2", + "phpstan/phpstan-strict-rules": "^2", + "phpunit/phpunit": "^10.5.17 || ^11.0.7", + "predis/predis": "^1.1 || ^2", + "psr/clock": "^1.0", + "rollbar/rollbar": "^4.0", + "ruflin/elastica": "^7 || ^8", + "symfony/mailer": "^5.4 || ^6", + "symfony/mime": "^5.4 || ^6" + }, + "suggest": { + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server", + "elasticsearch/elasticsearch": "Allow sending log messages to an Elasticsearch server via official client", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)", + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ext-mbstring": "Allow to work properly with unicode symbols", + "ext-sockets": "Allow sending log messages to a Syslog server (via UDP driver)", + "ext-curl": "Required to send log messages using the IFTTTHandler, the LogglyHandler, the SendGridHandler, the SlackWebhookHandler or the TelegramBotHandler", + "ext-openssl": "Required to send log messages using SSL", + "psr/clock": "Required to pass a clock to the Logger and control the timestamp of log records" + }, + "autoload": { + "psr-4": {"Monolog\\": "src/Monolog"} + }, + "autoload-dev": { + "psr-4": {"Monolog\\": "tests/Monolog"} + }, + "provide": { + "psr/log-implementation": "3.0.0" + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "scripts": { + "test": "@php vendor/bin/phpunit", + "phpstan": "@php vendor/bin/phpstan analyse" + }, + "config": { + "lock": false, + "sort-packages": true, + "platform-check": false, + "allow-plugins": { + "php-http/discovery": false + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php b/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php new file mode 100644 index 0000000..c519e05 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php @@ -0,0 +1,38 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Attribute; + +/** + * A reusable attribute to help configure a class or a method as a processor. + * + * Using it offers no guarantee: it needs to be leveraged by a Monolog third-party consumer. + * + * Using it with the Monolog library only has no effect at all: processors should still be turned into a callable if + * needed and manually pushed to the loggers and to the processable handlers. + */ +#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +class AsMonologProcessor +{ + /** + * @param string|null $channel The logging channel the processor should be pushed to. + * @param string|null $handler The handler the processor should be pushed to. + * @param string|null $method The method that processes the records (if the attribute is used at the class level). + * @param int|null $priority The priority of the processor so the order can be determined. + */ + public function __construct( + public readonly ?string $channel = null, + public readonly ?string $handler = null, + public readonly ?string $method = null, + public readonly ?int $priority = null + ) { + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Attribute/WithMonologChannel.php b/vendor/monolog/monolog/src/Monolog/Attribute/WithMonologChannel.php new file mode 100644 index 0000000..0feb213 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Attribute/WithMonologChannel.php @@ -0,0 +1,30 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Attribute; + +/** + * A reusable attribute to help configure a class, or one of its constructor/method arguments, + * as expecting a given logger channel. + * + * Using it offers no guarantee: it needs to be leveraged by a Monolog third-party consumer. + * + * Using it with the Monolog library only has no effect at all: wiring the logger instance into + * other classes is not managed by Monolog. + */ +#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_PARAMETER)] +final class WithMonologChannel +{ + public function __construct( + public readonly string $channel + ) { + } +} diff --git a/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php b/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php new file mode 100644 index 0000000..3cb7086 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php @@ -0,0 +1,24 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +class_alias(JsonSerializableDateTimeImmutable::class, 'Monolog\DateTimeImmutable'); + +// @phpstan-ignore-next-line +if (false) { + /** + * @deprecated Use \Monolog\JsonSerializableDateTimeImmutable instead. + */ + class DateTimeImmutable extends JsonSerializableDateTimeImmutable + { + } +} diff --git a/vendor/monolog/monolog/src/Monolog/ErrorHandler.php b/vendor/monolog/monolog/src/Monolog/ErrorHandler.php new file mode 100644 index 0000000..c10f7be --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/ErrorHandler.php @@ -0,0 +1,337 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Closure; +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; + +/** + * Monolog error handler + * + * A facility to enable logging of runtime errors, exceptions and fatal errors. + * + * Quick setup: <code>ErrorHandler::register($logger);</code> + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class ErrorHandler +{ + private Closure|null $previousExceptionHandler = null; + + /** @var array<class-string, LogLevel::*> an array of class name to LogLevel::* constant mapping */ + private array $uncaughtExceptionLevelMap = []; + + /** @var Closure|true|null */ + private Closure|bool|null $previousErrorHandler = null; + + /** @var array<int, LogLevel::*> an array of E_* constant to LogLevel::* constant mapping */ + private array $errorLevelMap = []; + + private bool $handleOnlyReportedErrors = true; + + private bool $hasFatalErrorHandler = false; + + /** @var int bitmask of E_* constants to capture stack traces for, 0 to disable */ + private int $captureStackTraceTypes = 0; + + private string $fatalLevel = LogLevel::ALERT; + + private string|null $reservedMemory = null; + + /** @var ?array{type: int, message: string, file: string, line: int, trace: mixed} */ + private array|null $lastFatalData = null; + + private const FATAL_ERRORS = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; + + public function __construct( + private LoggerInterface $logger + ) { + } + + /** + * Registers a new ErrorHandler for a given Logger + * + * By default it will handle errors, exceptions and fatal errors + * + * @param array<int, LogLevel::*>|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling + * @param array<class-string, LogLevel::*>|false $exceptionLevelMap an array of class name to LogLevel::* constant mapping, or false to disable exception handling + * @param LogLevel::*|null|false $fatalLevel a LogLevel::* constant, null to use the default LogLevel::ALERT or false to disable fatal error handling + * @return static + */ + public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null): self + { + /** @phpstan-ignore-next-line */ + $handler = new static($logger); + if ($errorLevelMap !== false) { + $handler->registerErrorHandler($errorLevelMap); + } + if ($exceptionLevelMap !== false) { + $handler->registerExceptionHandler($exceptionLevelMap); + } + if ($fatalLevel !== false) { + $handler->registerFatalHandler($fatalLevel); + } + + return $handler; + } + + /** + * @param array<class-string, LogLevel::*> $levelMap an array of class name to LogLevel::* constant mapping + * @return $this + */ + public function registerExceptionHandler(array $levelMap = [], bool $callPrevious = true): self + { + $prev = set_exception_handler(function (\Throwable $e): void { + $this->handleException($e); + }); + $this->uncaughtExceptionLevelMap = $levelMap; + foreach ($this->defaultExceptionLevelMap() as $class => $level) { + if (!isset($this->uncaughtExceptionLevelMap[$class])) { + $this->uncaughtExceptionLevelMap[$class] = $level; + } + } + if ($callPrevious && null !== $prev) { + $this->previousExceptionHandler = $prev(...); + } + + return $this; + } + + /** + * @param array<int, LogLevel::*> $levelMap an array of E_* constant to LogLevel::* constant mapping + * @return $this + */ + public function registerErrorHandler(array $levelMap = [], bool $callPrevious = true, int $errorTypes = -1, bool $handleOnlyReportedErrors = true): self + { + $prev = set_error_handler($this->handleError(...), $errorTypes); + $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap); + if ($callPrevious) { + $this->previousErrorHandler = $prev !== null ? $prev(...) : true; + } else { + $this->previousErrorHandler = null; + } + + $this->handleOnlyReportedErrors = $handleOnlyReportedErrors; + + return $this; + } + + /** + * @param LogLevel::*|null $level a LogLevel::* constant, null to use the default LogLevel::ALERT + * @param int $reservedMemorySize Amount of KBs to reserve in memory so that it can be freed when handling fatal errors giving Monolog some room in memory to get its job done + * @return $this + */ + public function registerFatalHandler($level = null, int $reservedMemorySize = 20): self + { + register_shutdown_function($this->handleFatalError(...)); + + $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize); + $this->fatalLevel = null === $level ? LogLevel::ALERT : $level; + $this->hasFatalErrorHandler = true; + + return $this; + } + + /** + * Attaches an ErrorException carrying the stack trace of the error to the log record's context + * + * PHP does not report where a warning/notice/deprecation came from, so without this the records + * only point at the line which raised the error, and not at its caller. Formatters rendering + * stack traces (e.g. LineFormatter::includeStacktraces) then show the full call site. + * + * This is off by default because context.exception makes errors look like exceptions to the + * handlers which treat that key specially, e.g. NewRelicHandler reports them via + * newrelic_notice_error and RollbarHandler as exception occurrences, and because formatters + * extending NormalizerFormatter then include the whole trace in every record. Narrowing + * $errorTypes is wise if you log a lot of errors: E_DEPRECATED in particular can be very + * frequent in legacy code while rarely being worth a stack trace. + * + * @param int $errorTypes bitmask of E_* constants to capture stack traces for + * @return $this + */ + public function captureStackTraces(bool $capture = true, int $errorTypes = E_ALL): self + { + $this->captureStackTraceTypes = $capture ? $errorTypes : 0; + + return $this; + } + + /** + * @return array<class-string, LogLevel::*> + */ + protected function defaultExceptionLevelMap(): array + { + return [ + 'ParseError' => LogLevel::CRITICAL, + 'Throwable' => LogLevel::ERROR, + ]; + } + + /** + * @return array<int, LogLevel::*> + */ + protected function defaultErrorLevelMap(): array + { + return [ + E_ERROR => LogLevel::CRITICAL, + E_WARNING => LogLevel::WARNING, + E_PARSE => LogLevel::ALERT, + E_NOTICE => LogLevel::NOTICE, + E_CORE_ERROR => LogLevel::CRITICAL, + E_CORE_WARNING => LogLevel::WARNING, + E_COMPILE_ERROR => LogLevel::ALERT, + E_COMPILE_WARNING => LogLevel::WARNING, + E_USER_ERROR => LogLevel::ERROR, + E_USER_WARNING => LogLevel::WARNING, + E_USER_NOTICE => LogLevel::NOTICE, + 2048 => LogLevel::NOTICE, // E_STRICT + E_RECOVERABLE_ERROR => LogLevel::ERROR, + E_DEPRECATED => LogLevel::NOTICE, + E_USER_DEPRECATED => LogLevel::NOTICE, + ]; + } + + private function handleException(\Throwable $e): never + { + $level = LogLevel::ERROR; + foreach ($this->uncaughtExceptionLevelMap as $class => $candidate) { + if ($e instanceof $class) { + $level = $candidate; + break; + } + } + + $this->logger->log( + $level, + sprintf('Uncaught Exception %s: "%s" at %s line %s', Utils::getClass($e), $e->getMessage(), $e->getFile(), $e->getLine()), + ['exception' => $e] + ); + + if (null !== $this->previousExceptionHandler) { + ($this->previousExceptionHandler)($e); + } + + if (!headers_sent() && \in_array(strtolower((string) \ini_get('display_errors')), ['0', '', 'false', 'off', 'none', 'no'], true)) { + // PHP 8.5+ warns if header('HTTP/...') already staged a status line, which is undetectable from userland + @http_response_code(500); + } + + exit(255); + } + + private function handleError(int $code, string $message, string $file = '', int $line = 0): bool + { + if ($this->handleOnlyReportedErrors && 0 === (error_reporting() & $code)) { + return false; + } + + $isFatal = $this->hasFatalErrorHandler && \in_array($code, self::FATAL_ERRORS, true); + + $trace = null; + if ($isFatal || 0 !== ($this->captureStackTraceTypes & $code)) { + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + array_shift($trace); // Exclude handleError from trace + } + + // fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries + if (!$isFatal) { + $level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL; + $context = ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]; + if (null !== $trace) { + $context['exception'] = self::createErrorException($code, $message, $file, $line, $trace); + } + $this->logger->log($level, self::codeToString($code).': '.$message, $context); + } else { + $this->lastFatalData = ['type' => $code, 'message' => $message, 'file' => $file, 'line' => $line, 'trace' => $trace]; + } + + if ($this->previousErrorHandler === true) { + return false; + } + if ($this->previousErrorHandler instanceof Closure) { + return (bool) ($this->previousErrorHandler)($code, $message, $file, $line); + } + + return true; + } + + /** + * @private + */ + public function handleFatalError(): void + { + $this->reservedMemory = ''; + + if (\is_array($this->lastFatalData)) { + $lastError = $this->lastFatalData; + } else { + $lastError = error_get_last(); + } + if (\is_array($lastError) && \in_array($lastError['type'], self::FATAL_ERRORS, true)) { + // PHP 8.5+ reports a trace for fatal errors which never reach the error handler (OOM, timeouts) + $trace = $lastError['trace'] ?? null; + $context = ['code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'], 'trace' => $trace]; + if (\is_array($trace)) { + /** @var list<array<string, mixed>> $trace */ + $context['exception'] = self::createErrorException($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line'], $trace); + } + $this->logger->log( + $this->fatalLevel, + 'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'], + $context + ); + + if ($this->logger instanceof Logger) { + foreach ($this->logger->getHandlers() as $handler) { + $handler->close(); + } + } + } + } + + /** + * @param list<array<string, mixed>> $trace + */ + private static function createErrorException(int $code, string $message, string $file, int $line, array $trace): \ErrorException + { + $e = new \ErrorException($message, 0, $code, $file, $line); + + // Exception::getTrace() is final, so overwriting the private property is the only way to + // report the real call site instead of ErrorHandler's own frame + (new \ReflectionProperty(\Exception::class, 'trace'))->setValue($e, $trace); + + return $e; + } + + private static function codeToString(int $code): string + { + return match ($code) { + E_ERROR => 'E_ERROR', + E_WARNING => 'E_WARNING', + E_PARSE => 'E_PARSE', + E_NOTICE => 'E_NOTICE', + E_CORE_ERROR => 'E_CORE_ERROR', + E_CORE_WARNING => 'E_CORE_WARNING', + E_COMPILE_ERROR => 'E_COMPILE_ERROR', + E_COMPILE_WARNING => 'E_COMPILE_WARNING', + E_USER_ERROR => 'E_USER_ERROR', + E_USER_WARNING => 'E_USER_WARNING', + E_USER_NOTICE => 'E_USER_NOTICE', + 2048 => 'E_STRICT', + E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', + E_DEPRECATED => 'E_DEPRECATED', + E_USER_DEPRECATED => 'E_USER_DEPRECATED', + default => 'Unknown PHP error', + }; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php new file mode 100644 index 0000000..beb5106 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php @@ -0,0 +1,87 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Formats a log message according to the ChromePHP array format + * + * @author Christophe Coevoet <stof@notk.org> + */ +class ChromePHPFormatter implements FormatterInterface +{ + /** + * Translates Monolog log levels to Wildfire levels. + * + * @return 'log'|'info'|'warn'|'error' + */ + private function toWildfireLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'log', + Level::Info => 'info', + Level::Notice => 'info', + Level::Warning => 'warn', + Level::Error => 'error', + Level::Critical => 'error', + Level::Alert => 'error', + Level::Emergency => 'error', + }; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record) + { + // Retrieve the line and file if set and remove them from the formatted extra + $backtrace = 'unknown'; + if (isset($record->extra['file'], $record->extra['line'])) { + $backtrace = $record->extra['file'].' : '.$record->extra['line']; + unset($record->extra['file'], $record->extra['line']); + } + + $message = ['message' => $record->message]; + if (\count($record->context) > 0) { + $message['context'] = $record->context; + } + if (\count($record->extra) > 0) { + $message['extra'] = $record->extra; + } + if (\count($message) === 1) { + $message = reset($message); + } + + return [ + $record->channel, + $message, + $backtrace, + $this->toWildfireLevel($record->level), + ]; + } + + /** + * @inheritDoc + */ + public function formatBatch(array $records) + { + $formatted = []; + + foreach ($records as $record) { + $formatted[] = $this->format($record); + } + + return $formatted; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php new file mode 100644 index 0000000..a0fa4a9 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php @@ -0,0 +1,84 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Elastica\Document; +use Monolog\LogRecord; + +/** + * Format a log message into an Elastica Document + * + * @author Jelle Vink <jelle.vink@gmail.com> + */ +class ElasticaFormatter extends NormalizerFormatter +{ + /** + * @var string Elastic search index name + */ + protected string $index; + + /** + * @var string|null Elastic search document type + */ + protected string|null $type; + + /** + * @param string $index Elastic Search index name + * @param ?string $type Elastic Search document type, deprecated as of Elastica 7 + */ + public function __construct(string $index, ?string $type) + { + // elasticsearch requires a ISO 8601 format date with optional millisecond precision. + parent::__construct('Y-m-d\TH:i:s.uP'); + + $this->index = $index; + $this->type = $type; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record) + { + $record = parent::format($record); + + return $this->getDocument($record); + } + + public function getIndex(): string + { + return $this->index; + } + + /** + * @deprecated since Elastica 7 type has no effect + */ + public function getType(): string + { + /** @phpstan-ignore-next-line */ + return $this->type; + } + + /** + * Convert a log message into an Elastica Document + * + * @param mixed[] $record + */ + protected function getDocument(array $record): Document + { + $document = new Document(); + $document->setData($record); + $document->setIndex($this->index); + + return $document; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php new file mode 100644 index 0000000..6326cf5 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php @@ -0,0 +1,86 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use DateTimeInterface; +use Monolog\LogRecord; + +/** + * Format a log message into an Elasticsearch record + * + * @author Avtandil Kikabidze <akalongman@gmail.com> + */ +class ElasticsearchFormatter extends NormalizerFormatter +{ + /** + * @var string Elasticsearch index name + */ + protected string $index; + + /** + * @var string Elasticsearch record type + */ + protected string $type; + + /** + * @param string $index Elasticsearch index name + * @param string $type Elasticsearch record type + */ + public function __construct(string $index, string $type) + { + // Elasticsearch requires an ISO 8601 format date with optional millisecond precision. + parent::__construct(DateTimeInterface::ATOM); + + $this->index = $index; + $this->type = $type; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record) + { + $record = parent::format($record); + + return $this->getDocument($record); + } + + /** + * Getter index + */ + public function getIndex(): string + { + return $this->index; + } + + /** + * Getter type + */ + public function getType(): string + { + return $this->type; + } + + /** + * Convert a log message into an Elasticsearch record + * + * @param mixed[] $record Log message + * @return mixed[] + */ + protected function getDocument(array $record): array + { + $record['_index'] = $this->index; + $record['_type'] = $this->type; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php new file mode 100644 index 0000000..cc805c8 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php @@ -0,0 +1,106 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\LogRecord; + +/** + * formats the record to be used in the FlowdockHandler + * + * @author Dominik Liebler <liebler.dominik@gmail.com> + * @deprecated Since 2.9.0 and 3.3.0, Flowdock was shutdown we will thus drop this handler in Monolog 4 + */ +class FlowdockFormatter implements FormatterInterface +{ + private string $source; + + private string $sourceEmail; + + public function __construct(string $source, string $sourceEmail) + { + $this->source = $source; + $this->sourceEmail = $sourceEmail; + } + + /** + * @inheritDoc + * + * @return mixed[] + */ + public function format(LogRecord $record): array + { + $tags = [ + '#logs', + '#' . $record->level->toPsrLogLevel(), + '#' . $record->channel, + ]; + + foreach ($record->extra as $value) { + $tags[] = '#' . $value; + } + + $subject = sprintf( + 'in %s: %s - %s', + $this->source, + $record->level->getName(), + $this->getShortMessage($record->message) + ); + + return [ + 'source' => $this->source, + 'from_address' => $this->sourceEmail, + 'subject' => $subject, + 'content' => $record->message, + 'tags' => $tags, + 'project' => $this->source, + ]; + } + + /** + * @inheritDoc + * + * @return mixed[][] + */ + public function formatBatch(array $records): array + { + $formatted = []; + + foreach ($records as $record) { + $formatted[] = $this->format($record); + } + + return $formatted; + } + + public function getShortMessage(string $message): string + { + static $hasMbString; + + if (null === $hasMbString) { + $hasMbString = \function_exists('mb_strlen'); + } + + $maxLength = 45; + + if ($hasMbString) { + if (mb_strlen($message, 'UTF-8') > $maxLength) { + $message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...'; + } + } else { + if (\strlen($message) > $maxLength) { + $message = substr($message, 0, $maxLength - 4) . ' ...'; + } + } + + return $message; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php new file mode 100644 index 0000000..5f78117 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php @@ -0,0 +1,85 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Class FluentdFormatter + * + * Serializes a log message to Fluentd unix socket protocol + * + * Fluentd config: + * + * <source> + * type unix + * path /var/run/td-agent/td-agent.sock + * </source> + * + * Monolog setup: + * + * $logger = new Monolog\Logger('fluent.tag'); + * $fluentHandler = new Monolog\Handler\SocketHandler('unix:///var/run/td-agent/td-agent.sock'); + * $fluentHandler->setFormatter(new Monolog\Formatter\FluentdFormatter()); + * $logger->pushHandler($fluentHandler); + * + * @author Andrius Putna <fordnox@gmail.com> + */ +class FluentdFormatter implements FormatterInterface +{ + /** + * @var bool $levelTag should message level be a part of the fluentd tag + */ + protected bool $levelTag = false; + + public function __construct(bool $levelTag = false) + { + $this->levelTag = $levelTag; + } + + public function isUsingLevelsInTag(): bool + { + return $this->levelTag; + } + + public function format(LogRecord $record): string + { + $tag = $record->channel; + if ($this->levelTag) { + $tag .= '.' . $record->level->toPsrLogLevel(); + } + + $message = [ + 'message' => $record->message, + 'context' => $record->context, + 'extra' => $record->extra, + ]; + + if (!$this->levelTag) { + $message['level'] = $record->level->value; + $message['level_name'] = $record->level->getName(); + } + + return Utils::jsonEncode([$tag, $record->datetime->getTimestamp(), $message]); + } + + public function formatBatch(array $records): string + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php b/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php new file mode 100644 index 0000000..3413a4b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php @@ -0,0 +1,38 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\LogRecord; + +/** + * Interface for formatters + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +interface FormatterInterface +{ + /** + * Formats a log record. + * + * @param LogRecord $record A record to format + * @return mixed The formatted record + */ + public function format(LogRecord $record); + + /** + * Formats a set of log records. + * + * @param array<LogRecord> $records A set of records to format + * @return mixed The formatted set of records + */ + public function formatBatch(array $records); +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php new file mode 100644 index 0000000..4774bde --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php @@ -0,0 +1,152 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Level; +use Gelf\Message; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Serializes a log message to GELF + * @see http://docs.graylog.org/en/latest/pages/gelf.html + * + * @author Matt Lehner <mlehner@gmail.com> + */ +class GelfMessageFormatter extends NormalizerFormatter +{ + protected const DEFAULT_MAX_LENGTH = 32766; + + /** + * @var string the name of the system for the Gelf log message + */ + protected string $systemName; + + /** + * @var string a prefix for 'extra' fields from the Monolog record (optional) + */ + protected string $extraPrefix; + + /** + * @var string a prefix for 'context' fields from the Monolog record (optional) + */ + protected string $contextPrefix; + + /** + * @var int max length per field + */ + protected int $maxLength; + + /** + * Translates Monolog log levels to Graylog2 log priorities. + */ + private function getGraylog2Priority(Level $level): int + { + return match ($level) { + Level::Debug => 7, + Level::Info => 6, + Level::Notice => 5, + Level::Warning => 4, + Level::Error => 3, + Level::Critical => 2, + Level::Alert => 1, + Level::Emergency => 0, + }; + } + + /** + * @throws \RuntimeException + */ + public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null) + { + if (!class_exists(Message::class)) { + throw new \RuntimeException('Composer package graylog2/gelf-php is required to use Monolog\'s GelfMessageFormatter'); + } + + parent::__construct('U.u'); + + $this->systemName = (null === $systemName || $systemName === '') ? (string) gethostname() : $systemName; + + $this->extraPrefix = null === $extraPrefix ? '' : $extraPrefix; + $this->contextPrefix = $contextPrefix; + $this->maxLength = null === $maxLength ? self::DEFAULT_MAX_LENGTH : $maxLength; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record): Message + { + $context = $extra = []; + if ($record->context !== []) { + /** @var array<array<mixed>|bool|float|int|string|null> $context */ + $context = parent::normalize($record->context); + } + if ($record->extra !== []) { + /** @var array<array<mixed>|bool|float|int|string|null> $extra */ + $extra = parent::normalize($record->extra); + } + + $message = new Message(); + $message + ->setTimestamp($record->datetime) + ->setShortMessage($record->message) + ->setHost($this->systemName) + ->setLevel($this->getGraylog2Priority($record->level)); + + // message length + system name length + 200 for padding / metadata + $len = 200 + \strlen($record->message) + \strlen($this->systemName); + + if ($len > $this->maxLength) { + $message->setShortMessage(Utils::substr($record->message, 0, $this->maxLength)); + } + + if ($record->channel !== '') { + $message->setAdditional('facility', $record->channel); + } + + foreach ($extra as $key => $val) { + $key = (string) preg_replace('#[^\w.-]#', '-', (string) $key); + $val = \is_bool($val) ? ($val ? 1 : 0) : $val; + $val = \is_scalar($val) || null === $val ? $val : $this->toJson($val); + $len = \strlen($this->extraPrefix . $key . $val); + if ($len > $this->maxLength) { + $message->setAdditional($this->extraPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength)); + + continue; + } + $message->setAdditional($this->extraPrefix . $key, $val); + } + + foreach ($context as $key => $val) { + $key = (string) preg_replace('#[^\w.-]#', '-', (string) $key); + $val = \is_bool($val) ? ($val ? 1 : 0) : $val; + $val = \is_scalar($val) || null === $val ? $val : $this->toJson($val); + $len = \strlen($this->contextPrefix . $key . $val); + if ($len > $this->maxLength) { + $message->setAdditional($this->contextPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength)); + + continue; + } + $message->setAdditional($this->contextPrefix . $key, $val); + } + + if (!$message->hasAdditional('file') && isset($context['exception']['file'])) { + if (1 === preg_match("/^(.+):([0-9]+)$/", $context['exception']['file'], $matches)) { + $message->setAdditional('file', $matches[1]); + $message->setAdditional('line', $matches[2]); + } + } + + return $message; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php new file mode 100644 index 0000000..c97b912 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php @@ -0,0 +1,40 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use DateTimeInterface; +use Monolog\LogRecord; + +/** + * Encodes message information into JSON in a format compatible with Cloud logging. + * + * @see https://cloud.google.com/logging/docs/structured-logging + * @see https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry + * + * @author Luís Cobucci <lcobucci@gmail.com> + */ +class GoogleCloudLoggingFormatter extends JsonFormatter +{ + protected function normalizeRecord(LogRecord $record): array + { + $normalized = parent::normalizeRecord($record); + + // Re-key level for GCP logging + $normalized['severity'] = $normalized['level_name']; + $normalized['time'] = $record->datetime->format(DateTimeInterface::RFC3339_EXTENDED); + + // Remove keys that are not used by GCP + unset($normalized['level'], $normalized['level_name'], $normalized['datetime']); + + return $normalized; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php new file mode 100644 index 0000000..e106515 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php @@ -0,0 +1,142 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Level; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Formats incoming records into an HTML table + * + * This is especially useful for html email logging + * + * @author Tiago Brito <tlfbrito@gmail.com> + */ +class HtmlFormatter extends NormalizerFormatter +{ + /** + * Translates Monolog log levels to html color priorities. + */ + protected function getLevelColor(Level $level): string + { + return match ($level) { + Level::Debug => '#CCCCCC', + Level::Info => '#28A745', + Level::Notice => '#17A2B8', + Level::Warning => '#FFC107', + Level::Error => '#FD7E14', + Level::Critical => '#DC3545', + Level::Alert => '#821722', + Level::Emergency => '#000000', + }; + } + + /** + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct(?string $dateFormat = null) + { + parent::__construct($dateFormat); + } + + /** + * Creates an HTML table row + * + * @param string $th Row header content + * @param string $td Row standard cell content + * @param bool $escapeTd false if td content must not be html escaped + */ + protected function addRow(string $th, string $td = ' ', bool $escapeTd = true): string + { + $th = htmlspecialchars($th, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8'); + if ($escapeTd) { + $td = '<pre>'.htmlspecialchars($td, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8').'</pre>'; + } + + return "<tr style=\"padding: 4px;text-align: left;\">\n<th style=\"vertical-align: top;background: #ccc;color: #000\" width=\"100\">$th:</th>\n<td style=\"padding: 4px;text-align: left;vertical-align: top;background: #eee;color: #000\">".$td."</td>\n</tr>"; + } + + /** + * Create a HTML h1 tag + * + * @param string $title Text to be in the h1 + */ + protected function addTitle(string $title, Level $level): string + { + $title = htmlspecialchars($title, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8'); + + return '<h1 style="background: '.$this->getLevelColor($level).';color: #ffffff;padding: 5px;" class="monolog-output">'.$title.'</h1>'; + } + + /** + * Formats a log record. + * + * @return string The formatted record + */ + public function format(LogRecord $record): string + { + $output = $this->addTitle($record->level->getName(), $record->level); + $output .= '<table cellspacing="1" width="100%" class="monolog-output">'; + + $output .= $this->addRow('Message', $record->message); + $output .= $this->addRow('Time', $this->formatDate($record->datetime)); + $output .= $this->addRow('Channel', $record->channel); + if (\count($record->context) > 0) { + $embeddedTable = '<table cellspacing="1" width="100%">'; + foreach ($record->context as $key => $value) { + $embeddedTable .= $this->addRow((string) $key, $this->convertToString($value)); + } + $embeddedTable .= '</table>'; + $output .= $this->addRow('Context', $embeddedTable, false); + } + if (\count($record->extra) > 0) { + $embeddedTable = '<table cellspacing="1" width="100%">'; + foreach ($record->extra as $key => $value) { + $embeddedTable .= $this->addRow((string) $key, $this->convertToString($value)); + } + $embeddedTable .= '</table>'; + $output .= $this->addRow('Extra', $embeddedTable, false); + } + + return $output.'</table>'; + } + + /** + * Formats a set of log records. + * + * @return string The formatted set of records + */ + public function formatBatch(array $records): string + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } + + /** + * @param mixed $data + */ + protected function convertToString($data): string + { + if (null === $data || \is_scalar($data)) { + return (string) $data; + } + + $data = $this->normalize($data); + + return Utils::jsonEncode($data, JSON_PRETTY_PRINT | Utils::DEFAULT_JSON_FLAGS, true); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php new file mode 100644 index 0000000..20db266 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php @@ -0,0 +1,242 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Stringable; +use Throwable; +use Monolog\LogRecord; + +/** + * Encodes whatever record data is passed to it as json + * + * This can be useful to log to databases or remote APIs + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class JsonFormatter extends NormalizerFormatter +{ + public const BATCH_MODE_JSON = 1; + public const BATCH_MODE_NEWLINES = 2; + + /** @var self::BATCH_MODE_* */ + protected int $batchMode; + + protected bool $appendNewline; + + protected bool $ignoreEmptyContextAndExtra; + + protected bool $includeStacktraces = false; + + /** + * @param self::BATCH_MODE_* $batchMode + */ + public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = true, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false) + { + $this->batchMode = $batchMode; + $this->appendNewline = $appendNewline; + $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra; + $this->includeStacktraces = $includeStacktraces; + + parent::__construct(); + } + + /** + * The batch mode option configures the formatting style for + * multiple records. By default, multiple records will be + * formatted as a JSON-encoded array. However, for + * compatibility with some API endpoints, alternative styles + * are available. + */ + public function getBatchMode(): int + { + return $this->batchMode; + } + + /** + * True if newlines are appended to every formatted record + */ + public function isAppendingNewlines(): bool + { + return $this->appendNewline; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record): string + { + $normalized = $this->normalizeRecord($record); + + return $this->toJson($normalized, true) . ($this->appendNewline ? "\n" : ''); + } + + /** + * @inheritDoc + */ + public function formatBatch(array $records): string + { + return match ($this->batchMode) { + static::BATCH_MODE_NEWLINES => $this->formatBatchNewlines($records), + default => $this->formatBatchJson($records), + }; + } + + /** + * @return $this + */ + public function includeStacktraces(bool $include = true): self + { + $this->includeStacktraces = $include; + + return $this; + } + + /** + * @return array<array<mixed>|bool|float|int|\stdClass|string|null> + */ + protected function normalizeRecord(LogRecord $record): array + { + $normalized = parent::normalizeRecord($record); + + if (isset($normalized['context']) && $normalized['context'] === []) { + if ($this->ignoreEmptyContextAndExtra) { + unset($normalized['context']); + } else { + $normalized['context'] = new \stdClass; + } + } + if (isset($normalized['extra']) && $normalized['extra'] === []) { + if ($this->ignoreEmptyContextAndExtra) { + unset($normalized['extra']); + } else { + $normalized['extra'] = new \stdClass; + } + } + + return $normalized; + } + + /** + * Return a JSON-encoded array of records. + * + * @phpstan-param LogRecord[] $records + */ + protected function formatBatchJson(array $records): string + { + $formatted = array_map(fn (LogRecord $record) => $this->normalizeRecord($record), $records); + + return $this->toJson($formatted, true); + } + + /** + * Use new lines to separate records instead of a + * JSON-encoded array. + * + * @phpstan-param LogRecord[] $records + */ + protected function formatBatchNewlines(array $records): string + { + $oldNewline = $this->appendNewline; + $this->appendNewline = false; + try { + $formatted = array_map(fn (LogRecord $record) => $this->format($record), $records); + } finally { + $this->appendNewline = $oldNewline; + } + + return implode("\n", $formatted); + } + + /** + * Normalizes given $data. + * + * @return null|scalar|array<mixed[]|scalar|null|object>|object + */ + protected function normalize(mixed $data, int $depth = 0): mixed + { + if (is_null($data) || is_scalar($data)) { + if (\is_float($data) && !is_finite($data)) { + // INF and NAN can't be represented in JSON; json_encode() would turn them into 0 + return parent::normalize($data, $depth); + } + + return $data; + } + + if ($depth > $this->maxNormalizeDepth) { + return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization'; + } + + if (\is_array($data)) { + $normalized = []; + + $count = 1; + foreach ($data as $key => $value) { + if ($count++ > $this->maxNormalizeItemCount) { + $normalized['...'] = 'Over '.$this->maxNormalizeItemCount.' items ('.\count($data).' total), aborting normalization'; + break; + } + + $normalized[$key] = $this->normalize($value, $depth + 1); + } + + return $normalized; + } + + if (\is_object($data)) { + if ($data instanceof \DateTimeInterface) { + return $this->formatDate($data); + } + + if ($data instanceof Throwable) { + return $this->normalizeException($data, $depth); + } + + // if the object has specific json serializability we want to make sure we skip the __toString treatment below + if ($data instanceof \JsonSerializable) { + return $data; + } + + if ($data instanceof Stringable) { + try { + return $data->__toString(); + } catch (Throwable) { + return $data::class; + } + } + + if (\get_class($data) === '__PHP_Incomplete_Class') { + return new \ArrayObject($data); + } + + return $data; + } + + return parent::normalize($data); + } + + /** + * Normalizes given exception with or without its own stack trace based on + * `includeStacktraces` property. + * + * @return array<array-key, string|int|array<string|int|array<string>>> + */ + protected function normalizeException(Throwable $e, int $depth = 0): array + { + $data = parent::normalizeException($e, $depth); + if (!$this->includeStacktraces) { + unset($data['trace']); + } + + return $data; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php new file mode 100644 index 0000000..bfba877 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php @@ -0,0 +1,345 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Closure; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Formats incoming records into a one-line string + * + * This is especially useful for logging to files + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * @author Christophe Coevoet <stof@notk.org> + */ +class LineFormatter extends NormalizerFormatter +{ + public const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"; + + protected string $format; + protected bool $allowInlineLineBreaks; + protected bool $ignoreEmptyContextAndExtra; + protected bool $includeStacktraces; + protected ?int $maxLevelNameLength = null; + protected string $indentStacktraces = ''; + protected Closure|null $stacktracesParser = null; + protected string $basePath = ''; + + private ?string $parsedFormat = null; + /** @var list<string|array{string, string|null}> literal text, or [name, null] for %name% and [context|extra, key] for %context.key% */ + private array $formatParts = []; + /** @var list<array{string, string}> */ + private array $formatKeys = []; + + /** + * @param string|null $format The format of the message + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries + */ + public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false) + { + $this->format = $format === null ? static::SIMPLE_FORMAT : $format; + $this->allowInlineLineBreaks = $allowInlineLineBreaks; + $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra; + $this->includeStacktraces($includeStacktraces); + parent::__construct($dateFormat); + } + + /** + * Setting a base path will hide the base path from exception and stack trace file names to shorten them + * @return $this + */ + public function setBasePath(string $path = ''): self + { + if ($path !== '') { + $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + } + + $this->basePath = $path; + + return $this; + } + + /** + * @return $this + */ + public function includeStacktraces(bool $include = true, ?Closure $parser = null): self + { + $this->includeStacktraces = $include; + if ($this->includeStacktraces) { + $this->allowInlineLineBreaks = true; + $this->stacktracesParser = $parser; + } + + return $this; + } + + /** + * Indent stack traces to separate them a bit from the main log record messages + * + * @param string $indent The string used to indent, for example " " + * @return $this + */ + public function indentStacktraces(string $indent): self + { + $this->indentStacktraces = $indent; + + return $this; + } + + /** + * @return $this + */ + public function allowInlineLineBreaks(bool $allow = true): self + { + $this->allowInlineLineBreaks = $allow; + + return $this; + } + + /** + * @return $this + */ + public function ignoreEmptyContextAndExtra(bool $ignore = true): self + { + $this->ignoreEmptyContextAndExtra = $ignore; + + return $this; + } + + /** + * Allows cutting the level name to get fixed-length levels like INF for INFO, ERR for ERROR if you set this to 3 for example + * + * @param int|null $maxLevelNameLength Maximum characters for the level name. Set null for infinite length (default) + * @return $this + */ + public function setMaxLevelNameLength(?int $maxLevelNameLength = null): self + { + $this->maxLevelNameLength = $maxLevelNameLength; + + return $this; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record): string + { + $vars = parent::format($record); + + if ($this->maxLevelNameLength !== null) { + $vars['level_name'] = substr($vars['level_name'], 0, $this->maxLevelNameLength); + } + + // $format is protected, so a subclass may change it after construction + if ($this->parsedFormat !== $this->format) { + $this->parseFormat(array_keys($vars)); + } + + // keys printed on their own are left out of %context% and %extra% + $remaining = ['context' => $vars['context'], 'extra' => $vars['extra']]; + foreach ($this->formatKeys as [$group, $key]) { + unset($remaining[$group][$key]); + } + + // the line is built from the parsed format, so placeholders in logged values are never expanded + $output = ''; + foreach ($this->formatParts as $part) { + if (\is_string($part)) { + $output .= $part; + continue; + } + + [$name, $key] = $part; + if ($key !== null) { + // %context.x% and %extra.x% of a missing key are removed + if (\array_key_exists($key, $vars[$name])) { + $output .= $this->stringify($vars[$name][$key]); + } + } elseif (isset($remaining[$name])) { + if (!$this->ignoreEmptyContextAndExtra || \count($remaining[$name]) > 0) { + $output .= $this->stringify($remaining[$name]); + } + } elseif (\array_key_exists($name, $vars)) { + $output .= $this->stringify($vars[$name]); + } else { + $output .= '%'.$name.'%'; + } + } + + return $output; + } + + /** + * @param array<int|string> $names the record fields, only those are placeholders so a stray % cannot eat the next one + */ + private function parseFormat(array $names): void + { + $this->formatParts = $this->formatKeys = []; + + $names = implode('|', array_map(static fn ($name) => preg_quote((string) $name), $names)); + preg_match_all('{%(?:(context|extra)\.([^%]*)|('.$names.'))%}', $this->format, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE); + $offset = 0; + foreach ($matches as $match) { + if ($match[0][1] > $offset) { + $this->formatParts[] = substr($this->format, $offset, $match[0][1] - $offset); + } + $offset = $match[0][1] + \strlen($match[0][0]); + + if (isset($match[3])) { + $this->formatParts[] = [$match[3][0], null]; + } elseif (isset($match[1], $match[2])) { + $this->formatParts[] = $this->formatKeys[] = [$match[1][0], $match[2][0]]; + } + } + if ($offset < \strlen($this->format)) { + $this->formatParts[] = substr($this->format, $offset); + } + + $this->parsedFormat = $this->format; + } + + public function formatBatch(array $records): string + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } + + /** + * @param mixed $value + */ + public function stringify($value): string + { + return $this->replaceNewlines($this->convertToString($value)); + } + + protected function normalizeException(\Throwable $e, int $depth = 0): string + { + $str = $this->formatException($e); + + $previous = $e->getPrevious(); + while ($previous instanceof \Throwable) { + $depth++; + if ($depth > $this->maxNormalizeDepth) { + $str .= "\n[previous exception] Over " . $this->maxNormalizeDepth . ' levels deep, aborting normalization'; + break; + } + $str .= "\n[previous exception] " . $this->formatException($previous); + $previous = $previous->getPrevious(); + } + + return $str; + } + + /** + * @param mixed $data + */ + protected function convertToString($data): string + { + if (null === $data || \is_bool($data)) { + return var_export($data, true); + } + + if (\is_scalar($data)) { + return (string) $data; + } + + return $this->toJson($data, true); + } + + protected function replaceNewlines(string $str): string + { + if ($this->allowInlineLineBreaks) { + if (0 === strpos($str, '{') || 0 === strpos($str, '[')) { + $str = preg_replace('/(?<!\\\\)\\\\[rn]/', "\n", $str); + if (null === $str) { + $pcreErrorCode = preg_last_error(); + + throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); + } + } + + return $str; + } + + return str_replace(["\r\n", "\r", "\n"], ' ', $str); + } + + private function formatException(\Throwable $e): string + { + $str = '[object] (' . Utils::getClass($e) . '(code: ' . $e->getCode(); + if ($e instanceof \SoapFault) { + if (isset($e->faultcode)) { + $str .= ' faultcode: ' . $e->faultcode; + } + + if (isset($e->faultactor)) { + $str .= ' faultactor: ' . $e->faultactor; + } + + if (isset($e->detail)) { + if (\is_string($e->detail)) { + $str .= ' detail: ' . $e->detail; + } elseif (\is_object($e->detail) || \is_array($e->detail)) { + $str .= ' detail: ' . $this->toJson($e->detail, true); + } + } + } + + $file = $e->getFile(); + if ($this->basePath !== '') { + $file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file); + } + + $str .= '): ' . $e->getMessage() . ' at ' . strtr((string) $file, DIRECTORY_SEPARATOR, '/') . ':' . $e->getLine() . ')'; + + if ($this->includeStacktraces) { + $str .= $this->stacktracesParser($e); + } + + return $str; + } + + private function stacktracesParser(\Throwable $e): string + { + $trace = $e->getTraceAsString(); + + if ($this->basePath !== '') { + $trace = preg_replace('{^(#\d+ )' . preg_quote($this->basePath) . '}m', '$1', $trace) ?? $trace; + } + + if ($this->stacktracesParser !== null) { + $trace = $this->stacktracesParserCustom($trace); + } + + if ($this->indentStacktraces !== '') { + $trace = str_replace("\n", "\n{$this->indentStacktraces}", $trace); + } + + if (trim($trace) === '') { + return ''; + } + + return "\n{$this->indentStacktraces}[stacktrace]\n{$this->indentStacktraces}" . strtr($trace, DIRECTORY_SEPARATOR, '/') . "\n"; + } + + private function stacktracesParserCustom(string $trace): string + { + return implode("\n", array_filter(array_map($this->stacktracesParser, explode("\n", $trace)), fn ($line) => is_string($line) && trim($line) !== '')); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php new file mode 100644 index 0000000..5f0b6a4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php @@ -0,0 +1,47 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\LogRecord; + +/** + * Encodes message information into JSON in a format compatible with Loggly. + * + * @author Adam Pancutt <adam@pancutt.com> + */ +class LogglyFormatter extends JsonFormatter +{ + /** + * Overrides the default batch mode to new lines for compatibility with the + * Loggly bulk API. + */ + public function __construct(int $batchMode = self::BATCH_MODE_NEWLINES, bool $appendNewline = false) + { + parent::__construct($batchMode, $appendNewline); + } + + /** + * Appends the 'timestamp' parameter for indexing by Loggly. + * + * @see https://www.loggly.com/docs/automated-parsing/#json + * @see \Monolog\Formatter\JsonFormatter::format() + */ + protected function normalizeRecord(LogRecord $record): array + { + $recordData = parent::normalizeRecord($record); + + $recordData["timestamp"] = $record->datetime->format("Y-m-d\TH:i:s.uO"); + unset($recordData["datetime"]); + + return $recordData; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php new file mode 100644 index 0000000..9e44c19 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php @@ -0,0 +1,70 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\LogRecord; + +/** + * Encodes message information into JSON in a format compatible with Logmatic. + * + * @author Julien Breux <julien.breux@gmail.com> + */ +class LogmaticFormatter extends JsonFormatter +{ + protected const MARKERS = ["sourcecode", "php"]; + + protected string $hostname = ''; + + protected string $appName = ''; + + /** + * @return $this + */ + public function setHostname(string $hostname): self + { + $this->hostname = $hostname; + + return $this; + } + + /** + * @return $this + */ + public function setAppName(string $appName): self + { + $this->appName = $appName; + + return $this; + } + + /** + * Appends the 'hostname' and 'appname' parameter for indexing by Logmatic. + * + * @see http://doc.logmatic.io/docs/basics-to-send-data + * @see \Monolog\Formatter\JsonFormatter::format() + */ + public function normalizeRecord(LogRecord $record): array + { + $record = parent::normalizeRecord($record); + + if ($this->hostname !== '') { + $record["hostname"] = $this->hostname; + } + if ($this->appName !== '') { + $record["appname"] = $this->appName; + } + + $record["@marker"] = static::MARKERS; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php new file mode 100644 index 0000000..d0e8749 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php @@ -0,0 +1,100 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\LogRecord; + +/** + * Serializes a log message to Logstash Event Format + * + * @see https://www.elastic.co/products/logstash + * @see https://github.com/elastic/logstash/blob/master/logstash-core/src/main/java/org/logstash/Event.java + * + * @author Tim Mower <timothy.mower@gmail.com> + */ +class LogstashFormatter extends NormalizerFormatter +{ + /** + * @var string the name of the system for the Logstash log message, used to fill the @source field + */ + protected string $systemName; + + /** + * @var string an application name for the Logstash log message, used to fill the @type field + */ + protected string $applicationName; + + /** + * @var string the key for 'extra' fields from the Monolog record + */ + protected string $extraKey; + + /** + * @var string the key for 'context' fields from the Monolog record + */ + protected string $contextKey; + + /** + * @param string $applicationName The application that sends the data, used as the "type" field of logstash + * @param string|null $systemName The system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine + * @param string $extraKey The key for extra keys inside logstash "fields", defaults to extra + * @param string $contextKey The key for context keys inside logstash "fields", defaults to context + */ + public function __construct(string $applicationName, ?string $systemName = null, string $extraKey = 'extra', string $contextKey = 'context') + { + // logstash requires a ISO 8601 format date with optional millisecond precision. + parent::__construct('Y-m-d\TH:i:s.uP'); + + $this->systemName = $systemName === null ? (string) gethostname() : $systemName; + $this->applicationName = $applicationName; + $this->extraKey = $extraKey; + $this->contextKey = $contextKey; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record): string + { + $recordData = parent::format($record); + + $message = [ + '@timestamp' => $recordData['datetime'], + '@version' => 1, + 'host' => $this->systemName, + ]; + if (isset($recordData['message'])) { + $message['message'] = $recordData['message']; + } + if (isset($recordData['channel'])) { + $message['type'] = $recordData['channel']; + $message['channel'] = $recordData['channel']; + } + if (isset($recordData['level_name'])) { + $message['level'] = $recordData['level_name']; + } + if (isset($recordData['level'])) { + $message['monolog_level'] = $recordData['level']; + } + if ('' !== $this->applicationName) { + $message['type'] = $this->applicationName; + } + if (\count($recordData['extra']) > 0) { + $message[$this->extraKey] = $recordData['extra']; + } + if (\count($recordData['context']) > 0) { + $message[$this->contextKey] = $recordData['context']; + } + + return $this->toJson($message) . "\n"; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php new file mode 100644 index 0000000..64ecef2 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php @@ -0,0 +1,129 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use MongoDB\BSON\Type; +use MongoDB\BSON\UTCDateTime; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Formats a record for use with the MongoDBHandler. + * + * @author Florian Plattner <me@florianplattner.de> + */ +class MongoDBFormatter implements FormatterInterface +{ + private bool $exceptionTraceAsString; + private int $maxNestingLevel; + + /** + * @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record->context is 2 + * @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings + */ + public function __construct(int $maxNestingLevel = 3, bool $exceptionTraceAsString = true) + { + $this->maxNestingLevel = max($maxNestingLevel, 0); + $this->exceptionTraceAsString = $exceptionTraceAsString; + } + + /** + * @inheritDoc + * + * @return mixed[] + */ + public function format(LogRecord $record): array + { + /** @var mixed[] $res */ + $res = $this->formatArray($record->toArray()); + + return $res; + } + + /** + * @inheritDoc + * + * @return array<mixed[]> + */ + public function formatBatch(array $records): array + { + $formatted = []; + foreach ($records as $key => $record) { + $formatted[$key] = $this->format($record); + } + + return $formatted; + } + + /** + * @param mixed[] $array + * @return mixed[]|string Array except when max nesting level is reached then a string "[...]" + */ + protected function formatArray(array $array, int $nestingLevel = 0) + { + if ($this->maxNestingLevel > 0 && $nestingLevel > $this->maxNestingLevel) { + return '[...]'; + } + + foreach ($array as $name => $value) { + if ($value instanceof \DateTimeInterface) { + $array[$name] = $this->formatDate($value, $nestingLevel + 1); + } elseif ($value instanceof \Throwable) { + $array[$name] = $this->formatException($value, $nestingLevel + 1); + } elseif (\is_array($value)) { + $array[$name] = $this->formatArray($value, $nestingLevel + 1); + } elseif (\is_object($value) && !$value instanceof Type) { + $array[$name] = $this->formatObject($value, $nestingLevel + 1); + } + } + + return $array; + } + + /** + * @param mixed $value + * @return mixed[]|string + */ + protected function formatObject($value, int $nestingLevel) + { + $objectVars = get_object_vars($value); + $objectVars['class'] = Utils::getClass($value); + + return $this->formatArray($objectVars, $nestingLevel); + } + + /** + * @return mixed[]|string + */ + protected function formatException(\Throwable $exception, int $nestingLevel) + { + $formattedException = [ + 'class' => Utils::getClass($exception), + 'message' => $exception->getMessage(), + 'code' => (int) $exception->getCode(), + 'file' => $exception->getFile() . ':' . $exception->getLine(), + ]; + + if ($this->exceptionTraceAsString === true) { + $formattedException['trace'] = $exception->getTraceAsString(); + } else { + $formattedException['trace'] = $exception->getTrace(); + } + + return $this->formatArray($formattedException, $nestingLevel); + } + + protected function formatDate(\DateTimeInterface $value, int $nestingLevel): UTCDateTime + { + return new UTCDateTime((int) floor(((float) $value->format('U.u')) * 1000)); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php new file mode 100644 index 0000000..7fc6de4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php @@ -0,0 +1,394 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\JsonSerializableDateTimeImmutable; +use Monolog\Utils; +use Throwable; +use Monolog\LogRecord; + +/** + * Normalizes incoming records to remove objects/resources so it's easier to dump to various targets + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class NormalizerFormatter implements FormatterInterface +{ + public const SIMPLE_DATE = "Y-m-d\TH:i:sP"; + + protected string $dateFormat; + protected int $maxNormalizeDepth = 9; + protected int $maxNormalizeItemCount = 1000; + protected ?int $maxTraceLength = null; + + private int $jsonEncodeOptions = Utils::DEFAULT_JSON_FLAGS; + + protected string $basePath = ''; + + /** + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct(?string $dateFormat = null) + { + $this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record) + { + return $this->normalizeRecord($record); + } + + /** + * Normalize an arbitrary value to a scalar|array|null + * + * @return null|scalar|array<mixed[]|scalar|null> + */ + public function normalizeValue(mixed $data): mixed + { + return $this->normalize($data); + } + + /** + * @inheritDoc + */ + public function formatBatch(array $records) + { + foreach ($records as $key => $record) { + $records[$key] = $this->format($record); + } + + return $records; + } + + public function getDateFormat(): string + { + return $this->dateFormat; + } + + /** + * @return $this + */ + public function setDateFormat(string $dateFormat): self + { + $this->dateFormat = $dateFormat; + + return $this; + } + + /** + * The maximum number of normalization levels to go through + */ + public function getMaxNormalizeDepth(): int + { + return $this->maxNormalizeDepth; + } + + /** + * @return $this + */ + public function setMaxNormalizeDepth(int $maxNormalizeDepth): self + { + $this->maxNormalizeDepth = $maxNormalizeDepth; + + return $this; + } + + /** + * The maximum number of items to normalize per level + */ + public function getMaxNormalizeItemCount(): int + { + return $this->maxNormalizeItemCount; + } + + /** + * @return $this + */ + public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self + { + $this->maxNormalizeItemCount = $maxNormalizeItemCount; + + return $this; + } + + /** + * The maximum number of stack trace frames to include + */ + public function getMaxTraceLength(): ?int + { + return $this->maxTraceLength; + } + + /** + * @return $this + */ + public function setMaxTraceLength(?int $maxTraceLength): self + { + $this->maxTraceLength = $maxTraceLength; + + return $this; + } + + /** + * Enables `json_encode` pretty print. + * + * @return $this + */ + public function setJsonPrettyPrint(bool $enable): self + { + if ($enable) { + $this->jsonEncodeOptions |= JSON_PRETTY_PRINT; + } else { + $this->jsonEncodeOptions &= ~JSON_PRETTY_PRINT; + } + + return $this; + } + + /** + * Setting a base path will hide the base path from exception and stack trace file names to shorten them + * @return $this + */ + public function setBasePath(string $path = ''): self + { + if ($path !== '') { + $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + } + + $this->basePath = $path; + + return $this; + } + + /** + * Provided as extension point + * + * Because normalize is called with sub-values of context data etc, normalizeRecord can be + * extended when data needs to be appended on the record array but not to other normalized data. + * + * @return array<mixed[]|scalar|null> + */ + protected function normalizeRecord(LogRecord $record): array + { + /** @var array<mixed[]|scalar|null> $normalized */ + $normalized = $this->normalize($record->toArray()); + + return $normalized; + } + + /** + * @return null|scalar|array<mixed[]|scalar|null> + */ + protected function normalize(mixed $data, int $depth = 0): mixed + { + if (null === $data || \is_scalar($data)) { + if (\is_float($data)) { + if (is_infinite($data)) { + return ($data > 0 ? '' : '-') . 'INF'; + } + if (is_nan($data)) { + return 'NaN'; + } + } + + return $data; + } + + if ($depth > $this->maxNormalizeDepth) { + return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization'; + } + + if (\is_array($data)) { + $normalized = []; + + $count = 1; + foreach ($data as $key => $value) { + if ($count++ > $this->maxNormalizeItemCount) { + $normalized['...'] = 'Over ' . $this->maxNormalizeItemCount . ' items ('.\count($data).' total), aborting normalization'; + break; + } + + $normalized[$key] = $this->normalize($value, $depth + 1); + } + + return $normalized; + } + + if ($data instanceof \DateTimeInterface) { + return $this->formatDate($data); + } + + if (\is_object($data)) { + if ($data instanceof Throwable) { + return $this->normalizeException($data, $depth); + } + + if ($data instanceof \JsonSerializable) { + /** @var null|scalar|array<mixed[]|scalar|null> $value */ + $value = $data->jsonSerialize(); + } elseif (\get_class($data) === '__PHP_Incomplete_Class') { + $accessor = new \ArrayObject($data); + $value = (string) $accessor['__PHP_Incomplete_Class_Name']; + } elseif (method_exists($data, '__toString')) { + try { + /** @var string $value */ + $value = $data->__toString(); + } catch (\Throwable) { + // if the toString method is failing, use the default behavior + /** @var null|scalar|array<mixed[]|scalar|null> $value */ + $value = json_decode($this->toJson($data, true), true); + } + } else { + // the rest is normalized by json encoding and decoding it + /** @var null|scalar|array<mixed[]|scalar|null> $value */ + $value = json_decode($this->toJson($data, true), true); + } + + return [Utils::getClass($data) => $value]; + } + + if (\is_resource($data)) { + return sprintf('[resource(%s)]', get_resource_type($data)); + } + + return '[unknown('.\gettype($data).')]'; + } + + /** + * @return array<array-key, string|int|array<string|int|array<string>>> + */ + protected function normalizeException(Throwable $e, int $depth = 0) + { + if ($depth > $this->maxNormalizeDepth) { + return ['Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization']; + } + + if ($e instanceof \JsonSerializable) { + return (array) $e->jsonSerialize(); + } + + $file = $e->getFile(); + if ($this->basePath !== '') { + $file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file); + } + + $data = [ + 'class' => Utils::getClass($e), + 'message' => $e->getMessage(), + 'code' => (int) $e->getCode(), + 'file' => $file.':'.$e->getLine(), + ]; + + if ($e instanceof \SoapFault) { + if (isset($e->faultcode)) { + $data['faultcode'] = $e->faultcode; + } + + if (isset($e->faultactor)) { + $data['faultactor'] = $e->faultactor; + } + + if (isset($e->detail)) { + if (\is_string($e->detail)) { + $data['detail'] = $e->detail; + } elseif (\is_object($e->detail) || \is_array($e->detail)) { + $data['detail'] = $this->toJson($e->detail, true); + } + } + } + + $trace = array_slice($e->getTrace(), 0, $this->maxTraceLength); + foreach ($trace as $frame) { + if (isset($frame['file'])) { + $file = $frame['file']; + if ($this->basePath !== '') { + $file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file) ?? $file; + } + $data['trace'][] = $file.':'.($frame['line'] ?? 0); + } else { + // Frames called by the engine itself have no file/line: shutdown functions, + // callbacks run by internal functions, destructors. Skipping them made traces + // look shorter than they were, and entirely empty for fatal errors caught in a + // shutdown function, so they are reported by name instead. + $call = $frame['function']; + // since PHP 8.4 a closure is named after its declaring scope, which already + // includes the class, so prefixing it again would just repeat it + if (isset($frame['class']) && !str_starts_with($call, '{closure:')) { + // before 8.4 the name is <namespace>\{closure}, and the class has the namespace + $call = str_ends_with($call, '\{closure}') ? '{closure}' : $call; + $call = Utils::getClassName($frame['class']).($frame['type'] ?? '::').$call; + } + // anonymous classes carry their declaration site after a NUL byte, which truncates + // syslog lines and is not valid JSON; PHP 8.4 embeds it in closure names too + $call = preg_replace('{@anonymous\x00.*?\$[0-9a-f]++(?=::|$)}s', '@anonymous', $call) ?? $call; + if ($this->basePath !== '') { + // closure names embed the file they were declared in since PHP 8.4, so the + // pattern cannot be anchored; limit it or a recurring base path is stripped twice + $call = preg_replace('{'.preg_quote($this->basePath).'}', '', $call, 1) ?? $call; + } + $data['trace'][] = 'internal['.$call.']:0'; + } + } + + if (($previous = $e->getPrevious()) instanceof \Throwable) { + $data['previous'] = $this->normalizeException($previous, $depth + 1); + } + + return $data; + } + + /** + * Return the JSON representation of a value + * + * @param mixed $data + * @throws \RuntimeException if encoding fails and errors are not ignored + * @return string if encoding fails and ignoreErrors is true 'null' is returned + */ + protected function toJson($data, bool $ignoreErrors = false): string + { + return Utils::jsonEncode($data, $this->jsonEncodeOptions, $ignoreErrors); + } + + protected function formatDate(\DateTimeInterface $date): string + { + // in case the date format isn't custom then we defer to the custom JsonSerializableDateTimeImmutable + // formatting logic, which will pick the right format based on whether useMicroseconds is on + if ($this->dateFormat === self::SIMPLE_DATE && $date instanceof JsonSerializableDateTimeImmutable) { + return (string) $date; + } + + return $date->format($this->dateFormat); + } + + /** + * @return $this + */ + public function addJsonEncodeOption(int $option): self + { + $this->jsonEncodeOptions |= $option; + + return $this; + } + + /** + * @return $this + */ + public function removeJsonEncodeOption(int $option): self + { + $this->jsonEncodeOptions &= ~$option; + + return $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/RedactingFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/RedactingFormatter.php new file mode 100644 index 0000000..1bf5818 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/RedactingFormatter.php @@ -0,0 +1,393 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\LogRecord; +use Monolog\Utils; + +/** + * Wraps another formatter to redact sensitive data from log records. + * + * It works in three passes so that it can mask secrets wherever they end up: + * + * - Before delegating, it masks the value of any context/extra key whose name + * matches one of the configured sensitive keys (case-insensitive, recursive). + * - After delegating, it removes those same secret values from the wrapped + * formatter's output, which catches the copies masking the record cannot + * reach, e.g. a secret interpolated into the message by the + * PsrLogMessageProcessor or embedded in an exception message. + * - Last, it runs the configured regex patterns over the output, which catches + * secrets that only became strings once the inner formatter normalized + * objects (e.g. tokens buried in an exception stack trace). If a pattern + * cannot be applied, the record is dropped instead of emitted unredacted. + * + * Objects in the record cannot be modified either, so sensitive keys found in what + * formatters normalize them to (public properties, or jsonSerialize()) are only + * handled by the output pass. That means their values are subject to + * $minSecretLength and must be strings or Stringable to be removed. + * + * On top of the sensitive keys, secrets are also read from the properties of the + * objects in the record matching a constructor parameter marked + * #[SensitiveParameter]. Those can only be handled by the output pass, as the + * objects carrying them cannot be modified. This is the one part that reflects on + * every logged object, so it can be turned off with $redactSensitiveParameters. + * + * Only string and array output can be swept, so wrapping a formatter which returns + * objects (e.g. the ElasticaFormatter) leaves you with the key masking alone. + * + * Because it is a formatter rather than a processor, it is guaranteed to run + * after every processor (both Logger- and Handler-level), so it always sees the + * final record with all data at hand. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +final class RedactingFormatter implements WrappingFormatterInterface +{ + /** + * Matches long token-like words (30+ alphanumerics, optionally prefixed like api_key_), + * which are very likely to be secrets/tokens. Provided as an opt-in pattern as it may + * cause collateral damage on legitimate long strings (hashes, UUIDs, base64, ...). + */ + public const TOKEN_PATTERN = '{\b(?:[a-z]+_)*[a-zA-Z0-9]{30,}\b}'; + + /** + * How deep to walk the record and the output, mirrors NormalizerFormatter's default + */ + private const MAX_DEPTH = 9; + + /** @var list<string> Lowercased sensitive keys */ + private array $sensitiveKeys; + + /** @var list<string> */ + private array $patterns; + + /** @var array<class-string, array<string, \ReflectionProperty>> */ + private array $sensitiveProperties = []; + + /** + * @param FormatterInterface $formatter The formatter to wrap and whose output gets redacted + * @param list<string> $sensitiveKeys Exact context/extra keys whose values to mask (case-insensitive) + * @param list<string> $patterns PCRE patterns to mask in the formatted output (e.g. self::TOKEN_PATTERN) + * @param string $mask Replacement token + * @param bool $redactSensitiveParameters Whether to also read secrets off the properties matching a + * #[SensitiveParameter] constructor parameter, which requires + * reflecting on every object in the record + * @param int $minSecretLength Minimum length a secret must have to be removed from the + * output, to avoid short values like "pass" redacting + * unrelated data + * + * @throws \InvalidArgumentException If a pattern is not a valid PCRE regex + */ + public function __construct( + private readonly FormatterInterface $formatter, + array $sensitiveKeys = ['password', 'passwd', 'pwd', 'secret', 'token', 'api_key', 'apikey', 'authorization', 'auth', 'cookie'], + array $patterns = [], + private readonly string $mask = '[REDACTED]', + private readonly bool $redactSensitiveParameters = true, + private readonly int $minSecretLength = 5, + ) { + $this->sensitiveKeys = array_values(array_map('strtolower', $sensitiveKeys)); + + foreach ($patterns as $pattern) { + if (@preg_match($pattern, '') === false) { + throw new \InvalidArgumentException(sprintf('Invalid redaction pattern provided to RedactingFormatter: %s', var_export($pattern, true))); + } + } + $this->patterns = array_values($patterns); + } + + public function getWrappedFormatter(): FormatterInterface + { + return $this->formatter; + } + + public function format(LogRecord $record) + { + // secrets must be collected before the keys get masked, as masking loses the values + $secrets = $this->collectSecrets([$record]); + + return $this->sweep($this->formatter->format($this->redactRecord($record)), $secrets); + } + + public function formatBatch(array $records) + { + $secrets = $this->collectSecrets($records); + + foreach ($records as $key => $record) { + $records[$key] = $this->redactRecord($record); + } + + return $this->sweep($this->formatter->formatBatch($records), $secrets); + } + + private function redactRecord(LogRecord $record): LogRecord + { + return $record->with( + context: $this->redactKeys($record->context), + extra: $this->redactKeys($record->extra), + ); + } + + /** + * @param array<mixed> $data + * @return array<mixed> + */ + private function redactKeys(array $data, int $depth = 0): array + { + // context comes from userland and can hold a self-referencing array + if ($depth > self::MAX_DEPTH) { + return $data; + } + + foreach ($data as $key => $value) { + if (\is_string($key) && \in_array(strtolower($key), $this->sensitiveKeys, true)) { + $data[$key] = $this->mask; + } elseif (\is_array($value)) { + $data[$key] = $this->redactKeys($value, $depth + 1); + } + } + + return $data; + } + + /** + * Gathers the secret values present in the given records, longest first + * + * @param iterable<LogRecord> $records + * @return list<string> + */ + private function collectSecrets(iterable $records): array + { + $secrets = []; + $seen = []; + foreach ($records as $record) { + $this->collect($record->context, $secrets, $seen, 0); + $this->collect($record->extra, $secrets, $seen, 0); + } + + if ([] === $secrets) { + return []; + } + + // every spelling the wrapped formatter can produce has to be looked for: json-escaped with or + // without unicode/slash escaping, html-escaped, and with line breaks turned into spaces + $escapedSecrets = []; + foreach ($secrets as $secret) { + $spellings = [ + htmlspecialchars($secret, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8'), + str_replace(["\r\n", "\r", "\n"], ' ', $secret), + ]; + foreach ([0, JSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES] as $flags) { + $spellings[] = substr(Utils::jsonEncode($secret, (Utils::DEFAULT_JSON_FLAGS & ~(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) | $flags, true), 1, -1); + } + foreach ($spellings as $escaped) { + if ($escaped !== $secret && $escaped !== '') { + $escapedSecrets[] = $escaped; + } + } + } + + $secrets = array_values(array_unique(array_merge($secrets, $escapedSecrets))); + // longest first, so that overlapping secrets do not leave fragments behind + usort($secrets, static fn (string $a, string $b) => \strlen($b) <=> \strlen($a)); + + return $secrets; + } + + /** + * @param list<string> $secrets + * @param array<int, true> $seen Ids of the objects visited so far, to survive cyclic graphs + */ + private function collect(mixed $data, array &$secrets, array &$seen, int $depth): void + { + if ($depth > self::MAX_DEPTH) { + return; + } + + if (\is_array($data)) { + foreach ($data as $key => $value) { + if (\is_string($key) && \in_array(strtolower($key), $this->sensitiveKeys, true)) { + // the value is masked in the record, but a nested array's leaves can still + // leak elsewhere (e.g. json-encoded by PsrLogMessageProcessor) + $this->collectSensitiveValue($value, $secrets, $depth + 1); + + continue; + } + + $this->collect($value, $secrets, $seen, $depth + 1); + } + + return; + } + + if (!\is_object($data)) { + return; + } + + $id = spl_object_id($data); + if (isset($seen[$id])) { + return; + } + $seen[$id] = true; + + // the array walks are essentially free, reflecting on objects is not + if ($this->redactSensitiveParameters) { + foreach ($this->getSensitiveProperties($data) as $property) { + if ($property->isInitialized($data)) { + $this->addSecret($property->getValue($data), $secrets); + } + } + } + + // formatters normalize an object to its public properties or to jsonSerialize(), so sensitive + // keys are looked for in both, which also reaches the objects nested inside this one + $this->collect(get_object_vars($data), $secrets, $seen, $depth); + if ($data instanceof \JsonSerializable) { + try { + $this->collect($data->jsonSerialize(), $secrets, $seen, $depth); + } catch (\Throwable) { + // the wrapped formatter deals with it failing + } + } + } + + /** + * Collects every string leaf nested inside a value under a sensitive key. + * + * @param list<string> $secrets + */ + private function collectSensitiveValue(mixed $value, array &$secrets, int $depth): void + { + if ($depth > self::MAX_DEPTH) { + return; + } + + if (\is_array($value)) { + foreach ($value as $item) { + $this->collectSensitiveValue($item, $secrets, $depth + 1); + } + + return; + } + + $this->addSecret($value, $secrets); + } + + /** + * Reflects the properties of an object matching a #[SensitiveParameter] constructor parameter + * + * Non-public properties are included as they can still leak through __toString(), and the + * result is cached per class as reflecting on every logged object would be far too costly. + * + * @return array<string, \ReflectionProperty> + */ + private function getSensitiveProperties(object $data): array + { + $class = $data::class; + if (isset($this->sensitiveProperties[$class])) { + return $this->sensitiveProperties[$class]; + } + + $names = Utils::getSensitiveParameterNames($class); + + // PHP 8.2+ wraps the arguments it hides from stack traces in a SensitiveParameterValue, + // whose own constructor parameter is not marked. Matched by name and read as a property + // so that it does not matter whether symfony/polyfill-php82 is installed on PHP 8.1: + // naming the class makes PHPStan report either the @internal getValue() the polyfill + // inherits, or a missing class when it is absent. + if ('SensitiveParameterValue' === $class) { + $names['value'] = true; + } + + $properties = []; + foreach ($names as $name => $_) { + // walking up is required as a private property of a parent class is not + // reachable through the child's ReflectionClass + for ($reflection = new \ReflectionClass($class); false !== $reflection; $reflection = $reflection->getParentClass()) { + if ($reflection->hasProperty($name)) { + $properties[$name] = $reflection->getProperty($name); + + break; + } + } + } + + return $this->sensitiveProperties[$class] = $properties; + } + + /** + * @param list<string> $secrets + */ + private function addSecret(mixed $value, array &$secrets): void + { + // a Stringable secret ends up in the output as its string form, so that is what + // has to be looked for + if ($value instanceof \Stringable) { + try { + $value = $value->__toString(); + } catch (\Throwable) { + return; + } + } + + // ints/floats are left out on purpose, sweeping a digit run out of the output + // would silently corrupt unrelated data + if (\is_string($value) && $value !== '' && \strlen($value) >= $this->minSecretLength) { + $secrets[] = $value; + } + } + + /** + * Removes the collected secrets and applies the configured patterns to the formatter output, + * recursing into arrays to support formatters that do not return a string (e.g. MongoDBFormatter). + * + * @param list<string> $secrets + */ + private function sweep(mixed $formatted, array $secrets, int $depth = 0): mixed + { + if ([] === $this->patterns && [] === $secrets) { + return $formatted; + } + + // deeper than any formatter will render anyway, and a custom one may well + // hand back a self-referencing array + if ($depth > self::MAX_DEPTH) { + return $formatted; + } + + if (\is_string($formatted)) { + if ([] !== $secrets) { + $formatted = str_replace($secrets, $this->mask, $formatted); + } + if ([] !== $this->patterns) { + $replaced = preg_replace($this->patterns, $this->mask, $formatted); + if (null === $replaced) { + // the patterns could not be applied so the output cannot be trusted, drop it + // entirely. Neither the patterns (which may embed a secret themselves) nor the + // mask are reported, preg_last_error_msg() is one of a fixed set of PCRE strings + return '[RedactingFormatter dropped this record, pattern redaction failed with "'.preg_last_error_msg().'"]'; + } + $formatted = $replaced; + } + + return $formatted; + } + + if (\is_array($formatted)) { + foreach ($formatted as $key => $value) { + $formatted[$key] = $this->sweep($value, $secrets, $depth + 1); + } + } + + return $formatted; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php new file mode 100644 index 0000000..ec73a0e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php @@ -0,0 +1,49 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\LogRecord; + +/** + * Formats data into an associative array of scalar (+ null) values. + * Objects and arrays will be JSON encoded. + * + * @author Andrew Lawson <adlawson@gmail.com> + */ +class ScalarFormatter extends NormalizerFormatter +{ + /** + * @inheritDoc + * + * @phpstan-return array<string, scalar|null> $record + */ + public function format(LogRecord $record): array + { + $result = []; + foreach ($record->toArray() as $key => $value) { + $result[$key] = $this->toScalar($value); + } + + return $result; + } + + protected function toScalar(mixed $value): string|int|float|bool|null + { + $normalized = $this->normalize($value); + + if (\is_array($normalized)) { + return $this->toJson($normalized, true); + } + + return $normalized; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/SyslogFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/SyslogFormatter.php new file mode 100644 index 0000000..34030ea --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/SyslogFormatter.php @@ -0,0 +1,66 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Serializes a log message according to RFC 5424 + * + * @author Dalibor Karlović <dalibor.karlovic@sigwin.hr> + * @author Renat Gabdullin <renatobyj@gmail.com> + */ +class SyslogFormatter extends LineFormatter +{ + private const SYSLOG_FACILITY_USER = 1; + private const FORMAT = "<%extra.priority%>1 %datetime% %extra.hostname% %extra.app-name% %extra.procid% %channel% %extra.structured-data% %level_name%: %message% %context% %extra%\n"; + private const NILVALUE = '-'; + + private string $hostname; + private int $procid; + + public function __construct(private string $applicationName = self::NILVALUE) + { + // a raw line break would let a message start what line-based consumers read as a second record + parent::__construct(self::FORMAT, 'Y-m-d\TH:i:s.uP', false, true); + $this->hostname = (string) gethostname(); + $this->procid = (int) getmypid(); + } + + public function format(LogRecord $record): string + { + $record->extra = $this->formatExtra($record); + + return parent::format($record); + } + + /** + * @return array<string, mixed> + */ + private function formatExtra(LogRecord $record): array + { + $extra = $record->extra; + $extra['app-name'] = $this->applicationName; + $extra['hostname'] = $this->hostname; + $extra['procid'] = $this->procid; + $extra['priority'] = self::calculatePriority($record->level); + $extra['structured-data'] = self::NILVALUE; + + return $extra; + } + + private static function calculatePriority(Level $level): int + { + return (self::SYSLOG_FACILITY_USER * 8) + $level->toRFC5424Level(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php new file mode 100644 index 0000000..4acfb92 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php @@ -0,0 +1,137 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Serializes a log message according to Wildfire's header requirements + * + * @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com> + * @author Christophe Coevoet <stof@notk.org> + * @author Kirill chEbba Chebunin <iam@chebba.org> + */ +class WildfireFormatter extends NormalizerFormatter +{ + /** + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct(?string $dateFormat = null) + { + parent::__construct($dateFormat); + + // http headers do not like non-ISO-8559-1 characters + $this->removeJsonEncodeOption(JSON_UNESCAPED_UNICODE); + } + + /** + * Translates Monolog log levels to Wildfire levels. + * + * @return 'LOG'|'INFO'|'WARN'|'ERROR' + */ + private function toWildfireLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'LOG', + Level::Info => 'INFO', + Level::Notice => 'INFO', + Level::Warning => 'WARN', + Level::Error => 'ERROR', + Level::Critical => 'ERROR', + Level::Alert => 'ERROR', + Level::Emergency => 'ERROR', + }; + } + + /** + * @inheritDoc + */ + public function format(LogRecord $record): string + { + // Retrieve the line and file if set and remove them from the formatted extra + $file = $line = ''; + if (isset($record->extra['file'])) { + $file = $record->extra['file']; + unset($record->extra['file']); + } + if (isset($record->extra['line'])) { + $line = $record->extra['line']; + unset($record->extra['line']); + } + + $message = ['message' => $record->message]; + $handleError = false; + if (\count($record->context) > 0) { + $message['context'] = $this->normalize($record->context); + $handleError = true; + } + if (\count($record->extra) > 0) { + $message['extra'] = $this->normalize($record->extra); + $handleError = true; + } + if (\count($message) === 1) { + $message = reset($message); + } + + if (is_array($message) && isset($message['context']) && \is_array($message['context']) && isset($message['context']['table'])) { + $type = 'TABLE'; + $label = $record->channel .': '. $record->message; + $message = $message['context']['table']; + } else { + $type = $this->toWildfireLevel($record->level); + $label = $record->channel; + } + + // Create JSON object describing the appearance of the message in the console + $json = $this->toJson([ + [ + 'Type' => $type, + 'File' => $file, + 'Line' => $line, + 'Label' => $label, + ], + $message, + ], $handleError); + + // The message itself is a serialization of the above JSON object + it's length + return sprintf( + '%d|%s|', + \strlen($json), + $json + ); + } + + /** + * @inheritDoc + * + * @phpstan-return never + */ + public function formatBatch(array $records) + { + throw new \BadMethodCallException('Batch formatting does not make sense for the WildfireFormatter'); + } + + /** + * @inheritDoc + * + * @return null|scalar|array<mixed[]|scalar|null>|object + */ + protected function normalize(mixed $data, int $depth = 0): mixed + { + if (\is_object($data) && !$data instanceof \DateTimeInterface) { + return $data; + } + + return parent::normalize($data, $depth); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/WrappingFormatterInterface.php b/vendor/monolog/monolog/src/Monolog/Formatter/WrappingFormatterInterface.php new file mode 100644 index 0000000..02a6b88 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/WrappingFormatterInterface.php @@ -0,0 +1,28 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Interface for formatters decorating another formatter + * + * Handlers which only accept one specific formatter can use Utils::unwrapFormatter() + * to see through the decoration and accept a wrapped instance of that formatter. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +interface WrappingFormatterInterface extends FormatterInterface +{ + /** + * Returns the formatter this one delegates the actual formatting to + */ + public function getWrappedFormatter(): FormatterInterface; +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php new file mode 100644 index 0000000..61d45d5 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php @@ -0,0 +1,104 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Logger; +use Monolog\ResettableInterface; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Base Handler class providing basic level/bubble support + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +abstract class AbstractHandler extends Handler implements ResettableInterface +{ + protected Level $level = Level::Debug; + protected bool $bubble = true; + + /** + * @param int|string|Level|LogLevel::* $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) + { + $this->setLevel($level); + $this->bubble = $bubble; + } + + /** + * @inheritDoc + */ + public function isHandling(LogRecord $record): bool + { + return $record->level->value >= $this->level->value; + } + + /** + * Sets minimum logging level at which this handler will be triggered. + * + * @param Level|LogLevel::* $level Level or level name + * @return $this + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function setLevel(int|string|Level $level): self + { + $this->level = Logger::toMonologLevel($level); + + return $this; + } + + /** + * Gets minimum logging level at which this handler will be triggered. + */ + public function getLevel(): Level + { + return $this->level; + } + + /** + * Sets the bubbling behavior. + * + * @param bool $bubble true means that this handler allows bubbling. + * false means that bubbling is not permitted. + * @return $this + */ + public function setBubble(bool $bubble): self + { + $this->bubble = $bubble; + + return $this; + } + + /** + * Gets the bubbling behavior. + * + * @return bool true means that this handler allows bubbling. + * false means that bubbling is not permitted. + */ + public function getBubble(): bool + { + return $this->bubble; + } + + /** + * @inheritDoc + */ + public function reset(): void + { + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php new file mode 100644 index 0000000..78bec3e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php @@ -0,0 +1,60 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\LogRecord; + +/** + * Base Handler class providing the Handler structure, including processors and formatters + * + * Classes extending it should (in most cases) only implement write($record) + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * @author Christophe Coevoet <stof@notk.org> + */ +abstract class AbstractProcessingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + use FormattableHandlerTrait; + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if (!$this->isHandling($record)) { + return false; + } + + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + $record->formatted = $this->getFormatter()->format($record); + + $this->write($record); + + return !$this->getBubble(); + } + + /** + * Writes the (already formatted) record down to the log of the implementing handler + */ + abstract protected function write(LogRecord $record): void; + + public function reset(): void + { + parent::reset(); + + $this->resetProcessors(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php new file mode 100644 index 0000000..4a70317 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php @@ -0,0 +1,95 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; + +/** + * Common syslog functionality + */ +abstract class AbstractSyslogHandler extends AbstractProcessingHandler +{ + protected int $facility; + + /** + * List of valid log facility names. + * @var array<string, int> + */ + protected array $facilities = [ + 'auth' => \LOG_AUTH, + 'authpriv' => \LOG_AUTHPRIV, + 'cron' => \LOG_CRON, + 'daemon' => \LOG_DAEMON, + 'kern' => \LOG_KERN, + 'lpr' => \LOG_LPR, + 'mail' => \LOG_MAIL, + 'news' => \LOG_NEWS, + 'syslog' => \LOG_SYSLOG, + 'user' => \LOG_USER, + 'uucp' => \LOG_UUCP, + ]; + + /** + * Translates Monolog log levels to syslog log priorities. + */ + protected function toSyslogPriority(Level $level): int + { + return $level->toRFC5424Level(); + } + + /** + * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant + */ + public function __construct(string|int $facility = \LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true) + { + parent::__construct($level, $bubble); + + if (!\defined('PHP_WINDOWS_VERSION_BUILD')) { + $this->facilities['local0'] = \LOG_LOCAL0; + $this->facilities['local1'] = \LOG_LOCAL1; + $this->facilities['local2'] = \LOG_LOCAL2; + $this->facilities['local3'] = \LOG_LOCAL3; + $this->facilities['local4'] = \LOG_LOCAL4; + $this->facilities['local5'] = \LOG_LOCAL5; + $this->facilities['local6'] = \LOG_LOCAL6; + $this->facilities['local7'] = \LOG_LOCAL7; + } else { + $this->facilities['local0'] = 128; // LOG_LOCAL0 + $this->facilities['local1'] = 136; // LOG_LOCAL1 + $this->facilities['local2'] = 144; // LOG_LOCAL2 + $this->facilities['local3'] = 152; // LOG_LOCAL3 + $this->facilities['local4'] = 160; // LOG_LOCAL4 + $this->facilities['local5'] = 168; // LOG_LOCAL5 + $this->facilities['local6'] = 176; // LOG_LOCAL6 + $this->facilities['local7'] = 184; // LOG_LOCAL7 + } + + // convert textual description of facility to syslog constant + if (\is_string($facility) && \array_key_exists(strtolower($facility), $this->facilities)) { + $facility = $this->facilities[strtolower($facility)]; + } elseif (!\in_array($facility, array_values($this->facilities), true)) { + throw new \UnexpectedValueException('Unknown facility value "'.$facility.'" given'); + } + + $this->facility = $facility; + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter('%channel%.%level_name%: %message% %context% %extra%'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php new file mode 100644 index 0000000..119f339 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php @@ -0,0 +1,170 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Gelf\Message as GelfMessage; +use Monolog\Level; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\JsonFormatter; +use PhpAmqpLib\Message\AMQPMessage; +use PhpAmqpLib\Channel\AMQPChannel; +use AMQPExchange; +use Monolog\LogRecord; + +class AmqpHandler extends AbstractProcessingHandler +{ + protected AMQPExchange|AMQPChannel $exchange; + + /** @var array<string, mixed> */ + private array $extraAttributes = []; + + protected string $exchangeName; + + /** + * @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use + * @param string|null $exchangeName Optional exchange name, for AMQPChannel (PhpAmqpLib) only + */ + public function __construct(AMQPExchange|AMQPChannel $exchange, ?string $exchangeName = null, int|string|Level $level = Level::Debug, bool $bubble = true) + { + if ($exchange instanceof AMQPChannel) { + $this->exchangeName = (string) $exchangeName; + } elseif ($exchangeName !== null) { + @trigger_error('The $exchangeName parameter can only be passed when using PhpAmqpLib, if using an AMQPExchange instance configure it beforehand', E_USER_DEPRECATED); + } + $this->exchange = $exchange; + + parent::__construct($level, $bubble); + } + + /** + * @return array<string, mixed> + */ + public function getExtraAttributes(): array + { + return $this->extraAttributes; + } + + /** + * Configure extra attributes to pass to the AMQPExchange (if you are using the amqp extension) + * + * @param array<string, mixed> $extraAttributes One of content_type, content_encoding, + * message_id, user_id, app_id, delivery_mode, + * priority, timestamp, expiration, type + * or reply_to, headers. + * @return $this + */ + public function setExtraAttributes(array $extraAttributes): self + { + $this->extraAttributes = $extraAttributes; + + return $this; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $data = $record->formatted; + $routingKey = $this->getRoutingKey($record); + + if($data instanceof GelfMessage) { + $data = json_encode($data->toArray()); + } + + if ($this->exchange instanceof AMQPExchange) { + $attributes = [ + 'delivery_mode' => 2, + 'content_type' => 'application/json', + ]; + if (\count($this->extraAttributes) > 0) { + $attributes = array_merge($attributes, $this->extraAttributes); + } + $this->exchange->publish( + $data, + $routingKey, + 0, + $attributes + ); + } else { + $this->exchange->basic_publish( + $this->createAmqpMessage($data), + $this->exchangeName, + $routingKey + ); + } + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + if ($this->exchange instanceof AMQPExchange) { + parent::handleBatch($records); + + return; + } + + foreach ($records as $record) { + if (!$this->isHandling($record)) { + continue; + } + + $record = $this->processRecord($record); + $data = $this->getFormatter()->format($record); + + if($data instanceof GelfMessage) { + $data = json_encode($data->toArray()); + } + + $this->exchange->batch_basic_publish( + $this->createAmqpMessage($data), + $this->exchangeName, + $this->getRoutingKey($record) + ); + } + + $this->exchange->publish_batch(); + } + + /** + * Gets the routing key for the AMQP exchange + */ + protected function getRoutingKey(LogRecord $record): string + { + $routingKey = sprintf('%s.%s', $record->level->name, $record->channel); + + return strtolower($routingKey); + } + + private function createAmqpMessage(string $data): AMQPMessage + { + $attributes = [ + 'delivery_mode' => 2, + 'content_type' => 'application/json', + ]; + if (\count($this->extraAttributes) > 0) { + $attributes = array_merge($attributes, $this->extraAttributes); + } + + return new AMQPMessage($data, $attributes); + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php new file mode 100644 index 0000000..6d8656b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php @@ -0,0 +1,300 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; +use Monolog\Utils; +use Monolog\LogRecord; +use Monolog\Level; + +use function headers_list; +use function stripos; + +/** + * Handler sending logs to browser's javascript console with no browser extension required + * + * @author Olivier Poitrey <rs@dailymotion.com> + */ +class BrowserConsoleHandler extends AbstractProcessingHandler +{ + protected static bool $initialized = false; + + /** @var LogRecord[] */ + protected static array $records = []; + + protected const FORMAT_HTML = 'html'; + protected const FORMAT_JS = 'js'; + protected const FORMAT_UNKNOWN = 'unknown'; + + /** + * @inheritDoc + * + * Formatted output may contain some formatting markers to be transferred to `console.log` using the %c format. + * + * Example of formatted string: + * + * You can do [[blue text]]{color: blue} or [[green background]]{background-color: green; color: white} + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter('[[%channel%]]{macro: autolabel} [[%level_name%]]{font-weight: bold} %message%'); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + // Accumulate records + static::$records[] = $record; + + // Register shutdown handler if not already done + if (!static::$initialized) { + static::$initialized = true; + $this->registerShutdownFunction(); + } + } + + /** + * Convert records to javascript console commands and send it to the browser. + * This method is automatically called on PHP shutdown if output is HTML or Javascript. + */ + public static function send(): void + { + $format = static::getResponseFormat(); + if ($format === self::FORMAT_UNKNOWN) { + return; + } + + if (\count(static::$records) > 0) { + if ($format === self::FORMAT_HTML) { + static::writeOutput('<script>' . self::generateScript() . '</script>'); + } else { // js format + static::writeOutput(self::generateScript()); + } + static::resetStatic(); + } + } + + public function close(): void + { + self::resetStatic(); + } + + public function reset(): void + { + parent::reset(); + + self::resetStatic(); + } + + /** + * Forget all logged records + */ + public static function resetStatic(): void + { + static::$records = []; + } + + /** + * Wrapper for register_shutdown_function to allow overriding + */ + protected function registerShutdownFunction(): void + { + if (PHP_SAPI !== 'cli') { + register_shutdown_function(['Monolog\Handler\BrowserConsoleHandler', 'send']); + } + } + + /** + * Wrapper for echo to allow overriding + */ + protected static function writeOutput(string $str): void + { + echo $str; + } + + /** + * Checks the format of the response + * + * If Content-Type is set to application/javascript or text/javascript -> js + * If Content-Type is set to text/html, or is unset -> html + * If Content-Type is anything else -> unknown + * + * @return string One of 'js', 'html' or 'unknown' + * @phpstan-return self::FORMAT_* + */ + protected static function getResponseFormat(): string + { + // Check content type + foreach (headers_list() as $header) { + if (stripos($header, 'content-type:') === 0) { + return static::getResponseFormatFromContentType($header); + } + } + + return self::FORMAT_HTML; + } + + /** + * @return string One of 'js', 'html' or 'unknown' + * @phpstan-return self::FORMAT_* + */ + protected static function getResponseFormatFromContentType(string $contentType): string + { + // This handler only works with HTML and javascript outputs + // text/javascript is obsolete in favour of application/javascript, but still used + if (stripos($contentType, 'application/javascript') !== false || stripos($contentType, 'text/javascript') !== false) { + return self::FORMAT_JS; + } + + if (stripos($contentType, 'text/html') !== false) { + return self::FORMAT_HTML; + } + + return self::FORMAT_UNKNOWN; + } + + private static function generateScript(): string + { + $script = []; + foreach (static::$records as $record) { + $context = self::dump('Context', $record->context); + $extra = self::dump('Extra', $record->extra); + + if (\count($context) === 0 && \count($extra) === 0) { + $script[] = self::call_array(self::getConsoleMethodForLevel($record->level), self::handleStyles($record->formatted)); + } else { + $script = array_merge( + $script, + [self::call_array('groupCollapsed', self::handleStyles($record->formatted))], + $context, + $extra, + [self::call('groupEnd')] + ); + } + } + + return "(function (c) {if (c && c.groupCollapsed) {\n" . implode("\n", $script) . "\n}})(console);"; + } + + private static function getConsoleMethodForLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'debug', + Level::Info, Level::Notice => 'info', + Level::Warning => 'warn', + Level::Error, Level::Critical, Level::Alert, Level::Emergency => 'error', + }; + } + + /** + * @return string[] + */ + private static function handleStyles(string $formatted): array + { + $args = []; + $format = '%c' . $formatted; + preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); + + foreach (array_reverse($matches) as $match) { + $args[] = '"font-weight: normal"'; + $args[] = self::quote(self::handleCustomStyles($match[2][0], $match[1][0])); + + $pos = $match[0][1]; + $format = Utils::substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . Utils::substr($format, $pos + \strlen($match[0][0])); + } + + $args[] = self::quote('font-weight: normal'); + $args[] = self::quote($format); + + return array_reverse($args); + } + + private static function handleCustomStyles(string $style, string $string): string + { + static $colors = ['blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey']; + static $labels = []; + + $style = preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function (array $m) use ($string, &$colors, &$labels) { + if (trim($m[1]) === 'autolabel') { + // Format the string as a label with consistent auto assigned background color + if (!isset($labels[$string])) { + $labels[$string] = $colors[\count($labels) % \count($colors)]; + } + $color = $labels[$string]; + + return "background-color: $color; color: white; border-radius: 3px; padding: 0 2px 0 2px"; + } + + return $m[1]; + }, $style); + + if (null === $style) { + $pcreErrorCode = preg_last_error(); + + throw new \RuntimeException('Failed to run preg_replace_callback: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); + } + + return $style; + } + + /** + * @param mixed[] $dict + * @return mixed[] + */ + private static function dump(string $title, array $dict): array + { + $script = []; + $dict = array_filter($dict, fn ($value) => $value !== null); + if (\count($dict) === 0) { + return $script; + } + $script[] = self::call('log', self::quote('%c%s'), self::quote('font-weight: bold'), self::quote($title)); + foreach ($dict as $key => $value) { + $value = Utils::jsonEncode($value, Utils::DEFAULT_JSON_FLAGS | JSON_HEX_TAG); + $script[] = self::call('log', self::quote('%s: %o'), self::quote((string) $key), $value); + } + + return $script; + } + + private static function quote(string $arg): string + { + // JSON_HEX_TAG keeps a literal < out of the output, so that a log message cannot break out + // of the surrounding <script> element via </script> or <!--<script>. json_encode also + // escapes \r and U+2028/U+2029, which would otherwise terminate the JS string literal. + return Utils::jsonEncode($arg, Utils::DEFAULT_JSON_FLAGS | JSON_HEX_TAG); + } + + /** + * @param mixed $args + */ + private static function call(...$args): string + { + $method = array_shift($args); + if (!\is_string($method)) { + throw new \UnexpectedValueException('Expected the first arg to be a string, got: '.var_export($method, true)); + } + + return self::call_array($method, $args); + } + + /** + * @param mixed[] $args + */ + private static function call_array(string $method, array $args): string + { + return 'c.' . $method . '(' . implode(', ', $args) . ');'; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php new file mode 100644 index 0000000..c799b6b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php @@ -0,0 +1,170 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Buffers all records until closing the handler and then pass them as batch. + * + * This is useful for a MailHandler to send only one mail per request instead of + * sending one per log message. + * + * @author Christophe Coevoet <stof@notk.org> + */ +class BufferHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + protected HandlerInterface $handler; + + protected int $bufferSize = 0; + + protected int $bufferLimit; + + protected bool $flushOnOverflow; + + /** @var LogRecord[] */ + protected array $buffer = []; + + protected bool $initialized = false; + + /** + * @param HandlerInterface $handler Handler. + * @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. + * @param bool $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded + */ + public function __construct(HandlerInterface $handler, int $bufferLimit = 0, int|string|Level $level = Level::Debug, bool $bubble = true, bool $flushOnOverflow = false) + { + parent::__construct($level, $bubble); + $this->handler = $handler; + $this->bufferLimit = $bufferLimit; + $this->flushOnOverflow = $flushOnOverflow; + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if ($record->level->isLowerThan($this->level)) { + return false; + } + + if (!$this->initialized) { + // __destructor() doesn't get called on Fatal errors + register_shutdown_function([$this, 'close']); + $this->initialized = true; + } + + if ($this->bufferLimit > 0 && $this->bufferSize === $this->bufferLimit) { + if ($this->flushOnOverflow) { + $this->flush(); + } else { + array_shift($this->buffer); + $this->bufferSize--; + } + } + + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + $this->buffer[] = $record; + $this->bufferSize++; + + return false === $this->bubble; + } + + public function flush(): void + { + if ($this->bufferSize === 0) { + return; + } + + $this->handler->handleBatch($this->buffer); + $this->clear(); + } + + public function __destruct() + { + // suppress the parent behavior since we already have register_shutdown_function() + // to call close(), and the reference contained there will prevent this from being + // GC'd until the end of the request + } + + /** + * @inheritDoc + */ + public function close(): void + { + $this->flush(); + + $this->handler->close(); + } + + /** + * Clears the buffer without flushing any messages down to the wrapped handler. + */ + public function clear(): void + { + $this->bufferSize = 0; + $this->buffer = []; + } + + public function reset(): void + { + $this->flush(); + + parent::reset(); + + $this->resetProcessors(); + + if ($this->handler instanceof ResettableInterface) { + $this->handler->reset(); + } + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + $this->handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($this->handler).' does not support formatters.'); + } + + /** + * @inheritDoc + */ + public function getFormatter(): FormatterInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + return $this->handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($this->handler).' does not support formatters.'); + } + + public function setHandler(HandlerInterface $handler): void + { + $this->handler = $handler; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php new file mode 100644 index 0000000..b714b23 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php @@ -0,0 +1,186 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\ChromePHPFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Level; +use Monolog\Utils; +use Monolog\LogRecord; +use Monolog\JsonSerializableDateTimeImmutable; + +/** + * Handler sending logs to the ChromePHP extension (http://www.chromephp.com/) + * + * This also works out of the box with Firefox 43+ + * + * @author Christophe Coevoet <stof@notk.org> + */ +class ChromePHPHandler extends AbstractProcessingHandler +{ + use WebRequestRecognizerTrait; + + /** + * Version of the extension + */ + protected const VERSION = '4.0'; + + /** + * Header name + */ + protected const HEADER_NAME = 'X-ChromeLogger-Data'; + + /** + * Regular expression to detect supported browsers (matches any Chrome, or Firefox 43+) + */ + protected const USER_AGENT_REGEX = '{\b(?:Chrome/\d+(?:\.\d+)*|HeadlessChrome|Firefox/(?:4[3-9]|[5-9]\d|\d{3,})(?:\.\d)*)\b}'; + + protected static bool $initialized = false; + + /** + * Tracks whether we sent too much data + * + * Chrome limits the headers to 4KB, so when we sent 3KB we stop sending + */ + protected static bool $overflowed = false; + + /** @var mixed[] */ + protected static array $json = [ + 'version' => self::VERSION, + 'columns' => ['label', 'log', 'backtrace', 'type'], + 'rows' => [], + ]; + + protected static bool $sendHeaders = true; + + public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) + { + parent::__construct($level, $bubble); + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + if (!$this->isWebRequest()) { + return; + } + + $messages = []; + + foreach ($records as $record) { + if ($record->level->isLowerThan($this->level)) { + continue; + } + + $message = $this->processRecord($record); + $messages[] = $message; + } + + if (\count($messages) > 0) { + $messages = $this->getFormatter()->formatBatch($messages); + self::$json['rows'] = array_merge(self::$json['rows'], $messages); + $this->send(); + } + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new ChromePHPFormatter(); + } + + /** + * Creates & sends header for a record + * + * @see sendHeader() + * @see send() + */ + protected function write(LogRecord $record): void + { + if (!$this->isWebRequest()) { + return; + } + + self::$json['rows'][] = $record->formatted; + + $this->send(); + } + + /** + * Sends the log header + * + * @see sendHeader() + */ + protected function send(): void + { + if (self::$overflowed || !self::$sendHeaders) { + return; + } + + if (!self::$initialized) { + self::$initialized = true; + + self::$sendHeaders = $this->headersAccepted(); + if (!self::$sendHeaders) { + return; + } + + self::$json['request_uri'] = $_SERVER['REQUEST_URI'] ?? ''; + } + + $json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true); + $data = base64_encode($json); + if (\strlen($data) > 3 * 1024) { + self::$overflowed = true; + + $record = new LogRecord( + message: 'Incomplete logs, chrome header size limit reached', + level: Level::Warning, + channel: 'monolog', + datetime: new JsonSerializableDateTimeImmutable(true), + ); + self::$json['rows'][\count(self::$json['rows']) - 1] = $this->getFormatter()->format($record); + $json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true); + $data = base64_encode($json); + } + + if (trim($data) !== '') { + $this->sendHeader(static::HEADER_NAME, $data); + } + } + + /** + * Send header string to the client + */ + protected function sendHeader(string $header, string $content): void + { + if (!headers_sent() && self::$sendHeaders) { + header(sprintf('%s: %s', $header, $content)); + } + } + + /** + * Verifies if the headers are accepted by the current user agent + */ + protected function headersAccepted(): bool + { + if (!isset($_SERVER['HTTP_USER_AGENT'])) { + return false; + } + + return preg_match(static::USER_AGENT_REGEX, $_SERVER['HTTP_USER_AGENT']) === 1; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php new file mode 100644 index 0000000..8d9c10e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php @@ -0,0 +1,97 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\JsonFormatter; +use Monolog\Level; +use Monolog\LogRecord; + +/** + * CouchDB handler + * + * @author Markus Bachmann <markus.bachmann@bachi.biz> + * @phpstan-type Options array{ + * host: string, + * port: int, + * dbname: string, + * username: string|null, + * password: string|null + * } + * @phpstan-type InputOptions array{ + * host?: string, + * port?: int, + * dbname?: string, + * username?: string|null, + * password?: string|null + * } + */ +class CouchDBHandler extends AbstractProcessingHandler +{ + /** + * @var mixed[] + * @phpstan-var Options + */ + private array $options; + + /** + * @param mixed[] $options + * + * @phpstan-param InputOptions $options + */ + public function __construct(array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) + { + $this->options = array_merge([ + 'host' => 'localhost', + 'port' => 5984, + 'dbname' => 'logger', + 'username' => null, + 'password' => null, + ], $options); + + parent::__construct($level, $bubble); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $basicAuth = null; + if (null !== $this->options['username'] && null !== $this->options['password']) { + $basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']); + } + + $url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname']; + $context = stream_context_create([ + 'http' => [ + 'method' => 'POST', + 'content' => $record->formatted, + 'ignore_errors' => true, + 'max_redirects' => 0, + 'header' => 'Content-type: application/json', + ], + ]); + + if (false === @file_get_contents($url, false, $context)) { + throw new \RuntimeException(sprintf('Could not connect to %s', $url)); + } + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php new file mode 100644 index 0000000..f9ebede --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php @@ -0,0 +1,167 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Logs to Cube. + * + * @link https://github.com/square/cube/wiki + * @author Wan Chen <kami@kamisama.me> + * @deprecated Since 2.8.0 and 3.2.0, Cube appears abandoned and thus we will drop this handler in Monolog 4 + */ +class CubeHandler extends AbstractProcessingHandler +{ + private ?\Socket $udpConnection = null; + private ?\CurlHandle $httpConnection = null; + private string $scheme; + private string $host; + private int $port; + /** @var string[] */ + private array $acceptedSchemes = ['http', 'udp']; + + /** + * Create a Cube handler + * + * @throws \UnexpectedValueException when given url is not a valid url. + * A valid url must consist of three parts : protocol://host:port + * Only valid protocols used by Cube are http and udp + */ + public function __construct(string $url, int|string|Level $level = Level::Debug, bool $bubble = true) + { + $urlInfo = parse_url($url); + + if ($urlInfo === false || !isset($urlInfo['scheme'], $urlInfo['host'], $urlInfo['port'])) { + throw new \UnexpectedValueException('URL "'.$url.'" is not valid'); + } + + if (!\in_array($urlInfo['scheme'], $this->acceptedSchemes, true)) { + throw new \UnexpectedValueException( + 'Invalid protocol (' . $urlInfo['scheme'] . ').' + . ' Valid options are ' . implode(', ', $this->acceptedSchemes) + ); + } + + $this->scheme = $urlInfo['scheme']; + $this->host = $urlInfo['host']; + $this->port = $urlInfo['port']; + + parent::__construct($level, $bubble); + } + + /** + * Establish a connection to an UDP socket + * + * @throws \LogicException when unable to connect to the socket + * @throws MissingExtensionException when there is no socket extension + */ + protected function connectUdp(): void + { + if (!\extension_loaded('sockets')) { + throw new MissingExtensionException('The sockets extension is required to use udp URLs with the CubeHandler'); + } + + $udpConnection = socket_create(AF_INET, SOCK_DGRAM, 0); + if (false === $udpConnection) { + throw new \LogicException('Unable to create a socket'); + } + + $this->udpConnection = $udpConnection; + if (!socket_connect($this->udpConnection, $this->host, $this->port)) { + throw new \LogicException('Unable to connect to the socket at ' . $this->host . ':' . $this->port); + } + } + + /** + * Establish a connection to an http server + * + * @throws \LogicException when unable to connect to the socket + * @throws MissingExtensionException when no curl extension + */ + protected function connectHttp(): void + { + if (!\extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is required to use http URLs with the CubeHandler'); + } + + $httpConnection = curl_init('http://'.$this->host.':'.$this->port.'/1.0/event/put'); + if (false === $httpConnection) { + throw new \LogicException('Unable to connect to ' . $this->host . ':' . $this->port); + } + + $this->httpConnection = $httpConnection; + curl_setopt($this->httpConnection, CURLOPT_CUSTOMREQUEST, "POST"); + curl_setopt($this->httpConnection, CURLOPT_RETURNTRANSFER, true); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $date = $record->datetime; + + $data = ['time' => $date->format('Y-m-d\TH:i:s.uO')]; + $context = $record->context; + + if (isset($context['type'])) { + $data['type'] = $context['type']; + unset($context['type']); + } else { + $data['type'] = $record->channel; + } + + $data['data'] = $context; + $data['data']['level'] = $record->level; + + if ($this->scheme === 'http') { + $this->writeHttp(Utils::jsonEncode($data)); + } else { + $this->writeUdp(Utils::jsonEncode($data)); + } + } + + private function writeUdp(string $data): void + { + if (null === $this->udpConnection) { + $this->connectUdp(); + } + + if (null === $this->udpConnection) { + throw new \LogicException('No UDP socket could be opened'); + } + + socket_send($this->udpConnection, $data, \strlen($data), 0); + } + + private function writeHttp(string $data): void + { + if (null === $this->httpConnection) { + $this->connectHttp(); + } + + if (null === $this->httpConnection) { + throw new \LogicException('No connection could be established'); + } + + curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']'); + curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, [ + 'Content-Type: application/json', + 'Content-Length: ' . \strlen('['.$data.']'), + ]); + + Curl\Util::execute($this->httpConnection, 5); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php b/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php new file mode 100644 index 0000000..2ef5887 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php @@ -0,0 +1,60 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\Curl; + +use CurlHandle; + +/** + * This class is marked as internal and it is not under the BC promise of the package. + * + * @internal + */ +final class Util +{ + /** @var array<int> */ + private static array $retriableErrorCodes = [ + CURLE_COULDNT_RESOLVE_HOST, + CURLE_COULDNT_CONNECT, + CURLE_HTTP_NOT_FOUND, + CURLE_READ_ERROR, + CURLE_OPERATION_TIMEOUTED, + CURLE_HTTP_POST_ERROR, + CURLE_SSL_CONNECT_ERROR, + ]; + + /** + * Executes a CURL request with optional retries and exception on failure + * + * @param CurlHandle $ch curl handler + * @return bool|string @see curl_exec + */ + public static function execute(CurlHandle $ch, int $retries = 5): bool|string + { + while ($retries > 0) { + $retries--; + $curlResponse = curl_exec($ch); + if ($curlResponse === false) { + $curlErrno = curl_errno($ch); + + if (false === \in_array($curlErrno, self::$retriableErrorCodes, true) || $retries === 0) { + $curlError = curl_error($ch); + + throw new \RuntimeException(sprintf('Curl error (code %d): %s', $curlErrno, $curlError)); + } + continue; + } + + return $curlResponse; + } + return false; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php new file mode 100644 index 0000000..f843a4d --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php @@ -0,0 +1,184 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Logger; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Simple handler wrapper that deduplicates log records across multiple requests + * + * It also includes the BufferHandler functionality and will buffer + * all messages until the end of the request or flush() is called. + * + * This works by storing all log records' messages above $deduplicationLevel + * to the file specified by $deduplicationStore. When further logs come in at the end of the + * request (or when flush() is called), all those above $deduplicationLevel are checked + * against the existing stored logs. If they match and the timestamps in the stored log is + * not older than $time seconds, the new log record is discarded. If no log record is new, the + * whole data set is discarded. + * + * This is mainly useful in combination with Mail handlers or things like Slack or HipChat handlers + * that send messages to people, to avoid spamming with the same message over and over in case of + * a major component failure like a database server being down which makes all requests fail in the + * same way. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class DeduplicationHandler extends BufferHandler +{ + protected string $deduplicationStore; + + protected Level $deduplicationLevel; + + protected int $time; + protected bool $gc = false; + + /** + * @param HandlerInterface $handler Handler. + * @param string|null $deduplicationStore The file/path where the deduplication log should be kept + * @param int|string|Level|LogLevel::* $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes + * @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $deduplicationLevel + */ + public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, int|string|Level $deduplicationLevel = Level::Error, int $time = 60, bool $bubble = true) + { + parent::__construct($handler, 0, Level::Debug, $bubble, false); + + $this->deduplicationStore = $deduplicationStore === null ? sys_get_temp_dir() . '/monolog-dedup-' . substr(md5(__FILE__), 0, 20) .'.log' : $deduplicationStore; + $this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel); + $this->time = $time; + } + + public function flush(): void + { + if ($this->bufferSize === 0) { + return; + } + + $store = null; + + if (file_exists($this->deduplicationStore)) { + $store = file($this->deduplicationStore, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + } + + $passthru = null; + + foreach ($this->buffer as $record) { + if ($record->level->value >= $this->deduplicationLevel->value) { + $passthru = $passthru === true || !\is_array($store) || !$this->isDuplicate($store, $record); + if ($passthru) { + $line = $this->buildDeduplicationStoreEntry($record); + file_put_contents($this->deduplicationStore, $line . "\n", FILE_APPEND | LOCK_EX); + if (!\is_array($store)) { + $store = []; + } + $store[] = $line; + } + } + } + + // default of null is valid as well as if no record matches duplicationLevel we just pass through + if ($passthru === true || $passthru === null) { + $this->handler->handleBatch($this->buffer); + } + + $this->clear(); + + if ($this->gc) { + $this->collectLogs(); + } + } + + /** + * If there is a store entry older than e.g. a day, this method should set `$this->gc` to `true` to trigger garbage collection. + * @param string[] $store The deduplication store + */ + protected function isDuplicate(array $store, LogRecord $record): bool + { + $timestampValidity = $record->datetime->getTimestamp() - $this->time; + $expectedMessage = preg_replace('{[\r\n].*}', '', $record->message); + $yesterday = time() - 86400; + + for ($i = \count($store) - 1; $i >= 0; $i--) { + $parts = explode(':', $store[$i], 3); + + if (\count($parts) < 3) { + // Skip invalid/incomplete lines (e.g. partially written due to concurrent access) + continue; + } + + [$timestamp, $level, $message] = $parts; + + if ($level === $record->level->getName() && $message === $expectedMessage && $timestamp > $timestampValidity) { + return true; + } + + if ($timestamp < $yesterday) { + $this->gc = true; + } + } + + return false; + } + + /** + * @return string The given record serialized as a single line of text + */ + protected function buildDeduplicationStoreEntry(LogRecord $record): string + { + return $record->datetime->getTimestamp() . ':' . $record->level->getName() . ':' . preg_replace('{[\r\n].*}', '', $record->message); + } + + private function collectLogs(): void + { + if (!file_exists($this->deduplicationStore)) { + return; + } + + $handle = fopen($this->deduplicationStore, 'rw+'); + + if (false === $handle) { + throw new \RuntimeException('Failed to open file for reading and writing: ' . $this->deduplicationStore); + } + + if (false === flock($handle, LOCK_EX)) { + fclose($handle); + return; + } + $validLogs = []; + + $timestampValidity = time() - $this->time; + + while (!feof($handle)) { + $log = fgets($handle); + if (\is_string($log) && '' !== $log && substr($log, 0, 10) >= $timestampValidity) { + $validLogs[] = $log; + } + } + + ftruncate($handle, 0); + rewind($handle); + foreach ($validLogs as $log) { + fwrite($handle, $log); + } + + flock($handle, LOCK_UN); + fclose($handle); + + $this->gc = false; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php new file mode 100644 index 0000000..eab9f10 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php @@ -0,0 +1,47 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Formatter\FormatterInterface; +use Doctrine\CouchDB\CouchDBClient; +use Monolog\LogRecord; + +/** + * CouchDB handler for Doctrine CouchDB ODM + * + * @author Markus Bachmann <markus.bachmann@bachi.biz> + */ +class DoctrineCouchDBHandler extends AbstractProcessingHandler +{ + private CouchDBClient $client; + + public function __construct(CouchDBClient $client, int|string|Level $level = Level::Debug, bool $bubble = true) + { + $this->client = $client; + parent::__construct($level, $bubble); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->client->postDocument($record->formatted); + } + + protected function getDefaultFormatter(): FormatterInterface + { + return new NormalizerFormatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php new file mode 100644 index 0000000..f1c5a95 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php @@ -0,0 +1,80 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Aws\Sdk; +use Aws\DynamoDb\DynamoDbClient; +use Monolog\Formatter\FormatterInterface; +use Aws\DynamoDb\Marshaler; +use Monolog\Formatter\ScalarFormatter; +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Amazon DynamoDB handler (http://aws.amazon.com/dynamodb/) + * + * @link https://github.com/aws/aws-sdk-php/ + * @author Andrew Lawson <adlawson@gmail.com> + */ +class DynamoDbHandler extends AbstractProcessingHandler +{ + public const DATE_FORMAT = 'Y-m-d\TH:i:s.uO'; + + protected DynamoDbClient $client; + + protected string $table; + + protected Marshaler $marshaler; + + public function __construct(DynamoDbClient $client, string $table, int|string|Level $level = Level::Debug, bool $bubble = true) + { + $this->marshaler = new Marshaler; + + $this->client = $client; + $this->table = $table; + + parent::__construct($level, $bubble); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $filtered = $this->filterEmptyFields($record->formatted); + $formatted = $this->marshaler->marshalItem($filtered); + + $this->client->putItem([ + 'TableName' => $this->table, + 'Item' => $formatted, + ]); + } + + /** + * @param mixed[] $record + * @return mixed[] + */ + protected function filterEmptyFields(array $record): array + { + return array_filter($record, function ($value) { + return [] !== $value; + }); + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new ScalarFormatter(self::DATE_FORMAT); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php new file mode 100644 index 0000000..93cf4e0 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php @@ -0,0 +1,144 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Elastic\Transport\Exception\TransportException; +use Elastica\Document; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\ElasticaFormatter; +use Monolog\Level; +use Elastica\Client; +use Elastica\Exception\ExceptionInterface; +use Monolog\LogRecord; +use Monolog\Utils; + +/** + * Elastic Search handler + * + * Usage example: + * + * $client = new \Elastica\Client(); + * $options = array( + * 'index' => 'elastic_index_name', + * 'type' => 'elastic_doc_type', Types have been removed in Elastica 7 + * ); + * $handler = new ElasticaHandler($client, $options); + * $log = new Logger('application'); + * $log->pushHandler($handler); + * + * @author Jelle Vink <jelle.vink@gmail.com> + * @phpstan-type Options array{ + * index: string, + * type: string, + * ignore_error: bool + * } + * @phpstan-type InputOptions array{ + * index?: string, + * type?: string, + * ignore_error?: bool + * } + */ +class ElasticaHandler extends AbstractProcessingHandler +{ + protected Client $client; + + /** + * @var mixed[] Handler config options + * @phpstan-var Options + */ + protected array $options; + + /** + * @param Client $client Elastica Client object + * @param mixed[] $options Handler configuration + * + * @phpstan-param InputOptions $options + */ + public function __construct(Client $client, array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) + { + parent::__construct($level, $bubble); + $this->client = $client; + $this->options = array_merge( + [ + 'index' => 'monolog', // Elastic index name + 'type' => 'record', // Elastic document type + 'ignore_error' => false, // Suppress Elastica exceptions + ], + $options + ); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->bulkSend([$record->formatted]); + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if (Utils::unwrapFormatter($formatter) instanceof ElasticaFormatter) { + return parent::setFormatter($formatter); + } + + throw new \InvalidArgumentException('ElasticaHandler is only compatible with ElasticaFormatter'); + } + + /** + * @return mixed[] + * + * @phpstan-return Options + */ + public function getOptions(): array + { + return $this->options; + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new ElasticaFormatter($this->options['index'], $this->options['type']); + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + $documents = $this->getFormatter()->formatBatch($records); + $this->bulkSend($documents); + } + + /** + * Use Elasticsearch bulk API to send list of documents + * + * @param Document[] $documents + * + * @throws \RuntimeException + */ + protected function bulkSend(array $documents): void + { + try { + $this->client->addDocuments($documents); + } catch (ExceptionInterface | TransportException $e) { + if (!$this->options['ignore_error']) { + throw new \RuntimeException("Error sending messages to Elasticsearch", 0, $e); + } + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php new file mode 100644 index 0000000..b3128c4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php @@ -0,0 +1,239 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Elastic\Elasticsearch\Response\Elasticsearch; +use Throwable; +use RuntimeException; +use Monolog\Level; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\ElasticsearchFormatter; +use InvalidArgumentException; +use Elasticsearch\Common\Exceptions\RuntimeException as ElasticsearchRuntimeException; +use Elasticsearch\Client; +use Monolog\LogRecord; +use Monolog\Utils; +use Elastic\Elasticsearch\Exception\InvalidArgumentException as ElasticInvalidArgumentException; +use Elastic\Elasticsearch\Client as Client8; + +/** + * Elasticsearch handler + * + * @link https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html + * + * Simple usage example: + * + * $client = \Elasticsearch\ClientBuilder::create() + * ->setHosts($hosts) + * ->build(); + * + * $options = array( + * 'index' => 'elastic_index_name', + * 'type' => 'elastic_doc_type', + * ); + * $handler = new ElasticsearchHandler($client, $options); + * $log = new Logger('application'); + * $log->pushHandler($handler); + * + * @author Avtandil Kikabidze <akalongman@gmail.com> + * @phpstan-type Options array{ + * index: string, + * type: string, + * ignore_error: bool, + * op_type: 'index'|'create' + * } + * @phpstan-type InputOptions array{ + * index?: string, + * type?: string, + * ignore_error?: bool, + * op_type?: 'index'|'create' + * } + */ +class ElasticsearchHandler extends AbstractProcessingHandler +{ + protected Client|Client8 $client; + + /** + * @var mixed[] Handler config options + * @phpstan-var Options + */ + protected array $options; + + /** + * @var bool + */ + private $needsType; + + /** + * @param Client|Client8 $client Elasticsearch Client object + * @param mixed[] $options Handler configuration + * + * @phpstan-param InputOptions $options + */ + public function __construct(Client|Client8 $client, array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) + { + parent::__construct($level, $bubble); + $this->client = $client; + $this->options = array_merge( + [ + 'index' => 'monolog', // Elastic index name + 'type' => '_doc', // Elastic document type + 'ignore_error' => false, // Suppress Elasticsearch exceptions + 'op_type' => 'index', // Elastic op_type (index or create) (https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#docs-index-api-op_type) + ], + $options + ); + + if ($client instanceof Client8 || $client::VERSION[0] === '7') { + $this->needsType = false; + // force the type to _doc for ES8/ES7 + $this->options['type'] = '_doc'; + } else { + $this->needsType = true; + } + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->bulkSend([$record->formatted]); + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if (Utils::unwrapFormatter($formatter) instanceof ElasticsearchFormatter) { + return parent::setFormatter($formatter); + } + + throw new InvalidArgumentException('ElasticsearchHandler is only compatible with ElasticsearchFormatter'); + } + + /** + * Getter options + * + * @return mixed[] + * + * @phpstan-return Options + */ + public function getOptions(): array + { + return $this->options; + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new ElasticsearchFormatter($this->options['index'], $this->options['type']); + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + $documents = $this->getFormatter()->formatBatch($records); + $this->bulkSend($documents); + } + + /** + * Use Elasticsearch bulk API to send list of documents + * + * @param array<array<mixed>> $records Records + _index/_type keys + * @throws \RuntimeException + */ + protected function bulkSend(array $records): void + { + try { + $params = [ + 'body' => [], + ]; + + foreach ($records as $record) { + $params['body'][] = [ + $this->options['op_type'] => $this->needsType ? [ + '_index' => $record['_index'], + '_type' => $record['_type'], + ] : [ + '_index' => $record['_index'], + ], + ]; + unset($record['_index'], $record['_type']); + + $params['body'][] = $record; + } + + /** @var Elasticsearch */ + $responses = $this->client->bulk($params); + + if ($responses['errors'] === true) { + throw $this->createExceptionFromResponses($responses); + } + } catch (Throwable $e) { + if (! $this->options['ignore_error']) { + throw new RuntimeException('Error sending messages to Elasticsearch', 0, $e); + } + } + } + + /** + * Creates elasticsearch exception from responses array + * + * Only the first error is converted into an exception. + * + * @param mixed[]|Elasticsearch $responses returned by $this->client->bulk() + */ + protected function createExceptionFromResponses($responses): Throwable + { + foreach ($responses['items'] ?? [] as $item) { + if (isset($item['index']['error'])) { + return $this->createExceptionFromError($item['index']['error']); + } + } + + if (class_exists(ElasticInvalidArgumentException::class)) { + return new ElasticInvalidArgumentException('Elasticsearch failed to index one or more records.'); + } + + if (class_exists(ElasticsearchRuntimeException::class)) { + return new ElasticsearchRuntimeException('Elasticsearch failed to index one or more records.'); + } + + throw new \LogicException('Unsupported elastic search client version'); + } + + /** + * Creates elasticsearch exception from error array + * + * @param mixed[] $error + */ + protected function createExceptionFromError(array $error): Throwable + { + $previous = isset($error['caused_by']) ? $this->createExceptionFromError($error['caused_by']) : null; + + if (class_exists(ElasticInvalidArgumentException::class)) { + return new ElasticInvalidArgumentException($error['type'] . ': ' . $error['reason'], 0, $previous); + } + + if (class_exists(ElasticsearchRuntimeException::class)) { + return new ElasticsearchRuntimeException($error['type'].': '.$error['reason'], 0, $previous); + } + + throw new \LogicException('Unsupported elastic search client version'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php new file mode 100644 index 0000000..a7e7186 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php @@ -0,0 +1,93 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Stores to PHP error_log() handler. + * + * @author Elan Ruusamäe <glen@delfi.ee> + */ +class ErrorLogHandler extends AbstractProcessingHandler +{ + public const OPERATING_SYSTEM = 0; + public const SAPI = 4; + + /** @var 0|4 */ + protected int $messageType; + protected bool $expandNewlines; + + /** + * @param 0|4 $messageType Says where the error should go. + * @param bool $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries + * + * @throws \InvalidArgumentException If an unsupported message type is set + */ + public function __construct(int $messageType = self::OPERATING_SYSTEM, int|string|Level $level = Level::Debug, bool $bubble = true, bool $expandNewlines = false) + { + parent::__construct($level, $bubble); + + if (false === \in_array($messageType, self::getAvailableTypes(), true)) { + $message = sprintf('The given message type "%s" is not supported', print_r($messageType, true)); + + throw new \InvalidArgumentException($message); + } + + $this->messageType = $messageType; + $this->expandNewlines = $expandNewlines; + } + + /** + * @return int[] With all available types + */ + public static function getAvailableTypes(): array + { + return [ + self::OPERATING_SYSTEM, + self::SAPI, + ]; + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter('[%datetime%] %channel%.%level_name%: %message% %context% %extra%'); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + if (!$this->expandNewlines) { + error_log((string) $record->formatted, $this->messageType); + + return; + } + + $lines = preg_split('{[\r\n]+}', (string) $record->formatted); + if ($lines === false) { + $pcreErrorCode = preg_last_error(); + + throw new \RuntimeException('Failed to preg_split formatted string: ' . $pcreErrorCode . ' / '. preg_last_error_msg()); + } + foreach ($lines as $line) { + error_log($line, $this->messageType); + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php new file mode 100644 index 0000000..58318be --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php @@ -0,0 +1,68 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Throwable; +use Monolog\LogRecord; + +/** + * Forwards records to at most one handler + * + * If a handler fails, the exception is suppressed and the record is forwarded to the next handler. + * + * As soon as one handler handles a record successfully, the handling stops there. + */ +class FallbackGroupHandler extends GroupHandler +{ + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + foreach ($this->handlers as $handler) { + try { + $handler->handle(clone $record); + break; + } catch (Throwable $e) { + // What throwable? + } + } + + return false === $this->bubble; + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + if (\count($this->processors) > 0) { + $processed = []; + foreach ($records as $record) { + $processed[] = $this->processRecord($record); + } + $records = $processed; + } + + foreach ($this->handlers as $handler) { + try { + $handler->handleBatch(array_map(fn ($record) => clone $record, $records)); + break; + } catch (Throwable $e) { + // What throwable? + } + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php new file mode 100644 index 0000000..4b2b1f6 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php @@ -0,0 +1,202 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Closure; +use Monolog\Level; +use Monolog\Logger; +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Simple handler wrapper that filters records based on a list of levels + * + * It can be configured with an exact list of levels to allow, or a min/max level. + * + * @author Hennadiy Verkh + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class FilterHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + /** + * Handler or factory Closure($record, $this) + * + * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface + */ + protected Closure|HandlerInterface $handler; + + /** + * Minimum level for logs that are passed to handler + * + * @var bool[] Map of Level value => true + * @phpstan-var array<value-of<Level::VALUES>, true> + */ + protected array $acceptedLevels; + + /** + * Whether the messages that are handled can bubble up the stack or not + */ + protected bool $bubble; + + /** + * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler + * + * @param Closure|HandlerInterface $handler Handler or factory Closure($record|null, $filterHandler). + * @param int|string|Level|array<int|string|Level|LogLevel::*> $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided + * @param int|string|Level|LogLevel::* $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::*|array<value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::*> $minLevelOrList + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $maxLevel + */ + public function __construct(Closure|HandlerInterface $handler, int|string|Level|array $minLevelOrList = Level::Debug, int|string|Level $maxLevel = Level::Emergency, bool $bubble = true) + { + $this->handler = $handler; + $this->bubble = $bubble; + $this->setAcceptedLevels($minLevelOrList, $maxLevel); + } + + /** + * @phpstan-return list<Level> List of levels + */ + public function getAcceptedLevels(): array + { + return array_map(fn (int $level) => Level::from($level), array_keys($this->acceptedLevels)); + } + + /** + * @param int|string|Level|LogLevel::*|array<int|string|Level|LogLevel::*> $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided + * @param int|string|Level|LogLevel::* $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array + * @return $this + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::*|array<value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::*> $minLevelOrList + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $maxLevel + */ + public function setAcceptedLevels(int|string|Level|array $minLevelOrList = Level::Debug, int|string|Level $maxLevel = Level::Emergency): self + { + if (\is_array($minLevelOrList)) { + $acceptedLevels = array_map(Logger::toMonologLevel(...), $minLevelOrList); + } else { + $minLevelOrList = Logger::toMonologLevel($minLevelOrList); + $maxLevel = Logger::toMonologLevel($maxLevel); + $acceptedLevels = array_values(array_filter(Level::cases(), fn (Level $level) => $level->value >= $minLevelOrList->value && $level->value <= $maxLevel->value)); + } + $this->acceptedLevels = []; + foreach ($acceptedLevels as $level) { + $this->acceptedLevels[$level->value] = true; + } + + return $this; + } + + /** + * @inheritDoc + */ + public function isHandling(LogRecord $record): bool + { + return isset($this->acceptedLevels[$record->level->value]); + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if (!$this->isHandling($record)) { + return false; + } + + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + $this->getHandler($record)->handle($record); + + return false === $this->bubble; + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + $filtered = []; + foreach ($records as $record) { + if ($this->isHandling($record)) { + $filtered[] = \count($this->processors) > 0 ? $this->processRecord($record) : $record; + } + } + + if (\count($filtered) > 0) { + $this->getHandler($filtered[\count($filtered) - 1])->handleBatch($filtered); + } + } + + /** + * Return the nested handler + * + * If the handler was provided as a factory, this will trigger the handler's instantiation. + */ + public function getHandler(LogRecord|null $record = null): HandlerInterface + { + if (!$this->handler instanceof HandlerInterface) { + $handler = ($this->handler)($record, $this); + if (!$handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory Closure should return a HandlerInterface"); + } + $this->handler = $handler; + } + + return $this->handler; + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.'); + } + + /** + * @inheritDoc + */ + public function getFormatter(): FormatterInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + return $handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.'); + } + + public function reset(): void + { + $this->resetProcessors(); + + if ($this->getHandler() instanceof ResettableInterface) { + $this->getHandler()->reset(); + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php new file mode 100644 index 0000000..e8a1b0b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php @@ -0,0 +1,27 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +use Monolog\LogRecord; + +/** + * Interface for activation strategies for the FingersCrossedHandler. + * + * @author Johannes M. Schmitt <schmittjoh@gmail.com> + */ +interface ActivationStrategyInterface +{ + /** + * Returns whether the given record activates the handler. + */ + public function isHandlerActivated(LogRecord $record): bool; +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php new file mode 100644 index 0000000..383e19a --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php @@ -0,0 +1,69 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +use Monolog\Level; +use Monolog\Logger; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Channel and Error level based monolog activation strategy. Allows to trigger activation + * based on level per channel. e.g. trigger activation on level 'ERROR' by default, except + * for records of the 'sql' channel; those should trigger activation on level 'WARN'. + * + * Example: + * + * <code> + * $activationStrategy = new ChannelLevelActivationStrategy( + * Level::Critical, + * array( + * 'request' => Level::Alert, + * 'sensitive' => Level::Error, + * ) + * ); + * $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy); + * </code> + * + * @author Mike Meessen <netmikey@gmail.com> + */ +class ChannelLevelActivationStrategy implements ActivationStrategyInterface +{ + private Level $defaultActionLevel; + + /** + * @var array<string, Level> + */ + private array $channelToActionLevel; + + /** + * @param int|string|Level|LogLevel::* $defaultActionLevel The default action level to be used if the record's category doesn't match any + * @param array<string, int|string|Level|LogLevel::*> $channelToActionLevel An array that maps channel names to action levels. + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $defaultActionLevel + * @phpstan-param array<string, value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::*> $channelToActionLevel + */ + public function __construct(int|string|Level $defaultActionLevel, array $channelToActionLevel = []) + { + $this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel); + $this->channelToActionLevel = array_map(Logger::toMonologLevel(...), $channelToActionLevel); + } + + public function isHandlerActivated(LogRecord $record): bool + { + if (isset($this->channelToActionLevel[$record->channel])) { + return $record->level->value >= $this->channelToActionLevel[$record->channel]->value; + } + + return $record->level->value >= $this->defaultActionLevel->value; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php new file mode 100644 index 0000000..c3ca296 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php @@ -0,0 +1,42 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +use Monolog\Level; +use Monolog\LogRecord; +use Monolog\Logger; +use Psr\Log\LogLevel; + +/** + * Error level based activation strategy. + * + * @author Johannes M. Schmitt <schmittjoh@gmail.com> + */ +class ErrorLevelActivationStrategy implements ActivationStrategyInterface +{ + private Level $actionLevel; + + /** + * @param int|string|Level $actionLevel Level or name or value + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $actionLevel + */ + public function __construct(int|string|Level $actionLevel) + { + $this->actionLevel = Logger::toMonologLevel($actionLevel); + } + + public function isHandlerActivated(LogRecord $record): bool + { + return $record->level->value >= $this->actionLevel->value; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php new file mode 100644 index 0000000..1ce64e8 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php @@ -0,0 +1,242 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Closure; +use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; +use Monolog\Handler\FingersCrossed\ActivationStrategyInterface; +use Monolog\Level; +use Monolog\Logger; +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Buffers all records until a certain level is reached + * + * The advantage of this approach is that you don't get any clutter in your log files. + * Only requests which actually trigger an error (or whatever your actionLevel is) will be + * in the logs, but they will contain all records, not only those above the level threshold. + * + * You can then have a passthruLevel as well which means that at the end of the request, + * even if it did not get activated, it will still send through log records of e.g. at least a + * warning level. + * + * You can find the various activation strategies in the + * Monolog\Handler\FingersCrossed\ namespace. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class FingersCrossedHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + /** + * Handler or factory Closure($record, $this) + * + * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface + */ + protected Closure|HandlerInterface $handler; + + protected ActivationStrategyInterface $activationStrategy; + + protected bool $buffering = true; + + protected int $bufferSize; + + /** @var LogRecord[] */ + protected array $buffer = []; + + protected bool $stopBuffering; + + protected Level|null $passthruLevel = null; + + protected bool $bubble; + + /** + * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler + * + * @param Closure|HandlerInterface $handler Handler or factory Closure($record|null, $fingersCrossedHandler). + * @param int|string|Level|LogLevel::*|null $activationStrategy Strategy which determines when this handler takes action, or a level name/value at which the handler is activated + * @param int $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param bool $stopBuffering Whether the handler should stop buffering after being triggered (default true) + * @param int|string|Level|LogLevel::*|null $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::*|ActivationStrategyInterface|null $activationStrategy + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::*|null $passthruLevel + */ + public function __construct(Closure|HandlerInterface $handler, int|string|Level|ActivationStrategyInterface|null $activationStrategy = null, int $bufferSize = 0, bool $bubble = true, bool $stopBuffering = true, int|string|Level|null $passthruLevel = null) + { + if (null === $activationStrategy) { + $activationStrategy = new ErrorLevelActivationStrategy(Level::Warning); + } + + // convert simple int activationStrategy to an object + if (!$activationStrategy instanceof ActivationStrategyInterface) { + $activationStrategy = new ErrorLevelActivationStrategy($activationStrategy); + } + + $this->handler = $handler; + $this->activationStrategy = $activationStrategy; + $this->bufferSize = $bufferSize; + $this->bubble = $bubble; + $this->stopBuffering = $stopBuffering; + + if ($passthruLevel !== null) { + $this->passthruLevel = Logger::toMonologLevel($passthruLevel); + } + } + + /** + * @inheritDoc + */ + public function isHandling(LogRecord $record): bool + { + return true; + } + + /** + * Manually activate this logger regardless of the activation strategy + */ + public function activate(): void + { + if ($this->stopBuffering) { + $this->buffering = false; + } + + $this->getHandler(end($this->buffer) ?: null)->handleBatch($this->buffer); + $this->buffer = []; + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + if ($this->buffering) { + $this->buffer[] = $record; + if ($this->bufferSize > 0 && \count($this->buffer) > $this->bufferSize) { + array_shift($this->buffer); + } + if ($this->activationStrategy->isHandlerActivated($record)) { + $this->activate(); + } + } else { + $this->getHandler($record)->handle($record); + } + + return false === $this->bubble; + } + + /** + * @inheritDoc + */ + public function close(): void + { + $this->flushBuffer(); + + $this->getHandler()->close(); + } + + public function reset(): void + { + $this->flushBuffer(); + + $this->resetProcessors(); + + if ($this->getHandler() instanceof ResettableInterface) { + $this->getHandler()->reset(); + } + } + + /** + * Clears the buffer without flushing any messages down to the wrapped handler. + * + * It also resets the handler to its initial buffering state. + */ + public function clear(): void + { + $this->buffer = []; + $this->reset(); + } + + /** + * Resets the state of the handler. Stops forwarding records to the wrapped handler. + */ + private function flushBuffer(): void + { + if (null !== $this->passthruLevel) { + $passthruLevel = $this->passthruLevel; + $this->buffer = array_filter($this->buffer, static function ($record) use ($passthruLevel) { + return $passthruLevel->includes($record->level); + }); + if (\count($this->buffer) > 0) { + $this->getHandler(end($this->buffer))->handleBatch($this->buffer); + } + } + + $this->buffer = []; + $this->buffering = true; + } + + /** + * Return the nested handler + * + * If the handler was provided as a factory, this will trigger the handler's instantiation. + */ + public function getHandler(LogRecord|null $record = null): HandlerInterface + { + if (!$this->handler instanceof HandlerInterface) { + $handler = ($this->handler)($record, $this); + if (!$handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory Closure should return a HandlerInterface"); + } + $this->handler = $handler; + } + + return $this->handler; + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.'); + } + + /** + * @inheritDoc + */ + public function getFormatter(): FormatterInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + return $handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php new file mode 100644 index 0000000..6b9e510 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php @@ -0,0 +1,174 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\WildfireFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Simple FirePHP Handler (http://www.firephp.org/), which uses the Wildfire protocol. + * + * @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com> + */ +class FirePHPHandler extends AbstractProcessingHandler +{ + use WebRequestRecognizerTrait; + + /** + * WildFire JSON header message format + */ + protected const PROTOCOL_URI = 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2'; + + /** + * FirePHP structure for parsing messages & their presentation + */ + protected const STRUCTURE_URI = 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1'; + + /** + * Must reference a "known" plugin, otherwise headers won't display in FirePHP + */ + protected const PLUGIN_URI = 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3'; + + /** + * Header prefix for Wildfire to recognize & parse headers + */ + protected const HEADER_PREFIX = 'X-Wf'; + + /** + * Whether or not Wildfire vendor-specific headers have been generated & sent yet + */ + protected static bool $initialized = false; + + /** + * Shared static message index between potentially multiple handlers + */ + protected static int $messageIndex = 1; + + protected static bool $sendHeaders = true; + + /** + * Base header creation function used by init headers & record headers + * + * @param array<int|string> $meta Wildfire Plugin, Protocol & Structure Indexes + * @param string $message Log message + * + * @return array<string, string> Complete header string ready for the client as key and message as value + * + * @phpstan-return non-empty-array<string, string> + */ + protected function createHeader(array $meta, string $message): array + { + $header = sprintf('%s-%s', static::HEADER_PREFIX, join('-', $meta)); + + return [$header => $message]; + } + + /** + * Creates message header from record + * + * @return array<string, string> + * + * @phpstan-return non-empty-array<string, string> + * + * @see createHeader() + */ + protected function createRecordHeader(LogRecord $record): array + { + // Wildfire is extensible to support multiple protocols & plugins in a single request, + // but we're not taking advantage of that (yet), so we're using "1" for simplicity's sake. + return $this->createHeader( + [1, 1, 1, self::$messageIndex++], + $record->formatted + ); + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new WildfireFormatter(); + } + + /** + * Wildfire initialization headers to enable message parsing + * + * @see createHeader() + * @see sendHeader() + * + * @return array<string, string> + */ + protected function getInitHeaders(): array + { + // Initial payload consists of required headers for Wildfire + return array_merge( + $this->createHeader(['Protocol', 1], static::PROTOCOL_URI), + $this->createHeader([1, 'Structure', 1], static::STRUCTURE_URI), + $this->createHeader([1, 'Plugin', 1], static::PLUGIN_URI) + ); + } + + /** + * Send header string to the client + */ + protected function sendHeader(string $header, string $content): void + { + if (!headers_sent() && self::$sendHeaders) { + header(sprintf('%s: %s', $header, $content)); + } + } + + /** + * Creates & sends header for a record, ensuring init headers have been sent prior + * + * @see sendHeader() + * @see sendInitHeaders() + */ + protected function write(LogRecord $record): void + { + if (!self::$sendHeaders || !$this->isWebRequest()) { + return; + } + + // WildFire-specific headers must be sent prior to any messages + if (!self::$initialized) { + self::$initialized = true; + + self::$sendHeaders = $this->headersAccepted(); + if (!self::$sendHeaders) { + return; + } + + foreach ($this->getInitHeaders() as $header => $content) { + $this->sendHeader($header, $content); + } + } + + $header = $this->createRecordHeader($record); + if (trim(current($header)) !== '') { + $this->sendHeader(key($header), current($header)); + } + } + + /** + * Verifies if the headers are accepted by the current user agent + */ + protected function headersAccepted(): bool + { + if (isset($_SERVER['HTTP_USER_AGENT']) && 1 === preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) { + return true; + } + + return isset($_SERVER['HTTP_X_FIREPHP_VERSION']); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php new file mode 100644 index 0000000..46ebfc0 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php @@ -0,0 +1,132 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Sends logs to Fleep.io using Webhook integrations + * + * You'll need a Fleep.io account to use this handler. + * + * @see https://fleep.io/integrations/webhooks/ Fleep Webhooks Documentation + * @author Ando Roots <ando@sqroot.eu> + */ +class FleepHookHandler extends SocketHandler +{ + protected const FLEEP_HOST = 'fleep.io'; + + protected const FLEEP_HOOK_URI = '/hook/'; + + /** + * @var string Webhook token (specifies the conversation where logs are sent) + */ + protected string $token; + + /** + * Construct a new Fleep.io Handler. + * + * For instructions on how to create a new web hook in your conversations + * see https://fleep.io/integrations/webhooks/ + * + * @param string $token Webhook token + * @throws MissingExtensionException if OpenSSL is missing + */ + public function __construct( + string $token, + $level = Level::Debug, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if (!\extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler'); + } + + $this->token = $token; + + $connectionString = 'ssl://' . static::FLEEP_HOST . ':443'; + parent::__construct( + $connectionString, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + } + + /** + * Returns the default formatter to use with this handler + * + * Overloaded to remove empty context and extra arrays from the end of the log message. + * + * @return LineFormatter + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter(null, null, true, true); + } + + /** + * Handles a log record + */ + public function write(LogRecord $record): void + { + parent::write($record); + $this->closeSocket(); + } + + /** + * @inheritDoc + */ + protected function generateDataStream(LogRecord $record): string + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the header of the API Call + */ + private function buildHeader(string $content): string + { + $header = "POST " . static::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n"; + $header .= "Host: " . static::FLEEP_HOST . "\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . \strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + /** + * Builds the body of API call + */ + private function buildContent(LogRecord $record): string + { + $dataArray = [ + 'message' => $record->formatted, + ]; + + return http_build_query($dataArray); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php new file mode 100644 index 0000000..60cd4e2 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php @@ -0,0 +1,127 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Utils; +use Monolog\Formatter\FlowdockFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Sends notifications through the Flowdock push API + * + * This must be configured with a FlowdockFormatter instance via setFormatter() + * + * Notes: + * API token - Flowdock API token + * + * @author Dominik Liebler <liebler.dominik@gmail.com> + * @see https://www.flowdock.com/api/push + * @deprecated Since 2.9.0 and 3.3.0, Flowdock was shutdown we will thus drop this handler in Monolog 4 + */ +class FlowdockHandler extends SocketHandler +{ + protected string $apiToken; + + /** + * @throws MissingExtensionException if OpenSSL is missing + */ + public function __construct( + string $apiToken, + $level = Level::Debug, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if (!\extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler'); + } + + parent::__construct( + 'ssl://api.flowdock.com:443', + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + $this->apiToken = $apiToken; + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if (!Utils::unwrapFormatter($formatter) instanceof FlowdockFormatter) { + throw new \InvalidArgumentException('The FlowdockHandler requires an instance of Monolog\Formatter\FlowdockFormatter to function correctly'); + } + + return parent::setFormatter($formatter); + } + + /** + * Gets the default formatter. + */ + protected function getDefaultFormatter(): FormatterInterface + { + throw new \InvalidArgumentException('The FlowdockHandler must be configured (via setFormatter) with an instance of Monolog\Formatter\FlowdockFormatter to function correctly'); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + parent::write($record); + + $this->closeSocket(); + } + + /** + * @inheritDoc + */ + protected function generateDataStream(LogRecord $record): string + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the body of API call + */ + private function buildContent(LogRecord $record): string + { + return Utils::jsonEncode($record->formatted); + } + + /** + * Builds the header of the API Call + */ + private function buildHeader(string $content): string + { + $header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n"; + $header .= "Host: api.flowdock.com\r\n"; + $header .= "Content-Type: application/json\r\n"; + $header .= "Content-Length: " . \strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php new file mode 100644 index 0000000..72da59e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php @@ -0,0 +1,34 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; + +/** + * Interface to describe loggers that have a formatter + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +interface FormattableHandlerInterface +{ + /** + * Sets the formatter. + * + * @return HandlerInterface self + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface; + + /** + * Gets the formatter. + */ + public function getFormatter(): FormatterInterface; +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php b/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php new file mode 100644 index 0000000..c044e07 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php @@ -0,0 +1,57 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; + +/** + * Helper trait for implementing FormattableInterface + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +trait FormattableHandlerTrait +{ + protected FormatterInterface|null $formatter = null; + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $this->formatter = $formatter; + + return $this; + } + + /** + * @inheritDoc + */ + public function getFormatter(): FormatterInterface + { + if (null === $this->formatter) { + $this->formatter = $this->getDefaultFormatter(); + } + + return $this->formatter; + } + + /** + * Gets the default formatter. + * + * Overwrite this if the LineFormatter is not a good default for your handler. + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FrankenPhpHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FrankenPhpHandler.php new file mode 100644 index 0000000..621bae6 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FrankenPhpHandler.php @@ -0,0 +1,100 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Logs records using FrankenPHP's frankenphp_log() function. + * + * This handler requires a NormalizerFormatter to function and expects an array in $record->formatted + * + * @see https://frankenphp.dev/docs/logging/#frankenphp_log + * + * @author Kévin Dunglas <kevin@dunglas.dev> + */ +class FrankenPhpHandler extends AbstractProcessingHandler +{ + /** + * @throws MissingExtensionException If frankenphp_log() is not available + */ + public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) + { + if (!\function_exists('frankenphp_log')) { + throw new MissingExtensionException( + 'You must run this handler under FrankenPHP, the frankenphp_log() function is not available' + ); + } + + parent::__construct($level, $bubble); + } + + /** + * Translates Monolog log levels to FrankenPHP's slog-based levels. + * + * slog's docs state its gap of 4 between named levels matches OpenTelemetry's SeverityNumber + * mapping, converted by subtracting 9. Applying that same subtraction to OpenTelemetry's own + * Syslog severity mapping for the 4 extra RFC 5424 levels slog has no constant for keeps this + * scale traceable to that spec instead of an arbitrary choice. + * + * FrankenPHP feeds these through zapslog, which buckets everything >= Error into "error", so + * above Error only the level_name context key tells the Monolog levels apart. + * + * @see https://pkg.go.dev/log/slog#hdr-Levels + * @see https://opentelemetry.io/docs/specs/otel/logs/data-model-appendix/ + */ + protected function toFrankenPhpLevel(Level $level): int + { + return match ($level) { + Level::Debug => \FRANKENPHP_LOG_LEVEL_DEBUG, + Level::Info => \FRANKENPHP_LOG_LEVEL_INFO, + Level::Notice => 1, + Level::Warning => \FRANKENPHP_LOG_LEVEL_WARN, + Level::Error => \FRANKENPHP_LOG_LEVEL_ERROR, + Level::Critical => 9, + Level::Alert => 10, + Level::Emergency => 12, + }; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->writeFrankenPhpLog($record->message, $this->toFrankenPhpLevel($record->level), $record->formatted); + } + + /** + * @param array<mixed> $context Displayed as structured attributes alongside the message + */ + protected function writeFrankenPhpLog(string $message, int $level, array $context): void + { + // frankenphp_log() merges $context into the same JSON object it already fills with "msg", + // "level" and "ts", so drop Monolog's duplicates of those three. level_name still carries + // the Monolog level name, which slog's own severity cannot express. + unset($context['message'], $context['level'], $context['datetime']); + + \frankenphp_log($message, $level, $context); + } + + /** + * @inheritDoc + */ + public function getDefaultFormatter(): FormatterInterface + { + return new NormalizerFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php new file mode 100644 index 0000000..ba5bb97 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php @@ -0,0 +1,58 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Gelf\PublisherInterface; +use Monolog\Level; +use Monolog\Formatter\GelfMessageFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Handler to send messages to a Graylog2 (http://www.graylog2.org) server + * + * @author Matt Lehner <mlehner@gmail.com> + * @author Benjamin Zikarsky <benjamin@zikarsky.de> + */ +class GelfHandler extends AbstractProcessingHandler +{ + /** + * @var PublisherInterface the publisher object that sends the message to the server + */ + protected PublisherInterface $publisher; + + /** + * @param PublisherInterface $publisher a gelf publisher object + */ + public function __construct(PublisherInterface $publisher, int|string|Level $level = Level::Debug, bool $bubble = true) + { + parent::__construct($level, $bubble); + + $this->publisher = $publisher; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->publisher->publish($record->formatted); + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new GelfMessageFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php new file mode 100644 index 0000000..0423dc3 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php @@ -0,0 +1,130 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\ResettableInterface; +use Monolog\LogRecord; + +/** + * Forwards records to multiple handlers + * + * @author Lenar Lõhmus <lenar@city.ee> + */ +class GroupHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface +{ + use ProcessableHandlerTrait; + + /** @var HandlerInterface[] */ + protected array $handlers; + protected bool $bubble; + + /** + * @param HandlerInterface[] $handlers Array of Handlers. + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @throws \InvalidArgumentException if an unsupported handler is set + */ + public function __construct(array $handlers, bool $bubble = true) + { + foreach ($handlers as $handler) { + if (!$handler instanceof HandlerInterface) { + throw new \InvalidArgumentException('The first argument of the GroupHandler must be an array of HandlerInterface instances.'); + } + } + + $this->handlers = $handlers; + $this->bubble = $bubble; + } + + /** + * @inheritDoc + */ + public function isHandling(LogRecord $record): bool + { + foreach ($this->handlers as $handler) { + if ($handler->isHandling($record)) { + return true; + } + } + + return false; + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + foreach ($this->handlers as $handler) { + $handler->handle(clone $record); + } + + return false === $this->bubble; + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + if (\count($this->processors) > 0) { + $processed = []; + foreach ($records as $record) { + $processed[] = $this->processRecord($record); + } + $records = $processed; + } + + foreach ($this->handlers as $handler) { + $handler->handleBatch(array_map(fn ($record) => clone $record, $records)); + } + } + + public function reset(): void + { + $this->resetProcessors(); + + foreach ($this->handlers as $handler) { + if ($handler instanceof ResettableInterface) { + $handler->reset(); + } + } + } + + public function close(): void + { + parent::close(); + + foreach ($this->handlers as $handler) { + $handler->close(); + } + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + foreach ($this->handlers as $handler) { + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + } + } + + return $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/Handler.php b/vendor/monolog/monolog/src/Monolog/Handler/Handler.php new file mode 100644 index 0000000..8a4e7ab --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/Handler.php @@ -0,0 +1,53 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Base Handler class providing basic close() support as well as handleBatch + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +abstract class Handler implements HandlerInterface +{ + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + foreach ($records as $record) { + $this->handle($record); + } + } + + /** + * @inheritDoc + */ + public function close(): void + { + } + + public function __destruct() + { + try { + $this->close(); + } catch (\Throwable $e) { + // do nothing + } + } + + public function __serialize(): array + { + $this->close(); + + return (array) $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php new file mode 100644 index 0000000..93306d9 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php @@ -0,0 +1,76 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\LogRecord; + +/** + * Interface that all Monolog Handlers must implement + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +interface HandlerInterface +{ + /** + * Checks whether the given record will be handled by this handler. + * + * This is mostly done for performance reasons, to avoid calling processors for nothing. + * + * Handlers should still check the record levels within handle(), returning false in isHandling() + * is no guarantee that handle() will not be called, and isHandling() might not be called + * for a given record. + * + * @param LogRecord $record Partial log record having only a level initialized + */ + public function isHandling(LogRecord $record): bool; + + /** + * Handles a record. + * + * All records may be passed to this method, and the handler should discard + * those that it does not want to handle. + * + * The return value of this function controls the bubbling process of the handler stack. + * Unless the bubbling is interrupted (by returning true), the Logger class will keep on + * calling further handlers in the stack with a given log record. + * + * @param LogRecord $record The record to handle + * @return bool true means that this handler handled the record, and that bubbling is not permitted. + * false means the record was either not processed or that this handler allows bubbling. + */ + public function handle(LogRecord $record): bool; + + /** + * Handles a set of records at once. + * + * @param array<LogRecord> $records The records to handle + */ + public function handleBatch(array $records): void; + + /** + * Closes the handler. + * + * Ends a log cycle and frees all resources used by the handler. + * + * Closing a Handler means flushing all buffers and freeing any open resources/handles. + * + * Implementations have to be idempotent (i.e. it should be possible to call close several times without breakage) + * and ideally handlers should be able to reopen themselves on handle() after they have been closed. + * + * This is useful at the end of a request and will be called automatically when the object + * is destroyed if you extend Monolog\Handler\Handler. + * + * If you are thinking of calling this method yourself, most likely you should be + * calling ResettableInterface::reset instead. Have a look. + */ + public function close(): void; +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php b/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php new file mode 100644 index 0000000..541ec25 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php @@ -0,0 +1,134 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * This simple wrapper class can be used to extend handlers functionality. + * + * Example: A custom filtering that can be applied to any handler. + * + * Inherit from this class and override handle() like this: + * + * public function handle(LogRecord $record) + * { + * if ($record meets certain conditions) { + * return false; + * } + * return $this->handler->handle($record); + * } + * + * @author Alexey Karapetov <alexey@karapetov.com> + */ +class HandlerWrapper implements HandlerInterface, ProcessableHandlerInterface, FormattableHandlerInterface, ResettableInterface +{ + protected HandlerInterface $handler; + + public function __construct(HandlerInterface $handler) + { + $this->handler = $handler; + } + + /** + * @inheritDoc + */ + public function isHandling(LogRecord $record): bool + { + return $this->handler->isHandling($record); + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + return $this->handler->handle($record); + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + $this->handler->handleBatch($records); + } + + /** + * @inheritDoc + */ + public function close(): void + { + $this->handler->close(); + } + + /** + * @inheritDoc + */ + public function pushProcessor(callable $callback): HandlerInterface + { + if ($this->handler instanceof ProcessableHandlerInterface) { + $this->handler->pushProcessor($callback); + + return $this; + } + + throw new \LogicException('The wrapped handler does not implement ' . ProcessableHandlerInterface::class); + } + + /** + * @inheritDoc + */ + public function popProcessor(): callable + { + if ($this->handler instanceof ProcessableHandlerInterface) { + return $this->handler->popProcessor(); + } + + throw new \LogicException('The wrapped handler does not implement ' . ProcessableHandlerInterface::class); + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + $this->handler->setFormatter($formatter); + + return $this; + } + + throw new \LogicException('The wrapped handler does not implement ' . FormattableHandlerInterface::class); + } + + /** + * @inheritDoc + */ + public function getFormatter(): FormatterInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + return $this->handler->getFormatter(); + } + + throw new \LogicException('The wrapped handler does not implement ' . FormattableHandlerInterface::class); + } + + public function reset(): void + { + if ($this->handler instanceof ResettableInterface) { + $this->handler->reset(); + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php new file mode 100644 index 0000000..b9c7ba8 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php @@ -0,0 +1,75 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * IFTTTHandler uses cURL to trigger IFTTT Maker actions + * + * Register a secret key and trigger/event name at https://ifttt.com/maker + * + * value1 will be the channel from monolog's Logger constructor, + * value2 will be the level name (ERROR, WARNING, ..) + * value3 will be the log record's message + * + * @author Nehal Patel <nehal@nehalpatel.me> + */ +class IFTTTHandler extends AbstractProcessingHandler +{ + private string $eventName; + private string $secretKey; + + /** + * @param string $eventName The name of the IFTTT Maker event that should be triggered + * @param string $secretKey A valid IFTTT secret key + * + * @throws MissingExtensionException If the curl extension is missing + */ + public function __construct(string $eventName, string $secretKey, int|string|Level $level = Level::Error, bool $bubble = true) + { + if (!\extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler'); + } + + $this->eventName = $eventName; + $this->secretKey = $secretKey; + + parent::__construct($level, $bubble); + } + + /** + * @inheritDoc + */ + public function write(LogRecord $record): void + { + $postData = [ + "value1" => $record->channel, + "value2" => $record["level_name"], + "value3" => $record->message, + ]; + $postString = Utils::jsonEncode($postData); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, "https://maker.ifttt.com/trigger/" . $this->eventName . "/with/key/" . $this->secretKey); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postString); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/json", + ]); + + Curl\Util::execute($ch); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php new file mode 100644 index 0000000..4b558bd --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php @@ -0,0 +1,74 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Inspired on LogEntriesHandler. + * + * @author Robert Kaufmann III <rok3@rok3.me> + * @author Gabriel Machado <gabriel.ms1@hotmail.com> + */ +class InsightOpsHandler extends SocketHandler +{ + protected string $logToken; + + /** + * @param string $token Log token supplied by InsightOps + * @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'. + * @param bool $useSSL Whether or not SSL encryption should be used + * + * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing + */ + public function __construct( + string $token, + string $region = 'us', + bool $useSSL = true, + $level = Level::Debug, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if ($useSSL && !\extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for InsightOpsHandler'); + } + + $endpoint = $useSSL + ? 'ssl://' . $region . '.data.logs.insight.rapid7.com:443' + : $region . '.data.logs.insight.rapid7.com:80'; + + parent::__construct( + $endpoint, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + $this->logToken = $token; + } + + /** + * @inheritDoc + */ + protected function generateDataStream(LogRecord $record): string + { + return $this->logToken . ' ' . $record->formatted; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php new file mode 100644 index 0000000..8c12898 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php @@ -0,0 +1,68 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\LogRecord; + +/** + * @author Robert Kaufmann III <rok3@rok3.me> + */ +class LogEntriesHandler extends SocketHandler +{ + protected string $logToken; + + /** + * @param string $token Log token supplied by LogEntries + * @param bool $useSSL Whether or not SSL encryption should be used. + * @param string $host Custom hostname to send the data to if needed + * + * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing + */ + public function __construct( + string $token, + bool $useSSL = true, + $level = Level::Debug, + bool $bubble = true, + string $host = 'data.logentries.com', + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if ($useSSL && !\extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler'); + } + + $endpoint = $useSSL ? 'ssl://' . $host . ':443' : $host . ':80'; + parent::__construct( + $endpoint, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + $this->logToken = $token; + } + + /** + * @inheritDoc + */ + protected function generateDataStream(LogRecord $record): string + { + return $this->logToken . ' ' . $record->formatted; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogMonsterHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogMonsterHandler.php new file mode 100644 index 0000000..0c78df4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogMonsterHandler.php @@ -0,0 +1,192 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Closure; +use Monolog\Level; +use Monolog\Logger; +use Monolog\ResettableInterface; +use Monolog\Formatter\FormatterInterface; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Watches log records go by and expects to be fed at least $hunger of them before + * the process ends. If it stays hungry until close() (and was not manually fed()), + * the monster gets angry and emits a complaint record at $angerLevel to the nested + * handler. Useful as a dead-man's switch for cron jobs / workers that should produce + * a known amount of log activity before they finish, or to make sure that every code + * path / request in the application at least logs some amount of records. + * + * Records carrying context are "cookies with chocolate chips" — when $wantsContextChips + * is true, only records with non-empty context count toward feeding the monster. + * + * Thanks to Jonathan Wage for the idea https://x.com/seldaek/status/1491110384023277569 + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class LogMonsterHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + /** + * Handler or factory Closure($record, $this) + * + * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface + */ + protected Closure|HandlerInterface $handler; + + protected int $hunger; + + protected Level $angerLevel; + + protected string $channel; + + protected bool $wantsContextChips; + + /** Number of records the monster has eaten so far */ + protected int $eaten = 0; + + /** Whether the monster has been manually fed and should stay quiet on close */ + protected bool $fed = false; + + /** + * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler + * + * @param Closure|HandlerInterface $handler Handler or factory Closure($record|null, $logMonsterHandler). + * @param int $hunger Number of log records the monster must eat before close() to stay satisfied. + * @param int|string|Level|LogLevel::* $angerLevel Level at which the monster logs its complaint when it goes hungry. + * @param string $channel Channel name stamped on the synthetic complaint record, note the record only gets sent to the given $handler, and will for example not go to the handlers configured for $channel in Symfony. + * @param bool $wantsContextChips If true, only records carrying context count toward feeding the monster. + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $angerLevel + */ + public function __construct(Closure|HandlerInterface $handler, int $hunger, int|string|Level $angerLevel = Level::Error, string $channel = 'log-monster', bool $wantsContextChips = false) + { + $this->handler = $handler; + $this->hunger = $hunger; + $this->channel = $channel; + $this->wantsContextChips = $wantsContextChips; + $this->angerLevel = Logger::toMonologLevel($angerLevel); + } + + /** + * @inheritDoc + */ + public function isHandling(LogRecord $record): bool + { + return true; + } + + /** + * Manually feed the log monster so it does not complain on close (until reset() is called) + */ + public function feed(): void + { + $this->fed = true; + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if (!$this->wantsContextChips || \count($record->context) > 0) { + $this->eaten++; + } + + // the monster only watches records go by, it never consumes them + return false; + } + + /** + * @inheritDoc + */ + public function close(): void + { + if (!$this->fed && $this->eaten < $this->hunger) { + $record = new LogRecord( + datetime: new \DateTimeImmutable('now'), + channel: $this->channel, + level: $this->angerLevel, + message: 'Om nom nom... the log monster is hangry: it only ate '.$this->eaten.' of '.$this->hunger.' expected log records', + context: ['eaten' => $this->eaten, 'hunger' => $this->hunger], + ); + + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + $this->getHandler($record)->handle($record); + } + + $this->getHandler()->close(); + } + + public function reset(): void + { + $this->fed = false; + $this->eaten = 0; + + $this->resetProcessors(); + + if ($this->getHandler() instanceof ResettableInterface) { + $this->getHandler()->reset(); + } + } + + /** + * Return the nested handler + * + * If the handler was provided as a factory, this will trigger the handler's instantiation. + */ + public function getHandler(?LogRecord $record = null): HandlerInterface + { + if (!$this->handler instanceof HandlerInterface) { + $handler = ($this->handler)($record, $this); + if (!$handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory Closure should return a HandlerInterface"); + } + $this->handler = $handler; + } + + return $this->handler; + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.'); + } + + /** + * @inheritDoc + */ + public function getFormatter(): FormatterInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + return $handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php new file mode 100644 index 0000000..c1ccc0e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php @@ -0,0 +1,156 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LogglyFormatter; +use CurlHandle; +use Monolog\LogRecord; + +/** + * Sends errors to Loggly. + * + * @author Przemek Sobstel <przemek@sobstel.org> + * @author Adam Pancutt <adam@pancutt.com> + * @author Gregory Barchard <gregory@barchard.net> + */ +class LogglyHandler extends AbstractProcessingHandler +{ + protected const HOST = 'logs-01.loggly.com'; + protected const ENDPOINT_SINGLE = 'inputs'; + protected const ENDPOINT_BATCH = 'bulk'; + + /** + * Caches the curl handlers for every given endpoint. + * + * @var CurlHandle[] + */ + protected array $curlHandlers = []; + + protected string $token; + + /** @var string[] */ + protected array $tag = []; + + /** + * @param string $token API token supplied by Loggly + * + * @throws MissingExtensionException If the curl extension is missing + */ + public function __construct(string $token, int|string|Level $level = Level::Debug, bool $bubble = true) + { + if (!\extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler'); + } + + $this->token = $token; + + parent::__construct($level, $bubble); + } + + /** + * Loads and returns the shared curl handler for the given endpoint. + */ + protected function getCurlHandler(string $endpoint): CurlHandle + { + if (!\array_key_exists($endpoint, $this->curlHandlers)) { + $this->curlHandlers[$endpoint] = $this->loadCurlHandle($endpoint); + } + + return $this->curlHandlers[$endpoint]; + } + + /** + * Starts a fresh curl session for the given endpoint and returns its handler. + */ + private function loadCurlHandle(string $endpoint): CurlHandle + { + $url = sprintf("https://%s/%s/%s/", static::HOST, $endpoint, $this->token); + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + return $ch; + } + + /** + * @param string[]|string $tag + * @return $this + */ + public function setTag(string|array $tag): self + { + if ('' === $tag || [] === $tag) { + $this->tag = []; + } else { + $this->tag = \is_array($tag) ? $tag : [$tag]; + } + + return $this; + } + + /** + * @param string[]|string $tag + * @return $this + */ + public function addTag(string|array $tag): self + { + if ('' !== $tag) { + $tag = \is_array($tag) ? $tag : [$tag]; + $this->tag = array_unique(array_merge($this->tag, $tag)); + } + + return $this; + } + + protected function write(LogRecord $record): void + { + $this->send($record->formatted, static::ENDPOINT_SINGLE); + } + + public function handleBatch(array $records): void + { + $level = $this->level; + + $records = array_filter($records, function ($record) use ($level) { + return ($record->level->value >= $level->value); + }); + + if (\count($records) > 0) { + $this->send($this->getFormatter()->formatBatch($records), static::ENDPOINT_BATCH); + } + } + + protected function send(string $data, string $endpoint): void + { + $ch = $this->getCurlHandler($endpoint); + + $headers = ['Content-Type: application/json']; + + if (\count($this->tag) > 0) { + $headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag); + } + + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + + Curl\Util::execute($ch, 5); + } + + protected function getDefaultFormatter(): FormatterInterface + { + return new LogglyFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php new file mode 100644 index 0000000..6aa1b31 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php @@ -0,0 +1,98 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LogmaticFormatter; +use Monolog\LogRecord; + +/** + * @author Julien Breux <julien.breux@gmail.com> + */ +class LogmaticHandler extends SocketHandler +{ + private string $logToken; + + private string $hostname; + + private string $appName; + + /** + * @param string $token Log token supplied by Logmatic. + * @param string $hostname Host name supplied by Logmatic. + * @param string $appName Application name supplied by Logmatic. + * @param bool $useSSL Whether or not SSL encryption should be used. + * + * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing + */ + public function __construct( + string $token, + string $hostname = '', + string $appName = '', + bool $useSSL = true, + $level = Level::Debug, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if ($useSSL && !\extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use SSL encrypted connection for LogmaticHandler'); + } + + $endpoint = $useSSL ? 'ssl://api.logmatic.io:10515' : 'api.logmatic.io:10514'; + $endpoint .= '/v1/'; + + parent::__construct( + $endpoint, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + + $this->logToken = $token; + $this->hostname = $hostname; + $this->appName = $appName; + } + + /** + * @inheritDoc + */ + protected function generateDataStream(LogRecord $record): string + { + return $this->logToken . ' ' . $record->formatted; + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + $formatter = new LogmaticFormatter(); + + if ($this->hostname !== '') { + $formatter->setHostname($this->hostname); + } + if ($this->appName !== '') { + $formatter->setAppName($this->appName); + } + + return $formatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php new file mode 100644 index 0000000..b6c8227 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php @@ -0,0 +1,91 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\HtmlFormatter; +use Monolog\LogRecord; + +/** + * Base class for all mail handlers + * + * @author Gyula Sallai + */ +abstract class MailHandler extends AbstractProcessingHandler +{ + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + $messages = []; + + foreach ($records as $record) { + if ($record->level->isLowerThan($this->level)) { + continue; + } + + $message = $this->processRecord($record); + $messages[] = $message; + } + + if (\count($messages) > 0) { + $this->send((string) $this->getFormatter()->formatBatch($messages), $messages); + } + } + + /** + * Send a mail with the given content + * + * @param string $content formatted email body to be sent + * @param array $records the array of log records that formed this content + * + * @phpstan-param non-empty-array<LogRecord> $records + */ + abstract protected function send(string $content, array $records): void; + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->send((string) $record->formatted, [$record]); + } + + /** + * @phpstan-param non-empty-array<LogRecord> $records + */ + protected function getHighestRecord(array $records): LogRecord + { + $highestRecord = null; + foreach ($records as $record) { + if ($highestRecord === null || $record->level->isHigherThan($highestRecord->level)) { + $highestRecord = $record; + } + } + + return $highestRecord; + } + + protected function isHtmlBody(string $body): bool + { + return ($body[0] ?? null) === '<'; + } + + /** + * Gets the default formatter. + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new HtmlFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php new file mode 100644 index 0000000..477ac34 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php @@ -0,0 +1,83 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Swift; +use Swift_Message; + +/** + * MandrillHandler uses cURL to send the emails to the Mandrill API + * + * @author Adam Nicholson <adamnicholson10@gmail.com> + */ +class MandrillHandler extends MailHandler +{ + protected Swift_Message $message; + protected string $apiKey; + + /** + * @phpstan-param (Swift_Message|callable(): Swift_Message) $message + * + * @param string $apiKey A valid Mandrill API key + * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced + * + * @throws \InvalidArgumentException if not a Swift Message is set + */ + public function __construct(string $apiKey, callable|Swift_Message $message, int|string|Level $level = Level::Error, bool $bubble = true) + { + parent::__construct($level, $bubble); + + if (!$message instanceof Swift_Message) { + $message = $message(); + } + if (!$message instanceof Swift_Message) { + throw new \InvalidArgumentException('You must provide either a Swift_Message instance or a callable returning it'); + } + $this->message = $message; + $this->apiKey = $apiKey; + } + + /** + * @inheritDoc + */ + protected function send(string $content, array $records): void + { + $mime = 'text/plain'; + if ($this->isHtmlBody($content)) { + $mime = 'text/html'; + } + + $message = clone $this->message; + $message->setBody($content, $mime); + /** @phpstan-ignore-next-line */ + if (version_compare(Swift::VERSION, '6.0.0', '>=')) { + $message->setDate(new \DateTimeImmutable()); + } else { + /** @phpstan-ignore-next-line */ + $message->setDate(time()); + } + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json'); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ + 'key' => $this->apiKey, + 'raw_message' => (string) $message, + 'async' => false, + ])); + + Curl\Util::execute($ch); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php b/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php new file mode 100644 index 0000000..3965aee --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php @@ -0,0 +1,21 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Exception can be thrown if an extension for a handler is missing + * + * @author Christian Bergau <cbergau86@gmail.com> + */ +class MissingExtensionException extends \Exception +{ +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php new file mode 100644 index 0000000..3a1c085 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php @@ -0,0 +1,83 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use MongoDB\Client; +use MongoDB\Collection; +use MongoDB\Driver\BulkWrite; +use MongoDB\Driver\Manager; +use Monolog\Level; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\MongoDBFormatter; +use Monolog\LogRecord; + +/** + * Logs to a MongoDB database. + * + * Usage example: + * + * $log = new \Monolog\Logger('application'); + * $client = new \MongoDB\Client('mongodb://localhost:27017'); + * $mongodb = new \Monolog\Handler\MongoDBHandler($client, 'logs', 'prod'); + * $log->pushHandler($mongodb); + * + * The above examples uses the MongoDB PHP library's client class; however, the + * MongoDB\Driver\Manager class from ext-mongodb is also supported. + */ +class MongoDBHandler extends AbstractProcessingHandler +{ + private Collection $collection; + + private Client|Manager $manager; + + private string|null $namespace = null; + + /** + * Constructor. + * + * @param Client|Manager $mongodb MongoDB library or driver client + * @param string $database Database name + * @param string $collection Collection name + */ + public function __construct(Client|Manager $mongodb, string $database, string $collection, int|string|Level $level = Level::Debug, bool $bubble = true) + { + if ($mongodb instanceof Client) { + $this->collection = method_exists($mongodb, 'getCollection') ? $mongodb->getCollection($database, $collection) : $mongodb->selectCollection($database, $collection); + } else { + $this->manager = $mongodb; + $this->namespace = $database . '.' . $collection; + } + + parent::__construct($level, $bubble); + } + + protected function write(LogRecord $record): void + { + if (isset($this->collection)) { + $this->collection->insertOne($record->formatted); + } + + if (isset($this->manager, $this->namespace)) { + $bulk = new BulkWrite; + $bulk->insert($record->formatted); + $this->manager->executeBulkWrite($this->namespace, $bulk); + } + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new MongoDBFormatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php new file mode 100644 index 0000000..a5d1a97 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php @@ -0,0 +1,179 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Formatter\LineFormatter; + +/** + * NativeMailerHandler uses the mail() function to send the emails + * + * @author Christophe Coevoet <stof@notk.org> + * @author Mark Garrett <mark@moderndeveloperllc.com> + */ +class NativeMailerHandler extends MailHandler +{ + /** + * The email addresses to which the message will be sent + * @var string[] + */ + protected array $to; + + /** + * The subject of the email + */ + protected string $subject; + + /** + * Optional headers for the message + * @var string[] + */ + protected array $headers = []; + + /** + * Optional parameters for the message + * @var string[] + */ + protected array $parameters = []; + + /** + * The wordwrap length for the message + */ + protected int $maxColumnWidth; + + /** + * The Content-type for the message + */ + protected string|null $contentType = null; + + /** + * The encoding for the message + */ + protected string $encoding = 'utf-8'; + + /** + * @param string|string[] $to The receiver of the mail + * @param string $subject The subject of the mail + * @param string $from The sender of the mail + * @param int $maxColumnWidth The maximum column width that the message lines will have + */ + public function __construct(string|array $to, string $subject, string $from, int|string|Level $level = Level::Error, bool $bubble = true, int $maxColumnWidth = 70) + { + parent::__construct($level, $bubble); + $this->to = (array) $to; + $this->subject = $subject; + $this->addHeader(sprintf('From: %s', $from)); + $this->maxColumnWidth = $maxColumnWidth; + } + + /** + * Add headers to the message + * + * @param string|string[] $headers Custom added headers + * @return $this + */ + public function addHeader($headers): self + { + foreach ((array) $headers as $header) { + if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) { + throw new \InvalidArgumentException('Headers can not contain newline characters for security reasons'); + } + $this->headers[] = $header; + } + + return $this; + } + + /** + * Add parameters to the message + * + * @param string|string[] $parameters Custom added parameters + * @return $this + */ + public function addParameter($parameters): self + { + $this->parameters = array_merge($this->parameters, (array) $parameters); + + return $this; + } + + /** + * @inheritDoc + */ + protected function send(string $content, array $records): void + { + $contentType = $this->getContentType() ?? ($this->isHtmlBody($content) ? 'text/html' : 'text/plain'); + + if ($contentType !== 'text/html') { + $content = wordwrap($content, $this->maxColumnWidth); + } + + $headers = ltrim(implode("\r\n", $this->headers) . "\r\n", "\r\n"); + $headers .= 'Content-type: ' . $contentType . '; charset=' . $this->getEncoding() . "\r\n"; + if ($contentType === 'text/html' && false === strpos($headers, 'MIME-Version:')) { + $headers .= 'MIME-Version: 1.0' . "\r\n"; + } + + $subjectFormatter = new LineFormatter($this->subject); + $subject = $subjectFormatter->format($this->getHighestRecord($records)); + + $parameters = implode(' ', $this->parameters); + foreach ($this->to as $to) { + $this->mail($to, $subject, $content, $headers, $parameters); + } + } + + public function getContentType(): ?string + { + return $this->contentType; + } + + public function getEncoding(): string + { + return $this->encoding; + } + + /** + * @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML messages. + * @return $this + */ + public function setContentType(string $contentType): self + { + if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) { + throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection'); + } + + $this->contentType = $contentType; + + return $this; + } + + /** + * @return $this + */ + public function setEncoding(string $encoding): self + { + if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) { + throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection'); + } + + $this->encoding = $encoding; + + return $this; + } + + + protected function mail(string $to, string $subject, string $content, string $headers, string $parameters): void + { + mail($to, $subject, $content, $headers, $parameters); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php new file mode 100644 index 0000000..4f28dd4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php @@ -0,0 +1,180 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Utils; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Class to record a log on a NewRelic application. + * Enabling New Relic High Security mode may prevent capture of useful information. + * + * This handler requires a NormalizerFormatter to function and expects an array in $record->formatted + * + * @see https://docs.newrelic.com/docs/agents/php-agent + * @see https://docs.newrelic.com/docs/accounts-partnerships/accounts/security/high-security + */ +class NewRelicHandler extends AbstractProcessingHandler +{ + /** + * @inheritDoc + */ + public function __construct( + int|string|Level $level = Level::Error, + bool $bubble = true, + + /** + * Name of the New Relic application that will receive logs from this handler. + */ + protected string|null $appName = null, + + /** + * Some context and extra data is passed into the handler as arrays of values. Do we send them as is + * (useful if we are using the API), or explode them for display on the NewRelic RPM website? + */ + protected bool $explodeArrays = false, + + /** + * Name of the current transaction + */ + protected string|null $transactionName = null + ) { + parent::__construct($level, $bubble); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + if (!$this->isNewRelicEnabled()) { + throw new MissingExtensionException('The newrelic PHP extension is required to use the NewRelicHandler'); + } + + if (null !== ($appName = $this->getAppName($record->context))) { + $this->setNewRelicAppName($appName); + } + + if (null !== ($transactionName = $this->getTransactionName($record->context))) { + $this->setNewRelicTransactionName($transactionName); + unset($record->formatted['context']['transaction_name']); + } + + if (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) { + newrelic_notice_error($record->message, $record->context['exception']); + unset($record->formatted['context']['exception']); + } else { + newrelic_notice_error($record->message); + } + + if (isset($record->formatted['context']) && \is_array($record->formatted['context'])) { + foreach ($record->formatted['context'] as $key => $parameter) { + if (\is_array($parameter) && $this->explodeArrays) { + foreach ($parameter as $paramKey => $paramValue) { + $this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue); + } + } else { + $this->setNewRelicParameter('context_' . $key, $parameter); + } + } + } + + if (isset($record->formatted['extra']) && \is_array($record->formatted['extra'])) { + foreach ($record->formatted['extra'] as $key => $parameter) { + if (\is_array($parameter) && $this->explodeArrays) { + foreach ($parameter as $paramKey => $paramValue) { + $this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue); + } + } else { + $this->setNewRelicParameter('extra_' . $key, $parameter); + } + } + } + } + + /** + * Checks whether the NewRelic extension is enabled in the system. + */ + protected function isNewRelicEnabled(): bool + { + return \extension_loaded('newrelic'); + } + + /** + * Returns the appname where this log should be sent. Each log can override the default appname, set in this + * handler's constructor, by providing the appname in it's context. + * + * @param mixed[] $context + */ + protected function getAppName(array $context): ?string + { + if (isset($context['appname'])) { + return $context['appname']; + } + + return $this->appName; + } + + /** + * Returns the name of the current transaction. Each log can override the default transaction name, set in this + * handler's constructor, by providing the transaction_name in it's context + * + * @param mixed[] $context + */ + protected function getTransactionName(array $context): ?string + { + if (isset($context['transaction_name'])) { + return $context['transaction_name']; + } + + return $this->transactionName; + } + + /** + * Sets the NewRelic application that should receive this log. + */ + protected function setNewRelicAppName(string $appName): void + { + newrelic_set_appname($appName); + } + + /** + * Overwrites the name of the current transaction + */ + protected function setNewRelicTransactionName(string $transactionName): void + { + newrelic_name_transaction($transactionName); + } + + /** + * @param mixed $value + */ + protected function setNewRelicParameter(string $key, $value): void + { + if (null === $value || \is_scalar($value)) { + newrelic_add_custom_parameter($key, $value); + } else { + newrelic_add_custom_parameter($key, Utils::jsonEncode($value, null, true)); + } + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new NormalizerFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php new file mode 100644 index 0000000..d9fea18 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php @@ -0,0 +1,42 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\LogRecord; + +/** + * No-op + * + * This handler handles anything, but does nothing, and does not stop bubbling to the rest of the stack. + * This can be used for testing, or to disable a handler when overriding a configuration without + * influencing the rest of the stack. + * + * @author Roel Harbers <roelharbers@gmail.com> + */ +class NoopHandler extends Handler +{ + /** + * @inheritDoc + */ + public function isHandling(LogRecord $record): bool + { + return true; + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + return false; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php new file mode 100644 index 0000000..1aa84e4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php @@ -0,0 +1,56 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Psr\Log\LogLevel; +use Monolog\Logger; +use Monolog\LogRecord; + +/** + * Blackhole + * + * Any record it can handle will be thrown away. This can be used + * to put on top of an existing stack to override it temporarily. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class NullHandler extends Handler +{ + private Level $level; + + /** + * @param string|int|Level $level The minimum logging level at which this handler will be triggered + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function __construct(string|int|Level $level = Level::Debug) + { + $this->level = Logger::toMonologLevel($level); + } + + /** + * @inheritDoc + */ + public function isHandling(LogRecord $record): bool + { + return $record->level->value >= $this->level->value; + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + return $record->level->value >= $this->level->value; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php new file mode 100644 index 0000000..adc0eb1 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php @@ -0,0 +1,139 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Handler to only pass log messages when a certain threshold of number of messages is reached. + * + * This can be useful in cases of processing a batch of data, but you're for example only interested + * in case it fails catastrophically instead of a warning for 1 or 2 events. Worse things can happen, right? + * + * Usage example: + * + * ``` + * $log = new Logger('application'); + * $handler = new SomeHandler(...) + * + * // Pass all warnings to the handler when more than 10 & all error messages when more then 5 + * $overflow = new OverflowHandler($handler, [Level::Warning->value => 10, Level::Error->value => 5]); + * + * $log->pushHandler($overflow); + *``` + * + * @author Kris Buist <krisbuist@gmail.com> + */ +class OverflowHandler extends AbstractHandler implements FormattableHandlerInterface +{ + private HandlerInterface $handler; + + /** @var array<int, int> */ + private array $thresholdMap = []; + + /** + * Buffer of all messages passed to the handler before the threshold was reached + * + * @var mixed[][] + */ + private array $buffer = []; + + /** + * @param array<int, int> $thresholdMap Dictionary of log level value => threshold + */ + public function __construct( + HandlerInterface $handler, + array $thresholdMap = [], + $level = Level::Debug, + bool $bubble = true + ) { + $this->handler = $handler; + foreach ($thresholdMap as $thresholdLevel => $threshold) { + $this->thresholdMap[$thresholdLevel] = $threshold; + } + parent::__construct($level, $bubble); + } + + /** + * Handles a record. + * + * All records may be passed to this method, and the handler should discard + * those that it does not want to handle. + * + * The return value of this function controls the bubbling process of the handler stack. + * Unless the bubbling is interrupted (by returning true), the Logger class will keep on + * calling further handlers in the stack with a given log record. + * + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if ($record->level->isLowerThan($this->level)) { + return false; + } + + $level = $record->level->value; + + if (!isset($this->thresholdMap[$level])) { + $this->thresholdMap[$level] = 0; + } + + if ($this->thresholdMap[$level] > 0) { + // The overflow threshold is not yet reached, so we're buffering the record and lowering the threshold by 1 + $this->thresholdMap[$level]--; + $this->buffer[$level][] = $record; + + return false === $this->bubble; + } + + if ($this->thresholdMap[$level] === 0) { + // This current message is breaking the threshold. Flush the buffer and continue handling the current record + foreach ($this->buffer[$level] ?? [] as $buffered) { + $this->handler->handle($buffered); + } + $this->thresholdMap[$level]--; + unset($this->buffer[$level]); + } + + $this->handler->handle($record); + + return false === $this->bubble; + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + $this->handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($this->handler).' does not support formatters.'); + } + + /** + * @inheritDoc + */ + public function getFormatter(): FormatterInterface + { + if ($this->handler instanceof FormattableHandlerInterface) { + return $this->handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($this->handler).' does not support formatters.'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php new file mode 100644 index 0000000..b37266d --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php @@ -0,0 +1,303 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Level; +use Monolog\Utils; +use PhpConsole\Connector; +use PhpConsole\Handler as VendorPhpConsoleHandler; +use PhpConsole\Helper; +use Monolog\LogRecord; +use PhpConsole\Storage; + +/** + * Monolog handler for Google Chrome extension "PHP Console" + * + * Display PHP error/debug log messages in Google Chrome console and notification popups, executes PHP code remotely + * + * Usage: + * 1. Install Google Chrome extension [now dead and removed from the chrome store] + * 2. See overview https://github.com/barbushin/php-console#overview + * 3. Install PHP Console library https://github.com/barbushin/php-console#installation + * 4. Example (result will looks like http://i.hizliresim.com/vg3Pz4.png) + * + * $logger = new \Monolog\Logger('all', array(new \Monolog\Handler\PHPConsoleHandler())); + * \Monolog\ErrorHandler::register($logger); + * echo $undefinedVar; + * $logger->debug('SELECT * FROM users', array('db', 'time' => 0.012)); + * PC::debug($_SERVER); // PHP Console debugger for any type of vars + * + * @author Sergey Barbushin https://www.linkedin.com/in/barbushin + * @phpstan-type Options array{ + * enabled: bool, + * classesPartialsTraceIgnore: string[], + * debugTagsKeysInContext: array<int|string>, + * useOwnErrorsHandler: bool, + * useOwnExceptionsHandler: bool, + * sourcesBasePath: string|null, + * registerHelper: bool, + * serverEncoding: string|null, + * headersLimit: int|null, + * password: string|null, + * enableSslOnlyMode: bool, + * ipMasks: string[], + * enableEvalListener: bool, + * dumperDetectCallbacks: bool, + * dumperLevelLimit: int, + * dumperItemsCountLimit: int, + * dumperItemSizeLimit: int, + * dumperDumpSizeLimit: int, + * detectDumpTraceAndSource: bool, + * dataStorage: Storage|null + * } + * @phpstan-type InputOptions array{ + * enabled?: bool, + * classesPartialsTraceIgnore?: string[], + * debugTagsKeysInContext?: array<int|string>, + * useOwnErrorsHandler?: bool, + * useOwnExceptionsHandler?: bool, + * sourcesBasePath?: string|null, + * registerHelper?: bool, + * serverEncoding?: string|null, + * headersLimit?: int|null, + * password?: string|null, + * enableSslOnlyMode?: bool, + * ipMasks?: string[], + * enableEvalListener?: bool, + * dumperDetectCallbacks?: bool, + * dumperLevelLimit?: int, + * dumperItemsCountLimit?: int, + * dumperItemSizeLimit?: int, + * dumperDumpSizeLimit?: int, + * detectDumpTraceAndSource?: bool, + * dataStorage?: Storage|null + * } + * + * @deprecated Since 2.8.0 and 3.2.0, PHPConsole is abandoned and thus we will drop this handler in Monolog 4 + */ +class PHPConsoleHandler extends AbstractProcessingHandler +{ + /** + * @phpstan-var Options + */ + private array $options = [ + 'enabled' => true, // bool Is PHP Console server enabled + 'classesPartialsTraceIgnore' => ['Monolog\\'], // array Hide calls of classes started with... + 'debugTagsKeysInContext' => [0, 'tag'], // bool Is PHP Console server enabled + 'useOwnErrorsHandler' => false, // bool Enable errors handling + 'useOwnExceptionsHandler' => false, // bool Enable exceptions handling + 'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths + 'registerHelper' => true, // bool Register PhpConsole\Helper that allows short debug calls like PC::debug($var, 'ta.g.s') + 'serverEncoding' => null, // string|null Server internal encoding + 'headersLimit' => null, // int|null Set headers size limit for your web-server + 'password' => null, // string|null Protect PHP Console connection by password + 'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed + 'ipMasks' => [], // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1') + 'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required) + 'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings + 'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level + 'dumperItemsCountLimit' => 100, // int Maximum dumped var same level array items or object properties number + 'dumperItemSizeLimit' => 5000, // int Maximum length of any string or dumped array item + 'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON + 'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug + 'dataStorage' => null, // \PhpConsole\Storage|null Fixes problem with custom $_SESSION handler (see https://github.com/barbushin/php-console#troubleshooting-with-_session-handler-overridden-in-some-frameworks) + ]; + + private Connector $connector; + + /** + * @param array<string, mixed> $options See \Monolog\Handler\PHPConsoleHandler::$options for more details + * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional) + * @throws \RuntimeException + * @phpstan-param InputOptions $options + */ + public function __construct(array $options = [], ?Connector $connector = null, int|string|Level $level = Level::Debug, bool $bubble = true) + { + if (!class_exists('PhpConsole\Connector')) { + throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation'); + } + parent::__construct($level, $bubble); + $this->options = $this->initOptions($options); + $this->connector = $this->initConnector($connector); + } + + /** + * @param array<string, mixed> $options + * @return array<string, mixed> + * + * @phpstan-param InputOptions $options + * @phpstan-return Options + */ + private function initOptions(array $options): array + { + $wrongOptions = array_diff(array_keys($options), array_keys($this->options)); + if (\count($wrongOptions) > 0) { + throw new \RuntimeException('Unknown options: ' . implode(', ', $wrongOptions)); + } + + return array_replace($this->options, $options); + } + + private function initConnector(?Connector $connector = null): Connector + { + if (null === $connector) { + if ($this->options['dataStorage'] instanceof Storage) { + Connector::setPostponeStorage($this->options['dataStorage']); + } + $connector = Connector::getInstance(); + } + + if ($this->options['registerHelper'] && !Helper::isRegistered()) { + Helper::register(); + } + + if ($this->options['enabled'] && $connector->isActiveClient()) { + if ($this->options['useOwnErrorsHandler'] || $this->options['useOwnExceptionsHandler']) { + $handler = VendorPhpConsoleHandler::getInstance(); + $handler->setHandleErrors($this->options['useOwnErrorsHandler']); + $handler->setHandleExceptions($this->options['useOwnExceptionsHandler']); + $handler->start(); + } + if (null !== $this->options['sourcesBasePath']) { + $connector->setSourcesBasePath($this->options['sourcesBasePath']); + } + if (null !== $this->options['serverEncoding']) { + $connector->setServerEncoding($this->options['serverEncoding']); + } + if (null !== $this->options['password']) { + $connector->setPassword($this->options['password']); + } + if ($this->options['enableSslOnlyMode']) { + $connector->enableSslOnlyMode(); + } + if (\count($this->options['ipMasks']) > 0) { + $connector->setAllowedIpMasks($this->options['ipMasks']); + } + if (null !== $this->options['headersLimit'] && $this->options['headersLimit'] > 0) { + $connector->setHeadersLimit($this->options['headersLimit']); + } + if ($this->options['detectDumpTraceAndSource']) { + $connector->getDebugDispatcher()->detectTraceAndSource = true; + } + $dumper = $connector->getDumper(); + $dumper->levelLimit = $this->options['dumperLevelLimit']; + $dumper->itemsCountLimit = $this->options['dumperItemsCountLimit']; + $dumper->itemSizeLimit = $this->options['dumperItemSizeLimit']; + $dumper->dumpSizeLimit = $this->options['dumperDumpSizeLimit']; + $dumper->detectCallbacks = $this->options['dumperDetectCallbacks']; + if ($this->options['enableEvalListener']) { + $connector->startEvalRequestsListener(); + } + } + + return $connector; + } + + public function getConnector(): Connector + { + return $this->connector; + } + + /** + * @return array<string, mixed> + */ + public function getOptions(): array + { + return $this->options; + } + + public function handle(LogRecord $record): bool + { + if ($this->options['enabled'] && $this->connector->isActiveClient()) { + return parent::handle($record); + } + + return !$this->bubble; + } + + /** + * Writes the record down to the log of the implementing handler + */ + protected function write(LogRecord $record): void + { + if ($record->level->isLowerThan(Level::Notice)) { + $this->handleDebugRecord($record); + } elseif (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) { + $this->handleExceptionRecord($record); + } else { + $this->handleErrorRecord($record); + } + } + + private function handleDebugRecord(LogRecord $record): void + { + [$tags, $filteredContext] = $this->getRecordTags($record); + $message = $record->message; + if (\count($filteredContext) > 0) { + $message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($filteredContext)), null, true); + } + $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']); + } + + private function handleExceptionRecord(LogRecord $record): void + { + $this->connector->getErrorsDispatcher()->dispatchException($record->context['exception']); + } + + private function handleErrorRecord(LogRecord $record): void + { + $context = $record->context; + + $this->connector->getErrorsDispatcher()->dispatchError( + $context['code'] ?? null, + $context['message'] ?? $record->message, + $context['file'] ?? null, + $context['line'] ?? null, + $this->options['classesPartialsTraceIgnore'] + ); + } + + /** + * @return array{string, mixed[]} + */ + private function getRecordTags(LogRecord $record): array + { + $tags = null; + $filteredContext = []; + if ($record->context !== []) { + $filteredContext = $record->context; + foreach ($this->options['debugTagsKeysInContext'] as $key) { + if (isset($filteredContext[$key])) { + $tags = $filteredContext[$key]; + if ($key === 0) { + array_shift($filteredContext); + } else { + unset($filteredContext[$key]); + } + break; + } + } + } + + return [$tags ?? $record->level->toPsrLogLevel(), $filteredContext]; + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter('%message%'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php new file mode 100644 index 0000000..2855a9f --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php @@ -0,0 +1,191 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Stores to STDIN of any process, specified by a command. + * + * Usage example: + * <pre> + * $log = new Logger('myLogger'); + * $log->pushHandler(new ProcessHandler('/usr/bin/php /var/www/monolog/someScript.php')); + * </pre> + * + * @author Kolja Zuelsdorf <koljaz@web.de> + */ +class ProcessHandler extends AbstractProcessingHandler +{ + /** + * Holds the process to receive data on its STDIN. + * + * @var resource|bool|null + */ + private $process; + + private string $command; + + private ?string $cwd; + + /** + * @var resource[] + */ + private array $pipes = []; + + private float $timeout; + + /** + * @var array<int, list<string>> + */ + protected const DESCRIPTOR_SPEC = [ + 0 => ['pipe', 'r'], // STDIN is a pipe that the child will read from + 1 => ['pipe', 'w'], // STDOUT is a pipe that the child will write to + 2 => ['pipe', 'w'], // STDERR is a pipe to catch the any errors + ]; + + /** + * @param string $command Command for the process to start. Absolute paths are recommended, + * especially if you do not use the $cwd parameter. + * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in. + * @param float $timeout The maximum timeout (in seconds) for the stream_select() function. + * @throws \InvalidArgumentException + */ + public function __construct(string $command, int|string|Level $level = Level::Debug, bool $bubble = true, ?string $cwd = null, float $timeout = 1.0) + { + if ($command === '') { + throw new \InvalidArgumentException('The command argument must be a non-empty string.'); + } + if ($cwd === '') { + throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string or null.'); + } + + parent::__construct($level, $bubble); + + $this->command = $command; + $this->cwd = $cwd; + $this->timeout = $timeout; + } + + /** + * Writes the record down to the log of the implementing handler + * + * @throws \UnexpectedValueException + */ + protected function write(LogRecord $record): void + { + $this->ensureProcessIsStarted(); + + $this->writeProcessInput($record->formatted); + + $errors = $this->readProcessErrors(); + if ($errors !== '') { + throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors)); + } + } + + /** + * Makes sure that the process is actually started, and if not, starts it, + * assigns the stream pipes, and handles startup errors, if any. + */ + private function ensureProcessIsStarted(): void + { + if (\is_resource($this->process) === false) { + $this->startProcess(); + + $this->handleStartupErrors(); + } + } + + /** + * Starts the actual process and sets all streams to non-blocking. + */ + private function startProcess(): void + { + $this->process = proc_open($this->command, static::DESCRIPTOR_SPEC, $this->pipes, $this->cwd); + + foreach ($this->pipes as $pipe) { + stream_set_blocking($pipe, false); + } + } + + /** + * Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any. + * + * @throws \UnexpectedValueException + */ + private function handleStartupErrors(): void + { + $selected = $this->selectErrorStream(); + if (false === $selected) { + throw new \UnexpectedValueException('Something went wrong while selecting a stream.'); + } + + $errors = $this->readProcessErrors(); + + if (\is_resource($this->process) === false || $errors !== '') { + throw new \UnexpectedValueException( + sprintf('The process "%s" could not be opened: ' . $errors, $this->command) + ); + } + } + + /** + * Selects the STDERR stream. + * + * @return int|bool + */ + protected function selectErrorStream() + { + $empty = []; + $errorPipes = [$this->pipes[2]]; + + $seconds = (int) $this->timeout; + return stream_select($errorPipes, $empty, $empty, $seconds, (int) (($this->timeout - $seconds) * 1000000)); + } + + /** + * Reads the errors of the process, if there are any. + * + * @codeCoverageIgnore + * @return string Empty string if there are no errors. + */ + protected function readProcessErrors(): string + { + return (string) stream_get_contents($this->pipes[2]); + } + + /** + * Writes to the input stream of the opened process. + * + * @codeCoverageIgnore + */ + protected function writeProcessInput(string $string): void + { + fwrite($this->pipes[0], $string); + } + + /** + * @inheritDoc + */ + public function close(): void + { + if (\is_resource($this->process)) { + foreach ($this->pipes as $pipe) { + fclose($pipe); + } + proc_close($this->process); + $this->process = null; + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php new file mode 100644 index 0000000..9fb290f --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php @@ -0,0 +1,43 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Processor\ProcessorInterface; +use Monolog\LogRecord; + +/** + * Interface to describe loggers that have processors + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +interface ProcessableHandlerInterface +{ + /** + * Adds a processor in the stack. + * + * @phpstan-param ProcessorInterface|(callable(LogRecord): LogRecord) $callback + * + * @param ProcessorInterface|callable $callback + * @return HandlerInterface self + */ + public function pushProcessor(callable $callback): HandlerInterface; + + /** + * Removes the processor on top of the stack and returns it. + * + * @phpstan-return ProcessorInterface|(callable(LogRecord): LogRecord) $callback + * + * @throws \LogicException In case the processor stack is empty + * @return callable|ProcessorInterface + */ + public function popProcessor(): callable; +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php b/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php new file mode 100644 index 0000000..74eeddd --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php @@ -0,0 +1,70 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\ResettableInterface; +use Monolog\Processor\ProcessorInterface; +use Monolog\LogRecord; + +/** + * Helper trait for implementing ProcessableInterface + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +trait ProcessableHandlerTrait +{ + /** + * @var callable[] + * @phpstan-var array<(callable(LogRecord): LogRecord)|ProcessorInterface> + */ + protected array $processors = []; + + /** + * @inheritDoc + */ + public function pushProcessor(callable $callback): HandlerInterface + { + array_unshift($this->processors, $callback); + + return $this; + } + + /** + * @inheritDoc + */ + public function popProcessor(): callable + { + if (\count($this->processors) === 0) { + throw new \LogicException('You tried to pop from an empty processor stack.'); + } + + return array_shift($this->processors); + } + + protected function processRecord(LogRecord $record): LogRecord + { + foreach ($this->processors as $processor) { + $record = $processor($record); + } + + return $record; + } + + protected function resetProcessors(): void + { + foreach ($this->processors as $processor) { + if ($processor instanceof ResettableInterface) { + $processor->reset(); + } + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php new file mode 100644 index 0000000..100e8e4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php @@ -0,0 +1,92 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Psr\Log\LoggerInterface; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Proxies log messages to an existing PSR-3 compliant logger. + * + * If a formatter is configured, the formatter's output MUST be a string and the + * formatted message will be fed to the wrapped PSR logger instead of the original + * log record's message. + * + * @author Michael Moussa <michael.moussa@gmail.com> + */ +class PsrHandler extends AbstractHandler implements FormattableHandlerInterface +{ + /** + * PSR-3 compliant logger + */ + protected LoggerInterface $logger; + + protected FormatterInterface|null $formatter = null; + private bool $includeExtra; + + /** + * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied + */ + public function __construct(LoggerInterface $logger, int|string|Level $level = Level::Debug, bool $bubble = true, bool $includeExtra = false) + { + parent::__construct($level, $bubble); + + $this->logger = $logger; + $this->includeExtra = $includeExtra; + } + + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if (!$this->isHandling($record)) { + return false; + } + + $message = $this->formatter !== null + ? (string) $this->formatter->format($record) + : $record->message; + + $context = $this->includeExtra + ? [...$record->extra, ...$record->context] + : $record->context; + + $this->logger->log($record->level->toPsrLogLevel(), $message, $context); + + return false === $this->bubble; + } + + /** + * Sets the formatter. + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $this->formatter = $formatter; + + return $this; + } + + /** + * Gets the formatter. + */ + public function getFormatter(): FormatterInterface + { + if ($this->formatter === null) { + throw new \LogicException('No formatter has been set and this handler does not have a default formatter'); + } + + return $this->formatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php new file mode 100644 index 0000000..b2a7895 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php @@ -0,0 +1,246 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Logger; +use Monolog\Utils; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Sends notifications through the pushover api to mobile phones + * + * @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com> + * @see https://www.pushover.net/api + */ +class PushoverHandler extends SocketHandler +{ + private string $token; + + /** @var array<int|string> */ + private array $users; + + private string $title; + + private string|int|null $user = null; + + private int $retry; + + private int $expire; + + private Level $highPriorityLevel; + + private Level $emergencyLevel; + + private bool $useFormattedMessage = false; + + /** + * All parameters that can be sent to Pushover + * @see https://pushover.net/api + * @var array<string, bool> + */ + private array $parameterNames = [ + 'token' => true, + 'user' => true, + 'message' => true, + 'device' => true, + 'title' => true, + 'url' => true, + 'url_title' => true, + 'priority' => true, + 'timestamp' => true, + 'sound' => true, + 'retry' => true, + 'expire' => true, + 'callback' => true, + ]; + + /** + * Sounds the api supports by default + * @see https://pushover.net/api#sounds + * @var string[] + */ + private array $sounds = [ + 'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming', + 'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb', + 'persistent', 'echo', 'updown', 'none', + ]; + + /** + * @param string $token Pushover api token + * @param string|array $users Pushover user id or array of ids the message will be sent to + * @param string|null $title Title sent to the Pushover API + * @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not + * the pushover.net app owner. OpenSSL is required for this option. + * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will + * send the same notification to the user. + * @param int $expire The expire parameter specifies how many seconds your notification will continue + * to be retried for (every retry seconds). + * + * @param int|string|Level|LogLevel::* $highPriorityLevel The minimum logging level at which this handler will start + * sending "high priority" requests to the Pushover API + * @param int|string|Level|LogLevel::* $emergencyLevel The minimum logging level at which this handler will start + * sending "emergency" requests to the Pushover API + * + * + * @phpstan-param string|array<int|string> $users + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $highPriorityLevel + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $emergencyLevel + */ + public function __construct( + string $token, + $users, + ?string $title = null, + int|string|Level $level = Level::Critical, + bool $bubble = true, + bool $useSSL = true, + int|string|Level $highPriorityLevel = Level::Critical, + int|string|Level $emergencyLevel = Level::Emergency, + int $retry = 30, + int $expire = 25200, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + $connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80'; + parent::__construct( + $connectionString, + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + + $this->token = $token; + $this->users = (array) $users; + $this->title = $title ?? (string) gethostname(); + $this->highPriorityLevel = Logger::toMonologLevel($highPriorityLevel); + $this->emergencyLevel = Logger::toMonologLevel($emergencyLevel); + $this->retry = $retry; + $this->expire = $expire; + } + + protected function generateDataStream(LogRecord $record): string + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + private function buildContent(LogRecord $record): string + { + // Pushover has a limit of 512 characters on title and message combined. + $maxMessageLength = 512 - \strlen($this->title); + + $message = ($this->useFormattedMessage) ? $record->formatted : $record->message; + $message = Utils::substr($message, 0, $maxMessageLength); + + $timestamp = $record->datetime->getTimestamp(); + + $dataArray = [ + 'token' => $this->token, + 'user' => $this->user, + 'message' => $message, + 'title' => $this->title, + 'timestamp' => $timestamp, + ]; + + if ($record->level->value >= $this->emergencyLevel->value) { + $dataArray['priority'] = 2; + $dataArray['retry'] = $this->retry; + $dataArray['expire'] = $this->expire; + } elseif ($record->level->value >= $this->highPriorityLevel->value) { + $dataArray['priority'] = 1; + } + + // First determine the available parameters + $context = array_intersect_key($record->context, $this->parameterNames); + $extra = array_intersect_key($record->extra, $this->parameterNames); + + // Least important info should be merged with subsequent info + $dataArray = array_merge($extra, $context, $dataArray); + + // Only pass sounds that are supported by the API + if (isset($dataArray['sound']) && !\in_array($dataArray['sound'], $this->sounds, true)) { + unset($dataArray['sound']); + } + + return http_build_query($dataArray); + } + + private function buildHeader(string $content): string + { + $header = "POST /1/messages.json HTTP/1.1\r\n"; + $header .= "Host: api.pushover.net\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . \strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + protected function write(LogRecord $record): void + { + foreach ($this->users as $user) { + $this->user = $user; + + parent::write($record); + $this->closeSocket(); + } + + $this->user = null; + } + + /** + * @param int|string|Level|LogLevel::* $level + * @return $this + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function setHighPriorityLevel(int|string|Level $level): self + { + $this->highPriorityLevel = Logger::toMonologLevel($level); + + return $this; + } + + /** + * @param int|string|Level|LogLevel::* $level + * @return $this + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function setEmergencyLevel(int|string|Level $level): self + { + $this->emergencyLevel = Logger::toMonologLevel($level); + + return $this; + } + + /** + * Use the formatted message? + * + * @return $this + */ + public function useFormattedMessage(bool $useFormattedMessage): self + { + $this->useFormattedMessage = $useFormattedMessage; + + return $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php new file mode 100644 index 0000000..c40d97c --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php @@ -0,0 +1,94 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Level; +use Monolog\LogRecord; +use Predis\Client as Predis; +use Redis; + +/** + * Logs to a Redis key using rpush + * + * usage example: + * + * $log = new Logger('application'); + * $redis = new RedisHandler(new Predis\Client("tcp://localhost:6379"), "logs"); + * $log->pushHandler($redis); + * + * @author Thomas Tourlourat <thomas@tourlourat.com> + */ +class RedisHandler extends AbstractProcessingHandler +{ + /** @var Predis<Predis>|Redis */ + private Predis|Redis $redisClient; + private string $redisKey; + protected int $capSize; + + /** + * @param Predis<Predis>|Redis $redis The redis instance + * @param string $key The key name to push records to + * @param int $capSize Number of entries to limit list size to, 0 = unlimited + */ + public function __construct(Predis|Redis $redis, string $key, int|string|Level $level = Level::Debug, bool $bubble = true, int $capSize = 0) + { + $this->redisClient = $redis; + $this->redisKey = $key; + $this->capSize = $capSize; + + parent::__construct($level, $bubble); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + if ($this->capSize > 0) { + $this->writeCapped($record); + } else { + $this->redisClient->rpush($this->redisKey, $record->formatted); + } + } + + /** + * Write and cap the collection + * Writes the record to the redis list and caps its + */ + protected function writeCapped(LogRecord $record): void + { + if ($this->redisClient instanceof Redis) { + $mode = \defined('Redis::MULTI') ? Redis::MULTI : 1; + $this->redisClient->multi($mode) + ->rPush($this->redisKey, $record->formatted) + ->ltrim($this->redisKey, -$this->capSize, -1) + ->exec(); + } else { + $redisKey = $this->redisKey; + $capSize = $this->capSize; + $this->redisClient->transaction(function ($tx) use ($record, $redisKey, $capSize) { + $tx->rpush($redisKey, $record->formatted); + $tx->ltrim($redisKey, -$capSize, -1); + }); + } + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php new file mode 100644 index 0000000..fa8e9e9 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php @@ -0,0 +1,65 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Level; +use Monolog\LogRecord; +use Predis\Client as Predis; +use Redis; + +/** + * Sends the message to a Redis Pub/Sub channel using PUBLISH + * + * usage example: + * + * $log = new Logger('application'); + * $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Level::Warning); + * $log->pushHandler($redis); + * + * @author Gaëtan Faugère <gaetan@fauge.re> + */ +class RedisPubSubHandler extends AbstractProcessingHandler +{ + /** @var Predis<Predis>|Redis */ + private Predis|Redis $redisClient; + private string $channelKey; + + /** + * @param Predis<Predis>|Redis $redis The redis instance + * @param string $key The channel key to publish records to + */ + public function __construct(Predis|Redis $redis, string $key, int|string|Level $level = Level::Debug, bool $bubble = true) + { + $this->redisClient = $redis; + $this->channelKey = $key; + + parent::__construct($level, $bubble); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->redisClient->publish($this->channelKey, $record->formatted); + } + + /** + * @inheritDoc + */ + protected function getDefaultFormatter(): FormatterInterface + { + return new LineFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php new file mode 100644 index 0000000..6b99432 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php @@ -0,0 +1,132 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Rollbar\RollbarLogger; +use Throwable; +use Monolog\LogRecord; + +/** + * Sends errors to Rollbar + * + * If the context data contains a `payload` key, that is used as an array + * of payload options to RollbarLogger's log method. + * + * Rollbar's context info will contain the context + extra keys from the log record + * merged, and then on top of that a few keys: + * + * - level (rollbar level name) + * - monolog_level (monolog level name, raw level, as rollbar only has 5 but monolog 8) + * - channel + * - datetime (unix timestamp) + * + * @author Paul Statezny <paulstatezny@gmail.com> + */ +class RollbarHandler extends AbstractProcessingHandler +{ + protected RollbarLogger $rollbarLogger; + + /** + * Records whether any log records have been added since the last flush of the rollbar notifier + */ + private bool $hasRecords = false; + + protected bool $initialized = false; + + /** + * @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token + */ + public function __construct(RollbarLogger $rollbarLogger, int|string|Level $level = Level::Error, bool $bubble = true) + { + $this->rollbarLogger = $rollbarLogger; + + parent::__construct($level, $bubble); + } + + /** + * Translates Monolog log levels to Rollbar levels. + * + * @return 'debug'|'info'|'warning'|'error'|'critical' + */ + protected function toRollbarLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'debug', + Level::Info => 'info', + Level::Notice => 'info', + Level::Warning => 'warning', + Level::Error => 'error', + Level::Critical => 'critical', + Level::Alert => 'critical', + Level::Emergency => 'critical', + }; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + if (!$this->initialized) { + // __destructor() doesn't get called on Fatal errors + register_shutdown_function([$this, 'close']); + $this->initialized = true; + } + + $context = $record->context; + $context = array_merge($context, $record->extra, [ + 'level' => $this->toRollbarLevel($record->level), + 'monolog_level' => $record->level->getName(), + 'channel' => $record->channel, + 'datetime' => $record->datetime->format('U'), + ]); + + if (isset($context['exception']) && $context['exception'] instanceof Throwable) { + $exception = $context['exception']; + unset($context['exception']); + $toLog = $exception; + } else { + $toLog = $record->message; + } + + $this->rollbarLogger->log($context['level'], $toLog, $context); + + $this->hasRecords = true; + } + + public function flush(): void + { + if ($this->hasRecords) { + $this->rollbarLogger->flush(); + $this->hasRecords = false; + } + } + + /** + * @inheritDoc + */ + public function close(): void + { + $this->flush(); + } + + /** + * @inheritDoc + */ + public function reset(): void + { + $this->flush(); + + parent::reset(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php new file mode 100644 index 0000000..b45d6ed --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php @@ -0,0 +1,386 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use DateTimeZone; +use InvalidArgumentException; +use Monolog\Level; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Stores logs to files that are rotated every day and a limited number of files are kept. + * + * This rotation is only intended to be used as a workaround. Using logrotate to + * handle the rotation is strongly encouraged when you can use it. + * + * @author Christophe Coevoet <stof@notk.org> + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class RotatingFileHandler extends StreamHandler +{ + public const FILE_PER_HOUR = 'Y-m-d-H'; + public const FILE_PER_DAY = 'Y-m-d'; + public const FILE_PER_MONTH = 'Y-m'; + public const FILE_PER_YEAR = 'Y'; + + protected string $filename; + protected int $maxFiles; + protected bool|null $mustRotate = null; + protected \DateTimeImmutable $nextRotation; + protected string $filenameFormat; + protected string $dateFormat; + protected DateTimeZone|null $timezone = null; + + /** + * @param int $maxFiles The maximal amount of files to keep (0 means unlimited) + * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) + * @param bool $useLocking Try to lock log file before doing any writes + */ + public function __construct(string $filename, int $maxFiles = 0, int|string|Level $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false, string $dateFormat = self::FILE_PER_DAY, string $filenameFormat = '{filename}-{date}', DateTimeZone|null $timezone = null) + { + $this->filename = Utils::canonicalizePath($filename); + $this->maxFiles = $maxFiles; + $this->timezone = $timezone; + $this->setFilenameFormat($filenameFormat, $dateFormat); + + parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking); + } + + /** + * @inheritDoc + */ + public function close(): void + { + parent::close(); + + if (true === $this->mustRotate) { + $this->rotate(); + } + } + + /** + * @inheritDoc + */ + public function reset(): void + { + parent::reset(); + } + + /** + * @return $this + */ + public function setFilenameFormat(string $filenameFormat, string $dateFormat): self + { + $this->setDateFormat($dateFormat); + if (substr_count($filenameFormat, '{date}') === 0) { + throw new InvalidArgumentException( + 'Invalid filename format - format must contain at least `{date}`, because otherwise rotating is impossible.' + ); + } + $this->filenameFormat = $filenameFormat; + $this->url = $this->getTimedFilename(); + $this->nextRotation = $this->getNextRotation(); + $this->close(); + + return $this; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + // on the first record written, if the log is new, we rotate (once per day) after the log has been written so that the new file exists + if (null === $this->mustRotate) { + $this->mustRotate = null === $this->url || !file_exists($this->url); + } + + // if the next rotation is expired, then we rotate immediately + if ($this->nextRotation <= $record->datetime) { + $this->mustRotate = true; + $this->close(); // triggers rotation + } + + parent::write($record); + + if (true === $this->mustRotate) { + $this->close(); // triggers rotation + } + } + + /** + * Rotates the files. + */ + protected function rotate(): void + { + // update filename + $this->url = $this->getTimedFilename(); + $this->nextRotation = $this->getNextRotation(); + + $this->mustRotate = false; + + // skip GC of old logs if files are unlimited + if (0 === $this->maxFiles) { + return; + } + + $logFiles = $this->findRotatedFiles(); + + if ($this->maxFiles >= \count($logFiles)) { + // no files to remove + return; + } + + // Sorting the files by name to remove the older ones + usort($logFiles, function ($a, $b) { + return strcmp($b, $a); + }); + + $basePath = self::normalizeDirectorySeparators(dirname($this->filename)); + + foreach (\array_slice($logFiles, $this->maxFiles) as $file) { + if (is_writable($file)) { + // suppress errors here as unlink() might fail if two processes + // are cleaning up/rotating at the same time + set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): bool { + return true; + }); + unlink($file); + + $dir = self::normalizeDirectorySeparators(dirname($file)); + while ($dir !== $basePath) { + $entries = scandir($dir); + if ($entries === false || \count(array_diff($entries, ['.', '..'])) > 0) { + break; + } + + rmdir($dir); + $dir = self::normalizeDirectorySeparators(dirname($dir)); + } + restore_error_handler(); + } + } + } + + protected function getTimedFilename(): string + { + $fileInfo = pathinfo($this->filename); + $timedFilename = str_replace( + ['{filename}', '{date}'], + [$fileInfo['filename'], (new \DateTimeImmutable(timezone: $this->timezone))->format($this->dateFormat)], + self::appendDirectorySeparator($fileInfo['dirname'] ?? '') . $this->filenameFormat + ); + + if (isset($fileInfo['extension'])) { + $timedFilename .= '.'.$fileInfo['extension']; + } + + return $timedFilename; + } + + /** + * Appends the trailing "/" to a pathinfo() dirname. + * + * pathinfo() reduces a wrapper URL with no subdirectory ("scheme://foo.log") + * to a bare "scheme:", and PHP does not route the single-slash "scheme:/" + * to the wrapper at all, so that case needs both slashes back. The pattern + * deliberately requires two characters before the colon so a Windows drive + * letter is left alone. + */ + private static function appendDirectorySeparator(string $dirName): string + { + if (1 === preg_match('#^[a-zA-Z][a-zA-Z0-9+.-]+:$#', $dirName)) { + return $dirName.'//'; + } + + return $dirName.'/'; + } + + /** + * Rewrites Windows directory separators to "/". + * + * SPL joins directory entries with DIRECTORY_SEPARATOR, so on Windows the + * iterator yields "C:\\logs\\foo.rot" while the pattern is built from a + * pathinfo() dirname. Both sides have to be normalised, and only on Windows: + * on POSIX a backslash is a legal filename character. + */ + private static function normalizeDirectorySeparators(string $path): string + { + if ('\\' !== \DIRECTORY_SEPARATOR) { + return $path; + } + + return str_replace('\\', '/', $path); + } + + /** + * Finds the log files that previous rotations left behind. + * + * glob() cannot see through stream wrappers (Drupal's private:// for one), + * so the pattern is translated to a regex and matched against a directory + * walk instead. It still comes from getGlobPattern(), so overriding that + * keeps changing which files the cleanup considers. Unlike glob(), symlinked + * directories are not followed, which also rules out symlink loops. + * + * @return string[] + */ + protected function findRotatedFiles(): array + { + $pattern = self::normalizeDirectorySeparators($this->getGlobPattern()); + + // split off the literal directory prefix, so only the subtree the pattern + // can actually reach has to be walked; characters getGlobPattern() escaped + // are part of that prefix + preg_match('{^(?:[^*?\[]|\[[*?\[]\])*}', $pattern, $literalPrefix); + $slashPos = strrpos($literalPrefix[0] ?? '', '/'); + $baseDir = false === $slashPos ? './' : strtr(substr($pattern, 0, $slashPos + 1), ['[[]' => '[', '[*]' => '*', '[?]' => '?']); + $relativePattern = false === $slashPos ? $pattern : substr($pattern, $slashPos + 1); + + $regex = '#^'.preg_quote($baseDir, '#').self::globToRegex($relativePattern).'$#'; + + if (!is_dir($baseDir)) { + return []; + } + + try { + // walking the subtree is only needed when the pattern itself nests + $iterator = str_contains($relativePattern, '/') + ? new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($baseDir, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::LEAVES_ONLY, + // an unreadable subdirectory skips that subtree instead of throwing + // all the way out of write()/close() and breaking logging + \RecursiveIteratorIterator::CATCH_GET_CHILD + ) + : new \FilesystemIterator($baseDir, \FilesystemIterator::SKIP_DOTS); + } catch (\UnexpectedValueException $e) { + // is_dir() above can pass on a directory we are still not allowed to open + return []; + } + + $logFiles = []; + foreach ($iterator as $path => $file) { + if (!$file->isFile()) { + continue; + } + + $path = self::normalizeDirectorySeparators((string) $path); + if (1 === preg_match($regex, $path)) { + $logFiles[] = $path; + } + } + + return $logFiles; + } + + /** + * Translates a glob pattern into a regex matching the same paths. + * + * Wildcards stop at "/" like glob's do, so a pattern for one directory + * cannot start matching nested files once the walk goes deeper. + */ + private static function globToRegex(string $glob): string + { + $regex = ''; + + for ($i = 0, $length = \strlen($glob); $i < $length; $i++) { + $char = $glob[$i]; + + if ('*' === $char) { + $regex .= '[^/]*'; + continue; + } + + if ('?' === $char) { + $regex .= '[^/]'; + continue; + } + + // a "]" directly after the opening bracket is literal, hence $i + 2 + if ('[' === $char && false !== ($end = strpos($glob, ']', $i + 2))) { + $class = substr($glob, $i + 1, $end - $i - 1); + $negate = ''; + if (str_starts_with($class, '!')) { + $negate = '^'; + $class = substr($class, 1); + } + $regex .= '['.$negate.str_replace(['\\', ']', '^'], ['\\\\', '\\]', '\\^'], $class).']'; + $i = $end; + continue; + } + + $regex .= preg_quote($char, '#'); + } + + return $regex; + } + + protected function getGlobPattern(): string + { + $fileInfo = pathinfo($this->filename); + $glob = str_replace( + ['{filename}', '{date}'], + [self::escapeGlob($fileInfo['filename']), str_replace( + ['Y', 'y', 'm', 'd', 'H'], + ['[0-9][0-9][0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]'], + $this->dateFormat + )], + self::escapeGlob(self::appendDirectorySeparator($fileInfo['dirname'] ?? '') . $this->filenameFormat) + ); + if (isset($fileInfo['extension'])) { + $glob .= '.'.self::escapeGlob($fileInfo['extension']); + } + + return $glob; + } + + /** + * Makes glob metacharacters in a literal part of the pattern match only + * themselves, as otherwise "logs[1]/foo.log" would look for its rotated + * files in "logs1/". + */ + private static function escapeGlob(string $literal): string + { + return strtr($literal, ['[' => '[[]', '*' => '[*]', '?' => '[?]']); + } + + protected function setDateFormat(string $dateFormat): void + { + if (0 === preg_match('{^[Yy](([/_.-]?m)([/_.-]?d([/_.-]?H)?)?)?$}', $dateFormat)) { + throw new InvalidArgumentException( + 'Invalid date format - format must be one of RotatingFileHandler::FILE_PER_HOUR ("Y-m-d-H"), '. + 'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '. + 'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '. + 'date formats using slashes, underscores and/or dots instead of dashes.' + ); + } + + $this->dateFormat = $dateFormat; + } + + protected function getNextRotation(): \DateTimeImmutable + { + $now = new \DateTimeImmutable('now', $this->timezone); + + // only the letters matter, whatever separates them (a subclass may allow more than + // setDateFormat() does), and anything not clearly hourly/monthly/yearly rotates daily + $units = preg_replace('{[^a-zA-Z]+}', '', strtr($this->dateFormat, 'y', 'Y')) ?? ''; + + return match (true) { + str_contains($units, 'H') => $now->setTime((int) $now->format('G') + 1, 0, 0), + $units === 'Ym' => (new \DateTimeImmutable('first day of next month', $this->timezone))->setTime(0, 0, 0), + $units === 'Y' => (new \DateTimeImmutable('first day of January next year', $this->timezone))->setTime(0, 0, 0), + default => (new \DateTimeImmutable('tomorrow', $this->timezone))->setTime(0, 0, 0), + }; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php new file mode 100644 index 0000000..1b10580 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php @@ -0,0 +1,121 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Closure; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Sampling handler + * + * A sampled event stream can be useful for logging high frequency events in + * a production environment where you only need an idea of what is happening + * and are not concerned with capturing every occurrence. Since the decision to + * handle or not handle a particular event is determined randomly, the + * resulting sampled log is not guaranteed to contain 1/N of the events that + * occurred in the application, but based on the Law of large numbers, it will + * tend to be close to this ratio with a large number of attempts. + * + * @author Bryan Davis <bd808@wikimedia.org> + * @author Kunal Mehta <legoktm@gmail.com> + */ +class SamplingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface +{ + use ProcessableHandlerTrait; + + /** + * Handler or factory Closure($record, $this) + * + * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface + */ + protected Closure|HandlerInterface $handler; + + protected int $factor; + + /** + * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler + * + * @param Closure|HandlerInterface $handler Handler or factory Closure($record|null, $samplingHandler). + * @param int $factor Sample factor (e.g. 10 means every ~10th record is sampled) + */ + public function __construct(Closure|HandlerInterface $handler, int $factor) + { + parent::__construct(); + $this->handler = $handler; + $this->factor = $factor; + } + + public function isHandling(LogRecord $record): bool + { + return $this->getHandler($record)->isHandling($record); + } + + public function handle(LogRecord $record): bool + { + if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) { + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + $this->getHandler($record)->handle($record); + } + + return false === $this->bubble; + } + + /** + * Return the nested handler + * + * If the handler was provided as a factory, this will trigger the handler's instantiation. + */ + public function getHandler(LogRecord|null $record = null): HandlerInterface + { + if (!$this->handler instanceof HandlerInterface) { + $handler = ($this->handler)($record, $this); + if (!$handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory Closure should return a HandlerInterface"); + } + $this->handler = $handler; + } + + return $this->handler; + } + + /** + * @inheritDoc + */ + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($formatter); + + return $this; + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.'); + } + + /** + * @inheritDoc + */ + public function getFormatter(): FormatterInterface + { + $handler = $this->getHandler(); + if ($handler instanceof FormattableHandlerInterface) { + return $handler->getFormatter(); + } + + throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php new file mode 100644 index 0000000..5847a58 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php @@ -0,0 +1,95 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Utils; + +/** + * SendGridHandler uses the SendGrid API v3 function to send Log emails, more information in https://www.twilio.com/docs/sendgrid/for-developers/sending-email/api-getting-started + * + * @author Ricardo Fontanelli <ricardo.fontanelli@hotmail.com> + */ +class SendGridHandler extends MailHandler +{ + /** + * The SendGrid API User + * @deprecated this is not used anymore as of SendGrid API v3 + */ + protected string $apiUser; + /** + * The email addresses to which the message will be sent + * @var string[] + */ + protected array $to; + + /** + * @param string|null $apiUser Unused user as of SendGrid API v3, you can pass null or any string + * @param list<string>|string $to + * @param non-empty-string $apiHost Allows you to use another endpoint (e.g. api.eu.sendgrid.com) + * @throws MissingExtensionException If the curl extension is missing + */ + public function __construct( + string|null $apiUser, + protected string $apiKey, + protected string $from, + array|string $to, + protected string $subject, + int|string|Level $level = Level::Error, + bool $bubble = true, + /** @var non-empty-string */ + private readonly string $apiHost = 'api.sendgrid.com', + ) { + if (!\extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler'); + } + + $this->to = (array) $to; + // @phpstan-ignore property.deprecated + $this->apiUser = $apiUser ?? ''; + parent::__construct($level, $bubble); + } + + protected function send(string $content, array $records): void + { + $body = []; + $body['personalizations'] = []; + $body['from']['email'] = $this->from; + foreach ($this->to as $recipient) { + $body['personalizations'][]['to'][]['email'] = $recipient; + } + $body['subject'] = $this->subject; + + if ($this->isHtmlBody($content)) { + $body['content'][] = [ + 'type' => 'text/html', + 'value' => $content, + ]; + } else { + $body['content'][] = [ + 'type' => 'text/plain', + 'value' => $content, + ]; + } + $ch = curl_init(); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Content-Type: application/json', + 'Authorization: Bearer '.$this->apiKey, + ]); + curl_setopt($ch, CURLOPT_URL, 'https://'.$this->apiHost.'/v3/mail/send'); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, Utils::jsonEncode($body)); + + Curl\Util::execute($ch, 2); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php b/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php new file mode 100644 index 0000000..0e46c2d --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php @@ -0,0 +1,381 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\Slack; + +use Monolog\Level; +use Monolog\Utils; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; + +/** + * Slack record utility helping to log to Slack webhooks or API. + * + * @author Greg Kedzierski <greg@gregkedzierski.com> + * @author Haralan Dobrev <hkdobrev@gmail.com> + * @see https://api.slack.com/incoming-webhooks + * @see https://api.slack.com/docs/message-attachments + */ +class SlackRecord +{ + public const COLOR_DANGER = 'danger'; + + public const COLOR_WARNING = 'warning'; + + public const COLOR_GOOD = 'good'; + + public const COLOR_DEFAULT = '#e3e4e6'; + + /** + * Slack channel (encoded ID or name) + */ + private string|null $channel; + + /** + * Name of a bot + */ + private string|null $username; + + /** + * User icon e.g. 'ghost', 'http://example.com/user.png' + */ + private string|null $userIcon; + + /** + * Whether the message should be added to Slack as attachment (plain text otherwise) + */ + private bool $useAttachment; + + /** + * Whether the the context/extra messages added to Slack as attachments are in a short style + */ + private bool $useShortAttachment; + + /** + * Whether the attachment should include context and extra data + */ + private bool $includeContextAndExtra; + + /** + * Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + * @var string[] + */ + private array $excludeFields; + + private FormatterInterface|null $formatter; + + private NormalizerFormatter $normalizerFormatter; + + /** + * @param string[] $excludeFields + */ + public function __construct( + ?string $channel = null, + ?string $username = null, + bool $useAttachment = true, + ?string $userIcon = null, + bool $useShortAttachment = false, + bool $includeContextAndExtra = false, + array $excludeFields = [], + FormatterInterface|null $formatter = null + ) { + $this + ->setChannel($channel) + ->setUsername($username) + ->useAttachment($useAttachment) + ->setUserIcon($userIcon) + ->useShortAttachment($useShortAttachment) + ->includeContextAndExtra($includeContextAndExtra) + ->excludeFields($excludeFields) + ->setFormatter($formatter); + + if ($this->includeContextAndExtra) { + $this->normalizerFormatter = new NormalizerFormatter(); + } + } + + /** + * Returns required data in format that Slack + * is expecting. + * + * @phpstan-return mixed[] + */ + public function getSlackData(LogRecord $record): array + { + $dataArray = []; + + if ($this->username !== null) { + $dataArray['username'] = $this->username; + } + + if ($this->channel !== null) { + $dataArray['channel'] = $this->channel; + } + + if ($this->formatter !== null && !$this->useAttachment) { + $message = $this->formatter->format($record); + } else { + $message = $record->message; + } + + $recordData = $this->removeExcludedFields($record); + + if ($this->useAttachment) { + $attachment = [ + 'fallback' => $message, + 'text' => $message, + 'color' => $this->getAttachmentColor($record->level), + 'fields' => [], + 'mrkdwn_in' => ['fields'], + 'ts' => $recordData['datetime']->getTimestamp(), + 'footer' => $this->username, + 'footer_icon' => $this->userIcon, + ]; + + if ($this->useShortAttachment) { + $attachment['title'] = $recordData['level_name']; + } else { + $attachment['title'] = 'Message'; + $attachment['fields'][] = $this->generateAttachmentField('Level', $recordData['level_name']); + } + + if ($this->includeContextAndExtra) { + foreach (['extra', 'context'] as $key) { + if (!isset($recordData[$key]) || \count($recordData[$key]) === 0) { + continue; + } + + if ($this->useShortAttachment) { + $attachment['fields'][] = $this->generateAttachmentField( + $key, + $recordData[$key] + ); + } else { + // Add all extra fields as individual fields in attachment + $attachment['fields'] = array_merge( + $attachment['fields'], + $this->generateAttachmentFields($recordData[$key]) + ); + } + } + } + + $dataArray['attachments'] = [$attachment]; + } else { + $dataArray['text'] = $message; + } + + if ($this->userIcon !== null) { + if (false !== ($iconUrl = filter_var($this->userIcon, FILTER_VALIDATE_URL))) { + $dataArray['icon_url'] = $iconUrl; + } else { + $dataArray['icon_emoji'] = ":{$this->userIcon}:"; + } + } + + return $dataArray; + } + + /** + * Returns a Slack message attachment color associated with + * provided level. + */ + public function getAttachmentColor(Level $level): string + { + return match ($level) { + Level::Error, Level::Critical, Level::Alert, Level::Emergency => static::COLOR_DANGER, + Level::Warning => static::COLOR_WARNING, + Level::Info, Level::Notice => static::COLOR_GOOD, + Level::Debug => static::COLOR_DEFAULT + }; + } + + /** + * Stringifies an array of key/value pairs to be used in attachment fields + * + * @param mixed[] $fields + */ + public function stringify(array $fields): string + { + /** @var array<array<mixed>|bool|float|int|string|null> $normalized */ + $normalized = $this->normalizerFormatter->normalizeValue($fields); + + $hasSecondDimension = \count(array_filter($normalized, 'is_array')) > 0; + $hasOnlyNonNumericKeys = \count(array_filter(array_keys($normalized), 'is_numeric')) === 0; + + return $hasSecondDimension || $hasOnlyNonNumericKeys + ? Utils::jsonEncode($normalized, JSON_PRETTY_PRINT|Utils::DEFAULT_JSON_FLAGS) + : Utils::jsonEncode($normalized, Utils::DEFAULT_JSON_FLAGS); + } + + /** + * Channel used by the bot when posting + * + * @param ?string $channel + * @return $this + */ + public function setChannel(?string $channel = null): self + { + $this->channel = $channel; + + return $this; + } + + /** + * Username used by the bot when posting + * + * @param ?string $username + * @return $this + */ + public function setUsername(?string $username = null): self + { + $this->username = $username; + + return $this; + } + + /** + * @return $this + */ + public function useAttachment(bool $useAttachment = true): self + { + $this->useAttachment = $useAttachment; + + return $this; + } + + /** + * @return $this + */ + public function setUserIcon(?string $userIcon = null): self + { + $this->userIcon = $userIcon; + + if (\is_string($userIcon)) { + $this->userIcon = trim($userIcon, ':'); + } + + return $this; + } + + /** + * @return $this + */ + public function useShortAttachment(bool $useShortAttachment = false): self + { + $this->useShortAttachment = $useShortAttachment; + + return $this; + } + + /** + * @return $this + */ + public function includeContextAndExtra(bool $includeContextAndExtra = false): self + { + $this->includeContextAndExtra = $includeContextAndExtra; + + if ($this->includeContextAndExtra) { + $this->normalizerFormatter = new NormalizerFormatter(); + } + + return $this; + } + + /** + * @param string[] $excludeFields + * @return $this + */ + public function excludeFields(array $excludeFields = []): self + { + $this->excludeFields = $excludeFields; + + return $this; + } + + /** + * @return $this + */ + public function setFormatter(?FormatterInterface $formatter = null): self + { + $this->formatter = $formatter; + + return $this; + } + + /** + * Generates attachment field + * + * @param string|mixed[] $value + * + * @return array{title: string, value: string, short: false} + */ + private function generateAttachmentField(string $title, $value): array + { + $value = \is_array($value) + ? sprintf('```%s```', substr($this->stringify($value), 0, 1990)) + : $value; + + return [ + 'title' => ucfirst($title), + 'value' => $value, + 'short' => false, + ]; + } + + /** + * Generates a collection of attachment fields from array + * + * @param mixed[] $data + * + * @return array<array{title: string, value: string, short: false}> + */ + private function generateAttachmentFields(array $data): array + { + /** @var array<array<mixed>|string> $normalized */ + $normalized = $this->normalizerFormatter->normalizeValue($data); + + $fields = []; + foreach ($normalized as $key => $value) { + $fields[] = $this->generateAttachmentField((string) $key, $value); + } + + return $fields; + } + + /** + * Get a copy of record with fields excluded according to $this->excludeFields + * + * @return mixed[] + */ + private function removeExcludedFields(LogRecord $record): array + { + $recordData = $record->toArray(); + foreach ($this->excludeFields as $field) { + $keys = explode('.', $field); + $node = &$recordData; + $lastKey = end($keys); + foreach ($keys as $key) { + if (!isset($node[$key])) { + break; + } + if ($lastKey === $key) { + unset($node[$key]); + break; + } + $node = &$node[$key]; + } + } + + return $recordData; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php new file mode 100644 index 0000000..2a34dda --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php @@ -0,0 +1,267 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Level; +use Monolog\Utils; +use Monolog\Handler\Slack\SlackRecord; +use Monolog\LogRecord; + +/** + * Sends notifications through Slack API + * + * @author Greg Kedzierski <greg@gregkedzierski.com> + * @see https://api.slack.com/ + */ +class SlackHandler extends SocketHandler +{ + /** + * Slack API token + */ + private string $token; + + /** + * Instance of the SlackRecord util class preparing data for Slack API. + */ + private SlackRecord $slackRecord; + + /** + * @param string $token Slack API token + * @param string $channel Slack channel (encoded ID or name) + * @param string|null $username Name of a bot + * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise) + * @param string|null $iconEmoji The emoji name to use (or null) + * @param bool $useShortAttachment Whether the context/extra messages added to Slack as attachments are in a short style + * @param bool $includeContextAndExtra Whether the attachment should include context and extra data + * @param string[] $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + * @throws MissingExtensionException If no OpenSSL PHP extension configured + */ + public function __construct( + string $token, + string $channel, + ?string $username = null, + bool $useAttachment = true, + ?string $iconEmoji = null, + $level = Level::Critical, + bool $bubble = true, + bool $useShortAttachment = false, + bool $includeContextAndExtra = false, + array $excludeFields = [], + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + if (!\extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler'); + } + + parent::__construct( + 'ssl://slack.com:443', + $level, + $bubble, + $persistent, + $timeout, + $writingTimeout, + $connectionTimeout, + $chunkSize + ); + + $this->slackRecord = new SlackRecord( + $channel, + $username, + $useAttachment, + $iconEmoji, + $useShortAttachment, + $includeContextAndExtra, + $excludeFields + ); + + $this->token = $token; + } + + public function getSlackRecord(): SlackRecord + { + return $this->slackRecord; + } + + public function getToken(): string + { + return $this->token; + } + + /** + * @inheritDoc + */ + protected function generateDataStream(LogRecord $record): string + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the body of API call + */ + private function buildContent(LogRecord $record): string + { + $dataArray = $this->prepareContentData($record); + + return http_build_query($dataArray); + } + + /** + * @return string[] + */ + protected function prepareContentData(LogRecord $record): array + { + $dataArray = $this->slackRecord->getSlackData($record); + $dataArray['token'] = $this->token; + + if (isset($dataArray['attachments']) && \is_array($dataArray['attachments']) && \count($dataArray['attachments']) > 0) { + $dataArray['attachments'] = Utils::jsonEncode($dataArray['attachments']); + } + + return $dataArray; + } + + /** + * Builds the header of the API Call + */ + private function buildHeader(string $content): string + { + $header = "POST /api/chat.postMessage HTTP/1.1\r\n"; + $header .= "Host: slack.com\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . \strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + parent::write($record); + $this->finalizeWrite(); + } + + /** + * Finalizes the request by reading some bytes and then closing the socket + * + * If we do not read some but close the socket too early, slack sometimes + * drops the request entirely. + */ + protected function finalizeWrite(): void + { + $res = $this->getResource(); + if (\is_resource($res)) { + @fread($res, 2048); + } + $this->closeSocket(); + } + + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + parent::setFormatter($formatter); + $this->slackRecord->setFormatter($formatter); + + return $this; + } + + public function getFormatter(): FormatterInterface + { + $formatter = parent::getFormatter(); + $this->slackRecord->setFormatter($formatter); + + return $formatter; + } + + /** + * Channel used by the bot when posting + * + * @return $this + */ + public function setChannel(string $channel): self + { + $this->slackRecord->setChannel($channel); + + return $this; + } + + /** + * Username used by the bot when posting + * + * @return $this + */ + public function setUsername(string $username): self + { + $this->slackRecord->setUsername($username); + + return $this; + } + + /** + * @return $this + */ + public function useAttachment(bool $useAttachment): self + { + $this->slackRecord->useAttachment($useAttachment); + + return $this; + } + + /** + * @return $this + */ + public function setIconEmoji(string $iconEmoji): self + { + $this->slackRecord->setUserIcon($iconEmoji); + + return $this; + } + + /** + * @return $this + */ + public function useShortAttachment(bool $useShortAttachment): self + { + $this->slackRecord->useShortAttachment($useShortAttachment); + + return $this; + } + + /** + * @return $this + */ + public function includeContextAndExtra(bool $includeContextAndExtra): self + { + $this->slackRecord->includeContextAndExtra($includeContextAndExtra); + + return $this; + } + + /** + * @param string[] $excludeFields + * @return $this + */ + public function excludeFields(array $excludeFields): self + { + $this->slackRecord->excludeFields($excludeFields); + + return $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php new file mode 100644 index 0000000..f265d80 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php @@ -0,0 +1,130 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Level; +use Monolog\Utils; +use Monolog\Handler\Slack\SlackRecord; +use Monolog\LogRecord; + +/** + * Sends notifications through Slack Webhooks + * + * @author Haralan Dobrev <hkdobrev@gmail.com> + * @see https://api.slack.com/incoming-webhooks + */ +class SlackWebhookHandler extends AbstractProcessingHandler +{ + /** + * Slack Webhook token + * + * @var non-empty-string + */ + private string $webhookUrl; + + /** + * Instance of the SlackRecord util class preparing data for Slack API. + */ + private SlackRecord $slackRecord; + + /** + * @param non-empty-string $webhookUrl Slack Webhook URL + * @param string|null $channel Slack channel (encoded ID or name) + * @param string|null $username Name of a bot + * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise) + * @param string|null $iconEmoji The emoji name to use (or null) + * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style + * @param bool $includeContextAndExtra Whether the attachment should include context and extra data + * @param string[] $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + * + * @throws MissingExtensionException If the curl extension is missing + */ + public function __construct( + string $webhookUrl, + ?string $channel = null, + ?string $username = null, + bool $useAttachment = true, + ?string $iconEmoji = null, + bool $useShortAttachment = false, + bool $includeContextAndExtra = false, + $level = Level::Critical, + bool $bubble = true, + array $excludeFields = [] + ) { + if (!\extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the SlackWebhookHandler'); + } + + parent::__construct($level, $bubble); + + $this->webhookUrl = $webhookUrl; + + $this->slackRecord = new SlackRecord( + $channel, + $username, + $useAttachment, + $iconEmoji, + $useShortAttachment, + $includeContextAndExtra, + $excludeFields + ); + } + + public function getSlackRecord(): SlackRecord + { + return $this->slackRecord; + } + + public function getWebhookUrl(): string + { + return $this->webhookUrl; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $postData = $this->slackRecord->getSlackData($record); + $postString = Utils::jsonEncode($postData); + + $ch = curl_init(); + $options = [ + CURLOPT_URL => $this->webhookUrl, + CURLOPT_POST => true, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HTTPHEADER => ['Content-type: application/json'], + CURLOPT_POSTFIELDS => $postString, + ]; + + curl_setopt_array($ch, $options); + + Curl\Util::execute($ch); + } + + public function setFormatter(FormatterInterface $formatter): HandlerInterface + { + parent::setFormatter($formatter); + $this->slackRecord->setFormatter($formatter); + + return $this; + } + + public function getFormatter(): FormatterInterface + { + $formatter = parent::getFormatter(); + $this->slackRecord->setFormatter($formatter); + + return $formatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php new file mode 100644 index 0000000..c1b00e9 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php @@ -0,0 +1,443 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Stores to any socket - uses fsockopen() or pfsockopen(). + * + * @author Pablo de Leon Belloc <pablolb@gmail.com> + * @see http://php.net/manual/en/function.fsockopen.php + */ +class SocketHandler extends AbstractProcessingHandler +{ + private string $connectionString; + private float $connectionTimeout; + /** @var resource|null */ + private $resource; + private float $timeout; + private float $writingTimeout; + private int|null $lastSentBytes = null; + private int|null $chunkSize; + private bool $persistent; + private int|null $errno = null; + private string|null $errstr = null; + private float|null $lastWritingAt = null; + + /** + * @param string $connectionString Socket connection string + * @param bool $persistent Flag to enable/disable persistent connections + * @param float $timeout Socket timeout to wait until the request is being aborted + * @param float $writingTimeout Socket timeout to wait until the request should've been sent/written + * @param float|null $connectionTimeout Socket connect timeout to wait until the connection should've been + * established + * @param int|null $chunkSize Sets the chunk size. Only has effect during connection in the writing cycle + * + * @throws \InvalidArgumentException If an invalid timeout value (less than 0) is passed. + * + * @psalm-taint-sink ssrf $connectionString + */ + public function __construct( + string $connectionString, + $level = Level::Debug, + bool $bubble = true, + bool $persistent = false, + float $timeout = 0.0, + float $writingTimeout = 10.0, + ?float $connectionTimeout = null, + ?int $chunkSize = null + ) { + parent::__construct($level, $bubble); + $this->connectionString = $connectionString; + + if ($connectionTimeout !== null) { + $this->validateTimeout($connectionTimeout); + } + + $this->connectionTimeout = $connectionTimeout ?? (float) \ini_get('default_socket_timeout'); + $this->persistent = $persistent; + $this->validateTimeout($timeout); + $this->timeout = $timeout; + $this->validateTimeout($writingTimeout); + $this->writingTimeout = $writingTimeout; + $this->chunkSize = $chunkSize; + } + + /** + * Connect (if necessary) and write to the socket + * + * @inheritDoc + * + * @throws \UnexpectedValueException + * @throws \RuntimeException + */ + protected function write(LogRecord $record): void + { + $this->connectIfNotConnected(); + $data = $this->generateDataStream($record); + $this->writeToSocket($data); + } + + /** + * We will not close a PersistentSocket instance so it can be reused in other requests. + */ + public function close(): void + { + if (!$this->isPersistent()) { + $this->closeSocket(); + } + } + + /** + * Close socket, if open + */ + public function closeSocket(): void + { + if (\is_resource($this->resource)) { + fclose($this->resource); + $this->resource = null; + } + } + + /** + * Set socket connection to be persistent. It only has effect before the connection is initiated. + * + * @return $this + */ + public function setPersistent(bool $persistent): self + { + $this->persistent = $persistent; + + return $this; + } + + /** + * Set connection timeout. Only has effect before we connect. + * + * @see http://php.net/manual/en/function.fsockopen.php + * @return $this + */ + public function setConnectionTimeout(float $seconds): self + { + $this->validateTimeout($seconds); + $this->connectionTimeout = $seconds; + + return $this; + } + + /** + * Set write timeout. Only has effect before we connect. + * + * @see http://php.net/manual/en/function.stream-set-timeout.php + * @return $this + */ + public function setTimeout(float $seconds): self + { + $this->validateTimeout($seconds); + $this->timeout = $seconds; + + return $this; + } + + /** + * Set writing timeout. Only has effect during connection in the writing cycle. + * + * @param float $seconds 0 for no timeout + * @return $this + */ + public function setWritingTimeout(float $seconds): self + { + $this->validateTimeout($seconds); + $this->writingTimeout = $seconds; + + return $this; + } + + /** + * Set chunk size. Only has effect during connection in the writing cycle. + * + * @return $this + */ + public function setChunkSize(int $bytes): self + { + $this->chunkSize = $bytes; + + return $this; + } + + /** + * Get current connection string + */ + public function getConnectionString(): string + { + return $this->connectionString; + } + + /** + * Get persistent setting + */ + public function isPersistent(): bool + { + return $this->persistent; + } + + /** + * Get current connection timeout setting + */ + public function getConnectionTimeout(): float + { + return $this->connectionTimeout; + } + + /** + * Get current in-transfer timeout + */ + public function getTimeout(): float + { + return $this->timeout; + } + + /** + * Get current local writing timeout + */ + public function getWritingTimeout(): float + { + return $this->writingTimeout; + } + + /** + * Get current chunk size + */ + public function getChunkSize(): ?int + { + return $this->chunkSize; + } + + /** + * Check to see if the socket is currently available. + * + * UDP might appear to be connected but might fail when writing. See http://php.net/fsockopen for details. + */ + public function isConnected(): bool + { + return \is_resource($this->resource) + && !feof($this->resource); // on TCP - other party can close connection. + } + + /** + * Wrapper to allow mocking + * + * @return resource|false + */ + protected function pfsockopen() + { + return @pfsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout); + } + + /** + * Wrapper to allow mocking + * + * @return resource|false + */ + protected function fsockopen() + { + return @fsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout); + } + + /** + * Wrapper to allow mocking + * + * @see http://php.net/manual/en/function.stream-set-timeout.php + */ + protected function streamSetTimeout(): bool + { + $seconds = floor($this->timeout); + $microseconds = round(($this->timeout - $seconds) * 1e6); + + if (!\is_resource($this->resource)) { + throw new \LogicException('streamSetTimeout called but $this->resource is not a resource'); + } + + return stream_set_timeout($this->resource, (int) $seconds, (int) $microseconds); + } + + /** + * Wrapper to allow mocking + * + * @see http://php.net/manual/en/function.stream-set-chunk-size.php + * + * @return int|false + */ + protected function streamSetChunkSize(): int|bool + { + if (!\is_resource($this->resource)) { + throw new \LogicException('streamSetChunkSize called but $this->resource is not a resource'); + } + + if (null === $this->chunkSize) { + throw new \LogicException('streamSetChunkSize called but $this->chunkSize is not set'); + } + + return stream_set_chunk_size($this->resource, $this->chunkSize); + } + + /** + * Wrapper to allow mocking + * + * @return int|false + */ + protected function fwrite(string $data): int|bool + { + if (!\is_resource($this->resource)) { + throw new \LogicException('fwrite called but $this->resource is not a resource'); + } + + return @fwrite($this->resource, $data); + } + + /** + * Wrapper to allow mocking + * + * @return mixed[]|bool + */ + protected function streamGetMetadata(): array|bool + { + if (!\is_resource($this->resource)) { + throw new \LogicException('streamGetMetadata called but $this->resource is not a resource'); + } + + return stream_get_meta_data($this->resource); + } + + private function validateTimeout(float $value): void + { + if ($value < 0) { + throw new \InvalidArgumentException("Timeout must be 0 or a positive float (got $value)"); + } + } + + private function connectIfNotConnected(): void + { + if ($this->isConnected()) { + return; + } + $this->connect(); + } + + protected function generateDataStream(LogRecord $record): string + { + return (string) $record->formatted; + } + + /** + * @return resource|null + */ + protected function getResource() + { + return $this->resource; + } + + private function connect(): void + { + $this->createSocketResource(); + $this->setSocketTimeout(); + $this->setStreamChunkSize(); + } + + private function createSocketResource(): void + { + if ($this->isPersistent()) { + $resource = $this->pfsockopen(); + } else { + $resource = $this->fsockopen(); + } + if (\is_bool($resource)) { + throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)"); + } + $this->resource = $resource; + } + + private function setSocketTimeout(): void + { + if (!$this->streamSetTimeout()) { + throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()"); + } + } + + private function setStreamChunkSize(): void + { + if (null !== $this->chunkSize && false === $this->streamSetChunkSize()) { + throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()"); + } + } + + private function writeToSocket(string $data): void + { + $length = \strlen($data); + $sent = 0; + $this->lastSentBytes = $sent; + $this->lastWritingAt = microtime(true); + while ($this->isConnected() && $sent < $length) { + if (0 === $sent) { + $chunk = $this->fwrite($data); + } else { + $chunk = $this->fwrite(substr($data, $sent)); + } + // PHP leaves the stream's timed_out flag set after a write times out, + // so a failed socket is closed and the next write reconnects + if ($chunk === false) { + $this->closeSocket(); + throw new \RuntimeException("Could not write to socket"); + } + $sent += $chunk; + $socketInfo = $this->streamGetMetadata(); + if (\is_array($socketInfo) && (bool) $socketInfo['timed_out']) { + $this->closeSocket(); + throw new \RuntimeException("Write timed-out"); + } + + if ($this->writingIsTimedOut($sent)) { + throw new \RuntimeException("Write timed-out, no data sent for `{$this->writingTimeout}` seconds, probably we got disconnected (sent $sent of $length)"); + } + } + if (!$this->isConnected() && $sent < $length) { + throw new \RuntimeException("End-of-file reached, probably we got disconnected (sent $sent of $length)"); + } + } + + private function writingIsTimedOut(int $sent): bool + { + // convert to ms + if (0.0 === $this->writingTimeout) { + return false; + } + + if ($sent !== $this->lastSentBytes) { + $this->lastWritingAt = microtime(true); + $this->lastSentBytes = $sent; + + return false; + } else { + usleep(100); + } + + if ((microtime(true) - (float) $this->lastWritingAt) >= $this->writingTimeout) { + $this->closeSocket(); + + return true; + } + + return false; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php new file mode 100644 index 0000000..1d28b65 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php @@ -0,0 +1,61 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Aws\Sqs\SqsClient; +use Monolog\Level; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Writes to any sqs queue. + * + * @author Martijn van Calker <git@amvc.nl> + */ +class SqsHandler extends AbstractProcessingHandler +{ + /** 256 KB in bytes - maximum message size in SQS */ + protected const MAX_MESSAGE_SIZE = 262144; + /** 100 KB in bytes - head message size for new error log */ + protected const HEAD_MESSAGE_SIZE = 102400; + + private SqsClient $client; + private string $queueUrl; + + public function __construct(SqsClient $sqsClient, string $queueUrl, int|string|Level $level = Level::Debug, bool $bubble = true) + { + parent::__construct($level, $bubble); + + $this->client = $sqsClient; + $this->queueUrl = $queueUrl; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + if (!isset($record->formatted) || 'string' !== \gettype($record->formatted)) { + throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string' . Utils::getRecordMessageForException($record)); + } + + $messageBody = $record->formatted; + if (\strlen($messageBody) >= static::MAX_MESSAGE_SIZE) { + $messageBody = Utils::substr($messageBody, 0, static::HEAD_MESSAGE_SIZE); + } + + $this->client->sendMessage([ + 'QueueUrl' => $this->queueUrl, + 'MessageBody' => $messageBody, + ]); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php new file mode 100644 index 0000000..8440e28 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php @@ -0,0 +1,311 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Stores to any stream resource + * + * Can be used to store into php://stderr, remote and local files, etc. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class StreamHandler extends AbstractProcessingHandler +{ + protected const MAX_CHUNK_SIZE = 2147483647; + /** 10MB */ + protected const DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024; + protected int $streamChunkSize; + /** @var resource|null */ + protected $stream; + protected string|null $url = null; + private string|null $errorMessage = null; + protected int|null $filePermission; + protected bool $useLocking; + protected string $fileOpenMode; + /** @var true|null */ + private bool|null $dirCreated = null; + private bool $retrying = false; + private int|null $inodeUrl = null; + + /** + * @param resource|string $stream If a missing path can't be created, an UnexpectedValueException will be thrown on first write + * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) + * @param bool $useLocking Try to lock log file before doing any writes + * @param string $fileOpenMode The fopen() mode used when opening a file, if $stream is a file path + * + * @throws \InvalidArgumentException If stream is not a resource or string + * + * @psalm-taint-sink file $stream + */ + public function __construct($stream, int|string|Level $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false, string $fileOpenMode = 'a') + { + parent::__construct($level, $bubble); + + if (($phpMemoryLimit = Utils::expandIniShorthandBytes(\ini_get('memory_limit'))) !== false) { + if ($phpMemoryLimit > 0) { + // use max 10% of allowed memory for the chunk size, and at least 100KB + $this->streamChunkSize = min(static::MAX_CHUNK_SIZE, max((int) ($phpMemoryLimit / 10), 100 * 1024)); + } else { + // memory is unlimited, set to the default 10MB + $this->streamChunkSize = static::DEFAULT_CHUNK_SIZE; + } + } else { + // no memory limit information, set to the default 10MB + $this->streamChunkSize = static::DEFAULT_CHUNK_SIZE; + } + + if (\is_resource($stream)) { + $this->stream = $stream; + + stream_set_chunk_size($this->stream, $this->streamChunkSize); + } elseif (\is_string($stream)) { + $this->url = Utils::canonicalizePath($stream); + } else { + throw new \InvalidArgumentException('A stream must either be a resource or a string.'); + } + + $this->fileOpenMode = $fileOpenMode; + $this->filePermission = $filePermission; + $this->useLocking = $useLocking; + } + + /** + * @inheritDoc + */ + public function reset(): void + { + parent::reset(); + + // auto-close on reset to make sure we periodically close the file in long running processes + // as long as they correctly call reset() between jobs + if ($this->url !== null && $this->url !== 'php://memory') { + $this->close(); + } + } + + /** + * @inheritDoc + */ + public function close(): void + { + if (null !== $this->url && \is_resource($this->stream)) { + fclose($this->stream); + } + $this->stream = null; + $this->dirCreated = null; + } + + /** + * Return the currently active stream if it is open + * + * @return resource|null + */ + public function getStream() + { + return $this->stream; + } + + /** + * Return the stream URL if it was configured with a URL and not an active resource + */ + public function getUrl(): ?string + { + return $this->url; + } + + public function getStreamChunkSize(): int + { + return $this->streamChunkSize; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + if ($this->hasUrlInodeWasChanged()) { + $this->close(); + $this->write($record); + + return; + } + + if (!\is_resource($this->stream)) { + $url = $this->url; + if (null === $url || '' === $url) { + throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().' . Utils::getRecordMessageForException($record)); + } + $this->createDir($url); + $this->errorMessage = null; + // forwarding to $this->customErrorHandler using a closure to make the + // private method accessible, see https://github.com/Seldaek/monolog/issues/1866 + set_error_handler(function (int $code, string $msg) { + return $this->customErrorHandler($msg); + }); + + try { + $stream = fopen($url, $this->fileOpenMode); + if ($this->filePermission !== null) { + @chmod($url, $this->filePermission); + } + } finally { + restore_error_handler(); + } + if (!\is_resource($stream)) { + $this->stream = null; + + throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $url) . Utils::getRecordMessageForException($record)); + } + stream_set_chunk_size($stream, $this->streamChunkSize); + $this->stream = $stream; + $this->inodeUrl = $this->getInodeFromUrl(); + } + + $stream = $this->stream; + if ($this->useLocking) { + // ignoring errors here, there's not much we can do about them + flock($stream, LOCK_EX); + } + + $this->errorMessage = null; + // forwarding to $this->customErrorHandler using a closure to make the + // private method accessible, see https://github.com/Seldaek/monolog/issues/1866 + set_error_handler(function (int $code, string $msg) { + return $this->customErrorHandler($msg); + }); + try { + $this->streamWrite($stream, $record); + } finally { + restore_error_handler(); + } + if ($this->errorMessage !== null) { + $error = $this->errorMessage; + // close the resource if possible to reopen it, and retry the failed write + if (!$this->retrying && $this->url !== null && $this->url !== 'php://memory') { + $this->retrying = true; + $this->close(); + $this->write($record); + + return; + } + + throw new \UnexpectedValueException('Writing to the log file failed: '.$error . Utils::getRecordMessageForException($record)); + } + + $this->retrying = false; + if ($this->useLocking) { + flock($stream, LOCK_UN); + } + } + + /** + * Write to stream + * @param resource $stream + */ + protected function streamWrite($stream, LogRecord $record): void + { + $data = (string) $record->formatted; + $length = \strlen($data); + $written = 0; + + // fwrite() may write only part of the data on non-blocking streams, so loop until it is all written, see https://github.com/Seldaek/monolog/issues/2011 + while ($written < $length) { + $result = fwrite($stream, substr($data, $written)); + if ($result === false) { + // write failed, let the customErrorHandler/errorMessage logic in write() report and retry it + break; + } + if ($result === 0) { + // the non-blocking stream's buffer is full, wait until it can be written to again instead of busy-looping or dropping the rest of the record + $write = [$stream]; + $read = $except = []; + stream_select($read, $write, $except, null); + continue; + } + $written += $result; + } + } + + /** + * @return true + */ + private function customErrorHandler(string $msg): bool + { + $this->errorMessage = preg_replace('{^(fopen|mkdir|fwrite)\(.*?\): }', '', $msg); + + return true; + } + + private function getDirFromStream(string $stream): ?string + { + $pos = strpos($stream, '://'); + if ($pos === false) { + return \dirname($stream); + } + + if ('file://' === substr($stream, 0, 7)) { + return \dirname(substr($stream, 7)); + } + + return null; + } + + private function createDir(string $url): void + { + // Do not try to create dir if it has already been tried. + if (true === $this->dirCreated) { + return; + } + + $dir = $this->getDirFromStream($url); + if (null !== $dir && !is_dir($dir)) { + $this->errorMessage = null; + // forwarding to $this->customErrorHandler using a closure to make the + // private method accessible, see https://github.com/Seldaek/monolog/issues/1866 + set_error_handler(function (int $code, string $msg) { + return $this->customErrorHandler($msg); + }); + $status = mkdir($dir, 0777, true); + restore_error_handler(); + if (false === $status && !is_dir($dir) && strpos((string) $this->errorMessage, 'File exists') === false) { + throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and it could not be created: '.$this->errorMessage, $dir)); + } + } + $this->dirCreated = true; + } + + private function getInodeFromUrl(): ?int + { + if ($this->url === null || str_starts_with($this->url, 'php://')) { + return null; + } + + $inode = @fileinode($this->url); + + return $inode === false ? null : $inode; + } + + private function hasUrlInodeWasChanged(): bool + { + if ($this->inodeUrl === null || $this->retrying || $this->inodeUrl === $this->getInodeFromUrl()) { + return false; + } + + $this->retrying = true; + + return true; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php new file mode 100644 index 0000000..33aa4fd --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php @@ -0,0 +1,109 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Closure; +use Monolog\Level; +use Monolog\LogRecord; +use Monolog\Utils; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; +use Symfony\Component\Mailer\MailerInterface; +use Symfony\Component\Mailer\Transport\TransportInterface; +use Symfony\Component\Mime\Email; + +/** + * SymfonyMailerHandler uses Symfony's Mailer component to send the emails + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class SymfonyMailerHandler extends MailHandler +{ + protected MailerInterface|TransportInterface $mailer; + /** @var Email|Closure(string, LogRecord[]): Email */ + private Email|Closure $emailTemplate; + + /** + * @phpstan-param Email|Closure(string, LogRecord[]): Email $email + * + * @param MailerInterface|TransportInterface $mailer The mailer to use + * @param Closure|Email $email An email template, the subject/body will be replaced + */ + public function __construct($mailer, Email|Closure $email, int|string|Level $level = Level::Error, bool $bubble = true) + { + parent::__construct($level, $bubble); + + $this->mailer = $mailer; + $this->emailTemplate = $email; + } + + /** + * {@inheritDoc} + */ + protected function send(string $content, array $records): void + { + $this->mailer->send($this->buildMessage($content, $records)); + } + + /** + * Gets the formatter for the Swift_Message subject. + * + * @param string|null $format The format of the subject + */ + protected function getSubjectFormatter(?string $format): FormatterInterface + { + return new LineFormatter($format); + } + + /** + * Creates instance of Email to be sent + * + * @param string $content formatted email body to be sent + * @param LogRecord[] $records Log records that formed the content + */ + protected function buildMessage(string $content, array $records): Email + { + $message = null; + if ($this->emailTemplate instanceof Email) { + $message = clone $this->emailTemplate; + } elseif (\is_callable($this->emailTemplate)) { + $message = ($this->emailTemplate)($content, $records); + } + + if (!$message instanceof Email) { + $record = reset($records); + + throw new \InvalidArgumentException('Could not resolve message as instance of Email or a callable returning it' . ($record instanceof LogRecord ? Utils::getRecordMessageForException($record) : '')); + } + + if (\count($records) > 0) { + $subjectFormatter = $this->getSubjectFormatter($message->getSubject()); + $message->subject($subjectFormatter->format($this->getHighestRecord($records))); + } + + if ($this->isHtmlBody($content)) { + if (null !== ($charset = $message->getHtmlCharset())) { + $message->html($content, $charset); + } else { + $message->html($content); + } + } else { + if (null !== ($charset = $message->getTextCharset())) { + $message->text($content, $charset); + } else { + $message->text($content); + } + } + + return $message->date(new \DateTimeImmutable()); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php new file mode 100644 index 0000000..f3d7674 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php @@ -0,0 +1,63 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Logs to syslog service. + * + * usage example: + * + * $log = new Logger('application'); + * $syslog = new SyslogHandler('myfacility', 'local6'); + * $formatter = new LineFormatter("%channel%.%level_name%: %message% %extra%"); + * $syslog->setFormatter($formatter); + * $log->pushHandler($syslog); + * + * @author Sven Paulus <sven@karlsruhe.org> + */ +class SyslogHandler extends AbstractSyslogHandler +{ + protected string $ident; + protected int $logopts; + + /** + * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant + * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID + */ + public function __construct(string $ident, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, int $logopts = LOG_PID) + { + parent::__construct($facility, $level, $bubble); + + $this->ident = $ident; + $this->logopts = $logopts; + } + + /** + * @inheritDoc + */ + public function close(): void + { + closelog(); + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + openlog($this->ident, $this->logopts, $this->facility); + syslog($this->toSyslogPriority($record->level), (string) $record->formatted); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php new file mode 100644 index 0000000..6c8dd15 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php @@ -0,0 +1,87 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\SyslogUdp; + +use Monolog\Utils; +use Socket; + +class UdpSocket +{ + protected const DATAGRAM_MAX_LENGTH = 65023; + + protected string $ip; + protected int $port; + protected int $maxLength; + protected ?Socket $socket = null; + + /** + * @param ?int $maxLength Maximum size in bytes of a single UDP datagram sent to $ip:$port. + * Defaults to the largest a UDP payload can theoretically be, but + * messages that size get fragmented at the IP level, and many routers + * and firewalls drop fragmented UDP packets, which silently truncates + * or loses the log entry on the receiving end. Passing a value that + * fits within the path MTU (eg. 1024) avoids that. + */ + public function __construct(string $ip, int $port = 514, ?int $maxLength = null) + { + $this->ip = $ip; + $this->port = $port; + $this->maxLength = $maxLength ?? self::DATAGRAM_MAX_LENGTH; + } + + public function write(string $line, string $header = ""): void + { + $this->send($this->assembleMessage($line, $header)); + } + + public function close(): void + { + if ($this->socket instanceof Socket) { + socket_close($this->socket); + $this->socket = null; + } + } + + protected function getSocket(): Socket + { + if (null !== $this->socket) { + return $this->socket; + } + + $domain = AF_INET; + $protocol = SOL_UDP; + // Check if we are using unix sockets. + if ($this->port === 0) { + $domain = AF_UNIX; + $protocol = IPPROTO_IP; + } + + $socket = socket_create($domain, SOCK_DGRAM, $protocol); + if ($socket instanceof Socket) { + return $this->socket = $socket; + } + + throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create'); + } + + protected function send(string $chunk): void + { + socket_sendto($this->getSocket(), $chunk, \strlen($chunk), 0, $this->ip, $this->port); + } + + protected function assembleMessage(string $line, string $header): string + { + $chunkSize = $this->maxLength - \strlen($header); + + return $header . Utils::substr($line, 0, $chunkSize); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php new file mode 100644 index 0000000..76f094b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php @@ -0,0 +1,162 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use DateTimeInterface; +use Monolog\Handler\SyslogUdp\UdpSocket; +use Monolog\Level; +use Monolog\LogRecord; +use Monolog\Utils; + +/** + * A Handler for logging to a remote syslogd server. + * + * @author Jesper Skovgaard Nielsen <nulpunkt@gmail.com> + * @author Dominik Kukacka <dominik.kukacka@gmail.com> + */ +class SyslogUdpHandler extends AbstractSyslogHandler +{ + const RFC3164 = 0; + const RFC5424 = 1; + const RFC5424e = 2; + + /** @var array<self::RFC*, string> */ + private array $dateFormats = [ + self::RFC3164 => 'M d H:i:s', + self::RFC5424 => \DateTime::RFC3339, + self::RFC5424e => \DateTime::RFC3339_EXTENDED, + ]; + + protected UdpSocket $socket; + protected string $ident; + /** @var self::RFC* */ + protected int $rfc; + + /** + * @param string $host Either IP/hostname or a path to a unix socket (port must be 0 then) + * @param int $port Port number, or 0 if $host is a unix socket + * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param string $ident Program name or tag for each log message. + * @param int $rfc RFC to format the message for. + * @param ?int $maxLength Maximum size in bytes of a single UDP datagram. Defaults to the + * largest a UDP payload can theoretically be, which risks getting + * silently truncated or dropped by routers/firewalls that reject + * fragmented UDP packets; pass a value that fits within the path + * MTU (eg. 1024) to avoid that. + * @throws MissingExtensionException when there is no socket extension + * + * @phpstan-param self::RFC* $rfc + */ + public function __construct(string $host, int $port = 514, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424, ?int $maxLength = null) + { + if (!\extension_loaded('sockets')) { + throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler'); + } + + parent::__construct($facility, $level, $bubble); + + $this->ident = $ident; + $this->rfc = $rfc; + + $this->socket = new UdpSocket($host, $port, $maxLength); + } + + protected function write(LogRecord $record): void + { + $lines = $this->splitMessageIntoLines($record->formatted); + + $header = $this->makeCommonSyslogHeader($this->toSyslogPriority($record->level), $record->datetime); + + foreach ($lines as $line) { + $this->socket->write($line, $header); + } + } + + public function close(): void + { + $this->socket->close(); + } + + /** + * @param string|string[] $message + * @return string[] + */ + private function splitMessageIntoLines($message): array + { + if (\is_array($message)) { + $message = implode("\n", $message); + } + + $lines = preg_split('/$\R?^/m', (string) $message, -1, PREG_SPLIT_NO_EMPTY); + if (false === $lines) { + $pcreErrorCode = preg_last_error(); + + throw new \RuntimeException('Could not preg_split: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); + } + + return $lines; + } + + /** + * Make common syslog header (see rfc5424 or rfc3164) + */ + protected function makeCommonSyslogHeader(int $severity, DateTimeInterface $datetime): string + { + $priority = $severity + $this->facility; + + $pid = getmypid(); + if (false === $pid) { + $pid = '-'; + } + + $hostname = gethostname(); + if (false === $hostname) { + $hostname = '-'; + } + + if ($this->rfc === self::RFC3164) { + // RFC 3164 timestamps have no zone and receivers read them as local time, so they + // follow the record's timezone (the Logger's) instead of being converted to UTC + $date = $datetime->format($this->dateFormats[$this->rfc]); + // RFC 3164 pads a day of the month below 10 with a space, not a zero (e.g. "Aug 7") + if ($date[4] === '0') { + $date[4] = ' '; + } + + return "<$priority>" . + $date . " " . + $hostname . " " . + $this->ident . "[" . $pid . "]: "; + } + + $date = $datetime->format($this->dateFormats[$this->rfc]); + + return "<$priority>1 " . + $date . " " . + $hostname . " " . + $this->ident . " " . + $pid . " - - "; + } + + /** + * Inject your own socket, mainly used for testing + * + * @return $this + */ + public function setSocket(UdpSocket $socket): self + { + $this->socket = $socket; + + return $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php new file mode 100644 index 0000000..1e7e6a4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php @@ -0,0 +1,467 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use RuntimeException; +use Monolog\Level; +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Handler sends logs to Telegram using Telegram Bot API. + * + * How to use: + * 1) Create a Telegram bot with https://telegram.me/BotFather; + * 2) Create a Telegram channel or a group where logs will be recorded; + * 3) Add the created bot from step 1 to the created channel/group from step 2. + * + * In order to create an instance of TelegramBotHandler use + * 1. The Telegram bot API key from step 1 + * 2. The channel name with the `@` prefix if you created a public channel (e.g. `@my_public_channel`), + * or the channel ID with the `-100` prefix if you created a private channel (e.g. `-1001234567890`), + * or the group ID from step 2 (e.g. `-1234567890`). + * + * @link https://core.telegram.org/bots/api + * + * @author Mazur Alexandr <alexandrmazur96@gmail.com> + */ +class TelegramBotHandler extends AbstractProcessingHandler +{ + private const BOT_API = 'https://api.telegram.org/bot'; + + /** + * The available values of parseMode according to the Telegram api documentation + */ + private const AVAILABLE_PARSE_MODES = [ + 'HTML', + 'MarkdownV2', + 'Markdown', // legacy mode without underline and strikethrough, use MarkdownV2 instead + ]; + + /** + * The maximum number of characters allowed in a message according to the Telegram api documentation + */ + private const MAX_MESSAGE_LENGTH = 4096; + + /** + * Telegram bot access token provided by BotFather. + * Create telegram bot with https://telegram.me/BotFather and use access token from it. + */ + private string $apiKey; + + /** + * Telegram channel name. + * Since to start with '@' symbol as prefix. + */ + private string $channel; + + /** + * The kind of formatting that is used for the message. + * See available options at https://core.telegram.org/bots/api#formatting-options + * or in AVAILABLE_PARSE_MODES + */ + private string|null $parseMode; + + /** + * Disables link previews for links in the message. + */ + private bool|null $disableWebPagePreview; + + /** + * Sends the message silently. Users will receive a notification with no sound. + */ + private bool|null $disableNotification; + + /** + * True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages. + * False - truncates a message that is too long. + */ + private bool $splitLongMessages; + + /** + * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests). + */ + private bool $delayBetweenMessages; + + /** + * Telegram message thread id, unique identifier for the target message thread (topic) of the forum; for forum supergroups only + * See how to get the `message_thread_id` https://stackoverflow.com/a/75178418 + */ + private int|null $topic; + + /** + * @param string $apiKey Telegram bot access token provided by BotFather + * @param string $channel Telegram channel name + * @param bool $splitLongMessages Split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages + * @param bool $delayBetweenMessages Adds delay between sending a split message according to Telegram API + * @param int $topic Telegram message thread id, unique identifier for the target message thread (topic) of the forum + * @throws MissingExtensionException If the curl extension is missing + */ + public function __construct( + string $apiKey, + string $channel, + $level = Level::Debug, + bool $bubble = true, + ?string $parseMode = null, + ?bool $disableWebPagePreview = null, + ?bool $disableNotification = null, + bool $splitLongMessages = false, + bool $delayBetweenMessages = false, + ?int $topic = null + ) { + if (!\extension_loaded('curl')) { + throw new MissingExtensionException('The curl extension is needed to use the TelegramBotHandler'); + } + + parent::__construct($level, $bubble); + + $this->apiKey = $apiKey; + $this->channel = $channel; + $this->setParseMode($parseMode); + $this->disableWebPagePreview($disableWebPagePreview); + $this->disableNotification($disableNotification); + $this->splitLongMessages($splitLongMessages); + $this->delayBetweenMessages($delayBetweenMessages); + $this->setTopic($topic); + } + + /** + * @return $this + */ + public function setParseMode(string|null $parseMode = null): self + { + if ($parseMode !== null && !\in_array($parseMode, self::AVAILABLE_PARSE_MODES, true)) { + throw new \InvalidArgumentException('Unknown parseMode, use one of these: ' . implode(', ', self::AVAILABLE_PARSE_MODES) . '.'); + } + + $this->parseMode = $parseMode; + + return $this; + } + + /** + * @return $this + */ + public function disableWebPagePreview(bool|null $disableWebPagePreview = null): self + { + $this->disableWebPagePreview = $disableWebPagePreview; + + return $this; + } + + /** + * @return $this + */ + public function disableNotification(bool|null $disableNotification = null): self + { + $this->disableNotification = $disableNotification; + + return $this; + } + + /** + * True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages. + * False - truncates a message that is too long. + * + * @return $this + */ + public function splitLongMessages(bool $splitLongMessages = false): self + { + $this->splitLongMessages = $splitLongMessages; + + return $this; + } + + /** + * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests). + * + * @return $this + */ + public function delayBetweenMessages(bool $delayBetweenMessages = false): self + { + $this->delayBetweenMessages = $delayBetweenMessages; + + return $this; + } + + /** + * @return $this + */ + public function setTopic(?int $topic = null): self + { + $this->topic = $topic; + + return $this; + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + $messages = []; + + foreach ($records as $record) { + if (!$this->isHandling($record)) { + continue; + } + + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + $messages[] = $record; + } + + if (\count($messages) > 0) { + $this->send((string) $this->getFormatter()->formatBatch($messages)); + } + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->send($record->formatted); + } + + /** + * Send request to @link https://api.telegram.org/bot on SendMessage action. + */ + protected function send(string $message): void + { + $messages = $this->handleMessageLength($message); + + foreach ($messages as $key => $msg) { + if ($this->delayBetweenMessages && $key > 0) { + sleep(1); + } + + $this->sendCurl($msg); + } + } + + /** + * Returns the Telegram Bot API base URL. + * Override in a subclass to point to a self-hosted Bot API server. + */ + protected function getBotApiUrl(): string + { + return self::BOT_API; + } + + /** + * Returns extra HTTP headers to send with every Telegram API request. + * Override in a subclass to inject custom headers (e.g. auth tokens, tracing). + * + * @return string[] + */ + protected function getCurlHeaders(): array + { + return []; + } + + protected function sendCurl(string $message): void + { + if ('' === trim($message)) { + return; + } + + $ch = curl_init(); + $url = $this->getBotApiUrl() . $this->apiKey . '/SendMessage'; + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); + $headers = $this->getCurlHeaders(); + if ($headers !== []) { + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + } + $params = [ + 'text' => $message, + 'chat_id' => $this->channel, + 'parse_mode' => $this->parseMode, + 'disable_web_page_preview' => $this->disableWebPagePreview, + 'disable_notification' => $this->disableNotification, + ]; + if ($this->topic !== null) { + $params['message_thread_id'] = $this->topic; + } + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); + + $this->validateApiResponse(Curl\Util::execute($ch)); + } + + /** + * @param string|bool $rawResult Raw response body from the Telegram API call + * @throws RuntimeException When the response is missing, non-JSON, or signals failure + */ + protected function validateApiResponse(string|bool $rawResult): void + { + if (!\is_string($rawResult)) { + throw new RuntimeException('Telegram API error. Description: No response'); + } + + $result = json_decode($rawResult, true); + + if (!\is_array($result)) { + throw new RuntimeException('Telegram API error. Description: Unexpected non-JSON response'); + } + if (($result['ok'] ?? null) !== true) { + throw new RuntimeException('Telegram API error. Description: ' . ($result['description'] ?? 'Unknown error')); + } + } + + /** + * Handle a message that is too long: truncates or splits into several + * @return string[] + */ + private function handleMessageLength(string $message): array + { + $truncatedMarker = ' (…truncated)'; + if (!$this->splitLongMessages && \strlen($message) > self::MAX_MESSAGE_LENGTH) { + $maxLength = self::MAX_MESSAGE_LENGTH - \strlen($truncatedMarker); + $truncated = Utils::substr($message, 0, $maxLength); + + if ($this->parseMode === 'HTML') { + $truncated = $this->trimPartialHtmlTag($truncated); + $closing = $this->closingHtmlTagsFor($this->updateOpenHtmlTags($truncated, [])); + + while ($truncated !== '' && \strlen($truncated . $closing) > $maxLength) { + $truncated = $this->trimPartialHtmlTag(Utils::substr($truncated, 0, -1)); + $closing = $this->closingHtmlTagsFor($this->updateOpenHtmlTags($truncated, [])); + } + + $truncated .= $closing; + } + + return [$truncated . $truncatedMarker]; + } + + if ($this->parseMode === 'HTML' && \strlen($message) > self::MAX_MESSAGE_LENGTH) { + return $this->splitHtmlMessage($message, self::MAX_MESSAGE_LENGTH); + } + + return str_split($message, self::MAX_MESSAGE_LENGTH); + } + + /** + * Splits an HTML $message into chunks of at most $maxLength characters, closing any + * tag left open at the end of a chunk and reopening it at the start of the next one, + * so that neither a tag nor a start/end tag pair is ever cut in half. + * + * @return string[] + */ + private function splitHtmlMessage(string $message, int $maxLength): array + { + $chunks = []; + $openTags = []; + $remaining = $message; + + while ($remaining !== '') { + $prefix = $this->openingHtmlTagsFor($openTags); + $slice = Utils::substr($remaining, 0, max(1, $maxLength - \strlen($prefix))); + $isLast = \strlen($slice) >= \strlen($remaining); + + if (!$isLast) { + $slice = $this->trimPartialHtmlTag($slice); + } + + $sliceOpenTags = $this->updateOpenHtmlTags($slice, $openTags); + $suffix = $isLast ? '' : $this->closingHtmlTagsFor($sliceOpenTags); + + while (!$isLast && $slice !== '' && \strlen($prefix . $slice . $suffix) > $maxLength) { + $slice = $this->trimPartialHtmlTag(Utils::substr($slice, 0, -1)); + $sliceOpenTags = $this->updateOpenHtmlTags($slice, $openTags); + $suffix = $this->closingHtmlTagsFor($sliceOpenTags); + } + + $chunks[] = $prefix . $slice . $suffix; + $remaining = Utils::substr($remaining, \strlen($slice)); + $openTags = $isLast ? [] : $sliceOpenTags; + } + + return $chunks; + } + + /** + * Backs off before a `<` that has no matching `>` yet, so $html never ends mid-tag. + */ + private function trimPartialHtmlTag(string $html): string + { + $lastLt = strrpos($html, '<'); + $lastGt = strrpos($html, '>'); + + if ($lastLt !== false && ($lastGt === false || $lastLt > $lastGt)) { + return Utils::substr($html, 0, $lastLt); + } + + return $html; + } + + /** + * Scans $html for tags, applying them onto $openTags, so the result is the set of + * tags still open after $html (tags opened before $html that $html did not close, + * plus any $html opened itself and did not close again). + * + * @param array<array{name: string, raw: string}> $openTags + * @return array<array{name: string, raw: string}> + */ + private function updateOpenHtmlTags(string $html, array $openTags): array + { + if (0 === preg_match_all('/<(\/?)([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/', $html, $matches, PREG_SET_ORDER)) { + return $openTags; + } + + foreach ($matches as $match) { + $name = strtolower($match[2]); + if ($match[1] === '/') { + for ($i = \count($openTags) - 1; $i >= 0; $i--) { + if ($openTags[$i]['name'] === $name) { + array_splice($openTags, $i, 1); + break; + } + } + } else { + $openTags[] = ['name' => $name, 'raw' => $match[0]]; + } + } + + return $openTags; + } + + /** + * @param array<array{name: string, raw: string}> $openTags + */ + private function closingHtmlTagsFor(array $openTags): string + { + $closing = ''; + foreach (array_reverse($openTags) as $tag) { + $closing .= '</' . $tag['name'] . '>'; + } + + return $closing; + } + + /** + * @param array<array{name: string, raw: string}> $openTags + */ + private function openingHtmlTagsFor(array $openTags): string + { + $opening = ''; + foreach ($openTags as $tag) { + $opening .= $tag['raw']; + } + + return $opening; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php new file mode 100644 index 0000000..cb95e79 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php @@ -0,0 +1,203 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Level; +use Monolog\Logger; +use Psr\Log\LogLevel; +use Monolog\LogRecord; +use NoDiscard; + +/** + * Used for testing purposes. + * + * It records all records and gives you access to them for verification. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @method bool hasEmergency(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasAlert(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasCritical(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasError(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasWarning(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasNotice(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasInfo(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasDebug(array{message: string, context?: mixed[]}|string $recordAssertions) + * + * @method bool hasEmergencyRecords() + * @method bool hasAlertRecords() + * @method bool hasCriticalRecords() + * @method bool hasErrorRecords() + * @method bool hasWarningRecords() + * @method bool hasNoticeRecords() + * @method bool hasInfoRecords() + * @method bool hasDebugRecords() + * + * @method bool hasEmergencyThatContains(string $message) + * @method bool hasAlertThatContains(string $message) + * @method bool hasCriticalThatContains(string $message) + * @method bool hasErrorThatContains(string $message) + * @method bool hasWarningThatContains(string $message) + * @method bool hasNoticeThatContains(string $message) + * @method bool hasInfoThatContains(string $message) + * @method bool hasDebugThatContains(string $message) + * + * @method bool hasEmergencyThatMatches(string $regex) + * @method bool hasAlertThatMatches(string $regex) + * @method bool hasCriticalThatMatches(string $regex) + * @method bool hasErrorThatMatches(string $regex) + * @method bool hasWarningThatMatches(string $regex) + * @method bool hasNoticeThatMatches(string $regex) + * @method bool hasInfoThatMatches(string $regex) + * @method bool hasDebugThatMatches(string $regex) + * + * @method bool hasEmergencyThatPasses(callable $predicate) + * @method bool hasAlertThatPasses(callable $predicate) + * @method bool hasCriticalThatPasses(callable $predicate) + * @method bool hasErrorThatPasses(callable $predicate) + * @method bool hasWarningThatPasses(callable $predicate) + * @method bool hasNoticeThatPasses(callable $predicate) + * @method bool hasInfoThatPasses(callable $predicate) + * @method bool hasDebugThatPasses(callable $predicate) + */ +class TestHandler extends AbstractProcessingHandler +{ + /** @var LogRecord[] */ + protected array $records = []; + /** @phpstan-var array<value-of<Level::VALUES>, LogRecord[]> */ + protected array $recordsByLevel = []; + private bool $skipReset = false; + + /** + * @return array<LogRecord> + */ + #[NoDiscard] + public function getRecords(): array + { + return $this->records; + } + + public function clear(): void + { + $this->records = []; + $this->recordsByLevel = []; + } + + public function reset(): void + { + if (!$this->skipReset) { + $this->clear(); + } + } + + public function setSkipReset(bool $skipReset): void + { + $this->skipReset = $skipReset; + } + + /** + * @param int|string|Level|LogLevel::* $level Logging level value or name + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + #[NoDiscard] + public function hasRecords(int|string|Level $level): bool + { + return isset($this->recordsByLevel[Logger::toMonologLevel($level)->value]); + } + + /** + * @param string|array $recordAssertions Either a message string or an array containing message and optionally context keys that will be checked against all records + * + * @phpstan-param array{message: string, context?: mixed[]}|string $recordAssertions + */ + #[NoDiscard] + public function hasRecord(string|array $recordAssertions, Level $level): bool + { + if (\is_string($recordAssertions)) { + $recordAssertions = ['message' => $recordAssertions]; + } + + return $this->hasRecordThatPasses(function (LogRecord $rec) use ($recordAssertions) { + if ($rec->message !== $recordAssertions['message']) { + return false; + } + if (isset($recordAssertions['context']) && $rec->context !== $recordAssertions['context']) { + return false; + } + + return true; + }, $level); + } + + #[NoDiscard] + public function hasRecordThatContains(string $message, Level $level): bool + { + return $this->hasRecordThatPasses(fn (LogRecord $rec) => str_contains($rec->message, $message), $level); + } + + #[NoDiscard] + public function hasRecordThatMatches(string $regex, Level $level): bool + { + return $this->hasRecordThatPasses(fn (LogRecord $rec) => preg_match($regex, $rec->message) > 0, $level); + } + + /** + * @phpstan-param callable(LogRecord, int): mixed $predicate + */ + #[NoDiscard] + public function hasRecordThatPasses(callable $predicate, Level $level): bool + { + $level = Logger::toMonologLevel($level); + + if (!isset($this->recordsByLevel[$level->value])) { + return false; + } + + foreach ($this->recordsByLevel[$level->value] as $i => $rec) { + if ((bool) $predicate($rec, $i)) { + return true; + } + } + + return false; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->recordsByLevel[$record->level->value][] = $record; + $this->records[] = $record; + } + + /** + * @param mixed[] $args + */ + #[NoDiscard] + public function __call(string $method, array $args): bool + { + if ((bool) preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches)) { + $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; + $level = \constant(Level::class.'::' . $matches[2]); + $callback = [$this, $genericMethod]; + if (\is_callable($callback)) { + $args[] = $level; + + return \call_user_func_array($callback, $args); + } + } + + throw new \BadMethodCallException('Call to undefined method ' . \get_class($this) . '::' . $method . '()'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php b/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php new file mode 100644 index 0000000..9c12c3d --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php @@ -0,0 +1,23 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +trait WebRequestRecognizerTrait +{ + /** + * Checks if PHP's serving a web request + */ + protected function isWebRequest(): bool + { + return 'cli' !== \PHP_SAPI && 'phpdbg' !== \PHP_SAPI; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php new file mode 100644 index 0000000..932fa70 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php @@ -0,0 +1,80 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\LogRecord; +use Throwable; + +/** + * Forwards records to multiple handlers suppressing failures of each handler + * and continuing through to give every handler a chance to succeed. + * + * @author Craig D'Amelio <craig@damelio.ca> + */ +class WhatFailureGroupHandler extends GroupHandler +{ + /** + * @inheritDoc + */ + public function handle(LogRecord $record): bool + { + if (\count($this->processors) > 0) { + $record = $this->processRecord($record); + } + + foreach ($this->handlers as $handler) { + try { + $handler->handle(clone $record); + } catch (Throwable) { + // What failure? + } + } + + return false === $this->bubble; + } + + /** + * @inheritDoc + */ + public function handleBatch(array $records): void + { + if (\count($this->processors) > 0) { + $processed = []; + foreach ($records as $record) { + $processed[] = $this->processRecord($record); + } + $records = $processed; + } + + foreach ($this->handlers as $handler) { + try { + $handler->handleBatch(array_map(fn ($record) => clone $record, $records)); + } catch (Throwable) { + // What failure? + } + } + } + + /** + * {@inheritDoc} + */ + public function close(): void + { + foreach ($this->handlers as $handler) { + try { + $handler->close(); + } catch (\Throwable $e) { + // What failure? + } + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php new file mode 100644 index 0000000..8841f2f --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php @@ -0,0 +1,90 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Level; +use Monolog\LogRecord; + +/** + * Handler sending logs to Zend Monitor + * + * @author Christian Bergau <cbergau86@gmail.com> + * @author Jason Davis <happydude@jasondavis.net> + */ +class ZendMonitorHandler extends AbstractProcessingHandler +{ + /** + * @throws MissingExtensionException + */ + public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) + { + if (!\function_exists('zend_monitor_custom_event')) { + throw new MissingExtensionException( + 'You must have Zend Server installed with Zend Monitor enabled in order to use this handler' + ); + } + + parent::__construct($level, $bubble); + } + + /** + * Translates Monolog log levels to ZendMonitor levels. + */ + protected function toZendMonitorLevel(Level $level): int + { + return match ($level) { + Level::Debug => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Info => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Notice => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Warning => \ZEND_MONITOR_EVENT_SEVERITY_WARNING, + Level::Error => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Critical => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Alert => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Emergency => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + }; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void + { + $this->writeZendMonitorCustomEvent( + $record->level->getName(), + $record->message, + $record->formatted, + $this->toZendMonitorLevel($record->level) + ); + } + + /** + * Write to Zend Monitor Events + * @param string $type Text displayed in "Class Name (custom)" field + * @param string $message Text displayed in "Error String" + * @param array<mixed> $formatted Displayed in Custom Variables tab + * @param int $severity Set the event severity level (-1,0,1) + */ + protected function writeZendMonitorCustomEvent(string $type, string $message, array $formatted, int $severity): void + { + zend_monitor_custom_event($type, $message, $formatted, $severity); + } + + /** + * @inheritDoc + */ + public function getDefaultFormatter(): FormatterInterface + { + return new NormalizerFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/JsonSerializableDateTimeImmutable.php b/vendor/monolog/monolog/src/Monolog/JsonSerializableDateTimeImmutable.php new file mode 100644 index 0000000..de2cc5e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/JsonSerializableDateTimeImmutable.php @@ -0,0 +1,48 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use DateTimeZone; + +/** + * Overrides default json encoding of date time objects + * + * @author Menno Holtkamp + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class JsonSerializableDateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable +{ + private bool $useMicroseconds; + + public function __construct(bool $useMicroseconds, ?DateTimeZone $timezone = null) + { + $this->useMicroseconds = $useMicroseconds; + + // if you like to use a custom time to pass to Logger::addRecord directly, + // call modify() or setTimestamp() on this instance to change the date after creating it + parent::__construct('now', $timezone); + } + + public function jsonSerialize(): string + { + if ($this->useMicroseconds) { + return $this->format('Y-m-d\TH:i:s.uP'); + } + + return $this->format('Y-m-d\TH:i:sP'); + } + + public function __toString(): string + { + return $this->jsonSerialize(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Level.php b/vendor/monolog/monolog/src/Monolog/Level.php new file mode 100644 index 0000000..38a74fb --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Level.php @@ -0,0 +1,209 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Psr\Log\LogLevel; + +/** + * Represents the log levels + * + * Monolog supports the logging levels described by RFC 5424 {@see https://datatracker.ietf.org/doc/html/rfc5424} + * but due to BC the severity values used internally are not 0-7. + * + * To get the level name/value out of a Level there are several options: + * + * - Use ->getName() to get the standard Monolog name which is full uppercased (e.g. "DEBUG") + * - Use ->toPsrLogLevel() to get the standard PSR-3 name which is full lowercased (e.g. "debug") + * - Use ->toRFC5424Level() to get the standard RFC 5424 value (e.g. 7 for debug, 0 for emergency) + * - Use ->name to get the enum case's name which is capitalized (e.g. "Debug") + * + * To get the internal value for filtering, if the includes/isLowerThan/isHigherThan methods are + * not enough, you can use ->value to get the enum case's integer value. + */ +enum Level: int +{ + /** + * Detailed debug information + */ + case Debug = 100; + + /** + * Interesting events + * + * Examples: User logs in, SQL logs. + */ + case Info = 200; + + /** + * Uncommon events + */ + case Notice = 250; + + /** + * Exceptional occurrences that are not errors + * + * Examples: Use of deprecated APIs, poor use of an API, + * undesirable things that are not necessarily wrong. + */ + case Warning = 300; + + /** + * Runtime errors + */ + case Error = 400; + + /** + * Critical conditions + * + * Example: Application component unavailable, unexpected exception. + */ + case Critical = 500; + + /** + * Action must be taken immediately + * + * Example: Entire website down, database unavailable, etc. + * This should trigger the SMS alerts and wake you up. + */ + case Alert = 550; + + /** + * Urgent alert. + */ + case Emergency = 600; + + /** + * @param value-of<self::NAMES>|LogLevel::*|'Debug'|'Info'|'Notice'|'Warning'|'Error'|'Critical'|'Alert'|'Emergency' $name + * @return static + */ + public static function fromName(string $name): self + { + return match (strtolower($name)) { + 'debug' => self::Debug, + 'info' => self::Info, + 'notice' => self::Notice, + 'warning' => self::Warning, + 'error' => self::Error, + 'critical' => self::Critical, + 'alert' => self::Alert, + 'emergency' => self::Emergency, + }; + } + + /** + * @param value-of<self::VALUES> $value + * @return static + */ + public static function fromValue(int $value): self + { + return self::from($value); + } + + /** + * Returns true if the passed $level is higher or equal to $this + */ + public function includes(Level $level): bool + { + return $this->value <= $level->value; + } + + public function isHigherThan(Level $level): bool + { + return $this->value > $level->value; + } + + public function isLowerThan(Level $level): bool + { + return $this->value < $level->value; + } + + /** + * Returns the monolog standardized all-capitals name of the level + * + * Use this instead of $level->name which returns the enum case name (e.g. Debug vs DEBUG if you use getName()) + * + * @return value-of<self::NAMES> + */ + public function getName(): string + { + return match ($this) { + self::Debug => 'DEBUG', + self::Info => 'INFO', + self::Notice => 'NOTICE', + self::Warning => 'WARNING', + self::Error => 'ERROR', + self::Critical => 'CRITICAL', + self::Alert => 'ALERT', + self::Emergency => 'EMERGENCY', + }; + } + + /** + * Returns the PSR-3 level matching this instance + * + * @phpstan-return \Psr\Log\LogLevel::* + */ + public function toPsrLogLevel(): string + { + return match ($this) { + self::Debug => LogLevel::DEBUG, + self::Info => LogLevel::INFO, + self::Notice => LogLevel::NOTICE, + self::Warning => LogLevel::WARNING, + self::Error => LogLevel::ERROR, + self::Critical => LogLevel::CRITICAL, + self::Alert => LogLevel::ALERT, + self::Emergency => LogLevel::EMERGENCY, + }; + } + + /** + * Returns the RFC 5424 level matching this instance + * + * @phpstan-return int<0, 7> + */ + public function toRFC5424Level(): int + { + return match ($this) { + self::Debug => 7, + self::Info => 6, + self::Notice => 5, + self::Warning => 4, + self::Error => 3, + self::Critical => 2, + self::Alert => 1, + self::Emergency => 0, + }; + } + + public const VALUES = [ + 100, + 200, + 250, + 300, + 400, + 500, + 550, + 600, + ]; + + public const NAMES = [ + 'DEBUG', + 'INFO', + 'NOTICE', + 'WARNING', + 'ERROR', + 'CRITICAL', + 'ALERT', + 'EMERGENCY', + ]; +} diff --git a/vendor/monolog/monolog/src/Monolog/LogRecord.php b/vendor/monolog/monolog/src/Monolog/LogRecord.php new file mode 100644 index 0000000..14c82f3 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/LogRecord.php @@ -0,0 +1,127 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use ArrayAccess; + +/** + * Monolog log record + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * @template-implements ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra'|'formatted', int|string|\DateTimeImmutable|array<mixed>> + */ +class LogRecord implements ArrayAccess +{ + private const MODIFIABLE_FIELDS = [ + 'extra' => true, + 'formatted' => true, + ]; + + public function __construct( + public readonly \DateTimeImmutable $datetime, + public readonly string $channel, + public readonly Level $level, + public readonly string $message, + /** @var array<mixed> */ + public readonly array $context = [], + /** @var array<mixed> */ + public array $extra = [], + public mixed $formatted = null, + ) { + } + + public function offsetSet(mixed $offset, mixed $value): void + { + if ($offset === 'extra') { + if (!\is_array($value)) { + throw new \InvalidArgumentException('extra must be an array'); + } + + $this->extra = $value; + + return; + } + + if ($offset === 'formatted') { + $this->formatted = $value; + + return; + } + + throw new \LogicException('Unsupported operation: setting '.$offset); + } + + public function offsetExists(mixed $offset): bool + { + if ($offset === 'level_name') { + return true; + } + + return isset($this->{$offset}); + } + + public function offsetUnset(mixed $offset): void + { + throw new \LogicException('Unsupported operation'); + } + + public function &offsetGet(mixed $offset): mixed + { + // handle special cases for the level enum + if ($offset === 'level_name') { + // avoid returning readonly props by ref as this is illegal + $copy = $this->level->getName(); + + return $copy; + } + if ($offset === 'level') { + // avoid returning readonly props by ref as this is illegal + $copy = $this->level->value; + + return $copy; + } + + if (isset(self::MODIFIABLE_FIELDS[$offset])) { + return $this->{$offset}; + } + + // avoid returning readonly props by ref as this is illegal + $copy = $this->{$offset}; + + return $copy; + } + + /** + * @phpstan-return array{message: string, context: mixed[], level: value-of<Level::VALUES>, level_name: value-of<Level::NAMES>, channel: string, datetime: \DateTimeImmutable, extra: mixed[]} + */ + public function toArray(): array + { + return [ + 'message' => $this->message, + 'context' => $this->context, + 'level' => $this->level->value, + 'level_name' => $this->level->getName(), + 'channel' => $this->channel, + 'datetime' => $this->datetime, + 'extra' => $this->extra, + ]; + } + + public function with(mixed ...$args): self + { + foreach (['message', 'context', 'level', 'channel', 'datetime', 'extra'] as $prop) { + $args[$prop] ??= $this->{$prop}; + } + + return new self(...$args); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Logger.php b/vendor/monolog/monolog/src/Monolog/Logger.php new file mode 100644 index 0000000..177e145 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Logger.php @@ -0,0 +1,819 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Closure; +use DateTimeZone; +use Fiber; +use Monolog\Handler\HandlerInterface; +use Monolog\Processor\ProcessorInterface; +use Psr\Clock\ClockInterface; +use Psr\Log\LoggerInterface; +use Psr\Log\InvalidArgumentException; +use Psr\Log\LogLevel; +use Throwable; +use Stringable; +use WeakMap; + +/** + * Monolog log channel + * + * It contains a stack of Handlers and a stack of Processors, + * and uses them to store records that are added to it. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * @final + */ +class Logger implements LoggerInterface, ResettableInterface +{ + /** + * Detailed debug information + * + * @deprecated Use \Monolog\Level::Debug + */ + public const DEBUG = 100; + + /** + * Interesting events + * + * Examples: User logs in, SQL logs. + * + * @deprecated Use \Monolog\Level::Info + */ + public const INFO = 200; + + /** + * Uncommon events + * + * @deprecated Use \Monolog\Level::Notice + */ + public const NOTICE = 250; + + /** + * Exceptional occurrences that are not errors + * + * Examples: Use of deprecated APIs, poor use of an API, + * undesirable things that are not necessarily wrong. + * + * @deprecated Use \Monolog\Level::Warning + */ + public const WARNING = 300; + + /** + * Runtime errors + * + * @deprecated Use \Monolog\Level::Error + */ + public const ERROR = 400; + + /** + * Critical conditions + * + * Example: Application component unavailable, unexpected exception. + * + * @deprecated Use \Monolog\Level::Critical + */ + public const CRITICAL = 500; + + /** + * Action must be taken immediately + * + * Example: Entire website down, database unavailable, etc. + * This should trigger the SMS alerts and wake you up. + * + * @deprecated Use \Monolog\Level::Alert + */ + public const ALERT = 550; + + /** + * Urgent alert. + * + * @deprecated Use \Monolog\Level::Emergency + */ + public const EMERGENCY = 600; + + /** + * Monolog API version + * + * This is only bumped when API breaks are done and should + * follow the major version of the library + */ + public const API = 3; + + /** + * Mapping between levels numbers defined in RFC 5424 and Monolog ones + * + * @phpstan-var array<int, Level> $rfc_5424_levels + */ + private const RFC_5424_LEVELS = [ + 7 => Level::Debug, + 6 => Level::Info, + 5 => Level::Notice, + 4 => Level::Warning, + 3 => Level::Error, + 2 => Level::Critical, + 1 => Level::Alert, + 0 => Level::Emergency, + ]; + + protected string $name; + + /** + * The handler stack + * + * @var list<HandlerInterface> + */ + protected array $handlers; + + /** + * Processors that will process all log records + * + * To process records of a single handler instead, add the processor on that specific handler + * + * @var array<(callable(LogRecord): LogRecord)|ProcessorInterface> + */ + protected array $processors; + + protected bool $microsecondTimestamps = true; + + protected DateTimeZone $timezone; + + /** + * Clock used to timestamp new records, or null to read the current time from the engine + */ + protected ClockInterface|null $clock = null; + + protected Closure|null $exceptionHandler = null; + + /** + * Keeps track of depth to prevent infinite logging loops + */ + private int $logDepth = 0; + + /** + * @var WeakMap<Fiber<mixed, mixed, mixed, mixed>, int> Keeps track of depth inside fibers to prevent infinite logging loops + */ + private WeakMap $fiberLogDepth; + + /** + * Whether to detect infinite logging loops + * This can be disabled via {@see useLoggingLoopDetection} if you have async handlers that do not play well with this + */ + private bool $detectCycles = true; + + /** + * @param string $name The logging channel, a simple descriptive name that is attached to all log records + * @param list<HandlerInterface> $handlers Optional stack of handlers, the first one in the array is called first, etc. + * @param callable[] $processors Optional array of processors + * @param DateTimeZone|null $timezone Optional timezone, if not provided date_default_timezone_get() will be used + * @param ClockInterface|null $clock Optional clock to read the current time from, if not provided the engine's current time is used + * + * @phpstan-param array<(callable(LogRecord): LogRecord)|ProcessorInterface> $processors + */ + public function __construct(string $name, array $handlers = [], array $processors = [], DateTimeZone|null $timezone = null, ClockInterface|null $clock = null) + { + $this->name = $name; + $this->setHandlers($handlers); + $this->processors = $processors; + $this->timezone = $timezone ?? new DateTimeZone(date_default_timezone_get()); + $this->clock = $clock; + $this->fiberLogDepth = new \WeakMap(); + } + + public function getName(): string + { + return $this->name; + } + + /** + * Return a new cloned instance with the name changed + * + * @return static + */ + public function withName(string $name): self + { + $new = clone $this; + $new->name = $name; + + return $new; + } + + /** + * Pushes a handler on to the stack. + * + * @return $this + */ + public function pushHandler(HandlerInterface $handler): self + { + array_unshift($this->handlers, $handler); + + return $this; + } + + /** + * Pops a handler from the stack + * + * @throws \LogicException If empty handler stack + */ + public function popHandler(): HandlerInterface + { + if (0 === \count($this->handlers)) { + throw new \LogicException('You tried to pop from an empty handler stack.'); + } + + return array_shift($this->handlers); + } + + /** + * Set handlers, replacing all existing ones. + * + * If a map is passed, keys will be ignored. + * + * @param list<HandlerInterface> $handlers + * @return $this + */ + public function setHandlers(array $handlers): self + { + $this->handlers = []; + foreach (array_reverse($handlers) as $handler) { + $this->pushHandler($handler); + } + + return $this; + } + + /** + * @return list<HandlerInterface> + */ + public function getHandlers(): array + { + return $this->handlers; + } + + /** + * Adds a processor on to the stack. + * + * @phpstan-param ProcessorInterface|(callable(LogRecord): LogRecord) $callback + * @return $this + */ + public function pushProcessor(ProcessorInterface|callable $callback): self + { + array_unshift($this->processors, $callback); + + return $this; + } + + /** + * Removes the processor on top of the stack and returns it. + * + * @phpstan-return ProcessorInterface|(callable(LogRecord): LogRecord) + * @throws \LogicException If empty processor stack + */ + public function popProcessor(): callable + { + if (0 === \count($this->processors)) { + throw new \LogicException('You tried to pop from an empty processor stack.'); + } + + return array_shift($this->processors); + } + + /** + * @return callable[] + * @phpstan-return array<ProcessorInterface|(callable(LogRecord): LogRecord)> + */ + public function getProcessors(): array + { + return $this->processors; + } + + /** + * Control the use of microsecond resolution timestamps in the 'datetime' + * member of new records. + * + * As of PHP7.1 microseconds are always included by the engine, so + * there is no performance penalty and Monolog 2 enabled microseconds + * by default. This function lets you disable them though in case you want + * to suppress microseconds from the output. + * + * @param bool $micro True to use microtime() to create timestamps + * @return $this + */ + public function useMicrosecondTimestamps(bool $micro): self + { + $this->microsecondTimestamps = $micro; + + return $this; + } + + /** + * @return $this + */ + public function useLoggingLoopDetection(bool $detectCycles): self + { + $this->detectCycles = $detectCycles; + + return $this; + } + + /** + * Adds a log record. + * + * @param int $level The logging level (a Monolog or RFC 5424 level) + * @param string $message The log message + * @param mixed[] $context The log context + * @param JsonSerializableDateTimeImmutable|null $datetime Optional log date to log into the past or future + * + * @return bool Whether the record has been processed + * + * @phpstan-param value-of<Level::VALUES>|Level $level + */ + public function addRecord(int|Level $level, string $message, array $context = [], JsonSerializableDateTimeImmutable|null $datetime = null): bool + { + if (\is_int($level) && isset(self::RFC_5424_LEVELS[$level])) { + $level = self::RFC_5424_LEVELS[$level]; + } + + if ($this->detectCycles) { + if (null !== ($fiber = Fiber::getCurrent())) { + $logDepth = $this->fiberLogDepth[$fiber] = ($this->fiberLogDepth[$fiber] ?? 0) + 1; + } else { + $logDepth = ++$this->logDepth; + } + } else { + $logDepth = 0; + } + + try { + if ($logDepth === 3) { + $this->warning('A possible infinite logging loop was detected and aborted. It appears some of your handler code is triggering logging, see the previous log record for a hint as to what may be the cause.'); + + return false; + } elseif ($logDepth >= 5) { // log depth 4 is let through, so we can log the warning above + return false; + } + + $recordInitialized = \count($this->processors) === 0; + + $record = new LogRecord( + datetime: $datetime ?? $this->createDateTime(), + channel: $this->name, + level: self::toMonologLevel($level), + message: $message, + context: $context, + extra: [], + ); + $handled = false; + + foreach ($this->handlers as $handler) { + if (false === $recordInitialized) { + // skip initializing the record as long as no handler is going to handle it + if (!$handler->isHandling($record)) { + continue; + } + + try { + foreach ($this->processors as $processor) { + $record = $processor($record); + } + $recordInitialized = true; + } catch (Throwable $e) { + $this->handleException($e, $record); + + return true; + } + } + + // once the record is initialized, send it to all handlers as long as the bubbling chain is not interrupted + try { + $handled = true; + if (true === $handler->handle(clone $record)) { + break; + } + } catch (Throwable $e) { + $this->handleException($e, $record); + + return true; + } + } + + return $handled; + } finally { + if ($this->detectCycles) { + if (isset($fiber)) { + $this->fiberLogDepth[$fiber]--; + } else { + $this->logDepth--; + } + } + } + } + + /** + * Ends a log cycle and frees all resources used by handlers. + * + * Closing a Handler means flushing all buffers and freeing any open resources/handles. + * Handlers that have been closed should be able to accept log records again and re-open + * themselves on demand, but this may not always be possible depending on implementation. + * + * This is useful at the end of a request and will be called automatically on every handler + * when they get destructed. + */ + public function close(): void + { + foreach ($this->handlers as $handler) { + $handler->close(); + } + } + + /** + * Ends a log cycle and resets all handlers and processors to their initial state. + * + * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal + * state, and getting it back to a state in which it can receive log records again. + * + * This is useful in case you want to avoid logs leaking between two requests or jobs when you + * have a long running process like a worker or an application server serving multiple requests + * in one process. + */ + public function reset(): void + { + foreach ($this->handlers as $handler) { + if ($handler instanceof ResettableInterface) { + $handler->reset(); + } + } + + foreach ($this->processors as $processor) { + if ($processor instanceof ResettableInterface) { + $processor->reset(); + } + } + } + + /** + * Gets the name of the logging level as a string. + * + * This still returns a string instead of a Level for BC, but new code should not rely on this method. + * + * @throws \Psr\Log\InvalidArgumentException If level is not defined + * + * @phpstan-param value-of<Level::VALUES>|Level $level + * @phpstan-return value-of<Level::NAMES> + * + * @deprecated Since 3.0, use {@see toMonologLevel} or {@see \Monolog\Level->getName()} instead + */ + public static function getLevelName(int|Level $level): string + { + return self::toMonologLevel($level)->getName(); + } + + /** + * Converts PSR-3 levels to Monolog ones if necessary + * + * @param int|string|Level|LogLevel::* $level Level number (monolog) or name (PSR-3) + * @throws \Psr\Log\InvalidArgumentException If level is not defined + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public static function toMonologLevel(string|int|Level $level): Level + { + if ($level instanceof Level) { + return $level; + } + + if (\is_string($level)) { + if (is_numeric($level)) { + $levelEnum = Level::tryFrom((int) $level); + if ($levelEnum === null) { + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); + } + + return $levelEnum; + } + + // Contains first char of all log levels and avoids using strtoupper() which may have + // strange results depending on locale (for example, "i" will become "İ" in Turkish locale) + $upper = strtr(substr($level, 0, 1), 'dinweca', 'DINWECA') . strtolower(substr($level, 1)); + if (\defined(Level::class.'::'.$upper)) { + return \constant(Level::class . '::' . $upper); + } + + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); + } + + $levelEnum = Level::tryFrom($level); + if ($levelEnum === null) { + throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); + } + + return $levelEnum; + } + + /** + * Checks whether the Logger has a handler that listens on the given level + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function isHandling(int|string|Level $level): bool + { + $record = new LogRecord( + datetime: $this->createDateTime(), + channel: $this->name, + message: '', + level: self::toMonologLevel($level), + ); + + foreach ($this->handlers as $handler) { + if ($handler->isHandling($record)) { + return true; + } + } + + return false; + } + + /** + * Set a custom exception handler that will be called if adding a new record fails + * + * The Closure will receive an exception object and the record that failed to be logged + * + * @return $this + */ + public function setExceptionHandler(Closure|null $callback): self + { + $this->exceptionHandler = $callback; + + return $this; + } + + public function getExceptionHandler(): Closure|null + { + return $this->exceptionHandler; + } + + /** + * Adds a log record at an arbitrary level. + * + * This method allows for compatibility with common interfaces. + * + * @param mixed $level The log level (a Monolog, PSR-3 or RFC 5424 level) + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + * + * @phpstan-param Level|LogLevel::* $level + */ + public function log($level, string|\Stringable $message, array $context = []): void + { + if (!$level instanceof Level) { + if (!\is_string($level) && !\is_int($level)) { + throw new \InvalidArgumentException('$level is expected to be a string, int or '.Level::class.' instance'); + } + + if (isset(self::RFC_5424_LEVELS[$level])) { + $level = self::RFC_5424_LEVELS[$level]; + } + + $level = static::toMonologLevel($level); + } + + $this->addRecord($level, (string) $message, $context); + } + + /** + * Adds a log record at the DEBUG level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function debug(string|\Stringable $message, array $context = []): void + { + $this->addRecord(Level::Debug, (string) $message, $context); + } + + /** + * Adds a log record at the INFO level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function info(string|\Stringable $message, array $context = []): void + { + $this->addRecord(Level::Info, (string) $message, $context); + } + + /** + * Adds a log record at the NOTICE level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function notice(string|\Stringable $message, array $context = []): void + { + $this->addRecord(Level::Notice, (string) $message, $context); + } + + /** + * Adds a log record at the WARNING level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function warning(string|\Stringable $message, array $context = []): void + { + $this->addRecord(Level::Warning, (string) $message, $context); + } + + /** + * Adds a log record at the ERROR level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function error(string|\Stringable $message, array $context = []): void + { + $this->addRecord(Level::Error, (string) $message, $context); + } + + /** + * Adds a log record at the CRITICAL level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function critical(string|\Stringable $message, array $context = []): void + { + $this->addRecord(Level::Critical, (string) $message, $context); + } + + /** + * Adds a log record at the ALERT level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function alert(string|\Stringable $message, array $context = []): void + { + $this->addRecord(Level::Alert, (string) $message, $context); + } + + /** + * Adds a log record at the EMERGENCY level. + * + * This method allows for compatibility with common interfaces. + * + * @param string|Stringable $message The log message + * @param mixed[] $context The log context + */ + public function emergency(string|\Stringable $message, array $context = []): void + { + $this->addRecord(Level::Emergency, (string) $message, $context); + } + + /** + * Sets the timezone to be used for the timestamp of log records. + * + * @return $this + */ + public function setTimezone(DateTimeZone $tz): self + { + $this->timezone = $tz; + + return $this; + } + + /** + * Returns the timezone to be used for the timestamp of log records. + */ + public function getTimezone(): DateTimeZone + { + return $this->timezone; + } + + /** + * Sets the clock to read the current time from when timestamping log records. + * + * Pass null to go back to reading the engine's current time. The timezone + * configured on the logger still decides how the timestamp is rendered. + * + * @return $this + */ + public function setClock(ClockInterface|null $clock): self + { + $this->clock = $clock; + + return $this; + } + + /** + * Returns the clock used to timestamp log records, or null if the engine's current time is used. + */ + public function getClock(): ClockInterface|null + { + return $this->clock; + } + + /** + * Builds the timestamp of a new record, reading the current time from the clock if one is set. + */ + private function createDateTime(): JsonSerializableDateTimeImmutable + { + if (null === $this->clock) { + return new JsonSerializableDateTimeImmutable($this->microsecondTimestamps, $this->timezone); + } + + $now = $this->clock->now(); + + if ($now instanceof JsonSerializableDateTimeImmutable) { + return $now; + } + + $datetime = new JsonSerializableDateTimeImmutable($this->microsecondTimestamps, $this->timezone); + + // The instant is applied without ever going through a local wall clock time, which + // is ambiguous across a DST transition, and without the "@U.u" notation, which is + // off by one second before 1970 and replaces the named timezone with an offset. + $datetime = $datetime->setTimestamp($now->getTimestamp()); + if (\PHP_VERSION_ID >= 80400) { + return $datetime->setMicrosecond($now->getMicrosecond()); + } + + $microseconds = (int) $now->format('u'); + if (0 !== $microseconds) { + // DateInterval has no notation for microseconds, they can only be set on the property + $interval = new \DateInterval('PT0S'); + $interval->f = $microseconds / 1000000; + + $datetime = $datetime->add($interval); + } + + return $datetime; + } + + /** + * Delegates exception management to the custom exception handler, + * or throws the exception if no custom handler is set. + */ + protected function handleException(Throwable $e, LogRecord $record): void + { + if (null === $this->exceptionHandler) { + throw $e; + } + + ($this->exceptionHandler)($e, $record); + } + + /** + * @return array<string, mixed> + */ + public function __serialize(): array + { + return [ + 'name' => $this->name, + 'handlers' => $this->handlers, + 'processors' => $this->processors, + 'microsecondTimestamps' => $this->microsecondTimestamps, + 'timezone' => $this->timezone, + 'exceptionHandler' => $this->exceptionHandler, + 'logDepth' => $this->logDepth, + 'detectCycles' => $this->detectCycles, + ]; + } + + /** + * @param array<string, mixed> $data + */ + public function __unserialize(array $data): void + { + foreach (['name', 'handlers', 'processors', 'microsecondTimestamps', 'timezone', 'exceptionHandler', 'logDepth', 'detectCycles'] as $property) { + if (isset($data[$property])) { + $this->$property = $data[$property]; + } + } + + $this->fiberLogDepth = new \WeakMap(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/ClosureContextProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/ClosureContextProcessor.php new file mode 100644 index 0000000..514b354 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/ClosureContextProcessor.php @@ -0,0 +1,51 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\LogRecord; + +/** + * Generates a context from a Closure if the Closure is the only value + * in the context + * + * It helps reduce the performance impact of debug logs if they do + * need to create lots of context information. If this processor is added + * on the correct handler the context data will only be generated + * when the logs are actually logged to that handler, which is useful when + * using FingersCrossedHandler or other filtering handlers to conditionally + * log records. + */ +class ClosureContextProcessor implements ProcessorInterface +{ + public function __invoke(LogRecord $record): LogRecord + { + $context = $record->context; + if (isset($context[0]) && 1 === \count($context) && $context[0] instanceof \Closure) { + try { + $context = $context[0](); + } catch (\Throwable $e) { + $context = [ + 'error_on_context_generation' => $e->getMessage(), + 'exception' => $e, + ]; + } + + if (!\is_array($context)) { + $context = [$context]; + } + + $record = $record->with(context: $context); + } + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php new file mode 100644 index 0000000..6b25505 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php @@ -0,0 +1,75 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Level; +use Monolog\Logger; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Injects Git branch and Git commit SHA in all records + * + * @author Nick Otter + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class GitProcessor implements ProcessorInterface +{ + private Level $level; + /** @var array{branch: string, commit: string}|array<never>|null */ + private static $cache = null; + + /** + * @param int|string|Level|LogLevel::* $level The minimum logging level at which this Processor will be triggered + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function __construct(int|string|Level $level = Level::Debug) + { + $this->level = Logger::toMonologLevel($level); + } + + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + // return if the level is not high enough + if ($record->level->isLowerThan($this->level)) { + return $record; + } + + $record->extra['git'] = self::getGitInfo(); + + return $record; + } + + /** + * @return array{branch: string, commit: string}|array<never> + */ + private static function getGitInfo(): array + { + if (self::$cache !== null) { + return self::$cache; + } + + $branches = shell_exec('git branch -v --no-abbrev'); + if (\is_string($branches) && 1 === preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) { + return self::$cache = [ + 'branch' => $matches[1], + 'commit' => $matches[2], + ]; + } + + return self::$cache = []; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php new file mode 100644 index 0000000..cba6e09 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\LogRecord; + +/** + * Injects value of gethostname in all records + */ +class HostnameProcessor implements ProcessorInterface +{ + private static string $host; + + public function __construct() + { + self::$host = (string) gethostname(); + } + + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + $record->extra['hostname'] = self::$host; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php new file mode 100644 index 0000000..3b68652 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php @@ -0,0 +1,126 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Level; +use Monolog\Logger; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Injects line/file:class/function where the log message came from + * + * Warning: This only works if the handler processes the logs directly. + * If you put the processor on a handler that is behind a FingersCrossedHandler + * for example, the processor will only be called once the trigger level is reached, + * and all the log records will have the same file/line/.. data from the call that + * triggered the FingersCrossedHandler. + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class IntrospectionProcessor implements ProcessorInterface +{ + protected Level $level; + + /** @var string[] */ + protected array $skipClassesPartials; + + protected int $skipStackFramesCount; + + protected const SKIP_FUNCTIONS = [ + 'call_user_func', + 'call_user_func_array', + ]; + + protected const SKIP_CLASSES = [ + 'Monolog\\', + ]; + + /** + * @param string|int|Level $level The minimum logging level at which this Processor will be triggered + * @param string[] $skipClassesPartials + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function __construct(int|string|Level $level = Level::Debug, array $skipClassesPartials = [], int $skipStackFramesCount = 0) + { + $this->level = Logger::toMonologLevel($level); + $this->skipClassesPartials = array_merge(static::SKIP_CLASSES, $skipClassesPartials); + $this->skipStackFramesCount = $skipStackFramesCount; + } + + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + // return if the level is not high enough + if ($record->level->isLowerThan($this->level)) { + return $record; + } + + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + + // skip first since it's always the current method + array_shift($trace); + // the call_user_func call is also skipped + array_shift($trace); + + $i = 0; + + while ($this->isTraceClassOrSkippedFunction($trace, $i)) { + if (isset($trace[$i]['class'])) { + foreach ($this->skipClassesPartials as $part) { + if (strpos($trace[$i]['class'], $part) !== false) { + $i++; + + continue 2; + } + } + } elseif (\in_array($trace[$i]['function'], static::SKIP_FUNCTIONS, true)) { + $i++; + + continue; + } + + break; + } + + $i += $this->skipStackFramesCount; + + // we should have the call source now + $record->extra = array_merge( + $record->extra, + [ + 'file' => $trace[$i - 1]['file'] ?? null, + 'line' => $trace[$i - 1]['line'] ?? null, + 'class' => $trace[$i]['class'] ?? null, + 'callType' => $trace[$i]['type'] ?? null, + 'function' => $trace[$i]['function'] ?? null, + ] + ); + + return $record; + } + + /** + * @param array<mixed> $trace + */ + private function isTraceClassOrSkippedFunction(array $trace, int $index): bool + { + if (!isset($trace[$index])) { + return false; + } + + return isset($trace[$index]['class']) || \in_array($trace[$index]['function'], static::SKIP_FUNCTIONS, true); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/LoadAverageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/LoadAverageProcessor.php new file mode 100644 index 0000000..762ed91 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/LoadAverageProcessor.php @@ -0,0 +1,66 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\LogRecord; + +/** + * Injects sys_getloadavg in all records @see https://www.php.net/manual/en/function.sys-getloadavg.php + * + * @author Johan Vlaar <johan.vlaar.1994@gmail.com> + */ +class LoadAverageProcessor implements ProcessorInterface +{ + public const LOAD_1_MINUTE = 0; + public const LOAD_5_MINUTE = 1; + public const LOAD_15_MINUTE = 2; + + private const AVAILABLE_LOAD = [ + self::LOAD_1_MINUTE, + self::LOAD_5_MINUTE, + self::LOAD_15_MINUTE, + ]; + + /** + * @var int + */ + protected $avgSystemLoad; + + /** + * @param self::LOAD_* $avgSystemLoad + */ + public function __construct(int $avgSystemLoad = self::LOAD_1_MINUTE) + { + if (!\in_array($avgSystemLoad, self::AVAILABLE_LOAD, true)) { + throw new \InvalidArgumentException(sprintf('Invalid average system load: `%s`', $avgSystemLoad)); + } + $this->avgSystemLoad = $avgSystemLoad; + } + + /** + * {@inheritDoc} + */ + public function __invoke(LogRecord $record): LogRecord + { + if (!\function_exists('sys_getloadavg')) { + return $record; + } + $usage = sys_getloadavg(); + if (false === $usage) { + return $record; + } + + $record->extra['load_average'] = $usage[$this->avgSystemLoad]; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php new file mode 100644 index 0000000..adc32c6 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php @@ -0,0 +1,39 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\LogRecord; + +/** + * Injects memory_get_peak_usage in all records + * + * @see Monolog\Processor\MemoryProcessor::__construct() for options + * @author Rob Jensen + */ +class MemoryPeakUsageProcessor extends MemoryProcessor +{ + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + $usage = memory_get_peak_usage($this->realUsage); + + if ($this->useFormatting) { + $usage = $this->formatBytes($usage); + } + + $record->extra['memory_peak_usage'] = $usage; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php new file mode 100644 index 0000000..f808e51 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php @@ -0,0 +1,60 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Some methods that are common for all memory processors + * + * @author Rob Jensen + */ +abstract class MemoryProcessor implements ProcessorInterface +{ + /** + * @var bool If true, get the real size of memory allocated from system. Else, only the memory used by emalloc() is reported. + */ + protected bool $realUsage; + + /** + * @var bool If true, then format memory size to human readable string (MB, KB, B depending on size) + */ + protected bool $useFormatting; + + /** + * @param bool $realUsage Set this to true to get the real size of memory allocated from system. + * @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size) + */ + public function __construct(bool $realUsage = true, bool $useFormatting = true) + { + $this->realUsage = $realUsage; + $this->useFormatting = $useFormatting; + } + + /** + * Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is + * + * @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as int + */ + protected function formatBytes(int $bytes) + { + if (!$this->useFormatting) { + return $bytes; + } + + if ($bytes > 1024 * 1024) { + return round($bytes / 1024 / 1024, 2).' MB'; + } elseif ($bytes > 1024) { + return round($bytes / 1024, 2).' KB'; + } + + return $bytes . ' B'; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php new file mode 100644 index 0000000..a814b1d --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php @@ -0,0 +1,39 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\LogRecord; + +/** + * Injects memory_get_usage in all records + * + * @see Monolog\Processor\MemoryProcessor::__construct() for options + * @author Rob Jensen + */ +class MemoryUsageProcessor extends MemoryProcessor +{ + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + $usage = memory_get_usage($this->realUsage); + + if ($this->useFormatting) { + $usage = $this->formatBytes($usage); + } + + $record->extra['memory_usage'] = $usage; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php new file mode 100644 index 0000000..3076a3d --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php @@ -0,0 +1,80 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Level; +use Monolog\Logger; +use Psr\Log\LogLevel; +use Monolog\LogRecord; + +/** + * Injects Hg branch and Hg revision number in all records + * + * @author Jonathan A. Schweder <jonathanschweder@gmail.com> + */ +class MercurialProcessor implements ProcessorInterface +{ + private Level $level; + /** @var array{branch: string, revision: string}|array<never>|null */ + private static $cache = null; + + /** + * @param int|string|Level $level The minimum logging level at which this Processor will be triggered + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function __construct(int|string|Level $level = Level::Debug) + { + $this->level = Logger::toMonologLevel($level); + } + + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + // return if the level is not high enough + if ($record->level->isLowerThan($this->level)) { + return $record; + } + + $record->extra['hg'] = self::getMercurialInfo(); + + return $record; + } + + /** + * @return array{branch: string, revision: string}|array<never> + */ + private static function getMercurialInfo(): array + { + if (self::$cache !== null) { + return self::$cache; + } + + $result = explode(' ', trim((string) shell_exec('hg id -nb'))); + if (\count($result) >= 3) { + return self::$cache = [ + 'branch' => $result[1], + 'revision' => $result[2], + ]; + } + if (\count($result) === 2) { + return self::$cache = [ + 'branch' => $result[1], + 'revision' => $result[0], + ]; + } + + return self::$cache = []; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php new file mode 100644 index 0000000..bb9a522 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php @@ -0,0 +1,32 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\LogRecord; + +/** + * Adds value of getmypid into records + * + * @author Andreas Hörnicke + */ +class ProcessIdProcessor implements ProcessorInterface +{ + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + $record->extra['process_id'] = getmypid(); + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php b/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php new file mode 100644 index 0000000..ebe41fc --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php @@ -0,0 +1,27 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\LogRecord; + +/** + * An optional interface to allow labelling Monolog processors. + * + * @author Nicolas Grekas <p@tchwork.com> + */ +interface ProcessorInterface +{ + /** + * @return LogRecord The processed record + */ + public function __invoke(LogRecord $record); +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php new file mode 100644 index 0000000..febc111 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php @@ -0,0 +1,87 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Utils; +use Monolog\LogRecord; + +/** + * Processes a record's message according to PSR-3 rules + * + * It replaces {foo} with the value from $context['foo'] + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class PsrLogMessageProcessor implements ProcessorInterface +{ + public const SIMPLE_DATE = "Y-m-d\TH:i:s.uP"; + + private ?string $dateFormat; + + private bool $removeUsedContextFields; + + /** + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * @param bool $removeUsedContextFields If set to true the fields interpolated into message gets unset + */ + public function __construct(?string $dateFormat = null, bool $removeUsedContextFields = false) + { + $this->dateFormat = $dateFormat; + $this->removeUsedContextFields = $removeUsedContextFields; + } + + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + if (false === strpos($record->message, '{')) { + return $record; + } + + $replacements = []; + $context = $record->context; + + foreach ($context as $key => $val) { + $placeholder = '{' . $key . '}'; + if (strpos($record->message, $placeholder) === false) { + continue; + } + + if ($val instanceof \DateTimeInterface) { + if (null === $this->dateFormat && method_exists($val, "__toString")) { + // handle monolog dates using __toString if no specific dateFormat was asked for + // so that it follows the useMicroseconds flag, and other date classes the same way + $replacements[$placeholder] = (string) $val; + } else { + $replacements[$placeholder] = $val->format($this->dateFormat ?? static::SIMPLE_DATE); + } + } elseif (null === $val || \is_scalar($val) || (\is_object($val) && method_exists($val, "__toString"))) { + $replacements[$placeholder] = $val; + } elseif ($val instanceof \UnitEnum) { + $replacements[$placeholder] = $val instanceof \BackedEnum ? $val->value : $val->name; + } elseif (\is_object($val)) { + $replacements[$placeholder] = '[object '.Utils::getClass($val).']'; + } elseif (\is_array($val)) { + $replacements[$placeholder] = 'array'.Utils::jsonEncode($val, null, true); + } else { + $replacements[$placeholder] = '['.\gettype($val).']'; + } + + if ($this->removeUsedContextFields) { + unset($context[$key]); + } + } + + return $record->with(message: strtr($record->message, $replacements), context: $context); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php new file mode 100644 index 0000000..f4e41ce --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php @@ -0,0 +1,65 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\LogRecord; + +/** + * Adds a tags array into record + * + * @author Martijn Riemers + */ +class TagProcessor implements ProcessorInterface +{ + /** @var string[] */ + private array $tags; + + /** + * @param string[] $tags + */ + public function __construct(array $tags = []) + { + $this->setTags($tags); + } + + /** + * @param string[] $tags + * @return $this + */ + public function addTags(array $tags = []): self + { + $this->tags = array_merge($this->tags, $tags); + + return $this; + } + + /** + * @param string[] $tags + * @return $this + */ + public function setTags(array $tags = []): self + { + $this->tags = $tags; + + return $this; + } + + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + $record->extra['tags'] = $this->tags; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php new file mode 100644 index 0000000..261e653 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php @@ -0,0 +1,67 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\ResettableInterface; +use Monolog\LogRecord; + +/** + * Adds a unique identifier into records + * + * @author Simon Mönch <sm@webfactory.de> + */ +class UidProcessor implements ProcessorInterface, ResettableInterface +{ + /** @var non-empty-string */ + private string $uid; + + /** + * @param int<1, 32> $length + */ + public function __construct(int $length = 7) + { + if ($length > 32 || $length < 1) { + throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32'); + } + + $this->uid = $this->generateUid($length); + } + + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + $record->extra['uid'] = $this->uid; + + return $record; + } + + public function getUid(): string + { + return $this->uid; + } + + public function reset(): void + { + $this->uid = $this->generateUid(\strlen($this->uid)); + } + + /** + * @param positive-int $length + * @return non-empty-string + */ + private function generateUid(int $length): string + { + return substr(bin2hex(random_bytes((int) ceil($length / 2))), 0, $length); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php new file mode 100644 index 0000000..b78385e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php @@ -0,0 +1,115 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use ArrayAccess; +use Monolog\LogRecord; + +/** + * Injects url/method and remote IP of the current web request in all records + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class WebProcessor implements ProcessorInterface +{ + /** + * @var array<string, mixed>|ArrayAccess<string, mixed> + */ + protected array|ArrayAccess $serverData; + + /** + * Default fields + * + * Array is structured as [key in record.extra => key in $serverData] + * + * @var array<string, string> + */ + protected array $extraFields = [ + 'url' => 'REQUEST_URI', + 'ip' => 'REMOTE_ADDR', + 'http_method' => 'REQUEST_METHOD', + 'server' => 'SERVER_NAME', + 'referrer' => 'HTTP_REFERER', + 'user_agent' => 'HTTP_USER_AGENT', + ]; + + /** + * @param array<string, mixed>|ArrayAccess<string, mixed>|null $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data + * @param array<string, string>|array<string>|null $extraFields Field names and the related key inside $serverData to be added (or just a list of field names to use the default configured $serverData mapping). If not provided it defaults to: [url, ip, http_method, server, referrer] + unique_id if present in server data + */ + public function __construct(array|ArrayAccess|null $serverData = null, array|null $extraFields = null) + { + if (null === $serverData) { + $this->serverData = &$_SERVER; + } else { + $this->serverData = $serverData; + } + + $defaultEnabled = ['url', 'ip', 'http_method', 'server', 'referrer']; + if (isset($this->serverData['UNIQUE_ID'])) { + $this->extraFields['unique_id'] = 'UNIQUE_ID'; + $defaultEnabled[] = 'unique_id'; + } + + if (null === $extraFields) { + $extraFields = $defaultEnabled; + } + if (isset($extraFields[0])) { + foreach (array_keys($this->extraFields) as $fieldName) { + if (!\in_array($fieldName, $extraFields, true)) { + unset($this->extraFields[$fieldName]); + } + } + } else { + $this->extraFields = $extraFields; + } + } + + /** + * @inheritDoc + */ + public function __invoke(LogRecord $record): LogRecord + { + // skip processing if for some reason request data + // is not present (CLI or wonky SAPIs) + if (!isset($this->serverData['REQUEST_URI'])) { + return $record; + } + + $record->extra = $this->appendExtraFields($record->extra); + + return $record; + } + + /** + * @return $this + */ + public function addExtraField(string $extraName, string $serverName): self + { + $this->extraFields[$extraName] = $serverName; + + return $this; + } + + /** + * @param mixed[] $extra + * @return mixed[] + */ + private function appendExtraFields(array $extra): array + { + foreach ($this->extraFields as $extraName => $serverName) { + $extra[$extraName] = $this->serverData[$serverName] ?? null; + } + + return $extra; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Registry.php b/vendor/monolog/monolog/src/Monolog/Registry.php new file mode 100644 index 0000000..2ef2edc --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Registry.php @@ -0,0 +1,133 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use InvalidArgumentException; + +/** + * Monolog log registry + * + * Allows to get `Logger` instances in the global scope + * via static method calls on this class. + * + * <code> + * $application = new Monolog\Logger('application'); + * $api = new Monolog\Logger('api'); + * + * Monolog\Registry::addLogger($application); + * Monolog\Registry::addLogger($api); + * + * function testLogger() + * { + * Monolog\Registry::api()->error('Sent to $api Logger instance'); + * Monolog\Registry::application()->error('Sent to $application Logger instance'); + * } + * </code> + * + * @author Tomas Tatarko <tomas@tatarko.sk> + */ +class Registry +{ + /** + * List of all loggers in the registry (by named indexes) + * + * @var Logger[] + */ + private static array $loggers = []; + + /** + * Adds new logging channel to the registry + * + * @param Logger $logger Instance of the logging channel + * @param string|null $name Name of the logging channel ($logger->getName() by default) + * @param bool $overwrite Overwrite instance in the registry if the given name already exists? + * @throws \InvalidArgumentException If $overwrite set to false and named Logger instance already exists + */ + public static function addLogger(Logger $logger, ?string $name = null, bool $overwrite = false): void + { + $name = $name ?? $logger->getName(); + + if (isset(self::$loggers[$name]) && !$overwrite) { + throw new InvalidArgumentException('Logger with the given name already exists'); + } + + self::$loggers[$name] = $logger; + } + + /** + * Checks if such logging channel exists by name or instance + * + * @param string|Logger $logger Name or logger instance + */ + public static function hasLogger($logger): bool + { + if ($logger instanceof Logger) { + $index = array_search($logger, self::$loggers, true); + + return false !== $index; + } + + return isset(self::$loggers[$logger]); + } + + /** + * Removes instance from registry by name or instance + * + * @param string|Logger $logger Name or logger instance + */ + public static function removeLogger($logger): void + { + if ($logger instanceof Logger) { + if (false !== ($idx = array_search($logger, self::$loggers, true))) { + unset(self::$loggers[$idx]); + } + } else { + unset(self::$loggers[$logger]); + } + } + + /** + * Clears the registry + */ + public static function clear(): void + { + self::$loggers = []; + } + + /** + * Gets Logger instance from the registry + * + * @param string $name Name of the requested Logger instance + * @throws \InvalidArgumentException If named Logger instance is not in the registry + */ + public static function getInstance(string $name): Logger + { + if (!isset(self::$loggers[$name])) { + throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name)); + } + + return self::$loggers[$name]; + } + + /** + * Gets Logger instance from the registry via static method call + * + * @param string $name Name of the requested Logger instance + * @param mixed[] $arguments Arguments passed to static method call + * @throws \InvalidArgumentException If named Logger instance is not in the registry + * @return Logger Requested instance of Logger + */ + public static function __callStatic(string $name, array $arguments): Logger + { + return self::getInstance($name); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/ResettableInterface.php b/vendor/monolog/monolog/src/Monolog/ResettableInterface.php new file mode 100644 index 0000000..4983a6b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/ResettableInterface.php @@ -0,0 +1,31 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +/** + * Handler or Processor implementing this interface will be reset when Logger::reset() is called. + * + * Resetting ends a log cycle gets them back to their initial state. + * + * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal + * state, and getting it back to a state in which it can receive log records again. + * + * This is useful in case you want to avoid logs leaking between two requests or jobs when you + * have a long running process like a worker or an application server serving multiple requests + * in one process. + * + * @author Grégoire Pineau <lyrixx@lyrixx.info> + */ +interface ResettableInterface +{ + public function reset(): void; +} diff --git a/vendor/monolog/monolog/src/Monolog/SignalHandler.php b/vendor/monolog/monolog/src/Monolog/SignalHandler.php new file mode 100644 index 0000000..b6a69fc --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/SignalHandler.php @@ -0,0 +1,113 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; +use ReflectionExtension; + +/** + * Monolog POSIX signal handler + * + * @author Robert Gust-Bardon <robert@gust-bardon.org> + */ +class SignalHandler +{ + private LoggerInterface $logger; + + /** @var array<int, callable|string|int> SIG_DFL, SIG_IGN or previous callable */ + private array $previousSignalHandler = []; + /** @var array<int, \Psr\Log\LogLevel::*> */ + private array $signalLevelMap = []; + /** @var array<int, bool> */ + private array $signalRestartSyscalls = []; + + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; + } + + /** + * @param int|string|Level $level Level or level name + * @return $this + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + public function registerSignalHandler(int $signo, int|string|Level $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self + { + if (!\extension_loaded('pcntl') || !\function_exists('pcntl_signal')) { + return $this; + } + + $level = Logger::toMonologLevel($level)->toPsrLogLevel(); + + if ($callPrevious) { + $handler = pcntl_signal_get_handler($signo); + $this->previousSignalHandler[$signo] = $handler; + } else { + unset($this->previousSignalHandler[$signo]); + } + $this->signalLevelMap[$signo] = $level; + $this->signalRestartSyscalls[$signo] = $restartSyscalls; + + if ($async !== null) { + pcntl_async_signals($async); + } + + pcntl_signal($signo, [$this, 'handleSignal'], $restartSyscalls); + + return $this; + } + + /** + * @param mixed $siginfo + */ + public function handleSignal(int $signo, $siginfo = null): void + { + /** @var array<int, string> $signals */ + static $signals = []; + + if (\count($signals) === 0 && \extension_loaded('pcntl')) { + $pcntl = new ReflectionExtension('pcntl'); + foreach ($pcntl->getConstants() as $name => $value) { + if (substr($name, 0, 3) === 'SIG' && $name[3] !== '_' && \is_int($value)) { + $signals[$value] = $name; + } + } + } + + $level = $this->signalLevelMap[$signo] ?? LogLevel::CRITICAL; + $signal = $signals[$signo] ?? $signo; + $context = $siginfo ?? []; + $this->logger->log($level, sprintf('Program received signal %s', $signal), $context); + + if (!isset($this->previousSignalHandler[$signo])) { + return; + } + + if ($this->previousSignalHandler[$signo] === SIG_DFL) { + if (\extension_loaded('pcntl') && \function_exists('pcntl_signal') && \function_exists('pcntl_sigprocmask') && \function_exists('pcntl_signal_dispatch') + && \extension_loaded('posix') && \function_exists('posix_getpid') && \function_exists('posix_kill') + ) { + $restartSyscalls = $this->signalRestartSyscalls[$signo] ?? true; + pcntl_signal($signo, SIG_DFL, $restartSyscalls); + pcntl_sigprocmask(SIG_UNBLOCK, [$signo], $oldset); + posix_kill(posix_getpid(), $signo); + pcntl_signal_dispatch(); + pcntl_sigprocmask(SIG_SETMASK, $oldset); + pcntl_signal($signo, [$this, 'handleSignal'], $restartSyscalls); + } + } elseif (\is_callable($this->previousSignalHandler[$signo])) { + $this->previousSignalHandler[$signo]($signo, $siginfo); + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Test/MonologTestCase.php b/vendor/monolog/monolog/src/Monolog/Test/MonologTestCase.php new file mode 100644 index 0000000..34c7724 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Test/MonologTestCase.php @@ -0,0 +1,71 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Test; + +use Monolog\Level; +use Monolog\Logger; +use Monolog\LogRecord; +use Monolog\JsonSerializableDateTimeImmutable; +use Monolog\Formatter\FormatterInterface; +use Psr\Log\LogLevel; + +/** + * Lets you easily generate log records and a dummy formatter for testing purposes + * + * @author Jordi Boggiano <j.boggiano@seld.be> + */ +class MonologTestCase extends \PHPUnit\Framework\TestCase +{ + /** + * @param array<mixed> $context + * @param array<mixed> $extra + * + * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level + */ + protected function getRecord(int|string|Level $level = Level::Warning, string|\Stringable $message = 'test', array $context = [], string $channel = 'test', \DateTimeImmutable $datetime = new JsonSerializableDateTimeImmutable(true), array $extra = []): LogRecord + { + return new LogRecord( + message: (string) $message, + context: $context, + level: Logger::toMonologLevel($level), + channel: $channel, + datetime: $datetime, + extra: $extra, + ); + } + + /** + * @phpstan-return list<LogRecord> + */ + protected function getMultipleRecords(): array + { + return [ + $this->getRecord(Level::Debug, 'debug message 1'), + $this->getRecord(Level::Debug, 'debug message 2'), + $this->getRecord(Level::Info, 'information'), + $this->getRecord(Level::Warning, 'warning'), + $this->getRecord(Level::Error, 'error'), + ]; + } + + protected function getIdentityFormatter(): FormatterInterface + { + $formatter = $this->createMock(FormatterInterface::class); + $formatter->expects(self::any()) + ->method('format') + ->willReturnCallback(function ($record) { + return $record->message; + }); + + return $formatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Test/TestCase.php b/vendor/monolog/monolog/src/Monolog/Test/TestCase.php new file mode 100644 index 0000000..bf40b31 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Test/TestCase.php @@ -0,0 +1,23 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Test; + +/** + * Lets you easily generate log records and a dummy formatter for testing purposes + * + * @author Jordi Boggiano <j.boggiano@seld.be> + * + * @deprecated use MonologTestCase instead. + */ +class TestCase extends MonologTestCase +{ +} diff --git a/vendor/monolog/monolog/src/Monolog/Utils.php b/vendor/monolog/monolog/src/Monolog/Utils.php new file mode 100644 index 0000000..a425f34 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Utils.php @@ -0,0 +1,327 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\WrappingFormatterInterface; + +final class Utils +{ + const DEFAULT_JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR; + + /** @var array<class-string, array<string, true>> */ + private static array $sensitiveParameterNames = []; + + public static function getClass(object $object): string + { + return self::getClassName(\get_class($object)); + } + + /** + * Strips the declaration site PHP appends to anonymous class names after a NUL byte + * + * Takes the name rather than the object because stack trace frames only carry the string. + * + * @param class-string $class + */ + public static function getClassName(string $class): string + { + if (false === ($pos = strpos($class, "@anonymous\0"))) { + return $class; + } + + if (false === ($parent = get_parent_class($class))) { + return substr($class, 0, $pos + 10); + } + + return $parent . '@anonymous'; + } + + /** + * Returns the names of the constructor parameters of a class which are marked #[SensitiveParameter] + * + * The attribute can only target parameters, and PHP does not copy it over to the promoted + * property, so the constructor signature is the only place it can be found. Non-promoted + * parameters are included too, to be matched by name against the object's properties, as + * assigning a sensitive parameter to a same-named property is just as common. + * + * Results are cached per class as the reflection cost is otherwise prohibitive. + * + * @param class-string $class + * @return array<string, true> Set of parameter names, to be used with isset() + */ + public static function getSensitiveParameterNames(string $class): array + { + if (isset(self::$sensitiveParameterNames[$class])) { + return self::$sensitiveParameterNames[$class]; + } + + $names = []; + try { + $constructor = (new \ReflectionClass($class))->getConstructor(); + if (null !== $constructor) { + foreach ($constructor->getParameters() as $parameter) { + // filtering by name and not IS_INSTANCEOF on purpose, so this keeps working + // on PHP < 8.2 where the attribute class does not exist yet + if (\count($parameter->getAttributes(\SensitiveParameter::class)) > 0) { + $names[$parameter->getName()] = true; + } + } + } + } catch (\ReflectionException) { + // class is not loadable, nothing we can do + } + + return self::$sensitiveParameterNames[$class] = $names; + } + + /** + * Resolves a chain of formatter decorators down to the formatter doing the actual work + * + * Useful for handlers which only accept one specific formatter, to let them accept it + * wrapped in a decorator like the RedactingFormatter. + */ + public static function unwrapFormatter(FormatterInterface $formatter): FormatterInterface + { + // bounded in case a decorator ends up wrapping itself + for ($i = 0; $i < 10 && $formatter instanceof WrappingFormatterInterface; $i++) { + $formatter = $formatter->getWrappedFormatter(); + } + + return $formatter; + } + + public static function substr(string $string, int $start, ?int $length = null): string + { + if (\extension_loaded('mbstring')) { + return mb_strcut($string, $start, $length); + } + + return substr($string, $start, (null === $length) ? \strlen($string) : $length); + } + + /** + * Makes sure if a relative path is passed in it is turned into an absolute path + * + * @param string $streamUrl stream URL or path without protocol + */ + public static function canonicalizePath(string $streamUrl): string + { + $prefix = ''; + if ('file://' === substr($streamUrl, 0, 7)) { + $streamUrl = substr($streamUrl, 7); + $prefix = 'file://'; + } + + // other type of stream, not supported + if (false !== strpos($streamUrl, '://')) { + return $streamUrl; + } + + // already absolute + if (substr($streamUrl, 0, 1) === '/' || substr($streamUrl, 1, 1) === ':' || substr($streamUrl, 0, 2) === '\\\\') { + return $prefix.$streamUrl; + } + + $streamUrl = getcwd() . '/' . $streamUrl; + + return $prefix.$streamUrl; + } + + /** + * Return the JSON representation of a value + * + * @param mixed $data + * @param int $encodeFlags flags to pass to json encode, defaults to DEFAULT_JSON_FLAGS + * @param bool $ignoreErrors whether to ignore encoding errors or to throw on error, when ignored and the encoding fails, "null" is returned which is valid json for null + * @throws \RuntimeException if encoding fails and errors are not ignored + * @return string when errors are ignored and the encoding fails, "null" is returned which is valid json for null + */ + public static function jsonEncode($data, ?int $encodeFlags = null, bool $ignoreErrors = false): string + { + if (null === $encodeFlags) { + $encodeFlags = self::DEFAULT_JSON_FLAGS; + } + + if ($ignoreErrors) { + $json = @json_encode($data, $encodeFlags); + if (false === $json) { + return 'null'; + } + + return $json; + } + + $json = json_encode($data, $encodeFlags); + if (false === $json) { + $json = self::handleJsonError(json_last_error(), $data); + } + + return $json; + } + + /** + * Handle a json_encode failure. + * + * If the failure is due to invalid string encoding, try to clean the + * input and encode again. If the second encoding attempt fails, the + * initial error is not encoding related or the input can't be cleaned then + * raise a descriptive exception. + * + * @param int $code return code of json_last_error function + * @param mixed $data data that was meant to be encoded + * @param int $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION + * @throws \RuntimeException if failure can't be corrected + * @return string JSON encoded data after error correction + */ + public static function handleJsonError(int $code, $data, ?int $encodeFlags = null): string + { + if ($code !== JSON_ERROR_UTF8) { + self::throwEncodeError($code, $data); + } + + if (\is_string($data)) { + self::detectAndCleanUtf8($data); + } elseif (\is_array($data)) { + array_walk_recursive($data, ['Monolog\Utils', 'detectAndCleanUtf8']); + } else { + self::throwEncodeError($code, $data); + } + + if (null === $encodeFlags) { + $encodeFlags = self::DEFAULT_JSON_FLAGS; + } + + $json = json_encode($data, $encodeFlags); + + if ($json === false) { + self::throwEncodeError(json_last_error(), $data); + } + + return $json; + } + + /** + * Throws an exception according to a given code with a customized message + * + * @param int $code return code of json_last_error function + * @param mixed $data data that was meant to be encoded + * @throws \RuntimeException + */ + private static function throwEncodeError(int $code, $data): never + { + $msg = match ($code) { + JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', + JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', + default => 'Unknown error', + }; + + throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true)); + } + + /** + * Detect invalid UTF-8 string characters and convert to valid UTF-8. + * + * Valid UTF-8 input will be left unmodified, but strings containing + * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed + * original encoding of ISO-8859-15. This conversion may result in + * incorrect output if the actual encoding was not ISO-8859-15, but it + * will be clean UTF-8 output and will not rely on expensive and fragile + * detection algorithms. + * + * Function converts the input in place in the passed variable so that it + * can be used as a callback for array_walk_recursive. + * + * @param mixed $data Input to check and convert if needed, passed by ref + */ + private static function detectAndCleanUtf8(&$data): void + { + if (\is_string($data) && preg_match('//u', $data) !== 1) { + $data = preg_replace_callback( + '/[\x80-\xFF]+/', + function (array $m): string { + return \function_exists('mb_convert_encoding') + ? mb_convert_encoding($m[0], 'UTF-8', 'ISO-8859-1') + : (\function_exists('utf8_encode') ? utf8_encode($m[0]) : ''); + }, + $data + ); + if (!\is_string($data)) { + $pcreErrorCode = preg_last_error(); + + throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); + } + $data = str_replace( + ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'], + ['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'], + $data + ); + } + } + + /** + * Converts a string with a valid 'memory_limit' format, to bytes. + * + * @param string|false $val + * @return int|false Returns an integer representing bytes. Returns FALSE in case of error. + */ + public static function expandIniShorthandBytes($val) + { + if (!\is_string($val)) { + return false; + } + + // support -1 + if ((int) $val < 0) { + return (int) $val; + } + + if (!(bool) preg_match('/^\s*(?<val>\d+)(?:\.\d+)?\s*(?<unit>[gmk]?)\s*$/i', $val, $match)) { + return false; + } + + $val = (int) $match['val']; + switch (strtolower($match['unit'])) { + case 'g': + $val *= 1024; + // no break + case 'm': + $val *= 1024; + // no break + case 'k': + $val *= 1024; + } + + return $val; + } + + public static function getRecordMessageForException(LogRecord $record): string + { + $context = ''; + $extra = ''; + + try { + if (\count($record->context) > 0) { + $context = "\nContext: " . json_encode($record->context, JSON_THROW_ON_ERROR); + } + if (\count($record->extra) > 0) { + $extra = "\nExtra: " . json_encode($record->extra, JSON_THROW_ON_ERROR); + } + } catch (\Throwable $e) { + // noop + } + + return "\nThe exception occurred while attempting to log: " . $record->message . $context . $extra; + } +} diff --git a/vendor/nette/schema/composer.json b/vendor/nette/schema/composer.json new file mode 100644 index 0000000..39eded8 --- /dev/null +++ b/vendor/nette/schema/composer.json @@ -0,0 +1,45 @@ +{ + "name": "nette/schema", + "description": "📐 Nette Schema: validates and normalizes data such as configuration or API input against a schema described in a few readable lines of PHP, with precise error messages.", + "keywords": ["nette", "schema", "validation", "data validation", "normalization", "configuration"], + "homepage": "https://doc.nette.org/schema", + "license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + } + ], + "require": { + "php": "8.1 - 8.6", + "nette/utils": "^4.0" + }, + "require-dev": { + "nette/tester": "^2.6", + "tracy/tracy": "^2.8", + "phpstan/phpstan": "^2.3@stable", + "phpstan/extension-installer": "^1.4@stable", + "nette/phpstan-rules": "^1.0.7" + }, + "autoload": { + "classmap": ["src/"], + "psr-4": { + "Nette\\": "src" + } + }, + "minimum-stability": "dev", + "scripts": { + "phpstan": "phpstan analyse", + "tester": "tester tests -s" + }, + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "config": { + "allow-plugins": { + "phpstan/extension-installer": true + } + } +} diff --git a/vendor/nette/schema/license.md b/vendor/nette/schema/license.md new file mode 100644 index 0000000..cf741bd --- /dev/null +++ b/vendor/nette/schema/license.md @@ -0,0 +1,60 @@ +Licenses +======== + +Good news! You may use Nette Framework under the terms of either +the New BSD License or the GNU General Public License (GPL) version 2 or 3. + +The BSD License is recommended for most projects. It is easy to understand and it +places almost no restrictions on what you can do with the framework. If the GPL +fits better to your project, you can use the framework under this license. + +You don't have to notify anyone which license you are using. You can freely +use Nette Framework in commercial projects as long as the copyright header +remains intact. + +Please be advised that the name "Nette Framework" is a protected trademark and its +usage has some limitations. So please do not use word "Nette" in the name of your +project or top-level domain, and choose a name that stands on its own merits. +If your stuff is good, it will not take long to establish a reputation for yourselves. + + +New BSD License +--------------- + +Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of "Nette Framework" nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as is" and +any express or implied warranties, including, but not limited to, the implied +warranties of merchantability and fitness for a particular purpose are +disclaimed. In no event shall the copyright owner or contributors be liable for +any direct, indirect, incidental, special, exemplary, or consequential damages +(including, but not limited to, procurement of substitute goods or services; +loss of use, data, or profits; or business interruption) however caused and on +any theory of liability, whether in contract, strict liability, or tort +(including negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. + + +GNU General Public License +-------------------------- + +GPL licenses are very very long, so instead of including them here we offer +you URLs with full text: + +- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html) +- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html) diff --git a/vendor/nette/schema/readme.md b/vendor/nette/schema/readme.md new file mode 100644 index 0000000..bd9cdbf --- /dev/null +++ b/vendor/nette/schema/readme.md @@ -0,0 +1,802 @@ +# Nette Schema + +[![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema) +[![Coverage Status](https://coveralls.io/repos/github/nette/schema/badge.svg?branch=master)](https://coveralls.io/github/nette/schema?branch=master) +[![Latest Stable Version](https://poser.pugx.org/nette/schema/v/stable)](https://github.com/nette/schema/releases) +[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/schema/blob/master/license.md) + + +Introduction +============ + +A practical library for validating and normalizing data structures against a given schema with a smart, easy-to-understand API. + +Documentation can be found on the [website](https://doc.nette.org/schema). + +Installation: + +```shell +composer require nette/schema +``` + +It requires PHP version 8.1 and supports PHP up to 8.6. + + +[Support Me](https://github.com/sponsors/dg) +-------------------------------------------- + +Do you like Nette Schema? Are you looking forward to the new features? + +[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg) + +Thank you! + + +Basic Usage +----------- + +In the variable `$schema`, we have a validation schema (we'll explain what this means and how to create one in a moment), and in the variable `$data`, we have the data structure we want to validate and normalize. This could be, for example, data submitted by a user via an API, a configuration file, etc. + +The task is handled by the [Nette\Schema\Processor](https://api.nette.org/schema/master/Nette/Schema/Processor.html) class, which processes the input and either returns normalized data or throws a [Nette\Schema\ValidationException](https://api.nette.org/schema/master/Nette/Schema/ValidationException.html) exception if an error occurs. + +```php +$processor = new Nette\Schema\Processor; + +try { + $normalized = $processor->process($schema, $data); +} catch (Nette\Schema\ValidationException $e) { + echo 'Data is invalid: ' . $e->getMessage(); +} +``` + +The method `$e->getMessages()` returns an array of all messages as strings, and `$e->getMessageObjects()` returns all messages as [Nette\Schema\Message](https://api.nette.org/schema/master/Nette/Schema/Message.html) objects. + + +Defining the Schema +------------------- + +And now let's create the schema. The class [Nette\Schema\Expect](https://api.nette.org/schema/master/Nette/Schema/Expect.html) is used to define it; we essentially define expectations for what the data should look like. Let's say the input data must be a structure (e.g., an array) containing elements `processRefund` of type bool and `refundAmount` of type int. + +```php +use Nette\Schema\Expect; + +$schema = Expect::structure([ + 'processRefund' => Expect::bool(), + 'refundAmount' => Expect::int(), +]); +``` + +We believe the schema definition looks understandable, even if you're seeing it for the first time. + +Let's send the following data for validation: + +```php +$data = [ + 'processRefund' => true, + 'refundAmount' => 17, +]; + +$normalized = $processor->process($schema, $data); // OK, passes validation +``` + +The output, i.e., the value `$normalized`, is a `stdClass` object. If we wanted the output to be an array, we would add casting `->castTo('array')` to the schema. + +All elements of the structure are optional and have a default value of `null`. Example: + +```php +$data = [ + 'refundAmount' => 17, +]; + +$normalized = $processor->process($schema, $data); // OK, passes validation +// $normalized = {'processRefund' => null, 'refundAmount' => 17} +``` + +The fact that the default value is `null` does not mean it would accept `'processRefund' => null` in the input data. No, the input must be a boolean, i.e. `true` or `false` only. We would have to explicitly allow `null` using `Expect::bool()->nullable()`. + +An item can be made mandatory using `Expect::bool()->required()`. We can change the default value, for example, to `false` using `Expect::bool()->default(false)` or shorthand `Expect::bool(false)`. + +And what if we wanted to accept `1` and `0` in addition to booleans? Then we list the values that we also want to normalize to boolean: + +```php +$schema = Expect::structure([ + 'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'), + 'refundAmount' => Expect::int(), +]); + +$normalized = $processor->process($schema, $data); +is_bool($normalized->processRefund); // true +``` + +Now you know the basics of defining a schema and how the structure items behave. We will now show what other elements you can use when defining a schema. + + +Data Types: type() +------------------ + +All standard PHP data types can be specified in the schema: + +```php +Expect::string($default = null) +Expect::int($default = null) +Expect::float($default = null) +Expect::bool($default = null) +Expect::null() +Expect::array($default = []) +Expect::list($default = []) +``` + +And also all types [supported by the Validators class](https://doc.nette.org/validators#toc-expected-types), for example `Expect::type('scalar')` or shorthand `Expect::scalar()`. Also class or interface names, e.g., `Expect::type('AddressEntity')`. + +Union syntax can also be used: + +```php +Expect::type('bool|string|array') +``` + +The default value is always `null` with the exception of `array` and `list`, where it is an empty array. (A list is an array indexed by a sequence of numeric keys starting from zero, i.e. a non-associative array). + + +Array of Values: arrayOf() listOf() +----------------------------------- + +An array represents too general a structure; it's more useful to specify precisely which elements it may contain. For example, an array whose elements can only be strings: + +```php +$schema = Expect::arrayOf('string'); + +$processor->process($schema, ['hello', 'world']); // OK +$processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK +$processor->process($schema, ['key' => 123]); // ERROR: 123 is not a string +``` + +The second parameter can specify keys (since version 1.2): + +```php +$schema = Expect::arrayOf('string', 'int'); + +$processor->process($schema, ['hello', 'world']); // OK +$processor->process($schema, ['a' => 'hello']); // ERROR: 'a' is not an int +``` + +A list is an indexed array: + +```php +$schema = Expect::listOf('string'); + +$processor->process($schema, ['a', 'b']); // OK +$processor->process($schema, ['a', 123]); // ERROR: 123 is not a string +$processor->process($schema, ['key' => 'a']); // ERROR: not a list +$processor->process($schema, [1 => 'a', 0 => 'b']); // ERROR: also not a list +``` + +With the `wrap` parameter, a single value is also accepted and wrapped into a one-item list (since version 1.4): + +```php +$schema = Expect::listOf('string', wrap: true); + +$processor->process($schema, 'hello'); // OK, gives ['hello'] +$processor->process($schema, ['a', 'b']); // OK +``` + +The parameter can also be a schema, so we can write: + +```php +Expect::arrayOf(Expect::bool()) +``` + +The default value is an empty array. If you specify a default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)` (since version 1.1). + + +Enumeration: anyOf() +-------------------- + +`anyOf()` represents a set of values or schemas that a value can take. Here's how to write an array of elements that can be either `'a'`, `true`, or `null`: + +```php +$schema = Expect::listOf( + Expect::anyOf('a', true, null), +); + +$processor->process($schema, ['a', true, null, 'a']); // OK +$processor->process($schema, ['a', false]); // ERROR: false does not belong there +``` + +The elements of the enumeration can also be schemas: + +```php +$schema = Expect::listOf( + Expect::anyOf(Expect::string(), true, null), +); + +$processor->process($schema, ['foo', true, null, 'bar']); // OK +$processor->process($schema, [123]); // ERROR +``` + +The `anyOf()` method accepts variants as separate parameters, not as an array. To pass it an array of values, use the unpack operator `anyOf(...$variants)`. + +Variants are tried in the order they are written and the first matching one wins. The single exception is `null`: when it belongs to the accepted values, a `null` input always gives `null`, even though a structure or an array variant would otherwise read it as an empty value of its own. + +The default value is `null`. Use the `firstIsDefault()` method to make the first item the default: + +```php +// default is 'hello' +Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault(); +``` + + +Enums: enum() +------------- + +A configuration file can only carry a plain string like `'hearts'`, but in your code you would much rather work with an enum. That is the gap `enum()` closes (since version 1.4): give it an enum with a backing value (`enum Suit: string`) and it accepts either the backing value or the case itself, always handing you back the case: + +```php +enum Suit: string +{ + case Hearts = 'hearts'; + case Spades = 'spades'; +} + +$schema = Expect::enum(Suit::class); + +$processor->process($schema, 'hearts'); // OK, returns Suit::Hearts +$processor->process($schema, Suit::Spades); // OK, returns Suit::Spades +$processor->process($schema, 'clubs'); // ERROR: expects to be Suit +``` + +Enums backed by integers work exactly the same, and so does everything you know from the other elements, such as `Expect::enum(Suit::class)->required()` or `->default(Suit::Hearts)`. + +When [generating a schema from a class](#mapping-to-objects-from), a `public Suit $suit` property gives you this very element, so you do not have to reach for `enum()` there. `Expect::type(Suit::class)` is a different thing: like any class name, it accepts only an instance, i.e. the case itself. + + +Structures +---------- + +Structures are objects with defined keys. Each key-value pair is referred to as a "property". + +Structures accept arrays and objects and return `stdClass` objects. + +By default, all properties are optional and have a default value of `null`. You can define mandatory properties using `required()`: + +```php +$schema = Expect::structure([ + 'required' => Expect::string()->required(), + 'optional' => Expect::string(), // default value is null +]); + +$processor->process($schema, ['optional' => '']); +// ERROR: the mandatory item 'required' is missing + +$processor->process($schema, ['required' => 'foo']); +// OK, returns {'required' => 'foo', 'optional' => null} +``` + +A structure itself is mandatory. Therefore, if it is nested inside another structure and the input does not contain it, it is created anyway - and it reports an error when it contains a required property. Use `required(false)` to make the entire nested structure optional. If it is missing in the input, `null` appears in the output, but if it is present, its required properties are enforced: + +```php +$schema = Expect::structure([ + 'db' => Expect::structure([ + 'dsn' => Expect::string()->required(), + ])->required(false), +]); + +$processor->process($schema, []); +// OK, returns {'db' => null} + +$processor->process($schema, ['db' => []]); +// ERROR: 'db › dsn' is missing +``` + +If you do not want properties with default values in the output, use `skipDefaults()`: + +```php +$schema = Expect::structure([ + 'required' => Expect::string()->required(), + 'optional' => Expect::string(), +])->skipDefaults(); + +$processor->process($schema, ['required' => 'foo']); +// OK, returns {'required' => 'foo'} +``` + +Although `null` is the default value for the `optional` property, it is not allowed in input data (the value must be a string). Properties accepting `null` are defined using `nullable()`: + +```php +$schema = Expect::structure([ + 'optional' => Expect::string(), + 'nullable' => Expect::string()->nullable(), +]); + +$processor->process($schema, ['optional' => null]); +// ERROR: 'optional' expects to be string, null given. + +$processor->process($schema, ['nullable' => null]); +// OK, returns {'optional' => null, 'nullable' => null} +``` + +The array of all structure properties is returned by the `getShape()` method. + +By default, no additional items can be present in the input data: + +```php +$schema = Expect::structure([ + 'key' => Expect::string(), +]); + +$processor->process($schema, ['additional' => 1]); +// ERROR: Unexpected item 'additional' +``` + +This can be changed using `otherItems()`. As a parameter, pass the schema to validate each extra item: + +```php +$schema = Expect::structure([ + 'key' => Expect::string(), +])->otherItems(Expect::int()); + +$processor->process($schema, ['additional' => 1]); // OK +$processor->process($schema, ['additional' => true]); // ERROR +``` + +You can create a new structure by extending another using `extend()`: + +```php +$dog = Expect::structure([ + 'name' => Expect::string(), + 'age' => Expect::int(), +]); + +$dogWithBreed = $dog->extend([ + 'breed' => Expect::string(), +]); +``` + + +Array +----- + +An array with defined keys (since version 1.3.2). Everything that applies to [structures](#structures) applies to it. + +```php +$schema = Expect::array([ + 'required' => Expect::string()->required(), + 'optional' => Expect::string(), // default value is null +]); +``` + +Tuples: tuple() +--------------- + +A tuple is a fixed-size array where each position has its own schema (since version 1.4): + +```php +$schema = Expect::tuple([ + Expect::int(), + Expect::string(), + Expect::bool(), +]); + +$processor->process($schema, [1, 'hello', true]); // OK +``` + +The input must be a list, positions given by keys or in another order are refused. When configurations are layered, a later tuple replaces the earlier one wholesale - mixing positions of two tuples is never what you meant. Positions beyond the shape can be allowed with `otherItems()`, which describes the rest elements, and `extend()` appends further positions. + +Unlike a structure, a tuple does not accept `null` as an empty value; call `nullable()` when `null` is a valid value. + + +Deprecated Properties +--------------------- + +You can mark a property as deprecated using the `deprecated([string $message])` method. Information about deprecation is returned using `$processor->getWarnings()`: + +```php +$schema = Expect::structure([ + 'old' => Expect::int()->deprecated('The item %path% is deprecated'), +]); + +$processor->process($schema, ['old' => 1]); // OK +$processor->getWarnings(); // ["The item 'old' is deprecated"] +``` + + +Description: description() +-------------------------- + +Any element can carry a human-readable description (since version 1.4). It has no effect on validation - the schema is often the only place where the meaning of a configuration option is written down at all, and `description()` is where you write it. It also travels into the [JSON Schema export](#exporting-to-json-schema): + +```php +$schema = Expect::structure([ + 'host' => Expect::string('localhost')->description('Database server hostname'), + 'port' => Expect::int(3306)->description('Port the server listens on'), +])->description('Database connection'); +``` + + +Ranges: min() max() +------------------- + +Use `min()` and `max()` to limit the count for arrays: + +```php +// array, at least 10 items, maximum 20 items +Expect::array()->min(10)->max(20); +``` + +For strings, they limit the length: + +```php +// string, at least 10 bytes long, maximum 20 bytes +Expect::string()->min(10)->max(20); +``` + +The length of a string is measured in bytes. To count characters of a UTF-8 string, use `Expect::unicode()`. + +For numbers, they limit the value: + +```php +// integer, between 10 and 20 inclusive +Expect::int()->min(10)->max(20); +``` + +Of course, it is possible to specify just `min()` or just `max()`: + +```php +// string, maximum 20 bytes +Expect::string()->max(20); +``` + + +Regular Expressions: pattern() +------------------------------ + +Using `pattern()`, you can specify a regular expression that the **entire** input string must match (i.e. as if it were wrapped in `^` and `$` characters): + +```php +// exactly 9 digits +Expect::string()->pattern('\d{9}'); +``` + +A pattern belongs to strings, just like `items()` belongs to arrays. Attach either of them to an element of a different kind and Schema raises a deprecation notice instead of silently ignoring the constraint (since version 1.4). + + +Custom Assertions: assert() +--------------------------- + +You can add any other constraints using `assert(callable $fn)`. + +```php +$countIsEven = fn($v) => count($v) % 2 === 0; + +$schema = Expect::arrayOf('string') + ->assert($countIsEven); // the count must be even + +$processor->process($schema, ['a', 'b']); // OK +$processor->process($schema, ['a', 'b', 'c']); // ERROR: 3 is not an even count +``` + +Or + +```php +Expect::string()->assert('is_file'); // file must exist +``` + +You can add a custom description to each assertion. It will be part of the error message. + +```php +$schema = Expect::arrayOf('string') + ->assert($countIsEven, 'Even items in array'); + +$processor->process($schema, ['a', 'b', 'c']); +// Failed assertion "Even items in array" for item with value array. +``` + +The method can be called repeatedly to add multiple constraints. It can be interleaved with calls to `transform()` and `castTo()`. + + +Transformation: transform() +--------------------------- + +Successfully validated data can be modified using a custom function: + +```php +// convert to uppercase: +Expect::string()->transform(fn(string $s) => strtoupper($s)); +``` + +The method can be called repeatedly to add multiple transformations. It can be interleaved with calls to `assert()` and `castTo()`. The operations are performed in the order in which they are declared: + +```php +Expect::type('string|int') + ->castTo('string') + ->assert('ctype_lower', 'All characters must be lowercased') + ->transform(fn(string $s) => strtoupper($s)); // convert to uppercase +``` + +The `transform()` method can simultaneously transform and validate the value. This is often simpler and involves less code duplication than chaining `transform()` and `assert()`. For this purpose, the function receives a [Nette\Schema\Context](https://api.nette.org/schema/master/Nette/Schema/Context.html) object with an `addError()` method, which can be used to add information about validation problems: + +```php +Expect::string() + ->transform(function (string $s, Nette\Schema\Context $context) { + if (!ctype_lower($s)) { + $context->addError('All characters must be lowercased', 'my.case.error'); + return null; + } + + return strtoupper($s); + }); +``` + + +Casting: castTo() +----------------- + +Successfully validated data can be cast: + +```php +Expect::scalar()->castTo('string'); +``` + +In addition to native PHP types, you can also cast to classes. It distinguishes between a simple class without a constructor and a class with a constructor. If the class has no constructor, an instance is created, and all structure elements are written to the properties: + +```php +class Info +{ + public bool $processRefund; + public int $refundAmount; +} + +Expect::structure([ + 'processRefund' => Expect::bool(), + 'refundAmount' => Expect::int(), +])->castTo(Info::class); + +// creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount +``` + +If the class has a constructor, the structure elements are passed as named arguments to the constructor: + +```php +class Info +{ + public function __construct( + public bool $processRefund, + public int $refundAmount, + ) { + } +} + +// creates $obj = new Info(processRefund: ..., refundAmount: ...) +``` + +Casting combined with a scalar parameter creates an object and passes the value as the single argument to the constructor: + +```php +Expect::string()->castTo(DateTime::class); +// creates new DateTime(...) +``` + + +Normalization: before() +----------------------- + +Before the validation itself, the data can be normalized using the `before()` method. As an example, let's take an element that must be an array of strings (e.g., `['a', 'b', 'c']`), but accepts input in the form of string `a b c`: + +```php +$explode = fn($v) => explode(' ', $v); + +$schema = Expect::arrayOf('string') + ->before($explode); + +$normalized = $processor->process($schema, 'a b c'); +// OK and returns ['a', 'b', 'c'] +``` + +An element has one handler: a second call to `before()` replaces the first one and raises a deprecation notice (since version 1.4), because in version 2.0 the handlers will be chained, each receiving the result of the previous one. Put all the normalization into one handler instead. + + +Mapping to Objects: from() +-------------------------- + +You can have the structure schema generated from a class. Example: + +```php +class Config +{ + public string $name; + public string|null $password = null; + public bool $admin = false; +} + +$schema = Expect::from(new Config); + +$data = [ + 'name' => 'Frank', +]; + +$normalized = $processor->process($schema, $data); +// $normalized instanceof Config +// $normalized = {'name' => 'Frank', 'password' => null, 'admin' => false} +``` + +Anonymous classes are also supported: + +```php +$schema = Expect::from(new class { + public string $name; + public ?string $password = null; + public bool $admin = false; +}); +``` + +Because the information obtained from the class definition may not be sufficient, you can supplement the elements with your own schema using the second parameter: + +```php +$schema = Expect::from(new Config, [ + 'name' => Expect::string()->pattern('\w:.*'), +]); +``` + + +Merging Multiple Configurations +------------------------------- + +Applications often assemble their configuration in layers: there are built-in default values, and on top of them the user supplies their own settings, which should override only the items they actually specify. That is exactly what `processMultiple()` does - it takes several datasets, merges them in order so that later ones take precedence, and validates the final result as a whole: + +```php +$schema = Expect::structure([ + 'host' => Expect::string(), + 'port' => Expect::int(), + 'logging' => Expect::bool(), +]); + +$defaults = ['host' => 'localhost', 'port' => 3306, 'logging' => false]; +$userConfig = ['port' => 5432, 'logging' => true]; + +$config = $processor->processMultiple($schema, [$defaults, $userConfig]); +// $config = {'host' => 'localhost', 'port' => 5432, 'logging' => true} +``` + +The `host` item keeps its default value because the user did not set it, while `port` and `logging` are overwritten by the later dataset. Values stored under string keys are merged this way; the items of a list (`listOf()`, `arrayOf()`) are appended one after another instead of being overwritten. + +Arrays and structures can set their strategy with `mergeMode()` (since version 1.4): + +```php +use Nette\Schema\MergeMode; + +Expect::arrayOf('string')->mergeMode(MergeMode::Replace); // the later array replaces the earlier one +``` + +`MergeMode::AppendKeys` merges by keys and appends list items, `OverwriteKeys` merges by keys and overwrites list items by position, and `Replace` keeps only the later value. Without `mergeMode()`, an array whose items are not described is merged deeply. For anything else, `mergeWith()` takes your own function combining the later value with the earlier one: + +```php +Expect::bool()->mergeWith(fn($value, $base) => $value || $base); // once enabled, stays enabled +``` + + +Exporting to JSON Schema +------------------------ + +Your schema is already a precise description of what the configuration may contain, and that description is useful outside PHP as well. `JsonSchema::export()` (since version 1.4) turns it into a [JSON Schema](https://json-schema.org) document, the format editors read to offer completion and underline mistakes directly in the JSON or YAML file: + +```php +use Nette\Schema\JsonSchema; + +$schema = Expect::structure([ + 'host' => Expect::string('localhost')->description('Database server hostname'), + 'port' => Expect::int(3306)->min(1)->max(65535), + 'user' => Expect::string()->required(), +]); + +echo json_encode(JsonSchema::export($schema), JSON_PRETTY_PRINT); +``` + +```json +{ + "type": "object", + "properties": { + "host": {"type": "string", "description": "Database server hostname"}, + "port": {"type": "integer", "minimum": 1, "maximum": 65535}, + "user": {"type": "string"} + }, + "required": ["user"], + "additionalProperties": false +} +``` + +The export describes the **shape** of the data: types, ranges, patterns, required items, enum values and the texts you added with `description()`. Default values, `castTo()` and `transform()` are deliberately left out - they describe what happens to the data once it has been validated, and JSON Schema has no way to say that. + +For the same reason, a type that exists only in PHP - a class such as `Expect::type(Address::class)`, a callable or a resource - throws `Nette\NotSupportedException` instead of producing a document that would quietly claim something else. + +Two differences remain between the export and the validation. JSON Schema counts the length of a string in characters, while `Expect::string()` counts bytes, so use `Expect::unicode()` for text that is not plain ASCII. And a `pattern()` is exported as it is, but a JSON Schema validator reads it as an ECMAScript regular expression, so constructions specific to PCRE may be understood differently there. + + +Under the Hood: normalize, merge, complete +------------------------------------------ + +Every schema element - whether built-in or one you write yourself - implements four methods that together define how it handles data. Three of them form the processing pipeline: + +1. **normalize()** - prepares the raw input. This is where `before()` hooks run and where, for example, an object is turned into an array. It runs first, separately on each dataset. +2. **merge()** - combines two already normalized datasets, with the later one taking priority. This step is used only by `processMultiple()`; `process()` skips it, because it has just a single dataset. +3. **complete()** - performs the actual validation, fills in default values for missing items, and applies `assert()`, `transform()` and `castTo()`. It runs last, on the merged result. + +The fourth method, **completeDefault()**, is called by the parent element for an item entirely missing from the input - it either supplies the default value or reports that a `required()` item is missing. + +So `process()` runs *normalize → complete*, while `processMultiple()` runs *normalize (each dataset) → merge → complete*. This order is why `before()` sees the raw input, whereas `transform()` sees the already validated value. + + +Custom Schema Elements +---------------------- + +You can get a long way with `assert()`, `transform()` and `before()`, so you rarely need to build anything from scratch. But when you want a reusable, self-contained element with its own validation and merging logic, you can create one by implementing the [Nette\Schema\Schema](https://api.nette.org/schema/master/Nette/Schema/Schema.html) interface. It has exactly the four methods described above: + +```php +interface Schema +{ + function normalize(mixed $value, Context $context); + function merge(mixed $value, mixed $base); + function complete(mixed $value, Context $context); + function completeDefault(Context $context); +} +``` + +Errors are not thrown; instead you report them through the [Nette\Schema\Context](https://api.nette.org/schema/master/Nette/Schema/Context.html) object using `$context->addError()` and return `null`. The `Processor` gathers all errors and throws them together at the end. + +As an example, let's build a reusable element for byte sizes in the friendly notation people use in configuration files - `'512kB'`, `'2 MB'` - which validates them and returns the number of bytes: + +```php +use Nette\Schema\Context; +use Nette\Schema\Schema; + +class ByteSizeSchema implements Schema +{ + private const Units = ['b' => 1, 'kb' => 1024, 'mb' => 1024 ** 2, 'gb' => 1024 ** 3]; + + public function normalize(mixed $value, Context $context): mixed + { + return is_int($value) ? "$value B" : $value; // unify both notations + } + + public function merge(mixed $value, mixed $base): mixed + { + return $value ?? $base; // the later value wins + } + + public function complete(mixed $value, Context $context): mixed + { + if (!is_string($value) || !preg_match('~^(\d+)\s*([a-zA-Z]+)$~', $value, $m)) { + $context->addError("The item %path% expects to be a size like '512kB'.", 'size.format'); + return null; + } + + $unit = self::Units[strtolower($m[2])] ?? null; + if ($unit === null) { + $context->addError("The item %path% uses an unknown unit '$m[2]'.", 'size.unit'); + return null; + } + + return (int) $m[1] * $unit; + } + + public function completeDefault(Context $context): mixed + { + return null; // value used when the item is missing from the input + } +} +``` + +You can use it anywhere a built-in element is expected - on its own or as part of a larger structure: + +```php +$schema = Expect::structure([ + 'maxUpload' => new ByteSizeSchema, + 'diskQuota' => new ByteSizeSchema, +]); + +$processor->process($schema, ['maxUpload' => '2 MB', 'diskQuota' => 512]); +// OK, returns {'maxUpload' => 2097152, 'diskQuota' => 512} + +$processor->process($schema, ['maxUpload' => '5 TB']); +// ERROR: The item 'maxUpload' uses an unknown unit 'TB'. +``` + +Because the element implements the whole interface, it also works automatically inside `processMultiple()` - the `Processor` calls its `merge()` method just like for any other element. Only `JsonSchema::export()` cannot know what such an element accepts, so it throws `Nette\NotSupportedException`. diff --git a/vendor/nette/schema/src/Schema/Context.php b/vendor/nette/schema/src/Schema/Context.php new file mode 100644 index 0000000..e043e40 --- /dev/null +++ b/vendor/nette/schema/src/Schema/Context.php @@ -0,0 +1,66 @@ +<?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\Schema; + +use function count; + + +/** + * Accumulates errors and warnings during schema validation and tracks the current path. + */ +final class Context +{ + public bool $skipDefaults = false; + + /** + * @internal path at which a null is not coerced to an empty value, because the enclosing anyOf() accepts it + * @var ?list<int|string> + */ + public ?array $keepNullAt = null; + + /** @var list<int|string> */ + public array $path = []; + + public bool $isKey = false; + + /** @var list<Message> */ + public array $errors = []; + + /** @var list<Message> */ + public array $warnings = []; + + /** @var list<array{DynamicParameter, string, list<int|string>}> */ + public array $dynamics = []; + + + /** @param array<string, mixed> $variables */ + public function addError(string $message, string $code, array $variables = []): Message + { + $variables['isKey'] = $this->isKey; + return $this->errors[] = new Message($message, $code, $this->path, $variables); + } + + + /** @param array<string, mixed> $variables */ + public function addWarning(string $message, string $code, array $variables = []): Message + { + $variables['isKey'] = $this->isKey; + 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 + */ + public function createChecker(): \Closure + { + $count = count($this->errors); + return fn(): bool => $count === count($this->errors); + } +} diff --git a/vendor/nette/schema/src/Schema/DynamicParameter.php b/vendor/nette/schema/src/Schema/DynamicParameter.php new file mode 100644 index 0000000..35ec47d --- /dev/null +++ b/vendor/nette/schema/src/Schema/DynamicParameter.php @@ -0,0 +1,13 @@ +<?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\Schema; + + +interface DynamicParameter +{ +} diff --git a/vendor/nette/schema/src/Schema/Elements/AnyOf.php b/vendor/nette/schema/src/Schema/Elements/AnyOf.php new file mode 100644 index 0000000..dc3366e --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/AnyOf.php @@ -0,0 +1,212 @@ +<?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\Schema\Elements; + +use Nette; +use Nette\Schema\{Context, Helpers, Kind, Schema}; +use function 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; + + /** @var mixed[] */ + private array $set; + private bool $dynamic = false; + + + public function __construct(mixed ...$set) + { + if (!$set) { + throw new Nette\InvalidStateException('The enumeration must not be empty.'); + } + + $this->set = $set; + } + + + /** + * Sets the first variant as the default value (instead of null). + */ + public function firstIsDefault(): self + { + $this->default = $this->set[0]; + return $this; + } + + + /** + * Allows null as an accepted value in addition to the defined variants. + */ + public function nullable(): self + { + $this->set[] = null; + return $this; + } + + + /** + * Allows the value to be a DynamicParameter as an accepted variant. + */ + public function dynamic(): self + { + $this->dynamic = true; + return $this; + } + + + /********************* inspection ****************d*g**/ + + + /** + * Scalar variants are reported as 'values', schema variants as 'variants'; scalars alone make an Enum, + * anything with a schema variant a Union. + * @return array<string, mixed> + * @internal + */ + public function describe(): array + { + $values = $variants = []; + $nullable = false; + foreach ($this->set as $item) { + if ($item === null) { + $nullable = true; + } elseif (!$item instanceof Schema) { + $values[] = $item; + } else { + $variants[] = $item; + } + } + + return [ + 'kind' => match (true) { + (bool) $variants => Kind::Union, + (bool) $values => Kind::Enum, + default => $nullable ? Kind::Null : Kind::Any, + }, + 'values' => $values, + 'variants' => $variants, + 'nullable' => $nullable, + 'dynamic' => $this->dynamic, + ] + $this->describeBase(); + } + + + /********************* processing ****************d*g**/ + + + public function normalize(mixed $value, Context $context): mixed + { + return $this->doNormalize($value, $context); + } + + + public function merge(mixed $value, mixed $base): mixed + { + if (is_array($value) && isset($value[Helpers::PreventMerging])) { + unset($value[Helpers::PreventMerging]); + return $value; + } + + if ($this->mergeWith) { + return ($this->mergeWith)($value, $base); + } + + return Helpers::merge($value, $base); + } + + + public function complete(mixed $value, Context $context): mixed + { + $this->doDeprecation($context); + $isOk = $context->createChecker(); + $value = $this->findAlternative($value, $context); + $isOk() && $value = $this->doTransform($value, $context); + return $isOk() ? $value : null; + } + + + private function findAlternative(mixed $value, Context $context): mixed + { + $keepNullAt = $value === null && in_array(null, $this->set, true) + ? $context->path + : $context->keepNullAt; + + $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; + $dolly->keepNullAt = $keepNullAt; + $res = $item->complete($item->normalize($value, $dolly), $dolly); + if (!$dolly->errors) { + $context->warnings = [...$context->warnings, ...$dolly->warnings]; + $context->dynamics = [...$context->dynamics, ...$dolly->dynamics]; + return $res; + } + + foreach ($dolly->errors as $error) { + if ($error->path !== $context->path || empty($error->variables['expected'])) { + $innerErrors[] = $error; + } else { + $expecteds[] = $error->variables['expected']; + } + } + } else { + if ($item === $value) { + return $value; + } + + $expecteds[] = Nette\Schema\Helpers::formatValue($item); + } + } + + if ($this->dynamic && $value instanceof Nette\Schema\DynamicParameter) { + return $value; + } + + if ($innerErrors) { + $context->errors = [...$context->errors, ...$innerErrors]; + } else { + $context->addError( + 'The %label% %path% expects to be %expected%, %value% given.', + Nette\Schema\Message::TypeMismatch, + [ + 'value' => $value, + 'expected' => implode('|', array_unique($expecteds)), + ], + ); + } + + return null; + } + + + public function completeDefault(Context $context): mixed + { + if ($this->required) { + $context->addError( + 'The mandatory item %path% is missing.', + Nette\Schema\Message::MissingItem, + ); + return null; + } + + if ($this->default instanceof Schema) { + return $this->default->completeDefault($context); + } + + return $this->default; + } +} diff --git a/vendor/nette/schema/src/Schema/Elements/ArrayType.php b/vendor/nette/schema/src/Schema/Elements/ArrayType.php new file mode 100644 index 0000000..a587dda --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/ArrayType.php @@ -0,0 +1,65 @@ +<?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\Schema\Elements; + +use Nette\Schema\{Context, MergeMode, Schema}; +use function is_array; + + +/** + * An array, a list or an iterable, optionally with a schema for its items and keys. + */ +final class ArrayType extends Type +{ + public function __construct( + string $type, + /** a single value is accepted and wrapped into a one-item list */ + private readonly bool $wrap = false, + ) { + parent::__construct($type); + } + + + public function doNormalize(mixed $value, Context $context): mixed + { + $value = parent::doNormalize($value, $context); + return $this->wrap && !is_array($value) && $value !== null ? [$value] : $value; + } + + + /** + * Sets the schema of items and optionally of keys. + */ + public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): static + { + return parent::items($valueType, $keyType); + } + + + /** + * Sets how the array is combined when merging multiple configuration layers. + */ + public function mergeMode(MergeMode $mode): static + { + return parent::mergeMode($mode); + } + + + /** @deprecated an array has no pattern */ + public function pattern(?string $pattern): static + { + trigger_error(__METHOD__ . '() is deprecated, an array has no pattern.', E_USER_DEPRECATED); + return parent::pattern($pattern); + } + + + public function describe(): array + { + return parent::describe() + ['wrap' => $this->wrap]; + } +} diff --git a/vendor/nette/schema/src/Schema/Elements/Base.php b/vendor/nette/schema/src/Schema/Elements/Base.php new file mode 100644 index 0000000..a16a788 --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/Base.php @@ -0,0 +1,224 @@ +<?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\Schema\Elements; + +use Nette; +use Nette\Schema\{Context, Helpers}; +use function count, is_string; + + +/** + * @internal + */ +trait Base +{ + private bool $required = false; + private mixed $default = null; + + /** @var ?\Closure(mixed): mixed */ + private ?\Closure $before = null; + + /** @var list<\Closure(mixed, Context): mixed> */ + private array $transforms = []; + private ?string $deprecated = null; + private ?string $description = null; + + /** @var ?\Closure(mixed, mixed): mixed */ + private ?\Closure $mergeWith = null; + + + public function default(mixed $value): static + { + $this->default = $value; + return $this; + } + + + public function required(bool $state = true): static + { + $this->required = $state; + return $this; + } + + + /** + * Sets a pre-normalization callback applied to the raw input value before any validation. + * @param callable(mixed): mixed $handler + */ + public function before(callable $handler): static + { + if ($this->before) { + trigger_error( + 'Calling before() repeatedly is deprecated, it replaces the previous handler while in 2.0 the handlers will be chained; merge them into one.', + E_USER_DEPRECATED, + ); + } + + $this->before = $handler(...); + return $this; + } + + + /** + * Sets a custom strategy combining two layers. Must be a pure combiner; canonicalize layer shape in before() instead. + * Either side may be null, a layer can legally be null. + * @param callable(mixed, mixed): mixed $fn + */ + public function mergeWith(callable $fn): static + { + $this->mergeWith = $fn(...); + return $this; + } + + + /** + * Casts the validated value to a built-in type or instantiates the given class; a null stays null for a class or ?type. + */ + public function castTo(string $type): static + { + 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): static + { + $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): static + { + $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; + } + $context->addError( + 'Failed assertion ' . ($description ? "'%assertion%'" : '%assertion%') . ' for %label% %path% with value %value%.', + Nette\Schema\Message::FailedAssertion, + ['value' => $value, 'assertion' => $expected], + ); + return null; + }); + } + + + /** + * Marks the item as deprecated; emits a warning with the given message when the item is used. + */ + public function deprecated(string $message = 'The item %path% is deprecated.'): static + { + $this->deprecated = $message; + return $this; + } + + + /** + * Sets a human-readable description of the item; it does not affect validation. + */ + public function description(string $description): static + { + $this->description = $description; + return $this; + } + + + /** + * The metadata every element reports from describe(); the element adds its own keys. + * @return array{required: bool, description: ?string} + */ + protected function describeBase(): array + { + return ['required' => $this->required, 'description' => $this->description]; + } + + + public function completeDefault(Context $context): mixed + { + if ($this->required) { + $context->addError( + 'The mandatory item %path% is missing.', + Nette\Schema\Message::MissingItem, + ); + return null; + } + + return $this->default; + } + + + public function doNormalize(mixed $value, Context $context): mixed + { + if ($this->before) { + $value = ($this->before)($value); + } + + return $value; + } + + + private function doDeprecation(Context $context): void + { + if ($this->deprecated !== null) { + $context->addWarning( + $this->deprecated, + Nette\Schema\Message::Deprecated, + ); + } + } + + + private function doTransform(mixed $value, Context $context): mixed + { + $isOk = $context->createChecker(); + foreach ($this->transforms as $handler) { + $value = $handler($value, $context); + if (!$isOk()) { + return null; + } + } + return $value; + } + + + /** @deprecated use Nette\Schema\Helpers::validateType() */ + private function doValidate(mixed $value, string $expected, Context $context): bool + { + $isOk = $context->createChecker(); + Helpers::validateType($value, $expected, $context); + return $isOk(); + } + + + /** + * @deprecated use Nette\Schema\Helpers::validateRange() + * @param array{int|float|null, int|float|null} $range + */ + private static function doValidateRange(mixed $value, array $range, Context $context, string $types = ''): bool + { + $isOk = $context->createChecker(); + Helpers::validateRange($value, $range, $context, $types); + return $isOk(); + } + + + /** @deprecated use doTransform() */ + private function doFinalize(mixed $value, Context $context): mixed + { + return $this->doTransform($value, $context); + } +} diff --git a/vendor/nette/schema/src/Schema/Elements/EnumType.php b/vendor/nette/schema/src/Schema/Elements/EnumType.php new file mode 100644 index 0000000..bec549c --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/EnumType.php @@ -0,0 +1,49 @@ +<?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\Schema\Elements; + +use Nette; +use Nette\Schema\{Context, Kind}; +use function is_int, is_string; + + +/** + * A backed enum: accepts a case or its backing value and yields the case. + */ +final class EnumType extends Type +{ + public function __construct( + /** @var class-string<\BackedEnum> */ + private string $enum, + ) { + if (!is_subclass_of($enum, \BackedEnum::class)) { + throw new Nette\InvalidArgumentException("'$enum' is not a backed enum."); + } + parent::__construct($enum); + } + + + public function doNormalize(mixed $value, Context $context): mixed + { + $value = parent::doNormalize($value, $context); + try { + return is_int($value) || is_string($value) ? $this->enum::tryFrom($value) ?? $value : $value; + } catch (\TypeError) { + return $value; // a string for an int-backed enum and vice versa + } + } + + + public function describe(): array + { + return [ + 'kind' => Kind::Enum, + 'values' => array_map(fn(\BackedEnum $case) => $case->value, ($this->enum)::cases()), + ] + parent::describe(); + } +} diff --git a/vendor/nette/schema/src/Schema/Elements/NumberType.php b/vendor/nette/schema/src/Schema/Elements/NumberType.php new file mode 100644 index 0000000..8a5759d --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/NumberType.php @@ -0,0 +1,40 @@ +<?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\Schema\Elements; + +use Nette\Schema\Schema; + + +/** + * An int or a float. + */ +final class NumberType extends Type +{ + /** @deprecated a number has no pattern */ + public function pattern(?string $pattern): static + { + trigger_error(__METHOD__ . '() is deprecated, a number has no pattern.', E_USER_DEPRECATED); + return parent::pattern($pattern); + } + + + /** @deprecated a number has no items */ + public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): static + { + trigger_error(__METHOD__ . '() is deprecated, a number has no items.', E_USER_DEPRECATED); + return parent::items($valueType, $keyType); + } + + + /** @deprecated a number has no default merging */ + public function mergeDefaults(bool $state = true): static + { + trigger_error(__METHOD__ . '() is deprecated, a number has no default merging.', E_USER_DEPRECATED); + return parent::mergeDefaults($state); + } +} diff --git a/vendor/nette/schema/src/Schema/Elements/StringType.php b/vendor/nette/schema/src/Schema/Elements/StringType.php new file mode 100644 index 0000000..28874ce --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/StringType.php @@ -0,0 +1,32 @@ +<?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\Schema\Elements; + +use Nette\Schema\Schema; + + +/** + * A string, plain or in a specified format. + */ +final class StringType extends Type +{ + /** @deprecated a string has no items */ + public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): static + { + trigger_error(__METHOD__ . '() is deprecated, a string has no items.', E_USER_DEPRECATED); + return parent::items($valueType, $keyType); + } + + + /** @deprecated a string has no default merging */ + public function mergeDefaults(bool $state = true): static + { + trigger_error(__METHOD__ . '() is deprecated, a string has no default merging.', E_USER_DEPRECATED); + return parent::mergeDefaults($state); + } +} diff --git a/vendor/nette/schema/src/Schema/Elements/Structure.php b/vendor/nette/schema/src/Schema/Elements/Structure.php new file mode 100644 index 0000000..894d8c3 --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/Structure.php @@ -0,0 +1,274 @@ +<?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\Schema\Elements; + +use Nette; +use Nette\Schema\{Context, Helpers, Kind, MergeMode, Schema}; +use function array_key_exists, is_array, is_object; + + +final class Structure implements Schema +{ + use Base; + + /** @var Schema[] */ + private array $items; + + /** for array|list */ + private ?Schema $otherItems = null; + + /** @var array{?int, ?int} */ + private array $range = [null, null]; + private bool $skipDefaults = false; + private ?MergeMode $mergeMode = null; + + + /** @param Schema[] $shape */ + public function __construct(array $shape) + { + (function (Schema ...$items) {})(...array_values($shape)); + $this->items = $shape; + $this->castTo('object'); + $this->required = true; + } + + + /** + * Not supported for structures; always throws. + */ + public function default(mixed $value): self + { + throw new Nette\InvalidStateException('Structure cannot have default value.'); + } + + + public function min(?int $min): self + { + $this->range[0] = $min; + return $this; + } + + + public function max(?int $max): self + { + $this->range[1] = $max; + return $this; + } + + + /** + * Allows extra keys not defined in the shape, validating their values against the given type. + */ + public function otherItems(string|Schema $type = 'mixed'): self + { + $this->otherItems = $type instanceof Schema ? $type : Nette\Schema\Expect::type($type); + return $this; + } + + + /** + * When enabled, missing properties are not filled with their default values. + */ + public function skipDefaults(bool $state = true): self + { + $this->skipDefaults = $state; + return $this; + } + + + /** + * Sets how the structure is combined when merging multiple configuration layers. + */ + public function mergeMode(MergeMode $mode): self + { + $this->mergeMode = $mode; + return $this; + } + + + /** + * 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([...$this->items, ...$shape]); + } + + + /** @return Schema[] */ + public function getShape(): array + { + return $this->items; + } + + + /********************* inspection ****************d*g**/ + + + /** + * @return array<string, mixed> + * @internal + */ + public function describe(): array + { + return [ + 'kind' => Kind::Structure, + 'shape' => $this->items, + 'otherItems' => $this->otherItems, + 'min' => $this->range[0], + 'max' => $this->range[1], + ] + $this->describeBase(); + } + + + /********************* processing ****************d*g**/ + + + public function normalize(mixed $value, Context $context): mixed + { + if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) { + unset($value[Helpers::PreventMerging]); + } + + $value = $this->doNormalize($value, $context); + if (is_object($value)) { + $value = (array) $value; + } + + if (is_array($value)) { + foreach ($value as $key => $val) { + $itemSchema = $this->items[$key] ?? $this->otherItems; + if ($itemSchema) { + $context->path[] = $key; + $value[$key] = $itemSchema->normalize($val, $context); + array_pop($context->path); + } + } + + if ($prevent) { + $value[Helpers::PreventMerging] = true; + } + } + + return $value; + } + + + public function merge(mixed $value, mixed $base): mixed + { + if (is_array($value) && isset($value[Helpers::PreventMerging])) { + unset($value[Helpers::PreventMerging]); + return $value; + } + + if ($this->mergeWith) { + return ($this->mergeWith)($value, $base); + } + + $mode = $this->mergeMode ?? ($this->otherItems === null ? MergeMode::OverwriteKeys : MergeMode::AppendKeys); + if ($mode === MergeMode::Replace) { + return $value; + } + + if (is_array($value) && is_array($base)) { + $index = $mode === MergeMode::OverwriteKeys ? null : 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) + ? $itemSchema->merge($val, $base[$key]) + : $val; + } + } + + return $base; + } + + return $value ?? $base; + } + + + public function complete(mixed $value, Context $context): mixed + { + // the marker travels with the value through normalize() and merge() consumes it; the layer that has + // nothing under it keeps it, and it is not an item of the shape + if (is_array($value)) { + unset($value[Helpers::PreventMerging]); + } + + if ($value === null && $context->keepNullAt !== $context->path) { + $value = []; // is unable to distinguish null from array in NEON + } + + $this->doDeprecation($context); + + $isOk = $context->createChecker(); + Helpers::validateType($value, 'array', $context); + $isOk() && Helpers::validateRange($value, $this->range, $context); + $isOk() && $this->validateItems($value, $context); + $isOk() && $value = $this->doTransform($value, $context); + return $isOk() ? $value : null; + } + + + /** @param array<mixed> $value */ + private function validateItems(array &$value, Context $context): void + { + $items = $this->items; + if ($extraKeys = array_keys(array_diff_key($value, $items))) { + if ($this->otherItems) { + $items += array_fill_keys($extraKeys, $this->otherItems); + } else { + $keys = array_map(strval(...), array_keys($items)); + foreach ($extraKeys as $key) { + $hint = Nette\Utils\Helpers::getSuggestion($keys, (string) $key); + $context->addError( + 'Unexpected item %path%' . ($hint ? ", did you mean '%hint%'?" : '.'), + Nette\Schema\Message::UnexpectedItem, + ['hint' => $hint], + )->path[] = $key; + } + } + } + + foreach ($items as $itemKey => $itemVal) { + $context->path[] = $itemKey; + if (array_key_exists($itemKey, $value)) { + $value[$itemKey] = $itemVal->complete($value[$itemKey], $context); + } else { + $default = $itemVal->completeDefault($context); // checks required item + if (!$context->skipDefaults && !$this->skipDefaults) { + $value[$itemKey] = $default; + } + } + + array_pop($context->path); + } + } + + + public function completeDefault(Context $context): mixed + { + 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; + } + } +} diff --git a/vendor/nette/schema/src/Schema/Elements/TupleType.php b/vendor/nette/schema/src/Schema/Elements/TupleType.php new file mode 100644 index 0000000..d567820 --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/TupleType.php @@ -0,0 +1,125 @@ +<?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\Schema\Elements; + +use Nette; +use Nette\Schema\{Context, Kind, Message, Schema}; +use function count; + + +/** + * A fixed-size list where each position has its own schema; a later layer replaces the tuple wholesale. + */ +final class TupleType extends Type +{ + /** @var list<Schema> */ + private array $items; + + /** the rest elements */ + private ?Schema $otherItems = null; + + + /** @param Schema[] $shape */ + public function __construct(array $shape) + { + if (!array_is_list($shape)) { + throw new Nette\InvalidArgumentException('Tuple shape must be indexed array.'); + } + + (function (Schema ...$items) {})(...$shape); + parent::__construct('list'); + parent::default(null); // a tuple of nothing is not a value, so null is not coerced to one + $this->items = $shape; + } + + + /** + * Not supported for tuples; always throws. + */ + public function default(mixed $value): static + { + throw new Nette\InvalidStateException('Tuple cannot have default value.'); + } + + + /** + * Allows positions beyond the shape, validating them against the given type. + */ + public function otherItems(string|Schema $type = 'mixed'): self + { + $this->otherItems = $type instanceof Schema ? $type : Nette\Schema\Expect::type($type); + return $this; + } + + + /** + * Appends positions to the tuple. + * @param Schema[]|self $shape + */ + public function extend(array|self $shape): self + { + $shape = $shape instanceof self ? $shape->items : $shape; + return new self([...$this->items, ...$shape]); + } + + + /** @return list<Schema> */ + public function getShape(): array + { + return $this->items; + } + + + public function describe(): array + { + return ['kind' => Kind::Tuple, 'shape' => $this->items, 'otherItems' => $this->otherItems] + parent::describe(); + } + + + protected function mergeValues(mixed $value, mixed $base): mixed + { + return $value; + } + + + protected function normalizeItems(array $value, Context $context): array + { + foreach ($value as $key => $val) { + if ($itemSchema = $this->items[$key] ?? $this->otherItems) { + $context->path[] = $key; + $value[$key] = $itemSchema->normalize($val, $context); + array_pop($context->path); + } + } + + return $value; + } + + + protected function validateItems(array &$value, Context $context): void + { + foreach ($value as $index => $val) { + $context->path[] = $index; + if ($itemSchema = $this->items[$index] ?? $this->otherItems) { + $value[$index] = $itemSchema->complete($val, $context); + } else { + $context->addError('Unexpected item %path%.', Message::UnexpectedItem); + } + array_pop($context->path); + } + + for ($index = count($value); $index < count($this->items); $index++) { + $context->path[] = $index; + $default = $this->items[$index]->completeDefault($context); // checks required item + if (!$context->skipDefaults) { + $value[] = $default; + } + array_pop($context->path); + } + } +} diff --git a/vendor/nette/schema/src/Schema/Elements/Type.php b/vendor/nette/schema/src/Schema/Elements/Type.php new file mode 100644 index 0000000..851bdda --- /dev/null +++ b/vendor/nette/schema/src/Schema/Elements/Type.php @@ -0,0 +1,359 @@ +<?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\Schema\Elements; + +use Nette; +use Nette\Schema\{Context, DynamicParameter, Helpers, Kind, MergeMode, Message, Schema, TypeExpression}; +use Nette\Utils\Validators; +use function array_key_exists, is_array, is_int, is_string; +use const INF; + + +class Type implements Schema +{ + use Base; + + private ?Schema $itemsValue = null; + private ?Schema $itemsKey = null; + + /** @var array{int|float|null, int|float|null} */ + private array $range = [null, null]; + private ?string $pattern = null; + private bool $merge = true; + private ?MergeMode $mergeMode = null; + + + public function __construct( + private string $type, + ) { + $defaults = ['list' => [], 'array' => []]; + $this->default = strpos($type, '[]') ? [] : $defaults[$type] ?? null; + } + + + /** + * Allows the value to be null in addition to the declared type. + */ + public function nullable(): static + { + $this->type = 'null|' . $this->type; + return $this; + } + + + /** + * Controls whether the default value is merged with the input array (enabled by default). + */ + public function mergeDefaults(bool $state = true): static + { + $this->unionDeprecated('mergeDefaults'); + $this->merge = $state; + return $this; + } + + + /** @internal */ + protected function mergeMode(MergeMode $mode): static + { + $this->mergeMode = $mode; + return $this; + } + + + /** + * Allows the value to be a DynamicParameter, which is recorded for deferred validation. + */ + public function dynamic(): static + { + $this->type = DynamicParameter::class . '|' . $this->type; + return $this; + } + + + public function min(int|float|null $min): static + { + $this->unionDeprecated('min'); + $this->range[0] = $min; + return $this; + } + + + public function max(int|float|null $max): static + { + $this->unionDeprecated('max'); + $this->range[1] = $max; + return $this; + } + + + /** + * @internal use arrayOf() or listOf() + */ + public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): static + { + $this->unionDeprecated('items'); + $this->itemsValue = $valueType instanceof Schema + ? $valueType + : Nette\Schema\Expect::type($valueType); + $this->itemsKey = $keyType instanceof Schema || $keyType === null + ? $keyType + : Nette\Schema\Expect::type($keyType); + return $this; + } + + + /** + * Sets a regex pattern the string value must match entirely (anchored to start and end). + */ + public function pattern(?string $pattern): static + { + $this->unionDeprecated('pattern'); + $this->pattern = $pattern; + return $this; + } + + + /** + * A union of kinds ('int|string') becomes anyOf() in the next major and takes no options of its own; + * they belong to the variants: anyOf(Expect::int()->min(1), Expect::string()->min(1)). + */ + private function unionDeprecated(string $option): void + { + if (static::class === self::class && $this->getParsed()['kind'] === Kind::Union) { + trigger_error( + "$option() on the union '$this->type' is deprecated, give it to the variants of anyOf() instead.", + E_USER_DEPRECATED, + ); + } + } + + + /********************* inspection ****************d*g**/ + + + /** + * Reports what the type accepts as a plain array (see TypeExpression::parse()); min(), max(), pattern() + * and items() narrow every variant they apply to, child schemas are reported as they are. + * @return array<string, mixed> + * @internal + */ + public function describe(): array + { + return $this->narrow($this->getParsed()) + $this->describeBase(); + } + + + /** + * The parsed expression; 'kind', 'nullable', 'dynamic' and the keys of the kind. + * @return array<string, mixed> + */ + protected function getParsed(): array + { + return TypeExpression::parse($this->type); + } + + + /** + * Puts min(), max(), pattern() and items() into every variant of the parsed expression that has the key. + * @param array<string, mixed> $item + * @return array<string, mixed> + */ + private function narrow(array $item): array + { + if ($item['kind'] === Kind::Union) { + $item['variants'] = array_map($this->narrow(...), $item['variants']); + } + if (array_key_exists('min', $item)) { // both bounds are checked, so the tighter one holds + $item['min'] = $this->range[0] === null ? $item['min'] : max($this->range[0], $item['min'] ?? -INF); + $item['max'] = $this->range[1] === null ? $item['max'] : min($this->range[1], $item['max'] ?? INF); + } + if (array_key_exists('pattern', $item)) { + $item['pattern'] = $this->pattern ?? $item['pattern']; + } + if (array_key_exists('items', $item)) { + $item['items'] = $this->itemsValue ?? $item['items']; + $item['keys'] = $this->itemsKey ?? $item['keys']; + } + return $item; + } + + + /********************* processing ****************d*g**/ + + + public function normalize(mixed $value, Context $context): mixed + { + if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) { + unset($value[Helpers::PreventMerging]); + } + + $value = $this->doNormalize($value, $context); + if (is_array($value)) { + $value = $this->normalizeItems($value, $context); + } + + if ($prevent && is_array($value)) { + $value[Helpers::PreventMerging] = true; + } + + return $value; + } + + + /** + * @param array<mixed> $value + * @return array<mixed> + * @internal + */ + protected function normalizeItems(array $value, Context $context): array + { + if (!$this->itemsValue) { + return $value; + } + + $res = []; + foreach ($value as $key => $val) { + $context->path[] = $key; + $context->isKey = true; + $key = $this->itemsKey + ? $this->itemsKey->normalize($key, $context) + : $key; + if (!is_int($key) && !is_string($key)) { + $context->addError( + 'The %label% %path% expects to be int|string, %value% given.', + Message::TypeMismatch, + ['value' => $key, 'expected' => 'int|string'], + ); + $context->isKey = false; + array_pop($context->path); + continue; + } + + $context->isKey = false; + $res[$key] = $this->itemsValue->normalize($val, $context); + array_pop($context->path); + } + + return $res; + } + + + public function merge(mixed $value, mixed $base): mixed + { + if (is_array($value) && isset($value[Helpers::PreventMerging])) { + unset($value[Helpers::PreventMerging]); + return $value; + } + + if ($this->mergeWith) { + return ($this->mergeWith)($value, $base); + } + + return $this->mergeValues($value, $base); + } + + + /** + * Without a mode, an array without described items merges deeply. + * @internal + */ + protected function mergeValues(mixed $value, mixed $base): mixed + { + if ($this->mergeMode === MergeMode::Replace) { + return $value; + } + + if (is_array($value) && is_array($base) && ($this->itemsValue || $this->mergeMode)) { + $index = $this->mergeMode === MergeMode::OverwriteKeys ? null : 0; + foreach ($value as $key => $val) { + if ($key === $index) { + $base[] = $val; + $index++; + } else { + $base[$key] = array_key_exists($key, $base) && $this->itemsValue + ? $this->itemsValue->merge($val, $base[$key]) + : $val; + } + } + + return $base; + } + + return Helpers::merge($value, $base); + } + + + public function complete(mixed $value, Context $context): mixed + { + $merge = $this->merge; + if (is_array($value) && isset($value[Helpers::PreventMerging])) { + unset($value[Helpers::PreventMerging]); + $merge = false; + } + + if ($value === null && is_array($this->default) && !Validators::is(null, $this->type) && $context->keepNullAt !== $context->path) { + $value = []; // is unable to distinguish null from array in NEON + } + + $this->doDeprecation($context); + + $isOk = $context->createChecker(); + Helpers::validateType($value, $this->type, $context); + $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() && $value = $this->doTransform($value, $context); + if (!$isOk()) { + return null; + } + + if ($value instanceof DynamicParameter && $this->type !== DynamicParameter::class) { + $expected = $this->type . ($this->range === [null, null] ? '' : ':' . implode('..', $this->range)); + $context->dynamics[] = [$value, str_replace(DynamicParameter::class . '|', '', $expected), $context->path]; + } + return $value; + } + + + /** + * @param array<mixed> $value + * @internal + */ + protected function validateItems(array &$value, Context $context): void + { + if (!($itemsValue = $this->itemsValue)) { + return; + } + + $res = []; + foreach ($value as $key => $val) { + $context->path[] = $key; + $context->isKey = true; + $isKeyOk = $context->createChecker(); + $key = $this->itemsKey ? $this->itemsKey->complete($key, $context) : $key; + if ($isKeyOk() && !is_int($key) && !is_string($key)) { + $context->addError( + 'The %label% %path% expects to be int|string, %value% given.', + Message::TypeMismatch, + ['value' => $key, 'expected' => 'int|string'], + ); + } + + $context->isKey = false; + $keyOk = $isKeyOk(); + $val = $itemsValue->complete($val, $context); + if ($keyOk) { + $res[$key] = $val; + } + + array_pop($context->path); + } + $value = $res; + } +} diff --git a/vendor/nette/schema/src/Schema/Expect.php b/vendor/nette/schema/src/Schema/Expect.php new file mode 100644 index 0000000..f5ef5c8 --- /dev/null +++ b/vendor/nette/schema/src/Schema/Expect.php @@ -0,0 +1,188 @@ +<?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\Schema; + +use Nette; +use Nette\Schema\Elements\{AnyOf, ArrayType, EnumType, NumberType, StringType, Structure, Type}; +use function array_key_exists, count, is_object; + + +/** + * Schema generator. + * + * @method static Type scalar($default = null) + * @method static StringType string($default = null) + * @method static NumberType int($default = null) + * @method static NumberType float($default = null) + * @method static Type bool($default = null) + * @method static Type null() + * @method static ArrayType list($default = []) + * @method static Type mixed($default = null) + * @method static StringType email($default = null) + * @method static StringType unicode($default = null) + */ +final class Expect +{ + /** @param array<int|string, mixed> $args */ + public static function __callStatic(string $name, array $args): Type + { + $type = self::type($name); + if ($args) { + $type->default(array_key_exists('default', $args) ? $args['default'] : $args[0]); + } + + return $type; + } + + + /** + * Creates a schema for a type expression (e.g., 'int|string', 'null|float', 'email'); an expression + * of a single kind of value gets its dedicated StringType, NumberType or ArrayType. An enum class means + * instanceof, as any class; Expect::enum() accepts its backing values. + */ + public static function type(string $type): Type + { + $class = self::typeClass(TypeExpression::parse($type)); + return new $class($type); + } + + + /** + * The subclass of Type that Expect::type() returns for a parsed expression: the dedicated one when + * every variant is of its kind, the plain Type otherwise. + * @param array<string, mixed> $item + * @return class-string<Type> + * @internal + */ + public static function typeClass(array $item): string + { + $variants = $item['kind'] === Kind::Union ? $item['variants'] : [$item]; + $classes = array_unique(array_map(fn(array $variant) => match ($variant['kind']) { + Kind::String => StringType::class, + Kind::Int, Kind::Float, Kind::Number => NumberType::class, + Kind::Array, Kind::List, Kind::Iterable => ArrayType::class, + default => Type::class, + }, $variants)); + return count($classes) === 1 ? reset($classes) : Type::class; + } + + + /** + * Creates a schema for a backed enum: a case or its backing value is accepted, the case is returned. + * @param class-string<\BackedEnum> $enum + */ + public static function enum(string $enum): EnumType + { + return new EnumType($enum); + } + + + /** + * Creates a union schema that accepts any of the given values or sub-schemas. + */ + public static function anyOf(mixed ...$set): AnyOf + { + return new AnyOf(...$set); + } + + + /** + * Creates a structure schema with defined properties; output is stdClass. + * @param Schema[] $shape + */ + public static function structure(array $shape): Structure + { + return new Structure($shape); + } + + + /** + * 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. + */ + public static function from(object $object, array $items = []): Structure + { + $ro = new \ReflectionObject($object); + $props = $ro->hasMethod('__construct') + ? $ro->getMethod('__construct')->getParameters() + : array_filter($ro->getProperties(\ReflectionProperty::IS_PUBLIC), fn($prop) => !$prop->isStatic()); + + foreach ($props as $prop) { + $name = $prop->getName(); + if ($prop instanceof \ReflectionParameter && $prop->isVariadic()) { + throw new Nette\InvalidArgumentException("Variadic parameter \$$name of {$ro->getName()}::__construct() is not supported by Expect::from()."); + } elseif (!isset($items[$name])) { + $type = Helpers::getPropertyType($prop) ?? 'mixed'; + if (is_subclass_of($enum = ltrim($type, '?'), \BackedEnum::class)) { + $item = self::enum($enum); + $enum === $type || $item->nullable(); + } else { + $item = self::type($type); + } + if ($prop instanceof \ReflectionProperty ? $prop->isInitialized($object) : $prop->isOptional()) { + $def = ($prop instanceof \ReflectionProperty ? $prop->getValue($object) : $prop->getDefaultValue()); + if (is_object($def) && !$def instanceof \UnitEnum) { + $item = static::from($def); + } elseif ($def === null && !Nette\Utils\Validators::is(null, $type)) { + $item->required(); + } else { + $item->default($def); + } + } else { + $item->required(); + } + $items[$name] = $item; + } + } + + return (new Structure($items))->castTo($ro->getName()); + } + + + /** + * 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 + */ + public static function array(?array $shape = []): Structure|ArrayType + { + $shape ??= []; + return Nette\Utils\Arrays::first($shape) instanceof Schema + ? (new Structure($shape))->castTo('array') + : (new ArrayType('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): ArrayType + { + return (new ArrayType('array'))->items($valueType, $keyType); + } + + + /** + * Creates a list schema (sequentially indexed from 0) where every element matches the given type. + * With $wrap, a single value is also accepted and wrapped into a one-item list. + */ + public static function listOf(string|Schema $type, bool $wrap = false): ArrayType + { + return (new ArrayType('list', $wrap))->items($type); + } + + + /** + * Creates a fixed-size array where each position has its own schema; a later layer replaces the tuple wholesale. + * @param Schema[] $shape + */ + public static function tuple(array $shape): Elements\TupleType + { + return new Elements\TupleType($shape); + } +} diff --git a/vendor/nette/schema/src/Schema/Helpers.php b/vendor/nette/schema/src/Schema/Helpers.php new file mode 100644 index 0000000..ffdd2d1 --- /dev/null +++ b/vendor/nette/schema/src/Schema/Helpers.php @@ -0,0 +1,250 @@ +<?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\Schema; + +use Nette; +use Nette\Utils\Reflection; +use function count, is_array, is_float, is_int, is_object, is_scalar, is_string, strlen; + + +/** + * @internal + */ +final class Helpers +{ + use Nette\StaticClass; + + public const PreventMerging = '_prevent_merging'; + + + /** + * Merges dataset. Left has higher priority than right one. + */ + public static function merge(mixed $value, mixed $base): mixed + { + if (is_array($value) && isset($value[self::PreventMerging])) { + unset($value[self::PreventMerging]); + return $value; + } + + if (is_array($value) && is_array($base)) { + $index = 0; + foreach ($value as $key => $val) { + if ($key === $index) { + $base[] = $val; + $index++; + } else { + $base[$key] = static::merge($val, $base[$key] ?? null); + } + } + + return $base; + + } elseif ($value === null && is_array($base)) { + return $base; + + } else { + return $value; + } + } + + + /** + * Returns the type of a property or parameter as a string, or null if not determinable. + */ + public static function getPropertyType(\ReflectionProperty|\ReflectionParameter $prop): ?string + { + if ($type = Nette\Utils\Type::fromReflection($prop)) { + return (string) $type; + } elseif ( + ($prop instanceof \ReflectionProperty) + && ($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 null; + } + + + /** + * Returns an annotation value. + * @param \ReflectionClass<object>|\ReflectionProperty $ref + */ + public static function parseAnnotation(\ReflectionClass|\ReflectionProperty $ref, string $name): ?string + { + if (!Reflection::areCommentsAvailable()) { + throw new Nette\InvalidStateException('You have to enable phpDoc comments in opcode cache.'); + } + + $re = '#[\s*]@' . preg_quote($name, '#') . '(?=\s|$)(?:[ \t]+([^@\s]\S*))?#'; + if ($ref->getDocComment() && preg_match($re, trim($ref->getDocComment(), '/*'), $m)) { + return $m[1] ?? ''; + } + + return null; + } + + + /** + * Formats a value for use in error messages (e.g., 'hello', true, object stdClass). + */ + public static function formatValue(mixed $value): string + { + if ($value instanceof DynamicParameter) { + return 'dynamic'; + } elseif (is_object($value)) { + return 'object ' . $value::class; + } elseif (is_string($value)) { + return "'" . Nette\Utils\Strings::truncate($value, 15, '...') . "'"; + } elseif (is_scalar($value)) { + return var_export($value, return: true); + } else { + return get_debug_type($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 + { + if (!Nette\Utils\Validators::is($value, $expected)) { + $expected = str_replace(DynamicParameter::class . '|', '', $expected); + $expected = str_replace(['|', ':'], [' or ', ' in range '], $expected); + $context->addError( + 'The %label% %path% expects to be %expected%, %value% given.', + Message::TypeMismatch, + ['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{int|float|null, int|float|null} $range + */ + public static function validateRange(mixed $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), true) + ? [Nette\Utils\Strings::length($value), 'characters'] + : [strlen($value), 'bytes']); + + if (!self::isInRange($length, $range)) { + $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)], + ); + } + } 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)], + ); + } + } + + + /** + * Checks whether a value falls within the given [min, max] range (null means no bound). + * @param array{int|float|null, int|float|null} $range + */ + public static function isInRange(mixed $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 + { + $res = @preg_match("\x01^(?:$pattern)$\x01Du", $value); // @ - an invalid pattern is thrown below + if ($res === false && preg_last_error() === PREG_INTERNAL_ERROR) { + throw new Nette\InvalidStateException("Invalid pattern '$pattern': " . Nette\Utils\Helpers::getLastError()); + } elseif (!$res) { + $context->addError( + "The %label% %path% expects to match pattern '%pattern%', %value% given.", + Message::PatternMismatch, + ['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). + * A null stays null for an enum or a class, and for a built-in type only when written as ?type. + * @return \Closure(mixed, Context): mixed + */ + public static function getCastStrategy(string $type): \Closure + { + if (str_starts_with($type, '?')) { + $cast = self::getCastStrategy(substr($type, 1)); + return static fn($value, Context $context) => $value === null ? null : $cast($value, $context); + + } elseif (Nette\Utils\Validators::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) { + if ($value === null) { + return null; + } + + 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 (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) { + if ($value === null) { + return null; + } + + 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/JsonSchema.php b/vendor/nette/schema/src/Schema/JsonSchema.php new file mode 100644 index 0000000..9f42244 --- /dev/null +++ b/vendor/nette/schema/src/Schema/JsonSchema.php @@ -0,0 +1,292 @@ +<?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\Schema; + +use Nette; +use function count, is_bool, is_float, is_int, is_string; + + +/** + * Exports a schema as JSON Schema. + */ +final class JsonSchema +{ + private const Formats = ['email' => 'email', 'url' => 'uri', 'uri' => 'uri']; + + + /** + * @return array<string, mixed>|\stdClass + * @throws Nette\NotSupportedException when the schema contains a class type or another PHP-only type + */ + public static function export(Schema $schema): array|\stdClass + { + return self::build($schema); + } + + + /** + * @param Schema|array<string, mixed> $schema a schema, or a description as describe() returns it + * @return array<string, mixed>|\stdClass + */ + private static function build(Schema|array $schema): array|\stdClass + { + $item = self::describe($schema); + $kind = $item['kind']; + if (!$kind instanceof Kind) { + throw new Nette\InvalidStateException('describe() must report a Kind.'); + } + + $res = match ($kind) { + Kind::Any => [], + Kind::Null => ['type' => 'null'], + Kind::Bool => ['type' => 'boolean'], + Kind::Int => ['type' => 'integer'] + self::range($item, 'minimum', 'maximum'), + Kind::Float, Kind::Number => ['type' => 'number'] + self::range($item, 'minimum', 'maximum'), + Kind::String => self::buildString($item), + // an iterable of items is narrowed to a JSON array, which PHP accepts too + Kind::List, Kind::Iterable => self::buildList($item), + Kind::Array => self::buildArray($item), + Kind::Structure => self::buildStructure($item), + Kind::Tuple => self::buildTuple($item), + Kind::Enum => self::buildEnum($item['values']), + Kind::Union => self::buildUnion($item), + Kind::Instance, Kind::Other, Kind::Object, Kind::Callable => throw new Nette\NotSupportedException( + "Type '" . ($item['type'] ?? strtolower($kind->name)) . "' cannot be expressed in JSON Schema.", + ), + }; + + if ($item['nullable'] ?? false) { + if (isset($res['enum'])) { + $res['enum'][] = null; + } + if (isset($res['type']) && $res['type'] !== 'null') { + $res['type'] = [$res['type'], 'null']; + } elseif (isset($res['anyOf'])) { + $res['anyOf'][] = ['type' => 'null']; + } + } + + if (($item['description'] ?? null) !== null) { + $res['description'] = $item['description']; + } + + return $res ?: new \stdClass; + } + + + /** + * @param Schema|array<string, mixed> $schema + * @return array<string, mixed> + */ + private static function describe(Schema|array $schema): array + { + if (!$schema instanceof Schema) { + return $schema; + } elseif ( + $schema instanceof Elements\Type + || $schema instanceof Elements\Structure + || $schema instanceof Elements\AnyOf + ) { + return $schema->describe(); + } + throw new Nette\NotSupportedException('Element ' . $schema::class . ' cannot be expressed in JSON Schema.'); + } + + + /** + * @param Schema|array<string, mixed>|null $schema + * @return array<string, mixed>|\stdClass + */ + private static function buildOrAny(Schema|array|null $schema): array|\stdClass + { + return $schema === null ? new \stdClass : self::build($schema); + } + + + /** + * @param array<string, mixed> $item + * @return array<string, mixed> + */ + private static function buildString(array $item): array + { + $res = ['type' => 'string'] + self::countRange($item, 'minLength', 'maxLength'); + if ($item['pattern'] !== null) { + $res['pattern'] = '^(?:' . $item['pattern'] . ')$'; + } + // only the formats JSON Schema knows; the others are checked by PHP alone, like assert() + if ($format = self::Formats[$item['format'] ?? ''] ?? null) { + $res['format'] = $format; + } + return $res; + } + + + /** + * A list that wraps a single value accepts the item alone as well. + * @param array<string, mixed> $item + * @return array<string, mixed> + */ + private static function buildList(array $item): array + { + $res = ['type' => 'array', 'items' => self::buildOrAny($item['items'])] + self::countRange($item, 'minItems', 'maxItems'); + $single = ($item['wrap'] ?? false) && ($item['min'] ?? 0) <= 1 && ($item['max'] ?? 1) >= 1; + return $single + ? ['anyOf' => [self::buildOrAny($item['items']), $res]] + : $res; + } + + + /** + * A PHP array is a JSON array when its keys are integers and an object otherwise. + * @param array<string, mixed> $item + * @return array<string, mixed> + */ + private static function buildArray(array $item): array + { + $keys = $item['keys'] === null ? null : self::describe($item['keys']); + if ($keys && $keys['kind'] === Kind::Int) { + return ['type' => 'array', 'items' => self::buildOrAny($item['items'])] + + self::countRange($item, 'minItems', 'maxItems'); + } elseif ($item['items'] === null && $keys === null) { + throw new Nette\NotSupportedException('An array without item type cannot be expressed in JSON Schema; use listOf(), arrayOf() or structure().'); + } + + $res = ['type' => 'object', 'additionalProperties' => self::buildOrAny($item['items'])] + + self::countRange($item, 'minProperties', 'maxProperties'); + // a JSON property name is a string, so only a key schema of strings says something about it + if ( + $keys + && ($keys['kind'] === Kind::String + || ($keys['kind'] === Kind::Enum && array_filter($keys['values'], is_string(...)) === $keys['values'])) + ) { + $names = self::build($keys); + if ($names !== ['type' => 'string']) { + $res['propertyNames'] = $names; + } + } + return $res; + } + + + /** + * @param array<string, mixed> $item + * @return array<string, mixed> + */ + private static function buildStructure(array $item): array + { + $properties = $required = []; + foreach ($item['shape'] as $key => $property) { + $properties[$key] = self::build($property); + if (self::isRequired($property)) { + $required[] = (string) $key; + } + } + + return [ + 'type' => 'object', + 'properties' => $properties && !array_is_list($properties) ? $properties : (object) $properties, // integer keys from 0 would encode as a JSON array + 'required' => $required, + 'additionalProperties' => $item['otherItems'] ? self::build($item['otherItems']) : false, + ] + self::countRange($item, 'minProperties', 'maxProperties'); + } + + + /** + * A required position makes all positions before it present too. + * @param array<string, mixed> $item + * @return array<string, mixed> + */ + private static function buildTuple(array $item): array + { + $res = ['type' => 'array']; + if ($item['shape']) { // prefixItems must not be empty + $res['prefixItems'] = array_map(self::build(...), $item['shape']); + } + $res['items'] = $item['otherItems'] ? self::build($item['otherItems']) : false; + + $range = self::countRange($item, 'minItems', 'maxItems'); + $positions = array_keys(array_filter($item['shape'], self::isRequired(...))); + if ($positions) { + $range['minItems'] = max($range['minItems'] ?? 0, max($positions) + 1); + } + return $res + $range; + } + + + /** + * Whether a missing item is an error. A structure is created from its defaults instead, + * so it fails only when something inside it is required or its size has a minimum. + * @param Schema|array<string, mixed> $schema + */ + private static function isRequired(Schema|array $schema): bool + { + $item = self::describe($schema); + return $item['required'] && match ($item['kind']) { + Kind::Structure => ($item['min'] ?? 0) > 0 || array_filter($item['shape'], self::isRequired(...)), + default => true, + }; + } + + + /** + * The type is stated only when every value shares it. + * @param list<mixed> $values + * @return array<string, mixed> + */ + private static function buildEnum(array $values): array + { + $types = array_unique(array_map(fn($value) => match (true) { + is_string($value) => 'string', + is_int($value) => 'integer', + is_float($value) => 'number', + is_bool($value) => 'boolean', + default => null, + }, $values)); + return (count($types) === 1 && reset($types) !== null ? ['type' => reset($types)] : []) + ['enum' => $values]; + } + + + /** + * Scalar values of an anyOf() come first as one enum, then the schema variants. + * @param array<string, mixed> $item + * @return array<string, mixed> + */ + private static function buildUnion(array $item): array + { + $variants = array_map(self::build(...), $item['variants']); + if ($item['values'] ?? []) { + array_unshift($variants, self::buildEnum($item['values'])); + } + return ['anyOf' => $variants]; + } + + + /** + * A count of characters, items or properties is a non-negative integer. + * @param array<string, mixed> $item + * @return array<string, int> + */ + private static function countRange(array $item, string $minKey, string $maxKey): array + { + return array_filter([ + $minKey => $item['min'] === null ? null : max(0, (int) ceil($item['min'])), + $maxKey => $item['max'] === null ? null : max(0, (int) floor($item['max'])), + ], fn($v) => $v !== null); + } + + + /** + * @param array<string, mixed> $item + * @return array<string, int|float> + */ + private static function range(array $item, string $minKey, string $maxKey): array + { + $number = fn(int|float|null $value) => $value === null ? null : ($value == (int) $value ? (int) $value : $value); // intentionally ==, a whole float is exported as int + return array_filter([$minKey => $number($item['min']), $maxKey => $number($item['max'])], fn($v) => $v !== null); + } +} diff --git a/vendor/nette/schema/src/Schema/Message.php b/vendor/nette/schema/src/Schema/Message.php new file mode 100644 index 0000000..443ba7e --- /dev/null +++ b/vendor/nette/schema/src/Schema/Message.php @@ -0,0 +1,97 @@ +<?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\Schema; + +use function array_key_exists; + + +/** + * Represents a single validation error or warning with a message template, error code, path, and variables. + */ +final class Message +{ + /** variables: {value: mixed, expected: string} */ + public const TypeMismatch = 'schema.typeMismatch'; + + /** variables: {value: mixed, expected: string} */ + public const ValueOutOfRange = 'schema.valueOutOfRange'; + + /** variables: {value: mixed, length: int, expected: string} */ + public const LengthOutOfRange = 'schema.lengthOutOfRange'; + + /** variables: {value: string, pattern: string} */ + public const PatternMismatch = 'schema.patternMismatch'; + + /** variables: {value: mixed, assertion: string} */ + public const FailedAssertion = 'schema.failedAssertion'; + + /** no variables */ + public const MissingItem = 'schema.missingItem'; + + /** variables: {hint: string} */ + public const UnexpectedItem = 'schema.unexpectedItem'; + + /** no variables */ + public const Deprecated = 'schema.deprecated'; + + /** @deprecated use Message::TypeMismatch */ + 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; + + + public function __construct( + public string $message, + public string $code, + /** @var list<int|string> */ + public array $path, + /** @var array<string, mixed> */ + public array $variables = [], + ) { + } + + + /** + * Formats the message template by substituting %variable% placeholders with their values. + */ + public function toString(): string + { + $vars = $this->variables; + $vars['label'] = empty($vars['isKey']) ? 'item' : 'key of item'; + $vars['path'] = $this->path + ? "'" . implode("\u{a0}›\u{a0}", $this->path) . "'" + : null; + $vars['value'] = Helpers::formatValue($vars['value'] ?? null); + + 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]; + }, $this->message); + } +} diff --git a/vendor/nette/schema/src/Schema/Processor.php b/vendor/nette/schema/src/Schema/Processor.php new file mode 100644 index 0000000..80abe38 --- /dev/null +++ b/vendor/nette/schema/src/Schema/Processor.php @@ -0,0 +1,111 @@ +<?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\Schema; + +use Nette; + + +/** + * Schema validator. + */ +final class Processor +{ + /** @var list<\Closure(Context): void> */ + public array $onNewContext = []; + private Context $context; + private bool $skipDefaults = false; + + + /** + * When enabled, missing properties are not filled with their default values. + */ + public function skipDefaults(bool $value = true): void + { + $this->skipDefaults = $value; + } + + + /** + * Normalizes and validates data. Result is a clean completed data. + * @throws ValidationException + */ + public function process(Schema $schema, mixed $data): mixed + { + $context = $this->createContext(); + try { + $data = $schema->normalize($data, $context); + $this->throwErrors($context); + $data = $schema->complete($data, $context); + $this->throwErrors($context); + return $data; + } finally { + $this->context = $context; + } + } + + + /** + * Normalizes and validates and merges multiple data. Result is a clean completed data. + * @param list<mixed> $dataset + * @throws ValidationException + */ + public function processMultiple(Schema $schema, array $dataset): mixed + { + $context = $this->createContext(); + try { + $flatten = null; + $first = true; + foreach ($dataset as $data) { + $data = $schema->normalize($data, $context); + $this->throwErrors($context); + $flatten = $first ? $data : $schema->merge($data, $flatten); + $first = false; + } + + $data = $schema->complete($flatten, $context); + $this->throwErrors($context); + return $data; + } finally { + $this->context = $context; + } + } + + + /** + * Returns all deprecation warnings collected during the last processing run. + * @return list<string> + */ + public function getWarnings(): array + { + $res = []; + if (isset($this->context)) { + foreach ($this->context->warnings as $message) { + $res[] = $message->toString(); + } + } + + return $res; + } + + + private function throwErrors(Context $context): void + { + if ($context->errors) { + throw new ValidationException(null, $context->errors); + } + } + + + private function createContext(): Context + { + $context = new Context; + $context->skipDefaults = $this->skipDefaults; + Nette\Utils\Arrays::invoke($this->onNewContext, $context); + return $context; + } +} diff --git a/vendor/nette/schema/src/Schema/Schema.php b/vendor/nette/schema/src/Schema/Schema.php new file mode 100644 index 0000000..619ebcf --- /dev/null +++ b/vendor/nette/schema/src/Schema/Schema.php @@ -0,0 +1,39 @@ +<?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\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). + * @return mixed + */ + function normalize(mixed $value, Context $context); + + /** + * Merges two normalized values, with $value taking priority over $base. + * @return mixed + */ + function merge(mixed $value, mixed $base); + + /** + * Validates the value and applies defaults, transforms, and assertions. + * @return mixed + */ + function complete(mixed $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/TypeExpression.php b/vendor/nette/schema/src/Schema/TypeExpression.php new file mode 100644 index 0000000..e3eb8d0 --- /dev/null +++ b/vendor/nette/schema/src/Schema/TypeExpression.php @@ -0,0 +1,150 @@ +<?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\Schema; + +use function count; + + +/** + * Translates the type-expression language of Expect::type() ('int|string', '?Foo', 'int[]', 'string:1..5', + * 'pattern:\d+') into a plain description. + * @internal + */ +final class TypeExpression +{ + /** + * The names Validators::is() knows and what kind of value they are; 'scalar' is a union handled apart, + * any other name is a class. + */ + private const Names = [ + 'mixed' => Kind::Any, + 'bool' => Kind::Bool, 'boolean' => Kind::Bool, + 'int' => Kind::Int, 'integer' => Kind::Int, + 'float' => Kind::Float, 'number' => Kind::Number, + 'string' => Kind::String, + 'unicode' => Kind::String, 'email' => Kind::String, 'uri' => Kind::String, 'url' => Kind::String, + 'identifier' => Kind::String, 'class' => Kind::String, 'interface' => Kind::String, + 'file' => Kind::String, 'directory' => Kind::String, 'alnum' => Kind::String, 'alpha' => Kind::String, + 'digit' => Kind::String, 'lower' => Kind::String, 'upper' => Kind::String, 'space' => Kind::String, + 'xdigit' => Kind::String, 'pattern' => Kind::String, + 'array' => Kind::Array, 'list' => Kind::List, 'iterable' => Kind::Iterable, + 'object' => Kind::Object, 'callable' => Kind::Callable, + 'resource' => Kind::Other, 'none' => Kind::Other, 'numeric' => Kind::Other, 'numericint' => Kind::Other, + ]; + + /** @var array<string, array<string, mixed>> */ + private static array $cache = []; + + + /** @return array<string, mixed> */ + public static function parse(string $expression): array + { + return self::$cache[$expression] ??= self::doParse($expression); + } + + + /** @return array<string, mixed> */ + private static function doParse(string $expression): array + { + $variants = []; + $nullable = $dynamic = false; + foreach (explode('|', $expression) as $part) { + if (str_starts_with($part, '?')) { + $nullable = true; + $part = substr($part, 1); + } + + if ($part === 'null') { + $nullable = true; + } elseif ($part === DynamicParameter::class) { + $dynamic = true; + } else { + array_push($variants, ...self::parseAlternative($part)); + } + } + + $item = match (count($variants)) { + 0 => ['kind' => $nullable ? Kind::Null : Kind::Any], + 1 => $variants[0], + default => ['kind' => Kind::Union, 'variants' => $variants], + }; + return $item + ['nullable' => $nullable && count($variants) > 0, 'dynamic' => $dynamic]; + } + + + /** + * One alternative of the expression; 'scalar' expands to several. + * @return list<array<string, mixed>> + */ + private static function parseAlternative(string $part): array + { + if (str_ends_with($part, '[]')) { + $items = self::parseAlternative(substr($part, 0, -2)); + return [[ + 'kind' => Kind::Iterable, + 'items' => count($items) === 1 ? $items[0] : ['kind' => Kind::Union, 'variants' => $items], + 'keys' => null, + 'min' => null, + 'max' => null, + ]]; + } + + if (str_contains($part, '&')) { + return [['kind' => Kind::Other, 'type' => $part]]; // an intersection type cannot be checked + } + + $parts = explode(':', $part, 2); + $name = $parts[0]; + $arg = $parts[1] ?? null; + [$min, $max] = $arg === null || $name === 'pattern' ? [null, null] : self::parseRange($arg); + $number = fn(Kind $kind) => ['kind' => $kind, 'min' => $min, 'max' => $max]; + $string = fn(?string $format = null, ?string $pattern = null) => [ + 'kind' => Kind::String, + 'min' => $min, + 'max' => $max, + 'pattern' => $pattern, + 'format' => $format, + ]; + $collection = fn(Kind $kind) => ['kind' => $kind, 'items' => null, 'keys' => null, 'min' => $min, 'max' => $max]; + + $kind = self::Names[$name] ?? Kind::Instance; + return match (true) { + $name === 'scalar' => [['kind' => Kind::Bool], $number(Kind::Number), $string()], + $name === 'pattern' => [$string(pattern: $arg)], + $kind === Kind::String => [$string(format: $name === 'string' ? null : $name)], + $kind === Kind::Int, $kind === Kind::Float, $kind === Kind::Number => [$number($kind)], + $kind === Kind::Array, $kind === Kind::List, $kind === Kind::Iterable => [$collection($kind)], + $kind === Kind::Instance => [['kind' => $kind, 'type' => $name]], + $kind === Kind::Other => [['kind' => $kind, 'type' => $part]], + default => [['kind' => $kind]], + }; + } + + + /** + * Bounds written as 'min..max', '..max', 'min..' or an exact 'value'. + * @return array{int|float|null, int|float|null} + */ + private static function parseRange(string $range): array + { + $bounds = explode('..', $range) + [1 => $range]; + return [ + $bounds[0] === '' ? null : self::parseBound($bounds[0]), + $bounds[1] === '' ? null : self::parseBound($bounds[1]), + ]; + } + + + /** + * An integer bound stays an integer, a float would lose the precision of large ones. + */ + private static function parseBound(string $bound): int|float + { + return is_numeric($bound) ? $bound + 0 : (float) $bound; + } +} diff --git a/vendor/nette/schema/src/Schema/ValidationException.php b/vendor/nette/schema/src/Schema/ValidationException.php new file mode 100644 index 0000000..cefca43 --- /dev/null +++ b/vendor/nette/schema/src/Schema/ValidationException.php @@ -0,0 +1,50 @@ +<?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\Schema; + +use Nette; + + +/** + * Validation error. + */ +class ValidationException extends Nette\InvalidStateException +{ + public function __construct( + ?string $message, + /** @var list<Message> */ + private readonly array $messages = [], + ) { + parent::__construct($message ?? $messages[0]->toString()); + } + + + /** + * Returns all validation error messages as formatted strings. + * @return list<string> + */ + public function getMessages(): array + { + $res = []; + foreach ($this->messages as $message) { + $res[] = $message->toString(); + } + + return $res; + } + + + /** + * Returns all validation error messages as Message objects. + * @return list<Message> + */ + public function getMessageObjects(): array + { + return $this->messages; + } +} diff --git a/vendor/nette/schema/src/Schema/enums.php b/vendor/nette/schema/src/Schema/enums.php new file mode 100644 index 0000000..8b2883a --- /dev/null +++ b/vendor/nette/schema/src/Schema/enums.php @@ -0,0 +1,48 @@ +<?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\Schema; + + +/** + * The category of value a schema element accepts, the 'kind' of describe(). + * @internal + */ +enum Kind +{ + case Any; + case Null; + case Bool; + case Int; + case Float; + + /** int or float */ + case Number; + case String; + case Array; + case List; + case Iterable; + case Structure; + case Enum; + case Tuple; + case Union; + case Instance; + case Object; + case Callable; + case Other; +} + + +/** + * Defines the strategy for merging array values from multiple configuration layers. + */ +enum MergeMode +{ + case Replace; + case OverwriteKeys; + case AppendKeys; +} diff --git a/vendor/nette/utils/.phpstorm.meta.php b/vendor/nette/utils/.phpstorm.meta.php new file mode 100644 index 0000000..64dc487 --- /dev/null +++ b/vendor/nette/utils/.phpstorm.meta.php @@ -0,0 +1,11 @@ +<?php declare(strict_types=1); + +namespace PHPSTORM_META; + +override(\Nette\Utils\Arrays::get(0), elementType(0)); +override(\Nette\Utils\Arrays::getRef(0), elementType(0)); +override(\Nette\Utils\Arrays::grep(0), type(0)); +override(\Nette\Utils\Arrays::toObject(0), type(1)); + +expectedArguments(\Nette\Utils\Image::resize(), 2, \Nette\Utils\Image::ShrinkOnly, \Nette\Utils\Image::Stretch, \Nette\Utils\Image::OrSmaller, \Nette\Utils\Image::OrBigger, \Nette\Utils\Image::Cover); +expectedArguments(\Nette\Utils\Image::calculateSize(), 4, \Nette\Utils\Image::ShrinkOnly, \Nette\Utils\Image::Stretch, \Nette\Utils\Image::OrSmaller, \Nette\Utils\Image::OrBigger, \Nette\Utils\Image::Cover); diff --git a/vendor/nette/utils/composer.json b/vendor/nette/utils/composer.json new file mode 100644 index 0000000..b881ec6 --- /dev/null +++ b/vendor/nette/utils/composer.json @@ -0,0 +1,61 @@ +{ + "name": "nette/utils", + "description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.", + "keywords": ["nette", "images", "json", "password", "validation", "utility", "string", "array", "core", "slugify", "utf-8", "unicode", "paginator", "datetime"], + "homepage": "https://nette.org", + "license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "require": { + "php": "8.2 - 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", + "jetbrains/phpstorm-attributes": "^1.2" + }, + "conflict": { + "nette/finder": "<3", + "nette/schema": "<1.2.2" + }, + "suggest": { + "ext-iconv": "to use Strings::chr(), ord() 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...", + "ext-gd": "to use Image", + "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()" + }, + "autoload": { + "classmap": ["src/"], + "psr-4": { + "Nette\\": "src" + } + }, + "minimum-stability": "dev", + "scripts": { + "phpstan": "phpstan analyse", + "tester": "tester tests -s" + }, + "extra": { + "branch-alias": { + "dev-master": "4.1-dev" + } + }, + "config": { + "allow-plugins": { + "phpstan/extension-installer": true + } + } +} diff --git a/vendor/nette/utils/license.md b/vendor/nette/utils/license.md new file mode 100644 index 0000000..cf741bd --- /dev/null +++ b/vendor/nette/utils/license.md @@ -0,0 +1,60 @@ +Licenses +======== + +Good news! You may use Nette Framework under the terms of either +the New BSD License or the GNU General Public License (GPL) version 2 or 3. + +The BSD License is recommended for most projects. It is easy to understand and it +places almost no restrictions on what you can do with the framework. If the GPL +fits better to your project, you can use the framework under this license. + +You don't have to notify anyone which license you are using. You can freely +use Nette Framework in commercial projects as long as the copyright header +remains intact. + +Please be advised that the name "Nette Framework" is a protected trademark and its +usage has some limitations. So please do not use word "Nette" in the name of your +project or top-level domain, and choose a name that stands on its own merits. +If your stuff is good, it will not take long to establish a reputation for yourselves. + + +New BSD License +--------------- + +Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of "Nette Framework" nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as is" and +any express or implied warranties, including, but not limited to, the implied +warranties of merchantability and fitness for a particular purpose are +disclaimed. In no event shall the copyright owner or contributors be liable for +any direct, indirect, incidental, special, exemplary, or consequential damages +(including, but not limited to, procurement of substitute goods or services; +loss of use, data, or profits; or business interruption) however caused and on +any theory of liability, whether in contract, strict liability, or tort +(including negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. + + +GNU General Public License +-------------------------- + +GPL licenses are very very long, so instead of including them here we offer +you URLs with full text: + +- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html) +- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html) diff --git a/vendor/nette/utils/readme.md b/vendor/nette/utils/readme.md new file mode 100644 index 0000000..f34633e --- /dev/null +++ b/vendor/nette/utils/readme.md @@ -0,0 +1,55 @@ +[![Nette Utils](https://github.com/nette/utils/assets/194960/c33fdb74-0652-4cad-ac6e-c1ce0d29e32a)](https://doc.nette.org/en/utils) + +[![Downloads this Month](https://img.shields.io/packagist/dm/nette/utils.svg)](https://packagist.org/packages/nette/utils) +[![Tests](https://github.com/nette/utils/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/utils/actions) +[![Coverage Status](https://coveralls.io/repos/github/nette/utils/badge.svg?branch=master)](https://coveralls.io/github/nette/utils?branch=master) +[![Latest Stable Version](https://poser.pugx.org/nette/utils/v/stable)](https://github.com/nette/utils/releases) +[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/utils/blob/master/license.md) + + +Introduction +------------ + +In package nette/utils you will find a set of useful classes for everyday use: + +✅ [Arrays](https://doc.nette.org/utils/arrays)<br> +✅ [Callback](https://doc.nette.org/utils/callback) - PHP callbacks<br> +✅ [Filesystem](https://doc.nette.org/utils/filesystem) - copying, renaming, …<br> +✅ [Finder](https://doc.nette.org/utils/finder) - finds files and directories<br> +✅ [Floats](https://doc.nette.org/utils/floats) - floating point numbers<br> +✅ [Helper Functions](https://doc.nette.org/utils/helpers)<br> +✅ [HTML elements](https://doc.nette.org/utils/html-elements) - generate HTML<br> +✅ [Images](https://doc.nette.org/utils/images) - crop, resize, rotate images<br> +✅ [Iterables](https://doc.nette.org/utils/iterables) <br> +✅ [JSON](https://doc.nette.org/utils/json) - encoding and decoding<br> +✅ [Generating Random Strings](https://doc.nette.org/utils/random)<br> +✅ [Paginator](https://doc.nette.org/utils/paginator) - pagination math<br> +✅ [PHP Reflection](https://doc.nette.org/utils/reflection)<br> +✅ [Strings](https://doc.nette.org/utils/strings) - useful text functions<br> +✅ [SmartObject](https://doc.nette.org/utils/smartobject) - PHP object enhancements<br> +✅ [Type](https://doc.nette.org/utils/type) - PHP data type<br> +✅ [Validation](https://doc.nette.org/utils/validators) - validate inputs<br> + + <!----> + +Installation +------------ + +The recommended way to install is via Composer: + +``` +composer require nette/utils +``` + +Nette Utils 4.1 is compatible with PHP 8.2 to 8.6. + + <!----> + +[Support Me](https://github.com/sponsors/dg) +-------------------------------------------- + +Do you like Nette Utils? Are you looking forward to the new features? + +[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg) + +Thank you! diff --git a/vendor/nette/utils/src/HtmlStringable.php b/vendor/nette/utils/src/HtmlStringable.php new file mode 100644 index 0000000..c9600d2 --- /dev/null +++ b/vendor/nette/utils/src/HtmlStringable.php @@ -0,0 +1,23 @@ +<?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; + + +/** + * Represents object convertible to HTML string. + */ +interface HtmlStringable +{ + /** + * Returns string in HTML format. + */ + function __toString(): string; +} + + +interface_exists(Utils\IHtmlString::class); diff --git a/vendor/nette/utils/src/Iterators/CachingIterator.php b/vendor/nette/utils/src/Iterators/CachingIterator.php new file mode 100644 index 0000000..4c2830c --- /dev/null +++ b/vendor/nette/utils/src/Iterators/CachingIterator.php @@ -0,0 +1,133 @@ +<?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\Iterators; + +use Nette; + + +/** + * Enhanced caching iterator with first/last/counter tracking. + * + * @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 + */ +class CachingIterator extends \CachingIterator implements \Countable +{ + use Nette\SmartObject; + + private int $counter = 0; + + + /** @param iterable<TKey, TValue>|\stdClass $iterable */ + public function __construct(iterable|\stdClass $iterable) + { + $iterable = $iterable instanceof \stdClass + ? new \ArrayIterator((array) $iterable) + : Nette\Utils\Iterables::toIterator($iterable); + parent::__construct($iterable, 0); + } + + + /** + * Is the current element the first one? + */ + public function isFirst(?int $gridWidth = null): bool + { + return $this->counter === 1 || ($gridWidth && $this->counter !== 0 && (($this->counter - 1) % $gridWidth) === 0); + } + + + /** + * Is the current element the last one? + */ + public function isLast(?int $gridWidth = null): bool + { + return !$this->hasNext() || ($gridWidth && ($this->counter % $gridWidth) === 0); + } + + + public function isEmpty(): bool + { + return $this->counter === 0; + } + + + public function isOdd(): bool + { + return $this->counter % 2 === 1; + } + + + public function isEven(): bool + { + return $this->counter % 2 === 0; + } + + + public function getCounter(): int + { + return $this->counter; + } + + + public function count(): int + { + $inner = $this->getInnerIterator(); + if ($inner instanceof \Countable) { + return $inner->count(); + + } else { + throw new Nette\NotSupportedException('Iterator is not countable.'); + } + } + + + /** + * Forwards to the next element. + */ + public function next(): void + { + parent::next(); + if (parent::valid()) { + $this->counter++; + } + } + + + /** + * Rewinds the Iterator. + */ + public function rewind(): void + { + parent::rewind(); + $this->counter = parent::valid() ? 1 : 0; + } + + + /** @return TKey */ + public function getNextKey(): mixed + { + return $this->getInnerIterator()->key(); + } + + + /** @return TValue */ + 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 new file mode 100644 index 0000000..34a17e0 --- /dev/null +++ b/vendor/nette/utils/src/Iterators/Mapper.php @@ -0,0 +1,30 @@ +<?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\Iterators; + + +/** + * @deprecated use Nette\Utils\Iterables::map() + */ +class Mapper extends \IteratorIterator +{ + private readonly \Closure $callback; + + + public function __construct(\Traversable $iterator, callable $callback) + { + parent::__construct($iterator); + $this->callback = $callback(...); + } + + + public function current(): mixed + { + return ($this->callback)(parent::current(), parent::key()); + } +} diff --git a/vendor/nette/utils/src/SmartObject.php b/vendor/nette/utils/src/SmartObject.php new file mode 100644 index 0000000..d9742c8 --- /dev/null +++ b/vendor/nette/utils/src/SmartObject.php @@ -0,0 +1,141 @@ +<?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; + +use Nette\Utils\ObjectHelpers; + + +/** + * Strict class for better experience. + * - 'did you mean' hints + * - access to undeclared members throws exceptions + * - support for @property annotations + * - support for calling event handlers stored in $onEvent via onEvent() + */ +trait SmartObject +{ + /** + * @param mixed[] $args + * @return mixed + * @throws MemberAccessException + */ + public function __call(string $name, array $args) + { + $class = static::class; + + if (ObjectHelpers::hasProperty($class, $name) === 'event') { // calling event handlers + $handlers = $this->$name ?? null; + if (is_iterable($handlers)) { + foreach ($handlers as $handler) { + $handler(...$args); + } + } elseif ($handlers !== null) { + throw new UnexpectedValueException("Property $class::$$name must be iterable or null, " . get_debug_type($handlers) . ' given.'); + } + + return null; + } + + ObjectHelpers::strictCall($class, $name); + } + + + /** + * @param mixed[] $args + * @return never + * @throws MemberAccessException + */ + public static function __callStatic(string $name, array $args) + { + ObjectHelpers::strictStaticCall(static::class, $name); + } + + + /** + * @return mixed + * @throws MemberAccessException if the property is not defined. + */ + public function &__get(string $name) + { + $class = static::class; + + if ($prop = ObjectHelpers::getMagicProperties($class)[$name] ?? null) { // property getter + if (!($prop & 0b0001)) { + throw new MemberAccessException("Cannot read a write-only property $class::\$$name."); + } + + $m = ($prop & 0b0010 ? 'get' : 'is') . ucfirst($name); + if ($prop & 0b10000) { + $trace = debug_backtrace(0, 1)[0]; // suppose this method is called from __call() + $loc = isset($trace['file'], $trace['line']) + ? " in $trace[file] on line $trace[line]" + : ''; + trigger_error("Property $class::\$$name is deprecated, use $class::$m() method$loc.", E_USER_DEPRECATED); + } + + if ($prop & 0b0100) { // return by reference + return $this->$m(); + } else { + $val = $this->$m(); + return $val; + } + } else { + ObjectHelpers::strictGet($class, $name); + } + } + + + /** + * @throws MemberAccessException if the property is not defined or is read-only + */ + public function __set(string $name, mixed $value): void + { + $class = static::class; + + if (ObjectHelpers::hasProperty($class, $name)) { // unsetted property + $this->$name = $value; + + } elseif ($prop = ObjectHelpers::getMagicProperties($class)[$name] ?? null) { // property setter + if (!($prop & 0b1000)) { + throw new MemberAccessException("Cannot write to a read-only property $class::\$$name."); + } + + $m = 'set' . ucfirst($name); + if ($prop & 0b10000) { + $trace = debug_backtrace(0, 1)[0]; // suppose this method is called from __call() + $loc = isset($trace['file'], $trace['line']) + ? " in $trace[file] on line $trace[line]" + : ''; + trigger_error("Property $class::\$$name is deprecated, use $class::$m() method$loc.", E_USER_DEPRECATED); + } + + $this->$m($value); + + } else { + ObjectHelpers::strictSet($class, $name); + } + } + + + /** + * @throws MemberAccessException + */ + public function __unset(string $name): void + { + $class = static::class; + if (!ObjectHelpers::hasProperty($class, $name)) { + throw new MemberAccessException("Cannot unset the property $class::\$$name."); + } + } + + + public function __isset(string $name): bool + { + return isset(ObjectHelpers::getMagicProperties(static::class)[$name]); + } +} diff --git a/vendor/nette/utils/src/StaticClass.php b/vendor/nette/utils/src/StaticClass.php new file mode 100644 index 0000000..e88a74b --- /dev/null +++ b/vendor/nette/utils/src/StaticClass.php @@ -0,0 +1,22 @@ +<?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; + + +/** + * Prevents instantiation. + */ +trait StaticClass +{ + /** + * Class is static and cannot be instantiated. + */ + private function __construct() + { + } +} diff --git a/vendor/nette/utils/src/Translator.php b/vendor/nette/utils/src/Translator.php new file mode 100644 index 0000000..85c2e1b --- /dev/null +++ b/vendor/nette/utils/src/Translator.php @@ -0,0 +1,23 @@ +<?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\Localization; + + +/** + * Translation provider. + */ +interface Translator +{ + /** + * Translates the given string. + */ + function translate(string|\Stringable $message, mixed ...$parameters): string|\Stringable; +} + + +interface_exists(ITranslator::class); diff --git a/vendor/nette/utils/src/Utils/ArrayHash.php b/vendor/nette/utils/src/Utils/ArrayHash.php new file mode 100644 index 0000000..cb19b36 --- /dev/null +++ b/vendor/nette/utils/src/Utils/ArrayHash.php @@ -0,0 +1,100 @@ +<?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 count, is_array, is_scalar, sprintf; + + +/** + * Array-like object with property access. + * @template T + * @implements \IteratorAggregate<array-key, T> + * @implements \ArrayAccess<array-key, T> + */ +class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate +{ + /** + * Transforms array to ArrayHash. + * @param array<T> $array + */ + public static function from(array $array, bool $recursive = true): static + { + $obj = new static; + foreach ($array as $key => $value) { + $obj->$key = $recursive && is_array($value) + ? static::from($value) + : $value; + } + + return $obj; + } + + + /** + * @return \Iterator<array-key, T> + */ + public function &getIterator(): \Iterator + { + foreach ((array) $this as $key => $foo) { + yield $key => $this->$key; + } + } + + + public function count(): int + { + return count((array) $this); + } + + + /** + * Replaces or appends an item. + * @param array-key $key + * @param T $value + */ + public function offsetSet($key, $value): void + { + if (!is_scalar($key)) { // prevents null + throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.', get_debug_type($key))); + } + + $this->$key = $value; + } + + + /** + * Returns an item. + * @param array-key $key + * @return T + */ + public function offsetGet($key): mixed + { + return $this->$key; + } + + + /** + * Determines whether an item exists. + * @param array-key $key + */ + public function offsetExists($key): bool + { + return isset($this->$key); + } + + + /** + * Removes the element from this list. + * @param array-key $key + */ + public function offsetUnset($key): void + { + unset($this->$key); + } +} diff --git a/vendor/nette/utils/src/Utils/ArrayList.php b/vendor/nette/utils/src/Utils/ArrayList.php new file mode 100644 index 0000000..7852ce8 --- /dev/null +++ b/vendor/nette/utils/src/Utils/ArrayList.php @@ -0,0 +1,130 @@ +<?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 count, is_int; + + +/** + * Generic list with integer indices. + * @template T + * @implements \IteratorAggregate<int, T> + * @implements \ArrayAccess<int, T> + */ +class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate +{ + /** @var list<T> */ + private array $list = []; + + + /** + * Transforms array to ArrayList. + * @param list<T> $array + */ + public static function from(array $array): static + { + if (!Arrays::isList($array)) { + throw new Nette\InvalidArgumentException('Array is not valid list.'); + } + + $obj = new static; + $obj->list = $array; + return $obj; + } + + + /** + * @return \Iterator<int, T> + */ + public function &getIterator(): \Iterator + { + foreach ($this->list as &$item) { + yield $item; + } + } + + + public function count(): int + { + return count($this->list); + } + + + /** + * Replaces or appends an item. + * @param ?int $index + * @param T $value + * @throws Nette\OutOfRangeException + */ + public function offsetSet($index, $value): void + { + if ($index === null) { + $this->list[] = $value; + + } elseif (!is_int($index) || $index < 0 || $index >= count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + + } else { + $this->list[$index] = $value; + } + } + + + /** + * Returns an item. + * @param int $index + * @return T + * @throws Nette\OutOfRangeException + */ + public function offsetGet($index): mixed + { + if (!is_int($index) || $index < 0 || $index >= count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + } + + return $this->list[$index]; + } + + + /** + * Determines whether an item exists. + * @param int $index + */ + public function offsetExists($index): bool + { + return is_int($index) && $index >= 0 && $index < count($this->list); + } + + + /** + * Removes the element at the specified position in this list. + * @param int $index + * @throws Nette\OutOfRangeException + */ + public function offsetUnset($index): void + { + if (!is_int($index) || $index < 0 || $index >= count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + } + + array_splice($this->list, $index, 1); + } + + + /** + * Prepends an item. + * @param T $value + */ + 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)); + } +} diff --git a/vendor/nette/utils/src/Utils/Arrays.php b/vendor/nette/utils/src/Utils/Arrays.php new file mode 100644 index 0000000..51916a6 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Arrays.php @@ -0,0 +1,572 @@ +<?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 JetBrains\PhpStorm\Language; +use Nette; +use function array_key_exists, count, func_num_args, is_array, is_int, is_object; +use const PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_NO_EMPTY; + + +/** + * Array manipulation utilities. + */ +class Arrays +{ + use Nette\StaticClass; + + /** + * Returns item from array. If it does not exist, it throws an exception, unless a default value is set. + * @template T + * @param array<T> $array + * @param array-key|array-key[] $key + * @param ?T $default + * @return ?T + * @throws Nette\InvalidArgumentException if item does not exist and default value is not provided + */ + public static function get(array $array, string|int|array $key, mixed $default = null): mixed + { + foreach (is_array($key) ? $key : [$key] as $k) { + if (is_array($array) && array_key_exists($k, $array)) { + $array = $array[$k]; + } else { + if (func_num_args() < 3) { + throw new Nette\InvalidArgumentException("Missing item '$k'."); + } + + return $default; + } + } + + return $array; + } + + + /** + * Returns reference to array item. If the index does not exist, new one is created with value null. + * @template T + * @param array<T> $array + * @param array-key|array-key[] $key + * @return ?T + * @throws Nette\InvalidArgumentException if traversed item is not an array + */ + public static function &getRef(array &$array, string|int|array $key): mixed + { + foreach (is_array($key) ? $key : [$key] as $k) { + if (is_array($array) || $array === null) { + $array = &$array[$k]; + } else { + throw new Nette\InvalidArgumentException('Traversed item is not an array.'); + } + } + + return $array; + } + + + /** + * 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. + * @template T1 + * @template T2 + * @param array<T1> $array1 + * @param array<T2> $array2 + * @return array<T1|T2|array<mixed>> + */ + public static function mergeTree(array $array1, array $array2): array + { + $res = $array1 + $array2; + foreach (array_intersect_key($array1, $array2) as $k => $v) { + if (is_array($v) && is_array($array2[$k])) { + $res[$k] = self::mergeTree($v, $array2[$k]); + } + } + + return $res; + } + + + /** + * 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 + { + return Helpers::falseToNull(array_search(self::toKey($key), array_keys($array), strict: true)); + } + + + /** + * @param array<mixed> $array + * @deprecated use getKeyOffset() + */ + public static function searchKey(array $array, string|int $key): ?int + { + return self::getKeyOffset($array, $key); + } + + + /** + * 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, true); + } + + + /** + * 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) + */ + public static function first(array $array, ?callable $predicate = null, ?callable $else = null): mixed + { + $key = self::firstKey($array, $predicate); + return $key === null + ? ($else ? $else() : null) + : $array[$key]; + } + + + /** + * 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) + */ + public static function last(array $array, ?callable $predicate = null, ?callable $else = null): mixed + { + $key = self::lastKey($array, $predicate); + return $key === null + ? ($else ? $else() : null) + : $array[$key]; + } + + + /** + * Returns the key of first item (matching the specified predicate if given) or null if there is no such item. + * @template K of int|string + * @template V + * @param array<K, V> $array + * @param ?callable(V, K, array<K, V>): bool $predicate + * @return ?K + */ + public static function firstKey(array $array, ?callable $predicate = null): int|string|null + { + if (!$predicate) { + return array_key_first($array); + } + foreach ($array as $k => $v) { + if ($predicate($v, $k, $array)) { + return $k; + } + } + return null; + } + + + /** + * Returns the key of last item (matching the specified predicate if given) or null if there is no such item. + * @template K of int|string + * @template V + * @param array<K, V> $array + * @param ?callable(V, K, array<K, V>): bool $predicate + * @return ?K + */ + public static function lastKey(array $array, ?callable $predicate = null): int|string|null + { + return $predicate + ? self::firstKey(array_reverse($array, preserve_keys: true), $predicate) + : array_key_last($array); + } + + + /** + * Inserts the contents of the $inserted array into the $array immediately before 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 + { + $offset = $key === null ? 0 : (int) self::getKeyOffset($array, $key); + $array = array_slice($array, 0, $offset, preserve_keys: true) + + $inserted + + array_slice($array, $offset, count($array), preserve_keys: true); + } + + + /** + * 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 end. + * @param array<mixed> $array + * @param array<mixed> $inserted + */ + public static function insertAfter(array &$array, string|int|null $key, array $inserted): void + { + if ($key === null || ($offset = self::getKeyOffset($array, $key)) === null) { + $offset = count($array) - 1; + } + + $array = array_slice($array, 0, $offset + 1, preserve_keys: true) + + $inserted + + array_slice($array, $offset + 1, count($array), preserve_keys: true); + } + + + /** + * Renames key in array. + * @param array<mixed> $array + */ + public static function renameKey(array &$array, string|int $oldKey, string|int $newKey): bool + { + $offset = self::getKeyOffset($array, $oldKey); + if ($offset === null) { + return false; + } + + $val = &$array[$oldKey]; + $keys = array_keys($array); + $keys[$offset] = $newKey; + $array = array_combine($keys, $array); + $array[$newKey] = &$val; + return true; + } + + + /** + * Returns only those array items, which matches a regular expression $pattern. + * @param string[] $array + * @return string[] + */ + public static function grep( + array $array, + #[Language('RegExp')] + string $pattern, + bool|int $invert = false, + ): array + { + $flags = $invert ? PREG_GREP_INVERT : 0; + return Strings::pcre('preg_grep', [$pattern, $array, $flags]); + } + + + /** + * 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; }; + array_walk_recursive($array, $cb); + return $res; + } + + + /** + * Checks if the array is indexed in ascending order of numeric keys from zero, a.k.a list. + * @return ($value is list ? true : false) + */ + public static function isList(mixed $value): bool + { + return is_array($value) && 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 + */ + public static function associate(array $array, string|array $path): array|\stdClass + { + $parts = is_array($path) + ? $path + : 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) . "'."); + } + + $res = $parts[0] === '->' ? new \stdClass : []; + + foreach ($array as $rowOrig) { + $row = (array) $rowOrig; + $x = &$res; + + for ($i = 0; $i < count($parts); $i++) { + $part = $parts[$i]; + if ($part === '[]') { + $x = &$x[]; + + } elseif ($part === '=') { + if (isset($parts[++$i])) { + $x = $row[$parts[$i]]; + $row = null; + } + break; // '=' is always the final operation + + } elseif ($part === '->') { + if (isset($parts[++$i])) { + if ($x === null) { + $x = new \stdClass; + } + + $x = &$x->{$row[$parts[$i]]}; + + } else { + $row = is_object($rowOrig) ? $rowOrig : (object) $row; + } + } elseif ($part !== '|') { + $x = &$x[(string) $row[$part]]; + } + } + + if ($x === null) { + $x = $row; + } + } + + return $res; + } + + + /** + * 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> + */ + public static function normalize(array $array, mixed $filling = null): array + { + $res = []; + foreach ($array as $k => $v) { + $res[is_int($k) ? $v : $k] = is_int($k) ? $filling : $v; + } + + return $res; + } + + + /** + * Returns and removes the value of an item from an array. If it does not exist, it throws an exception, + * or returns $default, if provided. + * @template T + * @param array<T> $array + * @param ?T $default + * @return ?T + * @throws Nette\InvalidArgumentException if item does not exist and default value is not provided + */ + public static function pick(array &$array, string|int $key, mixed $default = null): mixed + { + if (array_key_exists($key, $array)) { + $value = $array[$key]; + unset($array[$key]); + return $value; + + } elseif (func_num_args() < 3) { + throw new Nette\InvalidArgumentException("Missing item '$key'."); + + } else { + return $default; + } + } + + + /** + * Tests whether at least one element in the array passes the test implemented by the provided function. + * @template K of int|string + * @template V + * @param array<K, V> $array + * @param callable(V, K, array<K, V>): bool $predicate + */ + public static function some(iterable $array, callable $predicate): bool + { + foreach ($array as $k => $v) { + if ($predicate($v, $k, $array)) { + return true; + } + } + + return false; + } + + + /** + * Tests whether all elements in the array pass the test implemented by the provided function. + * @template K of int|string + * @template V + * @param array<K, V> $array + * @param callable(V, K, array<K, V>): bool $predicate + */ + public static function every(iterable $array, callable $predicate): bool + { + foreach ($array as $k => $v) { + if (!$predicate($v, $k, $array)) { + return false; + } + } + + return true; + } + + + /** + * Returns a new array containing all key-value pairs matching the given $predicate. + * @template K of int|string + * @template V + * @param array<K, V> $array + * @param callable(V, K, array<K, V>): bool $predicate + * @return array<K, V> + */ + public static function filter(array $array, callable $predicate): array + { + $res = []; + foreach ($array as $k => $v) { + if ($predicate($v, $k, $array)) { + $res[$k] = $v; + } + } + return $res; + } + + + /** + * Returns an array containing the original keys and results of applying the given transform function to each element. + * @template K of int|string + * @template V + * @template R + * @param array<K, V> $array + * @param callable(V, K, array<K, V>): R $transformer + * @return array<K, R> + */ + public static function map(iterable $array, callable $transformer): array + { + $res = []; + foreach ($array as $k => $v) { + $res[$k] = $transformer($v, $k, $array); + } + + return $res; + } + + + /** + * Returns an array containing new keys and values generated by applying the given transform function to each element. + * If the function returns null, the element is skipped. + * @template K of int|string + * @template V + * @template ResK of int|string + * @template ResV + * @param array<K, V> $array + * @param callable(V, K, array<K, V>): ?array{ResK, ResV} $transformer + * @return array<ResK, ResV> + */ + public static function mapWithKeys(array $array, callable $transformer): array + { + $res = []; + foreach ($array as $k => $v) { + $pair = $transformer($v, $k, $array); + if ($pair) { + $res[$pair[0]] = $pair[1]; + } + } + + return $res; + } + + + /** + * Invokes all callbacks and returns array of results. + * @param iterable<callable> $callbacks + * @return array<mixed> + */ + public static function invoke(iterable $callbacks, mixed ...$args): array + { + $res = []; + foreach ($callbacks as $k => $cb) { + $res[$k] = $cb(...$args); + } + + return $res; + } + + + /** + * Invokes method on every object in an array and returns array of results. + * @param iterable<object> $objects + * @return array<mixed> + */ + public static function invokeMethod(iterable $objects, string $method, mixed ...$args): array + { + $res = []; + foreach ($objects as $k => $obj) { + $res[$k] = $obj->$method(...$args); + } + + return $res; + } + + + /** + * 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 + */ + public static function toObject(iterable $array, object $object): object + { + foreach ($array as $k => $v) { + $object->$k = $v; + } + + return $object; + } + + + /** + * Converts value to array key. + */ + public static function toKey(mixed $value): int|string + { + 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. + * @param string[] $array + * @return string[] + */ + public static function wrap(array $array, string $prefix = '', string $suffix = ''): array + { + $res = []; + foreach ($array as $k => $v) { + $res[$k] = $prefix . $v . $suffix; + } + + return $res; + } +} diff --git a/vendor/nette/utils/src/Utils/Callback.php b/vendor/nette/utils/src/Utils/Callback.php new file mode 100644 index 0000000..f880f30 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Callback.php @@ -0,0 +1,142 @@ +<?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 func_get_args, ini_get, is_array, is_object, is_string, sprintf; + + +/** + * PHP callable tools. + */ +final class Callback +{ + use Nette\StaticClass; + + /** + * 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 { + if ($file === __FILE__) { + $msg = ini_get('html_errors') + ? Html::htmlToText($message) + : $message; + $msg = (string) preg_replace("#^$function\\(.*?\\): #", '', $msg); + if ($onError($msg, $severity) !== false) { + return true; + } + } + + return $prev ? $prev(...func_get_args()) !== false : false; + }, + ); + + try { + return $function(...$args); + } finally { + restore_error_handler(); + } + } + + + /** + * 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. + * @return callable + * @throws Nette\InvalidArgumentException + */ + public static function check(mixed $callable, bool $syntax = false): mixed + { + 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)), + ); + } + + return $callable; + } + + + /** + * Converts PHP callback to textual form. Class or method may not exists. + */ + public static function toString(mixed $callable): string + { + if ($callable instanceof \Closure) { + $inner = self::unwrap($callable); + return '{closure' . ($inner instanceof \Closure ? '}' : ' ' . self::toString($inner) . '}'); + } else { + is_callable(is_object($callable) ? [$callable, '__invoke'] : $callable, true, $textual); + return $textual; + } + } + + + /** + * Returns reflection for method or function used in PHP 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 + { + if ($callable instanceof \Closure) { + $callable = self::unwrap($callable); + } + + if (is_string($callable) && str_contains($callable, '::')) { + return new ReflectionMethod(...explode('::', $callable, 2)); + } elseif (is_array($callable)) { + return new ReflectionMethod($callable[0], $callable[1]); + } elseif (is_object($callable) && !$callable instanceof \Closure) { + return new ReflectionMethod($callable, '__invoke'); + } else { + assert($callable instanceof \Closure || is_string($callable)); + return new \ReflectionFunction($callable); + } + } + + + /** + * Checks whether PHP callback is function or static method. + */ + public static function isStatic(callable $callable): bool + { + return is_string(is_array($callable) ? $callable[0] : $callable); + } + + + /** + * Unwraps closure created by Closure::fromCallable(). + * @return callable|array{object|class-string, string}|string + */ + public static function unwrap(\Closure $closure): callable|array|string + { + $r = new \ReflectionFunction($closure); + $class = $r->getClosureScopeClass()?->name; + if (str_ends_with($r->name, '}')) { + return $closure; + + } elseif (($obj = $r->getClosureThis()) && $obj::class === $class) { + return [$obj, $r->name]; + + } elseif ($class) { + return [$class, $r->name]; + + } else { + return $r->name; + } + } +} diff --git a/vendor/nette/utils/src/Utils/DateTime.php b/vendor/nette/utils/src/Utils/DateTime.php new file mode 100644 index 0000000..bf99d14 --- /dev/null +++ b/vendor/nette/utils/src/Utils/DateTime.php @@ -0,0 +1,207 @@ +<?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 is_string; + + +/** + * Extends PHP's DateTime with strict validation and additional factory methods. + */ +class DateTime extends \DateTime implements \JsonSerializable +{ + /** minute in seconds */ + public const MINUTE = 60; + + /** hour in seconds */ + public const HOUR = 60 * self::MINUTE; + + /** day in seconds */ + public const DAY = 24 * self::HOUR; + + /** week in seconds */ + public const WEEK = 7 * self::DAY; + + /** average month in seconds */ + public const MONTH = 2_629_800; + + /** average year in seconds */ + public const YEAR = 31_557_600; + + + /** + * Creates a DateTime 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_numeric($time)) { + if ($time <= self::YEAR) { + $time += time(); + } + + return (new static)->setTimestamp((int) $time); + + } else { // textual or null + return new static((string) $time); + } + } + + + /** + * Creates DateTime 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 DateTime 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) + { + $this->apply($datetime, $timezone, ctr: true); + } + + + public function modify(string $modifier): static + { + $this->apply($modifier); + return $this; + } + + + 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); + } + + + /** + * Converts a relative time string (e.g. '10 minut') to seconds. + */ + public static function relativeToSeconds(string $relativeTime): int + { + return (new self('@0 ' . $relativeTime)) + ->getTimestamp(); + } + + + private function apply(string $datetime, ?\DateTimeZone $timezone = null, bool $ctr = false): void + { + $relPart = ''; + $absPart = preg_replace_callback( + '/[+-]?\s*\d+\s+((microsecond|millisecond|[mµu]sec)s?|[mµ]s|sec(ond)?s?|min(ute)?s?|hours?)(\s+ago)?\b/iu', + function ($m) use (&$relPart) { + $relPart .= $m[0] . ' '; + return ''; + }, + $datetime, + ); + + if ($ctr) { + parent::__construct(trim($absPart), $timezone); + $this->handleErrors($datetime); + } elseif (trim($absPart)) { + parent::modify($absPart) && $this->handleErrors($datetime); + } + + if ($relPart) { + $timezone ??= $this->getTimezone(); + $this->setTimezone(new \DateTimeZone('UTC')); + parent::modify($relPart) && $this->handleErrors($datetime); + $this->setTimezone($timezone); + } + } + + + /** + * 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'); + } + + + /** + * Returns a modified copy of the object. Use (clone $dt)->modify(...) for better type safety. + */ + public function modifyClone(string $modify = ''): static + { + $dolly = clone $this; + return $modify ? $dolly->modify($modify) : $dolly; + } + + + private function handleErrors(string $value): void + { + $errors = self::getLastErrors(); + $errors = [...$errors['errors'] ?? [], ...$errors['warnings'] ?? []]; + if ($errors) { + throw new \Exception(implode(', ', $errors) . " '$value'"); + } + } +} diff --git a/vendor/nette/utils/src/Utils/DateTimeImmutable.php b/vendor/nette/utils/src/Utils/DateTimeImmutable.php new file mode 100644 index 0000000..a2d2bb2 --- /dev/null +++ b/vendor/nette/utils/src/Utils/DateTimeImmutable.php @@ -0,0 +1,187 @@ +<?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 is_int, is_string; + + +/** + * 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(trim($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 = [...$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 new file mode 100644 index 0000000..9942053 --- /dev/null +++ b/vendor/nette/utils/src/Utils/FileInfo.php @@ -0,0 +1,65 @@ +<?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; + + +/** + * Represents the file or directory returned by the Finder. + * @internal do not create instances directly + */ +final class FileInfo extends \SplFileInfo +{ + public function __construct( + string $file, + private readonly string $relativePath = '', + ) { + parent::__construct($file); + $this->setInfoClass(self::class); + } + + + /** + * Returns the relative directory path. + */ + public function getRelativePath(): string + { + return $this->relativePath; + } + + + /** + * Returns the relative path including file name. + */ + public function getRelativePathname(): string + { + return ($this->relativePath === '' ? '' : $this->relativePath . DIRECTORY_SEPARATOR) + . $this->getBasename(); + } + + + /** + * Returns the contents of the file. + * @throws Nette\IOException + */ + public function read(): string + { + return FileSystem::read($this->getPathname()); + } + + + /** + * Writes the contents to the file. + * @throws Nette\IOException + */ + public function write(string $content): void + { + FileSystem::write($this->getPathname(), $content); + } +} diff --git a/vendor/nette/utils/src/Utils/FileSystem.php b/vendor/nette/utils/src/Utils/FileSystem.php new file mode 100644 index 0000000..4d824ba --- /dev/null +++ b/vendor/nette/utils/src/Utils/FileSystem.php @@ -0,0 +1,390 @@ +<?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 sprintf, strlen; +use const DIRECTORY_SEPARATOR; + + +/** + * File system tool. + */ +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 + { + if (!is_dir($dir) && !@mkdir($dir, $mode, recursive: true) && !is_dir($dir)) { // @ - dir may already exist + throw new Nette\IOException(sprintf( + "Unable to create directory '%s' with mode %s. %s", + self::normalizePath($dir), + decoct($mode), + Helpers::getLastError(), + )); + } + } + + + /** + * Copies a file or an entire directory. Overwrites existing files and directories by default. + * @throws Nette\IOException on error occurred + * @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists + */ + public static function copy(string $origin, string $target, bool $overwrite = true): void + { + if (stream_is_local($origin) && !file_exists($origin)) { + throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($origin))); + + } elseif (!$overwrite && file_exists($target)) { + throw new Nette\InvalidStateException(sprintf("File or directory '%s' already exists.", self::normalizePath($target))); + + } 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) { + if ($item->isDir()) { + static::createDir($target . '/' . $iterator->getSubPathname()); + } else { + static::copy($item->getPathname(), $target . '/' . $iterator->getSubPathname()); + } + } + } else { + static::createDir(dirname($target)); + if (@stream_copy_to_stream(static::open($origin, 'rb'), static::open($target, 'wb')) === false) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to copy file '%s' to '%s'. %s", + self::normalizePath($origin), + self::normalizePath($target), + Helpers::getLastError(), + )); + } + } + } + + + /** + * Opens file and returns resource. + * @return resource + * @throws Nette\IOException on error occurred + */ + public static function open(string $path, string $mode) + { + $f = @fopen($path, $mode); // @ is escalated to exception + if (!$f) { + throw new Nette\IOException(sprintf( + "Unable to open file '%s'. %s", + self::normalizePath($path), + Helpers::getLastError(), + )); + } + return $f; + } + + + /** + * Deletes a file or an entire directory if exists. If the directory is not empty, it deletes its contents first. + * @throws Nette\IOException on error occurred + */ + public static function delete(string $path): void + { + if (is_file($path) || is_link($path)) { + $func = DIRECTORY_SEPARATOR === '\\' && is_dir($path) ? 'rmdir' : 'unlink'; + if (!@$func($path)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to delete '%s'. %s", + self::normalizePath($path), + Helpers::getLastError(), + )); + } + } elseif (is_dir($path)) { + foreach (new \FilesystemIterator($path) as $item) { + assert($item instanceof \SplFileInfo); + static::delete($item->getPathname()); + } + + if (!@rmdir($path)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to delete directory '%s'. %s", + self::normalizePath($path), + Helpers::getLastError(), + )); + } + } + } + + + /** + * Renames or moves a file or a directory. Overwrites existing files and directories by default. + * @throws Nette\IOException on error occurred + * @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists + */ + public static function rename(string $origin, string $target, bool $overwrite = true): void + { + if (!$overwrite && file_exists($target)) { + throw new Nette\InvalidStateException(sprintf("File or directory '%s' already exists.", self::normalizePath($target))); + + } elseif (!file_exists($origin)) { + throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($origin))); + + } else { + static::createDir(dirname($target)); + if (realpath($origin) !== realpath($target)) { + static::delete($target); + } + + if (!@rename($origin, $target)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to rename file or directory '%s' to '%s'. %s", + self::normalizePath($origin), + self::normalizePath($target), + Helpers::getLastError(), + )); + } + } + } + + + /** + * Reads the content of a file. + * @throws Nette\IOException on error occurred + */ + public static function read(string $file): string + { + $content = @file_get_contents($file); // @ is escalated to exception + if ($content === false) { + throw new Nette\IOException(sprintf( + "Unable to read file '%s'. %s", + self::normalizePath($file), + Helpers::getLastError(), + )); + } + + return $content; + } + + + /** + * Reads the file content line by line. Because it reads continuously as we iterate over the lines, + * it is possible to read files larger than the available memory. + * @return \Generator<int, string> + * @throws Nette\IOException on error occurred + */ + public static function readLines(string $file, bool $stripNewLines = true): \Generator + { + return (function ($f) use ($file, $stripNewLines) { + $counter = 0; + do { + $line = Callback::invokeSafe('fgets', [$f], fn($error) => throw new Nette\IOException(sprintf( + "Unable to read file '%s'. %s", + self::normalizePath($file), + $error, + ))); + if ($line === false) { + fclose($f); + break; + } + if ($stripNewLines) { + $line = rtrim($line, "\r\n"); + } + + yield $counter++ => $line; + + } while (true); + })(static::open($file, 'r')); + } + + + /** + * Writes the string to a file. 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 write(string $file, string $content, ?int $mode = 0o666): void + { + static::createDir(dirname($file)); + if (@file_put_contents($file, $content) === false) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to write file '%s'. %s", + self::normalizePath($file), + Helpers::getLastError(), + )); + } + + if ($mode !== null && !@chmod($file, $mode)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to chmod file '%s' to mode %s. %s", + self::normalizePath($file), + decoct($mode), + Helpers::getLastError(), + )); + } + } + + + /** + * 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); // @ file may not exist + 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 + { + if (is_file($path)) { + if (!@chmod($path, $fileMode)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to chmod file '%s' to mode %s. %s", + self::normalizePath($path), + decoct($fileMode), + Helpers::getLastError(), + )); + } + } elseif (is_dir($path)) { + foreach (new \FilesystemIterator($path) as $item) { + assert($item instanceof \SplFileInfo); + static::makeWritable($item->getPathname(), $dirMode, $fileMode); + } + + if (!@chmod($path, $dirMode)) { // @ is escalated to exception + throw new Nette\IOException(sprintf( + "Unable to chmod directory '%s' to mode %s. %s", + self::normalizePath($path), + decoct($dirMode), + Helpers::getLastError(), + )); + } + } else { + throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($path))); + } + } + + + /** + * Determines if the path is absolute. + */ + public static function isAbsolute(string $path): bool + { + return (bool) preg_match('#([a-z]:)?[/\\\]|[a-z][a-z0-9+.-]*://#Ai', $path); + } + + + /** + * 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; a scheme like `phar://` is kept. + */ + public static function normalizePath(string $path): string + { + $scheme = preg_match('#^[a-z][a-z0-9+.-]*://#i', $path, $m) ? $m[0] : ''; + $path = substr($path, strlen($scheme)); + $parts = $path === '' ? [] : preg_split('~[/\\\]+~', $path); + $res = []; + foreach ($parts as $part) { + if ($part === '..' && $res && end($res) !== '..' && end($res) !== '') { + array_pop($res); + } elseif ($part !== '.') { + $res[] = $part; + } + } + + return $scheme . ($res === [''] + ? DIRECTORY_SEPARATOR + : implode(DIRECTORY_SEPARATOR, $res)); + } + + + /** + * Joins all segments of the path and normalizes the result. + */ + public static function joinPaths(string ...$paths): string + { + return self::normalizePath(implode('/', $paths)); + } + + + /** + * Resolves a path against a base path. If the path is absolute, returns it directly, if it's relative, joins it with the base path. + */ + public static function resolvePath(string $basePath, string $path): string + { + return match (true) { + self::isAbsolute($path) => self::platformSlashes($path), + $path === '' => self::platformSlashes($basePath), + default => self::joinPaths($basePath, $path), + }; + } + + + /** + * Converts backslashes to slashes. + */ + public static function unixSlashes(string $path): string + { + return strtr($path, '\\', '/'); + } + + + /** + * Converts slashes to platform-specific directory separators. + */ + public static function platformSlashes(string $path): string + { + return DIRECTORY_SEPARATOR === '/' + ? strtr($path, '\\', '/') + : str_replace(':\\\\', '://', strtr($path, '/', '\\')); // protocol:// + } +} diff --git a/vendor/nette/utils/src/Utils/Finder.php b/vendor/nette/utils/src/Utils/Finder.php new file mode 100644 index 0000000..cd1c564 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Finder.php @@ -0,0 +1,551 @@ +<?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 count, func_get_args, func_num_args, is_array, sprintf; +use const DIRECTORY_SEPARATOR, GLOB_NOESCAPE, GLOB_NOSORT, GLOB_ONLYDIR; + + +/** + * Searches for files and directories in directory trees. + * + * Finder::findFiles('*.php') + * ->size('> 10kB') + * ->from('.') + * ->exclude('temp'); + * + * @implements \IteratorAggregate<string, FileInfo> + */ +class Finder implements \IteratorAggregate +{ + /** @var array<array{string, string}> */ + private array $find = []; + + /** @var string[] */ + private array $in = []; + + /** @var array<\Closure(FileInfo): bool> */ + private array $filters = []; + + /** @var array<\Closure(FileInfo): bool> */ + private array $descentFilters = []; + + /** @var array<string|self> */ + private array $appends = []; + private bool $childFirst = false; + + /** @var ?(\Closure(FileInfo, FileInfo): int) */ + private ?\Closure $sort = null; + 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 + */ + 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'); + } + + + /** + * Begins search for files matching mask. The ** wildcard searches recursively. + * @param string|list<string> $masks + */ + public static function findFiles(string|array $masks = ['*']): static + { + $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic + return (new static)->addMask($masks, 'file'); + } + + + /** + * Begins search for directories matching mask. The ** wildcard searches recursively. + * @param string|list<string> $masks + */ + public static function findDirectories(string|array $masks = ['*']): static + { + $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic + return (new static)->addMask($masks, 'dir'); + } + + + /** + * Finds files matching the specified masks. + * @param string|list<string> $masks + */ + public function files(string|array $masks = ['*']): static + { + return $this->addMask((array) $masks, 'file'); + } + + + /** + * Finds directories matching the specified masks. + * @param string|list<string> $masks + */ + public function directories(string|array $masks = ['*']): static + { + return $this->addMask((array) $masks, 'dir'); + } + + + /** @param list<string> $masks */ + private function addMask(array $masks, string $mode): static + { + foreach ($masks as $mask) { + $orig = $mask; + if ($mode === 'dir') { + $mask = rtrim($mask, '/\\'); + } + if ($mask === '' || ($mode === 'file' && self::hasTrailingSeparator($mask))) { + throw new Nette\InvalidArgumentException("Invalid mask '$orig'"); + } + $this->find[] = [self::expandGlobStar($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 + */ + public function in(string|array $paths): static + { + $paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic + $this->addLocation($paths, ''); + return $this; + } + + + /** + * Searches recursively from the given directories. Wildcards * and ? are allowed; unlike in masks, [ and ] are taken literally. + * @param string|list<string> $paths + */ + public function from(string|array $paths): static + { + $paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic + $this->addLocation($paths, DIRECTORY_SEPARATOR . '**'); + 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, '/\\'); + $this->in[] = $path . $ext; + } + } + + + /** + * Lists directory's contents before the directory itself. By default, this is disabled. + */ + public function childFirst(bool $state = true): static + { + $this->childFirst = $state; + return $this; + } + + + /** + * Ignores unreadable directories. By default, this is enabled. + */ + public function ignoreUnreadableDirs(bool $state = true): static + { + $this->ignoreUnreadableDirs = $state; + return $this; + } + + + /** + * Sets a comparison function for sorting entries within each directory. + * @param callable(FileInfo, FileInfo): int $callback + */ + public function sortBy(callable $callback): static + { + $this->sort = $callback(...); + return $this; + } + + + /** + * Sorts files in each directory naturally by name. + */ + public function sortByName(): static + { + $this->sort = fn(FileInfo $a, FileInfo $b): int => strnatcmp($a->getBasename(), $b->getBasename()); + return $this; + } + + + /** + * 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 + */ + public function append(string|array|null $paths = null): static + { + if ($paths === null) { + return $this->appends[] = new static; + } + + $this->appends = [...$this->appends, ...(array) $paths]; + return $this; + } + + + /********************* filtering ****************d*g**/ + + + /** + * 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 + */ + 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'"); + } + $end = $m[3]; + $re = $this->buildPattern(self::expandGlobStar($m[2])); + $filter = fn(FileInfo $file): bool => ($end && !$file->isDir()) + || !preg_match($re, FileSystem::unixSlashes($file->getRelativePathname())); + + $this->descentFilter($filter); + if ($end === '' || $end === '/') { + $this->filter($filter); + } + } + + return $this; + } + + + /** + * Yields only entries which satisfy the given filter. + * @param callable(FileInfo): bool $callback + */ + public function filter(callable $callback): static + { + $this->filters[] = $callback(...); + return $this; + } + + + /** + * It descends only to directories that match the specified filter. + * @param callable(FileInfo): bool $callback + */ + public function descentFilter(callable $callback): static + { + $this->descentFilters[] = $callback(...); + return $this; + } + + + /** + * Sets the maximum depth of entries. + */ + public function limitDepth(?int $depth): static + { + $this->maxDepth = $depth ?? -1; + return $this; + } + + + /** + * 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 + { + if (func_num_args() === 1) { // in $operator is predicate + if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?((?:\d*\.)?\d+)\s*(K|M|G|)B?$#Di', $operator, $matches)) { + throw new Nette\InvalidArgumentException('Invalid size predicate format.'); + } + + [, $operator, $size, $unit] = $matches; + $units = ['' => 1, 'k' => 1e3, 'm' => 1e6, 'g' => 1e9]; + $size = (float) $size * $units[strtolower($unit)]; + $operator = $operator ?: '='; + } + + return $this->filter(fn(FileInfo $file): bool => !$file->isFile() || Helpers::compare($file->getSize(), $operator, $size)); + } + + + /** + * 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 + { + if (func_num_args() === 1) { // in $operator is predicate + if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?(.+)$#Di', $operator, $matches)) { + throw new Nette\InvalidArgumentException('Invalid date predicate format.'); + } + + [, $operator, $date] = $matches; + $operator = $operator ?: '='; + } + + $date = DateTime::from($date)->getTimestamp(); + return $this->filter(fn(FileInfo $file): bool => !$file->isFile() || Helpers::compare($file->getMTime(), $operator, $date)); + } + + + /********************* iterator generator ****************d*g**/ + + + /** + * Returns an array with all found files and directories. + * @return list<FileInfo> + */ + public function collect(): array + { + return iterator_to_array($this->getIterator(), preserve_keys: false); + } + + + /** @return \Generator<string, FileInfo> */ + public function getIterator(): \Generator + { + $plan = $this->buildPlan(); + foreach ($plan as $dir => $searches) { + yield from $this->traverseDir($dir, $searches); + } + + foreach ($this->appends as $item) { + if ($item instanceof self) { + yield from $item->getIterator(); + } else { + yield $item => new FileInfo($item); + } + } + } + + + /** + * @param array<object{pattern: string, mode: string, recursive: bool}> $searches + * @param string[] $subdirs + * @return \Generator<string, FileInfo> + */ + private function traverseDir(string $dir, array $searches, array $subdirs = []): \Generator + { + if ($this->maxDepth >= 0 && count($subdirs) > $this->maxDepth) { + return; + } elseif (!is_dir($dir)) { + throw new Nette\InvalidStateException(sprintf("Directory '%s' does not exist.", rtrim($dir, '/\\'))); + } + + try { + $pathNames = new \FilesystemIterator( + $dir, + \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_PATHNAME, + ); + } catch (\UnexpectedValueException $e) { + if ($this->ignoreUnreadableDirs) { + return; + } else { + throw new Nette\InvalidStateException($e->getMessage()); + } + } + + $files = $this->convertToFiles($pathNames, implode(DIRECTORY_SEPARATOR, $subdirs), FileSystem::isAbsolute($dir)); + + if ($this->sort) { + $files = iterator_to_array($files); + usort($files, $this->sort); + } + + foreach ($files as $file) { + $pathName = $file->getPathname(); + $cache = $subSearch = []; + + if ($file->isDir()) { + foreach ($searches as $search) { + if ($search->recursive && $this->proveFilters($this->descentFilters, $file, $cache)) { + $subSearch[] = $search; + } + } + } + + if ($this->childFirst && $subSearch) { + yield from $this->traverseDir($pathName, $subSearch, [...$subdirs, $file->getBasename()]); + } + + $relativePathname = FileSystem::unixSlashes($file->getRelativePathname()); + foreach ($searches as $search) { + if ( + "is_$search->mode"(Helpers::IsWindows && $file->isLink() ? $file->getLinkTarget() : $file->getPathname()) + && preg_match($search->pattern, $relativePathname) + && $this->proveFilters($this->filters, $file, $cache) + ) { + yield $pathName => $file; + break; + } + } + + if (!$this->childFirst && $subSearch) { + yield from $this->traverseDir($pathName, $subSearch, [...$subdirs, $file->getBasename()]); + } + } + } + + + /** @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); + } + 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) { + $res = &$cache[spl_object_id($filter)]; + $res ??= $filter($file); + if (!$res) { + return false; + } + } + + return true; + } + + + /** @return array<string, array<object{pattern: string, mode: string, recursive: bool}>> */ + private function buildPlan(): array + { + $plan = $dirCache = []; + foreach ($this->find as [$mask, $mode]) { + $splits = []; + if (FileSystem::isAbsolute($mask)) { + if ($this->in) { + throw new Nette\InvalidStateException("You cannot combine the absolute path in the mask '$mask' and the directory to search '{$this->in[0]}'."); + } + $splits[] = self::splitRecursivePart($mask); + } 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); + } + } + + foreach ($splits as [$base, $rest, $recursive]) { + $base = $base === '' ? '.' : $base; + $dirs = $dirCache[$base] ??= strpbrk($base, '*?[') + ? glob($base, GLOB_NOSORT | GLOB_ONLYDIR | GLOB_NOESCAPE) + : [strtr($base, ['[[]' => '[', '[]]' => ']'])]; // unescape [ and ] + + if (!$dirs) { + throw new Nette\InvalidStateException(sprintf("Directory '%s' does not exist.", rtrim($base, '/\\'))); + } + + $search = (object) ['pattern' => $this->buildPattern($rest), 'mode' => $mode, 'recursive' => $recursive]; + foreach ($dirs as $dir) { + $plan[$dir][] = $search; + } + } + } + + return $plan; + } + + + /** + * 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); + return isset($parts[1]) + ? [$parts[0], $parts[1] . $file, true] + : [$parts[0], $file, false]; + } + + + /** + * Converts wildcards to regular expression. + */ + private function buildPattern(string $mask): string + { + $mask = FileSystem::unixSlashes($mask); + if ($mask === '*') { + return '##'; + } elseif (str_starts_with($mask, './')) { + $anchor = '^'; + $mask = substr($mask, 2); + } else { + $anchor = '(?:^|/)'; + } + + $pattern = strtr( + preg_quote($mask, '#'), + [ + '\*\*/' => '(.+/)?', + '\*' => '[^/]*', + '\?' => '[^/]', + '\[\!' => '[^', + '\[' => '[', + '\]' => ']', + '\-' => '-', + ], + ); + return '#' . $anchor . $pattern . '$#D' . (Helpers::IsWindows ? 'i' : ''); + } +} diff --git a/vendor/nette/utils/src/Utils/Floats.php b/vendor/nette/utils/src/Utils/Floats.php new file mode 100644 index 0000000..4c8fbe2 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Floats.php @@ -0,0 +1,105 @@ +<?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; + + +/** + * Floating-point numbers comparison. + */ +class Floats +{ + use Nette\StaticClass; + + private const Epsilon = 1e-10; + + + public static function isZero(float $value): bool + { + return abs($value) < self::Epsilon; + } + + + public static function isInteger(float $value): bool + { + return abs(round($value) - $value) < self::Epsilon; + } + + + /** + * Compare two floats. If $a < $b it returns -1, if they are equal it returns 0 and if $a > $b it returns 1 + * @throws \LogicException if one of parameters is NAN + */ + public static function compare(float $a, float $b): int + { + if (is_nan($a) || is_nan($b)) { + throw new \LogicException('Trying to compare NAN'); + + } elseif (!is_finite($a) && !is_finite($b) && $a === $b) { + return 0; + } + + $diff = abs($a - $b); + if (($diff < self::Epsilon || ($diff / max(abs($a), abs($b)) < self::Epsilon))) { + return 0; + } + + return $a < $b ? -1 : 1; + } + + + /** + * Returns true if $a = $b + * @throws \LogicException if one of parameters is NAN + */ + public static function areEqual(float $a, float $b): bool + { + return self::compare($a, $b) === 0; + } + + + /** + * Returns true if $a < $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isLessThan(float $a, float $b): bool + { + return self::compare($a, $b) < 0; + } + + + /** + * Returns true if $a <= $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isLessThanOrEqualTo(float $a, float $b): bool + { + return self::compare($a, $b) <= 0; + } + + + /** + * Returns true if $a > $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isGreaterThan(float $a, float $b): bool + { + return self::compare($a, $b) > 0; + } + + + /** + * Returns true if $a >= $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isGreaterThanOrEqualTo(float $a, float $b): bool + { + return self::compare($a, $b) >= 0; + } +} diff --git a/vendor/nette/utils/src/Utils/Helpers.php b/vendor/nette/utils/src/Utils/Helpers.php new file mode 100644 index 0000000..95d51b9 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Helpers.php @@ -0,0 +1,125 @@ +<?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 ini_get, strlen; +use const PHP_OS_FAMILY; + + +/** + * Miscellaneous utilities. + */ +class Helpers +{ + public const IsWindows = PHP_OS_FAMILY === 'Windows'; + + + /** + * Executes a callback and returns the captured output as a string. + * @param callable(): void $func + */ + public static function capture(callable $func): string + { + ob_start(fn() => ''); + try { + $func(); + return ob_get_clean(); + } catch (\Throwable $e) { + ob_end_clean(); + throw $e; + } + } + + + /** + * 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. + */ + public static function getLastError(): string + { + $message = error_get_last()['message'] ?? ''; + $message = ini_get('html_errors') ? Html::htmlToText($message) : $message; + $message = preg_replace('#^\w+\(.*?\): #', '', $message); + return $message; + } + + + /** + * Converts false to null, does not change other values. + */ + public static function falseToNull(mixed $value): mixed + { + return $value === false ? null : $value; + } + + + /** + * 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 + { + if ($min > $max) { + throw new Nette\InvalidArgumentException("Minimum ($min) is not less than maximum ($max)."); + } + + return min(max($value, $min), $max); + } + + + /** + * Finds the string from $possibilities most similar to $value using Levenshtein distance, or null if none is close enough. + * @param string[] $possibilities + */ + public static function getSuggestion(array $possibilities, string $value): ?string + { + $best = null; + $min = (strlen($value) / 4 + 1) * 10 + .1; + foreach (array_unique($possibilities) as $item) { + if ($item !== $value && ($len = levenshtein($item, $value, 10, 11, 10)) < $min) { + $min = $len; + $best = $item; + } + } + + return $best; + } + + + /** + * 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 + { + return match ($operator) { + '>' => $left > $right, + '>=' => $left >= $right, + '<' => $left < $right, + '<=' => $left <= $right, + '=', '==' => $left == $right, // intentionally == + '===' => $left === $right, + '!=', '<>' => $left != $right, // intentionally != + '!==' => $left !== $right, + default => throw new Nette\InvalidArgumentException("Unknown operator '$operator'"), + }; + } + + + /** + * Splits a class name into namespace and short class name. + * @return array{string, string} + */ + public static function splitClassName(string $name): array + { + return ($pos = strrpos($name, '\\')) === false + ? ['', $name] + : [substr($name, 0, $pos), substr($name, $pos + 1)]; + } +} diff --git a/vendor/nette/utils/src/Utils/Html.php b/vendor/nette/utils/src/Utils/Html.php new file mode 100644 index 0000000..1d3fdeb --- /dev/null +++ b/vendor/nette/utils/src/Utils/Html.php @@ -0,0 +1,892 @@ +<?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\HtmlStringable; +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. + * + * @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 + * + * @method self accept(?string $val) + * @method self accesskey(?string $val, bool $state = null) + * @method self action(?string $val) + * @method self align(?string $val) + * @method self allow(?string $val, bool $state = null) + * @method self alt(?string $val) + * @method self async(?bool $val) + * @method self autocapitalize(?string $val) + * @method self autocomplete(?string $val) + * @method self autofocus(?bool $val) + * @method self autoplay(?bool $val) + * @method self charset(?string $val) + * @method self checked(?bool $val) + * @method self cite(?string $val) + * @method self class(?string $val, bool $state = null) + * @method self cols(?int $val) + * @method self colspan(?int $val) + * @method self content(?string $val) + * @method self contenteditable(?bool $val) + * @method self controls(?bool $val) + * @method self coords(?string $val) + * @method self crossorigin(?string $val) + * @method self datetime(?string $val) + * @method self decoding(?string $val) + * @method self default(?bool $val) + * @method self defer(?bool $val) + * @method self dir(?string $val) + * @method self dirname(?string $val) + * @method self disabled(?bool $val) + * @method self download(?bool $val) + * @method self draggable(?string $val) + * @method self dropzone(?string $val) + * @method self enctype(?string $val) + * @method self for(?string $val) + * @method self form(?string $val) + * @method self formaction(?string $val) + * @method self formenctype(?string $val) + * @method self formmethod(?string $val) + * @method self formnovalidate(?bool $val) + * @method self formtarget(?string $val) + * @method self headers(?string $val, bool $state = null) + * @method self height(?int $val) + * @method self hidden(?bool $val) + * @method self high(?float $val) + * @method self hreflang(?string $val) + * @method self id(?string $val) + * @method self integrity(?string $val) + * @method self inputmode(?string $val) + * @method self ismap(?bool $val) + * @method self itemprop(?string $val) + * @method self kind(?string $val) + * @method self label(?string $val) + * @method self lang(?string $val) + * @method self list(?string $val) + * @method self loop(?bool $val) + * @method self low(?float $val) + * @method self max(?float $val) + * @method self maxlength(?int $val) + * @method self minlength(?int $val) + * @method self media(?string $val) + * @method self method(?string $val) + * @method self min(?float $val) + * @method self multiple(?bool $val) + * @method self muted(?bool $val) + * @method self name(?string $val) + * @method self novalidate(?bool $val) + * @method self open(?bool $val) + * @method self optimum(?float $val) + * @method self pattern(?string $val) + * @method self ping(?string $val, bool $state = null) + * @method self placeholder(?string $val) + * @method self poster(?string $val) + * @method self preload(?string $val) + * @method self radiogroup(?string $val) + * @method self readonly(?bool $val) + * @method self rel(?string $val) + * @method self required(?bool $val) + * @method self reversed(?bool $val) + * @method self rows(?int $val) + * @method self rowspan(?int $val) + * @method self sandbox(?string $val, bool $state = null) + * @method self scope(?string $val) + * @method self selected(?bool $val) + * @method self shape(?string $val) + * @method self size(?int $val) + * @method self sizes(?string $val) + * @method self slot(?string $val) + * @method self span(?int $val) + * @method self spellcheck(?string $val) + * @method self src(?string $val) + * @method self srcdoc(?string $val) + * @method self srclang(?string $val) + * @method self srcset(?string $val) + * @method self start(?int $val) + * @method self step(?float $val) + * @method self style(?string $property, string $val = null) + * @method self tabindex(?int $val) + * @method self target(?string $val) + * @method self title(?string $val) + * @method self translate(?string $val) + * @method self type(?string $val) + * @method self usemap(?string $val) + * @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 = []; + + /** @var array<string, int> void elements */ + public static array $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 = []; + + /** element's name */ + private string $name = ''; + + private bool $isEmpty = false; + + + /** + * Constructs new HTML element. + * @param array<string, mixed>|string|null $attrs element's attributes or plain text content + */ + public static function el(?string $name = null, array|string|null $attrs = null): static + { + $el = new static; + $parts = explode(' ', (string) $name, 2); + $el->setName($parts[0]); + + if (is_array($attrs)) { + $el->attrs = $attrs; + + } elseif ($attrs !== null) { + $el->setText($attrs); + } + + if (isset($parts[1])) { + foreach (Strings::matchAll($parts[1] . ' ', '#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\2|\s))?#i') as $m) { + $el->attrs[$m[1]] = $m[3] ?? true; + } + } + + return $el; + } + + + /** + * 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 + { + return (new static)->setHtml($html); + } + + + /** + * Returns an object representing plain text. + * @deprecated use Html::text() + */ + public static function fromText(string $text): static + { + return (new static)->setText($text); + } + + + /** + * Converts to HTML. + */ + final public function toHtml(): string + { + return $this->render(); + } + + + /** + * Converts to plain text. + */ + final public function toText(): string + { + return $this->getText(); + } + + + /** + * Converts given HTML code to plain text. + */ + public static function htmlToText(string $html): string + { + return html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'); + } + + + /** + * Changes element's name. + */ + final public function setName(string $name, ?bool $isEmpty = null): static + { + $this->name = $name; + $this->isEmpty = $isEmpty ?? isset(static::$emptyElements[$name]); + return $this; + } + + + /** + * Returns element's name. + */ + final public function getName(): string + { + return $this->name; + } + + + /** + * Checks whether the element is a void (self-closing) element. + */ + final public function isEmpty(): bool + { + return $this->isEmpty; + } + + + /** + * Sets multiple attributes. + * @param array<string, mixed> $attrs + */ + public function addAttributes(array $attrs): static + { + $this->attrs = [...$this->attrs, ...$attrs]; + return $this; + } + + + /** + * Appends value to element's attribute. + */ + public function appendAttribute(string $name, mixed $value, mixed $option = true): static + { + if (is_array($value)) { + $prev = isset($this->attrs[$name]) ? (array) $this->attrs[$name] : []; + $this->attrs[$name] = $value + $prev; + + } elseif ((string) $value === '') { + $tmp = &$this->attrs[$name]; // appending empty value? -> ignore, but ensure it exists + + } elseif (!isset($this->attrs[$name]) || is_array($this->attrs[$name])) { // needs array + $this->attrs[$name][$value] = $option; + + } else { + $this->attrs[$name] = [$this->attrs[$name] => true, $value => $option]; + } + + return $this; + } + + + /** + * Sets element's attribute. + */ + public function setAttribute(string $name, mixed $value): static + { + $this->attrs[$name] = $value; + return $this; + } + + + /** + * Returns element's attribute. + */ + public function getAttribute(string $name): mixed + { + return $this->attrs[$name] ?? null; + } + + + /** + * Unsets element's attribute. + */ + public function removeAttribute(string $name): static + { + unset($this->attrs[$name]); + return $this; + } + + + /** + * Unsets element's attributes. + * @param list<string> $attributes + */ + public function removeAttributes(array $attributes): static + { + foreach ($attributes as $name) { + unset($this->attrs[$name]); + } + + return $this; + } + + + /** + * Sets element's attribute via property assignment. + */ + final public function __set(string $name, mixed $value): void + { + $this->attrs[$name] = $value; + } + + + /** + * Returns element's attribute via property access. + */ + final public function &__get(string $name): mixed + { + return $this->attrs[$name]; + } + + + /** + * Checks if element's attribute is set. + */ + final public function __isset(string $name): bool + { + return isset($this->attrs[$name]); + } + + + /** + * Unsets element's attribute via property unset. + */ + final public function __unset(string $name): void + { + unset($this->attrs[$name]); + } + + + /** + * Sets or returns element's attribute via method call. + * @param mixed[] $args + */ + 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); + $m[0] = $m[0] | "\x20"; + if ($p === 'get') { + return $this->attrs[$m] ?? null; + + } elseif ($p === 'add') { + $args[] = true; + } + } + + if (count($args) === 0) { // invalid + + } elseif (count($args) === 1) { // set + $this->attrs[$m] = $args[0]; + + } else { // add + $this->appendAttribute($m, $args[0], $args[1]); + } + + return $this; + } + + + /** + * 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 + { + if ($query) { + $query = http_build_query($query, '', '&'); + if ($query !== '') { + $path .= '?' . $query; + } + } + + $this->attrs['href'] = $path; + return $this; + } + + + /** + * Setter for data-* attributes. Booleans are converted to 'true' resp. 'false'. + */ + public function data(string $name, mixed $value = null): static + { + if (func_num_args() === 1) { + $this->attrs['data'] = $name; + } else { + $this->attrs["data-$name"] = is_bool($value) + ? json_encode($value) + : $value; + } + + return $this; + } + + + /** + * Sets element's HTML content. + */ + final public function setHtml(mixed $html): static + { + $this->children = [(string) $html]; + return $this; + } + + + /** + * Returns element's HTML content. + */ + final public function getHtml(): string + { + return implode('', $this->children); + } + + + /** + * Sets element's textual content. + */ + final public function setText(mixed $text): static + { + if (!$text instanceof HtmlStringable) { + $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8'); + } + + $this->children = [(string) $text]; + return $this; + } + + + /** + * Returns element's textual content. + */ + final public function getText(): string + { + return self::htmlToText($this->getHtml()); + } + + + /** + * 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 + { + return $this->insert(null, $child); + } + + + /** + * Appends plain-text string to element content. + */ + public function addText(\Stringable|string|int|null $text): static + { + if (!$text instanceof HtmlStringable) { + $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8'); + } + + return $this->insert(null, $text); + } + + + /** + * 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 + { + $this->insert(null, $child = static::el($name, $attrs)); + return $child; + } + + + /** + * Inserts child node. + */ + public function insert(?int $index, HtmlStringable|string $child, bool $replace = false): static + { + $child = $child instanceof self ? $child : (string) $child; + if ($index === null) { // append + $this->children[] = $child; + + } else { // insert or replace + array_splice($this->children, $index, $replace ? 1 : 0, [$child]); + } + + return $this; + } + + + /** + * Inserts (replaces) child node (\ArrayAccess implementation). + * @param ?int $index position or null for appending + * @param Html|string $child Html node or raw HTML string + */ + final public function offsetSet($index, $child): void + { + $this->insert($index, $child, replace: true); + } + + + /** + * Returns child node (\ArrayAccess implementation). + * @param int $index + */ + final public function offsetGet($index): self|string + { + return $this->children[$index]; + } + + + /** + * Exists child node? (\ArrayAccess implementation). + * @param int $index + */ + final public function offsetExists($index): bool + { + return isset($this->children[$index]); + } + + + /** + * Removes child node (\ArrayAccess implementation). + * @param int $index + */ + public function offsetUnset($index): void + { + if (isset($this->children[$index])) { + array_splice($this->children, $index, 1); + } + } + + + /** + * Returns children count. + */ + final public function count(): int + { + return count($this->children); + } + + + /** + * Removes all children. + */ + public function removeChildren(): void + { + $this->children = []; + } + + + /** + * Iterates over elements. + * @return \ArrayIterator<int, self|string> + */ + final public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->children); + } + + + /** + * Returns all children. + * @return array<int, self|string> + */ + final public function getChildren(): array + { + return $this->children; + } + + + /** + * Renders element's start tag, content and end tag. Pass indent level to enable pretty-printing. + */ + final public function render(?int $indent = null): string + { + $s = $this->startTag(); + + if (!$this->isEmpty) { + // add content + if ($indent !== null) { + $indent++; + } + + foreach ($this->children as $child) { + if ($child instanceof self) { + $s .= $child->render($indent); + } else { + $s .= $child; + } + } + + // add end tag + $s .= $this->endTag(); + } + + if ($indent !== null) { + return "\n" . str_repeat("\t", $indent - 1) . $s . "\n" . str_repeat("\t", max(0, $indent - 2)); + } + + return $s; + } + + + final public function __toString(): string + { + return $this->render(); + } + + + /** + * Returns element's start tag. + */ + final public function startTag(): string + { + return $this->name + ? '<' . $this->name . $this->attributes() . '>' + : ''; + } + + + /** + * Returns element's end tag. + */ + final public function endTag(): string + { + return $this->name && !$this->isEmpty ? '</' . $this->name . '>' : ''; + } + + + /** + * Returns element's attributes. + * @internal + */ + final public function attributes(): string + { + $s = ''; + $attrs = $this->attrs; + foreach ($attrs as $key => $value) { + if ($value === null || $value === false) { + continue; + + } elseif ($value === true) { + $s .= ' ' . $key; + + continue; + + } elseif (is_array($value)) { + if (str_starts_with($key, 'data-')) { + $value = Json::encode($value); + + } else { + $tmp = null; + foreach ($value as $k => $v) { + if ($v != null) { // intentionally ==, skip nulls & empty string + // composite 'style' vs. 'others' + $tmp[] = $v === true + ? $k + : (is_string($k) ? $k . ':' . $v : $v); + } + } + + if ($tmp === null) { + continue; + } + + $value = implode($key === 'style' || !strncmp($key, 'on', 2) ? ';' : ' ', $tmp); + } + } elseif (is_float($value)) { + $value = rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.'); + + } else { + $value = (string) $value; + } + + $q = str_contains($value, '"') ? "'" : '"'; + $s .= ' ' . $key . '=' . $q + . str_replace( + ['&', $q], + ['&', $q === '"' ? '"' : '''], + $value, + ) + . (str_contains($value, '`') && strpbrk($value, ' <>"\'') === false ? ' ' : '') + . $q; + } + + $s = str_replace('@', '@', $s); + return $s; + } + + + /** + * Clones all children too. + */ + public function __clone() + { + foreach ($this->children as $key => $value) { + if (is_object($value)) { + $this->children[$key] = clone $value; + } + } + } +} diff --git a/vendor/nette/utils/src/Utils/Image.php b/vendor/nette/utils/src/Utils/Image.php new file mode 100644 index 0000000..82d4d6e --- /dev/null +++ b/vendor/nette/utils/src/Utils/Image.php @@ -0,0 +1,855 @@ +<?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 extension_loaded, is_array, is_int, is_string; + + +/** + * Basic manipulation with images. Supported types are JPEG, PNG, GIF, WEBP, AVIF and BMP. + * + * <code> + * $image = Image::fromFile('nette.jpg'); + * $image->resize(150, 100); + * $image->sharpen(); + * $image->send(); + * </code> + * + * @method Image affine(array<int, float|int> $affine, ?array{x: int, y: int, width: int, height: int} $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) + * @method int colorAllocate(int $red, int $green, int $blue) + * @method int colorAllocateAlpha(int $red, int $green, int $blue, int $alpha) + * @method int colorAt(int $x, int $y) + * @method int colorClosest(int $red, int $green, int $blue) + * @method int colorClosestAlpha(int $red, int $green, int $blue, int $alpha) + * @method int colorClosestHWB(int $red, int $green, int $blue) + * @method void colorDeallocate(int $color) + * @method int colorExact(int $red, int $green, int $blue) + * @method int colorExactAlpha(int $red, int $green, int $blue, int $alpha) + * @method void colorMatch(Image $image2) + * @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 int colorsTotal() + * @method int colorTransparent(?int $color = null) + * @method void convolution(array<int, array<int, float>> $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 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 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 void gammaCorrect(float $inputgamma, float $outputgamma) + * @method array{int, int, int, int} 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 paletteCopy(Image $source) + * @method void paletteToTrueColor() + * @method void polygon(array<int, int> $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 void setBrush(Image $brush) + * @method void setClip(int $x1, int $y1, int $x2, int $y2) + * @method void setInterpolation(int $method = 3) + * @method void setPixel(int $x, int $y, ImageColor $color) + * @method void setStyle(array<int, int> $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 = []) + * @property-read positive-int $width + * @property-read positive-int $height + * @property-read \GdImage $imageResource + */ +class Image +{ + use Nette\SmartObject; + + /** Prevent from getting resized to a bigger size than the original */ + public const ShrinkOnly = 0b0001; + + /** Resizes to a specified width and height without keeping aspect ratio */ + public const Stretch = 0b0010; + + /** Resizes to fit into a specified width and height and preserves aspect ratio */ + public const OrSmaller = 0b0000; + + /** Resizes while bounding the smaller dimension to the specified width or height and preserves aspect ratio */ + public const OrBigger = 0b0100; + + /** Resizes to the smallest possible size to completely cover specified width and height and reserves aspect ratio */ + public const Cover = 0b1000; + + /** @deprecated use Image::ShrinkOnly */ + public const SHRINK_ONLY = self::ShrinkOnly; + + /** @deprecated use Image::Stretch */ + public const STRETCH = self::Stretch; + + /** @deprecated use Image::OrSmaller */ + public const FIT = self::OrSmaller; + + /** @deprecated use Image::OrBigger */ + public const FILL = self::OrBigger; + + /** @deprecated use Image::Cover */ + public const EXACT = self::Cover; + + /** @deprecated use Image::EmptyGIF */ + public const EMPTY_GIF = self::EmptyGIF; + + /** image types */ + public const + JPEG = ImageType::JPEG, + PNG = ImageType::PNG, + GIF = ImageType::GIF, + WEBP = ImageType::WEBP, + AVIF = ImageType::AVIF, + BMP = ImageType::BMP; + + 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 \GdImage $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 + { + return [ + 'red' => max(0, min(255, $red)), + 'green' => max(0, min(255, $green)), + 'blue' => max(0, min(255, $blue)), + 'alpha' => max(0, min(127, $transparency)), + ]; + } + + + /** + * 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 + * @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 + { + self::ensureExtension(); + $type = self::detectTypeFromFile($file); + if (!$type) { + 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); + } + + + /** + * 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 + * @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 + { + self::ensureExtension(); + $type = self::detectTypeFromString($s); + if (!$type) { + throw new UnknownImageFileException('Unknown type of image.'); + } + + return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__, $warnings); + } + + + /** @param callable-string $func */ + private static function invokeSafe( + string $func, + string $arg, + string $message, + string $callee, + ?string &$warnings = self::Sentinel, + ): 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); + } + + return new static($res); + } + + + /** + * 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 + { + self::ensureExtension(); + if ($width < 1 || $height < 1) { + throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.'); + } + + $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); + } + + return $image; + } + + + /** + * Returns the type of image from file. + * @param-out ?int $width + * @param-out ?int $height + * @return ?ImageType::* + */ + public static function detectTypeFromFile(string $file, mixed &$width = null, mixed &$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; + } + + + /** + * Returns the type of image from string. + * @param-out ?int $width + * @param-out ?int $height + * @return ?ImageType::* + */ + public static function detectTypeFromString(string $s, mixed &$width = null, mixed &$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; + } + + + /** + * Returns the file extension for the given image type. + * @param ImageType::* $type + * @return value-of<self::Formats> + */ + public static function typeToExtension(int $type): string + { + if (!isset(self::Formats[$type])) { + throw new Nette\InvalidArgumentException("Unsupported image type '$type'."); + } + + return self::Formats[$type]; + } + + + /** + * Returns the image type for given file extension. + * @return ImageType::* + */ + public static function extensionToType(string $extension): int + { + $extensions = array_flip(self::Formats) + ['jpg' => ImageType::JPEG]; + $extension = strtolower($extension); + if (!isset($extensions[$extension])) { + throw new Nette\InvalidArgumentException("Unsupported file extension '$extension'."); + } + + return $extensions[$extension]; + } + + + /** + * Returns the mime type for the given image type. + * @param ImageType::* $type + */ + public static function typeToMimeType(int $type): string + { + return 'image/' . self::typeToExtension($type); + } + + + /** + * Checks whether the given image type is supported by the GD extension. + * @param ImageType::* $type + */ + public static function isTypeSupported(int $type): bool + { + self::ensureExtension(); + return (bool) (imagetypes() & match ($type) { + ImageType::JPEG => IMG_JPG, + ImageType::PNG => IMG_PNG, + ImageType::GIF => IMG_GIF, + ImageType::WEBP => IMG_WEBP, + ImageType::AVIF => IMG_AVIF, + ImageType::BMP => IMG_BMP, + default => 0, + }); + } + + + /** + * Returns list of image types supported by the GD extension. + * @return ImageType::*[] + */ + public static function getSupportedTypes(): array + { + self::ensureExtension(); + $flag = imagetypes(); + return array_filter([ + $flag & IMG_GIF ? ImageType::GIF : null, + $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 & IMG_BMP ? ImageType::BMP : null, + ]); + } + + + /** + * Wraps GD image. + */ + public function __construct(\GdImage $image) + { + $this->setImageResource($image); + imagesavealpha($image, true); + } + + + /** + * Returns image width. + * @return positive-int + */ + public function getWidth(): int + { + return imagesx($this->image); + } + + + /** + * Returns image height. + * @return positive-int + */ + public function getHeight(): int + { + return imagesy($this->image); + } + + + /** + * Sets image resource. + */ + protected function setImageResource(\GdImage $image): static + { + $this->image = $image; + return $this; + } + + + /** + * Returns image GD resource. + */ + public function getImageResource(): \GdImage + { + return $this->image; + } + + + /** + * Scales an image. Width and height accept pixels or percent. + * @param int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly> $mode + */ + 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); + } + + [$newWidth, $newHeight] = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $mode); + + if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize + $newImage = static::fromBlank($newWidth, $newHeight, ImageColor::rgb(0, 0, 0, 0))->getImageResource(); + imagecopyresampled( + $newImage, + $this->image, + 0, + 0, + 0, + 0, + $newWidth, + $newHeight, + $this->getWidth(), + $this->getHeight(), + ); + $this->image = $newImage; + } + + if ($width < 0 || $height < 0) { + imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL); + } + + return $this; + } + + + /** + * 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, + int $mode = self::OrSmaller, + ): array + { + if ($newWidth === null) { + } elseif (self::isPercent($newWidth)) { + $newWidth = (int) round($srcWidth / 100 * abs($newWidth)); + $percents = true; + } else { + $newWidth = abs($newWidth); + } + + if ($newHeight === null) { + } elseif (self::isPercent($newHeight)) { + $newHeight = (int) round($srcHeight / 100 * abs($newHeight)); + $mode |= empty($percents) ? 0 : self::Stretch; + } else { + $newHeight = abs($newHeight); + } + + if ($mode & self::Stretch) { // non-proportional + if (!$newWidth || !$newHeight) { + throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.'); + } + + if ($mode & self::ShrinkOnly) { + $newWidth = min($srcWidth, $newWidth); + $newHeight = min($srcHeight, $newHeight); + } + } else { // proportional + if (!$newWidth && !$newHeight) { + throw new Nette\InvalidArgumentException('At least width or height must be specified.'); + } + + $scale = []; + if ($newWidth > 0) { // fit width + $scale[] = $newWidth / $srcWidth; + } + + if ($newHeight > 0) { // fit height + $scale[] = $newHeight / $srcHeight; + } + + if ($mode & self::OrBigger) { + $scale = [max($scale ?: [1])]; + } + + if ($mode & self::ShrinkOnly) { + $scale[] = 1; + } + + $scale = min($scale ?: [1]); + $newWidth = (int) round($srcWidth * $scale); + $newHeight = (int) round($srcHeight * $scale); + } + + return [max((int) $newWidth, 1), max((int) $newHeight, 1)]; + } + + + /** + * Crops image. Arguments accepts pixels or percent. + */ + public function crop(int|string $left, int|string $top, int|string $width, int|string $height): static + { + [$r['x'], $r['y'], $r['width'], $r['height']] + = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height); + if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') { + $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(); + imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']); + $this->image = $newImage; + } + + return $this; + } + + + /** + * Calculates dimensions of cutout in image. Arguments accepts pixels or percent. + * @return array{int, int, int, int} + */ + public static function calculateCutout( + int $srcWidth, + int $srcHeight, + int|string $left, + int|string $top, + int|string $newWidth, + 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 ($left < 0) { + $newWidth += $left; + $left = 0; + } + + if ($top < 0) { + $newHeight += $top; + $top = 0; + } + + $newWidth = min($newWidth, $srcWidth - $left); + $newHeight = min($newHeight, $srcHeight - $top); + return [$left, $top, $newWidth, $newHeight]; + } + + + /** + * Sharpens image a little bit. + */ + public function sharpen(): static + { + imageconvolution($this->image, [ // my magic numbers ;) + [-1, -1, -1], + [-1, 24, -1], + [-1, -1, -1], + ], 16, 0); + return $this; + } + + + /** + * Puts another image into this image. Left and top accepts pixels or percent. + * @param int<0, 100> $opacity 0..100 + */ + public function place(self $image, int|string $left = 0, int|string $top = 0, int $opacity = 100): static + { + $opacity = max(0, min(100, $opacity)); + if ($opacity === 0) { + return $this; + } + + $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); + + $output = $input = $image->image; + if ($opacity < 100) { + $tbl = []; + for ($i = 0; $i < 128; $i++) { + $tbl[$i] = round(127 - (127 - $i) * $opacity / 100); + } + + $output = imagecreatetruecolor($width, $height); + imagealphablending($output, false); + if (!$image->isTrueColor()) { + $input = $output; + imagefilledrectangle($output, 0, 0, $width, $height, (int) 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 = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24); + imagesetpixel($output, $x, $y, $c); + } + } + + imagealphablending($output, true); + } + + imagecopy( + $this->image, + $output, + $left, + $top, + 0, + 0, + $width, + $height, + ); + return $this; + } + + + /** + * 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, + string $fontFile, + float $size, + float $angle = 0, + array $options = [], + ): array + { + self::ensureExtension(); + $box = imagettfbbox($size, $angle, $fontFile, $text, $options); + return [ + 'left' => $minX = min([$box[0], $box[2], $box[4], $box[6]]), + 'top' => $minY = min([$box[1], $box[3], $box[5], $box[7]]), + 'width' => max([$box[0], $box[2], $box[4], $box[6]]) - $minX + 1, + 'height' => max([$box[1], $box[3], $box[5], $box[7]]) - $minY + 1, + ]; + } + + + /** + * Draws a rectangle using top-left coordinates and dimensions instead of two corner coordinates. + */ + public function rectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void + { + if ($width !== 0 && $height !== 0) { + $this->rectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color); + } + } + + + /** + * Draws a filled rectangle using top-left coordinates and dimensions instead of two corner coordinates. + */ + public function filledRectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void + { + if ($width !== 0 && $height !== 0) { + $this->filledRectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color); + } + } + + + /** + * 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::* $type + * @throws ImageException + */ + public function save(string $file, ?int $quality = null, ?int $type = null): void + { + $type ??= self::extensionToType(pathinfo($file, PATHINFO_EXTENSION)); + $this->output($type, $quality, $file); + } + + + /** + * 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 + { + return Helpers::capture(function () use ($type, $quality): void { + $this->output($type, $quality); + }); + } + + + /** + * Outputs image to string. + */ + public function __toString(): string + { + return $this->toString(); + } + + + /** + * 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 + */ + public function send(int $type = ImageType::JPEG, ?int $quality = null): void + { + header('Content-Type: ' . self::typeToMimeType($type)); + $this->output($type, $quality); + } + + + /** + * Outputs image to browser or file. + * @param ImageType::* $type + * @throws ImageException + */ + private function output(int $type, ?int $quality, ?string $file = null): void + { + [$defQuality, $min, $max] = match ($type) { + ImageType::JPEG => [85, 0, 100], + ImageType::PNG => [9, 0, 9], + ImageType::GIF => [null, null, null], + ImageType::WEBP => [80, 0, 100], + ImageType::AVIF => [30, 0, 100], + ImageType::BMP => [null, null, null], + default => throw new Nette\InvalidArgumentException("Unsupported image type '$type'."), + }; + + $args = [$this->image, $file]; + if ($defQuality !== null) { + $args[] = $quality === null ? $defQuality : max($min, min($max, $quality)); + } + + Callback::invokeSafe('image' . self::Formats[$type], $args, function (string $message) use ($file): void { + if ($file !== null) { + @unlink($file); // @ file may not exist + } + throw new ImageException($message); + }); + } + + + /** + * Call to undefined method. + * @param mixed[] $args + * @throws Nette\MemberAccessException + */ + public function __call(string $name, array $args): mixed + { + $function = 'image' . $name; + if (!function_exists($function)) { + ObjectHelpers::strictCall(static::class, $name); + } + + foreach ($args as $key => $value) { + if ($value instanceof self) { + $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); + } + } + + $res = $function($this->image, ...$args); + return $res instanceof \GdImage + ? $this->setImageResource($res) + : $res; + } + + + public function __clone() + { + ob_start(fn() => ''); + imagepng($this->image, null, 0); + $this->setImageResource(imagecreatefromstring(ob_get_clean()) ?: throw new Nette\ShouldNotHappenException); + } + + + /** @param-out int|float $num */ + private static function isPercent(int|string &$num): bool + { + if (is_string($num) && str_ends_with($num, '%')) { + $num = (float) substr($num, 0, -1); + return true; + } elseif (is_int($num) || $num === (string) (int) $num) { + $num = (int) $num; + return false; + } + + throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given."); + } + + + /** + * Prevents serialization. + */ + public function __serialize(): array + { + throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.'); + } + + + /** + * 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(); + 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')) { + throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); + } + } +} diff --git a/vendor/nette/utils/src/Utils/ImageColor.php b/vendor/nette/utils/src/Utils/ImageColor.php new file mode 100644 index 0000000..93da88f --- /dev/null +++ b/vendor/nette/utils/src/Utils/ImageColor.php @@ -0,0 +1,81 @@ +<?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 strlen; + + +/** + * Represent RGB color (0..255) with opacity (0..1). + */ +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); + } + + + /** + * Accepts formats #RRGGBB, #RRGGBBAA, #RGB, #RGBA + */ + public static function hex(string $hex): self + { + $hex = ltrim($hex, '#'); + $len = strlen($hex); + if ($len === 3 || $len === 4) { + return new self( + (int) hexdec($hex[0]) * 17, + (int) hexdec($hex[1]) * 17, + (int) hexdec($hex[2]) * 17, + (int) hexdec($hex[3] ?? 'F') * 17 / 255, + ); + } elseif ($len === 6 || $len === 8) { + return new self( + (int) hexdec($hex[0] . $hex[1]), + (int) hexdec($hex[2] . $hex[3]), + (int) hexdec($hex[4] . $hex[5]), + (int) hexdec(($hex[6] ?? 'F') . ($hex[7] ?? 'F')) / 255, + ); + } else { + throw new Nette\InvalidArgumentException('Invalid hex color format.'); + } + } + + + private function __construct( + public int $red, + public int $green, + public int $blue, + public float $opacity = 1, + ) { + $this->red = max(0, min(255, $red)); + $this->green = max(0, min(255, $green)); + $this->blue = max(0, min(255, $blue)); + $this->opacity = max(0, min(1, $opacity)); + } + + + /** + * 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 [ + max(0, min(255, $this->red)), + max(0, min(255, $this->green)), + max(0, min(255, $this->blue)), + max(0, min(127, (int) round(127 - $this->opacity * 127))), + ]; + } +} diff --git a/vendor/nette/utils/src/Utils/ImageType.php b/vendor/nette/utils/src/Utils/ImageType.php new file mode 100644 index 0000000..89c2790 --- /dev/null +++ b/vendor/nette/utils/src/Utils/ImageType.php @@ -0,0 +1,23 @@ +<?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; + + +/** + * Type of image file. + */ +/* enum */ final class ImageType +{ + public const + JPEG = IMAGETYPE_JPEG, + PNG = IMAGETYPE_PNG, + GIF = IMAGETYPE_GIF, + WEBP = IMAGETYPE_WEBP, + AVIF = 19, // IMAGETYPE_AVIF, + BMP = IMAGETYPE_BMP; +} diff --git a/vendor/nette/utils/src/Utils/Iterables.php b/vendor/nette/utils/src/Utils/Iterables.php new file mode 100644 index 0000000..e891bef --- /dev/null +++ b/vendor/nette/utils/src/Utils/Iterables.php @@ -0,0 +1,271 @@ +<?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_array; + + +/** + * Utilities for iterables. + */ +final class Iterables +{ + use Nette\StaticClass; + + /** + * Tests for the presence of value. + * @param iterable<mixed> $iterable + */ + public static function contains(iterable $iterable, mixed $value): bool + { + foreach ($iterable as $v) { + if ($v === $value) { + return true; + } + } + return false; + } + + + /** + * Tests for the presence of key. + * @param iterable<mixed> $iterable + */ + public static function containsKey(iterable $iterable, mixed $key): bool + { + foreach ($iterable as $k => $v) { + if ($k === $key) { + return true; + } + } + return false; + } + + + /** + * 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) + */ + public static function first(iterable $iterable, ?callable $predicate = null, ?callable $else = null): mixed + { + foreach ($iterable as $k => $v) { + if (!$predicate || $predicate($v, $k, $iterable)) { + return $v; + } + } + return $else ? $else() : 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) + */ + public static function firstKey(iterable $iterable, ?callable $predicate = null, ?callable $else = null): mixed + { + foreach ($iterable as $k => $v) { + if (!$predicate || $predicate($v, $k, $iterable)) { + return $k; + } + } + return $else ? $else() : null; + } + + + /** + * Tests whether at least one element in the iterable passes the test implemented by the provided function. + * @template K + * @template V + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): bool $predicate + */ + public static function some(iterable $iterable, callable $predicate): bool + { + foreach ($iterable as $k => $v) { + if ($predicate($v, $k, $iterable)) { + return true; + } + } + return false; + } + + + /** + * Tests whether all elements in the iterable pass the test implemented by the provided function. + * @template K + * @template V + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): bool $predicate + */ + public static function every(iterable $iterable, callable $predicate): bool + { + foreach ($iterable as $k => $v) { + if (!$predicate($v, $k, $iterable)) { + return false; + } + } + return true; + } + + + /** + * Returns a generator that yields only elements matching the given $predicate. Maintains original keys. + * @template K + * @template V + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): bool $predicate + * @return \Generator<K, V> + */ + public static function filter(iterable $iterable, callable $predicate): \Generator + { + foreach ($iterable as $k => $v) { + if ($predicate($v, $k, $iterable)) { + yield $k => $v; + } + } + } + + + /** + * Returns a generator that transforms values by calling $transformer. Maintains original keys. + * @template K + * @template V + * @template R + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): R $transformer + * @return \Generator<K, R> + */ + public static function map(iterable $iterable, callable $transformer): \Generator + { + foreach ($iterable as $k => $v) { + yield $k => $transformer($v, $k, $iterable); + } + } + + + /** + * Returns a generator that transforms keys and values by calling $transformer. If it returns null, the element is skipped. + * @template K + * @template V + * @template ResK + * @template ResV + * @param iterable<K, V> $iterable + * @param callable(V, K, iterable<K, V>): ?array{ResK, ResV} $transformer + * @return \Generator<ResK, ResV> + */ + public static function mapWithKeys(iterable $iterable, callable $transformer): \Generator + { + foreach ($iterable as $k => $v) { + $pair = $transformer($v, $k, $iterable); + if ($pair) { + yield $pair[0] => $pair[1]; + } + } + } + + + /** + * Creates a repeatable iterator from a factory function. + * The factory is called every time the iterator is iterated. + * @template K + * @template V + * @param callable(): iterable<K, V> $factory + * @return \IteratorAggregate<K, V> + */ + public static function repeatable(callable $factory): \IteratorAggregate + { + return new class ($factory(...)) implements \IteratorAggregate { + public function __construct( + /** @var \Closure(): iterable<mixed, mixed> */ + private readonly \Closure $factory, + ) { + } + + + public function getIterator(): \Iterator + { + return Iterables::toIterator(($this->factory)()); + } + }; + } + + + /** + * Wraps around iterator and caches its keys and values during iteration. + * This allows the data to be re-iterated multiple times. + * @template K + * @template V + * @param iterable<K, V> $iterable + * @return \IteratorAggregate<K, V> + */ + public static function memoize(iterable $iterable): \IteratorAggregate + { + return new class (self::toIterator($iterable)) implements \IteratorAggregate { + public function __construct( + private readonly \Iterator $iterator, + /** @var array<array{mixed, mixed}> */ + private array $cache = [], + ) { + } + + + public function getIterator(): \Generator + { + if (!$this->cache) { + $this->iterator->rewind(); + } + $i = 0; + while (true) { + if (isset($this->cache[$i])) { + [$k, $v] = $this->cache[$i]; + } elseif ($this->iterator->valid()) { + $k = $this->iterator->key(); + $v = $this->iterator->current(); + $this->iterator->next(); + $this->cache[$i] = [$k, $v]; + } else { + break; + } + yield $k => $v; + $i++; + } + } + }; + } + + + /** + * Creates an iterator from anything that is iterable. + * @template K + * @template V + * @param iterable<K, V> $iterable + * @return \Iterator<K, V> + */ + public static function toIterator(iterable $iterable): \Iterator + { + return match (true) { + $iterable instanceof \Iterator => $iterable, + $iterable instanceof \IteratorAggregate => self::toIterator($iterable->getIterator()), + is_array($iterable) => new \ArrayIterator($iterable), + default => throw new Nette\ShouldNotHappenException, + }; + } +} diff --git a/vendor/nette/utils/src/Utils/Json.php b/vendor/nette/utils/src/Utils/Json.php new file mode 100644 index 0000000..719c87c --- /dev/null +++ b/vendor/nette/utils/src/Utils/Json.php @@ -0,0 +1,81 @@ +<?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_int; +use const JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_SLASHES; + + +/** + * JSON encoder and decoder. + */ +final class Json +{ + use Nette\StaticClass; + + /** @deprecated use Json::decode(..., forceArrays: true) */ + public const FORCE_ARRAY = JSON_OBJECT_AS_ARRAY; + + /** @deprecated use Json::encode(..., pretty: true) */ + public const PRETTY = JSON_PRETTY_PRINT; + + /** @deprecated use Json::encode(..., asciiSafe: true) */ + public const ESCAPE_UNICODE = 1 << 19; + + + /** + * 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. + * @throws JsonException + */ + public static function encode( + mixed $value, + bool|int $pretty = false, + bool $asciiSafe = false, + bool $htmlSafe = false, + bool $forceObjects = false, + ): string + { + $flags = is_int($pretty) // back compatibility + ? ($pretty & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty & ~self::ESCAPE_UNICODE) // dresscode:ignore upgrading.declarations.deprecatedMember + : ($asciiSafe ? 0 : JSON_UNESCAPED_UNICODE) + | ($pretty ? JSON_PRETTY_PRINT : 0) + | ($forceObjects ? JSON_FORCE_OBJECT : 0) + | ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0); + + $flags |= JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION; + + $json = json_encode($value, $flags); + if ($error = json_last_error()) { + throw new JsonException(json_last_error_msg(), $error); + } + + return $json; + } + + + /** + * Decodes a JSON string to a PHP value. Use $forceArrays to decode objects as arrays. + * @throws JsonException + */ + public static function decode(string $json, bool|int $forceArrays = false): mixed + { + $flags = is_int($forceArrays) // back compatibility + ? $forceArrays + : ($forceArrays ? JSON_OBJECT_AS_ARRAY : 0); + $flags |= JSON_BIGINT_AS_STRING; + + $value = json_decode($json, flags: $flags); + if ($error = json_last_error()) { + throw new JsonException(json_last_error_msg(), $error); + } + + return $value; + } +} diff --git a/vendor/nette/utils/src/Utils/ObjectHelpers.php b/vendor/nette/utils/src/Utils/ObjectHelpers.php new file mode 100644 index 0000000..491cf48 --- /dev/null +++ b/vendor/nette/utils/src/Utils/ObjectHelpers.php @@ -0,0 +1,233 @@ +<?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 Nette\MemberAccessException; +use function strlen; + + +/** + * Nette\SmartObject helpers. + * @internal + */ +final class ObjectHelpers +{ + use Nette\StaticClass; + + /** + * @return never + * @throws MemberAccessException + */ + public static function strictGet(string $class, string $name): void + { + $rc = new \ReflectionClass($class); + $hint = self::getSuggestion([ + ...array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic()), + ...self::parseFullDoc($rc, '~^[ \t*]*@property(?:-read)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m'), + ], $name); + throw new MemberAccessException("Cannot read an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.')); + } + + + /** + * @return never + * @throws MemberAccessException + */ + public static function strictSet(string $class, string $name): void + { + $rc = new \ReflectionClass($class); + $hint = self::getSuggestion([ + ...array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic()), + ...self::parseFullDoc($rc, '~^[ \t*]*@property(?:-write)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m'), + ], $name); + throw new MemberAccessException("Cannot write to an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.')); + } + + + /** + * @return never + * @throws MemberAccessException + */ + public static function strictCall(string $class, string $method, array $additionalMethods = []): void + { + $trace = debug_backtrace(0, 3); // suppose this method is called from __call() + $context = ($trace[1]['function'] ?? null) === '__call' + ? ($trace[2]['class'] ?? null) + : null; + + if ($context && is_a($class, $context, allow_string: true) && method_exists($context, $method)) { // called parent::$method() + $class = get_parent_class($context); + } + + if (method_exists($class, $method)) { // insufficient visibility + $rm = new \ReflectionMethod($class, $method); + $visibility = $rm->isPrivate() + ? 'private ' + : ($rm->isProtected() ? 'protected ' : ''); + throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.')); + + } else { + $hint = self::getSuggestion([ + ...get_class_methods($class), + ...self::parseFullDoc(new \ReflectionClass($class), '~^[ \t*]*@method[ \t]+(?:static[ \t]+)?(?:\S+[ \t]+)??(\w+)\(~m'), + ...$additionalMethods, + ], $method); + throw new MemberAccessException("Call to undefined method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.')); + } + } + + + /** + * @return never + * @throws MemberAccessException + */ + public static function strictStaticCall(string $class, string $method): void + { + $trace = debug_backtrace(0, 3); // suppose this method is called from __callStatic() + $context = ($trace[1]['function'] ?? null) === '__callStatic' + ? ($trace[2]['class'] ?? null) + : null; + + if ($context && is_a($class, $context, allow_string: true) && method_exists($context, $method)) { // called parent::$method() + $class = get_parent_class($context); + } + + if (method_exists($class, $method)) { // insufficient visibility + $rm = new \ReflectionMethod($class, $method); + $visibility = $rm->isPrivate() + ? 'private ' + : ($rm->isProtected() ? 'protected ' : ''); + throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.')); + + } else { + $hint = self::getSuggestion( + array_filter((new \ReflectionClass($class))->getMethods(\ReflectionMethod::IS_PUBLIC), fn($m) => $m->isStatic()), + $method, + ); + throw new MemberAccessException("Call to undefined static method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.')); + } + } + + + /** + * Returns array of magic properties defined by annotation @property. + * @return array of [name => bit mask] + * @internal + */ + public static function getMagicProperties(string $class): array + { + static $cache; + $props = &$cache[$class]; + if ($props !== null) { + return $props; + } + + $rc = new \ReflectionClass($class); + preg_match_all( + '~^ [ \t*]* @property(|-read|-write|-deprecated) [ \t]+ [^\s$]+ [ \t]+ \$ (\w+) ()~mx', + (string) $rc->getDocComment(), + $matches, + PREG_SET_ORDER, + ); + + $props = []; + foreach ($matches as [, $type, $name]) { + $uname = ucfirst($name); + $write = $type !== '-read' + && $rc->hasMethod($nm = 'set' . $uname) + && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic(); + $read = $type !== '-write' + && ($rc->hasMethod($nm = 'get' . $uname) || $rc->hasMethod($nm = 'is' . $uname)) + && ($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; + } + } + + foreach ($rc->getTraits() as $trait) { + $props += self::getMagicProperties($trait->name); + } + + if ($parent = get_parent_class($class)) { + $props += self::getMagicProperties($parent); + } + + return $props; + } + + + /** + * Finds the best suggestion (for 8-bit encoding). + * @param (\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionClass|\ReflectionProperty|string)[] $possibilities + * @internal + */ + public static function getSuggestion(array $possibilities, string $value): ?string + { + $norm = preg_replace($re = '#^(get|set|has|is|add)(?=[A-Z])#', '+', $value); + $best = null; + $min = (strlen($value) / 4 + 1) * 10 + .1; + foreach (array_unique($possibilities, SORT_REGULAR) as $item) { + $item = $item instanceof \Reflector ? $item->name : $item; + 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; + } + } + + return $best; + } + + + private static function parseFullDoc(\ReflectionClass $rc, string $pattern): array + { + do { + $doc[] = $rc->getDocComment(); + $traits = $rc->getTraits(); + while ($trait = array_pop($traits)) { + $doc[] = $trait->getDocComment(); + $traits += $trait->getTraits(); + } + } while ($rc = $rc->getParentClass()); + + return preg_match_all($pattern, implode('', $doc), $m) ? $m[1] : []; + } + + + /** + * Checks if the public non-static property exists. + * Returns 'event' if the property exists and has event like name + * @internal + */ + public static function hasProperty(string $class, string $name): bool|string + { + static $cache; + $prop = &$cache[$class][$name]; + if ($prop === null) { + $prop = false; + try { + $rp = new \ReflectionProperty($class, $name); + if ($rp->isPublic() && !$rp->isStatic()) { + $prop = $name >= 'onA' && $name < 'on_' ? 'event' : true; + } + } catch (\ReflectionException) { + } + } + + return $prop; + } +} diff --git a/vendor/nette/utils/src/Utils/Paginator.php b/vendor/nette/utils/src/Utils/Paginator.php new file mode 100644 index 0000000..e95df0d --- /dev/null +++ b/vendor/nette/utils/src/Utils/Paginator.php @@ -0,0 +1,210 @@ +<?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; + + +/** + * Paginating math. + * + * @property int $page + * @property-read int $firstPage + * @property-read ?int $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 positive-int $itemsPerPage + * @property ?int<0,max> $itemCount + * @property-read int<0,max> $offset + * @property-read ?int<0,max> $countdownOffset + * @property-read int<0,max> $length + */ +class Paginator +{ + use Nette\SmartObject; + + private int $base = 1; + + /** @var positive-int */ + private int $itemsPerPage = 1; + + private int $page = 1; + + /** @var ?int<0, max> */ + private ?int $itemCount = null; + + + public function setPage(int $page): static + { + $this->page = $page; + return $this; + } + + + public function getPage(): int + { + return $this->base + $this->getPageIndex(); + } + + + public function getFirstPage(): int + { + return $this->base; + } + + + public function getLastPage(): ?int + { + return $this->itemCount === null + ? null + : $this->base + max(0, $this->getPageCount() - 1); + } + + + /** + * Returns the 1-based index of the first item on the current page, or 0 if the page is empty. + * @return int<0, max> + */ + public function getFirstItemOnPage(): int + { + return $this->itemCount !== 0 + ? $this->offset + 1 + : 0; + } + + + /** + * Returns the 1-based index of the last item on the current page. + * @return int<0, max> + */ + public function getLastItemOnPage(): int + { + return $this->offset + $this->length; + } + + + public function setBase(int $base): static + { + $this->base = $base; + return $this; + } + + + public function getBase(): int + { + return $this->base; + } + + + /** + * Returns zero-based page number. + * @return int<0, max> + */ + protected function getPageIndex(): int + { + $index = max(0, $this->page - $this->base); + return $this->itemCount === null + ? $index + : min($index, max(0, $this->getPageCount() - 1)); + } + + + public function isFirst(): bool + { + return $this->getPageIndex() === 0; + } + + + public function isLast(): bool + { + return $this->itemCount === null + ? false + : $this->getPageIndex() >= $this->getPageCount() - 1; + } + + + /** + * @return ?int<0, max> + */ + public function getPageCount(): ?int + { + return $this->itemCount === null + ? null + : max(0, (int) ceil($this->itemCount / $this->itemsPerPage)); + } + + + public function setItemsPerPage(int $itemsPerPage): static + { + $this->itemsPerPage = max(1, $itemsPerPage); + return $this; + } + + + /** + * @return positive-int + */ + public function getItemsPerPage(): int + { + return $this->itemsPerPage; + } + + + public function setItemCount(?int $itemCount = null): static + { + $this->itemCount = $itemCount === null ? null : max(0, $itemCount); + return $this; + } + + + /** + * @return ?int<0, max> + */ + public function getItemCount(): ?int + { + return $this->itemCount; + } + + + /** + * Returns the absolute index of the first item on current page. + * @return int<0, max> + */ + public function getOffset(): int + { + return $this->getPageIndex() * $this->itemsPerPage; + } + + + /** + * Returns the absolute index of the first item on current page in countdown paging. + * @return ?int<0, max> + */ + public function getCountdownOffset(): ?int + { + return $this->itemCount === null + ? null + : max(0, $this->itemCount - ($this->getPageIndex() + 1) * $this->itemsPerPage); + } + + + /** + * Returns the number of items on current page. + * @return int<0, max> + */ + public function getLength(): int + { + return $this->itemCount === null + ? $this->itemsPerPage + : max(0, 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 new file mode 100644 index 0000000..6a78314 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Process.php @@ -0,0 +1,564 @@ +<?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 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); // @ is escalated to exception + 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(as_float: 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(as_float: 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) { // @ an interrupting signal triggers a warning + $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/Random.php b/vendor/nette/utils/src/Utils/Random.php new file mode 100644 index 0000000..f3ec874 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Random.php @@ -0,0 +1,52 @@ +<?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 Random\Randomizer; +use function strlen; +use const PHP_VERSION_ID; + + +/** + * Secure random string generator. + */ +final class Random +{ + use Nette\StaticClass; + + /** + * Generates a random string of given length from characters specified in second argument. + * Supports intervals, such as `0-9` or `A-Z`. + */ + public static function generate(int $length = 10, string $charlist = '0-9a-z'): string + { + $charlist = preg_replace_callback( + '#.-.#', + fn(array $m): string => implode('', range($m[0][0], $m[0][2])), + $charlist, + ); + $charlist = count_chars($charlist, mode: 3); + $chLen = strlen($charlist); + + if ($length < 1) { + throw new Nette\InvalidArgumentException('Length must be greater than zero.'); + } elseif ($chLen < 2) { + throw new Nette\InvalidArgumentException('Character list must contain at least two chars.'); + } elseif (PHP_VERSION_ID >= 80300) { + return (new Randomizer)->getBytesFromString($charlist, $length); + } + + $res = ''; + for ($i = 0; $i < $length; $i++) { + $res .= $charlist[random_int(0, $chLen - 1)]; + } + + return $res; + } +} diff --git a/vendor/nette/utils/src/Utils/Reflection.php b/vendor/nette/utils/src/Utils/Reflection.php new file mode 100644 index 0000000..f464916 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Reflection.php @@ -0,0 +1,334 @@ +<?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 ord; + + +/** + * PHP reflection helpers. + */ +final class Reflection +{ + use Nette\StaticClass; + + /** @deprecated use Nette\Utils\Validators::isBuiltinType() */ + public static function isBuiltinType(string $type): bool + { + return Validators::isBuiltinType($type); + } + + + #[\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; + $pair = explode('::', $const); + if (isset($pair[1])) { + $pair[0] = Type::resolve($pair[0], $param); + try { + $rcc = new \ReflectionClassConstant($pair[0], $pair[1]); + } catch (\ReflectionException $e) { + $name = self::toString($param); + throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name.", 0, $e); + } + + return $rcc->getValue(); + + } elseif (!defined($const)) { + $const = substr((string) strrchr($const, '\\'), 1); + if (!defined($const)) { + $name = self::toString($param); + throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name."); + } + } + + return constant($const); + } + + return $param->getDefaultValue(); + } + + + /** + * 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 + { + foreach ($prop->getDeclaringClass()->getTraits() as $trait) { + if ($trait->hasProperty($prop->name) + // doc-comment guessing as workaround for insufficient PHP reflection + && $trait->getProperty($prop->name)->getDocComment() === $prop->getDocComment() + ) { + return self::getPropertyDeclaringClass($trait->getProperty($prop->name)); + } + } + + return $prop->getDeclaringClass(); + } + + + /** + * Returns a reflection of a method that contains a declaration of $method. + * Usually, each method is its own declaration, but the body of the method can also be in the trait and under a different name. + */ + public static function getMethodDeclaringMethod(\ReflectionMethod $method): \ReflectionMethod + { + // file & line guessing as workaround for insufficient PHP reflection + $decl = $method->getDeclaringClass(); + if ($decl->getFileName() === $method->getFileName() + && $decl->getStartLine() <= $method->getStartLine() + && $decl->getEndLine() >= $method->getEndLine() + ) { + return $method; + } + + $hash = [$method->getFileName(), $method->getStartLine(), $method->getEndLine()]; + if (($alias = $decl->getTraitAliases()[$method->name] ?? null) + && ($m = new \ReflectionMethod(...explode('::', $alias, 2))) + && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()] + ) { + return self::getMethodDeclaringMethod($m); + } + + foreach ($decl->getTraits() as $trait) { + if ($trait->hasMethod($method->name) + && ($m = $trait->getMethod($method->name)) + && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()] + ) { + return self::getMethodDeclaringMethod($m); + } + } + + return $method; + } + + + /** + * Finds out if reflection has access to PHPdoc comments. Comments may not be available due to the opcode cache. + */ + public static function areCommentsAvailable(): bool + { + static $res; + return $res ?? $res = (bool) (new \ReflectionMethod(self::class, __FUNCTION__))->getDocComment(); + } + + + /** + * Returns a human-readable string representation of a reflection object. + */ + public static function toString(\Reflector $ref): string + { + if ($ref instanceof \ReflectionClass) { + return $ref->name; + } elseif ($ref instanceof \ReflectionMethod) { + return $ref->getDeclaringClass()->name . '::' . $ref->name . '()'; + } elseif ($ref instanceof \ReflectionFunction) { + return $ref->isAnonymous() ? '{closure}()' : $ref->name . '()'; + } elseif ($ref instanceof \ReflectionProperty) { + return self::getPropertyDeclaringClass($ref)->name . '::$' . $ref->name; + } elseif ($ref instanceof \ReflectionParameter) { + return '$' . $ref->name . ' in ' . self::toString($ref->getDeclaringFunction()); + } else { + throw new Nette\InvalidArgumentException; + } + } + + + /** + * 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 + { + $lower = strtolower($name); + if (empty($name)) { + throw new Nette\InvalidArgumentException('Class name must not be empty.'); + + } elseif (Validators::isBuiltinType($lower)) { + return $lower; + + } elseif ($lower === 'self' || $lower === 'static') { + return $context->name; + + } elseif ($lower === 'parent') { + return $context->getParentClass() + ? $context->getParentClass()->name + : 'parent'; + + } elseif ($name[0] === '\\') { // fully qualified name + return ltrim($name, '\\'); + } + + $uses = self::getUseStatements($context); + $parts = explode('\\', $name, 2); + if (isset($uses[$parts[0]])) { + $parts[0] = $uses[$parts[0]]; + return implode('\\', $parts); + + } elseif ($context->inNamespace()) { + return $context->getNamespaceName() . '\\' . $name; + + } else { + return $name; + } + } + + + /** + * 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 + */ + public static function getUseStatements(\ReflectionClass $class): array + { + if ($class->isAnonymous()) { + throw new Nette\NotImplementedException('Anonymous classes are not supported.'); + } + + static $cache = []; + if (!isset($cache[$name = $class->name])) { + if ($class->isInternal()) { + $cache[$name] = []; + } else { + $code = (string) file_get_contents((string) $class->getFileName()); + $cache = self::parseUseStatements($code, $name) + $cache; + } + } + + return $cache[$name]; + } + + + /** + * 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()); + $tokens = []; + } + + $namespace = $class = null; + $classLevel = $level = 0; + $res = $uses = []; + + $nameTokens = [T_STRING, T_NS_SEPARATOR, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED]; + + while ($token = current($tokens)) { + next($tokens); + switch ($token->id) { + case T_NAMESPACE: + $namespace = ltrim(self::fetch($tokens, $nameTokens) . '\\', '\\'); + $uses = []; + break; + + case T_CLASS: + case T_INTERFACE: + case T_TRAIT: + case T_ENUM: + if ($name = self::fetch($tokens, T_STRING)) { + $class = $namespace . $name; + $classLevel = $level + 1; + $res[$class] = $uses; + if ($class === $forClass) { + return $res; + } + } + + break; + + case T_USE: + while (!$class && ($name = self::fetch($tokens, $nameTokens))) { + $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; + } else { + $tmp = explode('\\', $suffix); + $uses[end($tmp)] = $name . $suffix; + } + + if (!self::fetch($tokens, ',')) { + break; + } + } + } elseif (self::fetch($tokens, T_AS) && ($alias = self::fetch($tokens, T_STRING))) { + $uses[$alias] = $name; + + } else { + $tmp = explode('\\', $name); + $uses[end($tmp)] = $name; + } + + if (!self::fetch($tokens, ',')) { + break; + } + } + + break; + + case T_CURLY_OPEN: + case T_DOLLAR_OPEN_CURLY_BRACES: + case ord('{'): + $level++; + break; + + case ord('}'): + if ($level === $classLevel) { + $class = $classLevel = 0; + } + + $level--; + } + } + + return $res; + } + + + /** + * @param \PhpToken[] $tokens + * @param string|int|int[] $take + */ + private static function fetch(array &$tokens, string|int|array $take): ?string + { + $res = null; + while ($token = current($tokens)) { + if ($token->is($take)) { + $res .= $token->text; + } elseif (!$token->is([T_DOC_COMMENT, T_WHITESPACE, T_COMMENT])) { + break; + } + + next($tokens); + } + + return $res; + } +} diff --git a/vendor/nette/utils/src/Utils/ReflectionMethod.php b/vendor/nette/utils/src/Utils/ReflectionMethod.php new file mode 100644 index 0000000..653f0b4 --- /dev/null +++ b/vendor/nette/utils/src/Utils/ReflectionMethod.php @@ -0,0 +1,39 @@ +<?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 is_string; + + +/** + * ReflectionMethod preserving the original class name. + * @internal + */ +final class ReflectionMethod extends \ReflectionMethod +{ + /** @var \ReflectionClass<object> */ + private readonly \ReflectionClass $originalClass; + + + /** @param class-string|object $objectOrMethod */ + public function __construct(object|string $objectOrMethod, ?string $method = null) + { + if (is_string($objectOrMethod) && str_contains($objectOrMethod, '::')) { + [$objectOrMethod, $method] = explode('::', $objectOrMethod, 2); + } + parent::__construct($objectOrMethod, $method); + $this->originalClass = new \ReflectionClass($objectOrMethod); + } + + + /** @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 new file mode 100644 index 0000000..d12d042 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Strings.php @@ -0,0 +1,742 @@ +<?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 JetBrains\PhpStorm\Language; +use Nette; +use function defined, extension_loaded, function_exists, in_array, is_array, is_int, is_object, is_string, strlen; +use const ENT_IGNORE, ENT_NOQUOTES; + + +/** + * String tools library. + */ +class Strings +{ + use Nette\StaticClass; + + 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')] + public const TRIM_CHARACTERS = self::TrimCharacters; + + + /** + * @deprecated use Nette\Utils\Validators::isUnicode() + */ + public static function checkEncoding(string $s): bool + { + return $s === self::fixEncoding($s); + } + + + /** + * Removes all invalid UTF-8 characters from a string. + */ + public static function fixEncoding(string $s): string + { + // removes xD800-xDFFF, x110000 and higher + return htmlspecialchars_decode(htmlspecialchars($s, ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'), ENT_NOQUOTES); + } + + + /** + * Returns a specific character in UTF-8 from code point (number in range 0x0000..D7FF or 0xE000..10FFFF). + * @throws Nette\InvalidArgumentException if code point is not in valid range + */ + public static function chr(int $code): string + { + if ($code < 0 || ($code >= 0xD800 && $code <= 0xDFFF) || $code > 0x10FFFF) { + throw new Nette\InvalidArgumentException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.'); + } elseif (!extension_loaded('iconv')) { + 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; + } + + + /** + * Returns a code point of specific character in UTF-8 (number in range 0x0000..D7FF or 0xE000..10FFFF). + */ + public static function ord(string $c): int + { + if (!extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); + } + + $tmp = iconv('UTF-8', 'UTF-32BE//IGNORE', $c); + if ($tmp === false || $tmp === '') { + throw new Nette\InvalidArgumentException('Invalid UTF-8 character "' . ($c === '' ? '' : '\x' . strtoupper(bin2hex($c))) . '".'); + } + + return unpack('N', $tmp)[1] ?? throw new Nette\ShouldNotHappenException; + } + + + /** + * @deprecated use str_starts_with() + */ + public static function startsWith(string $haystack, string $needle): bool + { + return str_starts_with($haystack, $needle); + } + + + /** + * @deprecated use str_ends_with() + */ + public static function endsWith(string $haystack, string $needle): bool + { + return str_ends_with($haystack, $needle); + } + + + /** + * @deprecated use str_contains() + */ + public static function contains(string $haystack, string $needle): bool + { + return str_contains($haystack, $needle); + } + + + /** + * Returns a part of UTF-8 string specified by starting position and length. If start is negative, + * the returned string will start at the start'th character from the end of string. + */ + public static function substring(string $s, int $start, ?int $length = null): string + { + if (function_exists('mb_substr')) { + return mb_substr($s, $start, $length, 'UTF-8'); // MB is much faster + } elseif (!extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires extension ICONV or MBSTRING, neither is loaded.'); + } elseif ($length === null) { + $length = self::length($s); + } elseif ($start < 0 && $length < 0) { + $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; + } + + + /** + * Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines, + * trims end spaces on lines, normalizes UTF-8 to the normal form of NFC. + */ + public static function normalize(string $s): string + { + // convert to compressed normal form (NFC) + if (class_exists(\Normalizer::class, false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== false) { + $s = $n; + } + + $s = self::unixNewLines($s); + + // remove control characters; leave \t + \n + $s = self::pcre('preg_replace', ['#[\x00-\x08\x0B-\x1F\x7F-\x9F]+#u', '', $s]); + + // right trim + $s = self::pcre('preg_replace', ['#[\t ]+$#m', '', $s]); + + // leading and trailing blank lines + $s = trim($s, "\n"); + + return $s; + } + + + /** @deprecated use Strings::unixNewLines() */ + public static function normalizeNewLines(string $s): string + { + return self::unixNewLines($s); + } + + + /** + * Converts line endings to \n used on Unix-like systems. + * Line endings are: \n, \r, \r\n, U+2028 line separator, U+2029 paragraph separator. + */ + public static function unixNewLines(string $s): string + { + return preg_replace("~\r\n?|\u{2028}|\u{2029}~", "\n", $s); + } + + + /** + * Converts line endings to platform-specific, i.e. \r\n on Windows and \n elsewhere. + * Line endings are: \n, \r, \r\n, U+2028 line separator, U+2029 paragraph separator. + */ + public static function platformNewLines(string $s): string + { + return preg_replace("~\r\n?|\n|\u{2028}|\u{2029}~", PHP_EOL, $s); + } + + + /** + * Converts UTF-8 string to ASCII, ie removes diacritics etc. + */ + 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; + + // 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', + ]); // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß + 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 = \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.'); + } + + $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) + $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars + } + + return $s; + } + + + /** + * Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters + * except letters of the English alphabet and numbers with a hyphens. + */ + public static function webalize(string $s, ?string $charlist = null, bool $lower = true): string + { + $s = self::toAscii($s); + if ($lower) { + $s = strtolower($s); + } + + $s = self::pcre('preg_replace', ['#[^a-z0-9' . ($charlist !== null ? preg_quote($charlist, '#') : '') . ']+#i', '-', $s]); + $s = trim($s, '-'); + return $s; + } + + + /** + * Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated, + * an ellipsis (or something else set with third argument) is appended to the string. + */ + public static function truncate(string $s, int $maxLen, string $append = "\u{2026}"): string + { + if (self::length($s) > $maxLen) { + $maxLen -= self::length($append); + if ($maxLen < 1) { + return $append; + + } elseif ($matches = self::match($s, '#^.{1,' . $maxLen . '}(?=[\s\x00-/:-@\[-`{-~])#us')) { + return $matches[0] . $append; + + } else { + return self::substring($s, 0, $maxLen) . $append; + } + } + + return $s; + } + + + /** + * Indents a multiline text from the left. Second argument sets how many indentation chars should be used, + * while the indent itself is the third argument (*tab* by default). + */ + public static function indent(string $s, int $level = 1, string $chars = "\t"): string + { + if ($level > 0) { + $s = self::replace($s, '#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level)); + } + + return $s; + } + + + /** + * Converts all characters of UTF-8 string to lower case. + */ + public static function lower(string $s): string + { + return mb_strtolower($s, 'UTF-8'); + } + + + /** + * Converts the first character of a UTF-8 string to lower case and leaves the other characters unchanged. + */ + public static function firstLower(string $s): string + { + return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1); + } + + + /** + * Converts all characters of a UTF-8 string to upper case. + */ + public static function upper(string $s): string + { + return mb_strtoupper($s, 'UTF-8'); + } + + + /** + * Converts the first character of a UTF-8 string to upper case and leaves the other characters unchanged. + */ + public static function firstUpper(string $s): string + { + return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1); + } + + + /** + * Converts the first character of every word of a UTF-8 string to upper case and the others to lower case. + */ + public static function capitalize(string $s): string + { + return mb_convert_case($s, MB_CASE_TITLE, 'UTF-8'); + } + + + /** + * Compares two UTF-8 strings or their parts, without taking character case into account. If length is null, whole strings are compared, + * if it is negative, the corresponding number of characters from the end of the strings is compared, + * otherwise the appropriate number of characters from the beginning is compared. + */ + public static function compare(string $left, string $right, ?int $length = null): bool + { + if (class_exists(\Normalizer::class, 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 ($length < 0) { + $left = self::substring($left, $length, -$length); + $right = self::substring($right, $length, -$length); + } elseif ($length !== null) { + $left = self::substring($left, 0, $length); + $right = self::substring($right, 0, $length); + } + + return self::lower($left) === self::lower($right); + } + + + /** + * Finds the common prefix of strings or returns empty string if the prefix was not found. + * @param string[] $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]) { + while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xC0") { + $i--; + } + + return substr($first, 0, $i); + } + } + } + + return $first; + } + + + /** + * Returns number of characters (not bytes) in UTF-8 string. + * That is the number of Unicode code points which may differ from the number of graphemes. + */ + 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 + }; + } + + + /** + * Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string. + */ + public static function trim(string $s, string $charlist = self::TrimCharacters): string + { + $charlist = preg_quote($charlist, '#'); + return self::replace($s, '#^[' . $charlist . ']+|[' . $charlist . ']+$#Du'); + } + + + /** + * Pads a UTF-8 string to given length by prepending the $pad string to the beginning. + * @param non-empty-string $pad + */ + public static function padLeft(string $s, int $length, string $pad = ' '): string + { + $length = max(0, $length - self::length($s)); + $padLen = self::length($pad); + return str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s; + } + + + /** + * Pads UTF-8 string to given length by appending the $pad string to the end. + * @param non-empty-string $pad + */ + public static function padRight(string $s, int $length, string $pad = ' '): string + { + $length = max(0, $length - self::length($s)); + $padLen = self::length($pad); + return $s . str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen); + } + + + /** + * Reverses UTF-8 string. + */ + public static function reverse(string $s): string + { + if (!extension_loaded('iconv')) { + 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)); + } + + + /** + * Returns part of $haystack before $nth occurence of $needle or returns null if the needle was not found. + * Negative value means searching from the end. + */ + public static function before(string $haystack, string $needle, int $nth = 1): ?string + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null + ? null + : substr($haystack, 0, $pos); + } + + + /** + * Returns part of $haystack after $nth occurence of $needle or returns null if the needle was not found. + * Negative value means searching from the end. + */ + public static function after(string $haystack, string $needle, int $nth = 1): ?string + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null + ? null + : substr($haystack, $pos + strlen($needle)); + } + + + /** + * Returns position in characters of $nth occurence of $needle in $haystack or null if the $needle was not found. + * Negative value of `$nth` means searching from the end. + */ + public static function indexOf(string $haystack, string $needle, int $nth = 1): ?int + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null + ? null + : self::length(substr($haystack, 0, $pos)); + } + + + /** + * Returns position in characters of $nth occurence of $needle in $haystack or null if the needle was not found. + */ + private static function pos(string $haystack, string $needle, int $nth = 1): ?int + { + if (!$nth) { + return null; + } elseif ($nth > 0) { + if ($needle === '') { + return 0; + } + + $pos = 0; + while (($pos = strpos($haystack, $needle, $pos)) !== false && --$nth) { + $pos++; + } + } else { + $len = strlen($haystack); + if ($needle === '') { + return $len; + } elseif ($len === 0) { + return null; + } + + $pos = $len - 1; + while (($pos = strrpos($haystack, $needle, $pos - $len)) !== false && ++$nth) { + $pos--; + } + } + + return Helpers::falseToNull($pos); + } + + + /** + * Splits the string by a regular expression. Expressions in parentheses will be captured and returned as well. + * @return list<string> + */ + public static function split( + string $subject, + #[Language('RegExp')] + string $pattern, + bool|int $captureOffset = false, + bool $skipEmpty = false, + int $limit = -1, + bool $utf8 = false, + ): array + { + $flags = is_int($captureOffset) // back compatibility + ? $captureOffset + : ($captureOffset ? PREG_SPLIT_OFFSET_CAPTURE : 0) | ($skipEmpty ? PREG_SPLIT_NO_EMPTY : 0); + + $pattern .= $utf8 ? 'u' : ''; + $m = self::pcre('preg_split', [$pattern, $subject, $limit, $flags | PREG_SPLIT_DELIM_CAPTURE]); + return $utf8 && $captureOffset + ? self::bytesToChars($subject, [$m])[0] + : $m; + } + + + /** + * 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> + */ + public static function match( + string $subject, + #[Language('RegExp')] + string $pattern, + bool|int $captureOffset = false, + int $offset = 0, + bool $unmatchedAsNull = false, + bool $utf8 = false, + ): ?array + { + $flags = is_int($captureOffset) // back compatibility + ? $captureOffset + : ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0); + + if ($utf8) { + $offset = strlen(self::substring($subject, 0, $offset)); + $pattern .= 'u'; + } + + $m = []; + if ($offset > strlen($subject)) { + return null; + } elseif (!self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])) { + return null; + } elseif ($utf8 && $captureOffset) { + return self::bytesToChars($subject, [$m])[0]; + } else { + return $m; + } + } + + + /** + * 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>>) + */ + public static function matchAll( + string $subject, + #[Language('RegExp')] + string $pattern, + bool|int $captureOffset = false, + int $offset = 0, + bool $unmatchedAsNull = false, + bool $patternOrder = false, + bool $utf8 = false, + bool $lazy = false, + ): array|\Generator + { + if ($utf8) { + $offset = strlen(self::substring($subject, 0, $offset)); + $pattern .= 'u'; + } + + if ($lazy) { + $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); + } elseif ($utf8) { + $m = self::bytesToChars($subject, [$m])[0]; + } + yield $counter++ => $m; + } + })(); + } + + if ($offset > strlen($subject)) { + return []; + } + + $flags = is_int($captureOffset) // back compatibility + ? $captureOffset + : ($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), + $offset, + ]); + return $utf8 && $captureOffset + ? self::bytesToChars($subject, $m) + : $m; + } + + + /** + * Replaces all matches of the regular expression $pattern, which can be a string or array in the form `pattern => replacement`. + * @param string|array<string, string> $pattern + */ + public static function replace( + string $subject, + #[Language('RegExp')] + string|array $pattern, + string|callable $replacement = '', + int $limit = -1, + bool $captureOffset = false, + bool $unmatchedAsNull = false, + bool $utf8 = false, + ): string + { + if (is_object($replacement) || is_array($replacement)) { + if (!is_callable($replacement, false, $textual)) { + throw new Nette\InvalidStateException("Callback '$textual' is not callable."); + } + + $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'; + if ($captureOffset) { + $replacement = fn($m) => $replacement(self::bytesToChars($subject, [$m])[0]); + } + } + + return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit, 0, $flags]); + + } elseif (is_array($pattern) && is_string(key($pattern))) { + $replacement = array_values($pattern); + $pattern = array_keys($pattern); + } + + if ($utf8) { + $pattern = array_map(fn($item) => $item . 'u', (array) $pattern); + } + + return self::pcre('preg_replace', [$pattern, $replacement, $subject, $limit]); + } + + + /** + * @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; + foreach ($groups as &$matches) { + foreach ($matches as &$match) { + if ($match[1] > $lastBytes) { + $lastChars += self::length(substr($s, $lastBytes, $match[1] - $lastBytes)); + } elseif ($match[1] < $lastBytes) { + $lastChars -= self::length(substr($s, $match[1], $lastBytes - $match[1])); + } + + $lastBytes = $match[1]; + $match[1] = $lastChars; + } + } + + return $groups; + } + + + /** + * @param callable-string $func + * @param list<mixed> $args + * @internal + */ + public static function pcre(string $func, array $args): mixed + { + $res = Callback::invokeSafe($func, $args, function (string $message) use ($args): void { + // compile-time error, not detectable by preg_last_error + throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0])); + }); + + 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'], true)) + ) { + throw new RegexpException(preg_last_error_msg() + . ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code); + } + + return $res; + } +} diff --git a/vendor/nette/utils/src/Utils/Type.php b/vendor/nette/utils/src/Utils/Type.php new file mode 100644 index 0000000..56bb291 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Type.php @@ -0,0 +1,314 @@ +<?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 count, is_resource, is_string; + + +/** + * PHP type reflection. + */ +final readonly class Type +{ + /** @var list<string|self> */ + private array $types; + private ?string $singleName; + private string $kind; // | & + + + /** + * Creates a Type object based on reflection. Resolves self, static and parent to the actual class name. + * If the subject has no type, it returns null. + */ + public static function fromReflection( + \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $reflection, + ): ?self + { + $type = $reflection instanceof \ReflectionFunctionAbstract + ? $reflection->getReturnType() ?? ($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 + { + if ($type instanceof \ReflectionNamedType) { + $name = self::resolve($type->getName(), $of); + return $asObject + ? new self($type->allowsNull() && $name !== 'mixed' ? [$name, 'null'] : [$name]) + : $name; + + } elseif ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) { + return new self( + array_map(fn($t) => self::fromReflectionType($t, $of, asObject: false), $type->getTypes()), + $type instanceof \ReflectionUnionType ? '|' : '&', + ); + + } else { + throw new Nette\InvalidStateException('Unexpected type of ' . Reflection::toString($of)); + } + } + + + /** + * Creates the Type object according to the text notation. + */ + public static function fromString(string $type): self + { + if (!Validators::isTypeDeclaration($type)) { + throw new Nette\InvalidArgumentException("Invalid type '$type'."); + } + + if ($type[0] === '?') { + return new self([substr($type, 1), 'null']); + } + + $unions = []; + foreach (explode('|', $type) as $part) { + $part = explode('&', trim($part, '()')); + $unions[] = count($part) === 1 ? $part[0] : new self($part, '&'); + } + + return count($unions) === 1 && $unions[0] instanceof self + ? $unions[0] + : new self($unions); + } + + + /** + * Creates a Type object based on the actual type of value. + */ + public static function fromValue(mixed $value): self + { + $type = get_debug_type($value); + if (is_resource($value)) { + $type = 'mixed'; + } elseif (str_ends_with($type, '@anonymous')) { + $parent = substr($type, 0, -10); + $type = $parent === 'class' ? 'object' : $parent; + } + + return new self([$type]); + } + + + /** + * Resolves 'self', 'static' and 'parent' to the actual class name. + */ + public static function resolve( + string $type, + \ReflectionFunction|\ReflectionMethod|\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; + } elseif ($lower === 'static') { + return ($of instanceof ReflectionMethod ? $of->getOriginalClass() : $class)->name; + } elseif ($lower === 'parent' && $class->getParentClass()) { + return $class->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); + $types[] = 'null'; + } + + $this->types = array_values($types); + $this->singleName = is_string($types[0]) && ($types[1] ?? 'null') === 'null' ? $types[0] : null; + $this->kind = count($types) > 1 ? $kind : ''; + } + + + public function __toString(): string + { + $multi = count($this->types) > 1; + if ($this->singleName !== null) { + return ($multi ? '?' : '') . $this->singleName; + } + + $res = []; + foreach ($this->types as $type) { + $res[] = $type instanceof self && $multi ? "($type)" : $type; + } + return implode($this->kind, $res); + } + + + /** + * Returns a union type that accepts both the current type and the given type. + */ + public function with(string|self $type): self + { + $type = is_string($type) ? self::fromString($type) : $type; + return match (true) { + $this->allows($type) => $this, + $type->allows($this) => $type, + default => new self(array_unique( + [...$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>>> + */ + public function getNames(): array + { + return array_map(fn($t) => $t instanceof self ? $t->getNames() : $t, $this->types); + } + + + /** + * Returns the array of subtypes that make up the compound type as Type objects. + * @return list<self> + */ + public function getTypes(): array + { + return array_map(fn($t) => $t instanceof self ? $t : new self([$t]), $this->types); + } + + + /** + * Returns the type name for simple types, otherwise null. + */ + public function getSingleName(): ?string + { + return $this->singleName; + } + + + /** + * Returns true whether it is a union type. + */ + public function isUnion(): bool + { + return $this->kind === '|'; + } + + + /** + * Returns true whether it is an intersection type. + */ + public function isIntersection(): bool + { + return $this->kind === '&'; + } + + + /** + * Checks whether it is a simple (non-compound) type. Single nullable types such as ?int are also considered simple. + */ + public function isSimple(): bool + { + return $this->singleName !== null; + } + + + #[\Deprecated('use isSimple()')] + public function isSingle(): bool + { + return $this->singleName !== null; + } + + + /** + * Checks whether it is a simple PHP built-in type (int, string, bool, etc.). + */ + public function isBuiltin(): bool + { + return $this->singleName !== null && Validators::isBuiltinType($this->singleName); + } + + + /** + * Checks whether it is a simple class or interface name (not a built-in type). + */ + public function isClass(): bool + { + return $this->singleName !== null && !Validators::isBuiltinType($this->singleName); + } + + + /** + * Determines if type is special class name self/parent/static. + */ + public function isClassKeyword(): bool + { + return $this->singleName !== null && Validators::isClassKeyword($this->singleName); + } + + + /** + * Checks whether a value of the given type could be assigned to this type. + */ + public function allows(string|self $type): bool + { + if ($this->types === ['mixed']) { + return true; + } + + $type = is_string($type) ? self::fromString($type) : $type; + return $type->isUnion() + ? Arrays::every($type->types, fn($t) => $this->allowsAny($t instanceof self ? $t->types : [$t])) + : $this->allowsAny($type->types); + } + + + /** @param array<string> $givenTypes */ + private function allowsAny(array $givenTypes): bool + { + return $this->isUnion() + ? Arrays::some($this->types, fn($t) => $this->allowsAll($t instanceof self ? $t->types : [$t], $givenTypes)) + : $this->allowsAll($this->types, $givenTypes); + } + + + /** + * @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( + $givenTypes, + fn(string $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 new file mode 100644 index 0000000..2c583e7 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Validators.php @@ -0,0 +1,419 @@ +<?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 array_key_exists, gettype, is_float, is_int, is_object, is_string, strlen; + + +/** + * Validation utilities. + */ +class Validators +{ + use Nette\StaticClass; + + private const BuiltinTypes = [ + 'string' => 1, 'int' => 1, 'float' => 1, 'bool' => 1, 'array' => 1, 'object' => 1, + 'callable' => 1, 'iterable' => 1, 'void' => 1, 'null' => 1, 'mixed' => 1, 'false' => 1, + 'never' => 1, 'true' => 1, + ]; + + /** @var array<string, ?(callable(mixed): bool)> */ + protected static $validators = [ + // PHP types + 'array' => 'is_array', + 'bool' => 'is_bool', + 'boolean' => 'is_bool', + 'float' => 'is_float', + 'int' => 'is_int', + 'integer' => 'is_int', + 'null' => 'is_null', + 'object' => 'is_object', + 'resource' => 'is_resource', + 'scalar' => 'is_scalar', + 'string' => 'is_string', + + // pseudo-types + 'callable' => [self::class, 'isCallable'], + 'iterable' => 'is_iterable', + 'list' => [Arrays::class, 'isList'], + 'mixed' => [self::class, 'isMixed'], + 'none' => [self::class, 'isNone'], + 'number' => [self::class, 'isNumber'], + 'numeric' => [self::class, 'isNumeric'], + 'numericint' => [self::class, 'isNumericInt'], + + // string patterns + 'alnum' => 'ctype_alnum', + 'alpha' => 'ctype_alpha', + 'digit' => 'ctype_digit', + 'lower' => 'ctype_lower', + 'pattern' => null, + 'space' => 'ctype_space', + 'unicode' => [self::class, 'isUnicode'], + 'upper' => 'ctype_upper', + 'xdigit' => 'ctype_xdigit', + + // syntax validation + 'email' => [self::class, 'isEmail'], + 'identifier' => [self::class, 'isPhpIdentifier'], + 'uri' => [self::class, 'isUri'], + 'url' => [self::class, 'isUrl'], + + // environment validation + 'class' => 'class_exists', + 'interface' => 'interface_exists', + 'directory' => 'is_dir', + 'file' => 'is_file', + 'type' => [self::class, 'isType'], + ]; + + /** @var array<string, callable(mixed): int> */ + protected static $counters = [ + 'string' => 'strlen', + 'unicode' => [Strings::class, 'length'], + 'array' => 'count', + 'list' => 'count', + 'alnum' => 'strlen', + 'alpha' => 'strlen', + 'digit' => 'strlen', + 'lower' => 'strlen', + 'space' => 'strlen', + 'upper' => 'strlen', + 'xdigit' => 'strlen', + ]; + + + /** + * Verifies that the value is of expected types separated by pipe. + * @throws AssertionException + */ + public static function assert(mixed $value, string $expected, string $label = 'variable'): void + { + if (!static::is($value, $expected)) { + $expected = str_replace(['|', ':'], [' or ', ' in range '], $expected); + $translate = ['boolean' => 'bool', 'integer' => 'int', 'double' => 'float', 'NULL' => 'null']; + $type = $translate[gettype($value)] ?? gettype($value); + if (is_int($value) || is_float($value) || (is_string($value) && strlen($value) < 40)) { + $type .= ' ' . var_export($value, return: true); + } elseif (is_object($value)) { + $type .= ' ' . $value::class; + } + + throw new AssertionException("The $label expects to be $expected, $type given."); + } + } + + + /** + * Verifies that item $key in array exists and is of expected types separated by pipe. + * @param mixed[] $array + * @throws AssertionException + */ + public static function assertField( + array $array, + int|string $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) . '.'); + + } elseif ($expected) { + static::assert($array[$key], $expected, str_replace('%', (string) $key, $label)); + } + } + + + /** + * Verifies that the value is of expected types separated by pipe. + */ + public static function is(mixed $value, string $expected): bool + { + foreach (explode('|', $expected) as $item) { + if (str_ends_with($item, '[]')) { + if (is_iterable($value) && self::everyIs($value, substr($item, 0, -2))) { + return true; + } + + continue; + + } elseif (str_starts_with($item, '?')) { + $item = substr($item, 1); + if ($value === null) { + return true; + } + } + + [$type] = $item = explode(':', $item, 2); + if (isset(static::$validators[$type])) { + try { + if (!static::$validators[$type]($value)) { + continue; + } + } catch (\TypeError) { + continue; + } + } elseif ($type === 'pattern') { + if (Strings::match($value, '|^' . ($item[1] ?? '') . '$|D')) { + return true; + } + + continue; + + } elseif (!$value instanceof $type) { + continue; + } + + if (isset($item[1])) { + $length = $value; + if (isset(static::$counters[$type])) { + $length = static::$counters[$type]($value); + } + + $range = explode('..', $item[1]); + if (!isset($range[1])) { + $range[1] = $range[0]; + } + + if (($range[0] !== '' && $length < $range[0]) || ($range[1] !== '' && $length > $range[1])) { + continue; + } + } + + return true; + } + + return false; + } + + + /** + * Finds whether all values are of expected types separated by pipe. + * @param iterable<mixed> $values + */ + public static function everyIs(iterable $values, string $expected): bool + { + foreach ($values as $value) { + if (!static::is($value, $expected)) { + return false; + } + } + + return true; + } + + + /** + * Checks if the value is an integer or a float. + * @return ($value is int|float ? true : false) + */ + public static function isNumber(mixed $value): bool + { + return is_int($value) || is_float($value); + } + + + /** + * Checks if the value is an integer or a integer written in a string. + * @return ($value is non-empty-string ? bool : ($value is int ? true : false)) + */ + public static function isNumericInt(mixed $value): bool + { + return is_int($value) || (is_string($value) && preg_match('#^[+-]?[0-9]+$#D', $value)); + } + + + /** + * Checks if the value is a number or a number written in a string. + * @return ($value is non-empty-string ? bool : ($value is int|float ? true : false)) + */ + public static function isNumeric(mixed $value): bool + { + return is_float($value) || is_int($value) || (is_string($value) && preg_match('#^[+-]?([0-9]++\.?[0-9]*|\.[0-9]+)$#D', $value)); + } + + + /** + * Checks if the value is a syntactically correct callback. + */ + public static function isCallable(mixed $value): bool + { + return $value && is_callable($value, syntax_only: true); + } + + + /** + * Checks if the value is a valid UTF-8 string. + */ + public static function isUnicode(mixed $value): bool + { + return is_string($value) && preg_match('##u', $value); + } + + + /** + * Checks if the value is 0, '', false or null. + * @return ($value is 0|0.0|''|false|null ? true : false) + */ + public static function isNone(mixed $value): bool + { + return $value == null; // intentionally == + } + + + /** @internal */ + public static function isMixed(): bool + { + return true; + } + + + /** + * Checks if a variable is a zero-based integer indexed array. + * @deprecated use Nette\Utils\Arrays::isList + * @return ($value is list ? true : false) + */ + public static function isList(mixed $value): bool + { + return Arrays::isList($value); + } + + + /** + * 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 + { + if ($value === null || !(isset($range[0]) || isset($range[1]))) { + return false; + } + + $limit = $range[0] ?? $range[1]; + if (is_string($limit)) { + $value = (string) $value; + } elseif ($limit instanceof \DateTimeInterface) { + if (!$value instanceof \DateTimeInterface) { + return false; + } + } elseif (is_numeric($value)) { + $value *= 1; + } else { + return false; + } + + return (!isset($range[0]) || ($value >= $range[0])) && (!isset($range[1]) || ($value <= $range[1])); + } + + + /** + * Checks if the value is a valid email address. It does not verify that the domain actually exists, only the syntax is verified. + */ + public static function isEmail(string $value): bool + { + $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part + $alpha = "a-z\x80-\xFF"; // superset of IDN + return (bool) preg_match(<<<XX + (^(?n) + ("([ !#-[\\]-~]*|\\\\[ -~])+"|$atom+(\\.$atom+)*) # quoted or unquoted + @ + ([0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)+ # domain - RFC 1034 + [$alpha]([-0-9$alpha]{0,17}[$alpha])? # top domain + $)Dix + XX, $value); + } + + + /** + * Checks if the value is a valid URL address. + */ + 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,5})? # port + (/\\S*)? # path + (\\?\\S*)? # query + (\\#\\S*)? # fragment + $)Dix + XX, $value); + } + + + /** + * Checks if the value is a valid URI address, that is, actually a string beginning with a syntactically valid schema. + */ + public static function isUri(string $value): bool + { + return (bool) preg_match('#^[a-z\d+.-]+:\S+$#Di', $value); + } + + + /** + * Checks whether the input is a class, interface or trait. + * @deprecated + */ + public static function isType(string $type): bool + { + return class_exists($type) || interface_exists($type) || trait_exists($type); + } + + + /** + * Checks whether the input is a valid PHP identifier. + */ + public static function isPhpIdentifier(string $value): bool + { + return preg_match('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#D', $value) === 1; + } + + + /** + * Determines if type is PHP built-in type. Otherwise, it is the class name. + */ + public static function isBuiltinType(string $type): bool + { + return isset(self::BuiltinTypes[strtolower($type)]); + } + + + /** + * Determines if type is special class name self/parent/static. + */ + public static function isClassKeyword(string $name): bool + { + return (bool) preg_match('#^(self|parent|static)$#Di', $name); + } + + + /** + * Checks whether the given type declaration is syntactically valid. + */ + public static function isTypeDeclaration(string $type): bool + { + return (bool) preg_match(<<<'XX' + ~((?n) + \?? (?<type> \\? (?<name> [a-zA-Z_\x7f-\xff][\w\x7f-\xff]*) (\\ (?&name))* ) | + (?<intersection> (?&type) (& (?&type))+ ) | + (?<upart> (?&type) | \( (?&intersection) \) ) (\| (?&upart))+ + )$~xAD + XX, $type); + } +} diff --git a/vendor/nette/utils/src/Utils/exceptions.php b/vendor/nette/utils/src/Utils/exceptions.php new file mode 100644 index 0000000..ba1cdfe --- /dev/null +++ b/vendor/nette/utils/src/Utils/exceptions.php @@ -0,0 +1,64 @@ +<?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; + + +/** + * An error occurred while working with the image. + */ +class ImageException extends \Exception +{ +} + + +/** + * The image file is invalid or in an unsupported format. + */ +class UnknownImageFileException extends ImageException +{ +} + + +/** + * JSON encoding or decoding failed. + */ +class JsonException extends \JsonException +{ +} + + +/** + * Regular expression pattern or execution failed. + */ +class RegexpException extends \Exception +{ +} + + +/** + * Type validation failed. The value doesn't match the expected type constraints. + */ +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/nette/utils/src/compatibility.php b/vendor/nette/utils/src/compatibility.php new file mode 100644 index 0000000..b3e90d0 --- /dev/null +++ b/vendor/nette/utils/src/compatibility.php @@ -0,0 +1,30 @@ +<?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; + +if (false) { + /** @deprecated use Nette\HtmlStringable */ + interface IHtmlString extends Nette\HtmlStringable + { + } +} elseif (!interface_exists(IHtmlString::class)) { + class_alias(Nette\HtmlStringable::class, IHtmlString::class); +} + +namespace Nette\Localization; + +if (false) { + /** @deprecated use Nette\Localization\Translator */ + interface ITranslator extends Translator + { + } +} elseif (!interface_exists(ITranslator::class)) { + class_alias(Translator::class, ITranslator::class); +} diff --git a/vendor/nette/utils/src/exceptions.php b/vendor/nette/utils/src/exceptions.php new file mode 100644 index 0000000..d3a4421 --- /dev/null +++ b/vendor/nette/utils/src/exceptions.php @@ -0,0 +1,112 @@ +<?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; + + +/** + * The value is outside the allowed range. + */ +class ArgumentOutOfRangeException extends \InvalidArgumentException +{ +} + + +/** + * The object is in a state that does not allow the requested operation. + */ +class InvalidStateException extends \RuntimeException +{ +} + + +/** + * The requested feature is not implemented. + */ +class NotImplementedException extends \LogicException +{ +} + + +/** + * The requested operation is not supported. + */ +class NotSupportedException extends \LogicException +{ +} + + +/** + * The requested feature is deprecated and no longer available. + */ +class DeprecatedException extends NotSupportedException +{ +} + + +/** + * Cannot access the requested class property or method. + */ +class MemberAccessException extends \Error +{ +} + + +/** + * Failed to read from or write to a file or stream. + */ +class IOException extends \RuntimeException +{ +} + + +/** + * The requested file does not exist. + */ +class FileNotFoundException extends IOException +{ +} + + +/** + * The requested directory does not exist. + */ +class DirectoryNotFoundException extends IOException +{ +} + + +/** + * The provided argument has invalid type or format. + */ +class InvalidArgumentException extends \InvalidArgumentException +{ +} + + +/** + * The requested array or collection index does not exist. + */ +class OutOfRangeException extends \OutOfRangeException +{ +} + + +/** + * The returned value has unexpected type or format. + */ +class UnexpectedValueException extends \UnexpectedValueException +{ +} + + +/** + * Houston, we have a problem. + */ +class ShouldNotHappenException extends \LogicException +{ +} diff --git a/vendor/nikic/fast-route/.hhconfig b/vendor/nikic/fast-route/.hhconfig new file mode 100644 index 0000000..0c2153c --- /dev/null +++ b/vendor/nikic/fast-route/.hhconfig @@ -0,0 +1 @@ +assume_php=false diff --git a/vendor/nikic/fast-route/FastRoute.hhi b/vendor/nikic/fast-route/FastRoute.hhi new file mode 100644 index 0000000..8d50738 --- /dev/null +++ b/vendor/nikic/fast-route/FastRoute.hhi @@ -0,0 +1,126 @@ +<?hh // decl + +namespace FastRoute { + class BadRouteException extends \LogicException { + } + + interface RouteParser { + public function parse(string $route): array<array>; + } + + class RouteCollector { + public function __construct(RouteParser $routeParser, DataGenerator $dataGenerator); + public function addRoute(mixed $httpMethod, string $route, mixed $handler): void; + public function getData(): array; + } + + class Route { + public function __construct(string $httpMethod, mixed $handler, string $regex, array $variables); + public function matches(string $str): bool; + } + + interface DataGenerator { + public function addRoute(string $httpMethod, array $routeData, mixed $handler); + public function getData(): array; + } + + interface Dispatcher { + const int NOT_FOUND = 0; + const int FOUND = 1; + const int METHOD_NOT_ALLOWED = 2; + public function dispatch(string $httpMethod, string $uri): array; + } + + function simpleDispatcher( + (function(RouteCollector): void) $routeDefinitionCallback, + shape( + ?'routeParser' => classname<RouteParser>, + ?'dataGenerator' => classname<DataGenerator>, + ?'dispatcher' => classname<Dispatcher>, + ?'routeCollector' => classname<RouteCollector>, + ) $options = shape()): Dispatcher; + + function cachedDispatcher( + (function(RouteCollector): void) $routeDefinitionCallback, + shape( + ?'routeParser' => classname<RouteParser>, + ?'dataGenerator' => classname<DataGenerator>, + ?'dispatcher' => classname<Dispatcher>, + ?'routeCollector' => classname<RouteCollector>, + ?'cacheDisabled' => bool, + ?'cacheFile' => string, + ) $options = shape()): Dispatcher; +} + +namespace FastRoute\DataGenerator { + abstract class RegexBasedAbstract implements \FastRoute\DataGenerator { + protected abstract function getApproxChunkSize(); + protected abstract function processChunk($regexToRoutesMap); + + public function addRoute(string $httpMethod, array $routeData, mixed $handler): void; + public function getData(): array; + } + + class CharCountBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array<string, string> $regexToRoutesMap): array<string, mixed>; + } + + class GroupCountBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array<string, string> $regexToRoutesMap): array<string, mixed>; + } + + class GroupPosBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array<string, string> $regexToRoutesMap): array<string, mixed>; + } + + class MarkBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array<string, string> $regexToRoutesMap): array<string, mixed>; + } +} + +namespace FastRoute\Dispatcher { + abstract class RegexBasedAbstract implements \FastRoute\Dispatcher { + protected abstract function dispatchVariableRoute(array<array> $routeData, string $uri): array; + + public function dispatch(string $httpMethod, string $uri): array; + } + + class GroupPosBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array<array> $routeData, string $uri): array; + } + + class GroupCountBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array<array> $routeData, string $uri): array; + } + + class CharCountBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array<array> $routeData, string $uri): array; + } + + class MarkBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array<array> $routeData, string $uri): array; + } +} + +namespace FastRoute\RouteParser { + class Std implements \FastRoute\RouteParser { + const string VARIABLE_REGEX = <<<'REGEX' +\{ + \s* ([a-zA-Z][a-zA-Z0-9_]*) \s* + (?: + : \s* ([^{}]*(?:\{(?-1)\}[^{}]*)*) + )? +\} +REGEX; + const string DEFAULT_DISPATCH_REGEX = '[^/]+'; + public function parse(string $route): array<array>; + } +} diff --git a/vendor/nikic/fast-route/LICENSE b/vendor/nikic/fast-route/LICENSE new file mode 100644 index 0000000..478e764 --- /dev/null +++ b/vendor/nikic/fast-route/LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2013 by Nikita Popov. + +Some rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * The names of the contributors may not be used to endorse or + promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/nikic/fast-route/README.md b/vendor/nikic/fast-route/README.md new file mode 100644 index 0000000..de1925e --- /dev/null +++ b/vendor/nikic/fast-route/README.md @@ -0,0 +1,313 @@ +FastRoute - Fast request router for PHP +======================================= + +This library provides a fast implementation of a regular expression based router. [Blog post explaining how the +implementation works and why it is fast.][blog_post] + +Install +------- + +To install with composer: + +```sh +composer require nikic/fast-route +``` + +Requires PHP 5.4 or newer. + +Usage +----- + +Here's a basic usage example: + +```php +<?php + +require '/path/to/vendor/autoload.php'; + +$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) { + $r->addRoute('GET', '/users', 'get_all_users_handler'); + // {id} must be a number (\d+) + $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler'); + // The /{title} suffix is optional + $r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler'); +}); + +// Fetch method and URI from somewhere +$httpMethod = $_SERVER['REQUEST_METHOD']; +$uri = $_SERVER['REQUEST_URI']; + +// Strip query string (?foo=bar) and decode URI +if (false !== $pos = strpos($uri, '?')) { + $uri = substr($uri, 0, $pos); +} +$uri = rawurldecode($uri); + +$routeInfo = $dispatcher->dispatch($httpMethod, $uri); +switch ($routeInfo[0]) { + case FastRoute\Dispatcher::NOT_FOUND: + // ... 404 Not Found + break; + case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: + $allowedMethods = $routeInfo[1]; + // ... 405 Method Not Allowed + break; + case FastRoute\Dispatcher::FOUND: + $handler = $routeInfo[1]; + $vars = $routeInfo[2]; + // ... call $handler with $vars + break; +} +``` + +### Defining routes + +The routes are defined by calling the `FastRoute\simpleDispatcher()` function, which accepts +a callable taking a `FastRoute\RouteCollector` instance. The routes are added by calling +`addRoute()` on the collector instance: + +```php +$r->addRoute($method, $routePattern, $handler); +``` + +The `$method` is an uppercase HTTP method string for which a certain route should match. It +is possible to specify multiple valid methods using an array: + +```php +// These two calls +$r->addRoute('GET', '/test', 'handler'); +$r->addRoute('POST', '/test', 'handler'); +// Are equivalent to this one call +$r->addRoute(['GET', 'POST'], '/test', 'handler'); +``` + +By default the `$routePattern` uses a syntax where `{foo}` specifies a placeholder with name `foo` +and matching the regex `[^/]+`. To adjust the pattern the placeholder matches, you can specify +a custom pattern by writing `{bar:[0-9]+}`. Some examples: + +```php +// Matches /user/42, but not /user/xyz +$r->addRoute('GET', '/user/{id:\d+}', 'handler'); + +// Matches /user/foobar, but not /user/foo/bar +$r->addRoute('GET', '/user/{name}', 'handler'); + +// Matches /user/foo/bar as well +$r->addRoute('GET', '/user/{name:.+}', 'handler'); +``` + +Custom patterns for route placeholders cannot use capturing groups. For example `{lang:(en|de)}` +is not a valid placeholder, because `()` is a capturing group. Instead you can use either +`{lang:en|de}` or `{lang:(?:en|de)}`. + +Furthermore parts of the route enclosed in `[...]` are considered optional, so that `/foo[bar]` +will match both `/foo` and `/foobar`. Optional parts are only supported in a trailing position, +not in the middle of a route. + +```php +// This route +$r->addRoute('GET', '/user/{id:\d+}[/{name}]', 'handler'); +// Is equivalent to these two routes +$r->addRoute('GET', '/user/{id:\d+}', 'handler'); +$r->addRoute('GET', '/user/{id:\d+}/{name}', 'handler'); + +// Multiple nested optional parts are possible as well +$r->addRoute('GET', '/user[/{id:\d+}[/{name}]]', 'handler'); + +// This route is NOT valid, because optional parts can only occur at the end +$r->addRoute('GET', '/user[/{id:\d+}]/{name}', 'handler'); +``` + +The `$handler` parameter does not necessarily have to be a callback, it could also be a controller +class name or any other kind of data you wish to associate with the route. FastRoute only tells you +which handler corresponds to your URI, how you interpret it is up to you. + +#### Shortcut methods for common request methods + +For the `GET`, `POST`, `PUT`, `PATCH`, `DELETE` and `HEAD` request methods shortcut methods are available. For example: + +```php +$r->get('/get-route', 'get_handler'); +$r->post('/post-route', 'post_handler'); +``` + +Is equivalent to: + +```php +$r->addRoute('GET', '/get-route', 'get_handler'); +$r->addRoute('POST', '/post-route', 'post_handler'); +``` + +#### Route Groups + +Additionally, you can specify routes inside of a group. All routes defined inside a group will have a common prefix. + +For example, defining your routes as: + +```php +$r->addGroup('/admin', function (RouteCollector $r) { + $r->addRoute('GET', '/do-something', 'handler'); + $r->addRoute('GET', '/do-another-thing', 'handler'); + $r->addRoute('GET', '/do-something-else', 'handler'); +}); +``` + +Will have the same result as: + + ```php +$r->addRoute('GET', '/admin/do-something', 'handler'); +$r->addRoute('GET', '/admin/do-another-thing', 'handler'); +$r->addRoute('GET', '/admin/do-something-else', 'handler'); + ``` + +Nested groups are also supported, in which case the prefixes of all the nested groups are combined. + +### Caching + +The reason `simpleDispatcher` accepts a callback for defining the routes is to allow seamless +caching. By using `cachedDispatcher` instead of `simpleDispatcher` you can cache the generated +routing data and construct the dispatcher from the cached information: + +```php +<?php + +$dispatcher = FastRoute\cachedDispatcher(function(FastRoute\RouteCollector $r) { + $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); + $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1'); + $r->addRoute('GET', '/user/{name}', 'handler2'); +}, [ + 'cacheFile' => __DIR__ . '/route.cache', /* required */ + 'cacheDisabled' => IS_DEBUG_ENABLED, /* optional, enabled by default */ +]); +``` + +The second parameter to the function is an options array, which can be used to specify the cache +file location, among other things. + +### Dispatching a URI + +A URI is dispatched by calling the `dispatch()` method of the created dispatcher. This method +accepts the HTTP method and a URI. Getting those two bits of information (and normalizing them +appropriately) is your job - this library is not bound to the PHP web SAPIs. + +The `dispatch()` method returns an array whose first element contains a status code. It is one +of `Dispatcher::NOT_FOUND`, `Dispatcher::METHOD_NOT_ALLOWED` and `Dispatcher::FOUND`. For the +method not allowed status the second array element contains a list of HTTP methods allowed for +the supplied URI. For example: + + [FastRoute\Dispatcher::METHOD_NOT_ALLOWED, ['GET', 'POST']] + +> **NOTE:** The HTTP specification requires that a `405 Method Not Allowed` response include the +`Allow:` header to detail available methods for the requested resource. Applications using FastRoute +should use the second array element to add this header when relaying a 405 response. + +For the found status the second array element is the handler that was associated with the route +and the third array element is a dictionary of placeholder names to their values. For example: + + /* Routing against GET /user/nikic/42 */ + + [FastRoute\Dispatcher::FOUND, 'handler0', ['name' => 'nikic', 'id' => '42']] + +### Overriding the route parser and dispatcher + +The routing process makes use of three components: A route parser, a data generator and a +dispatcher. The three components adhere to the following interfaces: + +```php +<?php + +namespace FastRoute; + +interface RouteParser { + public function parse($route); +} + +interface DataGenerator { + public function addRoute($httpMethod, $routeData, $handler); + public function getData(); +} + +interface Dispatcher { + const NOT_FOUND = 0, FOUND = 1, METHOD_NOT_ALLOWED = 2; + + public function dispatch($httpMethod, $uri); +} +``` + +The route parser takes a route pattern string and converts it into an array of route infos, where +each route info is again an array of it's parts. The structure is best understood using an example: + + /* The route /user/{id:\d+}[/{name}] converts to the following array: */ + [ + [ + '/user/', + ['id', '\d+'], + ], + [ + '/user/', + ['id', '\d+'], + '/', + ['name', '[^/]+'], + ], + ] + +This array can then be passed to the `addRoute()` method of a data generator. After all routes have +been added the `getData()` of the generator is invoked, which returns all the routing data required +by the dispatcher. The format of this data is not further specified - it is tightly coupled to +the corresponding dispatcher. + +The dispatcher accepts the routing data via a constructor and provides a `dispatch()` method, which +you're already familiar with. + +The route parser can be overwritten individually (to make use of some different pattern syntax), +however the data generator and dispatcher should always be changed as a pair, as the output from +the former is tightly coupled to the input of the latter. The reason the generator and the +dispatcher are separate is that only the latter is needed when using caching (as the output of +the former is what is being cached.) + +When using the `simpleDispatcher` / `cachedDispatcher` functions from above the override happens +through the options array: + +```php +<?php + +$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) { + /* ... */ +}, [ + 'routeParser' => 'FastRoute\\RouteParser\\Std', + 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', + 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', +]); +``` + +The above options array corresponds to the defaults. By replacing `GroupCountBased` by +`GroupPosBased` you could switch to a different dispatching strategy. + +### A Note on HEAD Requests + +The HTTP spec requires servers to [support both GET and HEAD methods][2616-511]: + +> The methods GET and HEAD MUST be supported by all general-purpose servers + +To avoid forcing users to manually register HEAD routes for each resource we fallback to matching an +available GET route for a given resource. The PHP web SAPI transparently removes the entity body +from HEAD responses so this behavior has no effect on the vast majority of users. + +However, implementers using FastRoute outside the web SAPI environment (e.g. a custom server) MUST +NOT send entity bodies generated in response to HEAD requests. If you are a non-SAPI user this is +*your responsibility*; FastRoute has no purview to prevent you from breaking HTTP in such cases. + +Finally, note that applications MAY always specify their own HEAD method route for a given +resource to bypass this behavior entirely. + +### Credits + +This library is based on a router that [Levi Morrison][levi] implemented for the Aerys server. + +A large number of tests, as well as HTTP compliance considerations, were provided by [Daniel Lowrey][rdlowrey]. + + +[2616-511]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1 "RFC 2616 Section 5.1.1" +[blog_post]: http://nikic.github.io/2014/02/18/Fast-request-routing-using-regular-expressions.html +[levi]: https://github.com/morrisonlevi +[rdlowrey]: https://github.com/rdlowrey diff --git a/vendor/nikic/fast-route/composer.json b/vendor/nikic/fast-route/composer.json new file mode 100644 index 0000000..fb446a2 --- /dev/null +++ b/vendor/nikic/fast-route/composer.json @@ -0,0 +1,24 @@ +{ + "name": "nikic/fast-route", + "description": "Fast request router for PHP", + "keywords": ["routing", "router"], + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "autoload": { + "psr-4": { + "FastRoute\\": "src/" + }, + "files": ["src/functions.php"] + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35|~5.7" + } +} diff --git a/vendor/nikic/fast-route/src/BadRouteException.php b/vendor/nikic/fast-route/src/BadRouteException.php new file mode 100644 index 0000000..62262ec --- /dev/null +++ b/vendor/nikic/fast-route/src/BadRouteException.php @@ -0,0 +1,7 @@ +<?php + +namespace FastRoute; + +class BadRouteException extends \LogicException +{ +} diff --git a/vendor/nikic/fast-route/src/DataGenerator.php b/vendor/nikic/fast-route/src/DataGenerator.php new file mode 100644 index 0000000..af577cd --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator.php @@ -0,0 +1,26 @@ +<?php + +namespace FastRoute; + +interface DataGenerator +{ + /** + * Adds a route to the data generator. The route data uses the + * same format that is returned by RouterParser::parser(). + * + * The handler doesn't necessarily need to be a callable, it + * can be arbitrary data that will be returned when the route + * matches. + * + * @param string $httpMethod + * @param array $routeData + * @param mixed $handler + */ + public function addRoute($httpMethod, $routeData, $handler); + + /** + * Returns dispatcher data in some unspecified format, which + * depends on the used method of dispatch. + */ + public function getData(); +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/CharCountBased.php b/vendor/nikic/fast-route/src/DataGenerator/CharCountBased.php new file mode 100644 index 0000000..3cfeed6 --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/CharCountBased.php @@ -0,0 +1,31 @@ +<?php + +namespace FastRoute\DataGenerator; + +class CharCountBased extends RegexBasedAbstract +{ + protected function getApproxChunkSize() + { + return 30; + } + + protected function processChunk($regexToRoutesMap) + { + $routeMap = []; + $regexes = []; + + $suffixLen = 0; + $suffix = ''; + $count = count($regexToRoutesMap); + foreach ($regexToRoutesMap as $regex => $route) { + $suffixLen++; + $suffix .= "\t"; + + $regexes[] = '(?:' . $regex . '/(\t{' . $suffixLen . '})\t{' . ($count - $suffixLen) . '})'; + $routeMap[$suffix] = [$route->handler, $route->variables]; + } + + $regex = '~^(?|' . implode('|', $regexes) . ')$~'; + return ['regex' => $regex, 'suffix' => '/' . $suffix, 'routeMap' => $routeMap]; + } +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/GroupCountBased.php b/vendor/nikic/fast-route/src/DataGenerator/GroupCountBased.php new file mode 100644 index 0000000..54d9a05 --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/GroupCountBased.php @@ -0,0 +1,30 @@ +<?php + +namespace FastRoute\DataGenerator; + +class GroupCountBased extends RegexBasedAbstract +{ + protected function getApproxChunkSize() + { + return 10; + } + + protected function processChunk($regexToRoutesMap) + { + $routeMap = []; + $regexes = []; + $numGroups = 0; + foreach ($regexToRoutesMap as $regex => $route) { + $numVariables = count($route->variables); + $numGroups = max($numGroups, $numVariables); + + $regexes[] = $regex . str_repeat('()', $numGroups - $numVariables); + $routeMap[$numGroups + 1] = [$route->handler, $route->variables]; + + ++$numGroups; + } + + $regex = '~^(?|' . implode('|', $regexes) . ')$~'; + return ['regex' => $regex, 'routeMap' => $routeMap]; + } +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/GroupPosBased.php b/vendor/nikic/fast-route/src/DataGenerator/GroupPosBased.php new file mode 100644 index 0000000..fc4dc0a --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/GroupPosBased.php @@ -0,0 +1,27 @@ +<?php + +namespace FastRoute\DataGenerator; + +class GroupPosBased extends RegexBasedAbstract +{ + protected function getApproxChunkSize() + { + return 10; + } + + protected function processChunk($regexToRoutesMap) + { + $routeMap = []; + $regexes = []; + $offset = 1; + foreach ($regexToRoutesMap as $regex => $route) { + $regexes[] = $regex; + $routeMap[$offset] = [$route->handler, $route->variables]; + + $offset += count($route->variables); + } + + $regex = '~^(?:' . implode('|', $regexes) . ')$~'; + return ['regex' => $regex, 'routeMap' => $routeMap]; + } +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/MarkBased.php b/vendor/nikic/fast-route/src/DataGenerator/MarkBased.php new file mode 100644 index 0000000..0aebed9 --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/MarkBased.php @@ -0,0 +1,27 @@ +<?php + +namespace FastRoute\DataGenerator; + +class MarkBased extends RegexBasedAbstract +{ + protected function getApproxChunkSize() + { + return 30; + } + + protected function processChunk($regexToRoutesMap) + { + $routeMap = []; + $regexes = []; + $markName = 'a'; + foreach ($regexToRoutesMap as $regex => $route) { + $regexes[] = $regex . '(*MARK:' . $markName . ')'; + $routeMap[$markName] = [$route->handler, $route->variables]; + + ++$markName; + } + + $regex = '~^(?|' . implode('|', $regexes) . ')$~'; + return ['regex' => $regex, 'routeMap' => $routeMap]; + } +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php b/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php new file mode 100644 index 0000000..6457290 --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php @@ -0,0 +1,186 @@ +<?php + +namespace FastRoute\DataGenerator; + +use FastRoute\BadRouteException; +use FastRoute\DataGenerator; +use FastRoute\Route; + +abstract class RegexBasedAbstract implements DataGenerator +{ + /** @var mixed[][] */ + protected $staticRoutes = []; + + /** @var Route[][] */ + protected $methodToRegexToRoutesMap = []; + + /** + * @return int + */ + abstract protected function getApproxChunkSize(); + + /** + * @return mixed[] + */ + abstract protected function processChunk($regexToRoutesMap); + + public function addRoute($httpMethod, $routeData, $handler) + { + if ($this->isStaticRoute($routeData)) { + $this->addStaticRoute($httpMethod, $routeData, $handler); + } else { + $this->addVariableRoute($httpMethod, $routeData, $handler); + } + } + + /** + * @return mixed[] + */ + public function getData() + { + if (empty($this->methodToRegexToRoutesMap)) { + return [$this->staticRoutes, []]; + } + + return [$this->staticRoutes, $this->generateVariableRouteData()]; + } + + /** + * @return mixed[] + */ + private function generateVariableRouteData() + { + $data = []; + foreach ($this->methodToRegexToRoutesMap as $method => $regexToRoutesMap) { + $chunkSize = $this->computeChunkSize(count($regexToRoutesMap)); + $chunks = array_chunk($regexToRoutesMap, $chunkSize, true); + $data[$method] = array_map([$this, 'processChunk'], $chunks); + } + return $data; + } + + /** + * @param int + * @return int + */ + private function computeChunkSize($count) + { + $numParts = max(1, round($count / $this->getApproxChunkSize())); + return (int) ceil($count / $numParts); + } + + /** + * @param mixed[] + * @return bool + */ + private function isStaticRoute($routeData) + { + return count($routeData) === 1 && is_string($routeData[0]); + } + + private function addStaticRoute($httpMethod, $routeData, $handler) + { + $routeStr = $routeData[0]; + + if (isset($this->staticRoutes[$httpMethod][$routeStr])) { + throw new BadRouteException(sprintf( + 'Cannot register two routes matching "%s" for method "%s"', + $routeStr, $httpMethod + )); + } + + if (isset($this->methodToRegexToRoutesMap[$httpMethod])) { + foreach ($this->methodToRegexToRoutesMap[$httpMethod] as $route) { + if ($route->matches($routeStr)) { + throw new BadRouteException(sprintf( + 'Static route "%s" is shadowed by previously defined variable route "%s" for method "%s"', + $routeStr, $route->regex, $httpMethod + )); + } + } + } + + $this->staticRoutes[$httpMethod][$routeStr] = $handler; + } + + private function addVariableRoute($httpMethod, $routeData, $handler) + { + list($regex, $variables) = $this->buildRegexForRoute($routeData); + + if (isset($this->methodToRegexToRoutesMap[$httpMethod][$regex])) { + throw new BadRouteException(sprintf( + 'Cannot register two routes matching "%s" for method "%s"', + $regex, $httpMethod + )); + } + + $this->methodToRegexToRoutesMap[$httpMethod][$regex] = new Route( + $httpMethod, $handler, $regex, $variables + ); + } + + /** + * @param mixed[] + * @return mixed[] + */ + private function buildRegexForRoute($routeData) + { + $regex = ''; + $variables = []; + foreach ($routeData as $part) { + if (is_string($part)) { + $regex .= preg_quote($part, '~'); + continue; + } + + list($varName, $regexPart) = $part; + + if (isset($variables[$varName])) { + throw new BadRouteException(sprintf( + 'Cannot use the same placeholder "%s" twice', $varName + )); + } + + if ($this->regexHasCapturingGroups($regexPart)) { + throw new BadRouteException(sprintf( + 'Regex "%s" for parameter "%s" contains a capturing group', + $regexPart, $varName + )); + } + + $variables[$varName] = $varName; + $regex .= '(' . $regexPart . ')'; + } + + return [$regex, $variables]; + } + + /** + * @param string + * @return bool + */ + private function regexHasCapturingGroups($regex) + { + if (false === strpos($regex, '(')) { + // Needs to have at least a ( to contain a capturing group + return false; + } + + // Semi-accurate detection for capturing groups + return (bool) preg_match( + '~ + (?: + \(\?\( + | \[ [^\]\\\\]* (?: \\\\ . [^\]\\\\]* )* \] + | \\\\ . + ) (*SKIP)(*FAIL) | + \( + (?! + \? (?! <(?![!=]) | P< | \' ) + | \* + ) + ~x', + $regex + ); + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher.php b/vendor/nikic/fast-route/src/Dispatcher.php new file mode 100644 index 0000000..4ae72a3 --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher.php @@ -0,0 +1,26 @@ +<?php + +namespace FastRoute; + +interface Dispatcher +{ + const NOT_FOUND = 0; + const FOUND = 1; + const METHOD_NOT_ALLOWED = 2; + + /** + * Dispatches against the provided HTTP method verb and URI. + * + * Returns array with one of the following formats: + * + * [self::NOT_FOUND] + * [self::METHOD_NOT_ALLOWED, ['GET', 'OTHER_ALLOWED_METHODS']] + * [self::FOUND, $handler, ['varName' => 'value', ...]] + * + * @param string $httpMethod + * @param string $uri + * + * @return array + */ + public function dispatch($httpMethod, $uri); +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/CharCountBased.php b/vendor/nikic/fast-route/src/Dispatcher/CharCountBased.php new file mode 100644 index 0000000..ef1eec1 --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/CharCountBased.php @@ -0,0 +1,31 @@ +<?php + +namespace FastRoute\Dispatcher; + +class CharCountBased extends RegexBasedAbstract +{ + public function __construct($data) + { + list($this->staticRouteMap, $this->variableRouteData) = $data; + } + + protected function dispatchVariableRoute($routeData, $uri) + { + foreach ($routeData as $data) { + if (!preg_match($data['regex'], $uri . $data['suffix'], $matches)) { + continue; + } + + list($handler, $varNames) = $data['routeMap'][end($matches)]; + + $vars = []; + $i = 0; + foreach ($varNames as $varName) { + $vars[$varName] = $matches[++$i]; + } + return [self::FOUND, $handler, $vars]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/GroupCountBased.php b/vendor/nikic/fast-route/src/Dispatcher/GroupCountBased.php new file mode 100644 index 0000000..493e7a9 --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/GroupCountBased.php @@ -0,0 +1,31 @@ +<?php + +namespace FastRoute\Dispatcher; + +class GroupCountBased extends RegexBasedAbstract +{ + public function __construct($data) + { + list($this->staticRouteMap, $this->variableRouteData) = $data; + } + + protected function dispatchVariableRoute($routeData, $uri) + { + foreach ($routeData as $data) { + if (!preg_match($data['regex'], $uri, $matches)) { + continue; + } + + list($handler, $varNames) = $data['routeMap'][count($matches)]; + + $vars = []; + $i = 0; + foreach ($varNames as $varName) { + $vars[$varName] = $matches[++$i]; + } + return [self::FOUND, $handler, $vars]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/GroupPosBased.php b/vendor/nikic/fast-route/src/Dispatcher/GroupPosBased.php new file mode 100644 index 0000000..498220e --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/GroupPosBased.php @@ -0,0 +1,33 @@ +<?php + +namespace FastRoute\Dispatcher; + +class GroupPosBased extends RegexBasedAbstract +{ + public function __construct($data) + { + list($this->staticRouteMap, $this->variableRouteData) = $data; + } + + protected function dispatchVariableRoute($routeData, $uri) + { + foreach ($routeData as $data) { + if (!preg_match($data['regex'], $uri, $matches)) { + continue; + } + + // find first non-empty match + for ($i = 1; '' === $matches[$i]; ++$i); + + list($handler, $varNames) = $data['routeMap'][$i]; + + $vars = []; + foreach ($varNames as $varName) { + $vars[$varName] = $matches[$i++]; + } + return [self::FOUND, $handler, $vars]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/MarkBased.php b/vendor/nikic/fast-route/src/Dispatcher/MarkBased.php new file mode 100644 index 0000000..22eb09b --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/MarkBased.php @@ -0,0 +1,31 @@ +<?php + +namespace FastRoute\Dispatcher; + +class MarkBased extends RegexBasedAbstract +{ + public function __construct($data) + { + list($this->staticRouteMap, $this->variableRouteData) = $data; + } + + protected function dispatchVariableRoute($routeData, $uri) + { + foreach ($routeData as $data) { + if (!preg_match($data['regex'], $uri, $matches)) { + continue; + } + + list($handler, $varNames) = $data['routeMap'][$matches['MARK']]; + + $vars = []; + $i = 0; + foreach ($varNames as $varName) { + $vars[$varName] = $matches[++$i]; + } + return [self::FOUND, $handler, $vars]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php b/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php new file mode 100644 index 0000000..206e879 --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php @@ -0,0 +1,88 @@ +<?php + +namespace FastRoute\Dispatcher; + +use FastRoute\Dispatcher; + +abstract class RegexBasedAbstract implements Dispatcher +{ + /** @var mixed[][] */ + protected $staticRouteMap = []; + + /** @var mixed[] */ + protected $variableRouteData = []; + + /** + * @return mixed[] + */ + abstract protected function dispatchVariableRoute($routeData, $uri); + + public function dispatch($httpMethod, $uri) + { + if (isset($this->staticRouteMap[$httpMethod][$uri])) { + $handler = $this->staticRouteMap[$httpMethod][$uri]; + return [self::FOUND, $handler, []]; + } + + $varRouteData = $this->variableRouteData; + if (isset($varRouteData[$httpMethod])) { + $result = $this->dispatchVariableRoute($varRouteData[$httpMethod], $uri); + if ($result[0] === self::FOUND) { + return $result; + } + } + + // For HEAD requests, attempt fallback to GET + if ($httpMethod === 'HEAD') { + if (isset($this->staticRouteMap['GET'][$uri])) { + $handler = $this->staticRouteMap['GET'][$uri]; + return [self::FOUND, $handler, []]; + } + if (isset($varRouteData['GET'])) { + $result = $this->dispatchVariableRoute($varRouteData['GET'], $uri); + if ($result[0] === self::FOUND) { + return $result; + } + } + } + + // If nothing else matches, try fallback routes + if (isset($this->staticRouteMap['*'][$uri])) { + $handler = $this->staticRouteMap['*'][$uri]; + return [self::FOUND, $handler, []]; + } + if (isset($varRouteData['*'])) { + $result = $this->dispatchVariableRoute($varRouteData['*'], $uri); + if ($result[0] === self::FOUND) { + return $result; + } + } + + // Find allowed methods for this URI by matching against all other HTTP methods as well + $allowedMethods = []; + + foreach ($this->staticRouteMap as $method => $uriMap) { + if ($method !== $httpMethod && isset($uriMap[$uri])) { + $allowedMethods[] = $method; + } + } + + foreach ($varRouteData as $method => $routeData) { + if ($method === $httpMethod) { + continue; + } + + $result = $this->dispatchVariableRoute($routeData, $uri); + if ($result[0] === self::FOUND) { + $allowedMethods[] = $method; + } + } + + // If there are no allowed methods the route simply does not exist + if ($allowedMethods) { + return [self::METHOD_NOT_ALLOWED, $allowedMethods]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Route.php b/vendor/nikic/fast-route/src/Route.php new file mode 100644 index 0000000..e1bf7dd --- /dev/null +++ b/vendor/nikic/fast-route/src/Route.php @@ -0,0 +1,47 @@ +<?php + +namespace FastRoute; + +class Route +{ + /** @var string */ + public $httpMethod; + + /** @var string */ + public $regex; + + /** @var array */ + public $variables; + + /** @var mixed */ + public $handler; + + /** + * Constructs a route (value object). + * + * @param string $httpMethod + * @param mixed $handler + * @param string $regex + * @param array $variables + */ + public function __construct($httpMethod, $handler, $regex, $variables) + { + $this->httpMethod = $httpMethod; + $this->handler = $handler; + $this->regex = $regex; + $this->variables = $variables; + } + + /** + * Tests whether this route matches the given string. + * + * @param string $str + * + * @return bool + */ + public function matches($str) + { + $regex = '~^' . $this->regex . '$~'; + return (bool) preg_match($regex, $str); + } +} diff --git a/vendor/nikic/fast-route/src/RouteCollector.php b/vendor/nikic/fast-route/src/RouteCollector.php new file mode 100644 index 0000000..6e5aa6a --- /dev/null +++ b/vendor/nikic/fast-route/src/RouteCollector.php @@ -0,0 +1,165 @@ +<?php + +namespace FastRoute; + +class RouteCollector +{ + /** @var RouteParser */ + protected $routeParser; + + /** @var DataGenerator */ + protected $dataGenerator; + + /** @var string */ + protected $currentGroupPrefix; + + /** + * Constructs a route collector. + * + * @param RouteParser $routeParser + * @param DataGenerator $dataGenerator + */ + public function __construct(RouteParser $routeParser, DataGenerator $dataGenerator) + { + $this->routeParser = $routeParser; + $this->dataGenerator = $dataGenerator; + $this->currentGroupPrefix = ''; + } + + /** + * Adds a route to the collection. + * + * The syntax used in the $route string depends on the used route parser. + * + * @param string|string[] $httpMethod + * @param string $route + * @param mixed $handler + */ + public function addRoute($httpMethod, $route, $handler) + { + $route = $this->currentGroupPrefix . $route; + $routeDatas = $this->routeParser->parse($route); + foreach ((array) $httpMethod as $method) { + foreach ($routeDatas as $routeData) { + $this->dataGenerator->addRoute($method, $routeData, $handler); + } + } + } + + /** + * Create a route group with a common prefix. + * + * All routes created in the passed callback will have the given group prefix prepended. + * + * @param string $prefix + * @param callable $callback + */ + public function addGroup($prefix, callable $callback) + { + $previousGroupPrefix = $this->currentGroupPrefix; + $this->currentGroupPrefix = $previousGroupPrefix . $prefix; + $callback($this); + $this->currentGroupPrefix = $previousGroupPrefix; + } + + /** + * Adds a GET route to the collection + * + * This is simply an alias of $this->addRoute('GET', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function get($route, $handler) + { + $this->addRoute('GET', $route, $handler); + } + + /** + * Adds a POST route to the collection + * + * This is simply an alias of $this->addRoute('POST', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function post($route, $handler) + { + $this->addRoute('POST', $route, $handler); + } + + /** + * Adds a PUT route to the collection + * + * This is simply an alias of $this->addRoute('PUT', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function put($route, $handler) + { + $this->addRoute('PUT', $route, $handler); + } + + /** + * Adds a DELETE route to the collection + * + * This is simply an alias of $this->addRoute('DELETE', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function delete($route, $handler) + { + $this->addRoute('DELETE', $route, $handler); + } + + /** + * Adds a PATCH route to the collection + * + * This is simply an alias of $this->addRoute('PATCH', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function patch($route, $handler) + { + $this->addRoute('PATCH', $route, $handler); + } + + /** + * Adds a HEAD route to the collection + * + * This is simply an alias of $this->addRoute('HEAD', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function head($route, $handler) + { + $this->addRoute('HEAD', $route, $handler); + } + + /** + * Adds an OPTIONS route to the collection + * + * This is simply an alias of $this->addRoute('OPTIONS', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function options($route, $handler) + { + $this->addRoute('OPTIONS', $route, $handler); + } + + /** + * Returns the collected route data, as provided by the data generator. + * + * @return array + */ + public function getData() + { + return $this->dataGenerator->getData(); + } +} diff --git a/vendor/nikic/fast-route/src/RouteParser.php b/vendor/nikic/fast-route/src/RouteParser.php new file mode 100644 index 0000000..6a7685c --- /dev/null +++ b/vendor/nikic/fast-route/src/RouteParser.php @@ -0,0 +1,37 @@ +<?php + +namespace FastRoute; + +interface RouteParser +{ + /** + * Parses a route string into multiple route data arrays. + * + * The expected output is defined using an example: + * + * For the route string "/fixedRoutePart/{varName}[/moreFixed/{varName2:\d+}]", if {varName} is interpreted as + * a placeholder and [...] is interpreted as an optional route part, the expected result is: + * + * [ + * // first route: without optional part + * [ + * "/fixedRoutePart/", + * ["varName", "[^/]+"], + * ], + * // second route: with optional part + * [ + * "/fixedRoutePart/", + * ["varName", "[^/]+"], + * "/moreFixed/", + * ["varName2", [0-9]+"], + * ], + * ] + * + * Here one route string was converted into two route data arrays. + * + * @param string $route Route string to parse + * + * @return mixed[][] Array of route data arrays + */ + public function parse($route); +} diff --git a/vendor/nikic/fast-route/src/RouteParser/Std.php b/vendor/nikic/fast-route/src/RouteParser/Std.php new file mode 100644 index 0000000..4fbdee1 --- /dev/null +++ b/vendor/nikic/fast-route/src/RouteParser/Std.php @@ -0,0 +1,87 @@ +<?php + +namespace FastRoute\RouteParser; + +use FastRoute\BadRouteException; +use FastRoute\RouteParser; + +/** + * Parses route strings of the following form: + * + * "/user/{name}[/{id:[0-9]+}]" + */ +class Std implements RouteParser +{ + const VARIABLE_REGEX = <<<'REGEX' +\{ + \s* ([a-zA-Z_][a-zA-Z0-9_-]*) \s* + (?: + : \s* ([^{}]*(?:\{(?-1)\}[^{}]*)*) + )? +\} +REGEX; + const DEFAULT_DISPATCH_REGEX = '[^/]+'; + + public function parse($route) + { + $routeWithoutClosingOptionals = rtrim($route, ']'); + $numOptionals = strlen($route) - strlen($routeWithoutClosingOptionals); + + // Split on [ while skipping placeholders + $segments = preg_split('~' . self::VARIABLE_REGEX . '(*SKIP)(*F) | \[~x', $routeWithoutClosingOptionals); + if ($numOptionals !== count($segments) - 1) { + // If there are any ] in the middle of the route, throw a more specific error message + if (preg_match('~' . self::VARIABLE_REGEX . '(*SKIP)(*F) | \]~x', $routeWithoutClosingOptionals)) { + throw new BadRouteException('Optional segments can only occur at the end of a route'); + } + throw new BadRouteException("Number of opening '[' and closing ']' does not match"); + } + + $currentRoute = ''; + $routeDatas = []; + foreach ($segments as $n => $segment) { + if ($segment === '' && $n !== 0) { + throw new BadRouteException('Empty optional part'); + } + + $currentRoute .= $segment; + $routeDatas[] = $this->parsePlaceholders($currentRoute); + } + return $routeDatas; + } + + /** + * Parses a route string that does not contain optional segments. + * + * @param string + * @return mixed[] + */ + private function parsePlaceholders($route) + { + if (!preg_match_all( + '~' . self::VARIABLE_REGEX . '~x', $route, $matches, + PREG_OFFSET_CAPTURE | PREG_SET_ORDER + )) { + return [$route]; + } + + $offset = 0; + $routeData = []; + foreach ($matches as $set) { + if ($set[0][1] > $offset) { + $routeData[] = substr($route, $offset, $set[0][1] - $offset); + } + $routeData[] = [ + $set[1][0], + isset($set[2]) ? trim($set[2][0]) : self::DEFAULT_DISPATCH_REGEX + ]; + $offset = $set[0][1] + strlen($set[0][0]); + } + + if ($offset !== strlen($route)) { + $routeData[] = substr($route, $offset); + } + + return $routeData; + } +} diff --git a/vendor/nikic/fast-route/src/bootstrap.php b/vendor/nikic/fast-route/src/bootstrap.php new file mode 100644 index 0000000..0bce3a4 --- /dev/null +++ b/vendor/nikic/fast-route/src/bootstrap.php @@ -0,0 +1,12 @@ +<?php + +namespace FastRoute; + +require __DIR__ . '/functions.php'; + +spl_autoload_register(function ($class) { + if (strpos($class, 'FastRoute\\') === 0) { + $name = substr($class, strlen('FastRoute')); + require __DIR__ . strtr($name, '\\', DIRECTORY_SEPARATOR) . '.php'; + } +}); diff --git a/vendor/nikic/fast-route/src/functions.php b/vendor/nikic/fast-route/src/functions.php new file mode 100644 index 0000000..876a5d9 --- /dev/null +++ b/vendor/nikic/fast-route/src/functions.php @@ -0,0 +1,74 @@ +<?php + +namespace FastRoute; + +if (!function_exists('FastRoute\simpleDispatcher')) { + /** + * @param callable $routeDefinitionCallback + * @param array $options + * + * @return Dispatcher + */ + function simpleDispatcher(callable $routeDefinitionCallback, array $options = []) + { + $options += [ + 'routeParser' => 'FastRoute\\RouteParser\\Std', + 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', + 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', + 'routeCollector' => 'FastRoute\\RouteCollector', + ]; + + /** @var RouteCollector $routeCollector */ + $routeCollector = new $options['routeCollector']( + new $options['routeParser'], new $options['dataGenerator'] + ); + $routeDefinitionCallback($routeCollector); + + return new $options['dispatcher']($routeCollector->getData()); + } + + /** + * @param callable $routeDefinitionCallback + * @param array $options + * + * @return Dispatcher + */ + function cachedDispatcher(callable $routeDefinitionCallback, array $options = []) + { + $options += [ + 'routeParser' => 'FastRoute\\RouteParser\\Std', + 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', + 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', + 'routeCollector' => 'FastRoute\\RouteCollector', + 'cacheDisabled' => false, + ]; + + if (!isset($options['cacheFile'])) { + throw new \LogicException('Must specify "cacheFile" option'); + } + + if (!$options['cacheDisabled'] && file_exists($options['cacheFile'])) { + $dispatchData = require $options['cacheFile']; + if (!is_array($dispatchData)) { + throw new \RuntimeException('Invalid cache file "' . $options['cacheFile'] . '"'); + } + return new $options['dispatcher']($dispatchData); + } + + $routeCollector = new $options['routeCollector']( + new $options['routeParser'], new $options['dataGenerator'] + ); + $routeDefinitionCallback($routeCollector); + + /** @var RouteCollector $routeCollector */ + $dispatchData = $routeCollector->getData(); + if (!$options['cacheDisabled']) { + file_put_contents( + $options['cacheFile'], + '<?php return ' . var_export($dispatchData, true) . ';' + ); + } + + return new $options['dispatcher']($dispatchData); + } +} diff --git a/vendor/phpoption/phpoption/LICENSE b/vendor/phpoption/phpoption/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/vendor/phpoption/phpoption/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/vendor/phpoption/phpoption/composer.json b/vendor/phpoption/phpoption/composer.json new file mode 100644 index 0000000..6343947 --- /dev/null +++ b/vendor/phpoption/phpoption/composer.json @@ -0,0 +1,50 @@ +{ + "name": "phpoption/phpoption", + "description": "Option Type for PHP", + "keywords": ["php", "option", "language", "type"], + "license": "Apache-2.0", + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "https://github.com/schmittjoh" + }, + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + } + ], + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.54 || ^9.6.36 || ^10.5.64 || ^11.5.56 || ^12.5.33" + }, + "autoload": { + "psr-4": { + "PhpOption\\": "src/PhpOption/" + } + }, + "autoload-dev": { + "psr-4": { + "PhpOption\\Tests\\": "tests/PhpOption/Tests/" + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist" + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "1.9-dev" + } + } +} diff --git a/vendor/phpoption/phpoption/src/PhpOption/LazyOption.php b/vendor/phpoption/phpoption/src/PhpOption/LazyOption.php new file mode 100644 index 0000000..45a9386 --- /dev/null +++ b/vendor/phpoption/phpoption/src/PhpOption/LazyOption.php @@ -0,0 +1,177 @@ +<?php + +/* + * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace PhpOption; + +use Traversable; + +/** + * @template-covariant T + * + * @extends Option<T> + */ +final class LazyOption extends Option +{ + /** @var callable(mixed...):(Option<T>) */ + private $callback; + + /** @var array<int, mixed> */ + private $arguments; + + /** @var Option<T>|null */ + private $option; + + /** + * @template S + * @param callable(mixed...):(Option<S>) $callback + * @param array<int, mixed> $arguments + * + * @return LazyOption<S> + */ + public static function create($callback, array $arguments = []): self + { + return new self($callback, $arguments); + } + + /** + * @param callable(mixed...):(Option<T>) $callback + * @param array<int, mixed> $arguments + * + * @throws \InvalidArgumentException If the callback is not callable. + */ + public function __construct($callback, array $arguments = []) + { + if (!is_callable($callback)) { + throw new \InvalidArgumentException('Invalid callback given'); + } + + $this->callback = $callback; + $this->arguments = $arguments; + } + + public function isDefined(): bool + { + return $this->option()->isDefined(); + } + + public function isEmpty(): bool + { + return $this->option()->isEmpty(); + } + + public function get() + { + return $this->option()->get(); + } + + public function getOrElse($default) + { + return $this->option()->getOrElse($default); + } + + public function getOrCall($callable) + { + return $this->option()->getOrCall($callable); + } + + public function getOrThrow(\Exception $ex) + { + return $this->option()->getOrThrow($ex); + } + + public function orElse(Option $else) + { + return $this->option()->orElse($else); + } + + public function ifDefined($callable) + { + $this->option()->forAll($callable); + } + + public function forAll($callable) + { + return $this->option()->forAll($callable); + } + + public function map($callable) + { + return $this->option()->map($callable); + } + + public function flatMap($callable) + { + return $this->option()->flatMap($callable); + } + + public function filter($callable) + { + return $this->option()->filter($callable); + } + + public function filterNot($callable) + { + return $this->option()->filterNot($callable); + } + + public function select($value) + { + return $this->option()->select($value); + } + + public function reject($value) + { + return $this->option()->reject($value); + } + + /** + * @return Traversable<T> + */ + public function getIterator(): Traversable + { + return $this->option()->getIterator(); + } + + public function foldLeft($initialValue, $callable) + { + return $this->option()->foldLeft($initialValue, $callable); + } + + public function foldRight($initialValue, $callable) + { + return $this->option()->foldRight($initialValue, $callable); + } + + /** + * @return Option<T> + */ + private function option(): Option + { + if (null === $this->option) { + /** @var mixed */ + $option = call_user_func_array($this->callback, $this->arguments); + if ($option instanceof Option) { + $this->option = $option; + } else { + throw new \RuntimeException(sprintf('Expected instance of %s', Option::class)); + } + } + + return $this->option; + } +} diff --git a/vendor/phpoption/phpoption/src/PhpOption/None.php b/vendor/phpoption/phpoption/src/PhpOption/None.php new file mode 100644 index 0000000..1a13ccd --- /dev/null +++ b/vendor/phpoption/phpoption/src/PhpOption/None.php @@ -0,0 +1,168 @@ +<?php + +/* + * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace PhpOption; + +use EmptyIterator; + +/** + * @extends Option<never> + */ +final class None extends Option +{ + /** @var None|null */ + private static $instance; + + /** + * @return None + */ + public static function create(): self + { + if (null === self::$instance) { + self::$instance = new self(); + } + + return self::$instance; + } + + public function get() + { + throw new \RuntimeException('None has no value.'); + } + + /** + * @template S + * + * @param callable():S $callable + * + * @return S + */ + public function getOrCall($callable) + { + return $callable(); + } + + /** + * @template S + * + * @param S $default + * + * @return S + */ + public function getOrElse($default) + { + return $default; + } + + public function getOrThrow(\Exception $ex) + { + throw $ex; + } + + public function isEmpty(): bool + { + return true; + } + + public function isDefined(): bool + { + return false; + } + + public function orElse(Option $else) + { + return $else; + } + + public function ifDefined($callable) + { + // Just do nothing in that case. + } + + public function forAll($callable) + { + return $this; + } + + public function map($callable) + { + return $this; + } + + public function flatMap($callable) + { + return $this; + } + + public function filter($callable) + { + return $this; + } + + public function filterNot($callable) + { + return $this; + } + + public function select($value) + { + return $this; + } + + public function reject($value) + { + return $this; + } + + public function getIterator(): EmptyIterator + { + return new EmptyIterator(); + } + + /** + * @template S + * @template R + * + * @param S $initialValue + * @param callable(S, never):R $callable + * + * @return S + */ + public function foldLeft($initialValue, $callable) + { + return $initialValue; + } + + /** + * @template S + * @template R + * + * @param S $initialValue + * @param callable(never, S):R $callable + * + * @return S + */ + public function foldRight($initialValue, $callable) + { + return $initialValue; + } + + private function __construct() + { + } +} diff --git a/vendor/phpoption/phpoption/src/PhpOption/Option.php b/vendor/phpoption/phpoption/src/PhpOption/Option.php new file mode 100644 index 0000000..aad9d79 --- /dev/null +++ b/vendor/phpoption/phpoption/src/PhpOption/Option.php @@ -0,0 +1,443 @@ +<?php + +/* + * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace PhpOption; + +use ArrayAccess; +use IteratorAggregate; + +/** + * @template-covariant T + * + * @implements IteratorAggregate<T> + */ +abstract class Option implements IteratorAggregate +{ + /** + * Creates an option given a return value. + * + * This is intended for consuming existing APIs and allows you to easily + * convert them to an option. By default, we treat ``null`` as the None + * case, and everything else as Some. + * + * @template S + * + * @param S $value The actual return value. + * @param mixed $noneValue The value which should be considered "None"; + * null by default. + * + * @return Option<S> + */ + public static function fromValue($value, $noneValue = null) + { + if ($value === $noneValue) { + return None::create(); + } + + return new Some($value); + } + + /** + * Creates an option from an array's value. + * + * If the key does not exist in the array, the array is not actually an + * array, or the array's value at the given key is null, None is returned. + * Otherwise, Some is returned wrapping the value at the given key. + * + * @template K of array-key + * @template S + * + * @param array<K,S>|ArrayAccess<K,S>|null $array A potential array or + * \ArrayAccess value. + * @param K|null $key The key to check. + * + * @return Option<S> + */ + public static function fromArraysValue($array, $key) + { + if ($key === null || !(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) { + return None::create(); + } + + return new Some($array[$key]); + } + + /** + * Creates a lazy-option with the given callback. + * + * This is also a helper constructor for lazy-consuming existing APIs where + * the return value is not yet an option. By default, we treat ``null`` as + * the None case, and everything else as Some. + * + * @template S + * + * @param callable(mixed...):S $callback The callback to evaluate. + * @param array<int, mixed> $arguments The arguments for the callback. + * @param mixed $noneValue The value which should be considered "None"; + * null by default. + * + * @return LazyOption<S> + */ + public static function fromReturn($callback, array $arguments = [], $noneValue = null) + { + return new LazyOption(static function () use ($callback, $arguments, $noneValue) { + /** @var mixed */ + $return = call_user_func_array($callback, $arguments); + + if ($return === $noneValue) { + return None::create(); + } + + /** @var S $return */ + + return new Some($return); + }); + } + + /** + * Option factory, which creates new option based on passed value. + * + * If the value is already an option, it is returned as is. If the value is + * callable, a LazyOption invoking it is returned; should the callback + * return an Option, it is used directly, otherwise the result is passed + * to Option::fromValue(). In all other cases, the value is passed to + * Option::fromValue() directly. + * + * @template S + * + * @param Option<S>|callable():(S|Option<S>)|S $value + * @param mixed $noneValue Used for the None-check when + * $value is not an Option. + * + * @return Option<S>|LazyOption<S> + */ + public static function ensure($value, $noneValue = null) + { + if ($value instanceof self) { + return $value; + } elseif (is_callable($value)) { + return new LazyOption(static function () use ($value, $noneValue) { + /** @var mixed */ + $return = $value(); + + if ($return instanceof self) { + return $return; + } else { + return self::fromValue($return, $noneValue); + } + }); + } else { + return self::fromValue($value, $noneValue); + } + } + + /** + * Lift a function so that it accepts Option as parameters. + * + * We return a new closure that wraps the original callback. If any of the + * parameters passed to the lifted function is empty, the function will + * return None. Otherwise, we will pass all parameters to the original + * callback and return the value inside a new Option, unless an Option is + * returned from the function, in which case, we use that. + * + * @param callable $callback + * @param mixed $noneValue + * + * @return callable(mixed...):(Option<mixed>|LazyOption<mixed>) + */ + public static function lift($callback, $noneValue = null) + { + return static function () use ($callback, $noneValue) { + /** @var array<int, mixed> */ + $args = func_get_args(); + + $reduced_args = array_reduce( + $args, + /** @param bool $status */ + static function ($status, self $o) { + return $o->isEmpty() ? true : $status; + }, + false + ); + // if at least one parameter is empty, return None + if ($reduced_args) { + return None::create(); + } + + $args = array_map( + /** @return T */ + static function (self $o) { + // it is safe to do so because the fold above checked + // that all arguments are of type Some + /** @var T */ + return $o->get(); + }, + $args + ); + + return self::ensure(call_user_func_array($callback, $args), $noneValue); + }; + } + + /** + * Returns the value if available, or throws an exception otherwise. + * + * @throws \RuntimeException If value is not available. + * + * @return T + */ + abstract public function get(); + + /** + * Returns the value if available, or the default value if not. + * + * @template S + * + * @param S $default + * + * @return T|S + */ + abstract public function getOrElse($default); + + /** + * Returns the value if available, or the results of the callable. + * + * This is preferable over ``getOrElse`` if the computation of the default + * value is expensive. + * + * @template S + * + * @param callable():S $callable + * + * @return T|S + */ + abstract public function getOrCall($callable); + + /** + * Returns the value if available, or throws the passed exception. + * + * @param \Exception $ex + * + * @throws \Exception If value is not available. + * + * @return T + */ + abstract public function getOrThrow(\Exception $ex); + + /** + * Returns true if no value is available, false otherwise. + * + * @return bool + */ + abstract public function isEmpty(); + + /** + * Returns true if a value is available, false otherwise. + * + * @return bool + */ + abstract public function isDefined(); + + /** + * Returns this option if non-empty, or the passed option otherwise. + * + * This can be used to try multiple alternatives, and is especially useful + * with lazy evaluating options: + * + * ```php + * $repo->findSomething() + * ->orElse(new LazyOption(array($repo, 'findSomethingElse'))) + * ->orElse(new LazyOption(array($repo, 'createSomething'))); + * ``` + * + * @template U + * + * @param Option<U> $else + * + * @return Option<T|U> + */ + abstract public function orElse(self $else); + + /** + * This is similar to map() below except that the return value has no meaning; + * the passed callable is simply executed if the option is non-empty, and + * ignored if the option is empty. + * + * In all cases, the return value of the callable is discarded. + * + * ```php + * $comment->getMaybeFile()->ifDefined(function($file) { + * // Do something with $file here. + * }); + * ``` + * + * If you're looking for something like ``ifEmpty``, you can use ``getOrCall`` + * and ``getOrElse`` in these cases. + * + * @deprecated Use forAll() instead. + * + * @param callable(T):mixed $callable + * + * @return void + */ + abstract public function ifDefined($callable); + + /** + * This is similar to map() except that the return value of the callable has no meaning. + * + * The passed callable is simply executed if the option is non-empty, and ignored if the + * option is empty. This method is preferred for callables with side-effects, while map() + * is intended for callables without side-effects. + * + * @param callable(T):mixed $callable + * + * @return Option<T> + */ + abstract public function forAll($callable); + + /** + * Applies the callable to the value of the option if it is non-empty, + * and returns the return value of the callable wrapped in Some(). + * + * If the option is empty, then the callable is not applied. + * + * ```php + * (new Some("foo"))->map('strtoupper')->get(); // "FOO" + * ``` + * + * @template S + * + * @param callable(T):S $callable + * + * @return Option<S> + */ + abstract public function map($callable); + + /** + * Applies the callable to the value of the option if it is non-empty, and + * returns the return value of the callable directly. + * + * In contrast to ``map``, the return value of the callable is expected to + * be an Option itself; it is not automatically wrapped in Some(). + * + * @template S + * + * @param callable(T):Option<S> $callable must return an Option + * + * @return Option<S> + */ + abstract public function flatMap($callable); + + /** + * If the option is empty, it is returned immediately without applying the callable. + * + * If the option is non-empty, the callable is applied, and if it returns true, + * the option itself is returned; otherwise, None is returned. + * + * @param callable(T):bool $callable + * + * @return Option<T> + */ + abstract public function filter($callable); + + /** + * If the option is empty, it is returned immediately without applying the callable. + * + * If the option is non-empty, the callable is applied, and if it returns false, + * the option itself is returned; otherwise, None is returned. + * + * @param callable(T):bool $callable + * + * @return Option<T> + */ + abstract public function filterNot($callable); + + /** + * If the option is empty, it is returned immediately. + * + * If the option is non-empty, and its value does not equal the passed value + * (via a shallow comparison ===), then None is returned. Otherwise, the + * Option is returned. + * + * In other words, this will filter all but the passed value. + * + * @param mixed $value + * + * @return Option<T> + */ + abstract public function select($value); + + /** + * If the option is empty, it is returned immediately. + * + * If the option is non-empty, and its value does equal the passed value (via + * a shallow comparison ===), then None is returned; otherwise, the Option is + * returned. + * + * In other words, this will let all values through except the passed value. + * + * @param mixed $value + * + * @return Option<T> + */ + abstract public function reject($value); + + /** + * Binary operator for the initial value and the option's value. + * + * If empty, the initial value is returned. If non-empty, the callable + * receives the initial value and the option's value as arguments. + * + * ```php + * + * $some = new Some(5); + * $none = None::create(); + * $result = $some->foldLeft(1, function($a, $b) { return $a + $b; }); // int(6) + * $result = $none->foldLeft(1, function($a, $b) { return $a + $b; }); // int(1) + * + * // This can be used instead of something like the following: + * $option = Option::fromValue($integerOrNull); + * $result = 1; + * if ( ! $option->isEmpty()) { + * $result += $option->get(); + * } + * ``` + * + * @template S + * @template R + * + * @param S $initialValue + * @param callable(S, T):R $callable + * + * @return S|R + */ + abstract public function foldLeft($initialValue, $callable); + + /** + * foldLeft() but with reversed arguments for the callable. + * + * @template S + * @template R + * + * @param S $initialValue + * @param callable(T, S):R $callable + * + * @return S|R + */ + abstract public function foldRight($initialValue, $callable); +} diff --git a/vendor/phpoption/phpoption/src/PhpOption/Some.php b/vendor/phpoption/phpoption/src/PhpOption/Some.php new file mode 100644 index 0000000..6f5a418 --- /dev/null +++ b/vendor/phpoption/phpoption/src/PhpOption/Some.php @@ -0,0 +1,197 @@ +<?php + +/* + * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace PhpOption; + +use ArrayIterator; + +/** + * @template-covariant T + * + * @extends Option<T> + */ +final class Some extends Option +{ + /** @var T */ + private $value; + + /** + * @param T $value + */ + public function __construct($value) + { + $this->value = $value; + } + + /** + * @template U + * + * @param U $value + * + * @return Some<U> + */ + public static function create($value): self + { + return new self($value); + } + + public function isDefined(): bool + { + return true; + } + + public function isEmpty(): bool + { + return false; + } + + public function get() + { + return $this->value; + } + + /** + * @param mixed $default + * + * @return T + */ + public function getOrElse($default) + { + return $this->value; + } + + /** + * @param callable():mixed $callable + * + * @return T + */ + public function getOrCall($callable) + { + return $this->value; + } + + public function getOrThrow(\Exception $ex) + { + return $this->value; + } + + public function orElse(Option $else) + { + return $this; + } + + public function ifDefined($callable) + { + $this->forAll($callable); + } + + public function forAll($callable) + { + $callable($this->value); + + return $this; + } + + public function map($callable) + { + return new self($callable($this->value)); + } + + public function flatMap($callable) + { + /** @var mixed */ + $rs = $callable($this->value); + if (!$rs instanceof Option) { + throw new \RuntimeException('Callables passed to flatMap() must return an Option. Maybe you should use map() instead?'); + } + + return $rs; + } + + public function filter($callable) + { + if (true === $callable($this->value)) { + return $this; + } + + return None::create(); + } + + public function filterNot($callable) + { + if (false === $callable($this->value)) { + return $this; + } + + return None::create(); + } + + public function select($value) + { + if ($this->value === $value) { + return $this; + } + + return None::create(); + } + + public function reject($value) + { + if ($this->value === $value) { + return None::create(); + } + + return $this; + } + + /** + * @return ArrayIterator<int, T> + */ + public function getIterator(): ArrayIterator + { + return new ArrayIterator([$this->value]); + } + + /** + * @template S + * @template R + * + * @param S $initialValue + * @param callable(S, T):R $callable + * + * @return R + */ + public function foldLeft($initialValue, $callable) + { + return $callable($initialValue, $this->value); + } + + /** + * @template S + * @template R + * + * @param S $initialValue + * @param callable(T, S):R $callable + * + * @return R + */ + public function foldRight($initialValue, $callable) + { + return $callable($this->value, $initialValue); + } +} diff --git a/vendor/psr/container/.gitignore b/vendor/psr/container/.gitignore new file mode 100644 index 0000000..b2395aa --- /dev/null +++ b/vendor/psr/container/.gitignore @@ -0,0 +1,3 @@ +composer.lock +composer.phar +/vendor/ diff --git a/vendor/psr/container/LICENSE b/vendor/psr/container/LICENSE new file mode 100644 index 0000000..2877a48 --- /dev/null +++ b/vendor/psr/container/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2016 container-interop +Copyright (c) 2016 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/psr/container/README.md b/vendor/psr/container/README.md new file mode 100644 index 0000000..1b9d9e5 --- /dev/null +++ b/vendor/psr/container/README.md @@ -0,0 +1,13 @@ +Container interface +============== + +This repository holds all interfaces related to [PSR-11 (Container Interface)][psr-url]. + +Note that this is not a Container implementation of its own. It is merely abstractions that describe the components of a Dependency Injection Container. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-11/ +[package-url]: https://packagist.org/packages/psr/container +[implementation-url]: https://packagist.org/providers/psr/container-implementation + diff --git a/vendor/psr/container/composer.json b/vendor/psr/container/composer.json new file mode 100644 index 0000000..baf6cd1 --- /dev/null +++ b/vendor/psr/container/composer.json @@ -0,0 +1,27 @@ +{ + "name": "psr/container", + "type": "library", + "description": "Common Container Interface (PHP FIG PSR-11)", + "keywords": ["psr", "psr-11", "container", "container-interop", "container-interface"], + "homepage": "https://github.com/php-fig/container", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=7.4.0" + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + } +} diff --git a/vendor/psr/container/src/ContainerExceptionInterface.php b/vendor/psr/container/src/ContainerExceptionInterface.php new file mode 100644 index 0000000..0f213f2 --- /dev/null +++ b/vendor/psr/container/src/ContainerExceptionInterface.php @@ -0,0 +1,12 @@ +<?php + +namespace Psr\Container; + +use Throwable; + +/** + * Base interface representing a generic exception in a container. + */ +interface ContainerExceptionInterface extends Throwable +{ +} diff --git a/vendor/psr/container/src/ContainerInterface.php b/vendor/psr/container/src/ContainerInterface.php new file mode 100644 index 0000000..b2cad40 --- /dev/null +++ b/vendor/psr/container/src/ContainerInterface.php @@ -0,0 +1,36 @@ +<?php + +declare(strict_types=1); + +namespace Psr\Container; + +/** + * Describes the interface of a container that exposes methods to read its entries. + */ +interface ContainerInterface +{ + /** + * Finds an entry of the container by its identifier and returns it. + * + * @param string $id Identifier of the entry to look for. + * + * @throws NotFoundExceptionInterface No entry was found for **this** identifier. + * @throws ContainerExceptionInterface Error while retrieving the entry. + * + * @return mixed Entry. + */ + public function get(string $id); + + /** + * Returns true if the container can return an entry for the given identifier. + * Returns false otherwise. + * + * `has($id)` returning true does not mean that `get($id)` will not throw an exception. + * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`. + * + * @param string $id Identifier of the entry to look for. + * + * @return bool + */ + public function has(string $id): bool; +} diff --git a/vendor/psr/container/src/NotFoundExceptionInterface.php b/vendor/psr/container/src/NotFoundExceptionInterface.php new file mode 100644 index 0000000..650bf46 --- /dev/null +++ b/vendor/psr/container/src/NotFoundExceptionInterface.php @@ -0,0 +1,10 @@ +<?php + +namespace Psr\Container; + +/** + * No entry was found in the container. + */ +interface NotFoundExceptionInterface extends ContainerExceptionInterface +{ +} diff --git a/vendor/psr/event-dispatcher/.editorconfig b/vendor/psr/event-dispatcher/.editorconfig new file mode 100644 index 0000000..164f092 --- /dev/null +++ b/vendor/psr/event-dispatcher/.editorconfig @@ -0,0 +1,15 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[Makefile] +indent_style = tab diff --git a/vendor/psr/event-dispatcher/.gitignore b/vendor/psr/event-dispatcher/.gitignore new file mode 100644 index 0000000..3a9875b --- /dev/null +++ b/vendor/psr/event-dispatcher/.gitignore @@ -0,0 +1,2 @@ +/vendor/ +composer.lock diff --git a/vendor/psr/event-dispatcher/LICENSE b/vendor/psr/event-dispatcher/LICENSE new file mode 100644 index 0000000..3f1559b --- /dev/null +++ b/vendor/psr/event-dispatcher/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 PHP-FIG + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/psr/event-dispatcher/README.md b/vendor/psr/event-dispatcher/README.md new file mode 100644 index 0000000..294214a --- /dev/null +++ b/vendor/psr/event-dispatcher/README.md @@ -0,0 +1,6 @@ +PSR Event Dispatcher +==================== + +This repository holds the interfaces related to [PSR-14](http://www.php-fig.org/psr/psr-14/). + +Note that this is not an Event Dispatcher implementation of its own. It is merely interfaces that describe the components of an Event Dispatcher. See the specification for more details. diff --git a/vendor/psr/event-dispatcher/composer.json b/vendor/psr/event-dispatcher/composer.json new file mode 100644 index 0000000..667a714 --- /dev/null +++ b/vendor/psr/event-dispatcher/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/event-dispatcher", + "description": "Standard interfaces for event handling.", + "type": "library", + "keywords": ["psr", "psr-14", "events"], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "require": { + "php": ">=7.2.0" + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php b/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php new file mode 100644 index 0000000..4306fa9 --- /dev/null +++ b/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php @@ -0,0 +1,21 @@ +<?php +declare(strict_types=1); + +namespace Psr\EventDispatcher; + +/** + * Defines a dispatcher for events. + */ +interface EventDispatcherInterface +{ + /** + * Provide all relevant listeners with an event to process. + * + * @param object $event + * The object to process. + * + * @return object + * The Event that was passed, now modified by listeners. + */ + public function dispatch(object $event); +} diff --git a/vendor/psr/event-dispatcher/src/ListenerProviderInterface.php b/vendor/psr/event-dispatcher/src/ListenerProviderInterface.php new file mode 100644 index 0000000..bdacb6e --- /dev/null +++ b/vendor/psr/event-dispatcher/src/ListenerProviderInterface.php @@ -0,0 +1,19 @@ +<?php +declare(strict_types=1); + +namespace Psr\EventDispatcher; + +/** + * Mapper from an event to the listeners that are applicable to that event. + */ +interface ListenerProviderInterface +{ + /** + * @param object $event + * An event for which to return the relevant listeners. + * @return iterable[callable] + * An iterable (array, iterator, or generator) of callables. Each + * callable MUST be type-compatible with $event. + */ + public function getListenersForEvent(object $event) : iterable; +} diff --git a/vendor/psr/event-dispatcher/src/StoppableEventInterface.php b/vendor/psr/event-dispatcher/src/StoppableEventInterface.php new file mode 100644 index 0000000..5955081 --- /dev/null +++ b/vendor/psr/event-dispatcher/src/StoppableEventInterface.php @@ -0,0 +1,26 @@ +<?php +declare(strict_types=1); + +namespace Psr\EventDispatcher; + +/** + * An Event whose processing may be interrupted when the event has been handled. + * + * A Dispatcher implementation MUST check to determine if an Event + * is marked as stopped after each listener is called. If it is then it should + * return immediately without calling any further Listeners. + */ +interface StoppableEventInterface +{ + /** + * Is propagation stopped? + * + * This will typically only be used by the Dispatcher to determine if the + * previous listener halted propagation. + * + * @return bool + * True if the Event is complete and no further listeners should be called. + * False to continue calling listeners. + */ + public function isPropagationStopped() : bool; +} diff --git a/vendor/psr/http-client/CHANGELOG.md b/vendor/psr/http-client/CHANGELOG.md new file mode 100644 index 0000000..babba7c --- /dev/null +++ b/vendor/psr/http-client/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.3 + +Add `source` link in composer.json. No code changes. + +## 1.0.2 + +Allow PSR-7 (psr/http-message) 2.0. No code changes. + +## 1.0.1 + +Allow installation with PHP 8. No code changes. + +## 1.0.0 + +First stable release. No changes since 0.3.0. + +## 0.3.0 + +Added Interface suffix on exceptions + +## 0.2.0 + +All exceptions are in `Psr\Http\Client` namespace + +## 0.1.0 + +First release diff --git a/vendor/psr/http-client/LICENSE b/vendor/psr/http-client/LICENSE new file mode 100644 index 0000000..cd5e002 --- /dev/null +++ b/vendor/psr/http-client/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/psr/http-client/README.md b/vendor/psr/http-client/README.md new file mode 100644 index 0000000..84af5c5 --- /dev/null +++ b/vendor/psr/http-client/README.md @@ -0,0 +1,12 @@ +HTTP Client +=========== + +This repository holds all the common code related to [PSR-18 (HTTP Client)][psr-url]. + +Note that this is not a HTTP Client implementation of its own. It is merely abstractions that describe the components of a HTTP Client. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-18 +[package-url]: https://packagist.org/packages/psr/http-client +[implementation-url]: https://packagist.org/providers/psr/http-client-implementation diff --git a/vendor/psr/http-client/composer.json b/vendor/psr/http-client/composer.json new file mode 100644 index 0000000..6fed350 --- /dev/null +++ b/vendor/psr/http-client/composer.json @@ -0,0 +1,30 @@ +{ + "name": "psr/http-client", + "description": "Common interface for HTTP clients", + "keywords": ["psr", "psr-18", "http", "http-client"], + "homepage": "https://github.com/php-fig/http-client", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/http-client/src/ClientExceptionInterface.php b/vendor/psr/http-client/src/ClientExceptionInterface.php new file mode 100644 index 0000000..aa0b9cf --- /dev/null +++ b/vendor/psr/http-client/src/ClientExceptionInterface.php @@ -0,0 +1,10 @@ +<?php + +namespace Psr\Http\Client; + +/** + * Every HTTP client related exception MUST implement this interface. + */ +interface ClientExceptionInterface extends \Throwable +{ +} diff --git a/vendor/psr/http-client/src/ClientInterface.php b/vendor/psr/http-client/src/ClientInterface.php new file mode 100644 index 0000000..ad99fd4 --- /dev/null +++ b/vendor/psr/http-client/src/ClientInterface.php @@ -0,0 +1,20 @@ +<?php + +namespace Psr\Http\Client; + +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + +interface ClientInterface +{ + /** + * Sends a PSR-7 request and returns a PSR-7 response. + * + * @param RequestInterface $request + * + * @return ResponseInterface + * + * @throws \Psr\Http\Client\ClientExceptionInterface If an error happens while processing the request. + */ + public function sendRequest(RequestInterface $request): ResponseInterface; +} diff --git a/vendor/psr/http-client/src/NetworkExceptionInterface.php b/vendor/psr/http-client/src/NetworkExceptionInterface.php new file mode 100644 index 0000000..4a11627 --- /dev/null +++ b/vendor/psr/http-client/src/NetworkExceptionInterface.php @@ -0,0 +1,24 @@ +<?php + +namespace Psr\Http\Client; + +use Psr\Http\Message\RequestInterface; + +/** + * Thrown when the request cannot be completed because of network issues. + * + * There is no response object as this exception is thrown when no response has been received. + * + * Example: the target host name can not be resolved or the connection failed. + */ +interface NetworkExceptionInterface extends ClientExceptionInterface +{ + /** + * Returns the request. + * + * The request object MAY be a different object from the one passed to ClientInterface::sendRequest() + * + * @return RequestInterface + */ + public function getRequest(): RequestInterface; +} diff --git a/vendor/psr/http-client/src/RequestExceptionInterface.php b/vendor/psr/http-client/src/RequestExceptionInterface.php new file mode 100644 index 0000000..b17fc34 --- /dev/null +++ b/vendor/psr/http-client/src/RequestExceptionInterface.php @@ -0,0 +1,24 @@ +<?php + +namespace Psr\Http\Client; + +use Psr\Http\Message\RequestInterface; + +/** + * Exception for when a request failed. + * + * Examples: + * - Request is invalid (e.g. method is missing) + * - Runtime request errors (e.g. the body stream is not seekable) + */ +interface RequestExceptionInterface extends ClientExceptionInterface +{ + /** + * Returns the request. + * + * The request object MAY be a different object from the one passed to ClientInterface::sendRequest() + * + * @return RequestInterface + */ + public function getRequest(): RequestInterface; +} diff --git a/vendor/psr/http-factory/LICENSE b/vendor/psr/http-factory/LICENSE new file mode 100644 index 0000000..3f1559b --- /dev/null +++ b/vendor/psr/http-factory/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 PHP-FIG + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/psr/http-factory/README.md b/vendor/psr/http-factory/README.md new file mode 100644 index 0000000..bf8913b --- /dev/null +++ b/vendor/psr/http-factory/README.md @@ -0,0 +1,12 @@ +HTTP Factories +============== + +This repository holds all interfaces related to [PSR-17 (HTTP Factories)][psr-url]. + +Note that this is not a HTTP Factory implementation of its own. It is merely interfaces that describe the components of a HTTP Factory. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-17/ +[package-url]: https://packagist.org/packages/psr/http-factory +[implementation-url]: https://packagist.org/providers/psr/http-factory-implementation diff --git a/vendor/psr/http-factory/composer.json b/vendor/psr/http-factory/composer.json new file mode 100644 index 0000000..82a1d32 --- /dev/null +++ b/vendor/psr/http-factory/composer.json @@ -0,0 +1,38 @@ +{ + "name": "psr/http-factory", + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "psr", + "psr-7", + "psr-17", + "http", + "factory", + "message", + "request", + "response" + ], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/http-factory/src/RequestFactoryInterface.php b/vendor/psr/http-factory/src/RequestFactoryInterface.php new file mode 100644 index 0000000..cb39a08 --- /dev/null +++ b/vendor/psr/http-factory/src/RequestFactoryInterface.php @@ -0,0 +1,18 @@ +<?php + +namespace Psr\Http\Message; + +interface RequestFactoryInterface +{ + /** + * Create a new request. + * + * @param string $method The HTTP method associated with the request. + * @param UriInterface|string $uri The URI associated with the request. If + * the value is a string, the factory MUST create a UriInterface + * instance based on it. + * + * @return RequestInterface + */ + public function createRequest(string $method, $uri): RequestInterface; +} diff --git a/vendor/psr/http-factory/src/ResponseFactoryInterface.php b/vendor/psr/http-factory/src/ResponseFactoryInterface.php new file mode 100644 index 0000000..212562f --- /dev/null +++ b/vendor/psr/http-factory/src/ResponseFactoryInterface.php @@ -0,0 +1,18 @@ +<?php + +namespace Psr\Http\Message; + +interface ResponseFactoryInterface +{ + /** + * Create a new response. + * + * @param int $code HTTP status code; defaults to 200 + * @param string $reasonPhrase Reason phrase to associate with status code + * in generated response; if none is provided implementations MAY use + * the defaults as suggested in the HTTP specification. + * + * @return ResponseInterface + */ + public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface; +} diff --git a/vendor/psr/http-factory/src/ServerRequestFactoryInterface.php b/vendor/psr/http-factory/src/ServerRequestFactoryInterface.php new file mode 100644 index 0000000..9fe031a --- /dev/null +++ b/vendor/psr/http-factory/src/ServerRequestFactoryInterface.php @@ -0,0 +1,24 @@ +<?php + +namespace Psr\Http\Message; + +interface ServerRequestFactoryInterface +{ + /** + * Create a new server request. + * + * Note that server-params are taken precisely as given - no parsing/processing + * of the given values is performed, and, in particular, no attempt is made to + * determine the HTTP method or URI, which must be provided explicitly. + * + * @param string $method The HTTP method associated with the request. + * @param UriInterface|string $uri The URI associated with the request. If + * the value is a string, the factory MUST create a UriInterface + * instance based on it. + * @param array $serverParams Array of SAPI parameters with which to seed + * the generated request instance. + * + * @return ServerRequestInterface + */ + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface; +} diff --git a/vendor/psr/http-factory/src/StreamFactoryInterface.php b/vendor/psr/http-factory/src/StreamFactoryInterface.php new file mode 100644 index 0000000..90e3240 --- /dev/null +++ b/vendor/psr/http-factory/src/StreamFactoryInterface.php @@ -0,0 +1,45 @@ +<?php + +namespace Psr\Http\Message; + +interface StreamFactoryInterface +{ + /** + * Create a new stream from a string. + * + * The stream SHOULD be created with a temporary resource. + * + * @param string $content String content with which to populate the stream. + * + * @return StreamInterface + */ + public function createStream(string $content = ''): StreamInterface; + + /** + * Create a stream from an existing file. + * + * The file MUST be opened using the given mode, which may be any mode + * supported by the `fopen` function. + * + * The `$filename` MAY be any string supported by `fopen()`. + * + * @param string $filename Filename or stream URI to use as basis of stream. + * @param string $mode Mode with which to open the underlying filename/stream. + * + * @return StreamInterface + * @throws \RuntimeException If the file cannot be opened. + * @throws \InvalidArgumentException If the mode is invalid. + */ + public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface; + + /** + * Create a new stream from an existing resource. + * + * The stream MUST be readable and may be writable. + * + * @param resource $resource PHP resource to use as basis of stream. + * + * @return StreamInterface + */ + public function createStreamFromResource($resource): StreamInterface; +} diff --git a/vendor/psr/http-factory/src/UploadedFileFactoryInterface.php b/vendor/psr/http-factory/src/UploadedFileFactoryInterface.php new file mode 100644 index 0000000..d7adbf0 --- /dev/null +++ b/vendor/psr/http-factory/src/UploadedFileFactoryInterface.php @@ -0,0 +1,34 @@ +<?php + +namespace Psr\Http\Message; + +interface UploadedFileFactoryInterface +{ + /** + * Create a new uploaded file. + * + * If a size is not provided it will be determined by checking the size of + * the file. + * + * @see http://php.net/manual/features.file-upload.post-method.php + * @see http://php.net/manual/features.file-upload.errors.php + * + * @param StreamInterface $stream Underlying stream representing the + * uploaded file content. + * @param int|null $size in bytes + * @param int $error PHP file upload error + * @param string|null $clientFilename Filename as provided by the client, if any. + * @param string|null $clientMediaType Media type as provided by the client, if any. + * + * @return UploadedFileInterface + * + * @throws \InvalidArgumentException If the file resource is not readable. + */ + public function createUploadedFile( + StreamInterface $stream, + ?int $size = null, + int $error = \UPLOAD_ERR_OK, + ?string $clientFilename = null, + ?string $clientMediaType = null + ): UploadedFileInterface; +} diff --git a/vendor/psr/http-factory/src/UriFactoryInterface.php b/vendor/psr/http-factory/src/UriFactoryInterface.php new file mode 100644 index 0000000..06df0b4 --- /dev/null +++ b/vendor/psr/http-factory/src/UriFactoryInterface.php @@ -0,0 +1,17 @@ +<?php + +namespace Psr\Http\Message; + +interface UriFactoryInterface +{ + /** + * Create a new URI. + * + * @param string $uri + * + * @return UriInterface + * + * @throws \InvalidArgumentException If the given URI cannot be parsed. + */ + public function createUri(string $uri = ''): UriInterface; +} diff --git a/vendor/psr/http-message/CHANGELOG.md b/vendor/psr/http-message/CHANGELOG.md new file mode 100644 index 0000000..74b1ef9 --- /dev/null +++ b/vendor/psr/http-message/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.1 - 2016-08-06 + +### Added + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Updated all `@return self` annotation references in interfaces to use + `@return static`, which more closelly follows the semantics of the + specification. +- Updated the `MessageInterface::getHeaders()` return annotation to use the + value `string[][]`, indicating the format is a nested array of strings. +- Updated the `@link` annotation for `RequestInterface::withRequestTarget()` + to point to the correct section of RFC 7230. +- Updated the `ServerRequestInterface::withUploadedFiles()` parameter annotation + to add the parameter name (`$uploadedFiles`). +- Updated a `@throws` annotation for the `UploadedFileInterface::moveTo()` + method to correctly reference the method parameter (it was referencing an + incorrect parameter name previously). + +## 1.0.0 - 2016-05-18 + +Initial stable release; reflects accepted PSR-7 specification. diff --git a/vendor/psr/http-message/LICENSE b/vendor/psr/http-message/LICENSE new file mode 100644 index 0000000..c2d8e45 --- /dev/null +++ b/vendor/psr/http-message/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/psr/http-message/README.md b/vendor/psr/http-message/README.md new file mode 100644 index 0000000..2668be6 --- /dev/null +++ b/vendor/psr/http-message/README.md @@ -0,0 +1,16 @@ +PSR Http Message +================ + +This repository holds all interfaces/classes/traits related to +[PSR-7](http://www.php-fig.org/psr/psr-7/). + +Note that this is not a HTTP message implementation of its own. It is merely an +interface that describes a HTTP message. See the specification for more details. + +Usage +----- + +Before reading the usage guide we recommend reading the PSR-7 interfaces method list: + +* [`PSR-7 Interfaces Method List`](docs/PSR7-Interfaces.md) +* [`PSR-7 Usage Guide`](docs/PSR7-Usage.md) \ No newline at end of file diff --git a/vendor/psr/http-message/composer.json b/vendor/psr/http-message/composer.json new file mode 100644 index 0000000..c66e5ab --- /dev/null +++ b/vendor/psr/http-message/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/http-message", + "description": "Common interface for HTTP messages", + "keywords": ["psr", "psr-7", "http", "http-message", "request", "response"], + "homepage": "https://github.com/php-fig/http-message", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": "^7.2 || ^8.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + } +} diff --git a/vendor/psr/http-message/docs/PSR7-Interfaces.md b/vendor/psr/http-message/docs/PSR7-Interfaces.md new file mode 100644 index 0000000..3a7e7dd --- /dev/null +++ b/vendor/psr/http-message/docs/PSR7-Interfaces.md @@ -0,0 +1,130 @@ +# Interfaces + +The purpose of this list is to help in finding the methods when working with PSR-7. This can be considered as a cheatsheet for PSR-7 interfaces. + +The interfaces defined in PSR-7 are the following: + +| Class Name | Description | +|---|---| +| [Psr\Http\Message\MessageInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagemessageinterface) | Representation of a HTTP message | +| [Psr\Http\Message\RequestInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagerequestinterface) | Representation of an outgoing, client-side request. | +| [Psr\Http\Message\ServerRequestInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageserverrequestinterface) | Representation of an incoming, server-side HTTP request. | +| [Psr\Http\Message\ResponseInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageresponseinterface) | Representation of an outgoing, server-side response. | +| [Psr\Http\Message\StreamInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagestreaminterface) | Describes a data stream | +| [Psr\Http\Message\UriInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageuriinterface) | Value object representing a URI. | +| [Psr\Http\Message\UploadedFileInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageuploadedfileinterface) | Value object representing a file uploaded through an HTTP request. | + +## `Psr\Http\Message\MessageInterface` Methods + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getProtocolVersion()` | Retrieve HTTP protocol version | 1.0 or 1.1 | +| `withProtocolVersion($version)` | Returns new message instance with given HTTP protocol version | | +| `getHeaders()` | Retrieve all HTTP Headers | [Request Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields), [Response Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Response_fields) | +| `hasHeader($name)` | Checks if HTTP Header with given name exists | | +| `getHeader($name)` | Retrieves a array with the values for a single header | | +| `getHeaderLine($name)` | Retrieves a comma-separated string of the values for a single header | | +| `withHeader($name, $value)` | Returns new message instance with given HTTP Header | if the header existed in the original instance, replaces the header value from the original message with the value provided when creating the new instance. | +| `withAddedHeader($name, $value)` | Returns new message instance with appended value to given header | If header already exists value will be appended, if not a new header will be created | +| `withoutHeader($name)` | Removes HTTP Header with given name| | +| `getBody()` | Retrieves the HTTP Message Body | Returns object implementing `StreamInterface`| +| `withBody(StreamInterface $body)` | Returns new message instance with given HTTP Message Body | | + + +## `Psr\Http\Message\RequestInterface` Methods + +Same methods as `Psr\Http\Message\MessageInterface` + the following methods: + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getRequestTarget()` | Retrieves the message's request target | origin-form, absolute-form, authority-form, asterisk-form ([RFC7230](https://www.rfc-editor.org/rfc/rfc7230.txt)) | +| `withRequestTarget($requestTarget)` | Return a new message instance with the specific request-target | | +| `getMethod()` | Retrieves the HTTP method of the request. | GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE (defined in [RFC7231](https://tools.ietf.org/html/rfc7231)), PATCH (defined in [RFC5789](https://tools.ietf.org/html/rfc5789)) | +| `withMethod($method)` | Returns a new message instance with the provided HTTP method | | +| `getUri()` | Retrieves the URI instance | | +| `withUri(UriInterface $uri, $preserveHost = false)` | Returns a new message instance with the provided URI | | + + +## `Psr\Http\Message\ServerRequestInterface` Methods + +Same methods as `Psr\Http\Message\RequestInterface` + the following methods: + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getServerParams() ` | Retrieve server parameters | Typically derived from `$_SERVER` | +| `getCookieParams()` | Retrieves cookies sent by the client to the server. | Typically derived from `$_COOKIES` | +| `withCookieParams(array $cookies)` | Returns a new request instance with the specified cookies | | +| `withQueryParams(array $query)` | Returns a new request instance with the specified query string arguments | | +| `getUploadedFiles()` | Retrieve normalized file upload data | | +| `withUploadedFiles(array $uploadedFiles)` | Returns a new request instance with the specified uploaded files | | +| `getParsedBody()` | Retrieve any parameters provided in the request body | | +| `withParsedBody($data)` | Returns a new request instance with the specified body parameters | | +| `getAttributes()` | Retrieve attributes derived from the request | | +| `getAttribute($name, $default = null)` | Retrieve a single derived request attribute | | +| `withAttribute($name, $value)` | Returns a new request instance with the specified derived request attribute | | +| `withoutAttribute($name)` | Returns a new request instance that without the specified derived request attribute | | + +## `Psr\Http\Message\ResponseInterface` Methods: + +Same methods as `Psr\Http\Message\MessageInterface` + the following methods: + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getStatusCode()` | Gets the response status code. | | +| `withStatus($code, $reasonPhrase = '')` | Returns a new response instance with the specified status code and, optionally, reason phrase. | | +| `getReasonPhrase()` | Gets the response reason phrase associated with the status code. | | + +## `Psr\Http\Message\StreamInterface` Methods + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `__toString()` | Reads all data from the stream into a string, from the beginning to end. | | +| `close()` | Closes the stream and any underlying resources. | | +| `detach()` | Separates any underlying resources from the stream. | | +| `getSize()` | Get the size of the stream if known. | | +| `eof()` | Returns true if the stream is at the end of the stream.| | +| `isSeekable()` | Returns whether or not the stream is seekable. | | +| `seek($offset, $whence = SEEK_SET)` | Seek to a position in the stream. | | +| `rewind()` | Seek to the beginning of the stream. | | +| `isWritable()` | Returns whether or not the stream is writable. | | +| `write($string)` | Write data to the stream. | | +| `isReadable()` | Returns whether or not the stream is readable. | | +| `read($length)` | Read data from the stream. | | +| `getContents()` | Returns the remaining contents in a string | | +| `getMetadata($key = null)()` | Get stream metadata as an associative array or retrieve a specific key. | | + +## `Psr\Http\Message\UriInterface` Methods + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getScheme()` | Retrieve the scheme component of the URI. | | +| `getAuthority()` | Retrieve the authority component of the URI. | | +| `getUserInfo()` | Retrieve the user information component of the URI. | | +| `getHost()` | Retrieve the host component of the URI. | | +| `getPort()` | Retrieve the port component of the URI. | | +| `getPath()` | Retrieve the path component of the URI. | | +| `getQuery()` | Retrieve the query string of the URI. | | +| `getFragment()` | Retrieve the fragment component of the URI. | | +| `withScheme($scheme)` | Return an instance with the specified scheme. | | +| `withUserInfo($user, $password = null)` | Return an instance with the specified user information. | | +| `withHost($host)` | Return an instance with the specified host. | | +| `withPort($port)` | Return an instance with the specified port. | | +| `withPath($path)` | Return an instance with the specified path. | | +| `withQuery($query)` | Return an instance with the specified query string. | | +| `withFragment($fragment)` | Return an instance with the specified URI fragment. | | +| `__toString()` | Return the string representation as a URI reference. | | + +## `Psr\Http\Message\UploadedFileInterface` Methods + +| Method Name | Description | Notes | +|------------------------------------| ----------- | ----- | +| `getStream()` | Retrieve a stream representing the uploaded file. | | +| `moveTo($targetPath)` | Move the uploaded file to a new location. | | +| `getSize()` | Retrieve the file size. | | +| `getError()` | Retrieve the error associated with the uploaded file. | | +| `getClientFilename()` | Retrieve the filename sent by the client. | | +| `getClientMediaType()` | Retrieve the media type sent by the client. | | + +> `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. +> When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. + diff --git a/vendor/psr/http-message/docs/PSR7-Usage.md b/vendor/psr/http-message/docs/PSR7-Usage.md new file mode 100644 index 0000000..b6d048a --- /dev/null +++ b/vendor/psr/http-message/docs/PSR7-Usage.md @@ -0,0 +1,159 @@ +### PSR-7 Usage + +All PSR-7 applications comply with these interfaces +They were created to establish a standard between middleware implementations. + +> `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. +> When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. + + +The following examples will illustrate how basic operations are done in PSR-7. + +##### Examples + + +For this examples to work (at least) a PSR-7 implementation package is required. (eg: zendframework/zend-diactoros, guzzlehttp/psr7, slim/slim, etc) +All PSR-7 implementations should have the same behaviour. + +The following will be assumed: +`$request` is an object of `Psr\Http\Message\RequestInterface` and + +`$response` is an object implementing `Psr\Http\Message\RequestInterface` + + +### Working with HTTP Headers + +#### Adding headers to response: + +```php +$response->withHeader('My-Custom-Header', 'My Custom Message'); +``` + +#### Appending values to headers + +```php +$response->withAddedHeader('My-Custom-Header', 'The second message'); +``` + +#### Checking if header exists: + +```php +$request->hasHeader('My-Custom-Header'); // will return false +$response->hasHeader('My-Custom-Header'); // will return true +``` + +> Note: My-Custom-Header was only added in the Response + +#### Getting comma-separated values from a header (also applies to request) + +```php +// getting value from request headers +$request->getHeaderLine('Content-Type'); // will return: "text/html; charset=UTF-8" +// getting value from response headers +$response->getHeaderLine('My-Custom-Header'); // will return: "My Custom Message; The second message" +``` + +#### Getting array of value from a header (also applies to request) +```php +// getting value from request headers +$request->getHeader('Content-Type'); // will return: ["text/html", "charset=UTF-8"] +// getting value from response headers +$response->getHeader('My-Custom-Header'); // will return: ["My Custom Message", "The second message"] +``` + +#### Removing headers from HTTP Messages +```php +// removing a header from Request, removing deprecated "Content-MD5" header +$request->withoutHeader('Content-MD5'); + +// removing a header from Response +// effect: the browser won't know the size of the stream +// the browser will download the stream till it ends +$response->withoutHeader('Content-Length'); +``` + +### Working with HTTP Message Body + +When working with the PSR-7 there are two methods of implementation: +#### 1. Getting the body separately + +> This method makes the body handling easier to understand and is useful when repeatedly calling body methods. (You only call `getBody()` once). Using this method mistakes like `$response->write()` are also prevented. + +```php +$body = $response->getBody(); +// operations on body, eg. read, write, seek +// ... +// replacing the old body +$response->withBody($body); +// this last statement is optional as we working with objects +// in this case the "new" body is same with the "old" one +// the $body variable has the same value as the one in $request, only the reference is passed +``` + +#### 2. Working directly on response + +> This method is useful when only performing few operations as the `$request->getBody()` statement fragment is required + +```php +$response->getBody()->write('hello'); +``` + +### Getting the body contents + +The following snippet gets the contents of a stream contents. +> Note: Streams must be rewinded, if content was written into streams, it will be ignored when calling `getContents()` because the stream pointer is set to the last character, which is `\0` - meaning end of stream. +```php +$body = $response->getBody(); +$body->rewind(); // or $body->seek(0); +$bodyText = $body->getContents(); +``` +> Note: If `$body->seek(1)` is called before `$body->getContents()`, the first character will be ommited as the starting pointer is set to `1`, not `0`. This is why using `$body->rewind()` is recommended. + +### Append to body + +```php +$response->getBody()->write('Hello'); // writing directly +$body = $request->getBody(); // which is a `StreamInterface` +$body->write('xxxxx'); +``` + +### Prepend to body +Prepending is different when it comes to streams. The content must be copied before writing the content to be prepended. +The following example will explain the behaviour of streams. + +```php +// assuming our response is initially empty +$body = $repsonse->getBody(); +// writing the string "abcd" +$body->write('abcd'); + +// seeking to start of stream +$body->seek(0); +// writing 'ef' +$body->write('ef'); // at this point the stream contains "efcd" +``` + +#### Prepending by rewriting separately + +```php +// assuming our response body stream only contains: "abcd" +$body = $response->getBody(); +$body->rewind(); +$contents = $body->getContents(); // abcd +// seeking the stream to beginning +$body->rewind(); +$body->write('ef'); // stream contains "efcd" +$body->write($contents); // stream contains "efabcd" +``` + +> Note: `getContents()` seeks the stream while reading it, therefore if the second `rewind()` method call was not present the stream would have resulted in `abcdefabcd` because the `write()` method appends to stream if not preceeded by `rewind()` or `seek(0)`. + +#### Prepending by using contents as a string +```php +$body = $response->getBody(); +$body->rewind(); +$contents = $body->getContents(); // efabcd +$contents = 'ef'.$contents; +$body->rewind(); +$body->write($contents); +``` diff --git a/vendor/psr/http-message/src/MessageInterface.php b/vendor/psr/http-message/src/MessageInterface.php new file mode 100644 index 0000000..a83c985 --- /dev/null +++ b/vendor/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +<?php + +namespace Psr\Http\Message; + +/** + * HTTP messages consist of requests from a client to a server and responses + * from a server to a client. This interface defines the methods common to + * each. + * + * Messages are considered immutable; all methods that might change state MUST + * be implemented such that they retain the internal state of the current + * message and return an instance that contains the changed state. + * + * @link http://www.ietf.org/rfc/rfc7230.txt + * @link http://www.ietf.org/rfc/rfc7231.txt + */ +interface MessageInterface +{ + /** + * Retrieves the HTTP protocol version as a string. + * + * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0"). + * + * @return string HTTP protocol version. + */ + public function getProtocolVersion(): string; + + /** + * Return an instance with the specified HTTP protocol version. + * + * The version string MUST contain only the HTTP version number (e.g., + * "1.1", "1.0"). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new protocol version. + * + * @param string $version HTTP protocol version + * @return static + */ + public function withProtocolVersion(string $version): MessageInterface; + + /** + * Retrieves all message header values. + * + * The keys represent the header name as it will be sent over the wire, and + * each value is an array of strings associated with the header. + * + * // Represent the headers as a string + * foreach ($message->getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return string[][] Returns an associative array of the message's headers. Each + * key MUST be a header name, and each value MUST be an array of strings + * for that header. + */ + public function getHeaders(): array; + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader(string $name): bool; + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader(string $name): array; + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine(string $name): string; + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader(string $name, $value): MessageInterface; + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader(string $name, $value): MessageInterface; + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader(string $name): MessageInterface; + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(): StreamInterface; + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body): MessageInterface; +} diff --git a/vendor/psr/http-message/src/RequestInterface.php b/vendor/psr/http-message/src/RequestInterface.php new file mode 100644 index 0000000..33f85e5 --- /dev/null +++ b/vendor/psr/http-message/src/RequestInterface.php @@ -0,0 +1,130 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Representation of an outgoing, client-side request. + * + * Per the HTTP specification, this interface includes properties for + * each of the following: + * + * - Protocol version + * - HTTP method + * - URI + * - Headers + * - Message body + * + * During construction, implementations MUST attempt to set the Host header from + * a provided URI if no Host header is provided. + * + * Requests are considered immutable; all methods that might change state MUST + * be implemented such that they retain the internal state of the current + * message and return an instance that contains the changed state. + */ +interface RequestInterface extends MessageInterface +{ + /** + * Retrieves the message's request target. + * + * Retrieves the message's request-target either as it will appear (for + * clients), as it appeared at request (for servers), or as it was + * specified for the instance (see withRequestTarget()). + * + * In most cases, this will be the origin-form of the composed URI, + * unless a value was provided to the concrete implementation (see + * withRequestTarget() below). + * + * If no URI is available, and no request-target has been specifically + * provided, this method MUST return the string "/". + * + * @return string + */ + public function getRequestTarget(): string; + + /** + * Return an instance with the specific request-target. + * + * If the request needs a non-origin-form request-target — e.g., for + * specifying an absolute-form, authority-form, or asterisk-form — + * this method may be used to create an instance with the specified + * request-target, verbatim. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * changed request target. + * + * @link http://tools.ietf.org/html/rfc7230#section-5.3 (for the various + * request-target forms allowed in request messages) + * @param string $requestTarget + * @return static + */ + public function withRequestTarget(string $requestTarget): RequestInterface; + + + /** + * Retrieves the HTTP method of the request. + * + * @return string Returns the request method. + */ + public function getMethod(): string; + + /** + * Return an instance with the provided HTTP method. + * + * While HTTP method names are typically all uppercase characters, HTTP + * method names are case-sensitive and thus implementations SHOULD NOT + * modify the given string. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * changed request method. + * + * @param string $method Case-sensitive method. + * @return static + * @throws \InvalidArgumentException for invalid HTTP methods. + */ + public function withMethod(string $method): RequestInterface; + + /** + * Retrieves the URI instance. + * + * This method MUST return a UriInterface instance. + * + * @link http://tools.ietf.org/html/rfc3986#section-4.3 + * @return UriInterface Returns a UriInterface instance + * representing the URI of the request. + */ + public function getUri(): UriInterface; + + /** + * Returns an instance with the provided URI. + * + * This method MUST update the Host header of the returned request by + * default if the URI contains a host component. If the URI does not + * contain a host component, any pre-existing Host header MUST be carried + * over to the returned request. + * + * You can opt-in to preserving the original state of the Host header by + * setting `$preserveHost` to `true`. When `$preserveHost` is set to + * `true`, this method interacts with the Host header in the following ways: + * + * - If the Host header is missing or empty, and the new URI contains + * a host component, this method MUST update the Host header in the returned + * request. + * - If the Host header is missing or empty, and the new URI does not contain a + * host component, this method MUST NOT update the Host header in the returned + * request. + * - If a Host header is present and non-empty, this method MUST NOT update + * the Host header in the returned request. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new UriInterface instance. + * + * @link http://tools.ietf.org/html/rfc3986#section-4.3 + * @param UriInterface $uri New request URI to use. + * @param bool $preserveHost Preserve the original state of the Host header. + * @return static + */ + public function withUri(UriInterface $uri, bool $preserveHost = false): RequestInterface; +} diff --git a/vendor/psr/http-message/src/ResponseInterface.php b/vendor/psr/http-message/src/ResponseInterface.php new file mode 100644 index 0000000..e9299a9 --- /dev/null +++ b/vendor/psr/http-message/src/ResponseInterface.php @@ -0,0 +1,68 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Representation of an outgoing, server-side response. + * + * Per the HTTP specification, this interface includes properties for + * each of the following: + * + * - Protocol version + * - Status code and reason phrase + * - Headers + * - Message body + * + * Responses are considered immutable; all methods that might change state MUST + * be implemented such that they retain the internal state of the current + * message and return an instance that contains the changed state. + */ +interface ResponseInterface extends MessageInterface +{ + /** + * Gets the response status code. + * + * The status code is a 3-digit integer result code of the server's attempt + * to understand and satisfy the request. + * + * @return int Status code. + */ + public function getStatusCode(): int; + + /** + * Return an instance with the specified status code and, optionally, reason phrase. + * + * If no reason phrase is specified, implementations MAY choose to default + * to the RFC 7231 or IANA recommended reason phrase for the response's + * status code. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated status and reason phrase. + * + * @link http://tools.ietf.org/html/rfc7231#section-6 + * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + * @param int $code The 3-digit integer result code to set. + * @param string $reasonPhrase The reason phrase to use with the + * provided status code; if none is provided, implementations MAY + * use the defaults as suggested in the HTTP specification. + * @return static + * @throws \InvalidArgumentException For invalid status code arguments. + */ + public function withStatus(int $code, string $reasonPhrase = ''): ResponseInterface; + + /** + * Gets the response reason phrase associated with the status code. + * + * Because a reason phrase is not a required element in a response + * status line, the reason phrase value MAY be null. Implementations MAY + * choose to return the default RFC 7231 recommended reason phrase (or those + * listed in the IANA HTTP Status Code Registry) for the response's + * status code. + * + * @link http://tools.ietf.org/html/rfc7231#section-6 + * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + * @return string Reason phrase; must return an empty string if none present. + */ + public function getReasonPhrase(): string; +} diff --git a/vendor/psr/http-message/src/ServerRequestInterface.php b/vendor/psr/http-message/src/ServerRequestInterface.php new file mode 100644 index 0000000..8625d0e --- /dev/null +++ b/vendor/psr/http-message/src/ServerRequestInterface.php @@ -0,0 +1,261 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Representation of an incoming, server-side HTTP request. + * + * Per the HTTP specification, this interface includes properties for + * each of the following: + * + * - Protocol version + * - HTTP method + * - URI + * - Headers + * - Message body + * + * Additionally, it encapsulates all data as it has arrived to the + * application from the CGI and/or PHP environment, including: + * + * - The values represented in $_SERVER. + * - Any cookies provided (generally via $_COOKIE) + * - Query string arguments (generally via $_GET, or as parsed via parse_str()) + * - Upload files, if any (as represented by $_FILES) + * - Deserialized body parameters (generally from $_POST) + * + * $_SERVER values MUST be treated as immutable, as they represent application + * state at the time of request; as such, no methods are provided to allow + * modification of those values. The other values provide such methods, as they + * can be restored from $_SERVER or the request body, and may need treatment + * during the application (e.g., body parameters may be deserialized based on + * content type). + * + * Additionally, this interface recognizes the utility of introspecting a + * request to derive and match additional parameters (e.g., via URI path + * matching, decrypting cookie values, deserializing non-form-encoded body + * content, matching authorization headers to users, etc). These parameters + * are stored in an "attributes" property. + * + * Requests are considered immutable; all methods that might change state MUST + * be implemented such that they retain the internal state of the current + * message and return an instance that contains the changed state. + */ +interface ServerRequestInterface extends RequestInterface +{ + /** + * Retrieve server parameters. + * + * Retrieves data related to the incoming request environment, + * typically derived from PHP's $_SERVER superglobal. The data IS NOT + * REQUIRED to originate from $_SERVER. + * + * @return array + */ + public function getServerParams(): array; + + /** + * Retrieve cookies. + * + * Retrieves cookies sent by the client to the server. + * + * The data MUST be compatible with the structure of the $_COOKIE + * superglobal. + * + * @return array + */ + public function getCookieParams(): array; + + /** + * Return an instance with the specified cookies. + * + * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST + * be compatible with the structure of $_COOKIE. Typically, this data will + * be injected at instantiation. + * + * This method MUST NOT update the related Cookie header of the request + * instance, nor related values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated cookie values. + * + * @param array $cookies Array of key/value pairs representing cookies. + * @return static + */ + public function withCookieParams(array $cookies): ServerRequestInterface; + + /** + * Retrieve query string arguments. + * + * Retrieves the deserialized query string arguments, if any. + * + * Note: the query params might not be in sync with the URI or server + * params. If you need to ensure you are only getting the original + * values, you may need to parse the query string from `getUri()->getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(): array; + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query): ServerRequestInterface; + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(): array; + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface; + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data): ServerRequestInterface; + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(): array; + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute(string $name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute(string $name, $value): ServerRequestInterface; + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute(string $name): ServerRequestInterface; +} diff --git a/vendor/psr/http-message/src/StreamInterface.php b/vendor/psr/http-message/src/StreamInterface.php new file mode 100644 index 0000000..a62aabb --- /dev/null +++ b/vendor/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Describes a data stream. + * + * Typically, an instance will wrap a PHP stream; this interface provides + * a wrapper around the most common operations, including serialization of + * the entire stream to a string. + */ +interface StreamInterface +{ + /** + * Reads all data from the stream into a string, from the beginning to end. + * + * This method MUST attempt to seek to the beginning of the stream before + * reading data and read the stream until the end is reached. + * + * Warning: This could attempt to load a large amount of data into memory. + * + * This method MUST NOT raise an exception in order to conform with PHP's + * string casting operations. + * + * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring + * @return string + */ + public function __toString(): string; + + /** + * Closes the stream and any underlying resources. + * + * @return void + */ + public function close(): void; + + /** + * Separates any underlying resources from the stream. + * + * After the stream has been detached, the stream is in an unusable state. + * + * @return resource|null Underlying PHP stream, if any + */ + public function detach(); + + /** + * Get the size of the stream if known. + * + * @return int|null Returns the size in bytes if known, or null if unknown. + */ + public function getSize(): ?int; + + /** + * Returns the current position of the file read/write pointer + * + * @return int Position of the file pointer + * @throws \RuntimeException on error. + */ + public function tell(): int; + + /** + * Returns true if the stream is at the end of the stream. + * + * @return bool + */ + public function eof(): bool; + + /** + * Returns whether or not the stream is seekable. + * + * @return bool + */ + public function isSeekable(): bool; + + /** + * Seek to a position in the stream. + * + * @link http://www.php.net/manual/en/function.fseek.php + * @param int $offset Stream offset + * @param int $whence Specifies how the cursor position will be calculated + * based on the seek offset. Valid values are identical to the built-in + * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to + * offset bytes SEEK_CUR: Set position to current location plus offset + * SEEK_END: Set position to end-of-stream plus offset. + * @throws \RuntimeException on failure. + */ + public function seek(int $offset, int $whence = SEEK_SET): void; + + /** + * Seek to the beginning of the stream. + * + * If the stream is not seekable, this method will raise an exception; + * otherwise, it will perform a seek(0). + * + * @see seek() + * @link http://www.php.net/manual/en/function.fseek.php + * @throws \RuntimeException on failure. + */ + public function rewind(): void; + + /** + * Returns whether or not the stream is writable. + * + * @return bool + */ + public function isWritable(): bool; + + /** + * Write data to the stream. + * + * @param string $string The string that is to be written. + * @return int Returns the number of bytes written to the stream. + * @throws \RuntimeException on failure. + */ + public function write(string $string): int; + + /** + * Returns whether or not the stream is readable. + * + * @return bool + */ + public function isReadable(): bool; + + /** + * Read data from the stream. + * + * @param int $length Read up to $length bytes from the object and return + * them. Fewer than $length bytes may be returned if underlying stream + * call returns fewer bytes. + * @return string Returns the data read from the stream, or an empty string + * if no bytes are available. + * @throws \RuntimeException if an error occurs. + */ + public function read(int $length): string; + + /** + * Returns the remaining contents in a string + * + * @return string + * @throws \RuntimeException if unable to read or an error occurs while + * reading. + */ + public function getContents(): string; + + /** + * Get stream metadata as an associative array or retrieve a specific key. + * + * The keys returned are identical to the keys returned from PHP's + * stream_get_meta_data() function. + * + * @link http://php.net/manual/en/function.stream-get-meta-data.php + * @param string|null $key Specific metadata to retrieve. + * @return array|mixed|null Returns an associative array if no key is + * provided. Returns a specific key value if a key is provided and the + * value is found, or null if the key is not found. + */ + public function getMetadata(?string $key = null); +} diff --git a/vendor/psr/http-message/src/UploadedFileInterface.php b/vendor/psr/http-message/src/UploadedFileInterface.php new file mode 100644 index 0000000..dd19d65 --- /dev/null +++ b/vendor/psr/http-message/src/UploadedFileInterface.php @@ -0,0 +1,123 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Value object representing a file uploaded through an HTTP request. + * + * Instances of this interface are considered immutable; all methods that + * might change state MUST be implemented such that they retain the internal + * state of the current instance and return an instance that contains the + * changed state. + */ +interface UploadedFileInterface +{ + /** + * Retrieve a stream representing the uploaded file. + * + * This method MUST return a StreamInterface instance, representing the + * uploaded file. The purpose of this method is to allow utilizing native PHP + * stream functionality to manipulate the file upload, such as + * stream_copy_to_stream() (though the result will need to be decorated in a + * native PHP stream wrapper to work with such functions). + * + * If the moveTo() method has been called previously, this method MUST raise + * an exception. + * + * @return StreamInterface Stream representation of the uploaded file. + * @throws \RuntimeException in cases when no stream is available or can be + * created. + */ + public function getStream(): StreamInterface; + + /** + * Move the uploaded file to a new location. + * + * Use this method as an alternative to move_uploaded_file(). This method is + * guaranteed to work in both SAPI and non-SAPI environments. + * Implementations must determine which environment they are in, and use the + * appropriate method (move_uploaded_file(), rename(), or a stream + * operation) to perform the operation. + * + * $targetPath may be an absolute path, or a relative path. If it is a + * relative path, resolution should be the same as used by PHP's rename() + * function. + * + * The original file or stream MUST be removed on completion. + * + * If this method is called more than once, any subsequent calls MUST raise + * an exception. + * + * When used in an SAPI environment where $_FILES is populated, when writing + * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be + * used to ensure permissions and upload status are verified correctly. + * + * If you wish to move to a stream, use getStream(), as SAPI operations + * cannot guarantee writing to stream destinations. + * + * @see http://php.net/is_uploaded_file + * @see http://php.net/move_uploaded_file + * @param string $targetPath Path to which to move the uploaded file. + * @throws \InvalidArgumentException if the $targetPath specified is invalid. + * @throws \RuntimeException on any error during the move operation, or on + * the second or subsequent call to the method. + */ + public function moveTo(string $targetPath): void; + + /** + * Retrieve the file size. + * + * Implementations SHOULD return the value stored in the "size" key of + * the file in the $_FILES array if available, as PHP calculates this based + * on the actual size transmitted. + * + * @return int|null The file size in bytes or null if unknown. + */ + public function getSize(): ?int; + + /** + * Retrieve the error associated with the uploaded file. + * + * The return value MUST be one of PHP's UPLOAD_ERR_XXX constants. + * + * If the file was uploaded successfully, this method MUST return + * UPLOAD_ERR_OK. + * + * Implementations SHOULD return the value stored in the "error" key of + * the file in the $_FILES array. + * + * @see http://php.net/manual/en/features.file-upload.errors.php + * @return int One of PHP's UPLOAD_ERR_XXX constants. + */ + public function getError(): int; + + /** + * Retrieve the filename sent by the client. + * + * Do not trust the value returned by this method. A client could send + * a malicious filename with the intention to corrupt or hack your + * application. + * + * Implementations SHOULD return the value stored in the "name" key of + * the file in the $_FILES array. + * + * @return string|null The filename sent by the client or null if none + * was provided. + */ + public function getClientFilename(): ?string; + + /** + * Retrieve the media type sent by the client. + * + * Do not trust the value returned by this method. A client could send + * a malicious media type with the intention to corrupt or hack your + * application. + * + * Implementations SHOULD return the value stored in the "type" key of + * the file in the $_FILES array. + * + * @return string|null The media type sent by the client or null if none + * was provided. + */ + public function getClientMediaType(): ?string; +} diff --git a/vendor/psr/http-message/src/UriInterface.php b/vendor/psr/http-message/src/UriInterface.php new file mode 100644 index 0000000..15e2cf2 --- /dev/null +++ b/vendor/psr/http-message/src/UriInterface.php @@ -0,0 +1,324 @@ +<?php + +namespace Psr\Http\Message; + +/** + * Value object representing a URI. + * + * This interface is meant to represent URIs according to RFC 3986 and to + * provide methods for most common operations. Additional functionality for + * working with URIs can be provided on top of the interface or externally. + * Its primary use is for HTTP requests, but may also be used in other + * contexts. + * + * Instances of this interface are considered immutable; all methods that + * might change state MUST be implemented such that they retain the internal + * state of the current instance and return an instance that contains the + * changed state. + * + * Typically the Host header will be also be present in the request message. + * For server-side requests, the scheme will typically be discoverable in the + * server parameters. + * + * @link http://tools.ietf.org/html/rfc3986 (the URI specification) + */ +interface UriInterface +{ + /** + * Retrieve the scheme component of the URI. + * + * If no scheme is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.1. + * + * The trailing ":" character is not part of the scheme and MUST NOT be + * added. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.1 + * @return string The URI scheme. + */ + public function getScheme(): string; + + /** + * Retrieve the authority component of the URI. + * + * If no authority information is present, this method MUST return an empty + * string. + * + * The authority syntax of the URI is: + * + * <pre> + * [user-info@]host[:port] + * </pre> + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(): string; + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(): string; + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(): string; + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(): ?int; + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(): string; + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(): string; + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(): string; + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme(string $scheme): UriInterface; + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo(string $user, ?string $password = null): UriInterface; + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost(string $host): UriInterface; + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort(?int $port): UriInterface; + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath(string $path): UriInterface; + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * An empty query string value is equivalent to removing the query string. + * + * @param string $query The query string to use with the new instance. + * @return static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery(string $query): UriInterface; + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment(string $fragment): UriInterface; + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(): string; +} diff --git a/vendor/psr/log/LICENSE b/vendor/psr/log/LICENSE new file mode 100644 index 0000000..474c952 --- /dev/null +++ b/vendor/psr/log/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/psr/log/README.md b/vendor/psr/log/README.md new file mode 100644 index 0000000..a9f20c4 --- /dev/null +++ b/vendor/psr/log/README.md @@ -0,0 +1,58 @@ +PSR Log +======= + +This repository holds all interfaces/classes/traits related to +[PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md). + +Note that this is not a logger of its own. It is merely an interface that +describes a logger. See the specification for more details. + +Installation +------------ + +```bash +composer require psr/log +``` + +Usage +----- + +If you need a logger, you can use the interface like this: + +```php +<?php + +use Psr\Log\LoggerInterface; + +class Foo +{ + private $logger; + + public function __construct(LoggerInterface $logger = null) + { + $this->logger = $logger; + } + + public function doSomething() + { + if ($this->logger) { + $this->logger->info('Doing work'); + } + + try { + $this->doSomethingElse(); + } catch (Exception $exception) { + $this->logger->error('Oh no!', array('exception' => $exception)); + } + + // do something useful + } +} +``` + +You can then pick one of the implementations of the interface to get a logger. + +If you want to implement the interface, you can require this package and +implement `Psr\Log\LoggerInterface` in your code. Please read the +[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +for details. diff --git a/vendor/psr/log/composer.json b/vendor/psr/log/composer.json new file mode 100644 index 0000000..879fc6f --- /dev/null +++ b/vendor/psr/log/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/log", + "description": "Common interface for logging libraries", + "keywords": ["psr", "psr-3", "log"], + "homepage": "https://github.com/php-fig/log", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=8.0.0" + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + } +} diff --git a/vendor/psr/log/src/AbstractLogger.php b/vendor/psr/log/src/AbstractLogger.php new file mode 100644 index 0000000..d60a091 --- /dev/null +++ b/vendor/psr/log/src/AbstractLogger.php @@ -0,0 +1,15 @@ +<?php + +namespace Psr\Log; + +/** + * This is a simple Logger implementation that other Loggers can inherit from. + * + * It simply delegates all log-level-specific methods to the `log` method to + * reduce boilerplate code that a simple Logger that does the same thing with + * messages regardless of the error level has to implement. + */ +abstract class AbstractLogger implements LoggerInterface +{ + use LoggerTrait; +} diff --git a/vendor/psr/log/src/InvalidArgumentException.php b/vendor/psr/log/src/InvalidArgumentException.php new file mode 100644 index 0000000..67f852d --- /dev/null +++ b/vendor/psr/log/src/InvalidArgumentException.php @@ -0,0 +1,7 @@ +<?php + +namespace Psr\Log; + +class InvalidArgumentException extends \InvalidArgumentException +{ +} diff --git a/vendor/psr/log/src/LogLevel.php b/vendor/psr/log/src/LogLevel.php new file mode 100644 index 0000000..9cebcac --- /dev/null +++ b/vendor/psr/log/src/LogLevel.php @@ -0,0 +1,18 @@ +<?php + +namespace Psr\Log; + +/** + * Describes log levels. + */ +class LogLevel +{ + const EMERGENCY = 'emergency'; + const ALERT = 'alert'; + const CRITICAL = 'critical'; + const ERROR = 'error'; + const WARNING = 'warning'; + const NOTICE = 'notice'; + const INFO = 'info'; + const DEBUG = 'debug'; +} diff --git a/vendor/psr/log/src/LoggerAwareInterface.php b/vendor/psr/log/src/LoggerAwareInterface.php new file mode 100644 index 0000000..0621870 --- /dev/null +++ b/vendor/psr/log/src/LoggerAwareInterface.php @@ -0,0 +1,14 @@ +<?php + +namespace Psr\Log; + +/** + * Describes a logger-aware instance. + */ +interface LoggerAwareInterface +{ + /** + * Sets a logger instance on the object. + */ + public function setLogger(LoggerInterface $logger): void; +} diff --git a/vendor/psr/log/src/LoggerAwareTrait.php b/vendor/psr/log/src/LoggerAwareTrait.php new file mode 100644 index 0000000..85104db --- /dev/null +++ b/vendor/psr/log/src/LoggerAwareTrait.php @@ -0,0 +1,22 @@ +<?php + +namespace Psr\Log; + +/** + * Basic Implementation of LoggerAwareInterface. + */ +trait LoggerAwareTrait +{ + /** + * The logger instance. + */ + protected ?LoggerInterface $logger = null; + + /** + * Sets a logger. + */ + public function setLogger(LoggerInterface $logger): void + { + $this->logger = $logger; + } +} diff --git a/vendor/psr/log/src/LoggerInterface.php b/vendor/psr/log/src/LoggerInterface.php new file mode 100644 index 0000000..cb4cf64 --- /dev/null +++ b/vendor/psr/log/src/LoggerInterface.php @@ -0,0 +1,98 @@ +<?php + +namespace Psr\Log; + +/** + * Describes a logger instance. + * + * The message MUST be a string or object implementing __toString(). + * + * The message MAY contain placeholders in the form: {foo} where foo + * will be replaced by the context data in key "foo". + * + * The context array can contain arbitrary data. The only assumption that + * can be made by implementors is that if an Exception instance is given + * to produce a stack trace, it MUST be in a key named "exception". + * + * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md + * for the full interface specification. + */ +interface LoggerInterface +{ + /** + * System is unusable. + * + * @param mixed[] $context + */ + public function emergency(string|\Stringable $message, array $context = []): void; + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param mixed[] $context + */ + public function alert(string|\Stringable $message, array $context = []): void; + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param mixed[] $context + */ + public function critical(string|\Stringable $message, array $context = []): void; + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param mixed[] $context + */ + public function error(string|\Stringable $message, array $context = []): void; + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param mixed[] $context + */ + public function warning(string|\Stringable $message, array $context = []): void; + + /** + * Normal but significant events. + * + * @param mixed[] $context + */ + public function notice(string|\Stringable $message, array $context = []): void; + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param mixed[] $context + */ + public function info(string|\Stringable $message, array $context = []): void; + + /** + * Detailed debug information. + * + * @param mixed[] $context + */ + public function debug(string|\Stringable $message, array $context = []): void; + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param mixed[] $context + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []): void; +} diff --git a/vendor/psr/log/src/LoggerTrait.php b/vendor/psr/log/src/LoggerTrait.php new file mode 100644 index 0000000..a5d9980 --- /dev/null +++ b/vendor/psr/log/src/LoggerTrait.php @@ -0,0 +1,98 @@ +<?php + +namespace Psr\Log; + +/** + * This is a simple Logger trait that classes unable to extend AbstractLogger + * (because they extend another class, etc) can include. + * + * It simply delegates all log-level-specific methods to the `log` method to + * reduce boilerplate code that a simple Logger that does the same thing with + * messages regardless of the error level has to implement. + */ +trait LoggerTrait +{ + /** + * System is unusable. + */ + public function emergency(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::EMERGENCY, $message, $context); + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + */ + public function alert(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ALERT, $message, $context); + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + */ + public function critical(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + */ + public function error(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ERROR, $message, $context); + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + */ + public function warning(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::WARNING, $message, $context); + } + + /** + * Normal but significant events. + */ + public function notice(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::NOTICE, $message, $context); + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + */ + public function info(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::INFO, $message, $context); + } + + /** + * Detailed debug information. + */ + public function debug(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::DEBUG, $message, $context); + } + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * + * @throws \Psr\Log\InvalidArgumentException + */ + abstract public function log($level, string|\Stringable $message, array $context = []): void; +} diff --git a/vendor/psr/log/src/NullLogger.php b/vendor/psr/log/src/NullLogger.php new file mode 100644 index 0000000..de0561e --- /dev/null +++ b/vendor/psr/log/src/NullLogger.php @@ -0,0 +1,26 @@ +<?php + +namespace Psr\Log; + +/** + * This Logger can be used to avoid conditional log calls. + * + * Logging should always be optional, and if no logger is provided to your + * library creating a NullLogger instance to have something to throw logs at + * is a good way to avoid littering your code with `if ($this->logger) { }` + * blocks. + */ +class NullLogger extends AbstractLogger +{ + /** + * Logs with an arbitrary level. + * + * @param mixed[] $context + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []): void + { + // noop + } +} diff --git a/vendor/symfony/deprecation-contracts/CHANGELOG.md b/vendor/symfony/deprecation-contracts/CHANGELOG.md new file mode 100644 index 0000000..7932e26 --- /dev/null +++ b/vendor/symfony/deprecation-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/vendor/symfony/deprecation-contracts/LICENSE b/vendor/symfony/deprecation-contracts/LICENSE new file mode 100644 index 0000000..0ed3a24 --- /dev/null +++ b/vendor/symfony/deprecation-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-present 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 +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/symfony/deprecation-contracts/README.md b/vendor/symfony/deprecation-contracts/README.md new file mode 100644 index 0000000..9814864 --- /dev/null +++ b/vendor/symfony/deprecation-contracts/README.md @@ -0,0 +1,26 @@ +Symfony Deprecation Contracts +============================= + +A generic function and convention to trigger deprecation notices. + +This package provides a single global function named `trigger_deprecation()` that triggers silenced deprecation notices. + +By using a custom PHP error handler such as the one provided by the Symfony ErrorHandler component, +the triggered deprecations can be caught and logged for later discovery, both on dev and prod environments. + +The function requires at least 3 arguments: + - the name of the Composer package that is triggering the deprecation + - the version of the package that introduced the deprecation + - the message of the deprecation + - more arguments can be provided: they will be inserted in the message using `printf()` formatting + +Example: +```php +trigger_deprecation('symfony/blockchain', '8.9', 'Using "%s" is deprecated, use "%s" instead.', 'bitcoin', 'fabcoin'); +``` + +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 +`function trigger_deprecation() {}` in your application. diff --git a/vendor/symfony/deprecation-contracts/composer.json b/vendor/symfony/deprecation-contracts/composer.json new file mode 100644 index 0000000..d6a39dc --- /dev/null +++ b/vendor/symfony/deprecation-contracts/composer.json @@ -0,0 +1,35 @@ +{ + "name": "symfony/deprecation-contracts", + "type": "library", + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1" + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "3.8-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/vendor/symfony/deprecation-contracts/function.php b/vendor/symfony/deprecation-contracts/function.php new file mode 100644 index 0000000..2d56512 --- /dev/null +++ b/vendor/symfony/deprecation-contracts/function.php @@ -0,0 +1,27 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (!function_exists('trigger_deprecation')) { + /** + * Triggers a silenced deprecation notice. + * + * @param string $package The name of the Composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string $message The message of the deprecation + * @param mixed ...$args Values to insert in the message using printf() formatting + * + * @author Nicolas Grekas <p@tchwork.com> + */ + function trigger_deprecation(string $package, string $version, string $message, mixed ...$args): void + { + @trigger_error(($package || $version ? "Since $package $version: " : '').($args ? vsprintf($message, $args) : $message), \E_USER_DEPRECATED); + } +} diff --git a/vendor/symfony/polyfill-ctype/Ctype.php b/vendor/symfony/polyfill-ctype/Ctype.php new file mode 100644 index 0000000..e26cc02 --- /dev/null +++ b/vendor/symfony/polyfill-ctype/Ctype.php @@ -0,0 +1,232 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Ctype; + +/** + * Ctype implementation through regex. + * + * @internal + * + * @author Gert de Pagter <BackEndTea@gmail.com> + */ +final class Ctype +{ + /** + * Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. + * + * @see https://php.net/ctype-alnum + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_alnum($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text); + } + + /** + * Returns TRUE if every character in text is a letter, FALSE otherwise. + * + * @see https://php.net/ctype-alpha + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_alpha($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text); + } + + /** + * Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise. + * + * @see https://php.net/ctype-cntrl + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_cntrl($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text); + } + + /** + * Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise. + * + * @see https://php.net/ctype-digit + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_digit($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text); + } + + /** + * Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise. + * + * @see https://php.net/ctype-graph + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_graph($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text); + } + + /** + * Returns TRUE if every character in text is a lowercase letter. + * + * @see https://php.net/ctype-lower + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_lower($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text); + } + + /** + * Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all. + * + * @see https://php.net/ctype-print + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_print($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text); + } + + /** + * Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise. + * + * @see https://php.net/ctype-punct + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_punct($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text); + } + + /** + * Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. + * + * @see https://php.net/ctype-space + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_space($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text); + } + + /** + * Returns TRUE if every character in text is an uppercase letter. + * + * @see https://php.net/ctype-upper + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_upper($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text); + } + + /** + * Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise. + * + * @see https://php.net/ctype-xdigit + * + * @param mixed $text + * + * @return bool + */ + public static function ctype_xdigit($text) + { + $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text); + } + + /** + * Converts integers to their char versions according to normal ctype behaviour, if needed. + * + * If an integer between -128 and 255 inclusive is provided, + * it is interpreted as the ASCII value of a single character + * (negative values have 256 added in order to allow characters in the Extended ASCII range). + * Any other integer is interpreted as a string containing the decimal digits of the integer. + * + * @param mixed $int + * @param string $function + * + * @return mixed + */ + private static function convert_int_to_char_for_ctype($int, $function) + { + if (\PHP_VERSION_ID >= 80100 && !\is_string($int)) { + @trigger_error($function.'(): Argument of type '.get_debug_type($int).' will be interpreted as string in the future', \E_USER_DEPRECATED); + } + + if (!\is_int($int)) { + return $int; + } + + if ($int < -128 || $int > 255) { + return (string) $int; + } + + if ($int < 0) { + $int += 256; + } + + return \chr($int); + } +} diff --git a/vendor/symfony/polyfill-ctype/LICENSE b/vendor/symfony/polyfill-ctype/LICENSE new file mode 100644 index 0000000..7536cae --- /dev/null +++ b/vendor/symfony/polyfill-ctype/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-present 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 +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/symfony/polyfill-ctype/README.md b/vendor/symfony/polyfill-ctype/README.md new file mode 100644 index 0000000..b144d03 --- /dev/null +++ b/vendor/symfony/polyfill-ctype/README.md @@ -0,0 +1,12 @@ +Symfony Polyfill / Ctype +======================== + +This component provides `ctype_*` functions to users who run php versions without the ctype extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/vendor/symfony/polyfill-ctype/bootstrap.php b/vendor/symfony/polyfill-ctype/bootstrap.php new file mode 100644 index 0000000..d54524b --- /dev/null +++ b/vendor/symfony/polyfill-ctype/bootstrap.php @@ -0,0 +1,50 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Ctype as p; + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!function_exists('ctype_alnum')) { + function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); } +} +if (!function_exists('ctype_alpha')) { + function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); } +} +if (!function_exists('ctype_cntrl')) { + function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); } +} +if (!function_exists('ctype_digit')) { + function ctype_digit($text) { return p\Ctype::ctype_digit($text); } +} +if (!function_exists('ctype_graph')) { + function ctype_graph($text) { return p\Ctype::ctype_graph($text); } +} +if (!function_exists('ctype_lower')) { + function ctype_lower($text) { return p\Ctype::ctype_lower($text); } +} +if (!function_exists('ctype_print')) { + function ctype_print($text) { return p\Ctype::ctype_print($text); } +} +if (!function_exists('ctype_punct')) { + function ctype_punct($text) { return p\Ctype::ctype_punct($text); } +} +if (!function_exists('ctype_space')) { + function ctype_space($text) { return p\Ctype::ctype_space($text); } +} +if (!function_exists('ctype_upper')) { + function ctype_upper($text) { return p\Ctype::ctype_upper($text); } +} +if (!function_exists('ctype_xdigit')) { + function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); } +} diff --git a/vendor/symfony/polyfill-ctype/bootstrap80.php b/vendor/symfony/polyfill-ctype/bootstrap80.php new file mode 100644 index 0000000..ab2f861 --- /dev/null +++ b/vendor/symfony/polyfill-ctype/bootstrap80.php @@ -0,0 +1,46 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Ctype as p; + +if (!function_exists('ctype_alnum')) { + function ctype_alnum(mixed $text): bool { return p\Ctype::ctype_alnum($text); } +} +if (!function_exists('ctype_alpha')) { + function ctype_alpha(mixed $text): bool { return p\Ctype::ctype_alpha($text); } +} +if (!function_exists('ctype_cntrl')) { + function ctype_cntrl(mixed $text): bool { return p\Ctype::ctype_cntrl($text); } +} +if (!function_exists('ctype_digit')) { + function ctype_digit(mixed $text): bool { return p\Ctype::ctype_digit($text); } +} +if (!function_exists('ctype_graph')) { + function ctype_graph(mixed $text): bool { return p\Ctype::ctype_graph($text); } +} +if (!function_exists('ctype_lower')) { + function ctype_lower(mixed $text): bool { return p\Ctype::ctype_lower($text); } +} +if (!function_exists('ctype_print')) { + function ctype_print(mixed $text): bool { return p\Ctype::ctype_print($text); } +} +if (!function_exists('ctype_punct')) { + function ctype_punct(mixed $text): bool { return p\Ctype::ctype_punct($text); } +} +if (!function_exists('ctype_space')) { + function ctype_space(mixed $text): bool { return p\Ctype::ctype_space($text); } +} +if (!function_exists('ctype_upper')) { + function ctype_upper(mixed $text): bool { return p\Ctype::ctype_upper($text); } +} +if (!function_exists('ctype_xdigit')) { + function ctype_xdigit(mixed $text): bool { return p\Ctype::ctype_xdigit($text); } +} diff --git a/vendor/symfony/polyfill-ctype/composer.json b/vendor/symfony/polyfill-ctype/composer.json new file mode 100644 index 0000000..131ca7a --- /dev/null +++ b/vendor/symfony/polyfill-ctype/composer.json @@ -0,0 +1,38 @@ +{ + "name": "symfony/polyfill-ctype", + "type": "library", + "description": "Symfony polyfill for ctype functions", + "keywords": ["polyfill", "compatibility", "portable", "ctype"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2" + }, + "provide": { + "ext-ctype": "*" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Ctype\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/vendor/symfony/polyfill-mbstring/LICENSE b/vendor/symfony/polyfill-mbstring/LICENSE new file mode 100644 index 0000000..6e3afce --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present 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 +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/symfony/polyfill-mbstring/Mbstring.php b/vendor/symfony/polyfill-mbstring/Mbstring.php new file mode 100644 index 0000000..5a59d26 --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/Mbstring.php @@ -0,0 +1,1662 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Mbstring; + +/** + * Partial mbstring implementation in PHP, iconv based, UTF-8 centric. + * + * Implemented: + * - mb_chr - Returns a specific character from its Unicode code point + * - mb_convert_encoding - Convert character encoding + * - mb_convert_variables - Convert character code in variable(s) + * - mb_decode_mimeheader - Decode string in MIME header field + * - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED + * - mb_decode_numericentity - Decode HTML numeric string reference to character + * - mb_encode_numericentity - Encode character to HTML numeric string reference + * - mb_convert_case - Perform case folding on a string + * - mb_detect_encoding - Detect character encoding + * - mb_get_info - Get internal settings of mbstring + * - mb_http_input - Detect HTTP input character encoding + * - mb_http_output - Set/Get HTTP output character encoding + * - mb_internal_encoding - Set/Get internal character encoding + * - mb_list_encodings - Returns an array of all supported encodings + * - mb_ord - Returns the Unicode code point of a character + * - mb_output_handler - Callback function converts character encoding in output buffer + * - mb_scrub - Replaces ill-formed byte sequences with substitute characters + * - mb_strlen - Get string length + * - mb_strpos - Find position of first occurrence of string in a string + * - mb_strrpos - Find position of last occurrence of a string in a string + * - mb_str_split - Convert a string to an array + * - mb_strtolower - Make a string lowercase + * - mb_strtoupper - Make a string uppercase + * - mb_substitute_character - Set/Get substitution character + * - mb_substr - Get part of string + * - mb_stripos - Finds position of first occurrence of a string within another, case insensitive + * - mb_stristr - Finds first occurrence of a string within another, case insensitive + * - mb_strrchr - Finds the last occurrence of a character in a string within another + * - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive + * - mb_strripos - Finds position of last occurrence of a string within another, case insensitive + * - mb_strstr - Finds first occurrence of a string within another + * - mb_strwidth - Return width of string + * - mb_substr_count - Count the number of substring occurrences + * - mb_ucfirst - Make a string's first character uppercase + * - mb_lcfirst - Make a string's first character lowercase + * - mb_trim - Strip whitespace (or other characters) from the beginning and end of a string + * - mb_ltrim - Strip whitespace (or other characters) from the beginning of a string + * - mb_rtrim - Strip whitespace (or other characters) from the end of a string + * + * Not implemented: + * - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more) + * - mb_ereg_* - Regular expression with multibyte support + * - mb_parse_str - Parse GET/POST/COOKIE data and set global variable + * - mb_preferred_mime_name - Get MIME charset string + * - mb_regex_encoding - Returns current encoding for multibyte regex as string + * - mb_regex_set_options - Set/Get the default options for mbregex functions + * - mb_send_mail - Send encoded mail + * - mb_split - Split multibyte string using regular expression + * - mb_strcut - Get part of string + * - mb_strimwidth - Get truncated string with specified width + * + * @author Nicolas Grekas <p@tchwork.com> + * + * @internal + */ +final class Mbstring +{ + public const MB_CASE_FOLD = \PHP_INT_MAX; + + private const SIMPLE_CASE_FOLD = [ + ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"], + ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'], + ]; + + // Encodings rejected by mb_ord() and mb_chr(), with their aliases + private const UNSUPPORTED_CODEPOINT_ENCODINGS = [ + 'BASE64' => 'BASE64', + 'UUENCODE' => 'UUENCODE', + 'X-UUENCODE' => 'UUENCODE', + 'HTML-ENTITIES' => 'HTML-ENTITIES', + 'HTML' => 'HTML-ENTITIES', + 'QUOTED-PRINTABLE' => 'Quoted-Printable', + 'QPRINT' => 'Quoted-Printable', + 'UTF-7' => 'UTF-7', + 'UTF7' => 'UTF-7', + 'UTF7-IMAP' => 'UTF7-IMAP', + 'MUTF-7' => 'UTF7-IMAP', + 'JIS' => 'JIS', + 'ISO-2022-JP' => 'ISO-2022-JP', + 'ISO-2022-JP-2004' => 'ISO-2022-JP-2004', + 'ISO-2022-JP-MOBILE#KDDI' => 'ISO-2022-JP-MOBILE#KDDI', + 'ISO-2022-JP-KDDI' => 'ISO-2022-JP-MOBILE#KDDI', + 'ISO-2022-JP-MS' => 'ISO-2022-JP-MS', + 'ISO2022JPMS' => 'ISO-2022-JP-MS', + 'CP50220' => 'CP50220', + 'CP50220RAW' => 'CP50220', + 'CP50220-RAW' => 'CP50220', + 'JIS-MS' => 'CP50220', + 'CP50221' => 'CP50221', + 'CP50222' => 'CP50222', + ]; + + // Well-formed characters in group 1, then the maximal subparts of ill-formed sequences + private const UTF8_CHAR_REGEX = '/([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})|\xE0[\xA0-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]|\xED[\x80-\x9F]|\xF0[\x90-\xBF][\x80-\xBF]?|[\xF1-\xF3][\x80-\xBF]{1,2}|\xF4[\x80-\x8F][\x80-\xBF]?|[\x80-\xFF]/'; + + private static $encodingList = ['ASCII', 'UTF-8']; + private static $language = 'neutral'; + private static $internalEncoding = 'UTF-8'; + private static $iconvSupportsIgnore; + private static $convertibleEncodings = ['UTF-8' => true]; + + public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null) + { + if (\is_string($fromEncoding) && 2 < \strlen($fromEncoding) && '"' === $fromEncoding[0] && '"' === $fromEncoding[-1]) { + $fromEncoding = substr($fromEncoding, 1, -1); + } + + if (80000 <= \PHP_VERSION_ID + && (!isset(self::$convertibleEncodings[$toEncoding]) || (null !== $fromEncoding && !(\is_string($fromEncoding) && isset(self::$convertibleEncodings[$fromEncoding])))) + && null !== $error = self::getConversionError('mb_convert_encoding', 2, $toEncoding, $fromEncoding) + ) { + throw new \ValueError($error); + } + + if (\is_array($s)) { + return self::convertArray($s, $toEncoding, $fromEncoding); + } + + if (\is_array($fromEncoding) || (null !== $fromEncoding && false !== strpos($fromEncoding, ','))) { + $fromEncoding = self::mb_detect_encoding($s, $fromEncoding); + } else { + $fromEncoding = self::getEncoding($fromEncoding); + } + + $toEncoding = self::getEncoding($toEncoding); + + if ('BASE64' === $fromEncoding) { + $s = base64_decode($s); + $fromEncoding = $toEncoding; + } + + if ('BASE64' === $toEncoding) { + return base64_encode($s); + } + + if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) { + if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) { + $fromEncoding = 'Windows-1252'; + } + if ('UTF-8' !== $fromEncoding) { + $s = self::iconv($fromEncoding, 'UTF-8', $s); + } elseif (!preg_match('//u', $s)) { + $s = self::scrubUtf8($s); + } + + return preg_replace_callback('/[\x80-\xFF]+/', [__CLASS__, 'html_encoding_callback'], $s); + } + + if ('HTML-ENTITIES' === $fromEncoding) { + $decodeControlChars = static function ($m) { + $code = '' !== ($m[2] ?? '') ? hexdec($m[2]) : (int) $m[1]; + + if ($code < 32 || 127 === $code) { + return \chr($code); + } + if (128 <= $code && $code <= 159) { + return "\xC2".\chr(0x80 | ($code & 0x3F)); + } + + return $m[0]; + }; + + if (\PHP_VERSION_ID >= 70400) { + $s = html_entity_decode($s, \ENT_QUOTES, 'UTF-8'); + // html_entity_decode() leaves numeric entities for C0/C1 control + // characters as-is (HTML spec), but mb_convert_encoding() decodes + // them. Catch what html_entity_decode() missed. + if (false !== strpos($s, '&#')) { + $s = preg_replace_callback('/&#(?:0*([0-9]++)|[xX]0*([0-9a-fA-F]++));/', $decodeControlChars, $s); + } + } else { + // PHP < 7.4: html_entity_decode() truncates strings at NUL bytes, + // so decode the control character entities first then call + // html_entity_decode() on each NUL-delimited chunk independently. + $s = preg_replace_callback('/&#(?:0*([0-9]++)|[xX]0*([0-9a-fA-F]++));/', $decodeControlChars, $s); + $s = implode("\0", array_map(static function ($chunk) { + return html_entity_decode($chunk, \ENT_QUOTES, 'UTF-8'); + }, explode("\0", $s))); + } + $fromEncoding = 'UTF-8'; + } + + if ('UTF-8' === $fromEncoding && !preg_match('//u', $s)) { + $s = self::scrubUtf8($s); + } + + return self::iconv($fromEncoding, $toEncoding, $s); + } + + public static function mb_convert_variables($toEncoding, $fromEncoding, &...$vars) + { + if (\is_string($fromEncoding) && 2 < \strlen($fromEncoding) && '"' === $fromEncoding[0] && '"' === $fromEncoding[-1]) { + $fromEncoding = substr($fromEncoding, 1, -1); + } + + if (80000 <= \PHP_VERSION_ID && null !== $error = self::getConversionError('mb_convert_variables', 1, $toEncoding, $fromEncoding)) { + throw new \ValueError($error); + } + + $ok = true; + foreach ($vars as $i => &$var) { + $convert = static function (&$v) use (&$ok, $toEncoding, $fromEncoding, $i) { + if (\is_string($v)) { + if (false === $v = self::mb_convert_encoding($v, $toEncoding, $fromEncoding)) { + $ok = false; + } + } elseif (80600 <= \PHP_VERSION_ID && !\is_object($v)) { + trigger_error(\sprintf('mb_convert_variables(): Argument #%d must be of type string|array|object or only contain entries of type string|array|object, %s given', 3 + $i, strtok(get_debug_type($v), ' ')), \E_USER_WARNING); + } + }; + + if (\is_array($var)) { + array_walk_recursive($var, $convert); + } else { + $convert($var); + } + } + unset($var); + + return $ok ? $fromEncoding : false; + } + + public static function mb_decode_mimeheader($s) + { + return iconv_mime_decode($s, 2, self::$internalEncoding); + } + + public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null) + { + trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', \E_USER_WARNING); + } + + public static function mb_decode_numericentity($s, $convmap, $encoding = null) + { + if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { + return false; + } + + if (null !== $encoding && !\is_scalar($encoding)) { + trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return ''; // Instead of null (cf. mb_encode_numericentity). + } + + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = self::scrubUtf8($s); + } + } else { + $s = self::iconv($encoding, 'UTF-8', $s); + } + + $cnt = floor(\count($convmap) / 4) * 4; + + for ($i = 0; $i < $cnt; $i += 4) { + // collector_decode_htmlnumericentity ignores $convmap[$i + 3] + $convmap[$i] += $convmap[$i + 2]; + $convmap[$i + 1] += $convmap[$i + 2]; + } + + $s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))'.(\PHP_VERSION_ID >= 80200 ? '' : '(?!&)').';?/', static function (array $m) use ($cnt, $convmap) { + $c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1]; + for ($i = 0; $i < $cnt; $i += 4) { + if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) { + return self::mb_chr($c - $convmap[$i + 2]); + } + } + + return $m[0]; + }, $s); + + if (null === $encoding) { + return $s; + } + + return self::iconv('UTF-8', $encoding, $s); + } + + public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false) + { + if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { + return false; + } + + if (null !== $encoding && !\is_scalar($encoding)) { + trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; // Instead of '' (cf. mb_decode_numericentity). + } + + if (null !== $is_hex && !\is_scalar($is_hex)) { + trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = self::scrubUtf8($s); + } + } else { + $s = self::iconv($encoding, 'UTF-8', $s); + } + + static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + + $cnt = floor(\count($convmap) / 4) * 4; + $i = 0; + $len = \strlen($s); + $result = ''; + + while ($i < $len) { + $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"] ?? 1; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + + // code points above U+10FFFF are outside any convmap, but mb_ord() rejects them + if (false === $c = self::mb_ord($uchr)) { + $result .= $uchr; + continue; + } + + for ($j = 0; $j < $cnt; $j += 4) { + if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) { + $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3]; + $result .= $is_hex ? \sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';'; + continue 2; + } + } + $result .= $uchr; + } + + if (null === $encoding) { + return $result; + } + + return self::iconv('UTF-8', $encoding, $result); + } + + public static function mb_convert_case($s, $mode, $encoding = null) + { + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = self::scrubUtf8($s); + } + } else { + $s = self::iconv($encoding, 'UTF-8', $s); + } + + if (\MB_CASE_TITLE == $mode) { + static $titleRegexp = null; + if (null === $titleRegexp) { + $titleRegexp = self::getData('titleCaseRegexp'); + } + $s = preg_replace_callback($titleRegexp, [__CLASS__, 'title_case'], $s); + } else { + if (\MB_CASE_UPPER == $mode) { + static $upper = null; + if (null === $upper) { + $upper = self::getData('upperCase'); + } + $map = $upper; + } else { + if (self::MB_CASE_FOLD === $mode) { + static $caseFolding = null; + if (null === $caseFolding) { + $caseFolding = self::getData('caseFolding'); + } + $s = strtr($s, $caseFolding); + } + + static $lower = null; + if (null === $lower) { + $lower = self::getData('lowerCase'); + } + $map = $lower; + } + + static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + + $i = 0; + $len = \strlen($s); + + while ($i < $len) { + $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"] ?? 1; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + + if (isset($map[$uchr])) { + $uchr = $map[$uchr]; + $nlen = \strlen($uchr); + + if ($nlen == $ulen) { + $nlen = $i; + do { + $s[--$nlen] = $uchr[--$ulen]; + } while ($ulen); + } else { + $s = substr_replace($s, $uchr, $i - $ulen, $ulen); + $len += $nlen - $ulen; + $i += $nlen - $ulen; + } + } + } + } + + if (null === $encoding) { + return $s; + } + + return self::iconv('UTF-8', $encoding, $s); + } + + public static function mb_internal_encoding($encoding = null) + { + if (null === $encoding) { + return self::$internalEncoding; + } + + $normalizedEncoding = self::getEncoding($encoding); + + if ('UTF-8' === $normalizedEncoding || false !== @iconv($normalizedEncoding, $normalizedEncoding, ' ')) { + self::$internalEncoding = $normalizedEncoding; + + return true; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError(\sprintf('Argument #1 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + public static function mb_language($lang = null) + { + if (null === $lang) { + return self::$language; + } + + switch ($normalizedLang = strtolower($lang)) { + case 'uni': + case 'neutral': + self::$language = $normalizedLang; + + return true; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError(\sprintf('Argument #1 ($language) must be a valid language, "%s" given', $lang)); + } + + public static function mb_list_encodings() + { + return ['UTF-8']; + } + + public static function mb_encoding_aliases($encoding) + { + switch (strtoupper($encoding)) { + case 'UTF8': + case 'UTF-8': + return ['utf8']; + } + + return false; + } + + public static function mb_check_encoding($var = null, $encoding = null) + { + if (null === $encoding) { + if (null === $var) { + return false; + } + $encoding = self::$internalEncoding; + } + + if (!\is_array($var)) { + if ('UTF-8' === self::getEncoding($encoding)) { + return (bool) preg_match('//u', $var); + } + + return self::mb_detect_encoding($var, [$encoding]) || false !== @iconv($encoding, $encoding, $var); + } + + foreach ($var as $key => $value) { + if (!self::mb_check_encoding($key, $encoding)) { + return false; + } + if (!self::mb_check_encoding($value, $encoding)) { + return false; + } + } + + return true; + } + + public static function mb_detect_encoding($str, $encodingList = null, $strict = false) + { + if (null === $encodingList) { + $encodingList = self::$encodingList; + } else { + if (!\is_array($encodingList)) { + $encodingList = array_map('trim', explode(',', $encodingList)); + } + $encodingList = array_map('strtoupper', $encodingList); + } + + foreach ($encodingList as $enc) { + switch ($enc) { + case 'ASCII': + if (!preg_match('/[\x80-\xFF]/', $str)) { + return $enc; + } + break; + + case 'UTF8': + case 'UTF-8': + if (preg_match('//u', $str)) { + return 'UTF-8'; + } + break; + + default: + if (0 === strncmp($enc, 'ISO-8859-', 9)) { + return $enc; + } + } + } + + return false; + } + + public static function mb_detect_order($encodingList = null) + { + if (null === $encodingList) { + return self::$encodingList; + } + + if (!\is_array($encodingList)) { + $encodingList = array_map('trim', explode(',', $encodingList)); + } + $encodingList = array_map('strtoupper', $encodingList); + + foreach ($encodingList as $enc) { + switch ($enc) { + default: + if (strncmp($enc, 'ISO-8859-', 9)) { + return false; + } + // no break + case 'ASCII': + case 'UTF8': + case 'UTF-8': + } + } + + self::$encodingList = $encodingList; + + return true; + } + + public static function mb_strlen($s, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return \strlen($s); + } + + if (false !== $len = @iconv_strlen($s, $encoding)) { + return $len; + } + + if ('UTF-8' !== $encoding) { + return $len; + } + + return preg_match_all('/[\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]?|[\xE0-\xEF][\x80-\xBF]{0,2}|[\xF0-\xF7][\x80-\xBF]{0,3}|[\xF8-\xFB][\x80-\xBF]{0,4}|[\xFC-\xFD][\x80-\xBF]{0,5}|[\x80-\xBF\xFE\xFF]/s', $s); + } + + public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) + { + return self::find(__FUNCTION__, $haystack, $needle, $offset, $encoding, false, false); + } + + public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) + { + if ($offset != (int) $offset) { + $offset = 0; + } + + return self::find(__FUNCTION__, $haystack, $needle, $offset, $encoding, true, false); + } + + public static function mb_str_split($string, $split_length = 1, $encoding = null) + { + if (null !== $string && !\is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) { + trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', \E_USER_WARNING); + + return null; + } + + if (1 > $split_length = (int) $split_length) { + if (80000 > \PHP_VERSION_ID) { + trigger_error('The length of each segment must be greater than zero', \E_USER_WARNING); + + return false; + } + + throw new \ValueError('Argument #2 ($length) must be greater than 0'); + } + + if (80300 <= \PHP_VERSION_ID && 0x3FFFFFFF < $split_length) { + throw new \ValueError('Argument #2 ($length) is too large'); + } + + if (null === $encoding) { + $encoding = mb_internal_encoding(); + } + + if ('UTF-8' === $encoding = self::getEncoding($encoding)) { + $string = (string) $string; + + if (\strlen($string) <= $split_length) { + return '' === $string ? [] : [$string]; + } + + $rx = '/('; + while (65535 < $split_length) { + $rx .= '.{65535}'; + $split_length -= 65535; + } + $rx .= '.{'.$split_length.'})/Aus'; + + return preg_split($rx, $string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); + } + + $result = []; + $length = mb_strlen($string, $encoding); + + for ($i = 0; $i < $length; $i += $split_length) { + $result[] = mb_substr($string, $i, $split_length, $encoding); + } + + return $result; + } + + public static function mb_strtolower($s, $encoding = null) + { + return self::mb_convert_case($s, \MB_CASE_LOWER, $encoding); + } + + public static function mb_strtoupper($s, $encoding = null) + { + return self::mb_convert_case($s, \MB_CASE_UPPER, $encoding); + } + + public static function mb_substitute_character($c = null) + { + if (null === $c) { + return 'none'; + } + if (0 === strcasecmp($c, 'none')) { + return true; + } + if (80000 > \PHP_VERSION_ID) { + return false; + } + if (\is_int($c) || 'long' === $c || 'entity' === $c) { + return false; + } + + throw new \ValueError('Argument #1 ($substitute_character) must be "none", "long", "entity" or a valid codepoint'); + } + + public static function mb_substr($s, $start, $length = null, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return (string) substr($s, $start, null === $length ? 2147483647 : $length); + } + + if ($start < 0) { + $start = iconv_strlen($s, $encoding) + $start; + if ($start < 0) { + $start = 0; + } + } + + if (null === $length) { + $length = 2147483647; + } elseif ($length < 0) { + $length = iconv_strlen($s, $encoding) + $length - $start; + if ($length < 0) { + return ''; + } + } + + return (string) iconv_substr($s, $start, $length, $encoding); + } + + public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) + { + return self::find(__FUNCTION__, $haystack, $needle, $offset, $encoding, false, true); + } + + public static function mb_stristr($haystack, $needle, $part = false, $encoding = null) + { + return self::findPart(__FUNCTION__, $haystack, $needle, $part, $encoding, false, true); + } + + public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null) + { + return self::findPart(__FUNCTION__, $haystack, $needle, $part, $encoding, true, false); + } + + public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null) + { + return self::findPart(__FUNCTION__, $haystack, $needle, $part, $encoding, true, true); + } + + public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) + { + return self::find(__FUNCTION__, $haystack, $needle, $offset, $encoding, true, true); + } + + public static function mb_strstr($haystack, $needle, $part = false, $encoding = null) + { + return self::findPart(__FUNCTION__, $haystack, $needle, $part, $encoding, false, false); + } + + public static function mb_get_info($type = 'all') + { + $info = [ + 'internal_encoding' => self::$internalEncoding, + 'http_output' => 'pass', + 'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)', + 'func_overload' => 0, + 'func_overload_list' => 'no overload', + 'mail_charset' => 'UTF-8', + 'mail_header_encoding' => 'BASE64', + 'mail_body_encoding' => 'BASE64', + 'illegal_chars' => 0, + 'encoding_translation' => 'Off', + 'language' => self::$language, + 'detect_order' => self::$encodingList, + 'substitute_character' => 'none', + 'strict_detection' => 'Off', + ]; + + if ('all' === $type) { + return $info; + } + if (isset($info[$type])) { + return $info[$type]; + } + + return false; + } + + public static function mb_http_input($type = '') + { + return false; + } + + public static function mb_http_output($encoding = null) + { + return null !== $encoding ? 'pass' === $encoding : 'pass'; + } + + public static function mb_strwidth($s, $encoding = null) + { + $encoding = self::getEncoding($encoding); + static $wideChars = null; + if (null === $wideChars) { + $wideChars = self::getData('eastAsianWidthRegexp'); + } + + if ('UTF-8' !== $encoding) { + $s = self::iconv($encoding, 'UTF-8', $s); + } elseif (!preg_match('//u', $s)) { + // Each maximal subpart of an ill-formed sequence is one column wide + return preg_match_all(self::UTF8_CHAR_REGEX, $s) + preg_match_all($wideChars, self::scrubUtf8($s)); + } + + $s = preg_replace($wideChars, '', $s, -1, $wide); + + return ($wide << 1) + iconv_strlen($s, 'UTF-8'); + } + + public static function mb_substr_count($haystack, $needle, $encoding = null) + { + if ('' === $needle = (string) $needle) { + if (80000 > \PHP_VERSION_ID) { + trigger_error('mb_substr_count(): Empty substring', \E_USER_WARNING); + + return false; + } + + throw new \ValueError('mb_substr_count(): Argument #2 ($needle) must not be empty'); + } + + if (!$search = self::prepareSearch((string) $haystack, $needle, self::getEncoding($encoding), false, true)) { + return 0; + } + + return substr_count($search[0], $search[1]); + } + + public static function mb_output_handler($contents, $status) + { + return $contents; + } + + public static function mb_chr($code, $encoding = null) + { + if (null !== $encoding && !self::assertCodepointEncoding($encoding, 'mb_chr')) { + return false; + } + + if (0x80 > $code %= 0x200000) { + $s = \chr($code); + } elseif (0x800 > $code) { + $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); + } elseif (0x10000 > $code) { + $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } else { + $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } + + if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { + $s = mb_convert_encoding($s, $encoding, 'UTF-8'); + } + + return $s; + } + + public static function mb_ord($s, $encoding = null) + { + if ('' === (string) $s) { + if (80000 > \PHP_VERSION_ID) { + trigger_error('mb_ord(): Empty string', \E_USER_WARNING); + + return false; + } + + throw new \ValueError('mb_ord(): Argument #1 ($string) must not be empty'); + } + + if (null !== $encoding && !self::assertCodepointEncoding($encoding, 'mb_ord')) { + return false; + } + + if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { + $s = mb_convert_encoding($s, 'UTF-8', $encoding); + } + + $s = unpack('C*', substr($s, 0, 4)); + $code = $s[1] ?? 0; + if (0x80 > $code) { + return $code; + } + + if (0xC2 > $code || 0xF4 < $code) { + return false; + } + + $c2 = $s[2] ?? 0; + if (0x80 !== ($c2 & 0xC0)) { + return false; + } + + if (0xE0 > $code) { + return (($code & 0x1F) << 6) | ($c2 & 0x3F); + } + + $c3 = $s[3] ?? 0; + if (0x80 !== ($c3 & 0xC0) + || 0xE0 === $code && 0xA0 > $c2 + || 0xED === $code && 0xA0 <= $c2 + ) { + return false; + } + + if (0xF0 > $code) { + return (($code & 0x0F) << 12) | (($c2 & 0x3F) << 6) | ($c3 & 0x3F); + } + + $c4 = $s[4] ?? 0; + if (0x80 !== ($c4 & 0xC0) + || 0xF0 === $code && 0x90 > $c2 + || 0xF4 === $code && 0x90 <= $c2 + ) { + return false; + } + + return (($code & 0x07) << 18) | (($c2 & 0x3F) << 12) | (($c3 & 0x3F) << 6) | ($c4 & 0x3F); + } + + /** @return string|false */ + public static function mb_scrub(?string $string, ?string $encoding = null): string + { + if (null === $encoding) { + $encoding = self::mb_internal_encoding(); + } elseif (!self::assertEncoding($encoding, 'mb_scrub(): Argument #2 ($encoding) must be a valid encoding, "%s" given')) { + return false; + } + + return self::mb_convert_encoding((string) $string, $encoding, $encoding); + } + + /** @return string|false */ + public static function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = \STR_PAD_RIGHT, ?string $encoding = null) + { + if (null === $encoding) { + $encoding = self::mb_internal_encoding(); + } elseif (!self::assertEncoding($encoding, 'mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given')) { + return false; + } + + if (0 >= $padStringLength = self::mb_strlen($pad_string, $encoding)) { + if (\PHP_VERSION_ID < 80000) { + trigger_error('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string', \E_USER_WARNING); + + return false; + } + + throw new \ValueError('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string'); + } + + if (!\in_array($pad_type, [\STR_PAD_RIGHT, \STR_PAD_LEFT, \STR_PAD_BOTH], true)) { + if (\PHP_VERSION_ID < 80000) { + trigger_error('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH', \E_USER_WARNING); + + return false; + } + + throw new \ValueError('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH'); + } + + $paddingRequired = $length - self::mb_strlen($string, $encoding); + + if ($paddingRequired < 1) { + return $string; + } + + switch ($pad_type) { + case \STR_PAD_LEFT: + $leftPaddingLength = $paddingRequired; + break; + case \STR_PAD_RIGHT: + $leftPaddingLength = 0; + break; + default: + $leftPaddingLength = intdiv($paddingRequired, 2); + } + + $rightPaddingLength = $paddingRequired - $leftPaddingLength; + + return str_repeat($pad_string, intdiv($leftPaddingLength, $padStringLength)).self::mb_substr($pad_string, 0, $leftPaddingLength % $padStringLength, $encoding) + .$string + .str_repeat($pad_string, intdiv($rightPaddingLength, $padStringLength)).self::mb_substr($pad_string, 0, $rightPaddingLength % $padStringLength, $encoding); + } + + /** @return string|false */ + public static function mb_ucfirst(string $string, ?string $encoding = null) + { + if (null === $encoding) { + $encoding = self::mb_internal_encoding(); + } elseif (!self::assertEncoding($encoding, 'mb_ucfirst(): Argument #2 ($encoding) must be a valid encoding, "%s" given')) { + return false; + } + + $firstChar = mb_substr($string, 0, 1, $encoding); + $firstChar = mb_convert_case($firstChar, \MB_CASE_TITLE, $encoding); + + return $firstChar.mb_substr($string, 1, null, $encoding); + } + + /** @return string|false */ + public static function mb_lcfirst(string $string, ?string $encoding = null) + { + if (null === $encoding) { + $encoding = self::mb_internal_encoding(); + } elseif (!self::assertEncoding($encoding, 'mb_lcfirst(): Argument #2 ($encoding) must be a valid encoding, "%s" given')) { + return false; + } + + $firstChar = mb_substr($string, 0, 1, $encoding); + $firstChar = mb_convert_case($firstChar, \MB_CASE_LOWER, $encoding); + + return $firstChar.mb_substr($string, 1, null, $encoding); + } + + /** @return string|false */ + public static function mb_trim(string $string, ?string $characters = null, ?string $encoding = null) + { + return self::mb_internal_trim('{^[%s]+|[%1$s]+$}Du', $string, $characters, $encoding, __FUNCTION__); + } + + /** @return string|false */ + public static function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null) + { + return self::mb_internal_trim('{^[%s]+}Du', $string, $characters, $encoding, __FUNCTION__); + } + + /** @return string|false */ + public static function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null) + { + return self::mb_internal_trim('{[%s]+$}Du', $string, $characters, $encoding, __FUNCTION__); + } + + /** + * Finds the position of $needle in $haystack like native mbstring. + * + * @return int|false + */ + private static function find(string $function, $haystack, $needle, $offset, $encoding, bool $reverse, bool $fold) + { + $needle = (string) $needle; + + if (80000 > \PHP_VERSION_ID && '' === $needle && 'mb_stripos' === $function) { + trigger_error($function.'(): Empty delimiter', \E_USER_WARNING); + + return false; + } + + if (!$search = self::prepareSearch((string) $haystack, $needle, self::searchEncoding($encoding, $fold), $fold, $fold)) { + return false; + } + + [$haystack, $needle, $bytes, $dropped] = $search; + + if (80000 > \PHP_VERSION_ID && $fold && ('' === $haystack || '' === $needle)) { + return false; + } + + if (false === $start = self::utf8Offset($haystack, $offset = (int) $offset, $bytes)) { + // Native mbstring counts the ill-formed sequences that iconv() dropped: the offset could be in range + if ($dropped && abs($offset) <= self::utf8Length($haystack) + $dropped) { + return false; + } + + if (80000 > \PHP_VERSION_ID) { + trigger_error($function.'(): '.($reverse ? 'Offset is greater than the length of haystack string' : 'Offset not contained in string'), \E_USER_WARNING); + + return false; + } + + throw new \ValueError($function.'(): Argument #3 ($offset) must be contained in argument #1 ($haystack)'); + } + + if (80000 > \PHP_VERSION_ID && '' === $needle) { + if ('mb_strpos' === $function) { + trigger_error($function.'(): Empty delimiter', \E_USER_WARNING); + } + + return false; + } + + if (!$reverse) { + $pos = strpos($haystack, $needle, $start); + } else { + $pos = strrpos($haystack, $needle, 0 > $offset ? $start - \strlen($haystack) : $start); + } + + return false === $pos || $bytes ? $pos : self::utf8Length(substr($haystack, 0, $pos)); + } + + /** + * Returns the part of $haystack before or from $needle like native mbstring. + * + * @return string|false + */ + private static function findPart(string $function, $haystack, $needle, $part, $encoding, bool $reverse, bool $fold) + { + $needle = (string) $needle; + + if (80000 > \PHP_VERSION_ID && '' === $needle) { + if (!$reverse) { + trigger_error($function.'(): Empty delimiter', \E_USER_WARNING); + } + + return false; + } + + $haystack = (string) $haystack; + + if (!$search = self::prepareSearch($haystack, $needle, $encoding = self::searchEncoding($encoding, $fold), $fold, $fold)) { + return false; + } + + [$h, $n, $bytes] = $search; + + if (false === $pos = $reverse ? strrpos($h, $n) : strpos($h, $n)) { + return false; + } + + if ($bytes) { + return (string) ($part ? substr($haystack, 0, $pos) : substr($haystack, $pos)); + } + + if ($fold || ('UTF-8' === $encoding && (!preg_match('//u', $haystack) || !preg_match('//u', $needle)))) { + // Cut after as many characters as native mbstring counts before the match + $pos = self::utf8Length(substr($h, 0, $pos)); + $h = 'UTF-8' === $encoding ? self::markIllFormedUtf8($haystack) : self::utf8($haystack, $encoding); + $pos = self::utf8Offset($h, $pos, false); + } + + $h = (string) ($part ? substr($h, 0, $pos) : substr($h, $pos)); + + if (false !== strpos($h, "\xFF")) { + $h = str_replace("\xFF", 'none' === mb_substitute_character() ? '' : '?', $h); + } + + return 'UTF-8' === $encoding ? $h : (string) @self::iconv('UTF-8', $encoding, $h); + } + + /** + * @return array{string, string, bool, int}|null The haystack and the needle to search, whether offsets in them count bytes rather than UTF-8 characters, and how many bytes of ill-formed sequences iconv() dropped from the haystack + */ + private static function prepareSearch(string $haystack, string $needle, string $encoding, bool $fold, bool $markIllFormed) + { + if ('ASCII' === $encoding || ('CP850' === $encoding && !$fold)) { + if ('ASCII' === $encoding) { + // Native mbstring turns every byte above 0x7F into the same error marker + $haystack = preg_replace('/[\x80-\xFF]/', "\xFF", $haystack); + $needle = preg_replace('/[\x80-\xFF]/', "\xFF", $needle); + } + + if ($fold) { + $haystack = strtr($haystack, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + $needle = strtr($needle, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + return [$haystack, $needle, true, 0]; + } + + $dropped = 0; + + if ('UTF-8' !== $encoding) { + if (false === ($haystack = self::utf8($haystack, $encoding, $dropped)) || false === $needle = self::utf8($needle, $encoding)) { + return null; + } + } elseif ($markIllFormed) { + $haystack = self::markIllFormedUtf8($haystack); + $needle = self::markIllFormedUtf8($needle); + } + + return $fold ? [self::foldCase($haystack), self::foldCase($needle), false, $dropped] : [$haystack, $needle, false, $dropped]; + } + + private static function searchEncoding($encoding, bool $fold): string + { + $normalizedEncoding = self::getEncoding($encoding); + + // Native mbstring folds the case of 8bit strings as Latin-1 + return $fold && 'CP850' === $normalizedEncoding && null !== $encoding && 'CP850' !== strtoupper($encoding) ? 'ISO-8859-1' : $normalizedEncoding; + } + + /** + * Converts $s to UTF-8 to search it, ending with "\xFF", a byte that is invalid in UTF-8, when its last sequence is truncated, like native mbstring. + * + * @param int $dropped Set to the number of bytes of the ill-formed sequences that iconv() dropped elsewhere + * + * @return string|false False when the encoding is unknown + */ + private static function utf8(string $s, string $encoding, &$dropped = 0) + { + if ('UTF-8' === $encoding || '' === $s) { + return $s; + } + + if (false !== $u = @iconv($encoding, 'UTF-8', $s)) { + return $u; + } + + // Let iconv() warn about an unknown encoding + if (false === iconv($encoding, 'UTF-8', '')) { + return false; + } + + // iconv() drops the ill-formed sequences, but fails on a truncated one at the end + for ($i = 0; $i < 4; ++$i) { + if (false !== $u = @self::iconv($encoding, 'UTF-8', $i ? substr($s, 0, -$i) : $s)) { + $dropped = \strlen($s) - $i - \strlen((string) @iconv('UTF-8', $encoding, $u)); + + return $i || '' === $u ? $u."\xFF" : $u; + } + } + + $dropped = \strlen($s); + + return "\xFF"; + } + + /** + * Replaces each maximal subpart of ill-formed UTF-8 sequences with "\xFF", like native mbstring before searching case-insensitively. + */ + private static function markIllFormedUtf8(string $s): string + { + if (preg_match('//u', $s)) { + return $s; + } + + return preg_replace('/\G(?:[\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*+\K(?:\xE0[\xA0-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]|\xED[\x80-\x9F]|\xF0[\x90-\xBF][\x80-\xBF]?|[\xF1-\xF3][\x80-\xBF]{1,2}|\xF4[\x80-\x8F][\x80-\xBF]?|[\x80-\xFF])/', "\xFF", $s); + } + + /** + * Folds the case of UTF-8 $s like the simple case folding of native mbstring. + */ + private static function foldCase(string $s): string + { + static $map = null; + + if (null === $map) { + $map = array_combine(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1]) + self::getData('lowerCase'); + unset($map["\xC4\xB0"]); // U+0130 has no simple case folding + } + + return strtr($s, $map); + } + + /** + * Counts the characters of UTF-8 $s like native mbstring, even when ill-formed: one per byte that is not a continuation byte. + */ + private static function utf8Length(string $s): int + { + return \strlen($s) - array_sum(\array_slice(count_chars($s), 0x80, 0x40)); + } + + /** + * @return int|false The offset in bytes of the character at $offset, false when it is out of range, like native mbstring + */ + private static function utf8Offset(string $s, int $offset, bool $bytes) + { + if (0 === $offset) { + return 0; + } + + if ($bytes || preg_match('//u', $u = str_replace("\xFF", '?', $s))) { + $length = $bytes ? \strlen($s) : self::utf8Length($s); + + if (0 > $offset) { + $offset += $length; + } + + if (0 > $offset || $offset > $length) { + return false; + } + + if ($bytes) { + return $offset; + } + + for ($rx = ''; 65535 < $offset; $offset -= 65535) { + $rx .= '.{65535}'; + } + preg_match('/^'.$rx.'.{'.$offset.'}\K/su', $u, $m, \PREG_OFFSET_CAPTURE); + + return $m[0][1]; + } + + // Walk ill-formed UTF-8 like native mbstring: backward over the bytes that are not continuation bytes, forward by the lengths that lead bytes announce + $length = \strlen($s); + + if (0 > $offset) { + $i = $length; + + while (0 > $offset) { + if (0 === $i) { + return false; + } + + if (0x80 !== (\ord($s[--$i]) & 0xC0)) { + ++$offset; + } + } + + return $i; + } + + $i = 0; + + while (0 < $offset--) { + if ($i >= $length) { + return false; + } + + $c = \ord($s[$i]); + $i += $c < 0xC2 ? 1 : ($c < 0xE0 ? 2 : ($c < 0xF0 ? 3 : ($c < 0xF5 ? 4 : 1))); + } + + return min($i, $length); + } + + private static function html_encoding_callback(array $m) + { + $i = 1; + $entities = ''; + $m = unpack('C*', htmlentities($m[0], \ENT_COMPAT, 'UTF-8')); + + while (isset($m[$i])) { + if (0x80 > $m[$i]) { + $entities .= \chr($m[$i++]); + continue; + } + if (0xF0 <= $m[$i]) { + $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; + } elseif (0xE0 <= $m[$i]) { + $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; + } else { + $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80; + } + + $entities .= '&#'.$c.';'; + } + + return $entities; + } + + private static function title_case(array $s) + { + static $titleCase = null; + if (null === $titleCase) { + $titleCase = self::getData('titleCase'); + } + + return ($titleCase[$s[1]] ?? self::mb_convert_case($s[1], \MB_CASE_UPPER, 'UTF-8')).self::mb_convert_case($s[2], \MB_CASE_LOWER, 'UTF-8'); + } + + private static function getData($file) + { + if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) { + return require $file; + } + + return false; + } + + private static function getEncoding($encoding) + { + if (null === $encoding) { + return self::$internalEncoding; + } + + if ('UTF-8' === $encoding) { + return 'UTF-8'; + } + + $encoding = strtoupper($encoding); + + if ('8BIT' === $encoding || 'BINARY' === $encoding) { + return 'CP850'; + } + + if ('UTF8' === $encoding) { + return 'UTF-8'; + } + + if ('UTF-32' === $encoding) { + return 'UTF-32BE'; + } + + if ('UTF-16' === $encoding) { + return 'UTF-16BE'; + } + + if ('UCS-2' === $encoding) { + return 'UCS-2BE'; + } + + return $encoding; + } + + private static function iconv($fromEncoding, $toEncoding, $s) + { + if (null === self::$iconvSupportsIgnore) { + self::$iconvSupportsIgnore = false !== @iconv('UTF-8', 'UTF-8//IGNORE', ''); + } + + return self::$iconvSupportsIgnore + ? iconv($fromEncoding, $toEncoding.'//IGNORE', $s) + : iconv($fromEncoding, $toEncoding, $s); + } + + /** @return string|false */ + private static function mb_internal_trim(string $regex, string $string, ?string $characters, ?string $encoding, string $function) + { + if (null === $encoding) { + $encoding = self::mb_internal_encoding(); + } elseif (!self::assertEncoding($encoding, $function.'(): Argument #3 ($encoding) must be a valid encoding, "%s" given')) { + return false; + } + + if ('' === $characters) { + return $string; + } + + if ('UTF-8' === self::getEncoding($encoding)) { + $encoding = null; + if (!preg_match('//u', $string) || (null !== $characters && !preg_match('//u', $characters))) { + return self::mb_trim_invalid_utf8($string, $characters, $function); + } + } else { + $string = self::iconv($encoding, 'UTF-8', $string); + + if (null !== $characters) { + $characters = self::iconv($encoding, 'UTF-8', $characters); + } + } + + if (null === $characters) { + $characters = "\\0 \f\n\r\t\v\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}"; + } else { + $characters = preg_quote($characters); + } + + $string = preg_replace(\sprintf($regex, $characters), '', $string); + + if (null === $encoding) { + return $string; + } + + return self::iconv('UTF-8', $encoding, $string); + } + + /** + * Trims ill-formed UTF-8 like mbstring: each maximal subpart of an ill-formed + * sequence counts as one character, and the string is returned as is when + * nothing is trimmed, else re-encoded with the substitute character. + */ + private static function mb_trim_invalid_utf8(string $string, ?string $characters, string $function): string + { + $regex = self::UTF8_CHAR_REGEX; + + // Ill-formed sequences leave group 1 empty: they are trimmed when $characters has one too + preg_match_all($regex, $characters ?? "\0 \f\n\r\t\v\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", $m); + $trimmed = array_flip($m[1]); + + $start = 0; + $end = \strlen($string); + + while ('mb_rtrim' !== $function && $start < $end && preg_match($regex, $string, $m, 0, $start) && isset($trimmed[$m[1] ?? ''])) { + $start += \strlen($m[0]); + } + + while ('mb_ltrim' !== $function && $start < $end) { + // Characters are at most 4 bytes long, and only continuation bytes don't start one + for ($i = $end - 1; $i > $start && $i > $end - 4 && 0x80 === (\ord($string[$i]) & 0xC0); --$i) { + } + + preg_match_all($regex, substr($string, $i, $end - $i), $m); + + if (!isset($trimmed[end($m[1])])) { + break; + } + + $end -= \strlen(end($m[0])); + } + + if (0 === $start && \strlen($string) === $end) { + return $string; + } + + $string = substr($string, $start, $end - $start); + + return 'none' === mb_substitute_character() ? self::scrubUtf8($string) : mb_convert_encoding($string, 'UTF-8', 'UTF-8'); + } + + private static function scrubUtf8(string $s): string + { + return preg_replace(self::UTF8_CHAR_REGEX, '$1', $s); + } + + /** + * @param true[] $referenceIds The ids of the references followed to reach $array + */ + private static function convertArray(array $array, $toEncoding, $fromEncoding, array $referenceIds = []): array + { + $r = []; + + foreach ($array as $key => $v) { + if (null !== $v && !\is_scalar($v) && !\is_array($v)) { + trigger_error('mb_convert_encoding(): Object is not supported', \E_USER_WARNING); + continue; + } + + $k = \is_string($key) ? self::mb_convert_encoding($key, $toEncoding, $fromEncoding) : $key; + + if (\is_string($v)) { + $v = self::mb_convert_encoding($v, $toEncoding, $fromEncoding); + } elseif (\is_array($v)) { + // Only a reference can close a cycle: following the same one twice means one was found + $id = 70400 <= \PHP_VERSION_ID && ($reference = \ReflectionReference::fromArrayElement($array, $key)) ? $reference->getId() : null; + + if (null !== $id && isset($referenceIds[$id])) { + trigger_error('mb_convert_encoding(): Cannot convert recursively referenced values', \E_USER_WARNING); + $v = []; + } else { + $v = self::convertArray($v, $toEncoding, $fromEncoding, null === $id ? $referenceIds : $referenceIds + [$id => true]); + } + } + + // Keys that collide once converted keep their first value + $r += [$k => $v]; + } + + return $r; + } + + /** + * Returns the error native mbstring throws for these encoding arguments, if any. + */ + private static function getConversionError(string $function, int $argument, $toEncoding, $fromEncoding): ?string + { + if (!self::isConvertibleEncoding((string) $toEncoding)) { + return \sprintf('%s(): Argument #%d ($to_encoding) must be a valid encoding, "%s" given', $function, $argument, $toEncoding); + } + + if (null === $fromEncoding) { + return null; + } + + if (!$list = \is_array($fromEncoding) ? $fromEncoding : ('' === $fromEncoding ? [] : explode(',', $fromEncoding))) { + return \sprintf('%s(): Argument #%d ($from_encoding) must specify at least one encoding', $function, 1 + $argument); + } + + foreach ($list as $encoding) { + $encoding = \is_array($fromEncoding) ? (string) $encoding : trim($encoding, " \t"); + + // PHP 8.4 takes an empty entry of a comma-separated list for "auto" + if ('' === $encoding && !\is_array($fromEncoding) && 80400 <= \PHP_VERSION_ID) { + continue; + } + + if (0 !== strcasecmp($encoding, 'auto') && !self::isConvertibleEncoding($encoding)) { + return \sprintf('%s(): Argument #%d ($from_encoding) contains invalid encoding "%s"', $function, 1 + $argument, $encoding); + } + } + + return null; + } + + private static function isConvertibleEncoding(string $encoding): bool + { + if (isset(self::$convertibleEncodings[$encoding])) { + return true; + } + + $normalizedEncoding = self::getEncoding($encoding); + + // Native encoding names use no other characters, while iconv() also accepts suffixes like //TRANSLIT + if ('' === $normalizedEncoding || preg_match('/[^\w#\-.:]/', $encoding) || (null === (self::UNSUPPORTED_CODEPOINT_ENCODINGS[$normalizedEncoding] ?? null) && false === @iconv($normalizedEncoding, $normalizedEncoding, ''))) { + return false; + } + + return self::$convertibleEncodings[$encoding] = true; + } + + private static function assertEncoding(string $encoding, string $errorFormat): bool + { + try { + $validEncoding = @self::mb_check_encoding('', $encoding); + } catch (\ValueError $e) { + throw new \ValueError(\sprintf($errorFormat, $encoding)); + } + + if (!$validEncoding) { + if (80000 > \PHP_VERSION_ID) { + trigger_error(\sprintf($errorFormat, $encoding), \E_USER_WARNING); + } else { + throw new \ValueError(\sprintf($errorFormat, $encoding)); + } + } + + return $validEncoding; + } + + private static function assertCodepointEncoding(string $encoding, string $function): bool + { + if (null !== $name = self::UNSUPPORTED_CODEPOINT_ENCODINGS[strtoupper($encoding)] ?? null) { + if (80000 > \PHP_VERSION_ID) { + trigger_error(\sprintf('%s(): Unsupported encoding "%s"', $function, $name), \E_USER_WARNING); + + return false; + } + + throw new \ValueError(\sprintf('%s() does not support the "%s" encoding', $function, $name)); + } + + $normalizedEncoding = self::getEncoding($encoding); + + if ('UTF-8' === $normalizedEncoding || false !== @iconv($normalizedEncoding, $normalizedEncoding, '')) { + return true; + } + + if (80000 > \PHP_VERSION_ID) { + trigger_error(\sprintf('%s(): Unknown encoding "%s"', $function, $encoding), \E_USER_WARNING); + + return false; + } + + throw new \ValueError(\sprintf('%s(): Argument #2 ($encoding) must be a valid encoding, "%s" given', $function, $encoding)); + } +} diff --git a/vendor/symfony/polyfill-mbstring/README.md b/vendor/symfony/polyfill-mbstring/README.md new file mode 100644 index 0000000..478b40d --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/README.md @@ -0,0 +1,13 @@ +Symfony Polyfill / Mbstring +=========================== + +This component provides a partial, native PHP implementation for the +[Mbstring](https://php.net/mbstring) extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php b/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php new file mode 100644 index 0000000..512bba0 --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php @@ -0,0 +1,119 @@ +<?php + +return [ + 'İ' => 'i̇', + 'µ' => 'μ', + 'ſ' => 's', + 'ͅ' => 'ι', + 'ς' => 'σ', + 'ϐ' => 'β', + 'ϑ' => 'θ', + 'ϕ' => 'φ', + 'ϖ' => 'π', + 'ϰ' => 'κ', + 'ϱ' => 'ρ', + 'ϵ' => 'ε', + 'ẛ' => 'ṡ', + 'ι' => 'ι', + 'ß' => 'ss', + 'ʼn' => 'ʼn', + 'ǰ' => 'ǰ', + 'ΐ' => 'ΐ', + 'ΰ' => 'ΰ', + 'և' => 'եւ', + 'ẖ' => 'ẖ', + 'ẗ' => 'ẗ', + 'ẘ' => 'ẘ', + 'ẙ' => 'ẙ', + 'ẚ' => 'aʾ', + 'ẞ' => 'ss', + 'ὐ' => 'ὐ', + 'ὒ' => 'ὒ', + 'ὔ' => 'ὔ', + 'ὖ' => 'ὖ', + 'ᾀ' => 'ἀι', + 'ᾁ' => 'ἁι', + 'ᾂ' => 'ἂι', + 'ᾃ' => 'ἃι', + 'ᾄ' => 'ἄι', + 'ᾅ' => 'ἅι', + 'ᾆ' => 'ἆι', + 'ᾇ' => 'ἇι', + 'ᾈ' => 'ἀι', + 'ᾉ' => 'ἁι', + 'ᾊ' => 'ἂι', + 'ᾋ' => 'ἃι', + 'ᾌ' => 'ἄι', + 'ᾍ' => 'ἅι', + 'ᾎ' => 'ἆι', + 'ᾏ' => 'ἇι', + 'ᾐ' => 'ἠι', + 'ᾑ' => 'ἡι', + 'ᾒ' => 'ἢι', + 'ᾓ' => 'ἣι', + 'ᾔ' => 'ἤι', + 'ᾕ' => 'ἥι', + 'ᾖ' => 'ἦι', + 'ᾗ' => 'ἧι', + 'ᾘ' => 'ἠι', + 'ᾙ' => 'ἡι', + 'ᾚ' => 'ἢι', + 'ᾛ' => 'ἣι', + 'ᾜ' => 'ἤι', + 'ᾝ' => 'ἥι', + 'ᾞ' => 'ἦι', + 'ᾟ' => 'ἧι', + 'ᾠ' => 'ὠι', + 'ᾡ' => 'ὡι', + 'ᾢ' => 'ὢι', + 'ᾣ' => 'ὣι', + 'ᾤ' => 'ὤι', + 'ᾥ' => 'ὥι', + 'ᾦ' => 'ὦι', + 'ᾧ' => 'ὧι', + 'ᾨ' => 'ὠι', + 'ᾩ' => 'ὡι', + 'ᾪ' => 'ὢι', + 'ᾫ' => 'ὣι', + 'ᾬ' => 'ὤι', + 'ᾭ' => 'ὥι', + 'ᾮ' => 'ὦι', + 'ᾯ' => 'ὧι', + 'ᾲ' => 'ὰι', + 'ᾳ' => 'αι', + 'ᾴ' => 'άι', + 'ᾶ' => 'ᾶ', + 'ᾷ' => 'ᾶι', + 'ᾼ' => 'αι', + 'ῂ' => 'ὴι', + 'ῃ' => 'ηι', + 'ῄ' => 'ήι', + 'ῆ' => 'ῆ', + 'ῇ' => 'ῆι', + 'ῌ' => 'ηι', + 'ῒ' => 'ῒ', + 'ῖ' => 'ῖ', + 'ῗ' => 'ῗ', + 'ῢ' => 'ῢ', + 'ῤ' => 'ῤ', + 'ῦ' => 'ῦ', + 'ῧ' => 'ῧ', + 'ῲ' => 'ὼι', + 'ῳ' => 'ωι', + 'ῴ' => 'ώι', + 'ῶ' => 'ῶ', + 'ῷ' => 'ῶι', + 'ῼ' => 'ωι', + 'ff' => 'ff', + 'fi' => 'fi', + 'fl' => 'fl', + 'ffi' => 'ffi', + 'ffl' => 'ffl', + 'ſt' => 'st', + 'st' => 'st', + 'ﬓ' => 'մն', + 'ﬔ' => 'մե', + 'ﬕ' => 'մի', + 'ﬖ' => 'վն', + 'ﬗ' => 'մխ', +]; diff --git a/vendor/symfony/polyfill-mbstring/Resources/unidata/eastAsianWidthRegexp.php b/vendor/symfony/polyfill-mbstring/Resources/unidata/eastAsianWidthRegexp.php new file mode 100644 index 0000000..34d875e --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/Resources/unidata/eastAsianWidthRegexp.php @@ -0,0 +1,5 @@ +<?php + +// from W and F in https://unicode.org/Public/UNIDATA/EastAsianWidth.txt + +return '/[\x{1100}-\x{115F}\x{231A}-\x{231B}\x{2329}-\x{232A}\x{23E9}-\x{23EC}\x{23F0}\x{23F3}\x{25FD}-\x{25FE}\x{2614}-\x{2615}\x{2630}-\x{2637}\x{2648}-\x{2653}\x{267F}\x{268A}-\x{268F}\x{2693}\x{26A1}\x{26AA}-\x{26AB}\x{26BD}-\x{26BE}\x{26C4}-\x{26C5}\x{26CE}\x{26D4}\x{26EA}\x{26F2}-\x{26F3}\x{26F5}\x{26FA}\x{26FD}\x{2705}\x{270A}-\x{270B}\x{2728}\x{274C}\x{274E}\x{2753}-\x{2755}\x{2757}\x{2795}-\x{2797}\x{27B0}\x{27BF}\x{2B1B}-\x{2B1C}\x{2B50}\x{2B55}\x{2E80}-\x{2E99}\x{2E9B}-\x{2EF3}\x{2F00}-\x{2FD5}\x{2FF0}-\x{303E}\x{3041}-\x{3096}\x{3099}-\x{30FF}\x{3105}-\x{312F}\x{3131}-\x{318E}\x{3190}-\x{31E5}\x{31EF}-\x{321E}\x{3220}-\x{3247}\x{3250}-\x{A48C}\x{A490}-\x{A4C6}\x{A960}-\x{A97C}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE52}\x{FE54}-\x{FE66}\x{FE68}-\x{FE6B}\x{FF01}-\x{FF60}\x{FFE0}-\x{FFE6}\x{16FE0}-\x{16FE4}\x{16FF0}-\x{16FF6}\x{17000}-\x{18CD5}\x{18CFF}-\x{18D1E}\x{18D80}-\x{18DF2}\x{1AFF0}-\x{1AFF3}\x{1AFF5}-\x{1AFFB}\x{1AFFD}-\x{1AFFE}\x{1B000}-\x{1B122}\x{1B132}\x{1B150}-\x{1B152}\x{1B155}\x{1B164}-\x{1B167}\x{1B170}-\x{1B2FB}\x{1D300}-\x{1D356}\x{1D360}-\x{1D376}\x{1F004}\x{1F0CF}\x{1F18E}\x{1F191}-\x{1F19A}\x{1F200}-\x{1F202}\x{1F210}-\x{1F23B}\x{1F240}-\x{1F248}\x{1F250}-\x{1F251}\x{1F260}-\x{1F265}\x{1F300}-\x{1F320}\x{1F32D}-\x{1F335}\x{1F337}-\x{1F37C}\x{1F37E}-\x{1F393}\x{1F3A0}-\x{1F3CA}\x{1F3CF}-\x{1F3D3}\x{1F3E0}-\x{1F3F0}\x{1F3F4}\x{1F3F8}-\x{1F43E}\x{1F440}\x{1F442}-\x{1F4FC}\x{1F4FF}-\x{1F53D}\x{1F54B}-\x{1F54E}\x{1F550}-\x{1F567}\x{1F57A}\x{1F595}-\x{1F596}\x{1F5A4}\x{1F5FB}-\x{1F64F}\x{1F680}-\x{1F6C5}\x{1F6CC}\x{1F6D0}-\x{1F6D2}\x{1F6D5}-\x{1F6D8}\x{1F6DC}-\x{1F6DF}\x{1F6EB}-\x{1F6EC}\x{1F6F4}-\x{1F6FC}\x{1F7E0}-\x{1F7EB}\x{1F7F0}\x{1F90C}-\x{1F93A}\x{1F93C}-\x{1F945}\x{1F947}-\x{1F9FF}\x{1FA70}-\x{1FA7C}\x{1FA80}-\x{1FA8A}\x{1FA8E}-\x{1FAC6}\x{1FAC8}\x{1FACD}-\x{1FADC}\x{1FADF}-\x{1FAEA}\x{1FAEF}-\x{1FAF8}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u'; diff --git a/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php b/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php new file mode 100644 index 0000000..fac60b0 --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php @@ -0,0 +1,1397 @@ +<?php + +return array ( + 'A' => 'a', + 'B' => 'b', + 'C' => 'c', + 'D' => 'd', + 'E' => 'e', + 'F' => 'f', + 'G' => 'g', + 'H' => 'h', + 'I' => 'i', + 'J' => 'j', + 'K' => 'k', + 'L' => 'l', + 'M' => 'm', + 'N' => 'n', + 'O' => 'o', + 'P' => 'p', + 'Q' => 'q', + 'R' => 'r', + 'S' => 's', + 'T' => 't', + 'U' => 'u', + 'V' => 'v', + 'W' => 'w', + 'X' => 'x', + 'Y' => 'y', + 'Z' => 'z', + 'À' => 'à', + 'Á' => 'á', + 'Â' => 'â', + 'Ã' => 'ã', + 'Ä' => 'ä', + 'Å' => 'å', + 'Æ' => 'æ', + 'Ç' => 'ç', + 'È' => 'è', + 'É' => 'é', + 'Ê' => 'ê', + 'Ë' => 'ë', + 'Ì' => 'ì', + 'Í' => 'í', + 'Î' => 'î', + 'Ï' => 'ï', + 'Ð' => 'ð', + 'Ñ' => 'ñ', + 'Ò' => 'ò', + 'Ó' => 'ó', + 'Ô' => 'ô', + 'Õ' => 'õ', + 'Ö' => 'ö', + 'Ø' => 'ø', + 'Ù' => 'ù', + 'Ú' => 'ú', + 'Û' => 'û', + 'Ü' => 'ü', + 'Ý' => 'ý', + 'Þ' => 'þ', + 'Ā' => 'ā', + 'Ă' => 'ă', + 'Ą' => 'ą', + 'Ć' => 'ć', + 'Ĉ' => 'ĉ', + 'Ċ' => 'ċ', + 'Č' => 'č', + 'Ď' => 'ď', + 'Đ' => 'đ', + 'Ē' => 'ē', + 'Ĕ' => 'ĕ', + 'Ė' => 'ė', + 'Ę' => 'ę', + 'Ě' => 'ě', + 'Ĝ' => 'ĝ', + 'Ğ' => 'ğ', + 'Ġ' => 'ġ', + 'Ģ' => 'ģ', + 'Ĥ' => 'ĥ', + 'Ħ' => 'ħ', + 'Ĩ' => 'ĩ', + 'Ī' => 'ī', + 'Ĭ' => 'ĭ', + 'Į' => 'į', + 'İ' => 'i̇', + 'IJ' => 'ij', + 'Ĵ' => 'ĵ', + 'Ķ' => 'ķ', + 'Ĺ' => 'ĺ', + 'Ļ' => 'ļ', + 'Ľ' => 'ľ', + 'Ŀ' => 'ŀ', + 'Ł' => 'ł', + 'Ń' => 'ń', + 'Ņ' => 'ņ', + 'Ň' => 'ň', + 'Ŋ' => 'ŋ', + 'Ō' => 'ō', + 'Ŏ' => 'ŏ', + 'Ő' => 'ő', + 'Œ' => 'œ', + 'Ŕ' => 'ŕ', + 'Ŗ' => 'ŗ', + 'Ř' => 'ř', + 'Ś' => 'ś', + 'Ŝ' => 'ŝ', + 'Ş' => 'ş', + 'Š' => 'š', + 'Ţ' => 'ţ', + 'Ť' => 'ť', + 'Ŧ' => 'ŧ', + 'Ũ' => 'ũ', + 'Ū' => 'ū', + 'Ŭ' => 'ŭ', + 'Ů' => 'ů', + 'Ű' => 'ű', + 'Ų' => 'ų', + 'Ŵ' => 'ŵ', + 'Ŷ' => 'ŷ', + 'Ÿ' => 'ÿ', + 'Ź' => 'ź', + 'Ż' => 'ż', + 'Ž' => 'ž', + 'Ɓ' => 'ɓ', + 'Ƃ' => 'ƃ', + 'Ƅ' => 'ƅ', + 'Ɔ' => 'ɔ', + 'Ƈ' => 'ƈ', + 'Ɖ' => 'ɖ', + 'Ɗ' => 'ɗ', + 'Ƌ' => 'ƌ', + 'Ǝ' => 'ǝ', + 'Ə' => 'ə', + 'Ɛ' => 'ɛ', + 'Ƒ' => 'ƒ', + 'Ɠ' => 'ɠ', + 'Ɣ' => 'ɣ', + 'Ɩ' => 'ɩ', + 'Ɨ' => 'ɨ', + 'Ƙ' => 'ƙ', + 'Ɯ' => 'ɯ', + 'Ɲ' => 'ɲ', + 'Ɵ' => 'ɵ', + 'Ơ' => 'ơ', + 'Ƣ' => 'ƣ', + 'Ƥ' => 'ƥ', + 'Ʀ' => 'ʀ', + 'Ƨ' => 'ƨ', + 'Ʃ' => 'ʃ', + 'Ƭ' => 'ƭ', + 'Ʈ' => 'ʈ', + 'Ư' => 'ư', + 'Ʊ' => 'ʊ', + 'Ʋ' => 'ʋ', + 'Ƴ' => 'ƴ', + 'Ƶ' => 'ƶ', + 'Ʒ' => 'ʒ', + 'Ƹ' => 'ƹ', + 'Ƽ' => 'ƽ', + 'DŽ' => 'dž', + 'Dž' => 'dž', + 'LJ' => 'lj', + 'Lj' => 'lj', + 'NJ' => 'nj', + 'Nj' => 'nj', + 'Ǎ' => 'ǎ', + 'Ǐ' => 'ǐ', + 'Ǒ' => 'ǒ', + 'Ǔ' => 'ǔ', + 'Ǖ' => 'ǖ', + 'Ǘ' => 'ǘ', + 'Ǚ' => 'ǚ', + 'Ǜ' => 'ǜ', + 'Ǟ' => 'ǟ', + 'Ǡ' => 'ǡ', + 'Ǣ' => 'ǣ', + 'Ǥ' => 'ǥ', + 'Ǧ' => 'ǧ', + 'Ǩ' => 'ǩ', + 'Ǫ' => 'ǫ', + 'Ǭ' => 'ǭ', + 'Ǯ' => 'ǯ', + 'DZ' => 'dz', + 'Dz' => 'dz', + 'Ǵ' => 'ǵ', + 'Ƕ' => 'ƕ', + 'Ƿ' => 'ƿ', + 'Ǹ' => 'ǹ', + 'Ǻ' => 'ǻ', + 'Ǽ' => 'ǽ', + 'Ǿ' => 'ǿ', + 'Ȁ' => 'ȁ', + 'Ȃ' => 'ȃ', + 'Ȅ' => 'ȅ', + 'Ȇ' => 'ȇ', + 'Ȉ' => 'ȉ', + 'Ȋ' => 'ȋ', + 'Ȍ' => 'ȍ', + 'Ȏ' => 'ȏ', + 'Ȑ' => 'ȑ', + 'Ȓ' => 'ȓ', + 'Ȕ' => 'ȕ', + 'Ȗ' => 'ȗ', + 'Ș' => 'ș', + 'Ț' => 'ț', + 'Ȝ' => 'ȝ', + 'Ȟ' => 'ȟ', + 'Ƞ' => 'ƞ', + 'Ȣ' => 'ȣ', + 'Ȥ' => 'ȥ', + 'Ȧ' => 'ȧ', + 'Ȩ' => 'ȩ', + 'Ȫ' => 'ȫ', + 'Ȭ' => 'ȭ', + 'Ȯ' => 'ȯ', + 'Ȱ' => 'ȱ', + 'Ȳ' => 'ȳ', + 'Ⱥ' => 'ⱥ', + 'Ȼ' => 'ȼ', + 'Ƚ' => 'ƚ', + 'Ⱦ' => 'ⱦ', + 'Ɂ' => 'ɂ', + 'Ƀ' => 'ƀ', + 'Ʉ' => 'ʉ', + 'Ʌ' => 'ʌ', + 'Ɇ' => 'ɇ', + 'Ɉ' => 'ɉ', + 'Ɋ' => 'ɋ', + 'Ɍ' => 'ɍ', + 'Ɏ' => 'ɏ', + 'Ͱ' => 'ͱ', + 'Ͳ' => 'ͳ', + 'Ͷ' => 'ͷ', + 'Ϳ' => 'ϳ', + 'Ά' => 'ά', + 'Έ' => 'έ', + 'Ή' => 'ή', + 'Ί' => 'ί', + 'Ό' => 'ό', + 'Ύ' => 'ύ', + 'Ώ' => 'ώ', + 'Α' => 'α', + 'Β' => 'β', + 'Γ' => 'γ', + 'Δ' => 'δ', + 'Ε' => 'ε', + 'Ζ' => 'ζ', + 'Η' => 'η', + 'Θ' => 'θ', + 'Ι' => 'ι', + 'Κ' => 'κ', + 'Λ' => 'λ', + 'Μ' => 'μ', + 'Ν' => 'ν', + 'Ξ' => 'ξ', + 'Ο' => 'ο', + 'Π' => 'π', + 'Ρ' => 'ρ', + 'Σ' => 'σ', + 'Τ' => 'τ', + 'Υ' => 'υ', + 'Φ' => 'φ', + 'Χ' => 'χ', + 'Ψ' => 'ψ', + 'Ω' => 'ω', + 'Ϊ' => 'ϊ', + 'Ϋ' => 'ϋ', + 'Ϗ' => 'ϗ', + 'Ϙ' => 'ϙ', + 'Ϛ' => 'ϛ', + 'Ϝ' => 'ϝ', + 'Ϟ' => 'ϟ', + 'Ϡ' => 'ϡ', + 'Ϣ' => 'ϣ', + 'Ϥ' => 'ϥ', + 'Ϧ' => 'ϧ', + 'Ϩ' => 'ϩ', + 'Ϫ' => 'ϫ', + 'Ϭ' => 'ϭ', + 'Ϯ' => 'ϯ', + 'ϴ' => 'θ', + 'Ϸ' => 'ϸ', + 'Ϲ' => 'ϲ', + 'Ϻ' => 'ϻ', + 'Ͻ' => 'ͻ', + 'Ͼ' => 'ͼ', + 'Ͽ' => 'ͽ', + 'Ѐ' => 'ѐ', + 'Ё' => 'ё', + 'Ђ' => 'ђ', + 'Ѓ' => 'ѓ', + 'Є' => 'є', + 'Ѕ' => 'ѕ', + 'І' => 'і', + 'Ї' => 'ї', + 'Ј' => 'ј', + 'Љ' => 'љ', + 'Њ' => 'њ', + 'Ћ' => 'ћ', + 'Ќ' => 'ќ', + 'Ѝ' => 'ѝ', + 'Ў' => 'ў', + 'Џ' => 'џ', + 'А' => 'а', + 'Б' => 'б', + 'В' => 'в', + 'Г' => 'г', + 'Д' => 'д', + 'Е' => 'е', + 'Ж' => 'ж', + 'З' => 'з', + 'И' => 'и', + 'Й' => 'й', + 'К' => 'к', + 'Л' => 'л', + 'М' => 'м', + 'Н' => 'н', + 'О' => 'о', + 'П' => 'п', + 'Р' => 'р', + 'С' => 'с', + 'Т' => 'т', + 'У' => 'у', + 'Ф' => 'ф', + 'Х' => 'х', + 'Ц' => 'ц', + 'Ч' => 'ч', + 'Ш' => 'ш', + 'Щ' => 'щ', + 'Ъ' => 'ъ', + 'Ы' => 'ы', + 'Ь' => 'ь', + 'Э' => 'э', + 'Ю' => 'ю', + 'Я' => 'я', + 'Ѡ' => 'ѡ', + 'Ѣ' => 'ѣ', + 'Ѥ' => 'ѥ', + 'Ѧ' => 'ѧ', + 'Ѩ' => 'ѩ', + 'Ѫ' => 'ѫ', + 'Ѭ' => 'ѭ', + 'Ѯ' => 'ѯ', + 'Ѱ' => 'ѱ', + 'Ѳ' => 'ѳ', + 'Ѵ' => 'ѵ', + 'Ѷ' => 'ѷ', + 'Ѹ' => 'ѹ', + 'Ѻ' => 'ѻ', + 'Ѽ' => 'ѽ', + 'Ѿ' => 'ѿ', + 'Ҁ' => 'ҁ', + 'Ҋ' => 'ҋ', + 'Ҍ' => 'ҍ', + 'Ҏ' => 'ҏ', + 'Ґ' => 'ґ', + 'Ғ' => 'ғ', + 'Ҕ' => 'ҕ', + 'Җ' => 'җ', + 'Ҙ' => 'ҙ', + 'Қ' => 'қ', + 'Ҝ' => 'ҝ', + 'Ҟ' => 'ҟ', + 'Ҡ' => 'ҡ', + 'Ң' => 'ң', + 'Ҥ' => 'ҥ', + 'Ҧ' => 'ҧ', + 'Ҩ' => 'ҩ', + 'Ҫ' => 'ҫ', + 'Ҭ' => 'ҭ', + 'Ү' => 'ү', + 'Ұ' => 'ұ', + 'Ҳ' => 'ҳ', + 'Ҵ' => 'ҵ', + 'Ҷ' => 'ҷ', + 'Ҹ' => 'ҹ', + 'Һ' => 'һ', + 'Ҽ' => 'ҽ', + 'Ҿ' => 'ҿ', + 'Ӏ' => 'ӏ', + 'Ӂ' => 'ӂ', + 'Ӄ' => 'ӄ', + 'Ӆ' => 'ӆ', + 'Ӈ' => 'ӈ', + 'Ӊ' => 'ӊ', + 'Ӌ' => 'ӌ', + 'Ӎ' => 'ӎ', + 'Ӑ' => 'ӑ', + 'Ӓ' => 'ӓ', + 'Ӕ' => 'ӕ', + 'Ӗ' => 'ӗ', + 'Ә' => 'ә', + 'Ӛ' => 'ӛ', + 'Ӝ' => 'ӝ', + 'Ӟ' => 'ӟ', + 'Ӡ' => 'ӡ', + 'Ӣ' => 'ӣ', + 'Ӥ' => 'ӥ', + 'Ӧ' => 'ӧ', + 'Ө' => 'ө', + 'Ӫ' => 'ӫ', + 'Ӭ' => 'ӭ', + 'Ӯ' => 'ӯ', + 'Ӱ' => 'ӱ', + 'Ӳ' => 'ӳ', + 'Ӵ' => 'ӵ', + 'Ӷ' => 'ӷ', + 'Ӹ' => 'ӹ', + 'Ӻ' => 'ӻ', + 'Ӽ' => 'ӽ', + 'Ӿ' => 'ӿ', + 'Ԁ' => 'ԁ', + 'Ԃ' => 'ԃ', + 'Ԅ' => 'ԅ', + 'Ԇ' => 'ԇ', + 'Ԉ' => 'ԉ', + 'Ԋ' => 'ԋ', + 'Ԍ' => 'ԍ', + 'Ԏ' => 'ԏ', + 'Ԑ' => 'ԑ', + 'Ԓ' => 'ԓ', + 'Ԕ' => 'ԕ', + 'Ԗ' => 'ԗ', + 'Ԙ' => 'ԙ', + 'Ԛ' => 'ԛ', + 'Ԝ' => 'ԝ', + 'Ԟ' => 'ԟ', + 'Ԡ' => 'ԡ', + 'Ԣ' => 'ԣ', + 'Ԥ' => 'ԥ', + 'Ԧ' => 'ԧ', + 'Ԩ' => 'ԩ', + 'Ԫ' => 'ԫ', + 'Ԭ' => 'ԭ', + 'Ԯ' => 'ԯ', + 'Ա' => 'ա', + 'Բ' => 'բ', + 'Գ' => 'գ', + 'Դ' => 'դ', + 'Ե' => 'ե', + 'Զ' => 'զ', + 'Է' => 'է', + 'Ը' => 'ը', + 'Թ' => 'թ', + 'Ժ' => 'ժ', + 'Ի' => 'ի', + 'Լ' => 'լ', + 'Խ' => 'խ', + 'Ծ' => 'ծ', + 'Կ' => 'կ', + 'Հ' => 'հ', + 'Ձ' => 'ձ', + 'Ղ' => 'ղ', + 'Ճ' => 'ճ', + 'Մ' => 'մ', + 'Յ' => 'յ', + 'Ն' => 'ն', + 'Շ' => 'շ', + 'Ո' => 'ո', + 'Չ' => 'չ', + 'Պ' => 'պ', + 'Ջ' => 'ջ', + 'Ռ' => 'ռ', + 'Ս' => 'ս', + 'Վ' => 'վ', + 'Տ' => 'տ', + 'Ր' => 'ր', + 'Ց' => 'ց', + 'Ւ' => 'ւ', + 'Փ' => 'փ', + 'Ք' => 'ք', + 'Օ' => 'օ', + 'Ֆ' => 'ֆ', + 'Ⴀ' => 'ⴀ', + 'Ⴁ' => 'ⴁ', + 'Ⴂ' => 'ⴂ', + 'Ⴃ' => 'ⴃ', + 'Ⴄ' => 'ⴄ', + 'Ⴅ' => 'ⴅ', + 'Ⴆ' => 'ⴆ', + 'Ⴇ' => 'ⴇ', + 'Ⴈ' => 'ⴈ', + 'Ⴉ' => 'ⴉ', + 'Ⴊ' => 'ⴊ', + 'Ⴋ' => 'ⴋ', + 'Ⴌ' => 'ⴌ', + 'Ⴍ' => 'ⴍ', + 'Ⴎ' => 'ⴎ', + 'Ⴏ' => 'ⴏ', + 'Ⴐ' => 'ⴐ', + 'Ⴑ' => 'ⴑ', + 'Ⴒ' => 'ⴒ', + 'Ⴓ' => 'ⴓ', + 'Ⴔ' => 'ⴔ', + 'Ⴕ' => 'ⴕ', + 'Ⴖ' => 'ⴖ', + 'Ⴗ' => 'ⴗ', + 'Ⴘ' => 'ⴘ', + 'Ⴙ' => 'ⴙ', + 'Ⴚ' => 'ⴚ', + 'Ⴛ' => 'ⴛ', + 'Ⴜ' => 'ⴜ', + 'Ⴝ' => 'ⴝ', + 'Ⴞ' => 'ⴞ', + 'Ⴟ' => 'ⴟ', + 'Ⴠ' => 'ⴠ', + 'Ⴡ' => 'ⴡ', + 'Ⴢ' => 'ⴢ', + 'Ⴣ' => 'ⴣ', + 'Ⴤ' => 'ⴤ', + 'Ⴥ' => 'ⴥ', + 'Ⴧ' => 'ⴧ', + 'Ⴭ' => 'ⴭ', + 'Ꭰ' => 'ꭰ', + 'Ꭱ' => 'ꭱ', + 'Ꭲ' => 'ꭲ', + 'Ꭳ' => 'ꭳ', + 'Ꭴ' => 'ꭴ', + 'Ꭵ' => 'ꭵ', + 'Ꭶ' => 'ꭶ', + 'Ꭷ' => 'ꭷ', + 'Ꭸ' => 'ꭸ', + 'Ꭹ' => 'ꭹ', + 'Ꭺ' => 'ꭺ', + 'Ꭻ' => 'ꭻ', + 'Ꭼ' => 'ꭼ', + 'Ꭽ' => 'ꭽ', + 'Ꭾ' => 'ꭾ', + 'Ꭿ' => 'ꭿ', + 'Ꮀ' => 'ꮀ', + 'Ꮁ' => 'ꮁ', + 'Ꮂ' => 'ꮂ', + 'Ꮃ' => 'ꮃ', + 'Ꮄ' => 'ꮄ', + 'Ꮅ' => 'ꮅ', + 'Ꮆ' => 'ꮆ', + 'Ꮇ' => 'ꮇ', + 'Ꮈ' => 'ꮈ', + 'Ꮉ' => 'ꮉ', + 'Ꮊ' => 'ꮊ', + 'Ꮋ' => 'ꮋ', + 'Ꮌ' => 'ꮌ', + 'Ꮍ' => 'ꮍ', + 'Ꮎ' => 'ꮎ', + 'Ꮏ' => 'ꮏ', + 'Ꮐ' => 'ꮐ', + 'Ꮑ' => 'ꮑ', + 'Ꮒ' => 'ꮒ', + 'Ꮓ' => 'ꮓ', + 'Ꮔ' => 'ꮔ', + 'Ꮕ' => 'ꮕ', + 'Ꮖ' => 'ꮖ', + 'Ꮗ' => 'ꮗ', + 'Ꮘ' => 'ꮘ', + 'Ꮙ' => 'ꮙ', + 'Ꮚ' => 'ꮚ', + 'Ꮛ' => 'ꮛ', + 'Ꮜ' => 'ꮜ', + 'Ꮝ' => 'ꮝ', + 'Ꮞ' => 'ꮞ', + 'Ꮟ' => 'ꮟ', + 'Ꮠ' => 'ꮠ', + 'Ꮡ' => 'ꮡ', + 'Ꮢ' => 'ꮢ', + 'Ꮣ' => 'ꮣ', + 'Ꮤ' => 'ꮤ', + 'Ꮥ' => 'ꮥ', + 'Ꮦ' => 'ꮦ', + 'Ꮧ' => 'ꮧ', + 'Ꮨ' => 'ꮨ', + 'Ꮩ' => 'ꮩ', + 'Ꮪ' => 'ꮪ', + 'Ꮫ' => 'ꮫ', + 'Ꮬ' => 'ꮬ', + 'Ꮭ' => 'ꮭ', + 'Ꮮ' => 'ꮮ', + 'Ꮯ' => 'ꮯ', + 'Ꮰ' => 'ꮰ', + 'Ꮱ' => 'ꮱ', + 'Ꮲ' => 'ꮲ', + 'Ꮳ' => 'ꮳ', + 'Ꮴ' => 'ꮴ', + 'Ꮵ' => 'ꮵ', + 'Ꮶ' => 'ꮶ', + 'Ꮷ' => 'ꮷ', + 'Ꮸ' => 'ꮸ', + 'Ꮹ' => 'ꮹ', + 'Ꮺ' => 'ꮺ', + 'Ꮻ' => 'ꮻ', + 'Ꮼ' => 'ꮼ', + 'Ꮽ' => 'ꮽ', + 'Ꮾ' => 'ꮾ', + 'Ꮿ' => 'ꮿ', + 'Ᏸ' => 'ᏸ', + 'Ᏹ' => 'ᏹ', + 'Ᏺ' => 'ᏺ', + 'Ᏻ' => 'ᏻ', + 'Ᏼ' => 'ᏼ', + 'Ᏽ' => 'ᏽ', + 'Ა' => 'ა', + 'Ბ' => 'ბ', + 'Გ' => 'გ', + 'Დ' => 'დ', + 'Ე' => 'ე', + 'Ვ' => 'ვ', + 'Ზ' => 'ზ', + 'Თ' => 'თ', + 'Ი' => 'ი', + 'Კ' => 'კ', + 'Ლ' => 'ლ', + 'Მ' => 'მ', + 'Ნ' => 'ნ', + 'Ო' => 'ო', + 'Პ' => 'პ', + 'Ჟ' => 'ჟ', + 'Რ' => 'რ', + 'Ს' => 'ს', + 'Ტ' => 'ტ', + 'Უ' => 'უ', + 'Ფ' => 'ფ', + 'Ქ' => 'ქ', + 'Ღ' => 'ღ', + 'Ყ' => 'ყ', + 'Შ' => 'შ', + 'Ჩ' => 'ჩ', + 'Ც' => 'ც', + 'Ძ' => 'ძ', + 'Წ' => 'წ', + 'Ჭ' => 'ჭ', + 'Ხ' => 'ხ', + 'Ჯ' => 'ჯ', + 'Ჰ' => 'ჰ', + 'Ჱ' => 'ჱ', + 'Ჲ' => 'ჲ', + 'Ჳ' => 'ჳ', + 'Ჴ' => 'ჴ', + 'Ჵ' => 'ჵ', + 'Ჶ' => 'ჶ', + 'Ჷ' => 'ჷ', + 'Ჸ' => 'ჸ', + 'Ჹ' => 'ჹ', + 'Ჺ' => 'ჺ', + 'Ჽ' => 'ჽ', + 'Ჾ' => 'ჾ', + 'Ჿ' => 'ჿ', + 'Ḁ' => 'ḁ', + 'Ḃ' => 'ḃ', + 'Ḅ' => 'ḅ', + 'Ḇ' => 'ḇ', + 'Ḉ' => 'ḉ', + 'Ḋ' => 'ḋ', + 'Ḍ' => 'ḍ', + 'Ḏ' => 'ḏ', + 'Ḑ' => 'ḑ', + 'Ḓ' => 'ḓ', + 'Ḕ' => 'ḕ', + 'Ḗ' => 'ḗ', + 'Ḙ' => 'ḙ', + 'Ḛ' => 'ḛ', + 'Ḝ' => 'ḝ', + 'Ḟ' => 'ḟ', + 'Ḡ' => 'ḡ', + 'Ḣ' => 'ḣ', + 'Ḥ' => 'ḥ', + 'Ḧ' => 'ḧ', + 'Ḩ' => 'ḩ', + 'Ḫ' => 'ḫ', + 'Ḭ' => 'ḭ', + 'Ḯ' => 'ḯ', + 'Ḱ' => 'ḱ', + 'Ḳ' => 'ḳ', + 'Ḵ' => 'ḵ', + 'Ḷ' => 'ḷ', + 'Ḹ' => 'ḹ', + 'Ḻ' => 'ḻ', + 'Ḽ' => 'ḽ', + 'Ḿ' => 'ḿ', + 'Ṁ' => 'ṁ', + 'Ṃ' => 'ṃ', + 'Ṅ' => 'ṅ', + 'Ṇ' => 'ṇ', + 'Ṉ' => 'ṉ', + 'Ṋ' => 'ṋ', + 'Ṍ' => 'ṍ', + 'Ṏ' => 'ṏ', + 'Ṑ' => 'ṑ', + 'Ṓ' => 'ṓ', + 'Ṕ' => 'ṕ', + 'Ṗ' => 'ṗ', + 'Ṙ' => 'ṙ', + 'Ṛ' => 'ṛ', + 'Ṝ' => 'ṝ', + 'Ṟ' => 'ṟ', + 'Ṡ' => 'ṡ', + 'Ṣ' => 'ṣ', + 'Ṥ' => 'ṥ', + 'Ṧ' => 'ṧ', + 'Ṩ' => 'ṩ', + 'Ṫ' => 'ṫ', + 'Ṭ' => 'ṭ', + 'Ṯ' => 'ṯ', + 'Ṱ' => 'ṱ', + 'Ṳ' => 'ṳ', + 'Ṵ' => 'ṵ', + 'Ṷ' => 'ṷ', + 'Ṹ' => 'ṹ', + 'Ṻ' => 'ṻ', + 'Ṽ' => 'ṽ', + 'Ṿ' => 'ṿ', + 'Ẁ' => 'ẁ', + 'Ẃ' => 'ẃ', + 'Ẅ' => 'ẅ', + 'Ẇ' => 'ẇ', + 'Ẉ' => 'ẉ', + 'Ẋ' => 'ẋ', + 'Ẍ' => 'ẍ', + 'Ẏ' => 'ẏ', + 'Ẑ' => 'ẑ', + 'Ẓ' => 'ẓ', + 'Ẕ' => 'ẕ', + 'ẞ' => 'ß', + 'Ạ' => 'ạ', + 'Ả' => 'ả', + 'Ấ' => 'ấ', + 'Ầ' => 'ầ', + 'Ẩ' => 'ẩ', + 'Ẫ' => 'ẫ', + 'Ậ' => 'ậ', + 'Ắ' => 'ắ', + 'Ằ' => 'ằ', + 'Ẳ' => 'ẳ', + 'Ẵ' => 'ẵ', + 'Ặ' => 'ặ', + 'Ẹ' => 'ẹ', + 'Ẻ' => 'ẻ', + 'Ẽ' => 'ẽ', + 'Ế' => 'ế', + 'Ề' => 'ề', + 'Ể' => 'ể', + 'Ễ' => 'ễ', + 'Ệ' => 'ệ', + 'Ỉ' => 'ỉ', + 'Ị' => 'ị', + 'Ọ' => 'ọ', + 'Ỏ' => 'ỏ', + 'Ố' => 'ố', + 'Ồ' => 'ồ', + 'Ổ' => 'ổ', + 'Ỗ' => 'ỗ', + 'Ộ' => 'ộ', + 'Ớ' => 'ớ', + 'Ờ' => 'ờ', + 'Ở' => 'ở', + 'Ỡ' => 'ỡ', + 'Ợ' => 'ợ', + 'Ụ' => 'ụ', + 'Ủ' => 'ủ', + 'Ứ' => 'ứ', + 'Ừ' => 'ừ', + 'Ử' => 'ử', + 'Ữ' => 'ữ', + 'Ự' => 'ự', + 'Ỳ' => 'ỳ', + 'Ỵ' => 'ỵ', + 'Ỷ' => 'ỷ', + 'Ỹ' => 'ỹ', + 'Ỻ' => 'ỻ', + 'Ỽ' => 'ỽ', + 'Ỿ' => 'ỿ', + 'Ἀ' => 'ἀ', + 'Ἁ' => 'ἁ', + 'Ἂ' => 'ἂ', + 'Ἃ' => 'ἃ', + 'Ἄ' => 'ἄ', + 'Ἅ' => 'ἅ', + 'Ἆ' => 'ἆ', + 'Ἇ' => 'ἇ', + 'Ἐ' => 'ἐ', + 'Ἑ' => 'ἑ', + 'Ἒ' => 'ἒ', + 'Ἓ' => 'ἓ', + 'Ἔ' => 'ἔ', + 'Ἕ' => 'ἕ', + 'Ἠ' => 'ἠ', + 'Ἡ' => 'ἡ', + 'Ἢ' => 'ἢ', + 'Ἣ' => 'ἣ', + 'Ἤ' => 'ἤ', + 'Ἥ' => 'ἥ', + 'Ἦ' => 'ἦ', + 'Ἧ' => 'ἧ', + 'Ἰ' => 'ἰ', + 'Ἱ' => 'ἱ', + 'Ἲ' => 'ἲ', + 'Ἳ' => 'ἳ', + 'Ἴ' => 'ἴ', + 'Ἵ' => 'ἵ', + 'Ἶ' => 'ἶ', + 'Ἷ' => 'ἷ', + 'Ὀ' => 'ὀ', + 'Ὁ' => 'ὁ', + 'Ὂ' => 'ὂ', + 'Ὃ' => 'ὃ', + 'Ὄ' => 'ὄ', + 'Ὅ' => 'ὅ', + 'Ὑ' => 'ὑ', + 'Ὓ' => 'ὓ', + 'Ὕ' => 'ὕ', + 'Ὗ' => 'ὗ', + 'Ὠ' => 'ὠ', + 'Ὡ' => 'ὡ', + 'Ὢ' => 'ὢ', + 'Ὣ' => 'ὣ', + 'Ὤ' => 'ὤ', + 'Ὥ' => 'ὥ', + 'Ὦ' => 'ὦ', + 'Ὧ' => 'ὧ', + 'ᾈ' => 'ᾀ', + 'ᾉ' => 'ᾁ', + 'ᾊ' => 'ᾂ', + 'ᾋ' => 'ᾃ', + 'ᾌ' => 'ᾄ', + 'ᾍ' => 'ᾅ', + 'ᾎ' => 'ᾆ', + 'ᾏ' => 'ᾇ', + 'ᾘ' => 'ᾐ', + 'ᾙ' => 'ᾑ', + 'ᾚ' => 'ᾒ', + 'ᾛ' => 'ᾓ', + 'ᾜ' => 'ᾔ', + 'ᾝ' => 'ᾕ', + 'ᾞ' => 'ᾖ', + 'ᾟ' => 'ᾗ', + 'ᾨ' => 'ᾠ', + 'ᾩ' => 'ᾡ', + 'ᾪ' => 'ᾢ', + 'ᾫ' => 'ᾣ', + 'ᾬ' => 'ᾤ', + 'ᾭ' => 'ᾥ', + 'ᾮ' => 'ᾦ', + 'ᾯ' => 'ᾧ', + 'Ᾰ' => 'ᾰ', + 'Ᾱ' => 'ᾱ', + 'Ὰ' => 'ὰ', + 'Ά' => 'ά', + 'ᾼ' => 'ᾳ', + 'Ὲ' => 'ὲ', + 'Έ' => 'έ', + 'Ὴ' => 'ὴ', + 'Ή' => 'ή', + 'ῌ' => 'ῃ', + 'Ῐ' => 'ῐ', + 'Ῑ' => 'ῑ', + 'Ὶ' => 'ὶ', + 'Ί' => 'ί', + 'Ῠ' => 'ῠ', + 'Ῡ' => 'ῡ', + 'Ὺ' => 'ὺ', + 'Ύ' => 'ύ', + 'Ῥ' => 'ῥ', + 'Ὸ' => 'ὸ', + 'Ό' => 'ό', + 'Ὼ' => 'ὼ', + 'Ώ' => 'ώ', + 'ῼ' => 'ῳ', + 'Ω' => 'ω', + 'K' => 'k', + 'Å' => 'å', + 'Ⅎ' => 'ⅎ', + 'Ⅰ' => 'ⅰ', + 'Ⅱ' => 'ⅱ', + 'Ⅲ' => 'ⅲ', + 'Ⅳ' => 'ⅳ', + 'Ⅴ' => 'ⅴ', + 'Ⅵ' => 'ⅵ', + 'Ⅶ' => 'ⅶ', + 'Ⅷ' => 'ⅷ', + 'Ⅸ' => 'ⅸ', + 'Ⅹ' => 'ⅹ', + 'Ⅺ' => 'ⅺ', + 'Ⅻ' => 'ⅻ', + 'Ⅼ' => 'ⅼ', + 'Ⅽ' => 'ⅽ', + 'Ⅾ' => 'ⅾ', + 'Ⅿ' => 'ⅿ', + 'Ↄ' => 'ↄ', + 'Ⓐ' => 'ⓐ', + 'Ⓑ' => 'ⓑ', + 'Ⓒ' => 'ⓒ', + 'Ⓓ' => 'ⓓ', + 'Ⓔ' => 'ⓔ', + 'Ⓕ' => 'ⓕ', + 'Ⓖ' => 'ⓖ', + 'Ⓗ' => 'ⓗ', + 'Ⓘ' => 'ⓘ', + 'Ⓙ' => 'ⓙ', + 'Ⓚ' => 'ⓚ', + 'Ⓛ' => 'ⓛ', + 'Ⓜ' => 'ⓜ', + 'Ⓝ' => 'ⓝ', + 'Ⓞ' => 'ⓞ', + 'Ⓟ' => 'ⓟ', + 'Ⓠ' => 'ⓠ', + 'Ⓡ' => 'ⓡ', + 'Ⓢ' => 'ⓢ', + 'Ⓣ' => 'ⓣ', + 'Ⓤ' => 'ⓤ', + 'Ⓥ' => 'ⓥ', + 'Ⓦ' => 'ⓦ', + 'Ⓧ' => 'ⓧ', + 'Ⓨ' => 'ⓨ', + 'Ⓩ' => 'ⓩ', + 'Ⰰ' => 'ⰰ', + 'Ⰱ' => 'ⰱ', + 'Ⰲ' => 'ⰲ', + 'Ⰳ' => 'ⰳ', + 'Ⰴ' => 'ⰴ', + 'Ⰵ' => 'ⰵ', + 'Ⰶ' => 'ⰶ', + 'Ⰷ' => 'ⰷ', + 'Ⰸ' => 'ⰸ', + 'Ⰹ' => 'ⰹ', + 'Ⰺ' => 'ⰺ', + 'Ⰻ' => 'ⰻ', + 'Ⰼ' => 'ⰼ', + 'Ⰽ' => 'ⰽ', + 'Ⰾ' => 'ⰾ', + 'Ⰿ' => 'ⰿ', + 'Ⱀ' => 'ⱀ', + 'Ⱁ' => 'ⱁ', + 'Ⱂ' => 'ⱂ', + 'Ⱃ' => 'ⱃ', + 'Ⱄ' => 'ⱄ', + 'Ⱅ' => 'ⱅ', + 'Ⱆ' => 'ⱆ', + 'Ⱇ' => 'ⱇ', + 'Ⱈ' => 'ⱈ', + 'Ⱉ' => 'ⱉ', + 'Ⱊ' => 'ⱊ', + 'Ⱋ' => 'ⱋ', + 'Ⱌ' => 'ⱌ', + 'Ⱍ' => 'ⱍ', + 'Ⱎ' => 'ⱎ', + 'Ⱏ' => 'ⱏ', + 'Ⱐ' => 'ⱐ', + 'Ⱑ' => 'ⱑ', + 'Ⱒ' => 'ⱒ', + 'Ⱓ' => 'ⱓ', + 'Ⱔ' => 'ⱔ', + 'Ⱕ' => 'ⱕ', + 'Ⱖ' => 'ⱖ', + 'Ⱗ' => 'ⱗ', + 'Ⱘ' => 'ⱘ', + 'Ⱙ' => 'ⱙ', + 'Ⱚ' => 'ⱚ', + 'Ⱛ' => 'ⱛ', + 'Ⱜ' => 'ⱜ', + 'Ⱝ' => 'ⱝ', + 'Ⱞ' => 'ⱞ', + 'Ⱡ' => 'ⱡ', + 'Ɫ' => 'ɫ', + 'Ᵽ' => 'ᵽ', + 'Ɽ' => 'ɽ', + 'Ⱨ' => 'ⱨ', + 'Ⱪ' => 'ⱪ', + 'Ⱬ' => 'ⱬ', + 'Ɑ' => 'ɑ', + 'Ɱ' => 'ɱ', + 'Ɐ' => 'ɐ', + 'Ɒ' => 'ɒ', + 'Ⱳ' => 'ⱳ', + 'Ⱶ' => 'ⱶ', + 'Ȿ' => 'ȿ', + 'Ɀ' => 'ɀ', + 'Ⲁ' => 'ⲁ', + 'Ⲃ' => 'ⲃ', + 'Ⲅ' => 'ⲅ', + 'Ⲇ' => 'ⲇ', + 'Ⲉ' => 'ⲉ', + 'Ⲋ' => 'ⲋ', + 'Ⲍ' => 'ⲍ', + 'Ⲏ' => 'ⲏ', + 'Ⲑ' => 'ⲑ', + 'Ⲓ' => 'ⲓ', + 'Ⲕ' => 'ⲕ', + 'Ⲗ' => 'ⲗ', + 'Ⲙ' => 'ⲙ', + 'Ⲛ' => 'ⲛ', + 'Ⲝ' => 'ⲝ', + 'Ⲟ' => 'ⲟ', + 'Ⲡ' => 'ⲡ', + 'Ⲣ' => 'ⲣ', + 'Ⲥ' => 'ⲥ', + 'Ⲧ' => 'ⲧ', + 'Ⲩ' => 'ⲩ', + 'Ⲫ' => 'ⲫ', + 'Ⲭ' => 'ⲭ', + 'Ⲯ' => 'ⲯ', + 'Ⲱ' => 'ⲱ', + 'Ⲳ' => 'ⲳ', + 'Ⲵ' => 'ⲵ', + 'Ⲷ' => 'ⲷ', + 'Ⲹ' => 'ⲹ', + 'Ⲻ' => 'ⲻ', + 'Ⲽ' => 'ⲽ', + 'Ⲿ' => 'ⲿ', + 'Ⳁ' => 'ⳁ', + 'Ⳃ' => 'ⳃ', + 'Ⳅ' => 'ⳅ', + 'Ⳇ' => 'ⳇ', + 'Ⳉ' => 'ⳉ', + 'Ⳋ' => 'ⳋ', + 'Ⳍ' => 'ⳍ', + 'Ⳏ' => 'ⳏ', + 'Ⳑ' => 'ⳑ', + 'Ⳓ' => 'ⳓ', + 'Ⳕ' => 'ⳕ', + 'Ⳗ' => 'ⳗ', + 'Ⳙ' => 'ⳙ', + 'Ⳛ' => 'ⳛ', + 'Ⳝ' => 'ⳝ', + 'Ⳟ' => 'ⳟ', + 'Ⳡ' => 'ⳡ', + 'Ⳣ' => 'ⳣ', + 'Ⳬ' => 'ⳬ', + 'Ⳮ' => 'ⳮ', + 'Ⳳ' => 'ⳳ', + 'Ꙁ' => 'ꙁ', + 'Ꙃ' => 'ꙃ', + 'Ꙅ' => 'ꙅ', + 'Ꙇ' => 'ꙇ', + 'Ꙉ' => 'ꙉ', + 'Ꙋ' => 'ꙋ', + 'Ꙍ' => 'ꙍ', + 'Ꙏ' => 'ꙏ', + 'Ꙑ' => 'ꙑ', + 'Ꙓ' => 'ꙓ', + 'Ꙕ' => 'ꙕ', + 'Ꙗ' => 'ꙗ', + 'Ꙙ' => 'ꙙ', + 'Ꙛ' => 'ꙛ', + 'Ꙝ' => 'ꙝ', + 'Ꙟ' => 'ꙟ', + 'Ꙡ' => 'ꙡ', + 'Ꙣ' => 'ꙣ', + 'Ꙥ' => 'ꙥ', + 'Ꙧ' => 'ꙧ', + 'Ꙩ' => 'ꙩ', + 'Ꙫ' => 'ꙫ', + 'Ꙭ' => 'ꙭ', + 'Ꚁ' => 'ꚁ', + 'Ꚃ' => 'ꚃ', + 'Ꚅ' => 'ꚅ', + 'Ꚇ' => 'ꚇ', + 'Ꚉ' => 'ꚉ', + 'Ꚋ' => 'ꚋ', + 'Ꚍ' => 'ꚍ', + 'Ꚏ' => 'ꚏ', + 'Ꚑ' => 'ꚑ', + 'Ꚓ' => 'ꚓ', + 'Ꚕ' => 'ꚕ', + 'Ꚗ' => 'ꚗ', + 'Ꚙ' => 'ꚙ', + 'Ꚛ' => 'ꚛ', + 'Ꜣ' => 'ꜣ', + 'Ꜥ' => 'ꜥ', + 'Ꜧ' => 'ꜧ', + 'Ꜩ' => 'ꜩ', + 'Ꜫ' => 'ꜫ', + 'Ꜭ' => 'ꜭ', + 'Ꜯ' => 'ꜯ', + 'Ꜳ' => 'ꜳ', + 'Ꜵ' => 'ꜵ', + 'Ꜷ' => 'ꜷ', + 'Ꜹ' => 'ꜹ', + 'Ꜻ' => 'ꜻ', + 'Ꜽ' => 'ꜽ', + 'Ꜿ' => 'ꜿ', + 'Ꝁ' => 'ꝁ', + 'Ꝃ' => 'ꝃ', + 'Ꝅ' => 'ꝅ', + 'Ꝇ' => 'ꝇ', + 'Ꝉ' => 'ꝉ', + 'Ꝋ' => 'ꝋ', + 'Ꝍ' => 'ꝍ', + 'Ꝏ' => 'ꝏ', + 'Ꝑ' => 'ꝑ', + 'Ꝓ' => 'ꝓ', + 'Ꝕ' => 'ꝕ', + 'Ꝗ' => 'ꝗ', + 'Ꝙ' => 'ꝙ', + 'Ꝛ' => 'ꝛ', + 'Ꝝ' => 'ꝝ', + 'Ꝟ' => 'ꝟ', + 'Ꝡ' => 'ꝡ', + 'Ꝣ' => 'ꝣ', + 'Ꝥ' => 'ꝥ', + 'Ꝧ' => 'ꝧ', + 'Ꝩ' => 'ꝩ', + 'Ꝫ' => 'ꝫ', + 'Ꝭ' => 'ꝭ', + 'Ꝯ' => 'ꝯ', + 'Ꝺ' => 'ꝺ', + 'Ꝼ' => 'ꝼ', + 'Ᵹ' => 'ᵹ', + 'Ꝿ' => 'ꝿ', + 'Ꞁ' => 'ꞁ', + 'Ꞃ' => 'ꞃ', + 'Ꞅ' => 'ꞅ', + 'Ꞇ' => 'ꞇ', + 'Ꞌ' => 'ꞌ', + 'Ɥ' => 'ɥ', + 'Ꞑ' => 'ꞑ', + 'Ꞓ' => 'ꞓ', + 'Ꞗ' => 'ꞗ', + 'Ꞙ' => 'ꞙ', + 'Ꞛ' => 'ꞛ', + 'Ꞝ' => 'ꞝ', + 'Ꞟ' => 'ꞟ', + 'Ꞡ' => 'ꞡ', + 'Ꞣ' => 'ꞣ', + 'Ꞥ' => 'ꞥ', + 'Ꞧ' => 'ꞧ', + 'Ꞩ' => 'ꞩ', + 'Ɦ' => 'ɦ', + 'Ɜ' => 'ɜ', + 'Ɡ' => 'ɡ', + 'Ɬ' => 'ɬ', + 'Ɪ' => 'ɪ', + 'Ʞ' => 'ʞ', + 'Ʇ' => 'ʇ', + 'Ʝ' => 'ʝ', + 'Ꭓ' => 'ꭓ', + 'Ꞵ' => 'ꞵ', + 'Ꞷ' => 'ꞷ', + 'Ꞹ' => 'ꞹ', + 'Ꞻ' => 'ꞻ', + 'Ꞽ' => 'ꞽ', + 'Ꞿ' => 'ꞿ', + 'Ꟃ' => 'ꟃ', + 'Ꞔ' => 'ꞔ', + 'Ʂ' => 'ʂ', + 'Ᶎ' => 'ᶎ', + 'Ꟈ' => 'ꟈ', + 'Ꟊ' => 'ꟊ', + 'Ꟶ' => 'ꟶ', + 'A' => 'a', + 'B' => 'b', + 'C' => 'c', + 'D' => 'd', + 'E' => 'e', + 'F' => 'f', + 'G' => 'g', + 'H' => 'h', + 'I' => 'i', + 'J' => 'j', + 'K' => 'k', + 'L' => 'l', + 'M' => 'm', + 'N' => 'n', + 'O' => 'o', + 'P' => 'p', + 'Q' => 'q', + 'R' => 'r', + 'S' => 's', + 'T' => 't', + 'U' => 'u', + 'V' => 'v', + 'W' => 'w', + 'X' => 'x', + 'Y' => 'y', + 'Z' => 'z', + '𐐀' => '𐐨', + '𐐁' => '𐐩', + '𐐂' => '𐐪', + '𐐃' => '𐐫', + '𐐄' => '𐐬', + '𐐅' => '𐐭', + '𐐆' => '𐐮', + '𐐇' => '𐐯', + '𐐈' => '𐐰', + '𐐉' => '𐐱', + '𐐊' => '𐐲', + '𐐋' => '𐐳', + '𐐌' => '𐐴', + '𐐍' => '𐐵', + '𐐎' => '𐐶', + '𐐏' => '𐐷', + '𐐐' => '𐐸', + '𐐑' => '𐐹', + '𐐒' => '𐐺', + '𐐓' => '𐐻', + '𐐔' => '𐐼', + '𐐕' => '𐐽', + '𐐖' => '𐐾', + '𐐗' => '𐐿', + '𐐘' => '𐑀', + '𐐙' => '𐑁', + '𐐚' => '𐑂', + '𐐛' => '𐑃', + '𐐜' => '𐑄', + '𐐝' => '𐑅', + '𐐞' => '𐑆', + '𐐟' => '𐑇', + '𐐠' => '𐑈', + '𐐡' => '𐑉', + '𐐢' => '𐑊', + '𐐣' => '𐑋', + '𐐤' => '𐑌', + '𐐥' => '𐑍', + '𐐦' => '𐑎', + '𐐧' => '𐑏', + '𐒰' => '𐓘', + '𐒱' => '𐓙', + '𐒲' => '𐓚', + '𐒳' => '𐓛', + '𐒴' => '𐓜', + '𐒵' => '𐓝', + '𐒶' => '𐓞', + '𐒷' => '𐓟', + '𐒸' => '𐓠', + '𐒹' => '𐓡', + '𐒺' => '𐓢', + '𐒻' => '𐓣', + '𐒼' => '𐓤', + '𐒽' => '𐓥', + '𐒾' => '𐓦', + '𐒿' => '𐓧', + '𐓀' => '𐓨', + '𐓁' => '𐓩', + '𐓂' => '𐓪', + '𐓃' => '𐓫', + '𐓄' => '𐓬', + '𐓅' => '𐓭', + '𐓆' => '𐓮', + '𐓇' => '𐓯', + '𐓈' => '𐓰', + '𐓉' => '𐓱', + '𐓊' => '𐓲', + '𐓋' => '𐓳', + '𐓌' => '𐓴', + '𐓍' => '𐓵', + '𐓎' => '𐓶', + '𐓏' => '𐓷', + '𐓐' => '𐓸', + '𐓑' => '𐓹', + '𐓒' => '𐓺', + '𐓓' => '𐓻', + '𐲀' => '𐳀', + '𐲁' => '𐳁', + '𐲂' => '𐳂', + '𐲃' => '𐳃', + '𐲄' => '𐳄', + '𐲅' => '𐳅', + '𐲆' => '𐳆', + '𐲇' => '𐳇', + '𐲈' => '𐳈', + '𐲉' => '𐳉', + '𐲊' => '𐳊', + '𐲋' => '𐳋', + '𐲌' => '𐳌', + '𐲍' => '𐳍', + '𐲎' => '𐳎', + '𐲏' => '𐳏', + '𐲐' => '𐳐', + '𐲑' => '𐳑', + '𐲒' => '𐳒', + '𐲓' => '𐳓', + '𐲔' => '𐳔', + '𐲕' => '𐳕', + '𐲖' => '𐳖', + '𐲗' => '𐳗', + '𐲘' => '𐳘', + '𐲙' => '𐳙', + '𐲚' => '𐳚', + '𐲛' => '𐳛', + '𐲜' => '𐳜', + '𐲝' => '𐳝', + '𐲞' => '𐳞', + '𐲟' => '𐳟', + '𐲠' => '𐳠', + '𐲡' => '𐳡', + '𐲢' => '𐳢', + '𐲣' => '𐳣', + '𐲤' => '𐳤', + '𐲥' => '𐳥', + '𐲦' => '𐳦', + '𐲧' => '𐳧', + '𐲨' => '𐳨', + '𐲩' => '𐳩', + '𐲪' => '𐳪', + '𐲫' => '𐳫', + '𐲬' => '𐳬', + '𐲭' => '𐳭', + '𐲮' => '𐳮', + '𐲯' => '𐳯', + '𐲰' => '𐳰', + '𐲱' => '𐳱', + '𐲲' => '𐳲', + '𑢠' => '𑣀', + '𑢡' => '𑣁', + '𑢢' => '𑣂', + '𑢣' => '𑣃', + '𑢤' => '𑣄', + '𑢥' => '𑣅', + '𑢦' => '𑣆', + '𑢧' => '𑣇', + '𑢨' => '𑣈', + '𑢩' => '𑣉', + '𑢪' => '𑣊', + '𑢫' => '𑣋', + '𑢬' => '𑣌', + '𑢭' => '𑣍', + '𑢮' => '𑣎', + '𑢯' => '𑣏', + '𑢰' => '𑣐', + '𑢱' => '𑣑', + '𑢲' => '𑣒', + '𑢳' => '𑣓', + '𑢴' => '𑣔', + '𑢵' => '𑣕', + '𑢶' => '𑣖', + '𑢷' => '𑣗', + '𑢸' => '𑣘', + '𑢹' => '𑣙', + '𑢺' => '𑣚', + '𑢻' => '𑣛', + '𑢼' => '𑣜', + '𑢽' => '𑣝', + '𑢾' => '𑣞', + '𑢿' => '𑣟', + '𖹀' => '𖹠', + '𖹁' => '𖹡', + '𖹂' => '𖹢', + '𖹃' => '𖹣', + '𖹄' => '𖹤', + '𖹅' => '𖹥', + '𖹆' => '𖹦', + '𖹇' => '𖹧', + '𖹈' => '𖹨', + '𖹉' => '𖹩', + '𖹊' => '𖹪', + '𖹋' => '𖹫', + '𖹌' => '𖹬', + '𖹍' => '𖹭', + '𖹎' => '𖹮', + '𖹏' => '𖹯', + '𖹐' => '𖹰', + '𖹑' => '𖹱', + '𖹒' => '𖹲', + '𖹓' => '𖹳', + '𖹔' => '𖹴', + '𖹕' => '𖹵', + '𖹖' => '𖹶', + '𖹗' => '𖹷', + '𖹘' => '𖹸', + '𖹙' => '𖹹', + '𖹚' => '𖹺', + '𖹛' => '𖹻', + '𖹜' => '𖹼', + '𖹝' => '𖹽', + '𖹞' => '𖹾', + '𖹟' => '𖹿', + '𞤀' => '𞤢', + '𞤁' => '𞤣', + '𞤂' => '𞤤', + '𞤃' => '𞤥', + '𞤄' => '𞤦', + '𞤅' => '𞤧', + '𞤆' => '𞤨', + '𞤇' => '𞤩', + '𞤈' => '𞤪', + '𞤉' => '𞤫', + '𞤊' => '𞤬', + '𞤋' => '𞤭', + '𞤌' => '𞤮', + '𞤍' => '𞤯', + '𞤎' => '𞤰', + '𞤏' => '𞤱', + '𞤐' => '𞤲', + '𞤑' => '𞤳', + '𞤒' => '𞤴', + '𞤓' => '𞤵', + '𞤔' => '𞤶', + '𞤕' => '𞤷', + '𞤖' => '𞤸', + '𞤗' => '𞤹', + '𞤘' => '𞤺', + '𞤙' => '𞤻', + '𞤚' => '𞤼', + '𞤛' => '𞤽', + '𞤜' => '𞤾', + '𞤝' => '𞤿', + '𞤞' => '𞥀', + '𞤟' => '𞥁', + '𞤠' => '𞥂', + '𞤡' => '𞥃', +); diff --git a/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCase.php b/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCase.php new file mode 100644 index 0000000..64fd6a7 --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCase.php @@ -0,0 +1,139 @@ +<?php + +return array ( + 'DŽ' => 'Dž', + 'Dž' => 'Dž', + 'dž' => 'Dž', + 'LJ' => 'Lj', + 'Lj' => 'Lj', + 'lj' => 'Lj', + 'NJ' => 'Nj', + 'Nj' => 'Nj', + 'nj' => 'Nj', + 'DZ' => 'Dz', + 'Dz' => 'Dz', + 'dz' => 'Dz', + 'ა' => 'ა', + 'ბ' => 'ბ', + 'გ' => 'გ', + 'დ' => 'დ', + 'ე' => 'ე', + 'ვ' => 'ვ', + 'ზ' => 'ზ', + 'თ' => 'თ', + 'ი' => 'ი', + 'კ' => 'კ', + 'ლ' => 'ლ', + 'მ' => 'მ', + 'ნ' => 'ნ', + 'ო' => 'ო', + 'პ' => 'პ', + 'ჟ' => 'ჟ', + 'რ' => 'რ', + 'ს' => 'ს', + 'ტ' => 'ტ', + 'უ' => 'უ', + 'ფ' => 'ფ', + 'ქ' => 'ქ', + 'ღ' => 'ღ', + 'ყ' => 'ყ', + 'შ' => 'შ', + 'ჩ' => 'ჩ', + 'ც' => 'ც', + 'ძ' => 'ძ', + 'წ' => 'წ', + 'ჭ' => 'ჭ', + 'ხ' => 'ხ', + 'ჯ' => 'ჯ', + 'ჰ' => 'ჰ', + 'ჱ' => 'ჱ', + 'ჲ' => 'ჲ', + 'ჳ' => 'ჳ', + 'ჴ' => 'ჴ', + 'ჵ' => 'ჵ', + 'ჶ' => 'ჶ', + 'ჷ' => 'ჷ', + 'ჸ' => 'ჸ', + 'ჹ' => 'ჹ', + 'ჺ' => 'ჺ', + 'ჽ' => 'ჽ', + 'ჾ' => 'ჾ', + 'ჿ' => 'ჿ', + 'ß' => 'Ss', + 'ff' => 'Ff', + 'fi' => 'Fi', + 'fl' => 'Fl', + 'ffi' => 'Ffi', + 'ffl' => 'Ffl', + 'ſt' => 'St', + 'st' => 'St', + 'և' => 'Եւ', + 'ﬓ' => 'Մն', + 'ﬔ' => 'Մե', + 'ﬕ' => 'Մի', + 'ﬖ' => 'Վն', + 'ﬗ' => 'Մխ', + 'ᾀ' => 'ᾈ', + 'ᾁ' => 'ᾉ', + 'ᾂ' => 'ᾊ', + 'ᾃ' => 'ᾋ', + 'ᾄ' => 'ᾌ', + 'ᾅ' => 'ᾍ', + 'ᾆ' => 'ᾎ', + 'ᾇ' => 'ᾏ', + 'ᾈ' => 'ᾈ', + 'ᾉ' => 'ᾉ', + 'ᾊ' => 'ᾊ', + 'ᾋ' => 'ᾋ', + 'ᾌ' => 'ᾌ', + 'ᾍ' => 'ᾍ', + 'ᾎ' => 'ᾎ', + 'ᾏ' => 'ᾏ', + 'ᾐ' => 'ᾘ', + 'ᾑ' => 'ᾙ', + 'ᾒ' => 'ᾚ', + 'ᾓ' => 'ᾛ', + 'ᾔ' => 'ᾜ', + 'ᾕ' => 'ᾝ', + 'ᾖ' => 'ᾞ', + 'ᾗ' => 'ᾟ', + 'ᾘ' => 'ᾘ', + 'ᾙ' => 'ᾙ', + 'ᾚ' => 'ᾚ', + 'ᾛ' => 'ᾛ', + 'ᾜ' => 'ᾜ', + 'ᾝ' => 'ᾝ', + 'ᾞ' => 'ᾞ', + 'ᾟ' => 'ᾟ', + 'ᾠ' => 'ᾨ', + 'ᾡ' => 'ᾩ', + 'ᾢ' => 'ᾪ', + 'ᾣ' => 'ᾫ', + 'ᾤ' => 'ᾬ', + 'ᾥ' => 'ᾭ', + 'ᾦ' => 'ᾮ', + 'ᾧ' => 'ᾯ', + 'ᾨ' => 'ᾨ', + 'ᾩ' => 'ᾩ', + 'ᾪ' => 'ᾪ', + 'ᾫ' => 'ᾫ', + 'ᾬ' => 'ᾬ', + 'ᾭ' => 'ᾭ', + 'ᾮ' => 'ᾮ', + 'ᾯ' => 'ᾯ', + 'ᾳ' => 'ᾼ', + 'ᾼ' => 'ᾼ', + 'ῃ' => 'ῌ', + 'ῌ' => 'ῌ', + 'ῳ' => 'ῼ', + 'ῼ' => 'ῼ', + 'ᾲ' => 'Ὰͅ', + 'ᾴ' => 'Άͅ', + 'ῂ' => 'Ὴͅ', + 'ῄ' => 'Ήͅ', + 'ῲ' => 'Ὼͅ', + 'ῴ' => 'Ώͅ', + 'ᾷ' => 'ᾼ͂', + 'ῇ' => 'ῌ͂', + 'ῷ' => 'ῼ͂', +); diff --git a/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php b/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php new file mode 100644 index 0000000..2a8f6e7 --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php @@ -0,0 +1,5 @@ +<?php + +// from Case_Ignorable in https://unicode.org/Public/UNIDATA/DerivedCoreProperties.txt + +return '/(?<![\x{0027}\x{002E}\x{003A}\x{005E}\x{0060}\x{00A8}\x{00AD}\x{00AF}\x{00B4}\x{00B7}\x{00B8}\x{02B0}-\x{02C1}\x{02C2}-\x{02C5}\x{02C6}-\x{02D1}\x{02D2}-\x{02DF}\x{02E0}-\x{02E4}\x{02E5}-\x{02EB}\x{02EC}\x{02ED}\x{02EE}\x{02EF}-\x{02FF}\x{0300}-\x{036F}\x{0374}\x{0375}\x{037A}\x{0384}-\x{0385}\x{0387}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{0559}\x{0591}-\x{05BD}\x{05BF}\x{05C1}-\x{05C2}\x{05C4}-\x{05C5}\x{05C7}\x{05F4}\x{0600}-\x{0605}\x{0610}-\x{061A}\x{061C}\x{0640}\x{064B}-\x{065F}\x{0670}\x{06D6}-\x{06DC}\x{06DD}\x{06DF}-\x{06E4}\x{06E5}-\x{06E6}\x{06E7}-\x{06E8}\x{06EA}-\x{06ED}\x{070F}\x{0711}\x{0730}-\x{074A}\x{07A6}-\x{07B0}\x{07EB}-\x{07F3}\x{07F4}-\x{07F5}\x{07FA}\x{07FD}\x{0816}-\x{0819}\x{081A}\x{081B}-\x{0823}\x{0824}\x{0825}-\x{0827}\x{0828}\x{0829}-\x{082D}\x{0859}-\x{085B}\x{08D3}-\x{08E1}\x{08E2}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0971}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C81}\x{0CBC}\x{0CBF}\x{0CC6}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E46}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EB9}\x{0EBB}-\x{0EBC}\x{0EC6}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{10FC}\x{135D}-\x{135F}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17D7}\x{17DD}\x{180B}-\x{180D}\x{180E}\x{1843}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AA7}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1C78}-\x{1C7D}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1D2C}-\x{1D6A}\x{1D78}\x{1D9B}-\x{1DBF}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{1FBD}\x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}\x{1FFD}-\x{1FFE}\x{200B}-\x{200F}\x{2018}\x{2019}\x{2024}\x{2027}\x{202A}-\x{202E}\x{2060}-\x{2064}\x{2066}-\x{206F}\x{2071}\x{207F}\x{2090}-\x{209C}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2C7C}-\x{2C7D}\x{2CEF}-\x{2CF1}\x{2D6F}\x{2D7F}\x{2DE0}-\x{2DFF}\x{2E2F}\x{3005}\x{302A}-\x{302D}\x{3031}-\x{3035}\x{303B}\x{3099}-\x{309A}\x{309B}-\x{309C}\x{309D}-\x{309E}\x{30FC}-\x{30FE}\x{A015}\x{A4F8}-\x{A4FD}\x{A60C}\x{A66F}\x{A670}-\x{A672}\x{A674}-\x{A67D}\x{A67F}\x{A69C}-\x{A69D}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A700}-\x{A716}\x{A717}-\x{A71F}\x{A720}-\x{A721}\x{A770}\x{A788}\x{A789}-\x{A78A}\x{A7F8}-\x{A7F9}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}\x{A9CF}\x{A9E5}\x{A9E6}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA70}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AADD}\x{AAEC}-\x{AAED}\x{AAF3}-\x{AAF4}\x{AAF6}\x{AB5B}\x{AB5C}-\x{AB5F}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1E}\x{FBB2}-\x{FBC1}\x{FE00}-\x{FE0F}\x{FE13}\x{FE20}-\x{FE2F}\x{FE52}\x{FE55}\x{FEFF}\x{FF07}\x{FF0E}\x{FF1A}\x{FF3E}\x{FF40}\x{FF70}\x{FF9E}-\x{FF9F}\x{FFE3}\x{FFF9}-\x{FFFB}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10A01}-\x{10A03}\x{10A05}-\x{10A06}\x{10A0C}-\x{10A0F}\x{10A38}-\x{10A3A}\x{10A3F}\x{10AE5}-\x{10AE6}\x{10D24}-\x{10D27}\x{10F46}-\x{10F50}\x{11001}\x{11038}-\x{11046}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{110BD}\x{110CD}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{11A01}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C3F}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16B40}-\x{16B43}\x{16F8F}-\x{16F92}\x{16F93}-\x{16F9F}\x{16FE0}-\x{16FE1}\x{1BC9D}-\x{1BC9E}\x{1BCA0}-\x{1BCA3}\x{1D167}-\x{1D169}\x{1D173}-\x{1D17A}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D242}-\x{1D244}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E8D0}-\x{1E8D6}\x{1E944}-\x{1E94A}\x{1F3FB}-\x{1F3FF}\x{E0001}\x{E0020}-\x{E007F}\x{E0100}-\x{E01EF}])(\pL)(\pL*+)/u'; diff --git a/vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.php b/vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.php new file mode 100644 index 0000000..56b9cb8 --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.php @@ -0,0 +1,1489 @@ +<?php + +return array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', + 'f' => 'F', + 'g' => 'G', + 'h' => 'H', + 'i' => 'I', + 'j' => 'J', + 'k' => 'K', + 'l' => 'L', + 'm' => 'M', + 'n' => 'N', + 'o' => 'O', + 'p' => 'P', + 'q' => 'Q', + 'r' => 'R', + 's' => 'S', + 't' => 'T', + 'u' => 'U', + 'v' => 'V', + 'w' => 'W', + 'x' => 'X', + 'y' => 'Y', + 'z' => 'Z', + 'µ' => 'Μ', + 'à' => 'À', + 'á' => 'Á', + 'â' => 'Â', + 'ã' => 'Ã', + 'ä' => 'Ä', + 'å' => 'Å', + 'æ' => 'Æ', + 'ç' => 'Ç', + 'è' => 'È', + 'é' => 'É', + 'ê' => 'Ê', + 'ë' => 'Ë', + 'ì' => 'Ì', + 'í' => 'Í', + 'î' => 'Î', + 'ï' => 'Ï', + 'ð' => 'Ð', + 'ñ' => 'Ñ', + 'ò' => 'Ò', + 'ó' => 'Ó', + 'ô' => 'Ô', + 'õ' => 'Õ', + 'ö' => 'Ö', + 'ø' => 'Ø', + 'ù' => 'Ù', + 'ú' => 'Ú', + 'û' => 'Û', + 'ü' => 'Ü', + 'ý' => 'Ý', + 'þ' => 'Þ', + 'ÿ' => 'Ÿ', + 'ā' => 'Ā', + 'ă' => 'Ă', + 'ą' => 'Ą', + 'ć' => 'Ć', + 'ĉ' => 'Ĉ', + 'ċ' => 'Ċ', + 'č' => 'Č', + 'ď' => 'Ď', + 'đ' => 'Đ', + 'ē' => 'Ē', + 'ĕ' => 'Ĕ', + 'ė' => 'Ė', + 'ę' => 'Ę', + 'ě' => 'Ě', + 'ĝ' => 'Ĝ', + 'ğ' => 'Ğ', + 'ġ' => 'Ġ', + 'ģ' => 'Ģ', + 'ĥ' => 'Ĥ', + 'ħ' => 'Ħ', + 'ĩ' => 'Ĩ', + 'ī' => 'Ī', + 'ĭ' => 'Ĭ', + 'į' => 'Į', + 'ı' => 'I', + 'ij' => 'IJ', + 'ĵ' => 'Ĵ', + 'ķ' => 'Ķ', + 'ĺ' => 'Ĺ', + 'ļ' => 'Ļ', + 'ľ' => 'Ľ', + 'ŀ' => 'Ŀ', + 'ł' => 'Ł', + 'ń' => 'Ń', + 'ņ' => 'Ņ', + 'ň' => 'Ň', + 'ŋ' => 'Ŋ', + 'ō' => 'Ō', + 'ŏ' => 'Ŏ', + 'ő' => 'Ő', + 'œ' => 'Œ', + 'ŕ' => 'Ŕ', + 'ŗ' => 'Ŗ', + 'ř' => 'Ř', + 'ś' => 'Ś', + 'ŝ' => 'Ŝ', + 'ş' => 'Ş', + 'š' => 'Š', + 'ţ' => 'Ţ', + 'ť' => 'Ť', + 'ŧ' => 'Ŧ', + 'ũ' => 'Ũ', + 'ū' => 'Ū', + 'ŭ' => 'Ŭ', + 'ů' => 'Ů', + 'ű' => 'Ű', + 'ų' => 'Ų', + 'ŵ' => 'Ŵ', + 'ŷ' => 'Ŷ', + 'ź' => 'Ź', + 'ż' => 'Ż', + 'ž' => 'Ž', + 'ſ' => 'S', + 'ƀ' => 'Ƀ', + 'ƃ' => 'Ƃ', + 'ƅ' => 'Ƅ', + 'ƈ' => 'Ƈ', + 'ƌ' => 'Ƌ', + 'ƒ' => 'Ƒ', + 'ƕ' => 'Ƕ', + 'ƙ' => 'Ƙ', + 'ƚ' => 'Ƚ', + 'ƞ' => 'Ƞ', + 'ơ' => 'Ơ', + 'ƣ' => 'Ƣ', + 'ƥ' => 'Ƥ', + 'ƨ' => 'Ƨ', + 'ƭ' => 'Ƭ', + 'ư' => 'Ư', + 'ƴ' => 'Ƴ', + 'ƶ' => 'Ƶ', + 'ƹ' => 'Ƹ', + 'ƽ' => 'Ƽ', + 'ƿ' => 'Ƿ', + 'Dž' => 'DŽ', + 'dž' => 'DŽ', + 'Lj' => 'LJ', + 'lj' => 'LJ', + 'Nj' => 'NJ', + 'nj' => 'NJ', + 'ǎ' => 'Ǎ', + 'ǐ' => 'Ǐ', + 'ǒ' => 'Ǒ', + 'ǔ' => 'Ǔ', + 'ǖ' => 'Ǖ', + 'ǘ' => 'Ǘ', + 'ǚ' => 'Ǚ', + 'ǜ' => 'Ǜ', + 'ǝ' => 'Ǝ', + 'ǟ' => 'Ǟ', + 'ǡ' => 'Ǡ', + 'ǣ' => 'Ǣ', + 'ǥ' => 'Ǥ', + 'ǧ' => 'Ǧ', + 'ǩ' => 'Ǩ', + 'ǫ' => 'Ǫ', + 'ǭ' => 'Ǭ', + 'ǯ' => 'Ǯ', + 'Dz' => 'DZ', + 'dz' => 'DZ', + 'ǵ' => 'Ǵ', + 'ǹ' => 'Ǹ', + 'ǻ' => 'Ǻ', + 'ǽ' => 'Ǽ', + 'ǿ' => 'Ǿ', + 'ȁ' => 'Ȁ', + 'ȃ' => 'Ȃ', + 'ȅ' => 'Ȅ', + 'ȇ' => 'Ȇ', + 'ȉ' => 'Ȉ', + 'ȋ' => 'Ȋ', + 'ȍ' => 'Ȍ', + 'ȏ' => 'Ȏ', + 'ȑ' => 'Ȑ', + 'ȓ' => 'Ȓ', + 'ȕ' => 'Ȕ', + 'ȗ' => 'Ȗ', + 'ș' => 'Ș', + 'ț' => 'Ț', + 'ȝ' => 'Ȝ', + 'ȟ' => 'Ȟ', + 'ȣ' => 'Ȣ', + 'ȥ' => 'Ȥ', + 'ȧ' => 'Ȧ', + 'ȩ' => 'Ȩ', + 'ȫ' => 'Ȫ', + 'ȭ' => 'Ȭ', + 'ȯ' => 'Ȯ', + 'ȱ' => 'Ȱ', + 'ȳ' => 'Ȳ', + 'ȼ' => 'Ȼ', + 'ȿ' => 'Ȿ', + 'ɀ' => 'Ɀ', + 'ɂ' => 'Ɂ', + 'ɇ' => 'Ɇ', + 'ɉ' => 'Ɉ', + 'ɋ' => 'Ɋ', + 'ɍ' => 'Ɍ', + 'ɏ' => 'Ɏ', + 'ɐ' => 'Ɐ', + 'ɑ' => 'Ɑ', + 'ɒ' => 'Ɒ', + 'ɓ' => 'Ɓ', + 'ɔ' => 'Ɔ', + 'ɖ' => 'Ɖ', + 'ɗ' => 'Ɗ', + 'ə' => 'Ə', + 'ɛ' => 'Ɛ', + 'ɜ' => 'Ɜ', + 'ɠ' => 'Ɠ', + 'ɡ' => 'Ɡ', + 'ɣ' => 'Ɣ', + 'ɥ' => 'Ɥ', + 'ɦ' => 'Ɦ', + 'ɨ' => 'Ɨ', + 'ɩ' => 'Ɩ', + 'ɪ' => 'Ɪ', + 'ɫ' => 'Ɫ', + 'ɬ' => 'Ɬ', + 'ɯ' => 'Ɯ', + 'ɱ' => 'Ɱ', + 'ɲ' => 'Ɲ', + 'ɵ' => 'Ɵ', + 'ɽ' => 'Ɽ', + 'ʀ' => 'Ʀ', + 'ʂ' => 'Ʂ', + 'ʃ' => 'Ʃ', + 'ʇ' => 'Ʇ', + 'ʈ' => 'Ʈ', + 'ʉ' => 'Ʉ', + 'ʊ' => 'Ʊ', + 'ʋ' => 'Ʋ', + 'ʌ' => 'Ʌ', + 'ʒ' => 'Ʒ', + 'ʝ' => 'Ʝ', + 'ʞ' => 'Ʞ', + 'ͅ' => 'Ι', + 'ͱ' => 'Ͱ', + 'ͳ' => 'Ͳ', + 'ͷ' => 'Ͷ', + 'ͻ' => 'Ͻ', + 'ͼ' => 'Ͼ', + 'ͽ' => 'Ͽ', + 'ά' => 'Ά', + 'έ' => 'Έ', + 'ή' => 'Ή', + 'ί' => 'Ί', + 'α' => 'Α', + 'β' => 'Β', + 'γ' => 'Γ', + 'δ' => 'Δ', + 'ε' => 'Ε', + 'ζ' => 'Ζ', + 'η' => 'Η', + 'θ' => 'Θ', + 'ι' => 'Ι', + 'κ' => 'Κ', + 'λ' => 'Λ', + 'μ' => 'Μ', + 'ν' => 'Ν', + 'ξ' => 'Ξ', + 'ο' => 'Ο', + 'π' => 'Π', + 'ρ' => 'Ρ', + 'ς' => 'Σ', + 'σ' => 'Σ', + 'τ' => 'Τ', + 'υ' => 'Υ', + 'φ' => 'Φ', + 'χ' => 'Χ', + 'ψ' => 'Ψ', + 'ω' => 'Ω', + 'ϊ' => 'Ϊ', + 'ϋ' => 'Ϋ', + 'ό' => 'Ό', + 'ύ' => 'Ύ', + 'ώ' => 'Ώ', + 'ϐ' => 'Β', + 'ϑ' => 'Θ', + 'ϕ' => 'Φ', + 'ϖ' => 'Π', + 'ϗ' => 'Ϗ', + 'ϙ' => 'Ϙ', + 'ϛ' => 'Ϛ', + 'ϝ' => 'Ϝ', + 'ϟ' => 'Ϟ', + 'ϡ' => 'Ϡ', + 'ϣ' => 'Ϣ', + 'ϥ' => 'Ϥ', + 'ϧ' => 'Ϧ', + 'ϩ' => 'Ϩ', + 'ϫ' => 'Ϫ', + 'ϭ' => 'Ϭ', + 'ϯ' => 'Ϯ', + 'ϰ' => 'Κ', + 'ϱ' => 'Ρ', + 'ϲ' => 'Ϲ', + 'ϳ' => 'Ϳ', + 'ϵ' => 'Ε', + 'ϸ' => 'Ϸ', + 'ϻ' => 'Ϻ', + 'а' => 'А', + 'б' => 'Б', + 'в' => 'В', + 'г' => 'Г', + 'д' => 'Д', + 'е' => 'Е', + 'ж' => 'Ж', + 'з' => 'З', + 'и' => 'И', + 'й' => 'Й', + 'к' => 'К', + 'л' => 'Л', + 'м' => 'М', + 'н' => 'Н', + 'о' => 'О', + 'п' => 'П', + 'р' => 'Р', + 'с' => 'С', + 'т' => 'Т', + 'у' => 'У', + 'ф' => 'Ф', + 'х' => 'Х', + 'ц' => 'Ц', + 'ч' => 'Ч', + 'ш' => 'Ш', + 'щ' => 'Щ', + 'ъ' => 'Ъ', + 'ы' => 'Ы', + 'ь' => 'Ь', + 'э' => 'Э', + 'ю' => 'Ю', + 'я' => 'Я', + 'ѐ' => 'Ѐ', + 'ё' => 'Ё', + 'ђ' => 'Ђ', + 'ѓ' => 'Ѓ', + 'є' => 'Є', + 'ѕ' => 'Ѕ', + 'і' => 'І', + 'ї' => 'Ї', + 'ј' => 'Ј', + 'љ' => 'Љ', + 'њ' => 'Њ', + 'ћ' => 'Ћ', + 'ќ' => 'Ќ', + 'ѝ' => 'Ѝ', + 'ў' => 'Ў', + 'џ' => 'Џ', + 'ѡ' => 'Ѡ', + 'ѣ' => 'Ѣ', + 'ѥ' => 'Ѥ', + 'ѧ' => 'Ѧ', + 'ѩ' => 'Ѩ', + 'ѫ' => 'Ѫ', + 'ѭ' => 'Ѭ', + 'ѯ' => 'Ѯ', + 'ѱ' => 'Ѱ', + 'ѳ' => 'Ѳ', + 'ѵ' => 'Ѵ', + 'ѷ' => 'Ѷ', + 'ѹ' => 'Ѹ', + 'ѻ' => 'Ѻ', + 'ѽ' => 'Ѽ', + 'ѿ' => 'Ѿ', + 'ҁ' => 'Ҁ', + 'ҋ' => 'Ҋ', + 'ҍ' => 'Ҍ', + 'ҏ' => 'Ҏ', + 'ґ' => 'Ґ', + 'ғ' => 'Ғ', + 'ҕ' => 'Ҕ', + 'җ' => 'Җ', + 'ҙ' => 'Ҙ', + 'қ' => 'Қ', + 'ҝ' => 'Ҝ', + 'ҟ' => 'Ҟ', + 'ҡ' => 'Ҡ', + 'ң' => 'Ң', + 'ҥ' => 'Ҥ', + 'ҧ' => 'Ҧ', + 'ҩ' => 'Ҩ', + 'ҫ' => 'Ҫ', + 'ҭ' => 'Ҭ', + 'ү' => 'Ү', + 'ұ' => 'Ұ', + 'ҳ' => 'Ҳ', + 'ҵ' => 'Ҵ', + 'ҷ' => 'Ҷ', + 'ҹ' => 'Ҹ', + 'һ' => 'Һ', + 'ҽ' => 'Ҽ', + 'ҿ' => 'Ҿ', + 'ӂ' => 'Ӂ', + 'ӄ' => 'Ӄ', + 'ӆ' => 'Ӆ', + 'ӈ' => 'Ӈ', + 'ӊ' => 'Ӊ', + 'ӌ' => 'Ӌ', + 'ӎ' => 'Ӎ', + 'ӏ' => 'Ӏ', + 'ӑ' => 'Ӑ', + 'ӓ' => 'Ӓ', + 'ӕ' => 'Ӕ', + 'ӗ' => 'Ӗ', + 'ә' => 'Ә', + 'ӛ' => 'Ӛ', + 'ӝ' => 'Ӝ', + 'ӟ' => 'Ӟ', + 'ӡ' => 'Ӡ', + 'ӣ' => 'Ӣ', + 'ӥ' => 'Ӥ', + 'ӧ' => 'Ӧ', + 'ө' => 'Ө', + 'ӫ' => 'Ӫ', + 'ӭ' => 'Ӭ', + 'ӯ' => 'Ӯ', + 'ӱ' => 'Ӱ', + 'ӳ' => 'Ӳ', + 'ӵ' => 'Ӵ', + 'ӷ' => 'Ӷ', + 'ӹ' => 'Ӹ', + 'ӻ' => 'Ӻ', + 'ӽ' => 'Ӽ', + 'ӿ' => 'Ӿ', + 'ԁ' => 'Ԁ', + 'ԃ' => 'Ԃ', + 'ԅ' => 'Ԅ', + 'ԇ' => 'Ԇ', + 'ԉ' => 'Ԉ', + 'ԋ' => 'Ԋ', + 'ԍ' => 'Ԍ', + 'ԏ' => 'Ԏ', + 'ԑ' => 'Ԑ', + 'ԓ' => 'Ԓ', + 'ԕ' => 'Ԕ', + 'ԗ' => 'Ԗ', + 'ԙ' => 'Ԙ', + 'ԛ' => 'Ԛ', + 'ԝ' => 'Ԝ', + 'ԟ' => 'Ԟ', + 'ԡ' => 'Ԡ', + 'ԣ' => 'Ԣ', + 'ԥ' => 'Ԥ', + 'ԧ' => 'Ԧ', + 'ԩ' => 'Ԩ', + 'ԫ' => 'Ԫ', + 'ԭ' => 'Ԭ', + 'ԯ' => 'Ԯ', + 'ա' => 'Ա', + 'բ' => 'Բ', + 'գ' => 'Գ', + 'դ' => 'Դ', + 'ե' => 'Ե', + 'զ' => 'Զ', + 'է' => 'Է', + 'ը' => 'Ը', + 'թ' => 'Թ', + 'ժ' => 'Ժ', + 'ի' => 'Ի', + 'լ' => 'Լ', + 'խ' => 'Խ', + 'ծ' => 'Ծ', + 'կ' => 'Կ', + 'հ' => 'Հ', + 'ձ' => 'Ձ', + 'ղ' => 'Ղ', + 'ճ' => 'Ճ', + 'մ' => 'Մ', + 'յ' => 'Յ', + 'ն' => 'Ն', + 'շ' => 'Շ', + 'ո' => 'Ո', + 'չ' => 'Չ', + 'պ' => 'Պ', + 'ջ' => 'Ջ', + 'ռ' => 'Ռ', + 'ս' => 'Ս', + 'վ' => 'Վ', + 'տ' => 'Տ', + 'ր' => 'Ր', + 'ց' => 'Ց', + 'ւ' => 'Ւ', + 'փ' => 'Փ', + 'ք' => 'Ք', + 'օ' => 'Օ', + 'ֆ' => 'Ֆ', + 'ა' => 'Ა', + 'ბ' => 'Ბ', + 'გ' => 'Გ', + 'დ' => 'Დ', + 'ე' => 'Ე', + 'ვ' => 'Ვ', + 'ზ' => 'Ზ', + 'თ' => 'Თ', + 'ი' => 'Ი', + 'კ' => 'Კ', + 'ლ' => 'Ლ', + 'მ' => 'Მ', + 'ნ' => 'Ნ', + 'ო' => 'Ო', + 'პ' => 'Პ', + 'ჟ' => 'Ჟ', + 'რ' => 'Რ', + 'ს' => 'Ს', + 'ტ' => 'Ტ', + 'უ' => 'Უ', + 'ფ' => 'Ფ', + 'ქ' => 'Ქ', + 'ღ' => 'Ღ', + 'ყ' => 'Ყ', + 'შ' => 'Შ', + 'ჩ' => 'Ჩ', + 'ც' => 'Ც', + 'ძ' => 'Ძ', + 'წ' => 'Წ', + 'ჭ' => 'Ჭ', + 'ხ' => 'Ხ', + 'ჯ' => 'Ჯ', + 'ჰ' => 'Ჰ', + 'ჱ' => 'Ჱ', + 'ჲ' => 'Ჲ', + 'ჳ' => 'Ჳ', + 'ჴ' => 'Ჴ', + 'ჵ' => 'Ჵ', + 'ჶ' => 'Ჶ', + 'ჷ' => 'Ჷ', + 'ჸ' => 'Ჸ', + 'ჹ' => 'Ჹ', + 'ჺ' => 'Ჺ', + 'ჽ' => 'Ჽ', + 'ჾ' => 'Ჾ', + 'ჿ' => 'Ჿ', + 'ᏸ' => 'Ᏸ', + 'ᏹ' => 'Ᏹ', + 'ᏺ' => 'Ᏺ', + 'ᏻ' => 'Ᏻ', + 'ᏼ' => 'Ᏼ', + 'ᏽ' => 'Ᏽ', + 'ᲀ' => 'В', + 'ᲁ' => 'Д', + 'ᲂ' => 'О', + 'ᲃ' => 'С', + 'ᲄ' => 'Т', + 'ᲅ' => 'Т', + 'ᲆ' => 'Ъ', + 'ᲇ' => 'Ѣ', + 'ᲈ' => 'Ꙋ', + 'ᵹ' => 'Ᵹ', + 'ᵽ' => 'Ᵽ', + 'ᶎ' => 'Ᶎ', + 'ḁ' => 'Ḁ', + 'ḃ' => 'Ḃ', + 'ḅ' => 'Ḅ', + 'ḇ' => 'Ḇ', + 'ḉ' => 'Ḉ', + 'ḋ' => 'Ḋ', + 'ḍ' => 'Ḍ', + 'ḏ' => 'Ḏ', + 'ḑ' => 'Ḑ', + 'ḓ' => 'Ḓ', + 'ḕ' => 'Ḕ', + 'ḗ' => 'Ḗ', + 'ḙ' => 'Ḙ', + 'ḛ' => 'Ḛ', + 'ḝ' => 'Ḝ', + 'ḟ' => 'Ḟ', + 'ḡ' => 'Ḡ', + 'ḣ' => 'Ḣ', + 'ḥ' => 'Ḥ', + 'ḧ' => 'Ḧ', + 'ḩ' => 'Ḩ', + 'ḫ' => 'Ḫ', + 'ḭ' => 'Ḭ', + 'ḯ' => 'Ḯ', + 'ḱ' => 'Ḱ', + 'ḳ' => 'Ḳ', + 'ḵ' => 'Ḵ', + 'ḷ' => 'Ḷ', + 'ḹ' => 'Ḹ', + 'ḻ' => 'Ḻ', + 'ḽ' => 'Ḽ', + 'ḿ' => 'Ḿ', + 'ṁ' => 'Ṁ', + 'ṃ' => 'Ṃ', + 'ṅ' => 'Ṅ', + 'ṇ' => 'Ṇ', + 'ṉ' => 'Ṉ', + 'ṋ' => 'Ṋ', + 'ṍ' => 'Ṍ', + 'ṏ' => 'Ṏ', + 'ṑ' => 'Ṑ', + 'ṓ' => 'Ṓ', + 'ṕ' => 'Ṕ', + 'ṗ' => 'Ṗ', + 'ṙ' => 'Ṙ', + 'ṛ' => 'Ṛ', + 'ṝ' => 'Ṝ', + 'ṟ' => 'Ṟ', + 'ṡ' => 'Ṡ', + 'ṣ' => 'Ṣ', + 'ṥ' => 'Ṥ', + 'ṧ' => 'Ṧ', + 'ṩ' => 'Ṩ', + 'ṫ' => 'Ṫ', + 'ṭ' => 'Ṭ', + 'ṯ' => 'Ṯ', + 'ṱ' => 'Ṱ', + 'ṳ' => 'Ṳ', + 'ṵ' => 'Ṵ', + 'ṷ' => 'Ṷ', + 'ṹ' => 'Ṹ', + 'ṻ' => 'Ṻ', + 'ṽ' => 'Ṽ', + 'ṿ' => 'Ṿ', + 'ẁ' => 'Ẁ', + 'ẃ' => 'Ẃ', + 'ẅ' => 'Ẅ', + 'ẇ' => 'Ẇ', + 'ẉ' => 'Ẉ', + 'ẋ' => 'Ẋ', + 'ẍ' => 'Ẍ', + 'ẏ' => 'Ẏ', + 'ẑ' => 'Ẑ', + 'ẓ' => 'Ẓ', + 'ẕ' => 'Ẕ', + 'ẛ' => 'Ṡ', + 'ạ' => 'Ạ', + 'ả' => 'Ả', + 'ấ' => 'Ấ', + 'ầ' => 'Ầ', + 'ẩ' => 'Ẩ', + 'ẫ' => 'Ẫ', + 'ậ' => 'Ậ', + 'ắ' => 'Ắ', + 'ằ' => 'Ằ', + 'ẳ' => 'Ẳ', + 'ẵ' => 'Ẵ', + 'ặ' => 'Ặ', + 'ẹ' => 'Ẹ', + 'ẻ' => 'Ẻ', + 'ẽ' => 'Ẽ', + 'ế' => 'Ế', + 'ề' => 'Ề', + 'ể' => 'Ể', + 'ễ' => 'Ễ', + 'ệ' => 'Ệ', + 'ỉ' => 'Ỉ', + 'ị' => 'Ị', + 'ọ' => 'Ọ', + 'ỏ' => 'Ỏ', + 'ố' => 'Ố', + 'ồ' => 'Ồ', + 'ổ' => 'Ổ', + 'ỗ' => 'Ỗ', + 'ộ' => 'Ộ', + 'ớ' => 'Ớ', + 'ờ' => 'Ờ', + 'ở' => 'Ở', + 'ỡ' => 'Ỡ', + 'ợ' => 'Ợ', + 'ụ' => 'Ụ', + 'ủ' => 'Ủ', + 'ứ' => 'Ứ', + 'ừ' => 'Ừ', + 'ử' => 'Ử', + 'ữ' => 'Ữ', + 'ự' => 'Ự', + 'ỳ' => 'Ỳ', + 'ỵ' => 'Ỵ', + 'ỷ' => 'Ỷ', + 'ỹ' => 'Ỹ', + 'ỻ' => 'Ỻ', + 'ỽ' => 'Ỽ', + 'ỿ' => 'Ỿ', + 'ἀ' => 'Ἀ', + 'ἁ' => 'Ἁ', + 'ἂ' => 'Ἂ', + 'ἃ' => 'Ἃ', + 'ἄ' => 'Ἄ', + 'ἅ' => 'Ἅ', + 'ἆ' => 'Ἆ', + 'ἇ' => 'Ἇ', + 'ἐ' => 'Ἐ', + 'ἑ' => 'Ἑ', + 'ἒ' => 'Ἒ', + 'ἓ' => 'Ἓ', + 'ἔ' => 'Ἔ', + 'ἕ' => 'Ἕ', + 'ἠ' => 'Ἠ', + 'ἡ' => 'Ἡ', + 'ἢ' => 'Ἢ', + 'ἣ' => 'Ἣ', + 'ἤ' => 'Ἤ', + 'ἥ' => 'Ἥ', + 'ἦ' => 'Ἦ', + 'ἧ' => 'Ἧ', + 'ἰ' => 'Ἰ', + 'ἱ' => 'Ἱ', + 'ἲ' => 'Ἲ', + 'ἳ' => 'Ἳ', + 'ἴ' => 'Ἴ', + 'ἵ' => 'Ἵ', + 'ἶ' => 'Ἶ', + 'ἷ' => 'Ἷ', + 'ὀ' => 'Ὀ', + 'ὁ' => 'Ὁ', + 'ὂ' => 'Ὂ', + 'ὃ' => 'Ὃ', + 'ὄ' => 'Ὄ', + 'ὅ' => 'Ὅ', + 'ὑ' => 'Ὑ', + 'ὓ' => 'Ὓ', + 'ὕ' => 'Ὕ', + 'ὗ' => 'Ὗ', + 'ὠ' => 'Ὠ', + 'ὡ' => 'Ὡ', + 'ὢ' => 'Ὢ', + 'ὣ' => 'Ὣ', + 'ὤ' => 'Ὤ', + 'ὥ' => 'Ὥ', + 'ὦ' => 'Ὦ', + 'ὧ' => 'Ὧ', + 'ὰ' => 'Ὰ', + 'ά' => 'Ά', + 'ὲ' => 'Ὲ', + 'έ' => 'Έ', + 'ὴ' => 'Ὴ', + 'ή' => 'Ή', + 'ὶ' => 'Ὶ', + 'ί' => 'Ί', + 'ὸ' => 'Ὸ', + 'ό' => 'Ό', + 'ὺ' => 'Ὺ', + 'ύ' => 'Ύ', + 'ὼ' => 'Ὼ', + 'ώ' => 'Ώ', + 'ᾀ' => 'ἈΙ', + 'ᾁ' => 'ἉΙ', + 'ᾂ' => 'ἊΙ', + 'ᾃ' => 'ἋΙ', + 'ᾄ' => 'ἌΙ', + 'ᾅ' => 'ἍΙ', + 'ᾆ' => 'ἎΙ', + 'ᾇ' => 'ἏΙ', + 'ᾐ' => 'ἨΙ', + 'ᾑ' => 'ἩΙ', + 'ᾒ' => 'ἪΙ', + 'ᾓ' => 'ἫΙ', + 'ᾔ' => 'ἬΙ', + 'ᾕ' => 'ἭΙ', + 'ᾖ' => 'ἮΙ', + 'ᾗ' => 'ἯΙ', + 'ᾠ' => 'ὨΙ', + 'ᾡ' => 'ὩΙ', + 'ᾢ' => 'ὪΙ', + 'ᾣ' => 'ὫΙ', + 'ᾤ' => 'ὬΙ', + 'ᾥ' => 'ὭΙ', + 'ᾦ' => 'ὮΙ', + 'ᾧ' => 'ὯΙ', + 'ᾰ' => 'Ᾰ', + 'ᾱ' => 'Ᾱ', + 'ᾳ' => 'ΑΙ', + 'ι' => 'Ι', + 'ῃ' => 'ΗΙ', + 'ῐ' => 'Ῐ', + 'ῑ' => 'Ῑ', + 'ῠ' => 'Ῠ', + 'ῡ' => 'Ῡ', + 'ῥ' => 'Ῥ', + 'ῳ' => 'ΩΙ', + 'ⅎ' => 'Ⅎ', + 'ⅰ' => 'Ⅰ', + 'ⅱ' => 'Ⅱ', + 'ⅲ' => 'Ⅲ', + 'ⅳ' => 'Ⅳ', + 'ⅴ' => 'Ⅴ', + 'ⅵ' => 'Ⅵ', + 'ⅶ' => 'Ⅶ', + 'ⅷ' => 'Ⅷ', + 'ⅸ' => 'Ⅸ', + 'ⅹ' => 'Ⅹ', + 'ⅺ' => 'Ⅺ', + 'ⅻ' => 'Ⅻ', + 'ⅼ' => 'Ⅼ', + 'ⅽ' => 'Ⅽ', + 'ⅾ' => 'Ⅾ', + 'ⅿ' => 'Ⅿ', + 'ↄ' => 'Ↄ', + 'ⓐ' => 'Ⓐ', + 'ⓑ' => 'Ⓑ', + 'ⓒ' => 'Ⓒ', + 'ⓓ' => 'Ⓓ', + 'ⓔ' => 'Ⓔ', + 'ⓕ' => 'Ⓕ', + 'ⓖ' => 'Ⓖ', + 'ⓗ' => 'Ⓗ', + 'ⓘ' => 'Ⓘ', + 'ⓙ' => 'Ⓙ', + 'ⓚ' => 'Ⓚ', + 'ⓛ' => 'Ⓛ', + 'ⓜ' => 'Ⓜ', + 'ⓝ' => 'Ⓝ', + 'ⓞ' => 'Ⓞ', + 'ⓟ' => 'Ⓟ', + 'ⓠ' => 'Ⓠ', + 'ⓡ' => 'Ⓡ', + 'ⓢ' => 'Ⓢ', + 'ⓣ' => 'Ⓣ', + 'ⓤ' => 'Ⓤ', + 'ⓥ' => 'Ⓥ', + 'ⓦ' => 'Ⓦ', + 'ⓧ' => 'Ⓧ', + 'ⓨ' => 'Ⓨ', + 'ⓩ' => 'Ⓩ', + 'ⰰ' => 'Ⰰ', + 'ⰱ' => 'Ⰱ', + 'ⰲ' => 'Ⰲ', + 'ⰳ' => 'Ⰳ', + 'ⰴ' => 'Ⰴ', + 'ⰵ' => 'Ⰵ', + 'ⰶ' => 'Ⰶ', + 'ⰷ' => 'Ⰷ', + 'ⰸ' => 'Ⰸ', + 'ⰹ' => 'Ⰹ', + 'ⰺ' => 'Ⰺ', + 'ⰻ' => 'Ⰻ', + 'ⰼ' => 'Ⰼ', + 'ⰽ' => 'Ⰽ', + 'ⰾ' => 'Ⰾ', + 'ⰿ' => 'Ⰿ', + 'ⱀ' => 'Ⱀ', + 'ⱁ' => 'Ⱁ', + 'ⱂ' => 'Ⱂ', + 'ⱃ' => 'Ⱃ', + 'ⱄ' => 'Ⱄ', + 'ⱅ' => 'Ⱅ', + 'ⱆ' => 'Ⱆ', + 'ⱇ' => 'Ⱇ', + 'ⱈ' => 'Ⱈ', + 'ⱉ' => 'Ⱉ', + 'ⱊ' => 'Ⱊ', + 'ⱋ' => 'Ⱋ', + 'ⱌ' => 'Ⱌ', + 'ⱍ' => 'Ⱍ', + 'ⱎ' => 'Ⱎ', + 'ⱏ' => 'Ⱏ', + 'ⱐ' => 'Ⱐ', + 'ⱑ' => 'Ⱑ', + 'ⱒ' => 'Ⱒ', + 'ⱓ' => 'Ⱓ', + 'ⱔ' => 'Ⱔ', + 'ⱕ' => 'Ⱕ', + 'ⱖ' => 'Ⱖ', + 'ⱗ' => 'Ⱗ', + 'ⱘ' => 'Ⱘ', + 'ⱙ' => 'Ⱙ', + 'ⱚ' => 'Ⱚ', + 'ⱛ' => 'Ⱛ', + 'ⱜ' => 'Ⱜ', + 'ⱝ' => 'Ⱝ', + 'ⱞ' => 'Ⱞ', + 'ⱡ' => 'Ⱡ', + 'ⱥ' => 'Ⱥ', + 'ⱦ' => 'Ⱦ', + 'ⱨ' => 'Ⱨ', + 'ⱪ' => 'Ⱪ', + 'ⱬ' => 'Ⱬ', + 'ⱳ' => 'Ⱳ', + 'ⱶ' => 'Ⱶ', + 'ⲁ' => 'Ⲁ', + 'ⲃ' => 'Ⲃ', + 'ⲅ' => 'Ⲅ', + 'ⲇ' => 'Ⲇ', + 'ⲉ' => 'Ⲉ', + 'ⲋ' => 'Ⲋ', + 'ⲍ' => 'Ⲍ', + 'ⲏ' => 'Ⲏ', + 'ⲑ' => 'Ⲑ', + 'ⲓ' => 'Ⲓ', + 'ⲕ' => 'Ⲕ', + 'ⲗ' => 'Ⲗ', + 'ⲙ' => 'Ⲙ', + 'ⲛ' => 'Ⲛ', + 'ⲝ' => 'Ⲝ', + 'ⲟ' => 'Ⲟ', + 'ⲡ' => 'Ⲡ', + 'ⲣ' => 'Ⲣ', + 'ⲥ' => 'Ⲥ', + 'ⲧ' => 'Ⲧ', + 'ⲩ' => 'Ⲩ', + 'ⲫ' => 'Ⲫ', + 'ⲭ' => 'Ⲭ', + 'ⲯ' => 'Ⲯ', + 'ⲱ' => 'Ⲱ', + 'ⲳ' => 'Ⲳ', + 'ⲵ' => 'Ⲵ', + 'ⲷ' => 'Ⲷ', + 'ⲹ' => 'Ⲹ', + 'ⲻ' => 'Ⲻ', + 'ⲽ' => 'Ⲽ', + 'ⲿ' => 'Ⲿ', + 'ⳁ' => 'Ⳁ', + 'ⳃ' => 'Ⳃ', + 'ⳅ' => 'Ⳅ', + 'ⳇ' => 'Ⳇ', + 'ⳉ' => 'Ⳉ', + 'ⳋ' => 'Ⳋ', + 'ⳍ' => 'Ⳍ', + 'ⳏ' => 'Ⳏ', + 'ⳑ' => 'Ⳑ', + 'ⳓ' => 'Ⳓ', + 'ⳕ' => 'Ⳕ', + 'ⳗ' => 'Ⳗ', + 'ⳙ' => 'Ⳙ', + 'ⳛ' => 'Ⳛ', + 'ⳝ' => 'Ⳝ', + 'ⳟ' => 'Ⳟ', + 'ⳡ' => 'Ⳡ', + 'ⳣ' => 'Ⳣ', + 'ⳬ' => 'Ⳬ', + 'ⳮ' => 'Ⳮ', + 'ⳳ' => 'Ⳳ', + 'ⴀ' => 'Ⴀ', + 'ⴁ' => 'Ⴁ', + 'ⴂ' => 'Ⴂ', + 'ⴃ' => 'Ⴃ', + 'ⴄ' => 'Ⴄ', + 'ⴅ' => 'Ⴅ', + 'ⴆ' => 'Ⴆ', + 'ⴇ' => 'Ⴇ', + 'ⴈ' => 'Ⴈ', + 'ⴉ' => 'Ⴉ', + 'ⴊ' => 'Ⴊ', + 'ⴋ' => 'Ⴋ', + 'ⴌ' => 'Ⴌ', + 'ⴍ' => 'Ⴍ', + 'ⴎ' => 'Ⴎ', + 'ⴏ' => 'Ⴏ', + 'ⴐ' => 'Ⴐ', + 'ⴑ' => 'Ⴑ', + 'ⴒ' => 'Ⴒ', + 'ⴓ' => 'Ⴓ', + 'ⴔ' => 'Ⴔ', + 'ⴕ' => 'Ⴕ', + 'ⴖ' => 'Ⴖ', + 'ⴗ' => 'Ⴗ', + 'ⴘ' => 'Ⴘ', + 'ⴙ' => 'Ⴙ', + 'ⴚ' => 'Ⴚ', + 'ⴛ' => 'Ⴛ', + 'ⴜ' => 'Ⴜ', + 'ⴝ' => 'Ⴝ', + 'ⴞ' => 'Ⴞ', + 'ⴟ' => 'Ⴟ', + 'ⴠ' => 'Ⴠ', + 'ⴡ' => 'Ⴡ', + 'ⴢ' => 'Ⴢ', + 'ⴣ' => 'Ⴣ', + 'ⴤ' => 'Ⴤ', + 'ⴥ' => 'Ⴥ', + 'ⴧ' => 'Ⴧ', + 'ⴭ' => 'Ⴭ', + 'ꙁ' => 'Ꙁ', + 'ꙃ' => 'Ꙃ', + 'ꙅ' => 'Ꙅ', + 'ꙇ' => 'Ꙇ', + 'ꙉ' => 'Ꙉ', + 'ꙋ' => 'Ꙋ', + 'ꙍ' => 'Ꙍ', + 'ꙏ' => 'Ꙏ', + 'ꙑ' => 'Ꙑ', + 'ꙓ' => 'Ꙓ', + 'ꙕ' => 'Ꙕ', + 'ꙗ' => 'Ꙗ', + 'ꙙ' => 'Ꙙ', + 'ꙛ' => 'Ꙛ', + 'ꙝ' => 'Ꙝ', + 'ꙟ' => 'Ꙟ', + 'ꙡ' => 'Ꙡ', + 'ꙣ' => 'Ꙣ', + 'ꙥ' => 'Ꙥ', + 'ꙧ' => 'Ꙧ', + 'ꙩ' => 'Ꙩ', + 'ꙫ' => 'Ꙫ', + 'ꙭ' => 'Ꙭ', + 'ꚁ' => 'Ꚁ', + 'ꚃ' => 'Ꚃ', + 'ꚅ' => 'Ꚅ', + 'ꚇ' => 'Ꚇ', + 'ꚉ' => 'Ꚉ', + 'ꚋ' => 'Ꚋ', + 'ꚍ' => 'Ꚍ', + 'ꚏ' => 'Ꚏ', + 'ꚑ' => 'Ꚑ', + 'ꚓ' => 'Ꚓ', + 'ꚕ' => 'Ꚕ', + 'ꚗ' => 'Ꚗ', + 'ꚙ' => 'Ꚙ', + 'ꚛ' => 'Ꚛ', + 'ꜣ' => 'Ꜣ', + 'ꜥ' => 'Ꜥ', + 'ꜧ' => 'Ꜧ', + 'ꜩ' => 'Ꜩ', + 'ꜫ' => 'Ꜫ', + 'ꜭ' => 'Ꜭ', + 'ꜯ' => 'Ꜯ', + 'ꜳ' => 'Ꜳ', + 'ꜵ' => 'Ꜵ', + 'ꜷ' => 'Ꜷ', + 'ꜹ' => 'Ꜹ', + 'ꜻ' => 'Ꜻ', + 'ꜽ' => 'Ꜽ', + 'ꜿ' => 'Ꜿ', + 'ꝁ' => 'Ꝁ', + 'ꝃ' => 'Ꝃ', + 'ꝅ' => 'Ꝅ', + 'ꝇ' => 'Ꝇ', + 'ꝉ' => 'Ꝉ', + 'ꝋ' => 'Ꝋ', + 'ꝍ' => 'Ꝍ', + 'ꝏ' => 'Ꝏ', + 'ꝑ' => 'Ꝑ', + 'ꝓ' => 'Ꝓ', + 'ꝕ' => 'Ꝕ', + 'ꝗ' => 'Ꝗ', + 'ꝙ' => 'Ꝙ', + 'ꝛ' => 'Ꝛ', + 'ꝝ' => 'Ꝝ', + 'ꝟ' => 'Ꝟ', + 'ꝡ' => 'Ꝡ', + 'ꝣ' => 'Ꝣ', + 'ꝥ' => 'Ꝥ', + 'ꝧ' => 'Ꝧ', + 'ꝩ' => 'Ꝩ', + 'ꝫ' => 'Ꝫ', + 'ꝭ' => 'Ꝭ', + 'ꝯ' => 'Ꝯ', + 'ꝺ' => 'Ꝺ', + 'ꝼ' => 'Ꝼ', + 'ꝿ' => 'Ꝿ', + 'ꞁ' => 'Ꞁ', + 'ꞃ' => 'Ꞃ', + 'ꞅ' => 'Ꞅ', + 'ꞇ' => 'Ꞇ', + 'ꞌ' => 'Ꞌ', + 'ꞑ' => 'Ꞑ', + 'ꞓ' => 'Ꞓ', + 'ꞔ' => 'Ꞔ', + 'ꞗ' => 'Ꞗ', + 'ꞙ' => 'Ꞙ', + 'ꞛ' => 'Ꞛ', + 'ꞝ' => 'Ꞝ', + 'ꞟ' => 'Ꞟ', + 'ꞡ' => 'Ꞡ', + 'ꞣ' => 'Ꞣ', + 'ꞥ' => 'Ꞥ', + 'ꞧ' => 'Ꞧ', + 'ꞩ' => 'Ꞩ', + 'ꞵ' => 'Ꞵ', + 'ꞷ' => 'Ꞷ', + 'ꞹ' => 'Ꞹ', + 'ꞻ' => 'Ꞻ', + 'ꞽ' => 'Ꞽ', + 'ꞿ' => 'Ꞿ', + 'ꟃ' => 'Ꟃ', + 'ꟈ' => 'Ꟈ', + 'ꟊ' => 'Ꟊ', + 'ꟶ' => 'Ꟶ', + 'ꭓ' => 'Ꭓ', + 'ꭰ' => 'Ꭰ', + 'ꭱ' => 'Ꭱ', + 'ꭲ' => 'Ꭲ', + 'ꭳ' => 'Ꭳ', + 'ꭴ' => 'Ꭴ', + 'ꭵ' => 'Ꭵ', + 'ꭶ' => 'Ꭶ', + 'ꭷ' => 'Ꭷ', + 'ꭸ' => 'Ꭸ', + 'ꭹ' => 'Ꭹ', + 'ꭺ' => 'Ꭺ', + 'ꭻ' => 'Ꭻ', + 'ꭼ' => 'Ꭼ', + 'ꭽ' => 'Ꭽ', + 'ꭾ' => 'Ꭾ', + 'ꭿ' => 'Ꭿ', + 'ꮀ' => 'Ꮀ', + 'ꮁ' => 'Ꮁ', + 'ꮂ' => 'Ꮂ', + 'ꮃ' => 'Ꮃ', + 'ꮄ' => 'Ꮄ', + 'ꮅ' => 'Ꮅ', + 'ꮆ' => 'Ꮆ', + 'ꮇ' => 'Ꮇ', + 'ꮈ' => 'Ꮈ', + 'ꮉ' => 'Ꮉ', + 'ꮊ' => 'Ꮊ', + 'ꮋ' => 'Ꮋ', + 'ꮌ' => 'Ꮌ', + 'ꮍ' => 'Ꮍ', + 'ꮎ' => 'Ꮎ', + 'ꮏ' => 'Ꮏ', + 'ꮐ' => 'Ꮐ', + 'ꮑ' => 'Ꮑ', + 'ꮒ' => 'Ꮒ', + 'ꮓ' => 'Ꮓ', + 'ꮔ' => 'Ꮔ', + 'ꮕ' => 'Ꮕ', + 'ꮖ' => 'Ꮖ', + 'ꮗ' => 'Ꮗ', + 'ꮘ' => 'Ꮘ', + 'ꮙ' => 'Ꮙ', + 'ꮚ' => 'Ꮚ', + 'ꮛ' => 'Ꮛ', + 'ꮜ' => 'Ꮜ', + 'ꮝ' => 'Ꮝ', + 'ꮞ' => 'Ꮞ', + 'ꮟ' => 'Ꮟ', + 'ꮠ' => 'Ꮠ', + 'ꮡ' => 'Ꮡ', + 'ꮢ' => 'Ꮢ', + 'ꮣ' => 'Ꮣ', + 'ꮤ' => 'Ꮤ', + 'ꮥ' => 'Ꮥ', + 'ꮦ' => 'Ꮦ', + 'ꮧ' => 'Ꮧ', + 'ꮨ' => 'Ꮨ', + 'ꮩ' => 'Ꮩ', + 'ꮪ' => 'Ꮪ', + 'ꮫ' => 'Ꮫ', + 'ꮬ' => 'Ꮬ', + 'ꮭ' => 'Ꮭ', + 'ꮮ' => 'Ꮮ', + 'ꮯ' => 'Ꮯ', + 'ꮰ' => 'Ꮰ', + 'ꮱ' => 'Ꮱ', + 'ꮲ' => 'Ꮲ', + 'ꮳ' => 'Ꮳ', + 'ꮴ' => 'Ꮴ', + 'ꮵ' => 'Ꮵ', + 'ꮶ' => 'Ꮶ', + 'ꮷ' => 'Ꮷ', + 'ꮸ' => 'Ꮸ', + 'ꮹ' => 'Ꮹ', + 'ꮺ' => 'Ꮺ', + 'ꮻ' => 'Ꮻ', + 'ꮼ' => 'Ꮼ', + 'ꮽ' => 'Ꮽ', + 'ꮾ' => 'Ꮾ', + 'ꮿ' => 'Ꮿ', + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', + 'f' => 'F', + 'g' => 'G', + 'h' => 'H', + 'i' => 'I', + 'j' => 'J', + 'k' => 'K', + 'l' => 'L', + 'm' => 'M', + 'n' => 'N', + 'o' => 'O', + 'p' => 'P', + 'q' => 'Q', + 'r' => 'R', + 's' => 'S', + 't' => 'T', + 'u' => 'U', + 'v' => 'V', + 'w' => 'W', + 'x' => 'X', + 'y' => 'Y', + 'z' => 'Z', + '𐐨' => '𐐀', + '𐐩' => '𐐁', + '𐐪' => '𐐂', + '𐐫' => '𐐃', + '𐐬' => '𐐄', + '𐐭' => '𐐅', + '𐐮' => '𐐆', + '𐐯' => '𐐇', + '𐐰' => '𐐈', + '𐐱' => '𐐉', + '𐐲' => '𐐊', + '𐐳' => '𐐋', + '𐐴' => '𐐌', + '𐐵' => '𐐍', + '𐐶' => '𐐎', + '𐐷' => '𐐏', + '𐐸' => '𐐐', + '𐐹' => '𐐑', + '𐐺' => '𐐒', + '𐐻' => '𐐓', + '𐐼' => '𐐔', + '𐐽' => '𐐕', + '𐐾' => '𐐖', + '𐐿' => '𐐗', + '𐑀' => '𐐘', + '𐑁' => '𐐙', + '𐑂' => '𐐚', + '𐑃' => '𐐛', + '𐑄' => '𐐜', + '𐑅' => '𐐝', + '𐑆' => '𐐞', + '𐑇' => '𐐟', + '𐑈' => '𐐠', + '𐑉' => '𐐡', + '𐑊' => '𐐢', + '𐑋' => '𐐣', + '𐑌' => '𐐤', + '𐑍' => '𐐥', + '𐑎' => '𐐦', + '𐑏' => '𐐧', + '𐓘' => '𐒰', + '𐓙' => '𐒱', + '𐓚' => '𐒲', + '𐓛' => '𐒳', + '𐓜' => '𐒴', + '𐓝' => '𐒵', + '𐓞' => '𐒶', + '𐓟' => '𐒷', + '𐓠' => '𐒸', + '𐓡' => '𐒹', + '𐓢' => '𐒺', + '𐓣' => '𐒻', + '𐓤' => '𐒼', + '𐓥' => '𐒽', + '𐓦' => '𐒾', + '𐓧' => '𐒿', + '𐓨' => '𐓀', + '𐓩' => '𐓁', + '𐓪' => '𐓂', + '𐓫' => '𐓃', + '𐓬' => '𐓄', + '𐓭' => '𐓅', + '𐓮' => '𐓆', + '𐓯' => '𐓇', + '𐓰' => '𐓈', + '𐓱' => '𐓉', + '𐓲' => '𐓊', + '𐓳' => '𐓋', + '𐓴' => '𐓌', + '𐓵' => '𐓍', + '𐓶' => '𐓎', + '𐓷' => '𐓏', + '𐓸' => '𐓐', + '𐓹' => '𐓑', + '𐓺' => '𐓒', + '𐓻' => '𐓓', + '𐳀' => '𐲀', + '𐳁' => '𐲁', + '𐳂' => '𐲂', + '𐳃' => '𐲃', + '𐳄' => '𐲄', + '𐳅' => '𐲅', + '𐳆' => '𐲆', + '𐳇' => '𐲇', + '𐳈' => '𐲈', + '𐳉' => '𐲉', + '𐳊' => '𐲊', + '𐳋' => '𐲋', + '𐳌' => '𐲌', + '𐳍' => '𐲍', + '𐳎' => '𐲎', + '𐳏' => '𐲏', + '𐳐' => '𐲐', + '𐳑' => '𐲑', + '𐳒' => '𐲒', + '𐳓' => '𐲓', + '𐳔' => '𐲔', + '𐳕' => '𐲕', + '𐳖' => '𐲖', + '𐳗' => '𐲗', + '𐳘' => '𐲘', + '𐳙' => '𐲙', + '𐳚' => '𐲚', + '𐳛' => '𐲛', + '𐳜' => '𐲜', + '𐳝' => '𐲝', + '𐳞' => '𐲞', + '𐳟' => '𐲟', + '𐳠' => '𐲠', + '𐳡' => '𐲡', + '𐳢' => '𐲢', + '𐳣' => '𐲣', + '𐳤' => '𐲤', + '𐳥' => '𐲥', + '𐳦' => '𐲦', + '𐳧' => '𐲧', + '𐳨' => '𐲨', + '𐳩' => '𐲩', + '𐳪' => '𐲪', + '𐳫' => '𐲫', + '𐳬' => '𐲬', + '𐳭' => '𐲭', + '𐳮' => '𐲮', + '𐳯' => '𐲯', + '𐳰' => '𐲰', + '𐳱' => '𐲱', + '𐳲' => '𐲲', + '𑣀' => '𑢠', + '𑣁' => '𑢡', + '𑣂' => '𑢢', + '𑣃' => '𑢣', + '𑣄' => '𑢤', + '𑣅' => '𑢥', + '𑣆' => '𑢦', + '𑣇' => '𑢧', + '𑣈' => '𑢨', + '𑣉' => '𑢩', + '𑣊' => '𑢪', + '𑣋' => '𑢫', + '𑣌' => '𑢬', + '𑣍' => '𑢭', + '𑣎' => '𑢮', + '𑣏' => '𑢯', + '𑣐' => '𑢰', + '𑣑' => '𑢱', + '𑣒' => '𑢲', + '𑣓' => '𑢳', + '𑣔' => '𑢴', + '𑣕' => '𑢵', + '𑣖' => '𑢶', + '𑣗' => '𑢷', + '𑣘' => '𑢸', + '𑣙' => '𑢹', + '𑣚' => '𑢺', + '𑣛' => '𑢻', + '𑣜' => '𑢼', + '𑣝' => '𑢽', + '𑣞' => '𑢾', + '𑣟' => '𑢿', + '𖹠' => '𖹀', + '𖹡' => '𖹁', + '𖹢' => '𖹂', + '𖹣' => '𖹃', + '𖹤' => '𖹄', + '𖹥' => '𖹅', + '𖹦' => '𖹆', + '𖹧' => '𖹇', + '𖹨' => '𖹈', + '𖹩' => '𖹉', + '𖹪' => '𖹊', + '𖹫' => '𖹋', + '𖹬' => '𖹌', + '𖹭' => '𖹍', + '𖹮' => '𖹎', + '𖹯' => '𖹏', + '𖹰' => '𖹐', + '𖹱' => '𖹑', + '𖹲' => '𖹒', + '𖹳' => '𖹓', + '𖹴' => '𖹔', + '𖹵' => '𖹕', + '𖹶' => '𖹖', + '𖹷' => '𖹗', + '𖹸' => '𖹘', + '𖹹' => '𖹙', + '𖹺' => '𖹚', + '𖹻' => '𖹛', + '𖹼' => '𖹜', + '𖹽' => '𖹝', + '𖹾' => '𖹞', + '𖹿' => '𖹟', + '𞤢' => '𞤀', + '𞤣' => '𞤁', + '𞤤' => '𞤂', + '𞤥' => '𞤃', + '𞤦' => '𞤄', + '𞤧' => '𞤅', + '𞤨' => '𞤆', + '𞤩' => '𞤇', + '𞤪' => '𞤈', + '𞤫' => '𞤉', + '𞤬' => '𞤊', + '𞤭' => '𞤋', + '𞤮' => '𞤌', + '𞤯' => '𞤍', + '𞤰' => '𞤎', + '𞤱' => '𞤏', + '𞤲' => '𞤐', + '𞤳' => '𞤑', + '𞤴' => '𞤒', + '𞤵' => '𞤓', + '𞤶' => '𞤔', + '𞤷' => '𞤕', + '𞤸' => '𞤖', + '𞤹' => '𞤗', + '𞤺' => '𞤘', + '𞤻' => '𞤙', + '𞤼' => '𞤚', + '𞤽' => '𞤛', + '𞤾' => '𞤜', + '𞤿' => '𞤝', + '𞥀' => '𞤞', + '𞥁' => '𞤟', + '𞥂' => '𞤠', + '𞥃' => '𞤡', + 'ß' => 'SS', + 'ff' => 'FF', + 'fi' => 'FI', + 'fl' => 'FL', + 'ffi' => 'FFI', + 'ffl' => 'FFL', + 'ſt' => 'ST', + 'st' => 'ST', + 'և' => 'ԵՒ', + 'ﬓ' => 'ՄՆ', + 'ﬔ' => 'ՄԵ', + 'ﬕ' => 'ՄԻ', + 'ﬖ' => 'ՎՆ', + 'ﬗ' => 'ՄԽ', + 'ʼn' => 'ʼN', + 'ΐ' => 'Ϊ́', + 'ΰ' => 'Ϋ́', + 'ǰ' => 'J̌', + 'ẖ' => 'H̱', + 'ẗ' => 'T̈', + 'ẘ' => 'W̊', + 'ẙ' => 'Y̊', + 'ẚ' => 'Aʾ', + 'ὐ' => 'Υ̓', + 'ὒ' => 'Υ̓̀', + 'ὔ' => 'Υ̓́', + 'ὖ' => 'Υ̓͂', + 'ᾶ' => 'Α͂', + 'ῆ' => 'Η͂', + 'ῒ' => 'Ϊ̀', + 'ΐ' => 'Ϊ́', + 'ῖ' => 'Ι͂', + 'ῗ' => 'Ϊ͂', + 'ῢ' => 'Ϋ̀', + 'ΰ' => 'Ϋ́', + 'ῤ' => 'Ρ̓', + 'ῦ' => 'Υ͂', + 'ῧ' => 'Ϋ͂', + 'ῶ' => 'Ω͂', + 'ᾈ' => 'ἈΙ', + 'ᾉ' => 'ἉΙ', + 'ᾊ' => 'ἊΙ', + 'ᾋ' => 'ἋΙ', + 'ᾌ' => 'ἌΙ', + 'ᾍ' => 'ἍΙ', + 'ᾎ' => 'ἎΙ', + 'ᾏ' => 'ἏΙ', + 'ᾘ' => 'ἨΙ', + 'ᾙ' => 'ἩΙ', + 'ᾚ' => 'ἪΙ', + 'ᾛ' => 'ἫΙ', + 'ᾜ' => 'ἬΙ', + 'ᾝ' => 'ἭΙ', + 'ᾞ' => 'ἮΙ', + 'ᾟ' => 'ἯΙ', + 'ᾨ' => 'ὨΙ', + 'ᾩ' => 'ὩΙ', + 'ᾪ' => 'ὪΙ', + 'ᾫ' => 'ὫΙ', + 'ᾬ' => 'ὬΙ', + 'ᾭ' => 'ὭΙ', + 'ᾮ' => 'ὮΙ', + 'ᾯ' => 'ὯΙ', + 'ᾼ' => 'ΑΙ', + 'ῌ' => 'ΗΙ', + 'ῼ' => 'ΩΙ', + 'ᾲ' => 'ᾺΙ', + 'ᾴ' => 'ΆΙ', + 'ῂ' => 'ῊΙ', + 'ῄ' => 'ΉΙ', + 'ῲ' => 'ῺΙ', + 'ῴ' => 'ΏΙ', + 'ᾷ' => 'Α͂Ι', + 'ῇ' => 'Η͂Ι', + 'ῷ' => 'Ω͂Ι', +); diff --git a/vendor/symfony/polyfill-mbstring/bootstrap.php b/vendor/symfony/polyfill-mbstring/bootstrap.php new file mode 100644 index 0000000..0e934d7 --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/bootstrap.php @@ -0,0 +1,16 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +return require __DIR__.'/bootstrap72.php'; diff --git a/vendor/symfony/polyfill-mbstring/bootstrap72.php b/vendor/symfony/polyfill-mbstring/bootstrap72.php new file mode 100644 index 0000000..2e3a06d --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/bootstrap72.php @@ -0,0 +1,173 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Mbstring as p; + +if (!function_exists('mb_convert_encoding')) { + function mb_convert_encoding($string, $to_encoding, $from_encoding = null) { return p\Mbstring::mb_convert_encoding($string, $to_encoding, $from_encoding); } +} +if (!function_exists('mb_decode_mimeheader')) { + function mb_decode_mimeheader($string) { return p\Mbstring::mb_decode_mimeheader($string); } +} +if (!function_exists('mb_encode_mimeheader')) { + function mb_encode_mimeheader($string, $charset = null, $transfer_encoding = null, $newline = "\r\n", $indent = 0) { return p\Mbstring::mb_encode_mimeheader($string, $charset, $transfer_encoding, $newline, $indent); } +} +if (!function_exists('mb_decode_numericentity')) { + function mb_decode_numericentity($string, $map, $encoding = null) { return p\Mbstring::mb_decode_numericentity($string, $map, $encoding); } +} +if (!function_exists('mb_encode_numericentity')) { + function mb_encode_numericentity($string, $map, $encoding = null, $hex = false) { return p\Mbstring::mb_encode_numericentity($string, $map, $encoding, $hex); } +} +if (!function_exists('mb_convert_case')) { + function mb_convert_case($string, $mode, $encoding = null) { return p\Mbstring::mb_convert_case($string, $mode, $encoding); } +} +if (!function_exists('mb_internal_encoding')) { + function mb_internal_encoding($encoding = null) { return p\Mbstring::mb_internal_encoding($encoding); } +} +if (!function_exists('mb_language')) { + function mb_language($language = null) { return p\Mbstring::mb_language($language); } +} +if (!function_exists('mb_list_encodings')) { + function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); } +} +if (!function_exists('mb_encoding_aliases')) { + function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); } +} +if (!function_exists('mb_check_encoding')) { + function mb_check_encoding($value = null, $encoding = null) { return p\Mbstring::mb_check_encoding($value, $encoding); } +} +if (!function_exists('mb_detect_encoding')) { + function mb_detect_encoding($string, $encodings = null, $strict = false) { return p\Mbstring::mb_detect_encoding($string, $encodings, $strict); } +} +if (!function_exists('mb_detect_order')) { + function mb_detect_order($encoding = null) { return p\Mbstring::mb_detect_order($encoding); } +} +if (!function_exists('mb_parse_str')) { + function mb_parse_str($string, &$result = []) { parse_str($string, $result); return (bool) $result; } +} +if (!function_exists('mb_strlen')) { + function mb_strlen($string, $encoding = null) { return p\Mbstring::mb_strlen($string, $encoding); } +} +if (!function_exists('mb_strpos')) { + function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strpos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strtolower')) { + function mb_strtolower($string, $encoding = null) { return p\Mbstring::mb_strtolower($string, $encoding); } +} +if (!function_exists('mb_strtoupper')) { + function mb_strtoupper($string, $encoding = null) { return p\Mbstring::mb_strtoupper($string, $encoding); } +} +if (!function_exists('mb_substitute_character')) { + function mb_substitute_character($substitute_character = null) { return p\Mbstring::mb_substitute_character($substitute_character); } +} +if (!function_exists('mb_substr')) { + function mb_substr($string, $start, $length = 2147483647, $encoding = null) { return p\Mbstring::mb_substr($string, $start, $length, $encoding); } +} +if (!function_exists('mb_stripos')) { + function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_stripos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_stristr')) { + function mb_stristr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_stristr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strrchr')) { + function mb_strrchr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrchr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strrichr')) { + function mb_strrichr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrichr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strripos')) { + function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strripos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strrpos')) { + function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strrpos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strstr')) { + function mb_strstr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strstr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_get_info')) { + function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); } +} +if (!function_exists('mb_http_output')) { + function mb_http_output($encoding = null) { return p\Mbstring::mb_http_output($encoding); } +} +if (!function_exists('mb_strwidth')) { + function mb_strwidth($string, $encoding = null) { return p\Mbstring::mb_strwidth($string, $encoding); } +} +if (!function_exists('mb_substr_count')) { + function mb_substr_count($haystack, $needle, $encoding = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $encoding); } +} +if (!function_exists('mb_output_handler')) { + function mb_output_handler($string, $status) { return p\Mbstring::mb_output_handler($string, $status); } +} +if (!function_exists('mb_http_input')) { + function mb_http_input($type = null) { return p\Mbstring::mb_http_input($type); } +} + +if (!function_exists('mb_convert_variables')) { + function mb_convert_variables($to_encoding, $from_encoding, &...$vars) { return p\Mbstring::mb_convert_variables($to_encoding, $from_encoding, ...$vars); } +} + +if (!function_exists('mb_ord')) { + function mb_ord($string, $encoding = null) { return p\Mbstring::mb_ord($string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr($codepoint, $encoding = null) { return p\Mbstring::mb_chr($codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub($string, $encoding = null) { return p\Mbstring::mb_scrub($string, $encoding); } +} +if (!function_exists('mb_str_split')) { + function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); } +} + +if (!function_exists('mb_str_pad')) { + /** @return string|false */ + function mb_str_pad(?string $string, ?int $length, ?string $pad_string = ' ', ?int $pad_type = STR_PAD_RIGHT, ?string $encoding = null) { return p\Mbstring::mb_str_pad((string) $string, (int) $length, (string) $pad_string, (int) $pad_type, $encoding); } +} + +if (!function_exists('mb_ucfirst')) { + /** @return string|false */ + function mb_ucfirst(?string $string, ?string $encoding = null) { return p\Mbstring::mb_ucfirst((string) $string, $encoding); } +} + +if (!function_exists('mb_lcfirst')) { + /** @return string|false */ + function mb_lcfirst(?string $string, ?string $encoding = null) { return p\Mbstring::mb_lcfirst((string) $string, $encoding); } +} + +if (!function_exists('mb_trim')) { + /** @return string|false */ + function mb_trim(?string $string, ?string $characters = null, ?string $encoding = null) { return p\Mbstring::mb_trim((string) $string, $characters, $encoding); } +} + +if (!function_exists('mb_ltrim')) { + /** @return string|false */ + function mb_ltrim(?string $string, ?string $characters = null, ?string $encoding = null) { return p\Mbstring::mb_ltrim((string) $string, $characters, $encoding); } +} + +if (!function_exists('mb_rtrim')) { + /** @return string|false */ + function mb_rtrim(?string $string, ?string $characters = null, ?string $encoding = null) { return p\Mbstring::mb_rtrim((string) $string, $characters, $encoding); } +} + +if (extension_loaded('mbstring')) { + return; +} + +if (!defined('MB_CASE_UPPER')) { + define('MB_CASE_UPPER', 0); +} +if (!defined('MB_CASE_LOWER')) { + define('MB_CASE_LOWER', 1); +} +if (!defined('MB_CASE_TITLE')) { + define('MB_CASE_TITLE', 2); +} diff --git a/vendor/symfony/polyfill-mbstring/bootstrap80.php b/vendor/symfony/polyfill-mbstring/bootstrap80.php new file mode 100644 index 0000000..5fde10e --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/bootstrap80.php @@ -0,0 +1,167 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Mbstring as p; + +if (!function_exists('mb_convert_encoding')) { + function mb_convert_encoding(array|string|null $string, ?string $to_encoding, array|string|null $from_encoding = null): array|string|false { return p\Mbstring::mb_convert_encoding($string ?? '', (string) $to_encoding, $from_encoding); } +} +if (!function_exists('mb_decode_mimeheader')) { + function mb_decode_mimeheader(?string $string): string { return p\Mbstring::mb_decode_mimeheader((string) $string); } +} +if (!function_exists('mb_encode_mimeheader')) { + function mb_encode_mimeheader(?string $string, ?string $charset = null, ?string $transfer_encoding = null, ?string $newline = "\r\n", ?int $indent = 0): string { return p\Mbstring::mb_encode_mimeheader((string) $string, $charset, $transfer_encoding, (string) $newline, (int) $indent); } +} +if (!function_exists('mb_decode_numericentity')) { + function mb_decode_numericentity(?string $string, array $map, ?string $encoding = null): string { return p\Mbstring::mb_decode_numericentity((string) $string, $map, $encoding); } +} +if (!function_exists('mb_encode_numericentity')) { + function mb_encode_numericentity(?string $string, array $map, ?string $encoding = null, ?bool $hex = false): string { return p\Mbstring::mb_encode_numericentity((string) $string, $map, $encoding, (bool) $hex); } +} +if (!function_exists('mb_convert_case')) { + function mb_convert_case(?string $string, ?int $mode, ?string $encoding = null): string { return p\Mbstring::mb_convert_case((string) $string, (int) $mode, $encoding); } +} +if (!function_exists('mb_internal_encoding')) { + function mb_internal_encoding(?string $encoding = null): string|bool { return p\Mbstring::mb_internal_encoding($encoding); } +} +if (!function_exists('mb_language')) { + function mb_language(?string $language = null): string|bool { return p\Mbstring::mb_language($language); } +} +if (!function_exists('mb_list_encodings')) { + function mb_list_encodings(): array { return p\Mbstring::mb_list_encodings(); } +} +if (!function_exists('mb_encoding_aliases')) { + function mb_encoding_aliases(?string $encoding): array { return p\Mbstring::mb_encoding_aliases((string) $encoding); } +} +if (!function_exists('mb_check_encoding')) { + function mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool { return p\Mbstring::mb_check_encoding($value, $encoding); } +} +if (!function_exists('mb_detect_encoding')) { + function mb_detect_encoding(?string $string, array|string|null $encodings = null, ?bool $strict = false): string|false { return p\Mbstring::mb_detect_encoding((string) $string, $encodings, (bool) $strict); } +} +if (!function_exists('mb_detect_order')) { + function mb_detect_order(array|string|null $encoding = null): array|bool { return p\Mbstring::mb_detect_order($encoding); } +} +if (!function_exists('mb_parse_str')) { + function mb_parse_str(?string $string, &$result = []): bool { parse_str((string) $string, $result); return (bool) $result; } +} +if (!function_exists('mb_strlen')) { + function mb_strlen(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strlen((string) $string, $encoding); } +} +if (!function_exists('mb_strpos')) { + function mb_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strtolower')) { + function mb_strtolower(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtolower((string) $string, $encoding); } +} +if (!function_exists('mb_strtoupper')) { + function mb_strtoupper(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtoupper((string) $string, $encoding); } +} +if (!function_exists('mb_substitute_character')) { + function mb_substitute_character(string|int|null $substitute_character = null): string|int|bool { return p\Mbstring::mb_substitute_character($substitute_character); } +} +if (!function_exists('mb_substr')) { + function mb_substr(?string $string, ?int $start, ?int $length = null, ?string $encoding = null): string { return p\Mbstring::mb_substr((string) $string, (int) $start, $length, $encoding); } +} +if (!function_exists('mb_stripos')) { + function mb_stripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_stripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_stristr')) { + function mb_stristr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_stristr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strrchr')) { + function mb_strrchr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrchr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strrichr')) { + function mb_strrichr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrichr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strripos')) { + function mb_strripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strrpos')) { + function mb_strrpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strrpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strstr')) { + function mb_strstr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strstr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_get_info')) { + function mb_get_info(?string $type = 'all'): array|string|int|false|null { return p\Mbstring::mb_get_info((string) $type); } +} +if (!function_exists('mb_http_output')) { + function mb_http_output(?string $encoding = null): string|bool { return p\Mbstring::mb_http_output($encoding); } +} +if (!function_exists('mb_strwidth')) { + function mb_strwidth(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strwidth((string) $string, $encoding); } +} +if (!function_exists('mb_substr_count')) { + function mb_substr_count(?string $haystack, ?string $needle, ?string $encoding = null): int { return p\Mbstring::mb_substr_count((string) $haystack, (string) $needle, $encoding); } +} +if (!function_exists('mb_output_handler')) { + function mb_output_handler(?string $string, ?int $status): string { return p\Mbstring::mb_output_handler((string) $string, (int) $status); } +} +if (!function_exists('mb_http_input')) { + function mb_http_input(?string $type = null): array|string|false { return p\Mbstring::mb_http_input($type); } +} + +if (!function_exists('mb_convert_variables')) { + function mb_convert_variables(?string $to_encoding, array|string|null $from_encoding, mixed &$var, mixed &...$vars): string|false { return p\Mbstring::mb_convert_variables((string) $to_encoding, $from_encoding ?? '', $var, ...$vars); } +} + +if (!function_exists('mb_ord')) { + function mb_ord(?string $string, ?string $encoding = null): int|false { return p\Mbstring::mb_ord((string) $string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr(?int $codepoint, ?string $encoding = null): string|false { return p\Mbstring::mb_chr((int) $codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_scrub($string, $encoding); } +} +if (!function_exists('mb_str_split')) { + function mb_str_split(?string $string, ?int $length = 1, ?string $encoding = null): array { return p\Mbstring::mb_str_split((string) $string, (int) $length, $encoding); } +} + +if (!function_exists('mb_str_pad')) { + function mb_str_pad(?string $string, ?int $length, ?string $pad_string = ' ', ?int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad((string) $string, (int) $length, (string) $pad_string, (int) $pad_type, $encoding); } +} + +if (!function_exists('mb_ucfirst')) { + function mb_ucfirst(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_ucfirst((string) $string, $encoding); } +} + +if (!function_exists('mb_lcfirst')) { + function mb_lcfirst(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_lcfirst((string) $string, $encoding); } +} + +if (!function_exists('mb_trim')) { + function mb_trim(?string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_trim((string) $string, $characters, $encoding); } +} + +if (!function_exists('mb_ltrim')) { + function mb_ltrim(?string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_ltrim((string) $string, $characters, $encoding); } +} + +if (!function_exists('mb_rtrim')) { + function mb_rtrim(?string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_rtrim((string) $string, $characters, $encoding); } +} + +if (extension_loaded('mbstring')) { + return; +} + +if (!defined('MB_CASE_UPPER')) { + define('MB_CASE_UPPER', 0); +} +if (!defined('MB_CASE_LOWER')) { + define('MB_CASE_LOWER', 1); +} +if (!defined('MB_CASE_TITLE')) { + define('MB_CASE_TITLE', 2); +} diff --git a/vendor/symfony/polyfill-mbstring/composer.json b/vendor/symfony/polyfill-mbstring/composer.json new file mode 100644 index 0000000..daa07f8 --- /dev/null +++ b/vendor/symfony/polyfill-mbstring/composer.json @@ -0,0 +1,39 @@ +{ + "name": "symfony/polyfill-mbstring", + "type": "library", + "description": "Symfony polyfill for the Mbstring extension", + "keywords": ["polyfill", "shim", "compatibility", "portable", "mbstring"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2", + "ext-iconv": "*" + }, + "provide": { + "ext-mbstring": "*" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/vendor/symfony/polyfill-php80/LICENSE b/vendor/symfony/polyfill-php80/LICENSE new file mode 100644 index 0000000..0ed3a24 --- /dev/null +++ b/vendor/symfony/polyfill-php80/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-present 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 +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/symfony/polyfill-php80/Php80.php b/vendor/symfony/polyfill-php80/Php80.php new file mode 100644 index 0000000..68fac39 --- /dev/null +++ b/vendor/symfony/polyfill-php80/Php80.php @@ -0,0 +1,115 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Ion Bazan <ion.bazan@gmail.com> + * @author Nico Oelgart <nicoswd@gmail.com> + * @author Nicolas Grekas <p@tchwork.com> + * + * @internal + */ +final class Php80 +{ + public static function fdiv(float $dividend, float $divisor): float + { + return @($dividend / $divisor); + } + + public static function get_debug_type($value): string + { + switch (true) { + case null === $value: return 'null'; + case \is_bool($value): return 'bool'; + case \is_string($value): return 'string'; + case \is_array($value): return 'array'; + case \is_int($value): return 'int'; + case \is_float($value): return 'float'; + case \is_object($value): break; + case $value instanceof \__PHP_Incomplete_Class: return '__PHP_Incomplete_Class'; + default: + if (null === $type = @get_resource_type($value)) { + return 'unknown'; + } + + if ('Unknown' === $type) { + $type = 'closed'; + } + + return "resource ($type)"; + } + + $class = \get_class($value); + + if (false === strpos($class, '@')) { + return $class; + } + + return (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous'; + } + + public static function get_resource_id($res): int + { + if (!\is_resource($res) && null === @get_resource_type($res)) { + throw new \TypeError(\sprintf('Argument 1 passed to get_resource_id() must be of the type resource, %s given', get_debug_type($res))); + } + + return (int) $res; + } + + public static function preg_last_error_msg(): string + { + switch (preg_last_error()) { + case \PREG_INTERNAL_ERROR: + return 'Internal error'; + case \PREG_BAD_UTF8_ERROR: + return 'Malformed UTF-8 characters, possibly incorrectly encoded'; + case \PREG_BAD_UTF8_OFFSET_ERROR: + return 'The offset did not correspond to the beginning of a valid UTF-8 code point'; + case \PREG_BACKTRACK_LIMIT_ERROR: + return 'Backtrack limit exhausted'; + case \PREG_RECURSION_LIMIT_ERROR: + return 'Recursion limit exhausted'; + case \PREG_JIT_STACKLIMIT_ERROR: + return 'JIT stack limit exhausted'; + case \PREG_NO_ERROR: + return 'No error'; + default: + return 'Unknown error'; + } + } + + public static function str_contains(string $haystack, string $needle): bool + { + return '' === $needle || false !== strpos($haystack, $needle); + } + + public static function str_starts_with(string $haystack, string $needle): bool + { + return 0 === strncmp($haystack, $needle, \strlen($needle)); + } + + public static function str_ends_with(string $haystack, string $needle): bool + { + if ('' === $needle || $needle === $haystack) { + return true; + } + + if ('' === $haystack) { + return false; + } + + $needleLength = \strlen($needle); + + return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength); + } +} diff --git a/vendor/symfony/polyfill-php80/PhpToken.php b/vendor/symfony/polyfill-php80/PhpToken.php new file mode 100644 index 0000000..0f6b65e --- /dev/null +++ b/vendor/symfony/polyfill-php80/PhpToken.php @@ -0,0 +1,108 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Fedonyuk Anton <info@ensostudio.ru> + * + * @internal + */ +class PhpToken implements \Stringable +{ + /** + * @var int + */ + public $id; + + /** + * @var string + */ + public $text; + + /** + * @var -1|positive-int + */ + public $line; + + /** + * @var int + */ + public $pos; + + /** + * @param -1|positive-int $line + */ + public function __construct(int $id, string $text, int $line = -1, int $position = -1) + { + $this->id = $id; + $this->text = $text; + $this->line = $line; + $this->pos = $position; + } + + public function getTokenName(): ?string + { + if ($this->id < 256) { + return \chr($this->id & 0xFF); + } + + return 'UNKNOWN' === ($name = token_name($this->id)) ? null : $name; + } + + /** + * @param int|string|array $kind + */ + public function is($kind): bool + { + foreach ((array) $kind as $value) { + if (\in_array($value, [$this->id, $this->text], true)) { + return true; + } + } + + return false; + } + + public function isIgnorable(): bool + { + return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true); + } + + public function __toString(): string + { + return (string) $this->text; + } + + /** + * @return list<static> + */ + public static function tokenize(string $code, int $flags = 0): array + { + $line = 1; + $position = 0; + $tokens = token_get_all($code, $flags); + foreach ($tokens as $index => $token) { + if (\is_string($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; + } +} diff --git a/vendor/symfony/polyfill-php80/README.md b/vendor/symfony/polyfill-php80/README.md new file mode 100644 index 0000000..3816c55 --- /dev/null +++ b/vendor/symfony/polyfill-php80/README.md @@ -0,0 +1,25 @@ +Symfony Polyfill / Php80 +======================== + +This component provides features added to PHP 8.0 core: + +- [`Stringable`](https://php.net/stringable) interface +- [`fdiv`](https://php.net/fdiv) +- [`ValueError`](https://php.net/valueerror) class +- [`UnhandledMatchError`](https://php.net/unhandledmatcherror) class +- `FILTER_VALIDATE_BOOL` constant +- [`get_debug_type`](https://php.net/get_debug_type) +- [`PhpToken`](https://php.net/phptoken) class +- [`preg_last_error_msg`](https://php.net/preg_last_error_msg) +- [`str_contains`](https://php.net/str_contains) +- [`str_starts_with`](https://php.net/str_starts_with) +- [`str_ends_with`](https://php.net/str_ends_with) +- [`get_resource_id`](https://php.net/get_resource_id) + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php b/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php new file mode 100644 index 0000000..2b95542 --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php @@ -0,0 +1,31 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#[Attribute(Attribute::TARGET_CLASS)] +final class Attribute +{ + public const TARGET_CLASS = 1; + public const TARGET_FUNCTION = 2; + public const TARGET_METHOD = 4; + public const TARGET_PROPERTY = 8; + public const TARGET_CLASS_CONSTANT = 16; + public const TARGET_PARAMETER = 32; + public const TARGET_ALL = 63; + public const IS_REPEATABLE = 64; + + /** @var int */ + public $flags; + + public function __construct(int $flags = self::TARGET_ALL) + { + $this->flags = $flags; + } +} diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php b/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php new file mode 100644 index 0000000..bd1212f --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php @@ -0,0 +1,16 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000 && extension_loaded('tokenizer')) { + class PhpToken extends Symfony\Polyfill\Php80\PhpToken + { + } +} diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php b/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php new file mode 100644 index 0000000..7c62d75 --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php @@ -0,0 +1,20 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + interface Stringable + { + /** + * @return string + */ + public function __toString(); + } +} diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php b/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php new file mode 100644 index 0000000..01c6c6c --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php @@ -0,0 +1,16 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + class UnhandledMatchError extends Error + { + } +} diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php b/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php new file mode 100644 index 0000000..783dbc2 --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php @@ -0,0 +1,16 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + class ValueError extends Error + { + } +} diff --git a/vendor/symfony/polyfill-php80/bootstrap.php b/vendor/symfony/polyfill-php80/bootstrap.php new file mode 100644 index 0000000..e5f7dbc --- /dev/null +++ b/vendor/symfony/polyfill-php80/bootstrap.php @@ -0,0 +1,42 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php80 as p; + +if (\PHP_VERSION_ID >= 80000) { + return; +} + +if (!defined('FILTER_VALIDATE_BOOL') && defined('FILTER_VALIDATE_BOOLEAN')) { + define('FILTER_VALIDATE_BOOL', \FILTER_VALIDATE_BOOLEAN); +} + +if (!function_exists('fdiv')) { + function fdiv(float $num1, float $num2): float { return p\Php80::fdiv($num1, $num2); } +} +if (!function_exists('preg_last_error_msg')) { + function preg_last_error_msg(): string { return p\Php80::preg_last_error_msg(); } +} +if (!function_exists('str_contains')) { + function str_contains(?string $haystack, ?string $needle): bool { return p\Php80::str_contains($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('str_starts_with')) { + function str_starts_with(?string $haystack, ?string $needle): bool { return p\Php80::str_starts_with($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('str_ends_with')) { + function str_ends_with(?string $haystack, ?string $needle): bool { return p\Php80::str_ends_with($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('get_debug_type')) { + function get_debug_type($value): string { return p\Php80::get_debug_type($value); } +} +if (!function_exists('get_resource_id')) { + function get_resource_id($resource): int { return p\Php80::get_resource_id($resource); } +} diff --git a/vendor/symfony/polyfill-php80/composer.json b/vendor/symfony/polyfill-php80/composer.json new file mode 100644 index 0000000..a503b03 --- /dev/null +++ b/vendor/symfony/polyfill-php80/composer.json @@ -0,0 +1,37 @@ +{ + "name": "symfony/polyfill-php80", + "type": "library", + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "keywords": ["polyfill", "shim", "compatibility", "portable"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Php80\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/vendor/symfony/polyfill-php82/LICENSE b/vendor/symfony/polyfill-php82/LICENSE new file mode 100644 index 0000000..733c826 --- /dev/null +++ b/vendor/symfony/polyfill-php82/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2022-present 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 +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/symfony/polyfill-php82/NoDynamicProperties.php b/vendor/symfony/polyfill-php82/NoDynamicProperties.php new file mode 100644 index 0000000..450deff --- /dev/null +++ b/vendor/symfony/polyfill-php82/NoDynamicProperties.php @@ -0,0 +1,23 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php82; + +/** + * @internal + */ +trait NoDynamicProperties +{ + public function __set(string $name, $value): void + { + throw new \Error('Cannot create dynamic property '.self::class.'::$'.$name); + } +} diff --git a/vendor/symfony/polyfill-php82/Php82.php b/vendor/symfony/polyfill-php82/Php82.php new file mode 100644 index 0000000..774ab3a --- /dev/null +++ b/vendor/symfony/polyfill-php82/Php82.php @@ -0,0 +1,399 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php82; + +/** + * @author Alexander M. Turek <me@derrabus.de> + * @author Greg Roach <greg@subaqua.co.uk> + * + * @internal + */ +class Php82 +{ + /** + * Determines if a string matches the ODBC quoting rules. + * + * A valid quoted string begins with a '{', ends with a '}', and has no '}' + * inside of the string that aren't repeated (as to be escaped). + * + * These rules are what .NET also follows. + * + * @see https://github.com/php/php-src/blob/838f6bffff6363a204a2597cbfbaad1d7ee3f2b6/main/php_odbc_utils.c#L31-L57 + */ + public static function odbc_connection_string_is_quoted(string $str): bool + { + if ('' === $str || '{' !== $str[0]) { + return false; + } + + /* Check for } that aren't doubled up or at the end of the string */ + $length = \strlen($str) - 1; + for ($i = 0; $i < $length; ++$i) { + if ('}' !== $str[$i]) { + continue; + } + + if ('}' !== $str[++$i]) { + return false; + } + } + + return true; + } + + /** + * Determines if a value for a connection string should be quoted. + * + * The ODBC specification mentions: + * "Because of connection string and initialization file grammar, keywords and + * attribute values that contain the characters []{}(),;?*=!@ not enclosed + * with braces should be avoided." + * + * Note that it assumes that the string is *not* already quoted. You should + * check beforehand. + * + * @see https://github.com/php/php-src/blob/838f6bffff6363a204a2597cbfbaad1d7ee3f2b6/main/php_odbc_utils.c#L59-L73 + */ + public static function odbc_connection_string_should_quote(string $str): bool + { + return false !== strpbrk($str, '[]{}(),;?*=!@ '); + } + + public static function odbc_connection_string_quote(string $str): string + { + return '{'.str_replace('}', '}}', $str).'}'; + } + + /** + * Implementation closely based on the original C code - including the GOTOs + * and pointer-style string access. + * + * @see https://github.com/php/php-src/blob/master/Zend/zend_ini.c + */ + public static function ini_parse_quantity(string $value): int + { + // Avoid dependency on ctype_space() + $ctype_space = " \t\v\r\n\f"; + + $str = 0; + $str_end = \strlen($value); + $digits = $str; + $overflow = false; + + /* Ignore leading whitespace, but keep it for error messages. */ + while ($digits < $str_end && false !== strpos($ctype_space, $value[$digits])) { + ++$digits; + } + + /* Ignore trailing whitespace, but keep it for error messages. */ + while ($digits < $str_end && false !== strpos($ctype_space, $value[$str_end - 1])) { + --$str_end; + } + + if ($digits === $str_end) { + return 0; + } + + $is_negative = false; + + if ('+' === $value[$digits]) { + ++$digits; + } elseif ('-' === $value[$digits]) { + $is_negative = true; + ++$digits; + } + + if ($digits === $str_end || $value[$digits] < '0' || $value[$digits] > '9') { + $message = \sprintf( + 'Invalid quantity "%s": no valid leading digits, interpreting as "0" for backwards compatibility', + self::escapeString($value) + ); + + trigger_error($message, \E_USER_WARNING); + + return 0; + } + + $base = 10; + $allowed_digits = '0123456789'; + + if ('0' === $value[$digits] && ($digits + 1 === $str_end || false === strpos($allowed_digits, $value[$digits + 1]))) { + if ($digits + 1 === $str_end) { + return 0; + } + + switch ($value[$digits + 1]) { + case 'g': + case 'G': + case 'm': + case 'M': + case 'k': + case 'K': + goto evaluation; + case 'x': + case 'X': + $base = 16; + $allowed_digits = '0123456789abcdefABCDEF'; + break; + case 'o': + case 'O': + $base = 8; + $allowed_digits = '01234567'; + break; + case 'b': + case 'B': + $base = 2; + $allowed_digits = '01'; + break; + default: + $message = \sprintf( + 'Invalid prefix "0%s", interpreting as "0" for backwards compatibility', + $value[$digits + 1] + ); + trigger_error($message, \E_USER_WARNING); + + return 0; + } + + $digits += 2; + if ($digits === $str_end) { + $message = \sprintf( + 'Invalid quantity "%s": no digits after base prefix, interpreting as "0" for backwards compatibility', + self::escapeString($value) + ); + trigger_error($message, \E_USER_WARNING); + + return 0; + } + + $digits_consumed = $digits; + /* Ignore leading whitespace. */ + while ($digits_consumed < $str_end && false !== strpos($ctype_space, $value[$digits_consumed])) { + ++$digits_consumed; + } + if ($digits_consumed !== $str_end && ('+' === $value[$digits_consumed] || '-' === $value[$digits_consumed])) { + ++$digits_consumed; + } + + if ($digits_consumed + 1 < $str_end && '0' === $value[$digits_consumed]) { + switch ($value[$digits_consumed + 1]) { + case 'x': + case 'X': + case 'o': + case 'O': + $digits_consumed += 2; + break; + case 'b': + case 'B': + // 0b is a valid pair of digits in base 16 + if (16 !== $base) { + $digits_consumed += 2; + } + break; + } + } + + if ($digits !== $digits_consumed) { + $message = \sprintf( + 'Invalid quantity "%s": no digits after base prefix, interpreting as "0" for backwards compatibility', + self::escapeString($value) + ); + trigger_error($message, \E_USER_WARNING); + + return 0; + } + } + + evaluation: + + if (10 === $base && '0' === $value[$digits]) { + $base = 8; + $allowed_digits = '01234567'; + } + + while ($digits < $str_end && ' ' === $value[$digits]) { + ++$digits; + } + + if ($digits < $str_end && '+' === $value[$digits]) { + ++$digits; + } elseif ($digits < $str_end && '-' === $value[$digits]) { + $is_negative = true; + $overflow = true; + ++$digits; + } + + $digits_end = $digits; + + while ($digits_end < $str_end && false !== strpos($allowed_digits, $value[$digits_end])) { + ++$digits_end; + } + + // Mimic strtoul() on a zend_ulong using two half-width limbs, as PHP has no unsigned integers + $bits = \PHP_INT_SIZE << 2; + $mask = (1 << $bits) - 1; + $high = $low = 0; + + for ($i = $digits; $i < $digits_end; ++$i) { + $low = $low * $base + hexdec($value[$i]); + $high = $high * $base + ($low >> $bits); + $low &= $mask; + + if ($high > $mask) { + break; + } + } + + if ($high > $mask) { + $retval = -1; + $overflow = true; + } else { + $retval = ($high << $bits) | $low; + + if ($is_negative && 0 === $retval) { + $is_negative = false; + $overflow = false; + } elseif (0 > $retval) { + // -PHP_INT_MIN is PHP_INT_MIN itself + $overflow = $overflow || !$is_negative || \PHP_INT_MIN !== $retval; + } elseif ($is_negative) { + $retval = -$retval; + } + } + + if ($digits_end === $digits) { + $message = \sprintf( + 'Invalid quantity "%s": no valid leading digits, interpreting as "0" for backwards compatibility', + self::escapeString($value) + ); + trigger_error($message, \E_USER_WARNING); + + return 0; + } + + /* Allow for whitespace between integer portion and any suffix character */ + while ($digits_end < $str_end && false !== strpos($ctype_space, $value[$digits_end])) { + ++$digits_end; + } + + /* No exponent suffix. */ + if ($digits_end === $str_end) { + goto end; + } + + switch ($value[$str_end - 1]) { + case 'g': + case 'G': + $shift = 30; + break; + case 'm': + case 'M': + $shift = 20; + break; + case 'k': + case 'K': + $shift = 10; + break; + default: + /* Unknown suffix */ + $invalid = self::escapeString($value); + $interpreted = self::escapeString(substr($value, $str, $digits_end - $str)); + $chr = self::escapeString($value[$str_end - 1]); + + $message = \sprintf( + 'Invalid quantity "%s": unknown multiplier "%s", interpreting as "%s" for backwards compatibility', + $invalid, + $chr, + $interpreted + ); + + trigger_error($message, \E_USER_WARNING); + + return $retval; + } + + $factor = 1 << $shift; + + if (!$overflow) { + if ($retval > 0) { + $overflow = $retval > \PHP_INT_MAX / $factor; + } else { + $overflow = $retval < \PHP_INT_MIN / $factor; + } + } + + if (\is_float($retval * $factor)) { + $overflow = true; + $retval <<= $shift; + } else { + $retval *= $factor; + } + + if ($digits_end !== $str_end - 1) { + /* More than one character in suffix */ + $message = \sprintf( + 'Invalid quantity "%s", interpreting as "%s%s" for backwards compatibility', + self::escapeString($value), + self::escapeString(substr($value, $str, $digits_end - $str)), + self::escapeString($value[$str_end - 1]) + ); + trigger_error($message, \E_USER_WARNING); + + return $retval; + } + + end: + + if ($overflow) { + /* Not specifying the resulting value here because the caller may make + * additional conversions. Not specifying the allowed range + * because the caller may do narrower range checks. */ + $message = \sprintf( + 'Invalid quantity "%s": value is out of range, using overflow result for backwards compatibility', + self::escapeString($value) + ); + trigger_error($message, \E_USER_WARNING); + } + + return $retval; + } + + /** + * Escape the string to avoid null bytes and to make non-printable chars visible. + */ + private static function escapeString(string $string): string + { + $escaped = ''; + + for ($n = 0, $len = \strlen($string); $n < $len; ++$n) { + $c = \ord($string[$n]); + + if ($c < 32 || '\\' === $string[$n] || $c > 126) { + switch ($string[$n]) { + case "\n": $escaped .= '\\n'; break; + case "\r": $escaped .= '\\r'; break; + case "\t": $escaped .= '\\t'; break; + case "\f": $escaped .= '\\f'; break; + case "\v": $escaped .= '\\v'; break; + case '\\': $escaped .= '\\\\'; break; + case "\x1B": $escaped .= '\\e'; break; + default: + $escaped .= '\\x'.strtoupper(\sprintf('%02x', $c)); + } + } else { + $escaped .= $string[$n]; + } + } + + return $escaped; + } +} diff --git a/vendor/symfony/polyfill-php82/README.md b/vendor/symfony/polyfill-php82/README.md new file mode 100644 index 0000000..b319155 --- /dev/null +++ b/vendor/symfony/polyfill-php82/README.md @@ -0,0 +1,23 @@ +Symfony Polyfill / Php82 +======================== + +This component provides features added to PHP 8.2 core: + +- [`AllowDynamicProperties`](https://wiki.php.net/rfc/deprecate_dynamic_properties) +- [`SensitiveParameter`](https://wiki.php.net/rfc/redact_parameters_in_back_traces) +- [`SensitiveParameterValue`](https://wiki.php.net/rfc/redact_parameters_in_back_traces) +- [`Random\Engine`](https://wiki.php.net/rfc/rng_extension) +- [`Random\Engine\CryptoSafeEngine`](https://wiki.php.net/rfc/rng_extension) +- [`Random\Engine\Secure`](https://wiki.php.net/rfc/rng_extension) (check [arokettu/random-polyfill](https://packagist.org/packages/arokettu/random-polyfill) for more engines) +- [`odbc_connection_string_is_quoted()`](https://php.net/odbc_connection_string_is_quoted) +- [`odbc_connection_string_should_quote()`](https://php.net/odbc_connection_string_should_quote) +- [`odbc_connection_string_quote()`](https://php.net/odbc_connection_string_quote) +- [`ini_parse_quantity()`](https://php.net/ini_parse_quantity) + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/vendor/symfony/polyfill-php82/Random/Engine/Secure.php b/vendor/symfony/polyfill-php82/Random/Engine/Secure.php new file mode 100644 index 0000000..5565386 --- /dev/null +++ b/vendor/symfony/polyfill-php82/Random/Engine/Secure.php @@ -0,0 +1,50 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php82\Random\Engine; + +use Random\RandomException; +use Symfony\Polyfill\Php82\NoDynamicProperties; + +/** + * @author Tim Düsterhus <tim@bastelstu.be> + * @author Anton Smirnov <sandfox@sandfox.me> + * + * @internal + */ +class Secure +{ + use NoDynamicProperties; + + public function generate(): string + { + try { + return random_bytes(\PHP_INT_SIZE); + } catch (\Exception $e) { + throw new RandomException($e->getMessage(), $e->getCode(), $e->getPrevious()); + } + } + + public function __sleep(): array + { + throw new \Exception("Serialization of 'Random\Engine\Secure' is not allowed"); + } + + public function __wakeup(): void + { + throw new \Exception("Unserialization of 'Random\Engine\Secure' is not allowed"); + } + + public function __clone() + { + throw new \Error('Trying to clone an uncloneable object of class Random\Engine\Secure'); + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php b/vendor/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php new file mode 100644 index 0000000..d216e0a --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php @@ -0,0 +1,20 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80200) { + #[Attribute(Attribute::TARGET_CLASS)] + final class AllowDynamicProperties + { + public function __construct() + { + } + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php b/vendor/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php new file mode 100644 index 0000000..971ed57 --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php @@ -0,0 +1,18 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Random; + +if (\PHP_VERSION_ID < 80200) { + class BrokenRandomEngineError extends RandomError + { + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php b/vendor/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php new file mode 100644 index 0000000..fb32496 --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php @@ -0,0 +1,18 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Random; + +if (\PHP_VERSION_ID < 80200) { + interface CryptoSafeEngine extends Engine + { + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine.php b/vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine.php new file mode 100644 index 0000000..4fc78c8 --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine.php @@ -0,0 +1,19 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Random; + +if (\PHP_VERSION_ID < 80200) { + interface Engine + { + public function generate(): string; + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php b/vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php new file mode 100644 index 0000000..e779b54 --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php @@ -0,0 +1,20 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Random\Engine; + +use Symfony\Polyfill\Php82 as p; + +if (\PHP_VERSION_ID < 80200) { + final class Secure extends p\Random\Engine\Secure implements \Random\CryptoSafeEngine + { + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php b/vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php new file mode 100644 index 0000000..bf5e89e --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Random; + +use Symfony\Polyfill\Php82\NoDynamicProperties; + +if (\PHP_VERSION_ID < 80200) { + class RandomError extends \Error + { + use NoDynamicProperties; + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php b/vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php new file mode 100644 index 0000000..3b9aae1 --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php @@ -0,0 +1,21 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Random; + +use Symfony\Polyfill\Php82\NoDynamicProperties; + +if (\PHP_VERSION_ID < 80200) { + class RandomException extends \Exception + { + use NoDynamicProperties; + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php b/vendor/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php new file mode 100644 index 0000000..aea4dfb --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php @@ -0,0 +1,20 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80200) { + #[Attribute(Attribute::TARGET_PARAMETER)] + final class SensitiveParameter + { + public function __construct() + { + } + } +} diff --git a/vendor/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php b/vendor/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php new file mode 100644 index 0000000..8349170 --- /dev/null +++ b/vendor/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php @@ -0,0 +1,16 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80200) { + final class SensitiveParameterValue extends Symfony\Polyfill\Php82\SensitiveParameterValue + { + } +} diff --git a/vendor/symfony/polyfill-php82/SensitiveParameterValue.php b/vendor/symfony/polyfill-php82/SensitiveParameterValue.php new file mode 100644 index 0000000..944c0a6 --- /dev/null +++ b/vendor/symfony/polyfill-php82/SensitiveParameterValue.php @@ -0,0 +1,47 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php82; + +/** + * @author Tim Düsterhus <duesterhus@woltlab.com> + * + * @internal + */ +class SensitiveParameterValue +{ + private $value; + + public function __construct($value) + { + $this->value = $value; + } + + public function getValue() + { + return $this->value; + } + + public function __debugInfo(): array + { + return []; + } + + public function __sleep(): array + { + throw new \Exception("Serialization of 'SensitiveParameterValue' is not allowed"); + } + + public function __wakeup(): void + { + throw new \Exception("Unserialization of 'SensitiveParameterValue' is not allowed"); + } +} diff --git a/vendor/symfony/polyfill-php82/bootstrap.php b/vendor/symfony/polyfill-php82/bootstrap.php new file mode 100644 index 0000000..b8da6f0 --- /dev/null +++ b/vendor/symfony/polyfill-php82/bootstrap.php @@ -0,0 +1,38 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php82 as p; + +if (\PHP_VERSION_ID >= 80200) { + return; +} + +if (\extension_loaded('curl') && !defined('CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256') && curl_version()['version_number'] >= 0x075000) { + define('CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256', 10311); +} + +if (extension_loaded('odbc')) { + if (!function_exists('odbc_connection_string_is_quoted')) { + function odbc_connection_string_is_quoted(string $str): bool { return p\Php82::odbc_connection_string_is_quoted($str); } + } + + if (!function_exists('odbc_connection_string_should_quote')) { + function odbc_connection_string_should_quote(string $str): bool { return p\Php82::odbc_connection_string_should_quote($str); } + } + + if (!function_exists('odbc_connection_string_quote')) { + function odbc_connection_string_quote(string $str): string { return p\Php82::odbc_connection_string_quote($str); } + } +} + +if (!function_exists('ini_parse_quantity')) { + function ini_parse_quantity(string $shorthand): int { return p\Php82::ini_parse_quantity($shorthand); } +} diff --git a/vendor/symfony/polyfill-php82/composer.json b/vendor/symfony/polyfill-php82/composer.json new file mode 100644 index 0000000..2031ae8 --- /dev/null +++ b/vendor/symfony/polyfill-php82/composer.json @@ -0,0 +1,33 @@ +{ + "name": "symfony/polyfill-php82", + "type": "library", + "description": "Symfony polyfill backporting some PHP 8.2+ features to lower PHP versions", + "keywords": ["polyfill", "shim", "compatibility", "portable"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Php82\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/vendor/vlucas/phpdotenv/LICENSE b/vendor/vlucas/phpdotenv/LICENSE new file mode 100644 index 0000000..922c552 --- /dev/null +++ b/vendor/vlucas/phpdotenv/LICENSE @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2014, Graham Campbell. +Copyright (c) 2013, Vance Lucas. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/vlucas/phpdotenv/composer.json b/vendor/vlucas/phpdotenv/composer.json new file mode 100644 index 0000000..db6e40b --- /dev/null +++ b/vendor/vlucas/phpdotenv/composer.json @@ -0,0 +1,60 @@ +{ + "name": "vlucas/phpdotenv", + "description": "Loads environment variables from `.env` to `$_ENV` and `$_SERVER` automagically, and optionally to `getenv()`.", + "keywords": ["env", "dotenv", "environment"], + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Vance Lucas", + "email": "vance@vancelucas.com", + "homepage": "https://github.com/vlucas" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "ext-pcre": "*", + "graham-campbell/result-type": "^1.2", + "phpoption/phpoption": "^1.10", + "symfony/polyfill-ctype": "^1.26", + "symfony/polyfill-mbstring": "^1.26", + "symfony/polyfill-php80": "^1.26" + }, + "require-dev": { + "ext-filter": "*", + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit":"^8.5.34 || ^9.6.13 || ^10.4.2" + }, + "autoload": { + "psr-4": { + "Dotenv\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Dotenv\\Tests\\": "tests/Dotenv/" + } + }, + "suggest": { + "ext-filter": "Required to use the boolean validator." + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist" + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "5.8-dev" + } + } +} diff --git a/vendor/vlucas/phpdotenv/src/Dotenv.php b/vendor/vlucas/phpdotenv/src/Dotenv.php new file mode 100644 index 0000000..34ca850 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Dotenv.php @@ -0,0 +1,267 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv; + +use Dotenv\Exception\InvalidPathException; +use Dotenv\Loader\Loader; +use Dotenv\Loader\LoaderInterface; +use Dotenv\Parser\Parser; +use Dotenv\Parser\ParserInterface; +use Dotenv\Repository\Adapter\ArrayAdapter; +use Dotenv\Repository\Adapter\PutenvAdapter; +use Dotenv\Repository\RepositoryBuilder; +use Dotenv\Repository\RepositoryInterface; +use Dotenv\Store\StoreBuilder; +use Dotenv\Store\StoreInterface; +use Dotenv\Store\StringStore; + +class Dotenv +{ + /** + * The store instance. + * + * @var \Dotenv\Store\StoreInterface + */ + private $store; + + /** + * The parser instance. + * + * @var \Dotenv\Parser\ParserInterface + */ + private $parser; + + /** + * The loader instance. + * + * @var \Dotenv\Loader\LoaderInterface + */ + private $loader; + + /** + * The repository instance. + * + * @var \Dotenv\Repository\RepositoryInterface + */ + private $repository; + + /** + * Create a new dotenv instance. + * + * @param \Dotenv\Store\StoreInterface $store + * @param \Dotenv\Parser\ParserInterface $parser + * @param \Dotenv\Loader\LoaderInterface $loader + * @param \Dotenv\Repository\RepositoryInterface $repository + * + * @return void + */ + public function __construct( + StoreInterface $store, + ParserInterface $parser, + LoaderInterface $loader, + RepositoryInterface $repository + ) { + $this->store = $store; + $this->parser = $parser; + $this->loader = $loader; + $this->repository = $repository; + } + + /** + * Create a new dotenv instance. + * + * @param \Dotenv\Repository\RepositoryInterface $repository + * @param string|string[] $paths + * @param string|string[]|null $names + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @return \Dotenv\Dotenv + */ + public static function create(RepositoryInterface $repository, $paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) + { + $builder = $names === null ? StoreBuilder::createWithDefaultName() : StoreBuilder::createWithNoNames(); + + foreach ((array) $paths as $path) { + $builder = $builder->addPath($path); + } + + foreach ((array) $names as $name) { + $builder = $builder->addName($name); + } + + if ($shortCircuit) { + $builder = $builder->shortCircuit(); + } + + return new self($builder->fileEncoding($fileEncoding)->make(), new Parser(), new Loader(), $repository); + } + + /** + * Create a new mutable dotenv instance with default repository. + * + * @param string|string[] $paths + * @param string|string[]|null $names + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @return \Dotenv\Dotenv + */ + public static function createMutable($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) + { + $repository = RepositoryBuilder::createWithDefaultAdapters()->make(); + + return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); + } + + /** + * Create a new mutable dotenv instance with default repository with the putenv adapter. + * + * @param string|string[] $paths + * @param string|string[]|null $names + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @return \Dotenv\Dotenv + */ + public static function createUnsafeMutable($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) + { + $repository = RepositoryBuilder::createWithDefaultAdapters() + ->addAdapter(PutenvAdapter::class) + ->make(); + + return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); + } + + /** + * Create a new immutable dotenv instance with default repository. + * + * @param string|string[] $paths + * @param string|string[]|null $names + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @return \Dotenv\Dotenv + */ + public static function createImmutable($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) + { + $repository = RepositoryBuilder::createWithDefaultAdapters()->immutable()->make(); + + return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); + } + + /** + * Create a new immutable dotenv instance with default repository with the putenv adapter. + * + * @param string|string[] $paths + * @param string|string[]|null $names + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @return \Dotenv\Dotenv + */ + public static function createUnsafeImmutable($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) + { + $repository = RepositoryBuilder::createWithDefaultAdapters() + ->addAdapter(PutenvAdapter::class) + ->immutable() + ->make(); + + return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); + } + + /** + * Create a new dotenv instance with an array backed repository. + * + * @param string|string[] $paths + * @param string|string[]|null $names + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @return \Dotenv\Dotenv + */ + public static function createArrayBacked($paths, $names = null, bool $shortCircuit = true, ?string $fileEncoding = null) + { + $repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make(); + + return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); + } + + /** + * Parse the given content and resolve nested variables. + * + * This method behaves just like load(), only without mutating your actual + * environment. We do this by using an array backed repository. + * + * @param string $content + * + * @throws \Dotenv\Exception\InvalidFileException + * + * @return array<string, string|null> + */ + public static function parse(string $content) + { + $repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make(); + + $phpdotenv = new self(new StringStore($content), new Parser(), new Loader(), $repository); + + return $phpdotenv->load(); + } + + /** + * Read and load environment file(s). + * + * @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidFileException + * + * @return array<string, string|null> + */ + public function load() + { + $entries = $this->parser->parse($this->store->read()); + + return $this->loader->load($this->repository, $entries); + } + + /** + * Read and load environment file(s), silently failing if no files can be read. + * + * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidFileException + * + * @return array<string, string|null> + */ + public function safeLoad() + { + try { + return $this->load(); + } catch (InvalidPathException $e) { + // suppressing exception + return []; + } + } + + /** + * Required ensures that the specified variables exist, and returns a new validator object. + * + * @param string|string[] $variables + * + * @return \Dotenv\Validator + */ + public function required($variables) + { + return (new Validator($this->repository, (array) $variables))->required(); + } + + /** + * Returns a new validator object that won't check if the specified variables exist. + * + * @param string|string[] $variables + * + * @return \Dotenv\Validator + */ + public function ifPresent($variables) + { + return new Validator($this->repository, (array) $variables); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Exception/ExceptionInterface.php b/vendor/vlucas/phpdotenv/src/Exception/ExceptionInterface.php new file mode 100644 index 0000000..1e80f53 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Exception/ExceptionInterface.php @@ -0,0 +1,12 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Exception; + +use Throwable; + +interface ExceptionInterface extends Throwable +{ + // +} diff --git a/vendor/vlucas/phpdotenv/src/Exception/InvalidEncodingException.php b/vendor/vlucas/phpdotenv/src/Exception/InvalidEncodingException.php new file mode 100644 index 0000000..f02f8e4 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Exception/InvalidEncodingException.php @@ -0,0 +1,12 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Exception; + +use InvalidArgumentException; + +final class InvalidEncodingException extends InvalidArgumentException implements ExceptionInterface +{ + // +} diff --git a/vendor/vlucas/phpdotenv/src/Exception/InvalidFileException.php b/vendor/vlucas/phpdotenv/src/Exception/InvalidFileException.php new file mode 100644 index 0000000..6e878a5 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Exception/InvalidFileException.php @@ -0,0 +1,12 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Exception; + +use InvalidArgumentException; + +final class InvalidFileException extends InvalidArgumentException implements ExceptionInterface +{ + // +} diff --git a/vendor/vlucas/phpdotenv/src/Exception/InvalidPathException.php b/vendor/vlucas/phpdotenv/src/Exception/InvalidPathException.php new file mode 100644 index 0000000..ee836a7 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Exception/InvalidPathException.php @@ -0,0 +1,12 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Exception; + +use InvalidArgumentException; + +final class InvalidPathException extends InvalidArgumentException implements ExceptionInterface +{ + // +} diff --git a/vendor/vlucas/phpdotenv/src/Exception/ValidationException.php b/vendor/vlucas/phpdotenv/src/Exception/ValidationException.php new file mode 100644 index 0000000..3d6773a --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Exception/ValidationException.php @@ -0,0 +1,12 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Exception; + +use RuntimeException; + +final class ValidationException extends RuntimeException implements ExceptionInterface +{ + // +} diff --git a/vendor/vlucas/phpdotenv/src/Loader/Loader.php b/vendor/vlucas/phpdotenv/src/Loader/Loader.php new file mode 100644 index 0000000..7070b1f --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Loader/Loader.php @@ -0,0 +1,43 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Loader; + +use Dotenv\Repository\RepositoryInterface; + +final class Loader implements LoaderInterface +{ + /** + * Load the given entries into the repository. + * + * We'll substitute any nested variables, and send each variable to the + * repository, with the effect of actually mutating the environment. + * + * @param \Dotenv\Repository\RepositoryInterface $repository + * @param \Dotenv\Parser\Entry[] $entries + * + * @return array<string, string|null> + */ + public function load(RepositoryInterface $repository, array $entries) + { + $vars = []; + + foreach ($entries as $entry) { + $name = $entry->getName(); + + $value = $entry->getValue(); + + if ($value->isDefined()) { + $inner = Resolver::resolve($repository, $value->get()); + if ($repository->set($name, $inner)) { + $vars[$name] = $inner; + } + } elseif ($repository->clear($name)) { + $vars[$name] = null; + } + } + + return $vars; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Loader/LoaderInterface.php b/vendor/vlucas/phpdotenv/src/Loader/LoaderInterface.php new file mode 100644 index 0000000..f40d6ad --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Loader/LoaderInterface.php @@ -0,0 +1,20 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Loader; + +use Dotenv\Repository\RepositoryInterface; + +interface LoaderInterface +{ + /** + * Load the given entries into the repository. + * + * @param \Dotenv\Repository\RepositoryInterface $repository + * @param \Dotenv\Parser\Entry[] $entries + * + * @return array<string, string|null> + */ + public function load(RepositoryInterface $repository, array $entries); +} diff --git a/vendor/vlucas/phpdotenv/src/Loader/Resolver.php b/vendor/vlucas/phpdotenv/src/Loader/Resolver.php new file mode 100644 index 0000000..5ffb042 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Loader/Resolver.php @@ -0,0 +1,235 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Loader; + +use Dotenv\Parser\Value; +use Dotenv\Repository\RepositoryInterface; +use Dotenv\Util\Regex; +use Dotenv\Util\Str; +use PhpOption\Option; + +final class Resolver +{ + /** + * The characters allowed in the name of a nested variable. + */ + private const NAME_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.'; + + /** + * This class is a singleton. + * + * @codeCoverageIgnore + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Resolve the nested variables in the given value. + * + * Replaces ${varname} patterns in the allowed positions in the variable + * value by an existing environment variable. + * + * @param \Dotenv\Repository\RepositoryInterface $repository + * @param \Dotenv\Parser\Value $value + * + * @return string + */ + public static function resolve(RepositoryInterface $repository, Value $value) + { + $chars = $value->getChars(); + $vars = $value->getVars(); + + if ($vars === []) { + return $chars; + } + + $tail = []; + $used = []; + $cut = \strlen($chars); + + foreach (self::getOffsets($chars, $vars) as $i) { + $head = \substr($chars, $i, $cut - $i); + $cut = $i; + + // A variable can run on into the text resolved after it. + $need = self::getNeeded($head); + + while ($need !== null && $tail !== []) { + $top = \count($tail) - 1; + $piece = $tail[$top]; + $from = $used[$top]; + $to = $need === '' ? $from + \strspn($piece, self::NAME_CHARS, $from) : $from; + + if (isset($piece[$to])) { + $need = $need !== '' && $piece[$to] === $need[0] ? \substr($need, 1) : null; + $to++; + } + + $head .= \substr($piece, $from, $to - $from); + + if (isset($piece[$to])) { + $used[$top] = $to; + } else { + \array_pop($tail); + \array_pop($used); + } + } + + $head = self::resolveVariable($repository, $head); + + if ($head !== '') { + $tail[] = $head; + $used[] = 0; + } + } + + $resolved = \substr($chars, 0, $cut); + + for ($top = \count($tail) - 1; $top >= 0; $top--) { + $resolved .= \substr($tail[$top], $used[$top]); + } + + return $resolved; + } + + /** + * Convert the character offsets of the variables into byte offsets. + * + * @param string $chars + * @param int[] $vars + * + * @return int[] + */ + private static function getOffsets(string $chars, array $vars) + { + $valid = \preg_match('//u', $chars) === 1; + $offsets = []; + $char = 0; + $byte = 0; + + foreach (\array_reverse($vars) as $var) { + $byte = $valid ? self::skipChars($chars, $byte, $var - $char) : self::skipCountedChars($chars, $byte, $var - $char); + $char = $var; + $offsets[] = $byte; + } + + return \array_reverse($offsets); + } + + /** + * Skip the given number of characters in valid UTF-8. + * + * @param string $chars + * @param int $byte + * @param int $count + * + * @return int + */ + private static function skipChars(string $chars, int $byte, int $count) + { + // Every byte but a continuation byte starts a character. + $starts = $count + 1; + + while ($starts > 0 && isset($chars[$byte])) { + $slice = \substr($chars, $byte, $starts); + $byte += \strlen($slice); + $starts -= \strlen($slice) - (int) \preg_match_all('/[\x80-\xBF]/', $slice); + } + + return $starts > 0 ? $byte : $byte - 1; + } + + /** + * Skip the given number of characters, counted as the parser counted them. + * + * @param string $chars + * @param int $byte + * @param int $count + * + * @return int + */ + private static function skipCountedChars(string $chars, int $byte, int $count) + { + $rest = \strlen($chars) - $byte; + $low = \min($count, $rest); + + // Find the shortest length that holds one character too many. + for ($high = \min($count + 1, $rest); $high > $low; $high = \min(2 * $high, $rest)) { + if (Str::len(\substr($chars, $byte, $high)) > $count) { + while ($high - $low > 1) { + $middle = $low + \intdiv($high - $low, 2); + + if (Str::len(\substr($chars, $byte, $middle)) > $count) { + $high = $middle; + } else { + $low = $middle; + } + } + + return $byte + $low; + } + + if ($high === $rest) { + break; + } + + $low = $high; + } + + return $byte + $rest; + } + + /** + * Determine what must follow the given string for it to open a variable. + * + * That is, the rest of the opening, an empty string once only the name is + * unfinished, or null if it cannot open one. + * + * @param string $str + * + * @return string|null + */ + private static function getNeeded(string $str) + { + if ($str === '') { + return '${'; + } + + if ($str === '$') { + return '{'; + } + + if (\strncmp($str, '${', 2) === 0 && \strspn($str, self::NAME_CHARS, 2) === \strlen($str) - 2) { + return ''; + } + + return null; + } + + /** + * Resolve a single nested variable. + * + * @param \Dotenv\Repository\RepositoryInterface $repository + * @param string $str + * + * @return string + */ + private static function resolveVariable(RepositoryInterface $repository, string $str) + { + return Regex::replaceCallback( + '/\A\${([a-zA-Z0-9_.]+)}/', + static function (array $matches) use ($repository) { + /** @var string */ + return Option::fromValue($repository->get($matches[1]))->getOrElse($matches[0]); + }, + $str, + 1 + )->success()->getOrElse($str); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Parser/Entry.php b/vendor/vlucas/phpdotenv/src/Parser/Entry.php new file mode 100644 index 0000000..716f422 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Parser/Entry.php @@ -0,0 +1,59 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Parser; + +use PhpOption\Option; + +final class Entry +{ + /** + * The entry name. + * + * @var string + */ + private $name; + + /** + * The entry value. + * + * @var \Dotenv\Parser\Value|null + */ + private $value; + + /** + * Create a new entry instance. + * + * @param string $name + * @param \Dotenv\Parser\Value|null $value + * + * @return void + */ + public function __construct(string $name, ?Value $value = null) + { + $this->name = $name; + $this->value = $value; + } + + /** + * Get the entry name. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Get the entry value. + * + * @return \PhpOption\Option<\Dotenv\Parser\Value> + */ + public function getValue() + { + /** @var \PhpOption\Option<\Dotenv\Parser\Value> */ + return Option::fromValue($this->value); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Parser/EntryParser.php b/vendor/vlucas/phpdotenv/src/Parser/EntryParser.php new file mode 100644 index 0000000..f9879dd --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Parser/EntryParser.php @@ -0,0 +1,363 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Parser; + +use Dotenv\Util\Regex; +use Dotenv\Util\Str; +use GrahamCampbell\ResultType\Error; +use GrahamCampbell\ResultType\Result; +use GrahamCampbell\ResultType\Success; +use PhpOption\None; +use PhpOption\Some; + +final class EntryParser +{ + private const INITIAL_STATE = 0; + private const UNQUOTED_STATE = 1; + private const SINGLE_QUOTED_STATE = 2; + private const DOUBLE_QUOTED_STATE = 3; + private const ESCAPE_SEQUENCE_STATE = 4; + private const WHITESPACE_STATE = 5; + private const COMMENT_STATE = 6; + private const REJECT_STATES = [self::SINGLE_QUOTED_STATE, self::DOUBLE_QUOTED_STATE, self::ESCAPE_SEQUENCE_STATE]; + + /** + * This class is a singleton. + * + * @codeCoverageIgnore + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Parse a raw entry into a proper entry. + * + * That is, turn a raw environment variable entry into a name and possibly + * a value. We wrap the answer in a result type. + * + * @param string $entry + * + * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry, string> + */ + public static function parse(string $entry) + { + return self::splitStringIntoParts($entry)->flatMap(static function (array $parts) { + [$name, $value] = $parts; + + return self::parseName($name)->flatMap(static function (string $name) use ($value) { + $parsedValue = $value === null ? Success::create(null) : self::parseValue($value); + + return $parsedValue->map(static function (?Value $value) use ($name) { + return new Entry($name, $value); + }); + }); + }); + } + + /** + * Split the compound string into parts. + * + * @param string $line + * + * @return \GrahamCampbell\ResultType\Result<array{string, string|null},string> + */ + private static function splitStringIntoParts(string $line) + { + $result = \explode('=', $line, 2); + + if (isset($result[1])) { + $result = [\trim($result[0], " \n\r\t\0\x0B"), \trim($result[1], " \n\r\t\0\x0B")]; + } else { + $result = [$line, null]; + } + + if ($result[0] === '') { + return Error::create(self::getErrorMessage('an unexpected equals', $line)); + } + + return Success::create($result); + } + + /** + * Parse the given variable name. + * + * That is, strip the optional quotes and leading "export" from the + * variable name. We wrap the answer in a result type. + * + * @param string $name + * + * @return \GrahamCampbell\ResultType\Result<string, string> + */ + private static function parseName(string $name) + { + if (\strlen($name) > 6 && \substr($name, 0, 6) === 'export' && \ctype_space($name[6])) { + $name = \ltrim(\substr($name, 6), " \t\n\r\v\f"); + } + + if (self::isQuotedName($name)) { + $name = \substr($name, 1, -1); + } + + if (!self::isValidName($name)) { + return Error::create(self::getErrorMessage('an invalid name', $name)); + } + + return Success::create($name); + } + + /** + * Is the given variable name quoted? + * + * @param string $name + * + * @return bool + */ + private static function isQuotedName(string $name) + { + if (\strlen($name) < 3) { + return false; + } + + $first = $name[0]; + $last = $name[\strlen($name) - 1]; + + return ($first === '"' && $last === '"') || ($first === '\'' && $last === '\''); + } + + /** + * Is the given variable name valid? + * + * @param string $name + * + * @return bool + */ + private static function isValidName(string $name) + { + if (\preg_match('~\A[a-zA-Z0-9_.]+\z~', $name) === 1) { + return true; + } + + return Regex::matches('~\A[\p{Ll}\p{Lu}\p{M}\p{N}_.]+\z~u', $name)->success()->getOrElse(false); + } + + /** + * Parse the given variable value. + * + * This has the effect of stripping quotes and comments, dealing with + * special characters, and locating nested variables, but not resolving + * them. Formally, we run a finite state automaton with an output tape: a + * transducer. We wrap the answer in a result type. + * + * @param string $value + * + * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value, string> + */ + private static function parseValue(string $value) + { + if (\trim($value, " \n\r\t\0\x0B") === '') { + return Success::create(Value::blank()); + } + + $literal = self::parseLiteral($value); + + if ($literal->isDefined()) { + return Success::create(Value::blank()->append($literal->get(), false)); + } + + $chars = ''; + $pending = ''; + $length = 0; + $vars = []; + $state = self::INITIAL_STATE; + + foreach (Lexer::lex($value) as $token) { + $result = self::processToken($state, $token); + + if ($result->error()->isDefined()) { + return Error::create(self::getErrorMessage($result->error()->get(), $value)); + } + + [$chunk, $var, $state] = $result->success()->get(); + + if ($var) { + $chars .= $pending; + $length += Str::len($pending); + $pending = ''; + $vars[] = $length; + } + + $pending .= $chunk; + } + + if (\in_array($state, self::REJECT_STATES, true)) { + return Error::create(self::getErrorMessage('a missing closing quote', $value)); + } + + return Success::create(Value::create($chars.$pending, $vars)); + } + + /** + * Parse the given variable value, if it is a literal. + * + * That is, a value which can be used verbatim, save stripping quotes. + * Unquoted literals are capped at the lexer's chunk size, so that the + * fast path agrees with the transducer under any libc locale. + * + * @param string $value + * + * @return \PhpOption\Option<string> + */ + private static function parseLiteral(string $value) + { + if (\preg_match('~\A(?|([^\s\\\\\'"#$]{1,1000})|\'([^\']*)\'|"([^"\\\\$]*)")\z~', $value, $matches) === 1) { + return Some::create($matches[1]); + } + + return None::create(); + } + + /** + * Process the given token. + * + * @param int $state + * @param string $token + * + * @return \GrahamCampbell\ResultType\Result<array{string, bool, int}, string> + */ + private static function processToken(int $state, string $token) + { + switch ($state) { + case self::INITIAL_STATE: + if ($token === '\'') { + return Success::create(['', false, self::SINGLE_QUOTED_STATE]); + } elseif ($token === '"') { + return Success::create(['', false, self::DOUBLE_QUOTED_STATE]); + } elseif ($token === '#') { + return Success::create(['', false, self::COMMENT_STATE]); + } elseif ($token === '$') { + return Success::create([$token, true, self::UNQUOTED_STATE]); + } else { + return Success::create([$token, false, self::UNQUOTED_STATE]); + } + case self::UNQUOTED_STATE: + if ($token === '#') { + return Success::create(['', false, self::COMMENT_STATE]); + } elseif (\ctype_space($token)) { + return Success::create(['', false, self::WHITESPACE_STATE]); + } elseif ($token === '$') { + return Success::create([$token, true, self::UNQUOTED_STATE]); + } else { + return Success::create([$token, false, self::UNQUOTED_STATE]); + } + case self::SINGLE_QUOTED_STATE: + if ($token === '\'') { + return Success::create(['', false, self::WHITESPACE_STATE]); + } else { + return Success::create([$token, false, self::SINGLE_QUOTED_STATE]); + } + case self::DOUBLE_QUOTED_STATE: + if ($token === '"') { + return Success::create(['', false, self::WHITESPACE_STATE]); + } elseif ($token === '\\') { + return Success::create(['', false, self::ESCAPE_SEQUENCE_STATE]); + } elseif ($token === '$') { + return Success::create([$token, true, self::DOUBLE_QUOTED_STATE]); + } else { + return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); + } + case self::ESCAPE_SEQUENCE_STATE: + if ($token === '"' || $token === '\\') { + return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); + } elseif ($token === '$') { + return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); + } else { + $first = Str::substr($token, 0, 1); + if (\in_array($first, ['f', 'n', 'r', 't', 'v'], true)) { + return Success::create([\stripcslashes('\\'.$first).Str::substr($token, 1), false, self::DOUBLE_QUOTED_STATE]); + } else { + return Error::create('an unexpected escape sequence'); + } + } + case self::WHITESPACE_STATE: + if ($token === '#') { + return Success::create(['', false, self::COMMENT_STATE]); + } elseif (!\ctype_space($token)) { + return Error::create('unexpected whitespace'); + } else { + return Success::create(['', false, self::WHITESPACE_STATE]); + } + case self::COMMENT_STATE: + return Success::create(['', false, self::COMMENT_STATE]); + default: + throw new \Error('Parser entered invalid state.'); + } + } + + /** + * Generate a friendly error message. + * + * @param string $cause + * @param string $subject + * + * @return string + */ + private static function getErrorMessage(string $cause, string $subject) + { + $line = \strtok($subject, "\n"); + + if ($line === false) { + $line = ''; + } + + if (\strlen($line) > 80) { + $line = self::cutBytes($line, 80).'...'; + } + + $line = \addcslashes($line, "\0..\37\177"); + + return \sprintf( + 'Encountered %s at [%s].', + $cause, + $line + ); + } + + /** + * Cut the string to at most the given number of bytes. + * + * The cut never splits a multibyte UTF-8 character: an incomplete + * trailing sequence is dropped entirely. + * + * @param string $input + * @param int $limit + * + * @return string + */ + private static function cutBytes(string $input, int $limit) + { + $prefix = \substr($input, 0, $limit); + $length = \strlen($prefix); + + for ($i = $length - 1; $i >= 0 && $i >= $length - 4; $i--) { + $byte = \ord($prefix[$i]); + + if (($byte & 0xC0) !== 0x80) { + $need = $byte < 0x80 ? 1 : ($byte >= 0xF0 ? 4 : ($byte >= 0xE0 ? 3 : ($byte >= 0xC0 ? 2 : 1))); + + if ($i + $need > $length) { + $prefix = \substr($prefix, 0, $i); + } + + break; + } + } + + return $prefix; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Parser/Lexer.php b/vendor/vlucas/phpdotenv/src/Parser/Lexer.php new file mode 100644 index 0000000..dc060e8 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Parser/Lexer.php @@ -0,0 +1,58 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Parser; + +final class Lexer +{ + /** + * The regex for each type of token. + */ + private const PATTERNS = [ + '[\r\n]{1,1000}', '[^\S\r\n]{1,1000}', '\\\\', '\'', '"', '\\#', '\\$', '([^(\s\\\\\'"\\#\\$)]|\\(|\\)){1,1000}', + ]; + + /** + * This class is a singleton. + * + * @codeCoverageIgnore + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Convert content into a token stream. + * + * Multibyte string processing is not needed here, and nether is error + * handling, for performance reasons. + * + * @param string $content + * + * @return \Generator<string> + */ + public static function lex(string $content) + { + static $regex; + + if ($regex === null) { + $regex = '(('.\implode(')|(', self::PATTERNS).'))A'; + } + + $offset = 0; + + while (isset($content[$offset])) { + if (\preg_match($regex, $content, $matches, 0, $offset) !== 1) { + throw new \Error(\sprintf('Lexer encountered unexpected character [%s].', $content[$offset])); + } + + $offset += \strlen($matches[0]); + + yield $matches[0]; + } + } +} diff --git a/vendor/vlucas/phpdotenv/src/Parser/Lines.php b/vendor/vlucas/phpdotenv/src/Parser/Lines.php new file mode 100644 index 0000000..9547107 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Parser/Lines.php @@ -0,0 +1,120 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Parser; + +use Dotenv\Util\Regex; + +final class Lines +{ + /** + * This class is a singleton. + * + * @codeCoverageIgnore + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Process the array of lines of environment variables. + * + * This will produce an array of raw entries, one per variable. + * + * @param string[] $lines + * + * @return string[] + */ + public static function process(array $lines) + { + $output = []; + $multiline = false; + $multilineBuffer = []; + + foreach ($lines as $line) { + $startsOnCurrentLine = $multiline ? false : self::looksLikeMultilineStart($line); + + if ($startsOnCurrentLine) { + $multiline = true; + } + + if ($multiline) { + $multilineBuffer[] = $line; + + if (self::looksLikeMultilineStop($line, $startsOnCurrentLine)) { + $multiline = false; + $line = \implode("\n", $multilineBuffer); + $multilineBuffer = []; + } + } + + if (!$multiline && !self::isCommentOrWhitespace($line)) { + $output[] = $line; + } + } + + // Emit an unterminated multiline value so the parser reports the missing quote. + if ($multiline) { + $output[] = \implode("\n", $multilineBuffer); + } + + return $output; + } + + /** + * Determine if the given line can be the start of a multiline variable. + * + * @param string $line + * + * @return bool + */ + private static function looksLikeMultilineStart(string $line) + { + $pos = \strpos($line, '="'); + + if ($pos === false) { + return false; + } + + $hash = \strpos($line, '#'); + + if ($hash !== false && $hash < $pos) { + return false; + } + + return self::looksLikeMultilineStop($line, true) === false; + } + + /** + * Determine if the given line can be the start of a multiline variable. + * + * @param string $line + * @param bool $started + * + * @return bool + */ + private static function looksLikeMultilineStop(string $line, bool $started) + { + return Regex::occurrences('/(?<!\\\\)"/', \str_replace('\\\\', '', $line))->map(static function (int $count) use ($started) { + return $started ? $count > 1 : $count >= 1; + })->success()->getOrElse(false); + } + + /** + * Determine if the line in the file is a comment or whitespace. + * + * @param string $line + * + * @return bool + */ + private static function isCommentOrWhitespace(string $line) + { + $line = \trim($line, " \n\r\t\0\x0B"); + + return $line === '' || (isset($line[0]) && $line[0] === '#'); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Parser/Parser.php b/vendor/vlucas/phpdotenv/src/Parser/Parser.php new file mode 100644 index 0000000..9fc922f --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Parser/Parser.php @@ -0,0 +1,58 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Parser; + +use Dotenv\Exception\InvalidFileException; +use Dotenv\Util\Regex; +use GrahamCampbell\ResultType\Error; +use GrahamCampbell\ResultType\Success; + +final class Parser implements ParserInterface +{ + /** + * Parse content into an entry array. + * + * @param string $content + * + * @throws \Dotenv\Exception\InvalidFileException + * + * @return \Dotenv\Parser\Entry[] + */ + public function parse(string $content) + { + return Regex::split("/(\r\n|\n|\r)/", $content)->mapError(static function () { + return 'Could not split into separate lines.'; + })->flatMap(static function (array $lines) { + return self::process(Lines::process($lines)); + })->mapError(static function (string $error) { + throw new InvalidFileException(\sprintf('Failed to parse dotenv file. %s', $error)); + })->success()->get(); + } + + /** + * Convert the raw entries into proper entries. + * + * @param string[] $entries + * + * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[], string> + */ + private static function process(array $entries) + { + /** @var \Dotenv\Parser\Entry[] */ + $output = []; + + foreach ($entries as $raw) { + $entry = EntryParser::parse($raw); + + if ($entry->error()->isDefined()) { + return Error::create($entry->error()->get()); + } + + $output[] = $entry->success()->get(); + } + + return Success::create($output); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Parser/ParserInterface.php b/vendor/vlucas/phpdotenv/src/Parser/ParserInterface.php new file mode 100644 index 0000000..17cc42a --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Parser/ParserInterface.php @@ -0,0 +1,19 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Parser; + +interface ParserInterface +{ + /** + * Parse content into an entry array. + * + * @param string $content + * + * @throws \Dotenv\Exception\InvalidFileException + * + * @return \Dotenv\Parser\Entry[] + */ + public function parse(string $content); +} diff --git a/vendor/vlucas/phpdotenv/src/Parser/Value.php b/vendor/vlucas/phpdotenv/src/Parser/Value.php new file mode 100644 index 0000000..aed6c83 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Parser/Value.php @@ -0,0 +1,101 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Parser; + +use Dotenv\Util\Str; + +final class Value +{ + /** + * The string representation of the parsed value. + * + * @var string + */ + private $chars; + + /** + * The locations of the variables in the value. + * + * @var int[] + */ + private $vars; + + /** + * Internal constructor for a value. + * + * @param string $chars + * @param int[] $vars + * + * @return void + */ + private function __construct(string $chars, array $vars) + { + $this->chars = $chars; + $this->vars = $vars; + } + + /** + * Create an empty value instance. + * + * @return \Dotenv\Parser\Value + */ + public static function blank() + { + return new self('', []); + } + + /** + * Create a new value instance. + * + * @param string $chars + * @param int[] $vars + * + * @return \Dotenv\Parser\Value + */ + public static function create(string $chars, array $vars) + { + return new self($chars, $vars); + } + + /** + * Create a new value instance, appending the characters. + * + * @param string $chars + * @param bool $var + * + * @return \Dotenv\Parser\Value + */ + public function append(string $chars, bool $var) + { + return new self( + $this->chars.$chars, + $var ? \array_merge($this->vars, [Str::len($this->chars)]) : $this->vars + ); + } + + /** + * Get the string representation of the parsed value. + * + * @return string + */ + public function getChars() + { + return $this->chars; + } + + /** + * Get the locations of the variables in the value. + * + * @return int[] + */ + public function getVars() + { + $vars = $this->vars; + + \rsort($vars); + + return $vars; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/AdapterInterface.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/AdapterInterface.php new file mode 100644 index 0000000..5604398 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/AdapterInterface.php @@ -0,0 +1,15 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +interface AdapterInterface extends ReaderInterface, WriterInterface +{ + /** + * Create a new instance of the adapter, if it is available. + * + * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> + */ + public static function create(); +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/ApacheAdapter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ApacheAdapter.php new file mode 100644 index 0000000..b2ee143 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ApacheAdapter.php @@ -0,0 +1,88 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +use PhpOption\None; +use PhpOption\Option; +use PhpOption\Some; + +final class ApacheAdapter implements AdapterInterface +{ + /** + * Create a new apache adapter instance. + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Create a new instance of the adapter, if it is available. + * + * @return \PhpOption\Option<self> + */ + public static function create() + { + if (self::isSupported()) { + return Some::create(new self()); + } + + return None::create(); + } + + /** + * Determines if the adapter is supported. + * + * This happens if PHP is running as an Apache module. + * + * @return bool + */ + private static function isSupported() + { + return \function_exists('apache_getenv') && \function_exists('apache_setenv'); + } + + /** + * Read an environment variable, if it exists. + * + * @param non-empty-string $name + * + * @return \PhpOption\Option<string> + */ + public function read(string $name) + { + /** @var \PhpOption\Option<string> */ + return Option::fromValue(apache_getenv($name))->filter(static function ($value) { + return \is_string($value) && $value !== ''; + }); + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + return apache_setenv($name, $value); + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + return apache_setenv($name, ''); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/ArrayAdapter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ArrayAdapter.php new file mode 100644 index 0000000..58eea72 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ArrayAdapter.php @@ -0,0 +1,79 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +use PhpOption\Option; +use PhpOption\Some; + +final class ArrayAdapter implements AdapterInterface +{ + /** + * The variables and their values. + * + * @var array<string, string> + */ + private $variables; + + /** + * Create a new array adapter instance. + * + * @return void + */ + private function __construct() + { + $this->variables = []; + } + + /** + * Create a new instance of the adapter, if it is available. + * + * @return \PhpOption\Option<self> + */ + public static function create() + { + return Some::create(new self()); + } + + /** + * Read an environment variable, if it exists. + * + * @param non-empty-string $name + * + * @return \PhpOption\Option<string> + */ + public function read(string $name) + { + return Option::fromArraysValue($this->variables, $name); + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + $this->variables[$name] = $value; + + return true; + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + unset($this->variables[$name]); + + return true; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/EnvConstAdapter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/EnvConstAdapter.php new file mode 100644 index 0000000..0fe62c3 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/EnvConstAdapter.php @@ -0,0 +1,88 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +use PhpOption\Option; +use PhpOption\Some; + +final class EnvConstAdapter implements AdapterInterface +{ + /** + * Create a new env const adapter instance. + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Create a new instance of the adapter, if it is available. + * + * @return \PhpOption\Option<self> + */ + public static function create() + { + return Some::create(new self()); + } + + /** + * Read an environment variable, if it exists. + * + * @param non-empty-string $name + * + * @return \PhpOption\Option<string> + */ + public function read(string $name) + { + /** @var \PhpOption\Option<scalar> */ + $value = Option::fromArraysValue($_ENV, $name) + ->filter(static function ($value) { + return \is_scalar($value); + }); + + return $value->map(static function ($value) { + if ($value === false) { + return 'false'; + } + + if ($value === true) { + return 'true'; + } + + return (string) $value; + }); + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + $_ENV[$name] = $value; + + return true; + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + unset($_ENV[$name]); + + return true; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/GuardedWriter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/GuardedWriter.php new file mode 100644 index 0000000..fed8b9b --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/GuardedWriter.php @@ -0,0 +1,85 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +final class GuardedWriter implements WriterInterface +{ + /** + * The inner writer to use. + * + * @var \Dotenv\Repository\Adapter\WriterInterface + */ + private $writer; + + /** + * The variable name allow list. + * + * @var string[] + */ + private $allowList; + + /** + * Create a new guarded writer instance. + * + * @param \Dotenv\Repository\Adapter\WriterInterface $writer + * @param string[] $allowList + * + * @return void + */ + public function __construct(WriterInterface $writer, array $allowList) + { + $this->writer = $writer; + $this->allowList = $allowList; + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + // Don't set non-allowed variables + if (!$this->isAllowed($name)) { + return false; + } + + // Set the value on the inner writer + return $this->writer->write($name, $value); + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + // Don't clear non-allowed variables + if (!$this->isAllowed($name)) { + return false; + } + + // Set the value on the inner writer + return $this->writer->delete($name); + } + + /** + * Determine if the given variable is allowed. + * + * @param non-empty-string $name + * + * @return bool + */ + private function isAllowed(string $name) + { + return \in_array($name, $this->allowList, true); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/ImmutableWriter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ImmutableWriter.php new file mode 100644 index 0000000..3b279b8 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ImmutableWriter.php @@ -0,0 +1,110 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +final class ImmutableWriter implements WriterInterface +{ + /** + * The inner writer to use. + * + * @var \Dotenv\Repository\Adapter\WriterInterface + */ + private $writer; + + /** + * The inner reader to use. + * + * @var \Dotenv\Repository\Adapter\ReaderInterface + */ + private $reader; + + /** + * The record of loaded variables. + * + * @var array<string, string> + */ + private $loaded; + + /** + * Create a new immutable writer instance. + * + * @param \Dotenv\Repository\Adapter\WriterInterface $writer + * @param \Dotenv\Repository\Adapter\ReaderInterface $reader + * + * @return void + */ + public function __construct(WriterInterface $writer, ReaderInterface $reader) + { + $this->writer = $writer; + $this->reader = $reader; + $this->loaded = []; + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + // Don't overwrite existing environment variables + // Ruby's dotenv does this with `ENV[key] ||= value` + if ($this->isExternallyDefined($name)) { + return false; + } + + // Set the value on the inner writer + if (!$this->writer->write($name, $value)) { + return false; + } + + // Record that we have loaded the variable + $this->loaded[$name] = ''; + + return true; + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + // Don't clear existing environment variables + if ($this->isExternallyDefined($name)) { + return false; + } + + // Clear the value on the inner writer + if (!$this->writer->delete($name)) { + return false; + } + + // Leave the variable as fair game + unset($this->loaded[$name]); + + return true; + } + + /** + * Determine if the given variable is externally defined. + * + * That is, is it an "existing" variable. + * + * @param non-empty-string $name + * + * @return bool + */ + private function isExternallyDefined(string $name) + { + return $this->reader->read($name)->isDefined() && !isset($this->loaded[$name]); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiReader.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiReader.php new file mode 100644 index 0000000..0cfda6f --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiReader.php @@ -0,0 +1,48 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +use PhpOption\None; + +final class MultiReader implements ReaderInterface +{ + /** + * The set of readers to use. + * + * @var \Dotenv\Repository\Adapter\ReaderInterface[] + */ + private $readers; + + /** + * Create a new multi-reader instance. + * + * @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers + * + * @return void + */ + public function __construct(array $readers) + { + $this->readers = $readers; + } + + /** + * Read an environment variable, if it exists. + * + * @param non-empty-string $name + * + * @return \PhpOption\Option<string> + */ + public function read(string $name) + { + foreach ($this->readers as $reader) { + $result = $reader->read($name); + if ($result->isDefined()) { + return $result; + } + } + + return None::create(); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiWriter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiWriter.php new file mode 100644 index 0000000..15a9d8f --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/MultiWriter.php @@ -0,0 +1,64 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +final class MultiWriter implements WriterInterface +{ + /** + * The set of writers to use. + * + * @var \Dotenv\Repository\Adapter\WriterInterface[] + */ + private $writers; + + /** + * Create a new multi-writer instance. + * + * @param \Dotenv\Repository\Adapter\WriterInterface[] $writers + * + * @return void + */ + public function __construct(array $writers) + { + $this->writers = $writers; + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + foreach ($this->writers as $writers) { + if (!$writers->write($name, $value)) { + return false; + } + } + + return true; + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + foreach ($this->writers as $writers) { + if (!$writers->delete($name)) { + return false; + } + } + + return true; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/PutenvAdapter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/PutenvAdapter.php new file mode 100644 index 0000000..8b6e5ea --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/PutenvAdapter.php @@ -0,0 +1,102 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +use PhpOption\None; +use PhpOption\Option; +use PhpOption\Some; + +final class PutenvAdapter implements AdapterInterface +{ + /** + * Create a new putenv adapter instance. + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Create a new instance of the adapter, if it is available. + * + * @return \PhpOption\Option<self> + */ + public static function create() + { + if (self::isSupported()) { + return Some::create(new self()); + } + + return None::create(); + } + + /** + * Determines if the adapter is supported. + * + * @return bool + */ + private static function isSupported() + { + return \function_exists('getenv') && \function_exists('putenv'); + } + + /** + * Read an environment variable, if it exists. + * + * @param non-empty-string $name + * + * @return \PhpOption\Option<string> + */ + public function read(string $name) + { + if (\strpos($name, "\0") !== false) { + return None::create(); + } + + /** @var \PhpOption\Option<string> */ + return Option::fromValue(\getenv($name), false)->filter(static function ($value) { + return \is_string($value); + }); + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + if (\strpos($name, "\0") !== false || \strpos($value, "\0") !== false) { + return false; + } + + \putenv("$name=$value"); + + return true; + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + if (\strpos($name, "\0") !== false) { + return false; + } + + \putenv($name); + + return true; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/ReaderInterface.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ReaderInterface.php new file mode 100644 index 0000000..306a63f --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ReaderInterface.php @@ -0,0 +1,17 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +interface ReaderInterface +{ + /** + * Read an environment variable, if it exists. + * + * @param non-empty-string $name + * + * @return \PhpOption\Option<string> + */ + public function read(string $name); +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/ReplacingWriter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ReplacingWriter.php new file mode 100644 index 0000000..4c92a4f --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ReplacingWriter.php @@ -0,0 +1,104 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +final class ReplacingWriter implements WriterInterface +{ + /** + * The inner writer to use. + * + * @var \Dotenv\Repository\Adapter\WriterInterface + */ + private $writer; + + /** + * The inner reader to use. + * + * @var \Dotenv\Repository\Adapter\ReaderInterface + */ + private $reader; + + /** + * The record of seen variables. + * + * @var array<string, string> + */ + private $seen; + + /** + * Create a new replacement writer instance. + * + * @param \Dotenv\Repository\Adapter\WriterInterface $writer + * @param \Dotenv\Repository\Adapter\ReaderInterface $reader + * + * @return void + */ + public function __construct(WriterInterface $writer, ReaderInterface $reader) + { + $this->writer = $writer; + $this->reader = $reader; + $this->seen = []; + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + if ($this->exists($name)) { + return $this->writer->write($name, $value); + } + + // succeed if nothing to do + return true; + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + if ($this->exists($name)) { + return $this->writer->delete($name); + } + + // succeed if nothing to do + return true; + } + + /** + * Does the given environment variable exist. + * + * Returns true if it currently exists, or existed at any point in the past + * that we are aware of. + * + * @param non-empty-string $name + * + * @return bool + */ + private function exists(string $name) + { + if (isset($this->seen[$name])) { + return true; + } + + if ($this->reader->read($name)->isDefined()) { + $this->seen[$name] = ''; + + return true; + } + + return false; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/ServerConstAdapter.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ServerConstAdapter.php new file mode 100644 index 0000000..41f2799 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/ServerConstAdapter.php @@ -0,0 +1,88 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +use PhpOption\Option; +use PhpOption\Some; + +final class ServerConstAdapter implements AdapterInterface +{ + /** + * Create a new server const adapter instance. + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Create a new instance of the adapter, if it is available. + * + * @return \PhpOption\Option<self> + */ + public static function create() + { + return Some::create(new self()); + } + + /** + * Read an environment variable, if it exists. + * + * @param non-empty-string $name + * + * @return \PhpOption\Option<string> + */ + public function read(string $name) + { + /** @var \PhpOption\Option<scalar> */ + $value = Option::fromArraysValue($_SERVER, $name) + ->filter(static function ($value) { + return \is_scalar($value); + }); + + return $value->map(static function ($value) { + if ($value === false) { + return 'false'; + } + + if ($value === true) { + return 'true'; + } + + return (string) $value; + }); + } + + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value) + { + $_SERVER[$name] = $value; + + return true; + } + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name) + { + unset($_SERVER[$name]); + + return true; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/Adapter/WriterInterface.php b/vendor/vlucas/phpdotenv/src/Repository/Adapter/WriterInterface.php new file mode 100644 index 0000000..4cb3d61 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/Adapter/WriterInterface.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository\Adapter; + +interface WriterInterface +{ + /** + * Write to an environment variable, if possible. + * + * @param non-empty-string $name + * @param string $value + * + * @return bool + */ + public function write(string $name, string $value); + + /** + * Delete an environment variable, if possible. + * + * @param non-empty-string $name + * + * @return bool + */ + public function delete(string $name); +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/AdapterRepository.php b/vendor/vlucas/phpdotenv/src/Repository/AdapterRepository.php new file mode 100644 index 0000000..e4b8fb7 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/AdapterRepository.php @@ -0,0 +1,107 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository; + +use Dotenv\Repository\Adapter\ReaderInterface; +use Dotenv\Repository\Adapter\WriterInterface; +use InvalidArgumentException; + +final class AdapterRepository implements RepositoryInterface +{ + /** + * The reader to use. + * + * @var \Dotenv\Repository\Adapter\ReaderInterface + */ + private $reader; + + /** + * The writer to use. + * + * @var \Dotenv\Repository\Adapter\WriterInterface + */ + private $writer; + + /** + * Create a new adapter repository instance. + * + * @param \Dotenv\Repository\Adapter\ReaderInterface $reader + * @param \Dotenv\Repository\Adapter\WriterInterface $writer + * + * @return void + */ + public function __construct(ReaderInterface $reader, WriterInterface $writer) + { + $this->reader = $reader; + $this->writer = $writer; + } + + /** + * Determine if the given environment variable is defined. + * + * @param string $name + * + * @return bool + */ + public function has(string $name) + { + return '' !== $name && $this->reader->read($name)->isDefined(); + } + + /** + * Get an environment variable. + * + * @param string $name + * + * @throws \InvalidArgumentException + * + * @return string|null + */ + public function get(string $name) + { + if ('' === $name) { + throw new InvalidArgumentException('Expected name to be a non-empty string.'); + } + + return $this->reader->read($name)->getOrElse(null); + } + + /** + * Set an environment variable. + * + * @param string $name + * @param string $value + * + * @throws \InvalidArgumentException + * + * @return bool + */ + public function set(string $name, string $value) + { + if ('' === $name) { + throw new InvalidArgumentException('Expected name to be a non-empty string.'); + } + + return $this->writer->write($name, $value); + } + + /** + * Clear an environment variable. + * + * @param string $name + * + * @throws \InvalidArgumentException + * + * @return bool + */ + public function clear(string $name) + { + if ('' === $name) { + throw new InvalidArgumentException('Expected name to be a non-empty string.'); + } + + return $this->writer->delete($name); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/RepositoryBuilder.php b/vendor/vlucas/phpdotenv/src/Repository/RepositoryBuilder.php new file mode 100644 index 0000000..75befc9 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/RepositoryBuilder.php @@ -0,0 +1,272 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository; + +use Dotenv\Repository\Adapter\AdapterInterface; +use Dotenv\Repository\Adapter\EnvConstAdapter; +use Dotenv\Repository\Adapter\GuardedWriter; +use Dotenv\Repository\Adapter\ImmutableWriter; +use Dotenv\Repository\Adapter\MultiReader; +use Dotenv\Repository\Adapter\MultiWriter; +use Dotenv\Repository\Adapter\ReaderInterface; +use Dotenv\Repository\Adapter\ServerConstAdapter; +use Dotenv\Repository\Adapter\WriterInterface; +use InvalidArgumentException; +use PhpOption\Some; +use ReflectionClass; + +final class RepositoryBuilder +{ + /** + * The set of default adapters. + */ + private const DEFAULT_ADAPTERS = [ + ServerConstAdapter::class, + EnvConstAdapter::class, + ]; + + /** + * The set of readers to use. + * + * @var \Dotenv\Repository\Adapter\ReaderInterface[] + */ + private $readers; + + /** + * The set of writers to use. + * + * @var \Dotenv\Repository\Adapter\WriterInterface[] + */ + private $writers; + + /** + * Are we immutable? + * + * @var bool + */ + private $immutable; + + /** + * The variable name allow list. + * + * @var string[]|null + */ + private $allowList; + + /** + * Create a new repository builder instance. + * + * @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers + * @param \Dotenv\Repository\Adapter\WriterInterface[] $writers + * @param bool $immutable + * @param string[]|null $allowList + * + * @return void + */ + private function __construct(array $readers = [], array $writers = [], bool $immutable = false, ?array $allowList = null) + { + $this->readers = $readers; + $this->writers = $writers; + $this->immutable = $immutable; + $this->allowList = $allowList; + } + + /** + * Create a new repository builder instance with no adapters added. + * + * @return \Dotenv\Repository\RepositoryBuilder + */ + public static function createWithNoAdapters() + { + return new self(); + } + + /** + * Create a new repository builder instance with the default adapters added. + * + * @return \Dotenv\Repository\RepositoryBuilder + */ + public static function createWithDefaultAdapters() + { + $adapters = \iterator_to_array(self::defaultAdapters()); + + return new self($adapters, $adapters); + } + + /** + * Return the array of default adapters. + * + * @return \Generator<\Dotenv\Repository\Adapter\AdapterInterface> + */ + private static function defaultAdapters() + { + foreach (self::DEFAULT_ADAPTERS as $adapter) { + $instance = $adapter::create(); + if ($instance->isDefined()) { + yield $instance->get(); + } + } + } + + /** + * Determine if the given name if of an adapterclass. + * + * @param string $name + * + * @return bool + */ + private static function isAnAdapterClass(string $name) + { + if (!\class_exists($name)) { + return false; + } + + return (new ReflectionClass($name))->implementsInterface(AdapterInterface::class); + } + + /** + * Creates a repository builder with the given reader added. + * + * Accepts either a reader instance, or a class-string for an adapter. If + * the adapter is not supported, then we silently skip adding it. + * + * @param \Dotenv\Repository\Adapter\ReaderInterface|class-string<\Dotenv\Repository\Adapter\AdapterInterface> $reader + * + * @throws \InvalidArgumentException + * + * @return \Dotenv\Repository\RepositoryBuilder + */ + public function addReader($reader) + { + if (!(\is_string($reader) && self::isAnAdapterClass($reader)) && !($reader instanceof ReaderInterface)) { + throw new InvalidArgumentException( + \sprintf( + 'Expected either an instance of %s or a class-string implementing %s', + ReaderInterface::class, + AdapterInterface::class + ) + ); + } + + $optional = Some::create($reader)->flatMap(static function ($reader) { + return \is_string($reader) ? $reader::create() : Some::create($reader); + }); + + $readers = \array_merge($this->readers, \iterator_to_array($optional)); + + return new self($readers, $this->writers, $this->immutable, $this->allowList); + } + + /** + * Creates a repository builder with the given writer added. + * + * Accepts either a writer instance, or a class-string for an adapter. If + * the adapter is not supported, then we silently skip adding it. + * + * @param \Dotenv\Repository\Adapter\WriterInterface|class-string<\Dotenv\Repository\Adapter\AdapterInterface> $writer + * + * @throws \InvalidArgumentException + * + * @return \Dotenv\Repository\RepositoryBuilder + */ + public function addWriter($writer) + { + if (!(\is_string($writer) && self::isAnAdapterClass($writer)) && !($writer instanceof WriterInterface)) { + throw new InvalidArgumentException( + \sprintf( + 'Expected either an instance of %s or a class-string implementing %s', + WriterInterface::class, + AdapterInterface::class + ) + ); + } + + $optional = Some::create($writer)->flatMap(static function ($writer) { + return \is_string($writer) ? $writer::create() : Some::create($writer); + }); + + $writers = \array_merge($this->writers, \iterator_to_array($optional)); + + return new self($this->readers, $writers, $this->immutable, $this->allowList); + } + + /** + * Creates a repository builder with the given adapter added. + * + * Accepts either an adapter instance, or a class-string for an adapter. If + * the adapter is not supported, then we silently skip adding it. We will + * add the adapter as both a reader and a writer. + * + * @param \Dotenv\Repository\Adapter\AdapterInterface|class-string<\Dotenv\Repository\Adapter\AdapterInterface> $adapter + * + * @throws \InvalidArgumentException + * + * @return \Dotenv\Repository\RepositoryBuilder + */ + public function addAdapter($adapter) + { + if (!(\is_string($adapter) && self::isAnAdapterClass($adapter)) && !($adapter instanceof AdapterInterface)) { + throw new InvalidArgumentException( + \sprintf( + 'Expected either an instance of %s or a class-string implementing %s', + AdapterInterface::class, + AdapterInterface::class + ) + ); + } + + $optional = Some::create($adapter)->flatMap(static function ($adapter) { + return \is_string($adapter) ? $adapter::create() : Some::create($adapter); + }); + + $readers = \array_merge($this->readers, \iterator_to_array($optional)); + $writers = \array_merge($this->writers, \iterator_to_array($optional)); + + return new self($readers, $writers, $this->immutable, $this->allowList); + } + + /** + * Creates a repository builder with immutability enabled. + * + * @return \Dotenv\Repository\RepositoryBuilder + */ + public function immutable() + { + return new self($this->readers, $this->writers, true, $this->allowList); + } + + /** + * Creates a repository builder with the given allow list. + * + * @param string[]|null $allowList + * + * @return \Dotenv\Repository\RepositoryBuilder + */ + public function allowList(?array $allowList = null) + { + return new self($this->readers, $this->writers, $this->immutable, $allowList); + } + + /** + * Creates a new repository instance. + * + * @return \Dotenv\Repository\RepositoryInterface + */ + public function make() + { + $reader = new MultiReader($this->readers); + $writer = new MultiWriter($this->writers); + + if ($this->immutable) { + $writer = new ImmutableWriter($writer, $reader); + } + + if ($this->allowList !== null) { + $writer = new GuardedWriter($writer, $this->allowList); + } + + return new AdapterRepository($reader, $writer); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Repository/RepositoryInterface.php b/vendor/vlucas/phpdotenv/src/Repository/RepositoryInterface.php new file mode 100644 index 0000000..d9b18a4 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Repository/RepositoryInterface.php @@ -0,0 +1,51 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Repository; + +interface RepositoryInterface +{ + /** + * Determine if the given environment variable is defined. + * + * @param string $name + * + * @return bool + */ + public function has(string $name); + + /** + * Get an environment variable. + * + * @param string $name + * + * @throws \InvalidArgumentException + * + * @return string|null + */ + public function get(string $name); + + /** + * Set an environment variable. + * + * @param string $name + * @param string $value + * + * @throws \InvalidArgumentException + * + * @return bool + */ + public function set(string $name, string $value); + + /** + * Clear an environment variable. + * + * @param string $name + * + * @throws \InvalidArgumentException + * + * @return bool + */ + public function clear(string $name); +} diff --git a/vendor/vlucas/phpdotenv/src/Store/File/Paths.php b/vendor/vlucas/phpdotenv/src/Store/File/Paths.php new file mode 100644 index 0000000..4f678a5 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Store/File/Paths.php @@ -0,0 +1,44 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Store\File; + +/** + * @internal + */ +final class Paths +{ + /** + * This class is a singleton. + * + * @codeCoverageIgnore + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Returns the full paths to the files. + * + * @param string[] $paths + * @param string[] $names + * + * @return string[] + */ + public static function filePaths(array $paths, array $names) + { + $files = []; + + foreach ($paths as $path) { + foreach ($names as $name) { + $files[] = \rtrim($path, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR.$name; + } + } + + return $files; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Store/File/Reader.php b/vendor/vlucas/phpdotenv/src/Store/File/Reader.php new file mode 100644 index 0000000..650b28b --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Store/File/Reader.php @@ -0,0 +1,81 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Store\File; + +use Dotenv\Exception\InvalidEncodingException; +use Dotenv\Util\Str; +use PhpOption\Option; + +/** + * @internal + */ +final class Reader +{ + /** + * This class is a singleton. + * + * @codeCoverageIgnore + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Read the file(s), and return their raw content. + * + * We provide the file path as the key, and its content as the value. If + * short circuit mode is enabled, then the returned array with have length + * at most one. File paths that couldn't be read are omitted entirely. + * + * @param string[] $filePaths + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @throws \Dotenv\Exception\InvalidEncodingException + * + * @return array<string, string> + */ + public static function read(array $filePaths, bool $shortCircuit = true, ?string $fileEncoding = null) + { + $output = []; + + foreach ($filePaths as $filePath) { + $content = self::readFromFile($filePath, $fileEncoding); + if ($content->isDefined()) { + $output[$filePath] = $content->get(); + if ($shortCircuit) { + break; + } + } + } + + return $output; + } + + /** + * Read the given file. + * + * @param string $path + * @param string|null $encoding + * + * @throws \Dotenv\Exception\InvalidEncodingException + * + * @return \PhpOption\Option<string> + */ + private static function readFromFile(string $path, ?string $encoding = null) + { + /** @var Option<string> */ + $content = Option::fromValue(@\file_get_contents($path), false); + + return $content->flatMap(static function (string $content) use ($encoding) { + return Str::utf8($content, $encoding)->mapError(static function (string $error) { + throw new InvalidEncodingException($error); + })->success(); + }); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Store/FileStore.php b/vendor/vlucas/phpdotenv/src/Store/FileStore.php new file mode 100644 index 0000000..93c5484 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Store/FileStore.php @@ -0,0 +1,72 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Store; + +use Dotenv\Exception\InvalidPathException; +use Dotenv\Store\File\Reader; + +final class FileStore implements StoreInterface +{ + /** + * The file paths. + * + * @var string[] + */ + private $filePaths; + + /** + * Should file loading short circuit? + * + * @var bool + */ + private $shortCircuit; + + /** + * The file encoding. + * + * @var string|null + */ + private $fileEncoding; + + /** + * Create a new file store instance. + * + * @param string[] $filePaths + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @return void + */ + public function __construct(array $filePaths, bool $shortCircuit, ?string $fileEncoding = null) + { + $this->filePaths = $filePaths; + $this->shortCircuit = $shortCircuit; + $this->fileEncoding = $fileEncoding; + } + + /** + * Read the content of the environment file(s). + * + * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidPathException + * + * @return string + */ + public function read() + { + if ($this->filePaths === []) { + throw new InvalidPathException('At least one environment file path and file name must be provided.'); + } + + $contents = Reader::read($this->filePaths, $this->shortCircuit, $this->fileEncoding); + + if (\count($contents) > 0) { + return \implode("\n", $contents); + } + + throw new InvalidPathException( + \sprintf('Unable to read any of the environment file(s) at [%s].', \implode(', ', $this->filePaths)) + ); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Store/StoreBuilder.php b/vendor/vlucas/phpdotenv/src/Store/StoreBuilder.php new file mode 100644 index 0000000..2ce0851 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Store/StoreBuilder.php @@ -0,0 +1,141 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Store; + +use Dotenv\Store\File\Paths; + +final class StoreBuilder +{ + /** + * The of default name. + */ + private const DEFAULT_NAME = '.env'; + + /** + * The paths to search within. + * + * @var string[] + */ + private $paths; + + /** + * The file names to search for. + * + * @var string[] + */ + private $names; + + /** + * Should file loading short circuit? + * + * @var bool + */ + private $shortCircuit; + + /** + * The file encoding. + * + * @var string|null + */ + private $fileEncoding; + + /** + * Create a new store builder instance. + * + * @param string[] $paths + * @param string[] $names + * @param bool $shortCircuit + * @param string|null $fileEncoding + * + * @return void + */ + private function __construct(array $paths = [], array $names = [], bool $shortCircuit = false, ?string $fileEncoding = null) + { + $this->paths = $paths; + $this->names = $names; + $this->shortCircuit = $shortCircuit; + $this->fileEncoding = $fileEncoding; + } + + /** + * Create a new store builder instance with no names. + * + * @return \Dotenv\Store\StoreBuilder + */ + public static function createWithNoNames() + { + return new self(); + } + + /** + * Create a new store builder instance with the default name. + * + * @return \Dotenv\Store\StoreBuilder + */ + public static function createWithDefaultName() + { + return new self([], [self::DEFAULT_NAME]); + } + + /** + * Creates a store builder with the given path added. + * + * @param string $path + * + * @return \Dotenv\Store\StoreBuilder + */ + public function addPath(string $path) + { + return new self(\array_merge($this->paths, [$path]), $this->names, $this->shortCircuit, $this->fileEncoding); + } + + /** + * Creates a store builder with the given name added. + * + * @param string $name + * + * @return \Dotenv\Store\StoreBuilder + */ + public function addName(string $name) + { + return new self($this->paths, \array_merge($this->names, [$name]), $this->shortCircuit, $this->fileEncoding); + } + + /** + * Creates a store builder with short circuit mode enabled. + * + * @return \Dotenv\Store\StoreBuilder + */ + public function shortCircuit() + { + return new self($this->paths, $this->names, true, $this->fileEncoding); + } + + /** + * Creates a store builder with the specified file encoding. + * + * @param string|null $fileEncoding + * + * @return \Dotenv\Store\StoreBuilder + */ + public function fileEncoding(?string $fileEncoding = null) + { + return new self($this->paths, $this->names, $this->shortCircuit, $fileEncoding); + } + + /** + * Creates a new store instance. + * + * @return \Dotenv\Store\StoreInterface + */ + public function make() + { + return new FileStore( + Paths::filePaths($this->paths, $this->names), + $this->shortCircuit, + $this->fileEncoding + ); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Store/StoreInterface.php b/vendor/vlucas/phpdotenv/src/Store/StoreInterface.php new file mode 100644 index 0000000..6f5b986 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Store/StoreInterface.php @@ -0,0 +1,17 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Store; + +interface StoreInterface +{ + /** + * Read the content of the environment file(s). + * + * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidPathException + * + * @return string + */ + public function read(); +} diff --git a/vendor/vlucas/phpdotenv/src/Store/StringStore.php b/vendor/vlucas/phpdotenv/src/Store/StringStore.php new file mode 100644 index 0000000..b78a5c6 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Store/StringStore.php @@ -0,0 +1,41 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Store; + +final class StringStore implements StoreInterface +{ + /** + * The file content. + * + * @var string + */ + private $content; + + /** + * Create a new string store instance. + * + * @param string $content + * + * @return void + */ + public function __construct(string $content) + { + $this->content = $content; + } + + /** + * Read the content of the environment file(s). + * + * @return string + */ + public function read() + { + if (\substr($this->content, 0, 3) === "\xEF\xBB\xBF") { + return \substr($this->content, 3); + } + + return $this->content; + } +} diff --git a/vendor/vlucas/phpdotenv/src/Util/Regex.php b/vendor/vlucas/phpdotenv/src/Util/Regex.php new file mode 100644 index 0000000..1240427 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Util/Regex.php @@ -0,0 +1,101 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Util; + +use GrahamCampbell\ResultType\Error; +use GrahamCampbell\ResultType\Success; + +/** + * @internal + */ +final class Regex +{ + /** + * This class is a singleton. + * + * @codeCoverageIgnore + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Perform a preg match, wrapping up the result. + * + * @param string $pattern + * @param string $subject + * + * @return \GrahamCampbell\ResultType\Result<bool, string> + */ + public static function matches(string $pattern, string $subject) + { + return self::wrap(@\preg_match($pattern, $subject) === 1); + } + + /** + * Perform a preg match all, wrapping up the result. + * + * @param string $pattern + * @param string $subject + * + * @return \GrahamCampbell\ResultType\Result<int<0, max>, string> + */ + public static function occurrences(string $pattern, string $subject) + { + return self::wrap((int) @\preg_match_all($pattern, $subject)); + } + + /** + * Perform a preg replace callback, wrapping up the result. + * + * @param string $pattern + * @param callable(string[]): string $callback + * @param string $subject + * @param int|null $limit + * + * @return \GrahamCampbell\ResultType\Result<string, string> + */ + public static function replaceCallback(string $pattern, callable $callback, string $subject, ?int $limit = null) + { + return self::wrap((string) @\preg_replace_callback($pattern, $callback, $subject, $limit ?? -1)); + } + + /** + * Perform a preg split, wrapping up the result. + * + * @param string $pattern + * @param string $subject + * + * @return \GrahamCampbell\ResultType\Result<string[], string> + */ + public static function split(string $pattern, string $subject) + { + /** @var string[] */ + $result = (array) @\preg_split($pattern, $subject); + + return self::wrap($result); + } + + /** + * Wrap the result of a preg operation. + * + * @template V + * + * @param V $result + * + * @return \GrahamCampbell\ResultType\Result<V, string> + */ + private static function wrap($result) + { + if (\preg_last_error() !== \PREG_NO_ERROR) { + return Error::create(\preg_last_error_msg()); + } + + return Success::create($result); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Util/Str.php b/vendor/vlucas/phpdotenv/src/Util/Str.php new file mode 100644 index 0000000..f408f63 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Util/Str.php @@ -0,0 +1,129 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv\Util; + +use GrahamCampbell\ResultType\Error; +use GrahamCampbell\ResultType\Success; +use PhpOption\Option; + +/** + * @internal + */ +final class Str +{ + /** + * This class is a singleton. + * + * @codeCoverageIgnore + * + * @return void + */ + private function __construct() + { + // + } + + /** + * Convert a string to UTF-8 from the given encoding. + * + * @param string $input + * @param string|null $encoding + * + * @return \GrahamCampbell\ResultType\Result<string, string> + */ + public static function utf8(string $input, ?string $encoding = null) + { + if ($encoding !== null && !self::isValidEncoding($encoding)) { + return Error::create( + \sprintf('Illegal character encoding [%s] specified.', $encoding) + ); + } + + $converted = $encoding === null ? + @\mb_convert_encoding($input, 'UTF-8') : + @\mb_convert_encoding($input, 'UTF-8', $encoding); + + if (!is_string($converted)) { + return Error::create( + \sprintf('Conversion from encoding [%s] failed.', $encoding ?? 'NULL') + ); + } + + /** + * this is for support UTF-8 with BOM encoding + * @see https://en.wikipedia.org/wiki/Byte_order_mark + * @see https://github.com/vlucas/phpdotenv/issues/500 + */ + if (\substr($converted, 0, 3) === "\xEF\xBB\xBF") { + $converted = \substr($converted, 3); + } + + return Success::create($converted); + } + + /** + * Is the given character encoding valid? + * + * @param string $encoding + * + * @return bool + */ + private static function isValidEncoding(string $encoding) + { + foreach (\mb_list_encodings() as $candidate) { + if (\strcasecmp($candidate, $encoding) === 0) { + return true; + } + + foreach (@\mb_encoding_aliases($candidate) as $alias) { + if (\strcasecmp($alias, $encoding) === 0) { + return true; + } + } + } + + return false; + } + + /** + * Search for a given substring of the input. + * + * @param string $haystack + * @param string $needle + * + * @return \PhpOption\Option<int<0, max>> + */ + public static function pos(string $haystack, string $needle) + { + /** @var \PhpOption\Option<int<0, max>> */ + return Option::fromValue(\mb_strpos($haystack, $needle, 0, 'UTF-8'), false); + } + + /** + * Grab the specified substring of the input. + * + * @param string $input + * @param int $start + * @param int|null $length + * + * @return string + */ + public static function substr(string $input, int $start, ?int $length = null) + { + return \mb_substr($input, $start, $length, 'UTF-8'); + } + + /** + * Compute the length of the given string. + * + * @param string $input + * + * @return int + */ + public static function len(string $input) + { + return \mb_strlen($input, 'UTF-8'); + } +} diff --git a/vendor/vlucas/phpdotenv/src/Validator.php b/vendor/vlucas/phpdotenv/src/Validator.php new file mode 100644 index 0000000..efea122 --- /dev/null +++ b/vendor/vlucas/phpdotenv/src/Validator.php @@ -0,0 +1,216 @@ +<?php + +declare(strict_types=1); + +namespace Dotenv; + +use Dotenv\Exception\ValidationException; +use Dotenv\Repository\RepositoryInterface; +use Dotenv\Util\Regex; +use Dotenv\Util\Str; + +class Validator +{ + /** + * The environment repository instance. + * + * @var \Dotenv\Repository\RepositoryInterface + */ + private $repository; + + /** + * The variables to validate. + * + * @var string[] + */ + private $variables; + + /** + * Create a new validator instance. + * + * @param \Dotenv\Repository\RepositoryInterface $repository + * @param string[] $variables + * + * @return void + */ + public function __construct(RepositoryInterface $repository, array $variables) + { + $this->repository = $repository; + $this->variables = $variables; + } + + /** + * Assert that each variable is present. + * + * @throws \Dotenv\Exception\ValidationException + * + * @return \Dotenv\Validator + */ + public function required() + { + return $this->assert( + static function (?string $value) { + return $value !== null; + }, + 'is missing' + ); + } + + /** + * Assert that each variable is not empty. + * + * @throws \Dotenv\Exception\ValidationException + * + * @return \Dotenv\Validator + */ + public function notEmpty() + { + return $this->assertNullable( + static function (string $value) { + return Str::len(\trim($value, " \n\r\t\0\x0B")) > 0; + }, + 'is empty' + ); + } + + /** + * Assert that each specified variable is an integer. + * + * @throws \Dotenv\Exception\ValidationException + * + * @return \Dotenv\Validator + */ + public function isInteger() + { + return $this->assertNullable( + static function (string $value) { + return \ctype_digit($value); + }, + 'is not an integer' + ); + } + + /** + * Assert that each specified variable is a boolean. + * + * @throws \Dotenv\Exception\ValidationException + * + * @return \Dotenv\Validator + */ + public function isBoolean() + { + return $this->assertNullable( + static function (string $value) { + if ($value === '') { + return false; + } + + return \filter_var($value, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) !== null; + }, + 'is not a boolean' + ); + } + + /** + * Assert that each variable is amongst the given choices. + * + * @param string[] $choices + * + * @throws \Dotenv\Exception\ValidationException + * + * @return \Dotenv\Validator + */ + public function allowedValues(array $choices) + { + return $this->assertNullable( + static function (string $value) use ($choices) { + return \in_array($value, $choices, true); + }, + \sprintf('is not one of [%s]', \implode(', ', $choices)) + ); + } + + /** + * Assert that each variable matches the given regular expression. + * + * @param string $regex + * + * @throws \Dotenv\Exception\ValidationException + * + * @return \Dotenv\Validator + */ + public function allowedRegexValues(string $regex) + { + if (@\preg_match($regex, '') === false && \preg_last_error() === \PREG_INTERNAL_ERROR) { + return $this->assertNullable( + static function (string $value) { + return false; + }, + \sprintf('could not be validated against the invalid regular expression "%s"', $regex) + ); + } + + return $this->assertNullable( + static function (string $value) use ($regex) { + return Regex::matches($regex, $value)->success()->getOrElse(false); + }, + \sprintf('does not match "%s"', $regex) + ); + } + + /** + * Assert that the callback returns true for each variable. + * + * @param callable(?string):bool $callback + * @param string $message + * + * @throws \Dotenv\Exception\ValidationException + * + * @return \Dotenv\Validator + */ + public function assert(callable $callback, string $message) + { + $failing = []; + + foreach ($this->variables as $variable) { + if ($callback($this->repository->get($variable)) === false) { + $failing[] = \sprintf('%s %s', $variable, $message); + } + } + + if (\count($failing) > 0) { + throw new ValidationException(\sprintf( + 'One or more environment variables failed assertions: %s.', + \implode(', ', $failing) + )); + } + + return $this; + } + + /** + * Assert that the callback returns true for each variable. + * + * Skip checking null variable values. + * + * @param callable(string):bool $callback + * @param string $message + * + * @throws \Dotenv\Exception\ValidationException + * + * @return \Dotenv\Validator + */ + public function assertNullable(callable $callback, string $message) + { + return $this->assert( + static function (?string $value) use ($callback) { + if ($value === null) { + return true; + } + + return $callback($value); + }, + $message + ); + } +} diff --git a/vendor/workerman/coroutine/.gitignore b/vendor/workerman/coroutine/.gitignore new file mode 100644 index 0000000..68b9b27 --- /dev/null +++ b/vendor/workerman/coroutine/.gitignore @@ -0,0 +1,5 @@ +composer.lock +vendor +.idea +tests/.phpunit.result.cache +tests/workerman.log \ No newline at end of file diff --git a/vendor/workerman/coroutine/LICENSE b/vendor/workerman/coroutine/LICENSE new file mode 100644 index 0000000..62e1f43 --- /dev/null +++ b/vendor/workerman/coroutine/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 workerman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/workerman/coroutine/README.md b/vendor/workerman/coroutine/README.md new file mode 100644 index 0000000..ed2ebbe --- /dev/null +++ b/vendor/workerman/coroutine/README.md @@ -0,0 +1,3 @@ +# Workerman coroutine library + +This is Workerman's coroutine library, which includes `Coroutine` `Channel` `Barrier` `Parallel` `Pool`. \ No newline at end of file diff --git a/vendor/workerman/coroutine/composer.json b/vendor/workerman/coroutine/composer.json new file mode 100644 index 0000000..7a5b7c3 --- /dev/null +++ b/vendor/workerman/coroutine/composer.json @@ -0,0 +1,32 @@ +{ + "name": "workerman/coroutine", + "type": "library", + "license": "MIT", + "description": "Workerman coroutine", + "require": { + "php": ">=8.1", + "workerman/workerman": "^5.1" + }, + "autoload": { + "psr-4": { + "Workerman\\Coroutine\\": "src", + "Workerman\\": "src" + } + }, + "require-dev": { + "phpunit/phpunit": "^11.0", + "psr/log": "*" + }, + "autoload-dev": { + "psr-4": { + "Workerman\\Coroutine\\": "src", + "Workerman\\": "src", + "tests\\": "tests" + } + }, + "scripts": { + "test": "php tests/start.php start" + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/vendor/workerman/coroutine/src/Barrier.php b/vendor/workerman/coroutine/src/Barrier.php new file mode 100644 index 0000000..4b19004 --- /dev/null +++ b/vendor/workerman/coroutine/src/Barrier.php @@ -0,0 +1,65 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine; + +use Workerman\Coroutine\Barrier\BarrierInterface; +use Workerman\Events\Swoole; +use Workerman\Events\Swow; +use Workerman\Worker; + +/** + * Class Barrier + */ +class Barrier implements BarrierInterface +{ + + /** + * @var string + */ + protected static string $driver; + + /** + * Get driver. + * + * @return string + */ + protected static function getDriver(): string + { + return static::$driver ??= match (Worker::$eventLoopClass) { + Swoole::class => Barrier\Swoole::class, + Swow::class => Barrier\Swow::class, + default=> Barrier\Fiber::class, + }; + } + + /** + * @inheritDoc + */ + public static function wait(object &$barrier, int $timeout = -1): void + { + static::getDriver()::wait($barrier, $timeout); + } + + /** + * @inheritDoc + */ + public static function create(): object + { + return static::getDriver()::create(); + } + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Barrier/BarrierInterface.php b/vendor/workerman/coroutine/src/Barrier/BarrierInterface.php new file mode 100644 index 0000000..8ae4b8f --- /dev/null +++ b/vendor/workerman/coroutine/src/Barrier/BarrierInterface.php @@ -0,0 +1,39 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Barrier; + +/** + * Interface BarrierInterface + */ +interface BarrierInterface +{ + /** + * Wait for the barrier to be released. + * + * @param object $barrier + * @param int $timeout + * @return void + */ + public static function wait(object &$barrier, int $timeout = -1): void; + + /** + * Create a new barrier instance. + * + * @return BarrierInterface + */ + public static function create(): object; +} diff --git a/vendor/workerman/coroutine/src/Barrier/Fiber.php b/vendor/workerman/coroutine/src/Barrier/Fiber.php new file mode 100644 index 0000000..f33222a --- /dev/null +++ b/vendor/workerman/coroutine/src/Barrier/Fiber.php @@ -0,0 +1,85 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Barrier; + +use Revolt\EventLoop; +use RuntimeException; +use Workerman\Coroutine\Utils\DestructionWatcher; +use Workerman\Timer; +use Fiber as BaseFiber; +use Workerman\Worker; + +/** + * Class Fiber + */ +class Fiber implements BarrierInterface +{ + + /** + * @inheritDoc + */ + public static function wait(object &$barrier, int $timeout = -1): void + { + $coroutine = BaseFiber::getCurrent(); + $resumed = false; + $timerId = null; + + if ($timeout > 0 && $coroutine) { + $timerId = Timer::delay($timeout, function() use ($coroutine, &$resumed) { + if (!$resumed) { + $resumed = true; + $coroutine->resume(); + } + }); + } + + $coroutine && DestructionWatcher::watch($barrier, function() use ($coroutine, &$resumed, &$timerId) { + if (!$resumed) { + $resumed = true; + if ($timerId !== null) { + Timer::del($timerId); + } + // In PHP 8.4.0 and earlier, + // switching fibers during the execution of an object's destructor method is not allowed, + // so we implemented a delay. + if ($coroutine instanceof BaseFiber) { + Timer::delay(0.00001, function() use ($coroutine) { + $coroutine->resume(); + }); + return; + } + EventLoop::defer(function () use ($coroutine) { + $coroutine->resume(); + }); + } + }); + $barrier = null; + $coroutine && BaseFiber::suspend(); + } + + /** + * @inheritDoc + */ + public static function create(): object + { + if (!Worker::isRunning()) { + throw new RuntimeException('Fiber barrier only support in workerman runtime'); + } + return new self(); + } + +} diff --git a/vendor/workerman/coroutine/src/Barrier/Swoole.php b/vendor/workerman/coroutine/src/Barrier/Swoole.php new file mode 100644 index 0000000..d140691 --- /dev/null +++ b/vendor/workerman/coroutine/src/Barrier/Swoole.php @@ -0,0 +1,39 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Barrier; + +use Swoole\Coroutine\Barrier as SwooleBarrier; +class Swoole implements BarrierInterface +{ + + /** + * @inheritDoc + */ + public static function wait(object &$barrier, int $timeout = -1): void + { + SwooleBarrier::wait($barrier, $timeout); + } + + /** + * @inheritDoc + */ + public static function create(): object + { + return SwooleBarrier::make(); + } + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Barrier/Swow.php b/vendor/workerman/coroutine/src/Barrier/Swow.php new file mode 100644 index 0000000..5686cb2 --- /dev/null +++ b/vendor/workerman/coroutine/src/Barrier/Swow.php @@ -0,0 +1,47 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Barrier; + +use Swow\Errno; +use Swow\Sync\WaitReference; +use Swow\SyncException; + +class Swow implements BarrierInterface +{ + /** + * @inheritDoc + */ + public static function wait(object &$barrier, int $timeout = -1): void + { + try { + WaitReference::wait($barrier, $timeout > 0 ? $timeout * 1000 : -1); + } catch (SyncException $exception) { + if ($exception->getCode() !== Errno::ETIMEDOUT) { + throw $exception; + } + } + } + + /** + * @inheritDoc + */ + public static function create(): object + { + return new WaitReference(); + } + +} diff --git a/vendor/workerman/coroutine/src/Channel.php b/vendor/workerman/coroutine/src/Channel.php new file mode 100644 index 0000000..de5cc2f --- /dev/null +++ b/vendor/workerman/coroutine/src/Channel.php @@ -0,0 +1,114 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine; + +use InvalidArgumentException; +use Workerman\Coroutine\Channel\ChannelInterface; +use Workerman\Coroutine\Channel\Memory as ChannelMemory; +use Workerman\Coroutine\Channel\Swoole as ChannelSwoole; +use Workerman\Coroutine\Channel\Swow as ChannelSwow; +use Workerman\Coroutine\Channel\Fiber as ChannelFiber; +use Workerman\Events\Fiber; +use Workerman\Events\Swoole; +use Workerman\Events\Swow; +use Workerman\Worker; + +/** + * Class Channel + */ +class Channel implements ChannelInterface +{ + + /** + * @var ChannelInterface + */ + protected ChannelInterface $driver; + + /** + * Channel constructor. + * + * @param int $capacity + */ + public function __construct(int $capacity = 1) + { + if ($capacity < 1) { + throw new InvalidArgumentException("The capacity must be greater than 0"); + } + $this->driver = match (Worker::$eventLoopClass) { + Swoole::class => new ChannelSwoole($capacity), + Swow::class => new ChannelSwow($capacity), + Fiber::class => new ChannelFiber($capacity), + default => new ChannelMemory($capacity), + }; + } + + /** + * @inheritDoc + */ + public function push(mixed $data, float $timeout = -1): bool + { + return $this->driver->push($data, $timeout); + } + + /** + * @inheritDoc + */ + public function pop(float $timeout = -1): mixed + { + return $this->driver->pop($timeout); + } + + /** + * @inheritDoc + */ + public function length(): int + { + return $this->driver->length(); + } + + /** + * @inheritDoc + */ + public function getCapacity(): int + { + return $this->driver->getCapacity(); + } + + /** + * @inheritDoc + */ + public function hasConsumers(): bool + { + return $this->driver->hasConsumers(); + } + + /** + * @inheritDoc + */ + public function hasProducers(): bool + { + return $this->driver->hasProducers(); + } + + /** + * @inheritDoc + */ + public function close(): void + { + $this->driver->close(); + } +} diff --git a/vendor/workerman/coroutine/src/Channel/ChannelInterface.php b/vendor/workerman/coroutine/src/Channel/ChannelInterface.php new file mode 100644 index 0000000..bbde495 --- /dev/null +++ b/vendor/workerman/coroutine/src/Channel/ChannelInterface.php @@ -0,0 +1,76 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Channel; + +/** + * ChannelInterface + */ +interface ChannelInterface +{ + /** + * Push data to channel. + * + * @param mixed $data + * @param float $timeout + * @return bool + */ + public function push(mixed $data, float $timeout = -1): bool; + + /** + * Pop data from channel. + * + * @param float $timeout + * @return mixed + */ + public function pop(float $timeout = -1): mixed; + + /** + * Get the length of channel. + * + * @return int + */ + public function length(): int; + + /** + * Get the capacity of channel. + * + * @return int + */ + public function getCapacity(): int; + + /** + * Check if there are consumers waiting to pop data from the channel. + * + * @return bool + */ + public function hasConsumers(): bool; + + /** + * Check if there are producers waiting to push data to the channel. + * + * @return bool + */ + public function hasProducers(): bool; + + /** + * Close the channel. + * + * @return void + */ + public function close(): void; + +} diff --git a/vendor/workerman/coroutine/src/Channel/Fiber.php b/vendor/workerman/coroutine/src/Channel/Fiber.php new file mode 100644 index 0000000..9bace9d --- /dev/null +++ b/vendor/workerman/coroutine/src/Channel/Fiber.php @@ -0,0 +1,252 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Channel; + +use Fiber as BaseFiber; +use RuntimeException; +use Workerman\Timer; +use WeakMap; +use Workerman\Worker; + +/** + * Channel + */ +class Fiber implements ChannelInterface +{ + /** + * @var array + */ + private array $queue = []; + + /** + * @var WeakMap + */ + private WeakMap $waitingPush; + + /** + * @var WeakMap + */ + private WeakMap $waitingPop; + + /** + * @var int + */ + private int $capacity; + + /** + * @var bool + */ + private bool $closed = false; + + /** + * Constructor + * + * @param int $capacity + */ + public function __construct(int $capacity = 1) + { + $this->capacity = $capacity; + $this->waitingPush = new WeakMap(); + $this->waitingPop = new WeakMap(); + } + + /** + * @inheritDoc + */ + public function push(mixed $data, float $timeout = -1): bool + { + if ($this->closed) { + return false; + } + + if (count($this->queue) >= $this->capacity) { + + if ($timeout == 0) { + return false; + } + + $fiber = BaseFiber::getCurrent(); + if ($fiber === null) { + throw new RuntimeException("Fiber::getCurrent() returned null. Ensure this method is called within a Fiber context."); + } + + $this->waitingPush[$fiber] = true; + + $timedOut = false; + $timerId = null; + if ($timeout > 0 && Worker::isRunning()) { + $timerId = Timer::delay($timeout, function () use ($fiber, &$timedOut) { + $timedOut = true; + if ($fiber->isSuspended()) { + unset($this->waitingPush[$fiber]); + $fiber->resume(false); + } + }); + } + + BaseFiber::suspend(); + unset($this->waitingPush[$fiber]); + + if (!$timedOut && $timerId) { + Timer::del($timerId); + } + + if ($timedOut) { + return false; + } + + // If the channel is closed while waiting, return false. + if ($this->closed) { + return false; + } + + } + + foreach ($this->waitingPop as $popFiber => $_) { + unset($this->waitingPop[$popFiber]); + if ($popFiber->isSuspended()) { + $popFiber->resume($data); + return true; + } + } + + $this->queue[] = $data; + return true; + } + + /** + * @inheritDoc + */ + public function pop(float $timeout = -1): mixed + { + if ($this->closed && empty($this->queue)) { + return false; + } + + if (empty($this->queue)) { + if ($timeout == 0) { + return false; + } + + $fiber = BaseFiber::getCurrent(); + if ($fiber === null) { + throw new RuntimeException("Fiber::getCurrent() returned null. Ensure this method is called within a Fiber context."); + } + + $this->waitingPop[$fiber] = true; + + $timedOut = false; + $timerId = null; + if ($timeout > 0) { + Worker::isRunning() && $timerId = Timer::delay($timeout, function () use ($fiber, &$timedOut) { + $timedOut = true; + if ($fiber->isSuspended()) { + unset($this->waitingPop[$fiber]); + $fiber->resume(false); + } + }); + } + + $data = BaseFiber::suspend(); + + unset($this->waitingPop[$fiber]); + + if (!$timedOut && $timerId !== null) { + Timer::del($timerId); + } + + if ($timedOut) { + return false; + } + + if ($data === false && $this->closed) { + return false; + } + + return $data; + } + + $value = array_shift($this->queue); + + foreach ($this->waitingPush as $pushFiber => $_) { + unset($this->waitingPush[$pushFiber]); + if ($pushFiber->isSuspended()) { + $pushFiber->resume(); + break; + } + } + + return $value; + } + + /** + * @inheritDoc + */ + public function length(): int + { + return count($this->queue); + } + + /** + * @inheritDoc + */ + public function getCapacity(): int + { + return $this->capacity; + } + + /** + * @inheritDoc + */ + public function hasConsumers(): bool + { + return count($this->waitingPop) > 0; + } + + /** + * @inheritDoc + */ + public function hasProducers(): bool + { + return count($this->waitingPush) > 0; + } + + /** + * @inheritDoc + */ + public function close(): void + { + $this->closed = true; + + foreach ($this->waitingPush as $fiber => $_) { + unset($this->waitingPush[$fiber]); + if ($fiber->isSuspended()) { + $fiber->resume(false); + } + } + $this->waitingPush = new WeakMap(); + + foreach ($this->waitingPop as $fiber => $_) { + unset($this->waitingPop[$fiber]); + if ($fiber->isSuspended()) { + $fiber->resume(false); + } + } + $this->waitingPop = new WeakMap(); + } + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Channel/Memory.php b/vendor/workerman/coroutine/src/Channel/Memory.php new file mode 100644 index 0000000..2d52bf5 --- /dev/null +++ b/vendor/workerman/coroutine/src/Channel/Memory.php @@ -0,0 +1,69 @@ +<?php + +declare(strict_types=1); + +namespace Workerman\Coroutine\Channel; + +class Memory implements ChannelInterface +{ + private array $data = []; + private int $capacity; + private bool $closed = false; + + public function __construct(int $capacity = 0) + { + $this->capacity = $capacity; + } + + public function push(mixed $data, float $timeout = -1): bool + { + if ($this->closed) { + return false; + } + if ($this->capacity > 0 && count($this->data) >= $this->capacity) { + // Channel is full + return false; + } + $this->data[] = $data; + return true; + } + + public function pop(float $timeout = -1): mixed + { + if (count($this->data) > 0) { + return array_shift($this->data); + } + return false; + } + + public function length(): int + { + return count($this->data); + } + + public function getCapacity(): int + { + return $this->capacity; + } + + /** + * @inheritDoc + */ + public function hasConsumers(): bool + { + return false; + } + + /** + * @inheritDoc + */ + public function hasProducers(): bool + { + return false; + } + + public function close(): void + { + $this->closed = true; + } +} diff --git a/vendor/workerman/coroutine/src/Channel/Swoole.php b/vendor/workerman/coroutine/src/Channel/Swoole.php new file mode 100644 index 0000000..b6a4d47 --- /dev/null +++ b/vendor/workerman/coroutine/src/Channel/Swoole.php @@ -0,0 +1,165 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Channel; + +use Closure; +use RuntimeException; +use Swoole\Coroutine; +use Swoole\Coroutine\Channel; + +/** + * Class Swoole + */ +class Swoole implements ChannelInterface +{ + + /** + * @var Channel + */ + protected Channel $channel; + + /** + * Whether PHP has entered the shutdown phase, null until the shutdown handler is registered. + * + * Once shutdown functions have run, objects are destructed in arbitrary order, so the Swoole channel + * may already be destroyed, and calling a destroyed channel is an uncatchable fatal error. + * + * @var bool|null + */ + private static ?bool $shuttingDown = null; + + /** + * Constructor. + * + * @param int $capacity + */ + public function __construct(protected int $capacity = 1) + { + $this->channel = new Channel($capacity); + if (self::$shuttingDown === null) { + self::$shuttingDown = false; + register_shutdown_function(static fn () => self::$shuttingDown = true); + } + } + + /** + * @inheritDoc + */ + public function push(mixed $data, float $timeout = -1): bool + { + if (Coroutine::getCid() > 0) { + // Swoole treats a zero timeout as waiting forever. + if ($timeout == 0 && $this->channel->isFull()) { + return false; + } + return $this->channel->push($data, $timeout); + } + if (self::$shuttingDown) { + return false; + } + if ($this->channel->isFull()) { + if ($timeout == 0) { + return false; + } + throw new RuntimeException('Blocking push on a full channel must be called within a coroutine.'); + } + return $this->runInCoroutine(fn () => $this->channel->push($data)); + } + + /** + * @inheritDoc + */ + public function pop(float $timeout = -1): mixed + { + if (Coroutine::getCid() > 0) { + // Swoole treats a zero timeout as waiting forever. + if ($timeout == 0 && $this->channel->isEmpty()) { + return false; + } + return $this->channel->pop($timeout); + } + if (self::$shuttingDown) { + return false; + } + if ($this->channel->isEmpty()) { + if ($timeout == 0) { + return false; + } + throw new RuntimeException('Blocking pop on an empty channel must be called within a coroutine.'); + } + return $this->runInCoroutine(fn () => $this->channel->pop()); + } + + /** + * Run a non-blocking channel operation outside a coroutine. + * + * Swoole channel APIs raise an uncatchable fatal error outside a coroutine, so the operation + * runs in a short-lived coroutine, which completes synchronously because it never yields. + * + * @param Closure $operation + * @return mixed + */ + private function runInCoroutine(Closure $operation): mixed + { + $result = false; + Coroutine::create(function () use ($operation, &$result) { + $result = $operation(); + }); + return $result; + } + + /** + * @inheritDoc + */ + public function length(): int + { + return $this->channel->length(); + } + + /** + * @inheritDoc + */ + public function getCapacity(): int + { + return $this->channel->capacity; + } + + /** + * @inheritDoc + */ + public function hasConsumers(): bool + { + return $this->channel->stats()['consumer_num'] > 0; + } + + /** + * @inheritDoc + */ + public function hasProducers(): bool + { + return $this->channel->stats()['producer_num'] > 0; + } + + /** + * @inheritDoc + */ + public function close(): void + { + $this->channel->close(); + } + +} diff --git a/vendor/workerman/coroutine/src/Channel/Swow.php b/vendor/workerman/coroutine/src/Channel/Swow.php new file mode 100644 index 0000000..2fef1cd --- /dev/null +++ b/vendor/workerman/coroutine/src/Channel/Swow.php @@ -0,0 +1,110 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Channel; + +use Swow\Channel; +use Throwable; + +/** + * Class Swow + */ +class Swow implements ChannelInterface +{ + + /** + * @var Channel + */ + protected Channel $channel; + + /** + * Constructor. + * + * @param int $capacity + */ + public function __construct(protected int $capacity = 1) + { + $this->channel = new Channel($capacity); + } + + /** + * @inheritDoc + */ + public function push(mixed $data, float $timeout = -1): bool + { + try { + $this->channel->push($data, $timeout == -1 ? -1 : (int)($timeout * 1000)); + } catch (Throwable) { + return false; + } + return true; + } + + /** + * @inheritDoc + */ + public function pop(float $timeout = -1): mixed + { + try { + return $this->channel->pop($timeout == -1 ? -1 : (int)($timeout * 1000)); + } catch (Throwable) { + return false; + } + } + + /** + * @inheritDoc + */ + public function length(): int + { + return $this->channel->getLength(); + } + + /** + * @inheritDoc + */ + public function getCapacity(): int + { + return $this->channel->getCapacity(); + } + + /** + * @inheritDoc + */ + public function hasConsumers(): bool + { + return $this->channel->hasConsumers(); + } + + /** + * @inheritDoc + */ + public function hasProducers(): bool + { + return $this->channel->hasProducers(); + } + + /** + * @inheritDoc + */ + public function close(): void + { + if ($this->channel->isAvailable()) { + $this->channel->close(); + } + } + +} diff --git a/vendor/workerman/coroutine/src/Context.php b/vendor/workerman/coroutine/src/Context.php new file mode 100644 index 0000000..48a073c --- /dev/null +++ b/vendor/workerman/coroutine/src/Context.php @@ -0,0 +1,90 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine; + +use ArrayObject; +use Workerman\Coroutine\Context\ContextInterface; +use Workerman\Events\Swoole; +use Workerman\Events\Swow; +use Workerman\Worker; + +/** + * Class Context + */ +class Context implements ContextInterface +{ + + /** + * @var class-string<ContextInterface> + */ + protected static string $driver; + + /** + * @inheritDoc + */ + public static function get(?string $name = null, mixed $default = null): mixed + { + return static::$driver::get($name, $default); + } + + /** + * @inheritDoc + */ + public static function set(string $name, $value): void + { + static::$driver::set($name, $value); + } + + /** + * @inheritDoc + */ + public static function has(string $name): bool + { + return static::$driver::has($name); + } + + /** + * @inheritDoc + */ + public static function reset(?ArrayObject $data = null): void + { + static::$driver::reset($data); + } + + /** + * @inheritDoc + */ + public static function destroy(): void + { + static::$driver::destroy(); + } + + /** + * @return void + */ + public static function initDriver(): void + { + static::$driver ??= match (Worker::$eventLoopClass) { + Swoole::class => Context\Swoole::class, + Swow::class => Context\Swow::class, + default=> Context\Fiber::class, + }; + } + +} + +Context::initDriver(); \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Context/ContextInterface.php b/vendor/workerman/coroutine/src/Context/ContextInterface.php new file mode 100644 index 0000000..4920608 --- /dev/null +++ b/vendor/workerman/coroutine/src/Context/ContextInterface.php @@ -0,0 +1,50 @@ +<?php + +namespace Workerman\Coroutine\Context; + +use ArrayObject; + +/** + * Interface ContextInterface + */ +interface ContextInterface +{ + /** + * Get the value from the context with the specified name. + * If the name does not exist, return the default value. + * + * @param string|null $name The name of the value to get. + * @param mixed $default The default value to return if the name does not exist. + * @return mixed The value from the context or the default value. + */ + public static function get(?string $name = null, mixed $default = null): mixed; + + /** + * Set the value in the context with the specified name. + * + * @param string $name The name of the value to set. + * @param mixed $value The value to set. + */ + public static function set(string $name, mixed $value): void; + + /** + * Check if the specified name exists in the context. + * + * @param string $name The name to check. + * @return bool True if the name exists, otherwise false. + */ + public static function has(string $name): bool; + + /** + * Initialize the context with an array of data. + * + * @param ArrayObject|null $data The array of data to initialize the context. + */ + public static function reset(?ArrayObject $data = null): void; + + /** + * Destroy the context. + */ + public static function destroy(): void; + +} diff --git a/vendor/workerman/coroutine/src/Context/Fiber.php b/vendor/workerman/coroutine/src/Context/Fiber.php new file mode 100644 index 0000000..e004185 --- /dev/null +++ b/vendor/workerman/coroutine/src/Context/Fiber.php @@ -0,0 +1,107 @@ +<?php + +namespace Workerman\Coroutine\Context; + +use ArrayObject; +use WeakMap; +use Fiber as BaseFiber; + +/** + * Class Fiber + */ +class Fiber implements ContextInterface +{ + /** + * @var WeakMap + */ + private static WeakMap $contexts; + + /** + * @var ArrayObject + */ + private static ArrayObject $nonFiberContext; + + /** + * @inheritDoc + */ + public static function get(?string $name = null, mixed $default = null): mixed + { + $fiber = BaseFiber::getCurrent(); + if ($fiber === null) { + return $name !== null ? (static::$nonFiberContext[$name] ?? $default) : static::$nonFiberContext; + } + if ($name === null) { + return static::$contexts[$fiber] ??= new ArrayObject([], ArrayObject::ARRAY_AS_PROPS); + } + return static::$contexts[$fiber][$name] ?? $default; + } + + /** + * @inheritDoc + */ + public static function set(string $name, $value): void + { + $fiber = BaseFiber::getCurrent(); + if ($fiber === null) { + static::$nonFiberContext[$name] = $value; + return; + } + static::$contexts[$fiber] ??= new ArrayObject([], ArrayObject::ARRAY_AS_PROPS); + static::$contexts[$fiber][$name] = $value; + } + + /** + * @inheritDoc + */ + public static function has(string $name): bool + { + $fiber = BaseFiber::getCurrent(); + if ($fiber === null) { + return static::$nonFiberContext->offsetExists($name); + } + return isset(static::$contexts[$fiber]) && static::$contexts[$fiber]->offsetExists($name); + } + + /** + * @inheritDoc + */ + public static function reset(?ArrayObject $data = null): void + { + if ($data) { + $data->setFlags(ArrayObject::ARRAY_AS_PROPS); + } else { + $data = new ArrayObject([], ArrayObject::ARRAY_AS_PROPS); + } + $fiber = BaseFiber::getCurrent(); + if ($fiber === null) { + static::$nonFiberContext = $data; + return; + } + static::$contexts[$fiber] = $data; + } + + /** + * @inheritDoc + */ + public static function destroy(): void + { + $fiber = BaseFiber::getCurrent(); + if ($fiber === null) { + static::$nonFiberContext = new ArrayObject([], ArrayObject::ARRAY_AS_PROPS); + return; + } + unset(static::$contexts[$fiber]); + } + + /** + * Initialize the weakMap. + */ + public static function initContext(): void + { + static::$contexts = new WeakMap(); + static::$nonFiberContext = new ArrayObject([], ArrayObject::ARRAY_AS_PROPS); + } + +} + +Fiber::initContext(); \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Context/Swoole.php b/vendor/workerman/coroutine/src/Context/Swoole.php new file mode 100644 index 0000000..ceb4e62 --- /dev/null +++ b/vendor/workerman/coroutine/src/Context/Swoole.php @@ -0,0 +1,63 @@ +<?php + +namespace Workerman\Coroutine\Context; + +use ArrayObject; +use Swoole\Coroutine; + +class Swoole implements ContextInterface +{ + + /** + * @inheritDoc + */ + public static function get(?string $name = null, mixed $default = null): mixed + { + $context = Coroutine::getContext(); + if (!$context) { + return $default; + } + $context->setFlags(ArrayObject::ARRAY_AS_PROPS); + if ($name === null) { + return $context; + } + return $context[$name] ?? $default; + } + + /** + * @inheritDoc + */ + public static function set(string $name, $value): void + { + Coroutine::getContext()[$name] = $value; + } + + /** + * @inheritDoc + */ + public static function has(string $name): bool + { + $context = Coroutine::getContext(); + return $context->offsetExists($name); + } + + /** + * @inheritDoc + */ + public static function reset(?ArrayObject $data = null): void + { + $context = Coroutine::getContext(); + $context->setFlags(ArrayObject::ARRAY_AS_PROPS); + $context->exchangeArray($data ? $data->getArrayCopy() : []); + } + + /** + * @inheritDoc + */ + public static function destroy(): void + { + $context = Coroutine::getContext(); + $context->exchangeArray([]); + } + +} diff --git a/vendor/workerman/coroutine/src/Context/Swow.php b/vendor/workerman/coroutine/src/Context/Swow.php new file mode 100644 index 0000000..6c759b1 --- /dev/null +++ b/vendor/workerman/coroutine/src/Context/Swow.php @@ -0,0 +1,81 @@ +<?php + +namespace Workerman\Coroutine\Context; + +use ArrayObject; +use Swow\Coroutine; +use WeakMap; + +class Swow implements ContextInterface +{ + /** + * @var WeakMap + */ + public static WeakMap $contexts; + + /** + * @inheritDoc + */ + public static function get(?string $name = null, mixed $default = null): mixed + { + $fiber = Coroutine::getCurrent(); + if ($name === null) { + static::$contexts[$fiber] ??= new ArrayObject([], ArrayObject::ARRAY_AS_PROPS); + return static::$contexts[$fiber]; + } + return static::$contexts[$fiber][$name] ?? $default; + } + + /** + * @inheritDoc + */ + public static function set(string $name, $value): void + { + $coroutine = Coroutine::getCurrent(); + static::$contexts[$coroutine] ??= new ArrayObject([], ArrayObject::ARRAY_AS_PROPS); + static::$contexts[$coroutine][$name] = $value; + } + + /** + * @inheritDoc + */ + public static function has(string $name): bool + { + $fiber = Coroutine::getCurrent(); + return isset(static::$contexts[$fiber]) && static::$contexts[$fiber]->offsetExists($name); + } + + /** + * @inheritDoc + */ + public static function reset(?ArrayObject $data = null): void + { + if ($data) { + $data->setFlags(ArrayObject::ARRAY_AS_PROPS); + } else { + $data = new ArrayObject([], ArrayObject::ARRAY_AS_PROPS); + } + static::$contexts[Coroutine::getCurrent()] = $data; + } + + /** + * @inheritDoc + */ + public static function destroy(): void + { + unset(static::$contexts[Coroutine::getCurrent()]); + } + + /** + * Initialize the weakMap. + * + * @return void + */ + public static function initContext(): void + { + self::$contexts = new WeakMap(); + } + +} + +Swow::initContext(); \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Coroutine.php b/vendor/workerman/coroutine/src/Coroutine.php new file mode 100644 index 0000000..7d07deb --- /dev/null +++ b/vendor/workerman/coroutine/src/Coroutine.php @@ -0,0 +1,129 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman; + +use Workerman\Coroutine\Coroutine\CoroutineInterface; +use Workerman\Coroutine\Coroutine\Fiber; +use Workerman\Worker; +use Workerman\Coroutine\Coroutine\Swoole as SwooleCoroutine; +use Workerman\Coroutine\Coroutine\Swow as SwowCoroutine; +use Workerman\Events\Swoole as SwooleEvent; +use Workerman\Events\Swow as SwowEvent; + +/** + * Class Coroutine + */ +class Coroutine implements CoroutineInterface +{ + /** + * @var class-string<CoroutineInterface> + */ + protected static string $driverClass; + + /** + * @var CoroutineInterface + */ + public CoroutineInterface $driver; + + /** + * Coroutine constructor. + * + * @param callable $callable + */ + public function __construct(callable $callable) + { + $this->driver = new static::$driverClass($callable); + } + + /** + * @inheritDoc + */ + public static function create(callable $callable, ...$args): CoroutineInterface + { + return static::$driverClass::create($callable, ...$args); + } + + /** + * @inheritDoc + */ + public function start(mixed ...$args): mixed + { + return $this->driver->start(...$args); + } + + /** + * @inheritDoc + */ + public function resume(mixed ...$args): mixed + { + return $this->driver->resume(...$args); + } + + /** + * @inheritDoc + */ + public function id(): int + { + return $this->driver->id(); + } + + /** + * @inheritDoc + */ + public static function defer(callable $callable): void + { + static::$driverClass::defer($callable); + } + + /** + * @inheritDoc + */ + public static function suspend(mixed $value = null): mixed + { + return static::$driverClass::suspend($value); + } + + /** + * @inheritDoc + */ + public static function getCurrent(): CoroutineInterface + { + return static::$driverClass::getCurrent(); + } + + /** + * @inheritDoc + */ + public static function isCoroutine(): bool + { + return static::$driverClass::isCoroutine(); + } + + /** + * @return void + */ + public static function init(): void + { + static::$driverClass = match (Worker::$eventLoopClass ?? null) { + SwooleEvent::class => SwooleCoroutine::class, + SwowEvent::class => SwowCoroutine::class, + default => Fiber::class, + }; + } + +} +Coroutine::init(); diff --git a/vendor/workerman/coroutine/src/Coroutine/CoroutineInterface.php b/vendor/workerman/coroutine/src/Coroutine/CoroutineInterface.php new file mode 100644 index 0000000..2e0e4d5 --- /dev/null +++ b/vendor/workerman/coroutine/src/Coroutine/CoroutineInterface.php @@ -0,0 +1,90 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Coroutine; + +use Fiber; +use Swow\Coroutine as SwowCoroutine; + +/** + * Interface CoroutineInterface + */ +interface CoroutineInterface +{ + + /** + * Create a coroutine. + * + * @param callable $callable + * @param ...$data + * @return CoroutineInterface + */ + public static function create(callable $callable, ...$data): CoroutineInterface; + + /** + * Start a coroutine. + * + * @param mixed ...$args + * @return mixed + */ + public function start(mixed ...$args): mixed; + + /** + * Resume a coroutine. + * + * @param mixed ...$args + * @return mixed + */ + public function resume(mixed ...$args): mixed; + + /** + * Get the id of the coroutine. + * + * @return int + */ + public function id(): int; + + /** + * Register a callable to be executed when the current fiber is destroyed + * + * @param callable $callable + * @return void + */ + public static function defer(callable $callable): void; + + /** + * Yield the coroutine. + * + * @param mixed|null $value + * @return mixed + */ + public static function suspend(mixed $value = null): mixed; + + /** + * Get the current coroutine. + * + * @return CoroutineInterface|Fiber|SwowCoroutine|static + */ + public static function getCurrent(): CoroutineInterface|Fiber|SwowCoroutine|static; + + /** + * Check if the current coroutine is in a coroutine. + * + * @return bool + */ + public static function isCoroutine(): bool; + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Coroutine/Fiber.php b/vendor/workerman/coroutine/src/Coroutine/Fiber.php new file mode 100644 index 0000000..6738893 --- /dev/null +++ b/vendor/workerman/coroutine/src/Coroutine/Fiber.php @@ -0,0 +1,154 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Coroutine; + +use Fiber as BaseFiber; +use RuntimeException; +use WeakMap; +use Workerman\Coroutine\Utils\DestructionWatcher; + +/** + * Class Fiber + */ +class Fiber implements CoroutineInterface +{ + /** + * @var BaseFiber|null + */ + private ?BaseFiber $fiber; + + /** + * @var WeakMap + */ + private static WeakMap $instances; + + /** + * @var int + */ + private int $id; + + /** + * @param callable|null $callable + */ + public function __construct(?callable $callable = null) + { + static $id = 0; + $this->id = ++$id; + if ($callable) { + $callable = function(...$args) use ($callable) { + try { + $callable(...$args); + } finally { + $this->fiber = null; + } + }; + $this->fiber = new BaseFiber($callable); + self::$instances[$this->fiber] = $this; + } + } + + /** + * @inheritDoc + */ + public static function create(callable $callable, ...$args): CoroutineInterface + { + $fiber = new Fiber($callable); + $fiber->start(...$args); + return $fiber; + } + + /** + * @inheritDoc + */ + public function start(mixed ...$args): mixed + { + return $this->fiber->start(...$args); + } + + /** + * @inheritDoc + */ + public function resume(mixed ...$args): mixed + { + return $this->fiber->resume(...$args); + } + + /** + * @inheritDoc + */ + public static function suspend(mixed $value = null): mixed + { + return BaseFiber::suspend($value); + } + + /** + * @inheritDoc + */ + public function id(): int + { + return $this->id; + } + + /** + * @inheritDoc + */ + public static function defer(callable $callable): void + { + $baseFiber = BaseFiber::getCurrent(); + if ($baseFiber === null) { + throw new RuntimeException('Cannot defer outside of a fiber.'); + } + DestructionWatcher::watch($baseFiber, $callable); + } + + /** + * @inheritDoc + */ + public static function getCurrent(): CoroutineInterface + { + if (!$baseFiber = BaseFiber::getCurrent()) { + throw new RuntimeException('Not in fiber context'); + } + if (!isset(self::$instances[$baseFiber])) { + $fiber = new Fiber(); + $fiber->fiber = $baseFiber; + self::$instances[$baseFiber] = $fiber; + } + return self::$instances[$baseFiber]; + } + + /** + * @inheritDoc + */ + public static function isCoroutine(): bool + { + return BaseFiber::getCurrent() !== null; + } + + /** + * Initialize the fiber. + * + * @return void + */ + public static function init(): void + { + self::$instances = new WeakMap(); + } + +} + +Fiber::init(); diff --git a/vendor/workerman/coroutine/src/Coroutine/Swoole.php b/vendor/workerman/coroutine/src/Coroutine/Swoole.php new file mode 100644 index 0000000..89f82c2 --- /dev/null +++ b/vendor/workerman/coroutine/src/Coroutine/Swoole.php @@ -0,0 +1,148 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Coroutine; + +use RuntimeException; +use Swoole\Coroutine; +use WeakReference; + +class Swoole implements CoroutineInterface +{ + + /** + * @var array + */ + private static array $instances = []; + + /** + * @var int + */ + private int $id = 0; + + /** + * @var callable|null + */ + private $callable; + + /** + * Coroutine constructor. + * + * @param callable|null $callable + */ + public function __construct(?callable $callable = null) + { + $this->callable = $callable; + } + + /** + * @inheritDoc + */ + public static function create(callable $callable, ...$args): CoroutineInterface + { + $id = Coroutine::create($callable, ...$args); + if (isset(self::$instances[$id]) && $coroutine = self::$instances[$id]->get()) { + return $coroutine; + } + $coroutine = new self($callable); + $coroutine->id = $id; + self::$instances[$id] = WeakReference::create($coroutine); + return $coroutine; + } + + /** + * @inheritDoc + */ + public function start(mixed ...$args): CoroutineInterface + { + if ($this->id) { + throw new RuntimeException('Coroutine has already started'); + } + $this->id = Coroutine::create($this->callable, ...$args); + $this->callable = null; + if (isset(self::$instances[$this->id]) && $coroutine = self::$instances[$this->id]->get()) { + return $coroutine; + } + self::$instances[$this->id] = WeakReference::create($this); + return $this; + } + + /** + * @inheritDoc + */ + public function resume(mixed ...$args): mixed + { + return Coroutine::resume($this->id, ...$args); + } + + /** + * @inheritDoc + */ + public function id(): int + { + return $this->id; + } + + /** + * @inheritDoc + */ + public static function defer(callable $callable): void + { + Coroutine::defer($callable); + } + + /** + * @inheritDoc + */ + public static function suspend(mixed $value = null): mixed + { + return Coroutine::suspend($value); + } + + /** + * @inheritDoc + */ + public static function getCurrent(): CoroutineInterface + { + $id = Coroutine::getCid(); + if ($id === -1) { + throw new RuntimeException('Not in coroutine'); + } + if (!isset(self::$instances[$id])) { + $coroutine = new self(); + $coroutine->id = $id; + self::$instances[$id] = WeakReference::create($coroutine); + } + return self::$instances[$id]->get(); + } + + /** + * @inheritDoc + */ + public static function isCoroutine(): bool + { + return Coroutine::getCid() > 0; + } + + /** + * Destructor. + */ + public function __destruct() + { + unset(self::$instances[$this->id]); + } + +} diff --git a/vendor/workerman/coroutine/src/Coroutine/Swow.php b/vendor/workerman/coroutine/src/Coroutine/Swow.php new file mode 100644 index 0000000..8963542 --- /dev/null +++ b/vendor/workerman/coroutine/src/Coroutine/Swow.php @@ -0,0 +1,91 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine\Coroutine; + +use Swow\Coroutine; + +/** + * Class Swow + */ +class Swow extends Coroutine implements CoroutineInterface +{ + + /** + * @var array + */ + private array $callbacks = []; + + /** + * @inheritDoc + */ + public static function defer(callable $callable): void + { + $coroutine = static::getCurrent(); + $coroutine->callbacks[] = $callable; + } + + /** + * @inheritDoc + */ + public static function create(callable $callable, ...$args): CoroutineInterface + { + return static::run($callable, ...$args); + } + + /** + * @inheritDoc + */ + public function start(mixed ...$args): mixed + { + return $this->resume(...$args); + } + + /** + * @inheritDoc + */ + public function id(): int + { + return $this->getId(); + } + + /** + * @inheritDoc + */ + public static function suspend(mixed $value = null): mixed + { + return Coroutine::yield($value); + } + + /** + * @inheritDoc + */ + public static function isCoroutine(): bool + { + return true; + } + + /** + * Destructor. + */ + public function __destruct() + { + foreach (array_reverse($this->callbacks) as $callable) { + $callable(); + } + } + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Exception/PoolException.php b/vendor/workerman/coroutine/src/Exception/PoolException.php new file mode 100644 index 0000000..e1c49a7 --- /dev/null +++ b/vendor/workerman/coroutine/src/Exception/PoolException.php @@ -0,0 +1,8 @@ +<?php + +namespace Workerman\Coroutine\Exception; + +class PoolException extends \RuntimeException +{ + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Locker.php b/vendor/workerman/coroutine/src/Locker.php new file mode 100644 index 0000000..47b59a5 --- /dev/null +++ b/vendor/workerman/coroutine/src/Locker.php @@ -0,0 +1,66 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine; + +use RuntimeException; + +/** + * Class Locker + */ +class Locker +{ + /** + * @var Channel[] + */ + protected static array $channels = []; + + /** + * Lock. + * + * @param string $key + * @return bool + */ + public static function lock(string $key): bool + { + if (!isset(static::$channels[$key])) { + static::$channels[$key] = new Channel(1); + } + return static::$channels[$key]->push(true); + } + + /** + * Unlock. + * + * @param string $key + * @return bool + */ + public static function unlock(string $key): bool + { + if ($channel = static::$channels[$key] ?? null) { + // Must check hasProducers before pop, because pop in swow will wake up the producer, leading to inaccurate judgment. + $hasProducers = $channel->hasProducers(); + $result = $channel->pop(); + if (!$hasProducers) { + $channel->close(); + unset(static::$channels[$key]); + } + return $result; + } + throw new RuntimeException("Unlock failed, because the key $key is not locked"); + } + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/Parallel.php b/vendor/workerman/coroutine/src/Parallel.php new file mode 100644 index 0000000..3cedf0b --- /dev/null +++ b/vendor/workerman/coroutine/src/Parallel.php @@ -0,0 +1,117 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine; + +use Throwable; +use Workerman\Coroutine; + +/** + * Class Parallel + */ +class Parallel +{ + /** + * @var Channel|null + */ + protected ?Channel $channel = null; + + /** + * @var array + */ + protected array $callbacks = []; + + /** + * @var array + */ + protected array $results = []; + + /** + * @var array + */ + protected array $exceptions = []; + + /** + * Constructor. + * + * @param int $concurrent + */ + public function __construct(int $concurrent = -1) + { + if ($concurrent > 0) { + $this->channel = new Channel($concurrent); + } + } + + /** + * Add a coroutine. + * + * @param callable $callable + * @param string|null $key + * @return void + */ + public function add(callable $callable, ?string $key = null): void + { + if ($key === null) { + $this->callbacks[] = $callable; + } else { + $this->callbacks[$key] = $callable; + } + } + + /** + * Wait all coroutines complete and return results. + * + * @return array + */ + public function wait(): array + { + $barrier = Barrier::create(); + foreach ($this->callbacks as $key => $callback) { + $this->channel?->push(true); + // A completed Fiber may retain its closure until the caller frame returns. + // Use a mutable holder so the barrier reference can be released explicitly. + $barrierRef = new \stdClass(); + $barrierRef->value = $barrier; + Coroutine::create(function () use ($callback, $key, $barrierRef) { + try { + $this->results[$key] = $callback(); + } catch (Throwable $throwable) { + $this->exceptions[$key] = $throwable; + } finally { + try { + $this->channel?->pop(); + } finally { + $barrierRef->value = null; + } + } + }); + } + Barrier::wait($barrier); + return $this->results; + } + + /** + * Get failed results. + * + * @return array + */ + public function getExceptions(): array + { + return $this->exceptions; + } + +} diff --git a/vendor/workerman/coroutine/src/Pool.php b/vendor/workerman/coroutine/src/Pool.php new file mode 100644 index 0000000..31c693b --- /dev/null +++ b/vendor/workerman/coroutine/src/Pool.php @@ -0,0 +1,414 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine; + +use Closure; +use Psr\Log\LoggerInterface; +use stdClass; +use Throwable; +use WeakMap; +use WeakReference; +use Workerman\Coroutine; +use Workerman\Coroutine\Exception\PoolException; +use Workerman\Timer; +use Workerman\Worker; + +/** + * Class Pool + */ +class Pool implements PoolInterface +{ + /** + * @var Channel + */ + protected Channel $channel; + + /** + * @var int + */ + protected int $minConnections = 1; + + /** + * @var WeakMap + */ + protected WeakMap $connections; + + /** + * @var WeakMap + */ + protected WeakMap $idleConnections; + + /** + * @var ?object + */ + protected ?object $nonCoroutineConnection = null; + + /** + * @var WeakMap + */ + protected WeakMap $lastUsedTimes; + + /** + * @var WeakMap + */ + protected WeakMap $lastHeartbeatTimes; + + /** + * @var Closure|null + */ + protected ?Closure $connectionCreateHandler = null; + + /** + * @var Closure|null + */ + protected ?Closure $connectionDestroyHandler = null; + + /** + * @var Closure|null + */ + protected ?Closure $connectionHeartbeatHandler = null; + + /** + * @var float + */ + protected float $idleTimeout = 60; + + /** + * @var float + */ + protected float $heartbeatInterval = 50; + + /** + * @var float + */ + protected float $waitTimeout = 10; + + /** + * @var LoggerInterface|Closure|null + */ + protected LoggerInterface|Closure|null $logger = null; + + /** + * @var array|string[] + */ + private array $configurableProperties = [ + 'minConnections', + 'idleTimeout', + 'heartbeatInterval', + 'waitTimeout', + ]; + + /** + * Constructor. + * + * @param int $maxConnections + * @param array $config + */ + public function __construct(protected int $maxConnections = 1, protected array $config = []) + { + foreach ($config as $key => $value) { + $camelCaseKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key)))); + if (in_array($camelCaseKey, $this->configurableProperties, true)) { + $this->$camelCaseKey = $value; + } + } + + $this->channel = new Channel($maxConnections); + $this->lastUsedTimes = new WeakMap(); + $this->lastHeartbeatTimes = new WeakMap(); + $this->connections = new WeakMap(); + $this->idleConnections = new WeakMap(); + + if (Worker::isRunning()) { + $weakPool = WeakReference::create($this); + $timerId = Timer::repeat(1, static function () use ($weakPool, &$timerId) { + if ($pool = $weakPool->get()) { + $pool->checkConnections(); + return; + } + // Deleting a timer inside its own callback kills the current coroutine under Swow, + // which skips Workerman's timer bookkeeping, so delete it from another callback. + Timer::delay(0.001, static fn () => Timer::del($timerId)); + }); + } + } + + /** + * Set the connection creator. + * + * @param callable $connectionCreateHandler + * @return $this + */ + public function setConnectionCreator(callable $connectionCreateHandler): self + { + $this->connectionCreateHandler = $connectionCreateHandler; + return $this; + } + + /** + * Set the connection closer. + * + * @param callable $connectionDestroyHandler + * @return $this + */ + public function setConnectionCloser(callable $connectionDestroyHandler): self + { + $this->connectionDestroyHandler = $connectionDestroyHandler; + return $this; + } + + /** + * Set the connection heartbeat checker. + * + * @param callable $connectionHeartbeatHandler + * @return $this + */ + public function setHeartbeatChecker(callable $connectionHeartbeatHandler): self + { + $this->connectionHeartbeatHandler = $connectionHeartbeatHandler; + return $this; + } + + /** + * Get connection. + * + * @return object + * @throws Throwable + */ + public function get(): object + { + if (!Coroutine::isCoroutine()) { + if (!$this->nonCoroutineConnection) { + $this->nonCoroutineConnection = $this->createConnection(); + } + return $this->nonCoroutineConnection; + } + // closeConnection() cannot remove an idle connection from the channel, so discard such connections here. + do { + if ($this->channel->length() === 0 && $this->getConnectionCount() < $this->maxConnections) { + return $this->createConnection(); + } + $connection = $this->channel->pop($this->waitTimeout); + if (!$connection) { + throw new PoolException("Failed to get a connection from the pool within the wait timeout ($this->waitTimeout seconds). The connection pool is exhausted."); + } + } while (!isset($this->connections[$connection])); + unset($this->idleConnections[$connection]); + $this->lastUsedTimes[$connection] = time(); + return $connection; + } + + /** + * Put connection to pool. + * + * @param object $connection + * @return void + * @throws Throwable + */ + public function put(object $connection): void + { + // This connection does not belong to the connection pool. + // It may have been closed by $this->closeConnection($connection). + if (!isset($this->connections[$connection])) { + throw new PoolException('The connection does not belong to the connection pool.'); + } + if ($connection === $this->nonCoroutineConnection) { + return; + } + if (isset($this->idleConnections[$connection])) { + throw new PoolException('The connection has already been returned to the connection pool.'); + } + // Mark before pushing: push() may resume a waiting get() which clears the mark before push() returns. + $this->idleConnections[$connection] = true; + try { + if ($this->channel->push($connection)) { + return; + } + } catch (Throwable $throwable) { + $this->closeConnection($connection); + throw $throwable; + } + $this->closeConnection($connection); + } + + /** + * Check if the connection is valid. + * + * @param $connection + * @return bool + */ + protected function isValidConnection($connection): bool + { + return is_object($connection); + } + + /** + * Create connection. + * + * @return object + * @throws Throwable + */ + public function createConnection(): object + { + if ($this->getConnectionCount() >= $this->maxConnections) { + throw new PoolException('CreateConnection failed, maximum connection limit reached.'); + } + // Create a placeholder to ensure the correct value of getConnectionCount(). + $placeholder = new stdClass; + $this->connections[$placeholder] = 0; + try { + // Coroutines will switch here, so we need $placeholder to ensure the correct value of getConnectionCount(). + $connection = ($this->connectionCreateHandler)(); + if (!$this->isValidConnection($connection)) { + throw new PoolException('CreateConnection failed, expected a connection object, but got ' . gettype($connection) . '.'); + } + unset($this->connections[$placeholder]); + $this->connections[$connection] = $this->lastUsedTimes[$connection] = $this->lastHeartbeatTimes[$connection] = time(); + } catch (Throwable $throwable) { + unset($this->connections[$placeholder]); + throw $throwable; + } + return $connection; + } + + /** + * Close the connection and remove the connection from the connection pool. + * + * @param object $connection + * @return void + */ + public function closeConnection(object $connection): void + { + if (!isset($this->connections[$connection])) { + return; + } + // Mark this connection as no longer belonging to the connection pool. + unset($this->lastUsedTimes[$connection], $this->lastHeartbeatTimes[$connection], $this->idleConnections[$connection], $this->connections[$connection]); + if ($this->nonCoroutineConnection === $connection) { + $this->nonCoroutineConnection = null; + } + if (!$this->connectionDestroyHandler) { + return; + } + try { + ($this->connectionDestroyHandler)($connection); + } catch (Throwable $throwable) { + $this->log($throwable); + } + } + + /** + * Cleanup idle connections. + * + * @return void + */ + protected function checkConnections(): void + { + $num = $this->channel->length(); + $time = time(); + for($i = $num; $i > 0; $i--) { + $connection = $this->channel->pop(0); + if (!$connection) { + return; + } + // Closed by closeConnection() while idle. + if (!isset($this->connections[$connection])) { + continue; + } + $lastUsedTime = $this->lastUsedTimes[$connection]; + if ($time - $lastUsedTime > $this->idleTimeout && $this->channel->length() >= $this->minConnections) { + $this->closeConnection($connection); + continue; + } + $this->trySendHeartbeat($connection) && $this->channel->push($connection); + } + if ($this->nonCoroutineConnection) { + $this->trySendHeartbeat($this->nonCoroutineConnection); + } + } + + /** + * Try to send heartbeat. + * + * @param $connection + * @return bool + */ + private function trySendHeartbeat($connection): bool + { + $lastHeartbeatTime = $this->lastHeartbeatTimes[$connection] ?? 0; + $time = time(); + if ($this->connectionHeartbeatHandler && $time - $lastHeartbeatTime >= $this->heartbeatInterval) { + try { + ($this->connectionHeartbeatHandler)($connection); + $this->lastHeartbeatTimes[$connection] = $time; + } catch (Throwable $throwable) { + $this->log($throwable); + $this->closeConnection($connection); + return false; + } + } + return true; + } + + /** + * Get the number of connections in the connection pool. + * + * @return int + */ + public function getConnectionCount(): int + { + return count($this->connections); + } + + /** + * Close connections. + * + * @return void + */ + public function closeConnections(): void + { + $num = $this->channel->length(); + for ($i = $num; $i > 0; $i--) { + $connection = $this->channel->pop(0); + if (!$connection) { + return; + } + $this->closeConnection($connection); + } + $this->nonCoroutineConnection && $this->closeConnection($this->nonCoroutineConnection); + } + + /** + * Log. + * + * @param $message + * @return void + */ + protected function log($message): void + { + if (!$this->logger) { + echo $message . PHP_EOL; + return; + } + if ($this->logger instanceof Closure) { + ($this->logger)($message); + return; + } + $this->logger->info((string)$message); + } + +} diff --git a/vendor/workerman/coroutine/src/PoolInterface.php b/vendor/workerman/coroutine/src/PoolInterface.php new file mode 100644 index 0000000..fd42899 --- /dev/null +++ b/vendor/workerman/coroutine/src/PoolInterface.php @@ -0,0 +1,69 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Coroutine; + +/** + * Interface PoolInterface + */ +interface PoolInterface +{ + + /** + * Get a connection from the pool. + * + * @return mixed + */ + public function get(): mixed; + + /** + * Put a connection back to the pool. + * + * @param object $connection + * @return void + */ + public function put(object $connection): void; + + /** + * Create a connection. + * + * @return object + */ + public function createConnection(): object; + + /** + * Close the connection and remove the connection from the connection pool. + * + * @param object $connection + * @return void + */ + public function closeConnection(object $connection): void; + + /** + * Get the number of connections in the connection pool. + * + * @return int + */ + public function getConnectionCount(): int; + + /** + * Close connections in the connection pool. + * + * @return void + */ + public function closeConnections(): void; + +} diff --git a/vendor/workerman/coroutine/src/Utils/DestructionWatcher.php b/vendor/workerman/coroutine/src/Utils/DestructionWatcher.php new file mode 100644 index 0000000..3a2b734 --- /dev/null +++ b/vendor/workerman/coroutine/src/Utils/DestructionWatcher.php @@ -0,0 +1,67 @@ +<?php +/** + * This file is part of workerman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Workerman\Coroutine\Utils; + +use WeakMap; + +class DestructionWatcher +{ + /** + * @var WeakMap + */ + protected static WeakMap $objects; + + /** + * @var callable[] + */ + protected array $callbacks = []; + + /** + * DestructionWatcher constructor. + * + * @param callable|null $callback + */ + public function __construct(?callable $callback = null) + { + if ($callback) { + $this->callbacks[] = $callback; + } + } + + /** + * DestructionWatcher destructor. + */ + public function __destruct() + { + foreach (array_reverse($this->callbacks) as $callback) { + $callback(); + } + } + + /** + * Watch object destruction. + * + * @param object $object + * @param callable $callback + * @return void + */ + public static function watch(object $object, callable $callback): void + { + static::$objects ??= new WeakMap(); + static::$objects[$object] ??= new static(); + static::$objects[$object]->callbacks[] = $callback; + } + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/src/WaitGroup.php b/vendor/workerman/coroutine/src/WaitGroup.php new file mode 100644 index 0000000..9327860 --- /dev/null +++ b/vendor/workerman/coroutine/src/WaitGroup.php @@ -0,0 +1,77 @@ +<?php +/** + * @author workbunny/Chaz6chez + * @email chaz6chez1993@outlook.com + */ +declare(strict_types=1); + +namespace Workerman\Coroutine; + +use BadMethodCallException; +use Workerman\Worker; +use Workerman\Coroutine\Coroutine\CoroutineInterface; +use Workerman\Coroutine\WaitGroup\Fiber as FiberWaitGroup; +use Workerman\Coroutine\WaitGroup\Swoole as SwooleWaitGroup; +use Workerman\Coroutine\WaitGroup\Swow as SwowWaitGroup; +use Workerman\Coroutine\WaitGroup\WaitGroupInterface; +use Workerman\Events\Swoole; +use Workerman\Events\Swow; + +/** + * @method bool add(int $delta = 1) + * @method bool done() + * @method int count() + * @method bool wait(int|float $timeout = -1) + */ +class WaitGroup +{ + /** + * @var class-string<CoroutineInterface> + */ + protected static string $driverClass; + + /** + * @var WaitGroupInterface + */ + protected WaitGroupInterface $driver; + + /** + * 构造方法 + */ + public function __construct() + { + $this->driver = new (self::driverClass()); + } + + /** + * Get driver class. + * + * @return class-string<CoroutineInterface> + */ + protected static function driverClass(): string + { + return static::$driverClass ??= match (Worker::$eventLoopClass ?? null) { + Swoole::class => SwooleWaitGroup::class, + Swow::class => SwowWaitGroup::class, + default => FiberWaitGroup::class, + }; + } + + + /** + * 代理调用WaitGroupInterface方法 + * + * @codeCoverageIgnore 系统魔术方法,忽略覆盖 + * @param string $name + * @param array $arguments + * @return mixed + */ + public function __call(string $name, array $arguments): mixed + { + if (!method_exists($this->driver, $name)) { + throw new BadMethodCallException("Method $name not exists. "); + } + + return $this->driver->$name(...$arguments); + } +} diff --git a/vendor/workerman/coroutine/src/WaitGroup/Fiber.php b/vendor/workerman/coroutine/src/WaitGroup/Fiber.php new file mode 100644 index 0000000..94db77a --- /dev/null +++ b/vendor/workerman/coroutine/src/WaitGroup/Fiber.php @@ -0,0 +1,66 @@ +<?php +/** + * @author workbunny/Chaz6chez + * @email chaz6chez1993@outlook.com + */ +declare(strict_types=1); + +namespace Workerman\Coroutine\WaitGroup; + +use Workerman\Coroutine\Channel\Fiber as Channel; + +class Fiber implements WaitGroupInterface +{ + + /** @var int */ + protected int $count; + + /** + * @var Channel + */ + protected Channel $channel; + + public function __construct() + { + $this->count = 0; + $this->channel = new Channel(1); + } + + /** @inheritdoc */ + public function add(int $delta = 1): bool + { + $this->count += max($delta, 1); + + return true; + } + + /** @inheritdoc */ + public function done(): bool + { + if ($this->count > 0) { + $this->count--; + // Signal only a suspended waiter, a buffered signal would wake the next wait() early. + if ($this->count === 0 && $this->channel->hasConsumers()) { + $this->channel->push(true); + } + } + + return true; + } + + /** @inheritdoc */ + public function count(): int + { + return $this->count; + } + + /** @inheritdoc */ + public function wait(int|float $timeout = -1): bool + { + if ($this->count > 0) { + return $this->channel->pop($timeout); + } + return true; + } + +} diff --git a/vendor/workerman/coroutine/src/WaitGroup/Swoole.php b/vendor/workerman/coroutine/src/WaitGroup/Swoole.php new file mode 100644 index 0000000..978fd0b --- /dev/null +++ b/vendor/workerman/coroutine/src/WaitGroup/Swoole.php @@ -0,0 +1,61 @@ +<?php +/** + * @author workbunny/Chaz6chez + * @email chaz6chez1993@outlook.com + */ +declare(strict_types=1); + +namespace Workerman\Coroutine\WaitGroup; + +use Swoole\Coroutine\WaitGroup; + +/** + * Class Swoole + */ +class Swoole implements WaitGroupInterface +{ + + /** @var WaitGroup */ + protected WaitGroup $waitGroup; + + + public function __construct() + { + $this->waitGroup = new WaitGroup(); + } + + /** @inheritdoc */ + public function add(int $delta = 1): bool + { + $this->waitGroup->add(max($delta, 1)); + + return true; + } + + /** @inheritdoc */ + public function done(): bool + { + if ($this->count() > 0) { + $this->waitGroup->done(); + } + + return true; + } + + /** @inheritdoc */ + public function count(): int + { + return $this->waitGroup->count(); + } + + /** @inheritdoc */ + public function wait(int|float $timeout = -1): bool + { + // Swoole treats a zero timeout as waiting forever. + if ($timeout == 0) { + return $this->count() === 0; + } + return $this->waitGroup->wait($timeout > 0 ? max($timeout, 0.001) : -1); + } + +} diff --git a/vendor/workerman/coroutine/src/WaitGroup/Swow.php b/vendor/workerman/coroutine/src/WaitGroup/Swow.php new file mode 100644 index 0000000..4344148 --- /dev/null +++ b/vendor/workerman/coroutine/src/WaitGroup/Swow.php @@ -0,0 +1,64 @@ +<?php +/** + * @author workbunny/Chaz6chez + * @email chaz6chez1993@outlook.com + */ +declare(strict_types=1); + +namespace Workerman\Coroutine\WaitGroup; + +use Swow\Sync\WaitGroup; +use Throwable; + +class Swow implements WaitGroupInterface +{ + + /** @var WaitGroup */ + protected WaitGroup $waitGroup; + + /** @var int count */ + protected int $count; + + public function __construct() + { + $this->waitGroup = new WaitGroup(); + $this->count = 0; + } + + /** @inheritdoc */ + public function add(int $delta = 1): bool + { + $this->waitGroup->add($delta = max($delta, 1)); + $this->count += $delta; + + return true; + } + + /** @inheritdoc */ + public function done(): bool + { + if ($this->count() > 0) { + $this->count--; + $this->waitGroup->done(); + } + + return true; + } + + /** @inheritdoc */ + public function count(): int + { + return $this->count; + } + + /** @inheritdoc */ + public function wait(int|float $timeout = -1): bool + { + try { + $this->waitGroup->wait($timeout > 0 ? (int) ($timeout * 1000) : $timeout); + return true; + } catch (Throwable) { + return false; + } + } +} diff --git a/vendor/workerman/coroutine/src/WaitGroup/WaitGroupInterface.php b/vendor/workerman/coroutine/src/WaitGroup/WaitGroupInterface.php new file mode 100644 index 0000000..9fbfd7c --- /dev/null +++ b/vendor/workerman/coroutine/src/WaitGroup/WaitGroupInterface.php @@ -0,0 +1,42 @@ +<?php +/** + * @author workbunny/Chaz6chez + * @email chaz6chez1993@outlook.com + */ +declare(strict_types=1); + +namespace Workerman\Coroutine\WaitGroup; + +interface WaitGroupInterface +{ + + /** + * Increment count + * + * @param int $delta + * @return bool + */ + public function add(int $delta = 1): bool; + + /** + * Complete count + * + * @return bool + */ + public function done(): bool; + + /** + * Return count + * + * @return int + */ + public function count(): int; + + /** + * Wait + * + * @param int|float $timeout second + * @return bool timeout:false success:true + */ + public function wait(int|float $timeout = -1): bool; +} diff --git a/vendor/workerman/coroutine/stubs/SwowStub.php b/vendor/workerman/coroutine/stubs/SwowStub.php new file mode 100644 index 0000000..609c5a8 --- /dev/null +++ b/vendor/workerman/coroutine/stubs/SwowStub.php @@ -0,0 +1,36 @@ +<?php + +namespace Swow; + +class Coroutine +{ + public function resume(mixed ...$args): mixed + { + // Stub for PHPStorm + return null; + } + + public static function getCurrent(): static + { + // Stub for PHPStorm + return new Coroutine; + } + + public static function yield (mixed ...$args) : mixed + { + // Stub for PHPStorm + return null; + } + + public function getId() : int + { + // Stub for PHPStorm + return 0; + } + + public static function run(callable $callable , mixed ... $args): static + { + // Stub for PHPStorm + return new Coroutine; + } +} diff --git a/vendor/workerman/coroutine/tests/BarrierTest.php b/vendor/workerman/coroutine/tests/BarrierTest.php new file mode 100644 index 0000000..33f177f --- /dev/null +++ b/vendor/workerman/coroutine/tests/BarrierTest.php @@ -0,0 +1,43 @@ +<?php + +declare(strict_types=1); + +namespace tests; + +use PHPUnit\Framework\TestCase; +use Workerman\Coroutine\Barrier; +use Workerman\Coroutine; +use Workerman\Timer; + +/** + * Class FiberBarrierTest + * + * Tests for the Fiber Barrier implementation. + */ +class BarrierTest extends TestCase +{ + + /** + * Test that the barrier is set to null after calling wait. + */ + public function testWaitSetsBarrierToNull() + { + $barrier = Barrier::create(); + $results = [0]; + Coroutine::create(function () use ($barrier, &$results) { + Timer::sleep(0.1); + $results[] = 1; + }); + Coroutine::create(function () use ($barrier, &$results) { + Timer::sleep(0.2); + $results[] = 2; + }); + Coroutine::create(function () use ($barrier, &$results) { + Timer::sleep(0.3); + $results[] = 3; + }); + Barrier::wait($barrier); + $this->assertNull($barrier, 'Barrier should be null after wait is called.'); + $this->assertEquals([0, 1, 2, 3], $results, 'All coroutines should have been executed.'); + } +} diff --git a/vendor/workerman/coroutine/tests/ChannelTest.php b/vendor/workerman/coroutine/tests/ChannelTest.php new file mode 100644 index 0000000..fefff80 --- /dev/null +++ b/vendor/workerman/coroutine/tests/ChannelTest.php @@ -0,0 +1,313 @@ +<?php +declare(strict_types=1); + +namespace tests; + +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; +use ReflectionClass; +use ReflectionException; +use stdClass; +use Workerman\Coroutine\Channel; +use PHPUnit\Framework\Attributes\DataProvider; +use Workerman\Coroutine\Channel\Memory; +use Workerman\Coroutine; + +class ChannelTest extends TestCase +{ + /** + * Test initializing channel with valid capacity. + */ + public function testInitializeWithValidCapacity() + { + $channel = new Channel(1); + $this->assertInstanceOf(Channel::class, $channel); + $this->assertEquals(1, $channel->getCapacity()); + } + + /** + * Test initializing channel with invalid capacities. + */ + #[DataProvider('invalidCapacitiesProvider')] + public function testInitializeWithInvalidCapacity($capacity) + { + $this->expectException(InvalidArgumentException::class); + new Channel($capacity); + } + + /** + * Data provider for invalid capacities. + */ + public static function invalidCapacitiesProvider(): array + { + return [ + [0], + [-1], + [-100] + ]; + } + + /** + * Test pushing and popping data. + */ + public function testPushAndPop() + { + $channel = new Channel(2); + $data1 = 'test data 1'; + $data2 = 'test data 2'; + + // Push data into the channel + $this->assertTrue($channel->push($data1)); + $this->assertTrue($channel->push($data2)); + + // Verify the length of the channel + $this->assertEquals(2, $channel->length()); + + // Pop data from the channel + $this->assertEquals($data1, $channel->pop()); + $this->assertEquals($data2, $channel->pop()); + } + + /** + * Test pushing data when the channel is full. + * @throws ReflectionException + */ + public function testPushWhenFull() + { + // Memory driver does not support push with timeout + if ($this->driverIsMemory()) { + $this->assertTrue(true); + return; + } + $channel = new Channel(1); + $this->assertTrue($channel->push('data1')); + + $timeout = 0.5; + // Attempt to push when the channel is full with a timeout + $startTime = microtime(true); + $this->assertFalse($channel->push('data2', $timeout)); + $elapsedTime = microtime(true) - $startTime; + + // Verify that the push operation timed out + $this->assertTrue(0.1 > abs($elapsedTime - $timeout)); + } + + /** + * Test popping data when the channel is empty. + * @throws ReflectionException + */ + public function testPopWhenEmpty() + { + // Memory driver does not support push with timeout + if ($this->driverIsMemory()) { + $this->assertTrue(true); + return; + } + $channel = new Channel(1); + + // Attempt to pop when the channel is empty with a timeout + $startTime = microtime(true); + $this->assertFalse($channel->pop(0.1)); + $elapsedTime = microtime(true) - $startTime; + + // Verify that the pop operation timed out + $this->assertGreaterThanOrEqual(0.09, $elapsedTime); + } + + /** + * Test closing the channel and its effects. + */ + public function testCloseChannel() + { + $channel = new Channel(1); + $this->assertTrue($channel->push('data')); + + // Close the channel + $channel->close(); + + // Attempt to push after closing + $this->assertFalse($channel->push('new data')); + + // Pop the remaining data + $this->assertEquals('data', $channel->pop()); + + // Attempt to pop after channel is empty and closed + $this->assertFalse($channel->pop()); + } + + /** + * Test that push and pop return false when channel is closed. + */ + public function testPushAndPopReturnFalseWhenClosed() + { + $channel = new Channel(1); + $channel->close(); + + $this->assertFalse($channel->push('data')); + $this->assertFalse($channel->pop()); + } + + /** + * Test the length and capacity methods. + */ + public function testLengthAndCapacity() + { + $channel = new Channel(5); + $this->assertEquals(0, $channel->length()); + $this->assertEquals(5, $channel->getCapacity()); + + $channel->push('data1'); + $channel->push('data2'); + + $this->assertEquals(2, $channel->length()); + } + + /** + * Test pushing and popping with different data types. + */ + #[DataProvider('dataTypesProvider')] + public function testPushAndPopWithDifferentDataTypes($data) + { + $channel = new Channel(1); + $this->assertTrue($channel->push($data)); + $this->assertSame($data, $channel->pop()); + } + + /** + * Data provider for different data types. + */ + public static function dataTypesProvider(): array + { + return [ + ['string'], + [123], + [123.456], + [true], + [false], + [null], + [[]], + [['key' => 'value']], + [new stdClass()], + [fopen('php://memory', 'r')], + ]; + } + + /** + * Test pushing to a closed channel immediately returns false. + */ + public function testPushToClosedChannel() + { + $channel = new Channel(1); + $channel->close(); + $this->assertFalse($channel->push('data', 0)); + } + + /** + * Test popping from a closed and empty channel immediately returns false. + */ + public function testPopFromClosedAndEmptyChannel() + { + $channel = new Channel(1); + $channel->close(); + $this->assertFalse($channel->pop(0)); + } + + /** + * @return bool + * @throws ReflectionException + */ + protected function driverIsMemory(): bool + { + $reflectionClass = new ReflectionClass(Channel::class); + $instance = $reflectionClass->newInstance(); + $property = $reflectionClass->getProperty('driver'); + $driverValue = $property->getValue($instance); + return $driverValue instanceof Memory; + } + + /** + * 测试 hasConsumers 当没有消费者时返回 false + */ + public function testHasConsumersWhenNoConsumers() + { + if (!Coroutine::isCoroutine()) { + $this->assertTrue(true); + return; + } + $channel = new Channel(1); + $this->assertFalse($channel->hasConsumers()); + $channel->close(); + } + + /** + * 测试 hasConsumers 当有消费者等待时返回 true + * @throws ReflectionException + */ + public function testHasConsumersWhenConsumersWaiting() + { + if ($this->driverIsMemory()) { + $this->assertTrue(true); + return; + } + $channel = new Channel(1); + $sync = new Channel(1); + + Coroutine::create(function () use ($channel, $sync) { + $sync->push(true); + $channel->pop(); + }); + + $sync->pop(); + + $this->assertTrue($channel->hasConsumers()); + + Coroutine::create(function () use ($channel) { + $channel->push('data'); + }); + $channel->close(); + } + + /** + * 测试 hasProducers 当没有生产者时返回 false + * @throws ReflectionException + */ + public function testHasProducersWhenNoProducers() + { + if ($this->driverIsMemory()) { + $this->assertTrue(true); + return; + } + $channel = new Channel(1); + $this->assertFalse($channel->hasProducers()); + $channel->close(); + } + + /** + * 测试 hasProducers 当有生产者等待时返回 true + * @throws ReflectionException + */ + public function testHasProducersWhenProducersWaiting() + { + if ($this->driverIsMemory()) { + $this->assertTrue(true); + return; + } + $channel = new Channel(1); + $channel->push('data1'); + + $sync = new Channel(1); + + Coroutine::create(function () use ($channel, $sync) { + $sync->push(true); + $channel->push('data2'); + }); + + $sync->pop(); + + $this->assertTrue($channel->hasProducers()); + + $channel->pop(); + $channel->close(); + } + +} diff --git a/vendor/workerman/coroutine/tests/ContextTest.php b/vendor/workerman/coroutine/tests/ContextTest.php new file mode 100644 index 0000000..788aeb8 --- /dev/null +++ b/vendor/workerman/coroutine/tests/ContextTest.php @@ -0,0 +1,169 @@ +<?php + +namespace tests; + +use ArrayObject; +use PHPUnit\Framework\TestCase; +use Workerman\Coroutine\Context; +use Workerman\Coroutine; + +// Now, the test cases +class ContextTest extends TestCase +{ + public function testContextSetAndGetWithinCoroutine() + { + Coroutine::create(function () { + $key = 'testContextSetAndGetWithinCoroutine'; + Context::set($key, 'value'); + $this->assertEquals('value', Context::get($key)); + }); + } + + public function testContextGet() + { + Context::reset(new ArrayObject(['not_exist' => 'value'])); + $key = 'testContextGet'; + Context::reset(new ArrayObject([$key => 'value'])); + $context = Context::get(); + $this->assertArrayNotHasKey('not_exist', $context); + $this->assertObjectNotHasProperty('not_exist', $context); + $this->assertArrayHasKey($key, $context); + $this->assertObjectHasProperty($key, $context); + $this->assertEquals('value', $context[$key]); + $this->assertEquals('value', $context->$key); + $this->assertInstanceOf('ArrayObject', $context); + unset($context[$key]); + $this->assertNull(Context::get($key)); + $context[$key] = 'value'; + $this->assertEquals('value', Context::get($key)); + unset($context->$key); + $this->assertNull(Context::get($key)); + $context->$key = 'value'; + $this->assertEquals('value', Context::get($key)); + } + + public function testContextIsolationBetweenCoroutines() + { + $values = []; + + Coroutine::create(function () use (&$values) { + Context::set('key', 'value1'); + $values[] = Context::get('key'); + // Ensure the value is not available after coroutine ends + Context::destroy(); + }); + + Coroutine::create(function () use (&$values) { + Context::set('key', 'value2'); + $values[] = Context::get('key'); + // Ensure the value is not available after coroutine ends + Context::destroy(); + }); + + $this->assertEquals(['value1', 'value2'], $values); + } + + public function testContextDestroyedAfterCoroutineEnds() + { + Coroutine::create(function () { + Context::set('key', 'value'); + $this->assertTrue(Context::has('key')); + // Simulate coroutine end and context destruction + Context::destroy(); + }); + + // After coroutine ends, the context should be destroyed + // Need to simulate this by trying to access context outside coroutine + $this->assertNull(Context::get('key')); + $this->assertFalse(Context::has('key')); + } + + public function testContextHasMethod() + { + Coroutine::create(function () { + $this->assertFalse(Context::has('key')); + Context::set('key', 'value'); + $this->assertTrue(Context::has('key')); + }); + } + + public function testContextResetMethod() + { + Coroutine::create(function () { + Context::reset(new ArrayObject(['key3' => 'value1'])); + Context::reset(new ArrayObject(['key1' => 'value1', 'key2' => 'value2'])); + $this->assertEquals('value1', Context::get('key1')); + $this->assertEquals('value2', Context::get('key2')); + // Test that other keys are not set + $this->assertNull(Context::get('key3')); + }); + } + + public function testContextDataNotSharedBetweenCoroutines() + { + $result = []; + + Coroutine::create(function () use (&$result) { + Context::set('counter', 1); + $result[] = Context::get('counter'); + Context::destroy(); + }); + + Coroutine::create(function () use (&$result) { + $this->assertNull(Context::get('counter')); + Context::set('counter', 2); + $result[] = Context::get('counter'); + Context::destroy(); + }); + + $this->assertEquals([1, 2], $result); + } + + public function testContextDefaultValues() + { + Coroutine::create(function () { + $this->assertEquals('default', Context::get('non_existing_key', 'default')); + }); + } + + public function testContextSetOverrideValue() + { + Coroutine::create(function () { + Context::set('key', 'initial'); + $this->assertEquals('initial', Context::get('key')); + Context::set('key', 'overridden'); + $this->assertEquals('overridden', Context::get('key')); + }); + } + + public function testContextMultipleKeys() + { + Coroutine::create(function () { + Context::set('key1', 'value1'); + Context::set('key2', 'value2'); + $this->assertEquals('value1', Context::get('key1')); + $this->assertEquals('value2', Context::get('key2')); + }); + } + + public function testContextPersistenceWithinCoroutine() + { + Coroutine::create(function () { + Context::set('key', 'value'); + + // Simulate asynchronous operation within coroutine + $this->someAsyncOperation(function () { + $this->assertEquals('value', Context::get('key')); + }); + + // Context should persist throughout the coroutine + $this->assertEquals('value', Context::get('key')); + }); + } + + private function someAsyncOperation(callable $callback) + { + // Simulate async operation + $callback(); + } +} diff --git a/vendor/workerman/coroutine/tests/CoroutineTest.php b/vendor/workerman/coroutine/tests/CoroutineTest.php new file mode 100644 index 0000000..c763fb0 --- /dev/null +++ b/vendor/workerman/coroutine/tests/CoroutineTest.php @@ -0,0 +1,184 @@ +<?php + +namespace tests; + +use PHPUnit\Framework\TestCase; +use Workerman\Coroutine; +use Workerman\Coroutine\Coroutine\CoroutineInterface; +use Workerman\Events\Swoole; +use Workerman\Worker; + +class CoroutineTest extends TestCase +{ + public function testCreateReturnsCoroutineInterface() + { + $callable = function() {}; + $coroutine = Coroutine::create($callable); + $this->assertInstanceOf(CoroutineInterface::class, $coroutine); + } + + public function testStartExecutesCoroutine() + { + $value = null; + Coroutine::create(function() use (&$value) { + $value = 'started'; + }); + $this->assertEquals('started', $value); + } + + public function testSuspendAndResumeCoroutine() + { + if (Worker::$eventLoopClass === Swoole::class) { + // Swoole does not support suspend and resume + $this->assertTrue(true); + return; + } + $value = []; + $coroutine = Coroutine::create(function() use (&$value) { + $value[] = 'before suspend'; + $resumedValue = Coroutine::suspend(); + $value[] = 'after resume'; + $value[] = $resumedValue; + }); + $this->assertEquals(['before suspend'], $value); + $coroutine->resume('resumed data'); + unset($coroutine); + gc_collect_cycles(); + $this->assertEquals(['before suspend', 'after resume', 'resumed data'], $value); + } + + public function testGetCurrentReturnsCurrentCoroutine() + { + $currentCoroutine = null; + $coroutine = Coroutine::create(function() use (&$currentCoroutine) { + $currentCoroutine = Coroutine::getCurrent(); + }); + $this->assertSame($coroutine, $currentCoroutine); + } + + public function testCoroutineIdIsInteger() + { + $coroutine = Coroutine::create(function() {}); + $id = $coroutine->id(); + $this->assertIsInt($id); + } + + public function testDeferExecutesAfterCoroutineDestruction() + { + $value = []; + $coroutine = Coroutine::create(function() use (&$value) { + Coroutine::defer(function() use (&$value) { + $value[] = 'defer1'; + }); + Coroutine::defer(function() use (&$value) { + $value[] = 'defer2'; + }); + $value[] = 'before suspend'; + Coroutine::suspend(); + $value[] = 'after resume'; + }); + $this->assertEquals(['before suspend'], $value); + $coroutine->resume(); + unset($coroutine); + gc_collect_cycles(); + $this->assertEquals(['before suspend', 'after resume', 'defer2', 'defer1'], $value); + } + + public function testMultipleCoroutines() + { + $sequence = []; + $coroutine1 = Coroutine::create(function() use (&$sequence) { + $sequence[] = 'coroutine1 start'; + Coroutine::suspend(); + $sequence[] = 'coroutine1 resumed'; + }); + $coroutine2 = Coroutine::create(function() use (&$sequence) { + $sequence[] = 'coroutine2 start'; + Coroutine::suspend(); + $sequence[] = 'coroutine2 resumed'; + }); + $this->assertEquals(['coroutine1 start', 'coroutine2 start'], $sequence); + $coroutine1->resume(); + $coroutine2->resume(); + $this->assertEquals( + ['coroutine1 start', 'coroutine2 start', 'coroutine1 resumed', 'coroutine2 resumed'], + $sequence + ); + } + + public function testCoroutineWithArguments() + { + $result = null; + $coroutine = new Coroutine(function($a, $b) use (&$result) { + $result = $a + $b; + }); + $coroutine->start(2, 3); + $this->assertEquals(5, $result); + } + + public function testSuspendReturnsValue() + { + if (Worker::$eventLoopClass === Swoole::class) { + // Swoole does not support suspend and resume + $this->assertTrue(true); + return; + } + $coroutine = new Coroutine(function() { + $valueFromResume = Coroutine::suspend('first suspend'); + Coroutine::suspend($valueFromResume); + }); + $first_suspend = $coroutine->start(); + $this->assertEquals('first suspend', $first_suspend); + $result = $coroutine->resume('value from resume'); + $this->assertEquals('value from resume', $result); + } + + public function testNestedCoroutines() + { + $sequence = []; + $coroutine = Coroutine::create(function() use (&$sequence) { + $sequence[] = 'outer start'; + $inner = Coroutine::create(function() use (&$sequence) { + $sequence[] = 'inner start'; + Coroutine::suspend(); + $sequence[] = 'inner resumed'; + }); + Coroutine::suspend(); + $sequence[] = 'outer resumed'; + $inner->resume(); + $sequence[] = 'outer end'; + }); + $this->assertEquals(['outer start', 'inner start'], $sequence); + $coroutine->resume(); + $this->assertEquals(['outer start', 'inner start', 'outer resumed', 'inner resumed', 'outer end'], $sequence); + } + + /*public function testCoroutineExceptionHandling() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Test exception'); + Coroutine::create(function() { + throw new \Exception('Test exception'); + }); + }*/ + + public function testDeferOrder() + { + $value = []; + $coroutine = Coroutine::create(function() use (&$value) { + Coroutine::defer(function() use (&$value) { + $value[] = 'defer1'; + }); + Coroutine::defer(function() use (&$value) { + $value[] = 'defer2'; + }); + $value[] = 'coroutine body'; + }); + unset($coroutine); + // Force garbage collection + gc_collect_cycles(); + $this->assertEquals(['coroutine body', 'defer2', 'defer1'], $value); + } + +} + diff --git a/vendor/workerman/coroutine/tests/FiberChannelTest.php b/vendor/workerman/coroutine/tests/FiberChannelTest.php new file mode 100644 index 0000000..dc5c8b9 --- /dev/null +++ b/vendor/workerman/coroutine/tests/FiberChannelTest.php @@ -0,0 +1,346 @@ +<?php + +use PHPUnit\Framework\TestCase; +use Workerman\Coroutine\Channel\Fiber as Channel; +use Workerman\Timer; +use Fiber as BaseFiber; + +class FiberChannelTest extends TestCase +{ + /** + * Test basic push and pop operations. + */ + public function testBasicPushPop() + { + $channel = new Channel(); + + $fiber = new BaseFiber(function() use ($channel) { + $channel->push('test data'); + }); + + $fiber->start(); + + $this->assertEquals('test data', $channel->pop()); + } + + /** + * Test that pop will block until data is available or timeout occurs. + */ + public function testPopWithTimeout() + { + $channel = new Channel(); + + $fiber = new BaseFiber(function() use ($channel) { + $result = $channel->pop(0.5); + $this->assertFalse($result); + }); + + $startTime = microtime(true); + + $fiber->start(); + + // Allow time for the fiber to suspend and wait + Timer::sleep(0.2); // 200 ms + + // Ensure that the fiber is still waiting (not timed out yet) + $this->assertTrue($fiber->isSuspended()); + + // Wait until the timeout should have occurred + Timer::sleep(0.4); // 400 ms + + $endTime = microtime(true); + + $this->assertTrue($fiber->isTerminated()); + $this->assertGreaterThanOrEqual(0.5, $endTime - $startTime); + } + + /** + * Test that push will block when capacity is reached and timeout occurs. + */ + public function testPushWithTimeout() + { + $channel = new Channel(1); + + $this->assertTrue($channel->push('data1')); + + $fiber = new BaseFiber(function() use ($channel) { + $result = $channel->push('data2', 0.5); + $this->assertFalse($result); + }); + + $startTime = microtime(true); + + $fiber->start(); + + // Allow time for the fiber to suspend and wait + Timer::sleep(0.2); // 200 ms + + // Ensure that the fiber is still waiting (not timed out yet) + $this->assertTrue($fiber->isSuspended()); + + // Wait until the timeout should have occurred + Timer::sleep(0.4); // 400 ms + + $endTime = microtime(true); + + $this->assertTrue($fiber->isTerminated()); + $this->assertGreaterThanOrEqual(0.5, $endTime - $startTime); + } + + /** + * Test that push returns false immediately if capacity is full and timeout is zero. + */ + public function testPushNonBlockingWhenFull() + { + $channel = new Channel(1); + + $this->assertTrue($channel->push('data1')); + + $result = $channel->push('data2', 0); + $this->assertFalse($result); + } + + /** + * Test that pop returns false immediately if the channel is empty and timeout is zero. + */ + public function testPopNonBlockingWhenEmpty() + { + $channel = new Channel(); + + $result = $channel->pop(0); + $this->assertFalse($result); + } + + /** + * Test closing the channel. + */ + public function testCloseChannel() + { + $channel = new Channel(); + + $channel->close(); + + $this->assertFalse($channel->push('data')); + $this->assertFalse($channel->pop()); + } + + /** + * Test that waiting pushers and poppers are resumed when the channel is closed. + */ + public function testWaitersAreResumedOnClose() + { + $channelPush = new Channel(1); + $channelPop = new Channel(1); + + $pushFiber = new BaseFiber(function() use ($channelPush) { + $channelPush->push('data', 1); + $result = $channelPush->push('data', 1); + $this->assertFalse($result); + }); + + $popFiber = new BaseFiber(function() use ($channelPop) { + $result = $channelPop->pop(1); + $this->assertFalse($result); + }); + + $pushFiber->start(); + $popFiber->start(); + + // Allow time for fibers to suspend + Timer::sleep(0.1); // 100 ms + + // Close the channel to resume fibers + $channelPush->close(); + $channelPop->close(); + + // Allow time for fibers to process after resuming + Timer::sleep(0.1); // 100 ms + + $this->assertTrue($pushFiber->isTerminated()); + $this->assertTrue($popFiber->isTerminated()); + } + + /** + * Test that length and getCapacity methods return correct values. + */ + public function testLengthAndCapacity() + { + $capacity = 2; + $channel = new Channel($capacity); + + $this->assertEquals(0, $channel->length()); + $this->assertEquals($capacity, $channel->getCapacity()); + + $channel->push('data1'); + $this->assertEquals(1, $channel->length()); + + $channel->push('data2'); + $this->assertEquals(2, $channel->length()); + + $channel->pop(); + $this->assertEquals(1, $channel->length()); + + $channel->pop(); + $this->assertEquals(0, $channel->length()); + } + + /** + * Test pushing to a closed channel. + */ + public function testPushToClosedChannel() + { + $channel = new Channel(); + + $channel->close(); + + $result = $channel->push('data'); + $this->assertFalse($result); + } + + /** + * Test popping from a closed channel. + */ + public function testPopFromClosedChannel() + { + $channel = new Channel(); + + $channel->push('data'); + + $channel->close(); + + $this->assertEquals('data', $channel->pop()); + $this->assertFalse($channel->pop()); + } + + /** + * Test multiple push and pop operations with fibers. + */ + public function testMultiplePushPopWithFibers() + { + $channel = new Channel(2); + + $results = []; + + $producerFiber = new BaseFiber(function() use ($channel) { + $channel->push('data1'); + $channel->push('data2'); + $channel->push('data3'); + }); + + $consumerFiber = new BaseFiber(function() use ($channel, &$results) { + $results[] = $channel->pop(); + $results[] = $channel->pop(); + $results[] = $channel->pop(); + }); + + $producerFiber->start(); + $consumerFiber->start(); + + // Allow time for fibers to execute + usleep(500000); // 500 ms + + $this->assertEquals(['data1', 'data2', 'data3'], $results); + } + + /** + * Test that fibers are properly blocked and resumed in push and pop operations. + */ + public function testFiberBlockingAndResuming() + { + $channel = new Channel(1); + + $pushFiber = new BaseFiber(function() use ($channel) { + $channel->push('data1'); + $channel->push('data2'); + $channel->push('data3'); + }); + + $popFiber = new BaseFiber(function() use ($channel) { + $this->assertEquals('data1', $channel->pop()); + $this->assertEquals('data2', $channel->pop()); + $this->assertEquals('data3', $channel->pop()); + }); + + $pushFiber->start(); + $popFiber->start(); + + // Allow time for fibers to execute + Timer::sleep(0.5); // 500 ms + + $this->assertTrue($pushFiber->isTerminated()); + $this->assertTrue($popFiber->isTerminated()); + } + + /** + * Test that pushing data after capacity is reached blocks until space is available. + */ + public function testPushBlocksWhenFull() + { + $channel = new Channel(1); + + $channel->push('data1'); + + $pushFiber = new BaseFiber(function() use ($channel) { + $channel->push('data2'); + }); + + $popFiber = new BaseFiber(function() use ($channel) { + Timer::sleep(0.2); // Wait before popping + $this->assertEquals('data1', $channel->pop()); + }); + + $pushFiber->start(); + $popFiber->start(); + + // Allow time for fibers to execute + Timer::sleep(0.5); // 500 ms + + $this->assertTrue($pushFiber->isTerminated()); + $this->assertTrue($popFiber->isTerminated()); + } + + /** + * Test that popping data from an empty channel blocks until data is available. + */ + public function testPopBlocksWhenEmpty() + { + $channel = new Channel(); + + $popFiber = new BaseFiber(function() use ($channel) { + $this->assertEquals('data1', $channel->pop()); + }); + + $pushFiber = new BaseFiber(function() use ($channel) { + Timer::sleep(0.2); // Wait before pushing + $channel->push('data1'); + }); + + $popFiber->start(); + $pushFiber->start(); + + // Allow time for fibers to execute + Timer::sleep(0.5); // 500 ms + + $this->assertTrue($pushFiber->isTerminated()); + $this->assertTrue($popFiber->isTerminated()); + } + + /** + * Test pushing and popping with zero timeout. + */ + public function testPushPopWithZeroTimeout() + { + $channel = new Channel(1); + + $this->assertTrue($channel->push('data1')); + + $result = $channel->push('data2', 0); + $this->assertFalse($result); + + $result = $channel->pop(0); + $this->assertEquals('data1', $result); + + $result = $channel->pop(0); + $this->assertFalse($result); + } +} diff --git a/vendor/workerman/coroutine/tests/LockerTest.php b/vendor/workerman/coroutine/tests/LockerTest.php new file mode 100644 index 0000000..b1a18b1 --- /dev/null +++ b/vendor/workerman/coroutine/tests/LockerTest.php @@ -0,0 +1,130 @@ +<?php + +declare(strict_types=1); + +namespace tests; + +use PHPUnit\Framework\TestCase; +use Workerman\Coroutine\Locker; +use RuntimeException; +use Workerman\Coroutine; +use ReflectionClass; +use Workerman\Timer; + +class LockerTest extends TestCase +{ + + public function testLock() + { + $key = 'testLock'; + Locker::lock($key); + $timeStart = microtime(true); + $timeDiff2 = 0; + Coroutine::create(function () use ($key, $timeStart, &$timeDiff2) { + $this->assertChannelExists($key); + Locker::lock($key); + $timeDiff = microtime(true) - $timeStart; + $this->assertGreaterThan($timeDiff2, $timeDiff); + Locker::unlock($key); + }); + usleep(100000); + $timeDiff2 = microtime(true) - $timeStart; + Locker::unlock($key); + } + + public function testLockAndUnlock() + { + $key = 'testLockAndUnlock'; + $this->assertTrue(Locker::lock($key)); + $this->assertTrue(Locker::unlock($key)); + $this->assertChannelRemoved($key); + } + + public function testUnlockWithoutLockThrowsException() + { + $this->expectException(RuntimeException::class); + Locker::unlock('non_existent_key'); + } + + public function testRelockAfterUnlock() + { + $key = 'testRelockAfterUnlock'; + Locker::lock($key); + Locker::unlock($key); + + $this->assertTrue(Locker::lock($key)); + Locker::unlock($key); + $this->assertChannelRemoved($key); + } + + public function testMultipleCoroutinesLocking() + { + $key = 'testMultipleCoroutinesLocking'; + $results = []; + Coroutine::create(function () use ($key, &$results) { + Coroutine::create(function () use ($key, &$results) { + Locker::lock($key); + $results[] = 'A'; + Timer::sleep(0.1); + usleep(100000); + Locker::unlock($key); + }); + + Coroutine::create(function () use ($key, &$results) { + Timer::sleep(0.05); + Locker::lock($key); + $results[] = 'B'; + Locker::unlock($key); + }); + + Coroutine::create(function () use ($key, &$results) { + Timer::sleep(0.05); + Locker::lock($key); + $results[] = 'C'; + Locker::unlock($key); + }); + + }); + + Timer::sleep(0.3); + $this->assertEquals(['A', 'B', 'C'], $results); + $this->assertChannelRemoved($key); + } + + public function testChannelRemainsWhenWaiting() + { + $key = 'testChannelRemainsWhenWaiting'; + Locker::lock($key); + + Coroutine::create(function () use ($key) { + Coroutine::create(function () use ($key) { + Locker::lock($key); + Locker::unlock($key); + }); + + Locker::unlock($key); + + $this->assertChannelRemoved($key); + }); + } + + private function assertChannelExists(string $key): void + { + $channels = $this->getChannels(); + $this->assertArrayHasKey($key, $channels, "Channel for key '$key' should exist"); + } + + private function assertChannelRemoved(string $key): void + { + $channels = $this->getChannels(); + $this->assertArrayNotHasKey($key, $channels, "Channel for key '$key' should be removed"); + } + + private function getChannels(): array + { + $reflector = new ReflectionClass(Locker::class); + $property = $reflector->getProperty('channels'); + return $property->getValue(); + } + +} \ No newline at end of file diff --git a/vendor/workerman/coroutine/tests/ParallelTest.php b/vendor/workerman/coroutine/tests/ParallelTest.php new file mode 100644 index 0000000..6d34fa1 --- /dev/null +++ b/vendor/workerman/coroutine/tests/ParallelTest.php @@ -0,0 +1,329 @@ +<?php + +namespace tests; + +use PHPUnit\Framework\TestCase; +use Workerman\Coroutine\Parallel; +use Workerman\Coroutine; +use Workerman\Timer; + +/** + * Test cases for the Workerman\Coroutine\Parallel class. + */ +class ParallelTest extends TestCase +{ + /** + * Test that callables are added and executed, and results are collected properly. + */ + public function testAddAndWait() + { + $parallel = new Parallel(); + + $parallel->add(function () { + // Simulate some work. + Timer::sleep(0.01); + return 1; + }, 'task1'); + + $parallel->add(function () { + // Simulate some work. + Timer::sleep(0.005); + return 2; + }, 'task2'); + + $results = $parallel->wait(); + + $this->assertEquals(['task1' => 1, 'task2' => 2], $results); + } + + /** + * Test that exceptions thrown in callables are caught and can be retrieved. + */ + public function testExceptions() + { + $parallel = new Parallel(); + + $parallel->add(function () { + throw new \Exception('Test exception'); + }, 'task_with_exception'); + + $parallel->add(function () { + return 'normal result'; + }, 'normal_task'); + + $results = $parallel->wait(); + $exceptions = $parallel->getExceptions(); + + // Check that the normal task result is present. + $this->assertEquals(['normal_task' => 'normal result'], $results); + + // Check that the exception is captured for the failing task. + $this->assertArrayHasKey('task_with_exception', $exceptions); + $this->assertInstanceOf(\Exception::class, $exceptions['task_with_exception']); + $this->assertEquals('Test exception', $exceptions['task_with_exception']->getMessage()); + } + + /** + * Test that a synchronous task cannot make wait return before asynchronous tasks complete. + */ + public function testSynchronousAndAsynchronousTasksCompleteBeforeWaitReturns() + { + $parallel = new Parallel(); + $completed = false; + + $parallel->add(function () { + throw new \RuntimeException('immediate failure'); + }, 'immediate'); + + $parallel->add(function () use (&$completed) { + Timer::sleep(0.01); + $completed = true; + return 'delayed result'; + }, 'delayed'); + + $results = $parallel->wait(); + $exceptions = $parallel->getExceptions(); + + $this->assertTrue($completed); + $this->assertSame(['delayed' => 'delayed result'], $results); + $this->assertArrayHasKey('immediate', $exceptions); + $this->assertInstanceOf(\RuntimeException::class, $exceptions['immediate']); + } + + /** + * Test concurrency control by limiting the number of concurrent tasks. + */ + public function testConcurrencyLimit() + { + $concurrentLimit = 2; + $parallel = new Parallel($concurrentLimit); + + $startTimes = []; + $endTimes = []; + + for ($i = 0; $i < 5; $i++) { + $parallel->add(function () use (&$startTimes, &$endTimes, $i) { + $startTimes[$i] = microtime(true); + // Simulate some work. + Timer::sleep(0.1); // 100 milliseconds + $endTimes[$i] = microtime(true); + return $i; + }, "task{$i}"); + } + + $parallel->wait(); + + // Since we limited concurrency to 2, tasks should finish in batches. + // We'll check that at no point more than $concurrentLimit tasks were running simultaneously. + + // Collect start and end times into an array of intervals. + $intervals = []; + for ($i = 0; $i < 5; $i++) { + $intervals[] = ['start' => $startTimes[$i], 'end' => $endTimes[$i]]; + } + + // Check the maximum number of overlapping intervals does not exceed the concurrency limit. + $maxConcurrent = $this->getMaxConcurrentIntervals($intervals); + + $this->assertLessThanOrEqual($concurrentLimit, $maxConcurrent); + } + + /** + * Helper function to determine the maximum number of overlapping intervals. + * + * @param array $intervals + * @return int + */ + private function getMaxConcurrentIntervals(array $intervals) + { + $events = []; + foreach ($intervals as $interval) { + $events[] = ['time' => $interval['start'], 'type' => 'start']; + $events[] = ['time' => $interval['end'], 'type' => 'end']; + } + + // Sort events by time, 'start' before 'end' if times are equal. + usort($events, function ($a, $b) { + if ($a['time'] == $b['time']) { + return $a['type'] === 'start' ? -1 : 1; + } + return $a['time'] < $b['time'] ? -1 : 1; + }); + + $maxConcurrent = 0; + $currentConcurrent = 0; + + foreach ($events as $event) { + if ($event['type'] === 'start') { + $currentConcurrent++; + if ($currentConcurrent > $maxConcurrent) { + $maxConcurrent = $currentConcurrent; + } + } else { + $currentConcurrent--; + } + } + + return $maxConcurrent; + } + + /** + * Test that callables are executed in parallel when no concurrency limit is set. + */ + public function testParallelExecutionWithoutConcurrencyLimit() + { + $parallel = new Parallel(); + + $startTimes = []; + $endTimes = []; + + $parallel->add(function () use (&$startTimes, &$endTimes) { + $startTimes[] = microtime(true); + Timer::sleep(0.1); // 100 milliseconds + $endTimes[] = microtime(true); + return 'task1'; + }, 'task1'); + + $parallel->add(function () use (&$startTimes, &$endTimes) { + $startTimes[] = microtime(true); + Timer::sleep(0.1);// 100 milliseconds + $endTimes[] = microtime(true); + return 'task2'; + }, 'task2'); + + $parallel->wait(); + + // Calculate total elapsed time. + $totalTime = max($endTimes) - min($startTimes); + + // The total time should be approximately the duration of one task, not the sum of both. + $this->assertLessThan(0.2, $totalTime); + } + + /** + * Test adding callables without specifying keys and ensure results are correctly indexed. + */ + public function testAddWithoutKeys() + { + $parallel = new Parallel(); + + $parallel->add(function () { + return 'result1'; + }); + + $parallel->add(function () { + return 'result2'; + }); + + $results = $parallel->wait(); + + // Since no keys were specified, indices should be 0 and 1. + $this->assertEquals(['result1', 'result2'], $results); + } + + /** + * Test that the Parallel class can handle a large number of tasks. + */ + public function testLargeNumberOfTasks() + { + $parallel = new Parallel(); + + $taskCount = 100; + for ($i = 0; $i < $taskCount; $i++) { + $parallel->add(function () use ($i) { + return $i * $i; + }, "task{$i}"); + } + + $results = $parallel->wait(); + + // Verify that all tasks have been completed and results are correct. + for ($i = 0; $i < $taskCount; $i++) { + $this->assertEquals($i * $i, $results["task{$i}"]); + } + } + + /** + * Test that adding a non-callable throws a TypeError. + */ + public function testAddNonCallable() + { + $this->expectException(\TypeError::class); + + $parallel = new Parallel(); + $parallel->add('not a callable'); + } + + /** + * Test that the wait method can be called multiple times safely. + */ + public function testMultipleWaitCalls() + { + $parallel = new Parallel(); + + $parallel->add(function () { + return 'first call'; + }, 'task1'); + + $resultsFirst = $parallel->wait(); + + $this->assertEquals(['task1' => 'first call'], $resultsFirst); + + // Add another task after first wait. + $parallel->add(function () { + return 'second call'; + }, 'task2'); + + $resultsSecond = $parallel->wait(); + + // Since the callbacks array is not cleared after wait, results should include both tasks. + $this->assertEquals(['task1' => 'first call', 'task2' => 'second call'], $resultsSecond); + } + + /** + * Test that the class properly handles empty tasks (no callables added). + */ + public function testNoTasks() + { + $parallel = new Parallel(); + + $results = $parallel->wait(); + + $this->assertEmpty($results); + } + + /** + * Test that the class handles tasks that return null. + */ + public function testTasksReturningNull() + { + $parallel = new Parallel(); + + $parallel->add(function () { + // No return statement, implicitly returns null. + }, 'nullTask'); + + $results = $parallel->wait(); + + $this->assertArrayHasKey('nullTask', $results); + $this->assertNull($results['nullTask']); + } + + /** + * Test defer can be used in tasks. + */ + public function testWithDefer() + { + $parallel = new Parallel(); + $results = []; + $parallel->add(function () use (&$results) { + Coroutine::defer(function () use (&$results) { + $results[] = 'defer1'; + }); + }); + $parallel->wait(); + $this->assertEquals(['defer1'], $results); + } + +} + diff --git a/vendor/workerman/coroutine/tests/PoolTest.php b/vendor/workerman/coroutine/tests/PoolTest.php new file mode 100644 index 0000000..b2b4770 --- /dev/null +++ b/vendor/workerman/coroutine/tests/PoolTest.php @@ -0,0 +1,678 @@ +<?php + +namespace test; + +use PHPUnit\Framework\TestCase; +use ReflectionMethod; +use ReflectionProperty; +use Workerman\Coroutine; +use Workerman\Coroutine\Exception\PoolException; +use Workerman\Coroutine\Pool; +use Psr\Log\LoggerInterface; +use ReflectionClass; +use stdClass; +use Exception; +use Workerman\Events\Event; +use Workerman\Events\Select; +use Workerman\Timer; +use Workerman\Worker; + +class PoolTest extends TestCase +{ + + public function testConstructorWithConfig() + { + $config = [ + 'min_connections' => 2, + 'idle_timeout' => 30, + 'heartbeat_interval' => 10, + 'wait_timeout' => 5, + ]; + $pool = new Pool(10, $config); + + $this->assertEquals(10, $this->getPrivateProperty($pool, 'maxConnections')); + $this->assertEquals(2, $this->getPrivateProperty($pool, 'minConnections')); + $this->assertEquals(30, $this->getPrivateProperty($pool, 'idleTimeout')); + $this->assertEquals(10, $this->getPrivateProperty($pool, 'heartbeatInterval')); + $this->assertEquals(5, $this->getPrivateProperty($pool, 'waitTimeout')); + } + + public function testSetConnectionCreator() + { + $pool = new Pool(5); + $connectionCreator = function () { + return new stdClass(); + }; + $pool->setConnectionCreator($connectionCreator); + $this->assertSame($connectionCreator, $this->getPrivateProperty($pool, 'connectionCreateHandler')); + } + + public function testSetConnectionCloser() + { + $pool = new Pool(5); + $connectionCloser = function ($conn) { + // Close connection. + }; + $pool->setConnectionCloser($connectionCloser); + $this->assertSame($connectionCloser, $this->getPrivateProperty($pool, 'connectionDestroyHandler')); + } + + public function testGetConnection() + { + $pool = new Pool(5); + + $connectionMock = $this->createMock(stdClass::class); + + // 设置连接创建器 + $pool->setConnectionCreator(function () use ($connectionMock) { + return $connectionMock; + }); + + $connection = $pool->get(); + + $this->assertSame($connectionMock, $connection); + $this->assertEquals(1, $this->getCurrentConnections($pool)); + + // 检查 WeakMap 是否更新 + $connections = $this->getPrivateProperty($pool, 'connections'); + $lastUsedTimes = $this->getPrivateProperty($pool, 'lastUsedTimes'); + $lastHeartbeatTimes = $this->getPrivateProperty($pool, 'lastHeartbeatTimes'); + + $this->assertTrue($connections->offsetExists($connection)); + $this->assertTrue($lastUsedTimes->offsetExists($connection)); + $this->assertTrue($lastHeartbeatTimes->offsetExists($connection)); + } + + public function testPutConnection() + { + $pool = new Pool(5); + + $connectionMock = $this->createMock(stdClass::class); + + $pool->setConnectionCreator(function () use ($connectionMock) { + return $connectionMock; + }); + + $connection = $pool->get(); + + $pool->put($connection); + + if (Coroutine::isCoroutine()) { + $channel = $this->getPrivateProperty($pool, 'channel'); + $this->assertEquals(1, $channel->length()); + } + + $this->assertEquals(1, $pool->getConnectionCount()); + } + + public function testPutConnectionDoesNotBelong() + { + $this->expectException(PoolException::class); + $this->expectExceptionMessage('The connection does not belong to the connection pool.'); + + $pool = new Pool(5); + $connection = new stdClass(); + + $pool->put($connection); + } + + public function testPutSameConnectionTwice() + { + $pool = new Pool(2); + $created = 0; + $closed = 0; + $pool->setConnectionCreator(function () use (&$created) { + $created++; + return new stdClass(); + }); + $pool->setConnectionCloser(function () use (&$closed) { + $closed++; + }); + + $connection = $pool->get(); + $pool->put($connection); + + // 非协程下归还是空操作,重复归还不能抛异常,也不能新建连接。 + if (!Coroutine::isCoroutine()) { + $pool->put($connection); + $this->assertSame($connection, $pool->get()); + $this->assertEquals(1, $created); + $this->assertEquals(0, $closed); + $this->assertEquals(1, $pool->getConnectionCount()); + return; + } + + try { + $pool->put($connection); + $this->fail('Putting the same connection twice should throw.'); + } catch (PoolException $exception) { + $this->assertSame('The connection has already been returned to the connection pool.', $exception->getMessage()); + } + + $channel = $this->getPrivateProperty($pool, 'channel'); + $this->assertEquals(1, $channel->length()); + $this->assertEquals(1, $created); + $this->assertEquals(0, $closed); + $this->assertEquals(1, $pool->getConnectionCount()); + + $first = $pool->get(); + $second = $pool->get(); + $this->assertSame($connection, $first); + $this->assertNotSame($first, $second); + $this->assertEquals(2, $pool->getConnectionCount()); + + $pool->put($first); + $pool->put($second); + $this->assertEquals(2, $channel->length()); + + // 池子已满时,重复归还必须立刻失败,不能阻塞在通道写入上。 + $repeatedReturnFinished = false; + $repeatedReturnException = null; + Coroutine::create(function () use ($pool, $first, &$repeatedReturnFinished, &$repeatedReturnException) { + try { + $pool->put($first); + } catch (PoolException $exception) { + $repeatedReturnException = $exception; + } + $repeatedReturnFinished = true; + }); + Timer::sleep(0.05); + + $this->assertTrue($repeatedReturnFinished); + $this->assertInstanceOf(PoolException::class, $repeatedReturnException); + $this->assertSame('The connection has already been returned to the connection pool.', $repeatedReturnException->getMessage()); + $this->assertEquals(2, $channel->length()); + $this->assertEquals(2, $created); + $this->assertEquals(0, $closed); + $this->assertEquals(2, $pool->getConnectionCount()); + } + + public function testGetDiscardsConnectionClosedAfterReturn() + { + $pool = new Pool(3, ['wait_timeout' => 2]); + $closed = []; + $pool->setConnectionCreator(function () { + return new stdClass(); + }); + $pool->setConnectionCloser(function (object $connection) use (&$closed) { + $closed[spl_object_id($connection)] = $connection; + }); + + $connection = $pool->get(); + $pool->put($connection); + $pool->closeConnection($connection); + + $this->assertCount(1, $closed); + $this->assertSame($connection, $closed[spl_object_id($connection)]); + $this->assertEquals(0, $pool->getConnectionCount()); + + // 非协程连接不会进入通道,关闭后下次 get() 直接新建。 + if (!Coroutine::isCoroutine()) { + $replacement = $pool->get(); + $this->assertNotSame($connection, $replacement); + $this->assertEquals(1, $pool->getConnectionCount()); + return; + } + + $kept = $pool->get(); + $discarded = [$pool->get(), $pool->get()]; + $pool->put($kept); + foreach ($discarded as $item) { + $pool->put($item); + $pool->closeConnection($item); + } + + $started = microtime(true); + $borrowed = $pool->get(); + $elapsed = microtime(true) - $started; + + $this->assertSame($kept, $borrowed); + $this->assertArrayNotHasKey(spl_object_id($borrowed), $closed); + $this->assertLessThan(0.5, $elapsed); + $this->assertEquals(1, $pool->getConnectionCount()); + $this->assertCount(3, $closed); + } + + public function testCheckConnectionsSkipsConnectionClosedAfterReturn() + { + if (!Coroutine::isCoroutine()) { + $this->assertTrue(true); + return; + } + + $pool = new Pool(3, ['idle_timeout' => 3600, 'min_connections' => 1]); + $closed = 0; + $pool->setConnectionCreator(function () { + return new stdClass(); + }); + $pool->setConnectionCloser(function () use (&$closed) { + $closed++; + }); + + $closedConnection = $pool->get(); + $kept = $pool->get(); + $pool->put($closedConnection); + $pool->put($kept); + $pool->closeConnection($closedConnection); + + $this->assertEquals(1, $closed); + $this->assertEquals(1, $pool->getConnectionCount()); + + $reflectedMethod = new ReflectionMethod($pool, 'checkConnections'); + $reflectedMethod->invoke($pool); + + $channel = $this->getPrivateProperty($pool, 'channel'); + $this->assertEquals(1, $channel->length()); + $this->assertEquals(1, $closed); + $this->assertSame($kept, $pool->get()); + + // 队列里只剩已关闭的连接时,检查过程也不能抛错。 + $pool->put($kept); + $pool->closeConnection($kept); + $reflectedMethod->invoke($pool); + + $this->assertEquals(0, $channel->length()); + $this->assertEquals(0, $pool->getConnectionCount()); + $this->assertEquals(2, $closed); + } + + public function testConnectionClosedDuringHeartbeatIsNotReused() + { + if (!Coroutine::isCoroutine()) { + $this->assertTrue(true); + return; + } + + $pool = new Pool(1, [ + 'heartbeat_interval' => 0, + 'idle_timeout' => 3600, + 'min_connections' => 0, + ]); + $closed = []; + $pool->setConnectionCreator(function () { + return new stdClass(); + }); + $pool->setConnectionCloser(function (object $connection) use (&$closed) { + $closed[spl_object_id($connection)] = true; + }); + $pool->setHeartbeatChecker(function (object $connection) use ($pool) { + $pool->closeConnection($connection); + }); + + $connection = $pool->get(); + $pool->put($connection); + + $reflectedMethod = new ReflectionMethod($pool, 'checkConnections'); + $reflectedMethod->invoke($pool); + $reflectedMethod->invoke($pool); + + $replacement = $pool->get(); + $this->assertNotSame($connection, $replacement); + $this->assertArrayHasKey(spl_object_id($connection), $closed); + $this->assertArrayNotHasKey(spl_object_id($replacement), $closed); + $this->assertEquals(1, $pool->getConnectionCount()); + $this->assertCount(1, $closed); + } + + public function testConcurrentBorrowReturnAndClose() + { + if (in_array(Worker::$eventLoopClass, [Select::class, Event::class], true)) { + $this->assertTrue(true); + return; + } + + $maxConnections = 8; + $workers = 60; + $rounds = 40; + $pool = new Pool($maxConnections, [ + 'wait_timeout' => 5, + 'idle_timeout' => 3600, + 'heartbeat_interval' => 0, + 'min_connections' => 1, + ]); + $errors = []; + $done = 0; + $operations = 0; + $closedCount = 0; + $inUse = []; + $pool->setConnectionCreator(function () { + return new stdClass(); + }); + $pool->setConnectionCloser(function (object $connection) use (&$closedCount) { + $connection->closed = true; + $closedCount++; + }); + $pool->setHeartbeatChecker(function () { + Timer::sleep(0.001); + }); + + $reflectedMethod = new ReflectionMethod($pool, 'checkConnections'); + Coroutine::create(function () use ($pool, $reflectedMethod, $workers, &$done) { + while ($done < $workers) { + $reflectedMethod->invoke($pool); + Timer::sleep(0.005); + } + }); + + for ($i = 0; $i < $workers; $i++) { + Coroutine::create(function () use ($pool, $rounds, $maxConnections, &$inUse, &$errors, &$done, &$operations) { + try { + for ($n = 0; $n < $rounds; $n++) { + $connection = $pool->get(); + $id = spl_object_id($connection); + if (isset($inUse[$id])) { + $errors[] = "connection $id borrowed twice"; + } + if (!empty($connection->closed)) { + $errors[] = "closed connection $id was borrowed again"; + } + $inUse[$id] = true; + Timer::sleep(0.001); + unset($inUse[$id]); + if ($n % 10 === 0) { + $pool->closeConnection($connection); + } else { + $pool->put($connection); + } + $operations++; + if ($pool->getConnectionCount() > $maxConnections) { + $errors[] = 'connection count exceeded the pool limit'; + } + } + } catch (\Throwable $throwable) { + $errors[] = $throwable::class . ': ' . $throwable->getMessage(); + } finally { + $done++; + } + }); + } + + $deadline = microtime(true) + 60; + while ($done < $workers && microtime(true) < $deadline) { + Timer::sleep(0.02); + } + + $this->assertSame($workers, $done, implode(PHP_EOL, array_slice($errors, 0, 8))); + $this->assertCount(0, $errors, implode(PHP_EOL, array_slice($errors, 0, 8))); + $this->assertSame($workers * $rounds, $operations); + $this->assertSame([], $inUse); + $this->assertLessThanOrEqual($maxConnections, $pool->getConnectionCount()); + $this->assertGreaterThan(0, $closedCount); + } + + public function testCreateConnection() + { + $pool = new Pool(5); + $connectionMock = $this->createMock(stdClass::class); + + $pool->setConnectionCreator(function () use ($connectionMock) { + return $connectionMock; + }); + + $connection = $pool->createConnection(); + + $this->assertSame($connectionMock, $connection); + + // 确保 currentConnections 增加 + $this->assertEquals(1, $this->getCurrentConnections($pool)); + + // 检查 WeakMap 是否更新 + $connections = $this->getPrivateProperty($pool, 'connections'); + $lastUsedTimes = $this->getPrivateProperty($pool, 'lastUsedTimes'); + $lastHeartbeatTimes = $this->getPrivateProperty($pool, 'lastHeartbeatTimes'); + + $this->assertTrue($connections->offsetExists($connection)); + $this->assertTrue($lastUsedTimes->offsetExists($connection)); + $this->assertTrue($lastHeartbeatTimes->offsetExists($connection)); + } + + public function testCreateMaxConnections() + { + if (in_array(Worker::$eventLoopClass, [Select::class, Event::class])) { + $this->assertTrue(true); + return; + } + $maxConnections = 2; + $pool = new Pool($maxConnections); + + $pool->setConnectionCreator(function () { + Timer::sleep(0.01); + return $this->createMock(stdClass::class); + }); + + $connections = []; + for ($i = 0; $i < 3; $i++) { + Coroutine::create(function () use ($pool, &$connections) { + $connections[] = $pool->get(); + }); + } + + Timer::sleep(0.1); + $this->assertEquals($maxConnections, $this->getCurrentConnections($pool)); + + $lastUsedTimes = $this->getPrivateProperty($pool, 'lastUsedTimes'); + $lastHeartbeatTimes = $this->getPrivateProperty($pool, 'lastHeartbeatTimes'); + + $this->assertCount($maxConnections, $lastUsedTimes); + $this->assertCount($maxConnections, $lastHeartbeatTimes); + + foreach ($connections as $connection) { + $pool->put($connection); + } + + } + + public function testCreateConnectionThrowsException() + { + $pool = new Pool(5); + + $pool->setConnectionCreator(function () { + throw new Exception('Failed to create connection'); + }); + + $this->expectException(Exception::class); + $this->expectExceptionMessage('Failed to create connection'); + + try { + $pool->createConnection(); + } finally { + // 确保 currentConnections 减少 + $this->assertEquals(0, $this->getCurrentConnections($pool)); + } + } + + public function testCloseConnection() + { + $pool = new Pool(5); + + $connection = $this->createMock(ConnectionMock::class); + + // 模拟连接属于连接池 + $connections = $this->getPrivateProperty($pool, 'connections'); + $connections[$connection] = time(); + + $connection->expects($this->once())->method('close'); + $pool->setConnectionCloser(function ($conn) { + $conn->close(); + }); + + $pool->closeConnection($connection); + + // 确保 currentConnections 减少 + $this->assertEquals(0, $this->getCurrentConnections($pool)); + + // 确保连接从 WeakMap 中移除 + $this->assertFalse($connections->offsetExists($connection)); + } + + public function testCloseConnections() + { + $maxConnections = 5; + + $pool = new Pool($maxConnections); + + $pool->setConnectionCreator(function () { + $connection = $this->createMock(ConnectionMock::class); + $connection->expects($this->once())->method('close'); + return $connection; + }); + + $pool->setConnectionCloser(function ($conn) { + $conn->close(); + }); + + $connections = []; + for ($i = 0; $i < $maxConnections; $i++) { + $connections[] = $pool->get(); + } + + $this->assertEquals(Coroutine::isCoroutine() ? $maxConnections : 1, $this->getCurrentConnections($pool)); + + $pool->closeConnections(); + $this->assertEquals(Coroutine::isCoroutine() ? $maxConnections : 0, $this->getCurrentConnections($pool)); + if (!Coroutine::isCoroutine()) { + return; + } + + foreach ($connections as $connection) { + $pool->put($connection); + } + $this->assertEquals($maxConnections, $this->getCurrentConnections($pool)); + $pool->closeConnections(); + $this->assertEquals(0, $this->getCurrentConnections($pool)); + + $connections = []; + for ($i = 0; $i < $maxConnections; $i++) { + $connections[] = $pool->get(); + } + $this->assertEquals($maxConnections, $this->getCurrentConnections($pool)); + foreach ($connections as $connection) { + $pool->put($connection); + } + $pool->closeConnections(); + unset($connections); + $this->assertEquals(0, $this->getCurrentConnections($pool)); + } + + public function testCloseConnectionWithExceptionInDestroyHandler() + { + $pool = new Pool(5); + + $connection = $this->createMock(stdClass::class); + + // 模拟连接属于连接池 + $connections = $this->getPrivateProperty($pool, 'connections'); + $connections[$connection] = time(); + + $exception = new Exception('Error closing connection'); + + $pool->setConnectionCloser(function ($conn) use ($exception) { + throw $exception; + }); + + // 设置日志记录器 + $loggerMock = $this->createMock(LoggerInterface::class); + $loggerMock->expects($this->once()) + ->method('info') + ->with($this->stringContains('Error closing connection')); + + $this->setPrivateProperty($pool, 'logger', $loggerMock); + + $pool->closeConnection($connection); + + // 确保 currentConnections 减少 + $this->assertEquals(0, $this->getCurrentConnections($pool)); + + // 确保连接从 WeakMap 中移除 + $this->assertFalse($connections->offsetExists($connection)); + } + + public function testHeartbeatChecker() + { + $pool = $this->getMockBuilder(Pool::class) + ->setConstructorArgs([5]) + ->onlyMethods(['closeConnection']) + ->getMock(); + + $connection = $this->createMock(stdClass::class); + + // 设置连接心跳检测器 + $pool->setHeartbeatChecker(function ($conn) { + // 模拟心跳检测 + }); + + // 模拟连接在通道中 + $channel = $this->getPrivateProperty($pool, 'channel'); + $channel->push($connection); + + // 设置连接的上次使用时间和心跳时间 + $connections = $this->getPrivateProperty($pool, 'connections'); + $connections[$connection] = time(); + + $lastUsedTimes = $this->getPrivateProperty($pool, 'lastUsedTimes'); + $lastUsedTimes[$connection] = time(); + + $lastHeartbeatTimes = $this->getPrivateProperty($pool, 'lastHeartbeatTimes'); + $lastHeartbeatTimes[$connection] = time() - 100; // 超过心跳间隔 + + // 调用受保护的 checkConnections 方法 + $reflectedMethod = new ReflectionMethod($pool, 'checkConnections'); + $reflectedMethod->invoke($pool); + + // 检查心跳时间是否更新 + $lastHeartbeatTimes = $this->getPrivateProperty($pool, 'lastHeartbeatTimes'); + $this->assertGreaterThan(time() - 2, $lastHeartbeatTimes[$connection]); + } + + public function testConnectionDestroyedWithoutReturn() + { + $pool = new Pool(5); + + // 设置连接创建器 + $pool->setConnectionCreator(function () { + return new stdClass; + }); + + // 获取初始的 currentConnections + $initialConnections = $this->getCurrentConnections($pool); + + // 从连接池获取一个连接 + $connection = $pool->get(); + + // 检查 currentConnections 是否增加 + $this->assertEquals(Coroutine::isCoroutine() ? $initialConnections + 1 : 1, $this->getCurrentConnections($pool)); + + // 不归还连接,并销毁连接对象 + unset($connection); + + // 检查 currentConnections 是否减少 + $this->assertEquals(Coroutine::isCoroutine() ? $initialConnections : 1, $this->getCurrentConnections($pool)); + } + + private function getPrivateProperty($object, string $property) + { + $prop = new ReflectionProperty($object, $property); + return $prop->getValue($object); + } + + private function setPrivateProperty($object, string $property, $value) + { + $prop = new ReflectionProperty($object, $property); + $prop->setValue($object, $value); + } + + private function getCurrentConnections($object): int + { + return $object->getConnectionCount(); + } + +} + +// 定义 ConnectionMock 类用于测试 +class ConnectionMock +{ + public function close() + { + // 模拟关闭连接 + } +} diff --git a/vendor/workerman/coroutine/tests/WaitGroupTest.php b/vendor/workerman/coroutine/tests/WaitGroupTest.php new file mode 100644 index 0000000..17d16fc --- /dev/null +++ b/vendor/workerman/coroutine/tests/WaitGroupTest.php @@ -0,0 +1,56 @@ +<?php + +declare(strict_types=1); + +namespace tests; + +use PHPUnit\Framework\TestCase; +use Workerman\Coroutine; +use Workerman\Timer; +use Workerman\Coroutine\WaitGroup; + +/** + * Class WaitGroupTest + * + * Tests for the Fiber WaitGroup implementation. + */ +class WaitGroupTest extends TestCase +{ + + public function testWaitWaitGroupDone() + { + $waitGroup = new WaitGroup(); + $this->assertEquals(0, $waitGroup->count()); + $results = [0]; + $this->assertTrue($waitGroup->add()); + Coroutine::create(function () use ($waitGroup, &$results) { + try { + Timer::sleep(0.1); + $results[] = 1; + } finally { + $this->assertTrue($waitGroup->done()); + } + }); + $this->assertTrue($waitGroup->add()); + Coroutine::create(function () use ($waitGroup, &$results) { + try { + Timer::sleep(0.2); + $results[] = 2; + } finally { + $this->assertTrue($waitGroup->done()); + } + }); + $this->assertTrue($waitGroup->add()); + Coroutine::create(function () use ($waitGroup, &$results) { + try { + Timer::sleep(0.3); + $results[] = 3; + } finally { + $this->assertTrue($waitGroup->done()); + } + }); + $this->assertTrue($waitGroup->wait()); + $this->assertEquals(0, $waitGroup->count(), 'WaitGroup count should be 0 after wait is called.'); + $this->assertEquals([0, 1, 2, 3], $results, 'All coroutines should have been executed.'); + } +} diff --git a/vendor/workerman/coroutine/tests/start.php b/vendor/workerman/coroutine/tests/start.php new file mode 100644 index 0000000..62fa8a0 --- /dev/null +++ b/vendor/workerman/coroutine/tests/start.php @@ -0,0 +1,109 @@ +<?php + +use Workerman\Events\Event; +use Workerman\Events\Select; +use Workerman\Events\Swow; +use Workerman\Events\Swoole; +use Workerman\Events\Fiber; +use Workerman\Timer; +use Workerman\Worker; + +require_once __DIR__ . '/../vendor/autoload.php'; + +$phpunitDisplayOptions = [ + '--colors=always', + '--display-deprecations', + '--display-phpunit-deprecations', + '--display-errors', + '--display-notices', + '--display-warnings', + '--display-incomplete', + '--display-skipped', +]; + +if (DIRECTORY_SEPARATOR === '/' || (!extension_loaded('swow') && !class_exists(Revolt\EventLoop::class))) { + create_test_worker(function () use ($phpunitDisplayOptions) { + (new PHPUnit\TextUI\Application)->run([ + __DIR__ . '/../vendor/bin/phpunit', + ...$phpunitDisplayOptions, + __DIR__ . '/ChannelTest.php', + __DIR__ . '/PoolTest.php', + __DIR__ . '/BarrierTest.php', + __DIR__ . '/ContextTest.php', + __DIR__ . '/WaitGroupTest.php', + ]); + }, Select::class); +} + +if (extension_loaded('event')) { + create_test_worker(function () use ($phpunitDisplayOptions) { + (new PHPUnit\TextUI\Application)->run([ + __DIR__ . '/../vendor/bin/phpunit', + ...$phpunitDisplayOptions, + __DIR__ . '/ChannelTest.php', + __DIR__ . '/PoolTest.php', + __DIR__ . '/BarrierTest.php', + __DIR__ . '/ContextTest.php', + __DIR__ . '/WaitGroupTest.php', + ]); + }, Event::class); +} + +if (class_exists(Revolt\EventLoop::class) && (DIRECTORY_SEPARATOR === '/' || !extension_loaded('swow'))) { + create_test_worker(function () use ($phpunitDisplayOptions) { + (new PHPUnit\TextUI\Application)->run([ + __DIR__ . '/../vendor/bin/phpunit', + ...$phpunitDisplayOptions, + ...glob(__DIR__ . '/*Test.php') + ]); + }, Fiber::class); +} + +if (extension_loaded('Swoole')) { + create_test_worker(function () use ($phpunitDisplayOptions) { + (new PHPUnit\TextUI\Application)->run([ + __DIR__ . '/../vendor/bin/phpunit', + ...$phpunitDisplayOptions, + ...glob(__DIR__ . '/*Test.php') + ]); + }, Swoole::class); +} + +if (extension_loaded('Swow')) { + create_test_worker(function () use ($phpunitDisplayOptions) { + (new PHPUnit\TextUI\Application)->run([ + __DIR__ . '/../vendor/bin/phpunit', + ...$phpunitDisplayOptions, + ...glob(__DIR__ . '/*Test.php') + ]); + }, Swow::class); +} + +function create_test_worker(Closure $callable, $eventLoopClass): void +{ + $worker = new Worker(); + $worker->eventLoop = $eventLoopClass; + $worker->onWorkerStart = function () use ($callable, $eventLoopClass) { + $fp = fopen(__FILE__, 'r+'); + flock($fp, LOCK_EX); + echo PHP_EOL . PHP_EOL. PHP_EOL . '[TEST EVENT-LOOP: ' . basename(str_replace('\\', '/', $eventLoopClass)) . ']' . PHP_EOL; + try { + $callable(); + } catch (Throwable $e) { + echo $e; + } finally { + flock($fp, LOCK_UN); + } + Timer::repeat(1, function () use ($fp) { + if (flock($fp, LOCK_EX | LOCK_NB)) { + if(function_exists('posix_kill')) { + posix_kill(posix_getppid(), SIGINT); + } else { + Worker::stopAll(); + } + } + }); + }; +} + +Worker::runAll(); diff --git a/vendor/workerman/webman-framework/.gitignore b/vendor/workerman/webman-framework/.gitignore new file mode 100644 index 0000000..3f2c43a --- /dev/null +++ b/vendor/workerman/webman-framework/.gitignore @@ -0,0 +1,5 @@ +composer.lock +vendor +vendor/ +.idea +.idea/ \ No newline at end of file diff --git a/vendor/workerman/webman-framework/README.md b/vendor/workerman/webman-framework/README.md new file mode 100644 index 0000000..96a900a --- /dev/null +++ b/vendor/workerman/webman-framework/README.md @@ -0,0 +1,5 @@ +# webman-framework +Note: This repository is the core code of the webman framework. If you want to build an application using webman, visit the main [webman](https://github.com/walkor/webman) repository. + +## LICENSE +MIT diff --git a/vendor/workerman/webman-framework/composer.json b/vendor/workerman/webman-framework/composer.json new file mode 100644 index 0000000..6719660 --- /dev/null +++ b/vendor/workerman/webman-framework/composer.json @@ -0,0 +1,52 @@ +{ + "name": "workerman/webman-framework", + "type": "library", + "keywords": [ + "high performance", + "http service" + ], + "homepage": "https://www.workerman.net", + "license": "MIT", + "description": "High performance HTTP Service Framework.", + "authors": [ + { + "name": "walkor", + "email": "walkor@workerman.net", + "homepage": "https://www.workerman.net", + "role": "Developer" + } + ], + "support": { + "email": "walkor@workerman.net", + "issues": "https://github.com/walkor/webman/issues", + "forum": "https://wenda.workerman.net/", + "wiki": "https://doc.workerman.net/", + "source": "https://github.com/walkor/webman-framework" + }, + "require": { + "php": ">=8.1", + "ext-json": "*", + "workerman/workerman": "^5.1 || dev-master", + "nikic/fast-route": "^1.3", + "psr/container": ">=1.0", + "psr/log": "^2.0 || ^3.0" + }, + "suggest": { + "ext-event": "For better performance. " + }, + "autoload": { + "psr-4": { + "Webman\\": "./src", + "support\\": "./src/support", + "Support\\": "./src/support", + "Support\\Bootstrap\\": "./src/support/bootstrap", + "Support\\Exception\\": "./src/support/exception", + "Support\\View\\": "./src/support/view" + }, + "files": [ + "./src/support/helpers.php" + ] + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/vendor/workerman/webman-framework/src/App.php b/vendor/workerman/webman-framework/src/App.php new file mode 100644 index 0000000..0cdd50d --- /dev/null +++ b/vendor/workerman/webman-framework/src/App.php @@ -0,0 +1,1384 @@ +<?php + +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + +use ArrayObject; +use Closure; +use Exception; +use FastRoute\Dispatcher; +use Illuminate\Database\Eloquent\Model; +use Psr\Log\LoggerInterface; +use ReflectionEnum; +use support\exception\InputValueException; +use support\exception\PageNotFoundException; +use think\Model as ThinkModel; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\ContainerInterface; +use Psr\Container\NotFoundExceptionInterface; +use ReflectionClass; +use ReflectionException; +use ReflectionFunction; +use ReflectionFunctionAbstract; +use ReflectionMethod; +use support\exception\MissingInputException; +use support\exception\RecordNotFoundException; +use support\exception\InputTypeException; +use Throwable; +use Webman\Exception\ExceptionHandler; +use Webman\Exception\ExceptionHandlerInterface; +use Webman\Http\Request; +use Webman\Http\Response; +use Webman\Route\Route as RouteObject; +use support\annotation\route\Route as RouteAttribute; +use Workerman\Connection\TcpConnection; +use Workerman\Protocols\Http; +use Workerman\Worker; +use function array_merge; +use function array_pop; +use function array_reduce; +use function array_splice; +use function array_values; +use function class_exists; +use function clearstatcache; +use function count; +use function current; +use function end; +use function explode; +use function get_class_methods; +use function gettype; +use function implode; +use function is_a; +use function is_array; +use function is_dir; +use function is_file; +use function is_numeric; +use function is_object; +use function is_string; +use function key; +use function method_exists; +use function ob_get_clean; +use function ob_start; +use function pathinfo; +use function scandir; +use function str_replace; +use function strpos; +use function strtolower; +use function substr; +use function trim; + +/** + * Class App + * @package Webman + */ +class App +{ + + /** + * @var callable[] + */ + protected static $callbacks = []; + + /** + * @var array<string, ReflectionFunctionAbstract> + */ + protected static array $reflectorCache = []; + + /** + * @var array<string, array<int, array<string, mixed>>> + */ + protected static array $parameterMetadataCache = []; + + /** + * @var Worker + */ + protected static $worker = null; + + /** + * @var ?LoggerInterface + */ + protected static ?LoggerInterface $logger = null; + + /** + * @var string + */ + protected static $appPath = ''; + + /** + * @var string + */ + protected static $publicPath = ''; + + /** + * @var string + */ + protected static $requestClass = ''; + + /** + * App constructor. + * @param string $requestClass + * @param LoggerInterface $logger + * @param string $appPath + * @param string $publicPath + */ + public function __construct(string $requestClass, LoggerInterface $logger, string $appPath, string $publicPath) + { + static::$requestClass = $requestClass; + static::$logger = $logger; + static::$publicPath = $publicPath; + static::$appPath = $appPath; + } + + /** + * OnMessage. + * @param TcpConnection|mixed $connection + * @param Request|mixed $request + * @return null + * @throws Throwable + */ + public function onMessage($connection, $request) + { + try { + Context::reset(new ArrayObject([Request::class => $request])); + $path = $request->path(); + $key = $request->method() . $path; + if (isset(static::$callbacks[$key])) { + [$callback, $request->plugin, $request->app, $request->controller, $request->action, $request->route] = static::$callbacks[$key]; + static::send($connection, $callback($request), $request); + return null; + } + + $status = 200; + if ( + static::unsafeUri($connection, $path, $request) || + static::findFile($connection, $path, $key, $request) || + static::findRoute($connection, $path, $key, $request, $status) + ) { + return null; + } + + $controllerAndAction = static::parseControllerAction($path); + $plugin = $controllerAndAction['plugin'] ?? static::getPluginByPath($path); + if (!$controllerAndAction || \Webman\Route::isDefaultRouteDisabled($plugin, $controllerAndAction['app'] ?: '*') || + \Webman\Route::isDefaultRouteDisabled($controllerAndAction['controller']) || + \Webman\Route::isDefaultRouteDisabled([$controllerAndAction['controller'], $controllerAndAction['action']])) { + $request->plugin = $plugin; + $callback = static::getFallback($plugin, $status); + $request->app = $request->controller = $request->action = ''; + static::send($connection, $callback($request), $request); + return null; + } + $app = $controllerAndAction['app']; + $controller = $controllerAndAction['controller']; + $action = $controllerAndAction['action']; + + if ($methodNotAllowed = static::defaultRouteMethodNotAllowedResponse($controller, $action, $request->method())) { + $callback = $methodNotAllowed; + static::collectCallbacks($key, [$callback, $plugin, $app, $controller, $action, null]); + [$callback, $request->plugin, $request->app, $request->controller, $request->action, $request->route] = static::$callbacks[$key]; + static::send($connection, $callback($request), $request); + return null; + } + + $callback = static::getCallback($plugin, $app, [$controller, $action]); + static::collectCallbacks($key, [$callback, $plugin, $app, $controller, $action, null]); + [$callback, $request->plugin, $request->app, $request->controller, $request->action, $request->route] = static::$callbacks[$key]; + static::send($connection, $callback($request), $request); + } catch (Throwable $e) { + static::send($connection, static::exceptionResponse($e, $request), $request); + } + return null; + } + + /** + * Method allowlist for default route (no explicit route path). + * If action method has Route attributes with empty path, they are treated as allowed methods. + * Returns a cached callback producing 405 response when current method is not allowed, otherwise null. + * @param string $controllerClass + * @param string $action + * @param string $httpMethod + * @return callable|null + */ + protected static function defaultRouteMethodNotAllowedResponse(string $controllerClass, string $action, string $httpMethod): ?callable + { + $httpMethod = strtoupper($httpMethod); + static $allowedCache = []; + $cacheKey = $controllerClass . '::' . $action; + + if (!isset($allowedCache[$cacheKey])) { + $allowed = []; + try { + if (method_exists($controllerClass, $action)) { + $ref = new ReflectionMethod($controllerClass, $action); + $attrs = $ref->getAttributes(RouteAttribute::class, \ReflectionAttribute::IS_INSTANCEOF); + foreach ($attrs as $attr) { + /** @var RouteAttribute $route */ + $route = $attr->newInstance(); + if ($route->path !== null) { + continue; + } + foreach ($route->methods as $m) { + $m = strtoupper((string)$m); + $allowed[$m] = $m; + } + } + } + } catch (Throwable $e) { + } + $allowedCache[$cacheKey] = $allowed; + if (count($allowedCache) > 1024) { + unset($allowedCache[key($allowedCache)]); + } + } else { + $allowed = $allowedCache[$cacheKey]; + } + + if (!$allowed || isset($allowed[$httpMethod])) { + return null; + } + + $allowHeader = implode(', ', array_values($allowed)); + return static function () use ($allowHeader) { + return new Response(405, ['Allow' => $allowHeader], '405 Method Not Allowed'); + }; + } + + /** + * OnWorkerStart. + * @param $worker + * @return void + */ + public function onWorkerStart($worker) + { + static::$worker = $worker; + Http::requestClass(static::$requestClass); + } + + /** + * CollectCallbacks. + * @param string $key + * @param array $data + * @return void + */ + protected static function collectCallbacks(string $key, array $data) + { + static::$callbacks[$key] = $data; + if (count(static::$callbacks) > 1024) { + unset(static::$callbacks[key(static::$callbacks)]); + } + } + + /** + * UnsafeUri. + * @param TcpConnection $connection + * @param string $path + * @param $request + * @return bool + */ + protected static function unsafeUri(TcpConnection $connection, string $path, $request): bool + { + if (!$path || $path[0] !== '/' || static::containsPathTraversal($path)) { + $callback = static::getFallback('', 400); + $request->plugin = $request->app = $request->controller = $request->action = ''; + static::send($connection, $callback($request, 400), $request); + return true; + } + return false; + } + + /** + * Check if a path contains directory traversal or dangerous sequences. + * @param string $path + * @return bool + */ + protected static function containsPathTraversal(string $path): bool + { + return strpos($path, '/../') !== false + || substr($path, -3) === '/..' + || strpos($path, "\\") !== false + || strpos($path, "\0") !== false; + } + + /** + * GetFallback. + * @param string $plugin + * @param int $status + * @return Closure + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws ReflectionException + */ + protected static function getFallback(string $plugin = '', int $status = 404): Closure + { + // When route, controller and action not found, try to use Route::fallback + return \Webman\Route::getFallback($plugin, $status) ?: function ($req = null) { + throw new PageNotFoundException(); + }; + } + + /** + * ExceptionResponse. + * @param Throwable $e + * @param $request + * @return Response + */ + protected static function exceptionResponse(Throwable $e, $request): Response + { + try { + $app = $request->app ?: ''; + $plugin = $request->plugin ?: ''; + $exceptionConfig = static::config($plugin, 'exception'); + $appExceptionConfig = static::config("", 'exception'); + if (!isset($exceptionConfig['']) && isset($appExceptionConfig['@'])) { + //如果插件没有配置自己的异常处理器并且配置了全局@异常处理器 则使用全局异常处理器 + $defaultException = $appExceptionConfig['@'] ?? ExceptionHandler::class; + } else { + $defaultException = $exceptionConfig[''] ?? ExceptionHandler::class; + } + $exceptionHandlerClass = $exceptionConfig[$app] ?? $defaultException; + + /** @var ExceptionHandlerInterface $exceptionHandler */ + $exceptionHandler = (static::container($plugin) ?? static::container(''))->make($exceptionHandlerClass, [ + 'logger' => static::$logger, + 'debug' => static::config($plugin, 'app.debug') + ]); + $exceptionHandler->report($e); + $response = $exceptionHandler->render($request, $e); + $response->exception($e); + return $response; + } catch (Throwable $e) { + $response = new Response(500, [], static::config($plugin ?? '', 'app.debug') ? (string)$e : $e->getMessage()); + $response->exception($e); + return $response; + } + } + + /** + * GetCallback. + * @param string $plugin + * @param string $app + * @param $call + * @param array $args + * @param bool $withGlobalMiddleware + * @param RouteObject|null $route + * @return callable + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws ReflectionException + */ + public static function getCallback(string $plugin, string $app, $call, array $args = [], bool $withGlobalMiddleware = true, ?RouteObject $route = null) + { + $isController = is_array($call) && is_string($call[0]); + $middlewares = Middleware::getMiddleware($plugin, $app, $call, $route, $withGlobalMiddleware); + + $container = static::container($plugin) ?? static::container(''); + foreach ($middlewares as $key => $item) { + $middleware = $item[0]; + if (is_string($middleware)) { + $middleware = $container->get($middleware); + } elseif ($middleware instanceof Closure) { + $middleware = call_user_func($middleware, $container); + } + $middlewares[$key][0] = $middleware; + } + + $needInject = static::isNeedInject($call, $args); + $anonymousArgs = array_values($args); + // Pre-compute return type for Response check optimization in middleware chain + $alwaysReturnsResponse = false; + if ($middlewares) { + try { + $returnType = static::getReflector($call)->getReturnType(); + $alwaysReturnsResponse = $returnType instanceof \ReflectionNamedType + && !$returnType->allowsNull() + && is_a($returnType->getName(), Response::class, true); + } catch (Throwable $e) { + } + } + if ($isController) { + $controllerReuse = static::config($plugin, 'app.controller_reuse', true); + if (!$controllerReuse) { + if ($needInject) { + // Pre-compute metadata at closure creation time + $reflector = static::getReflector($call); + $metadataList = static::getMethodParameterMetadata($reflector); + $debug = static::config($plugin, 'app.debug'); + $call = function ($request) use ($call, $plugin, $args, $container, $metadataList, $debug) { + $call[0] = $container->make($call[0]); + $inputs = $args ? array_merge($request->all(), $args) : $request->all(); + $resolvedArgs = array_values(static::resolveMethodDependenciesFromMetadata($container, $request, $inputs, $metadataList, $debug)); + return $call(...$resolvedArgs); + }; + $needInject = false; + } else { + $call = function ($request, ...$anonymousArgs) use ($call, $plugin, $container) { + $call[0] = $container->make($call[0]); + return $call($request, ...$anonymousArgs); + }; + } + } else { + $call[0] = $container->get($call[0]); + } + } + + if ($needInject) { + $call = static::resolveInject($container, $call, $args, static::config($plugin, 'app.debug')); + } + + if ($middlewares) { + if ($alwaysReturnsResponse) { + $innermost = function ($request) use ($call, $anonymousArgs) { + try { + return $call($request, ...$anonymousArgs); + } catch (Throwable $e) { + return static::exceptionResponse($e, $request); + } + }; + } else { + $innermost = function ($request) use ($call, $anonymousArgs) { + try { + $response = $call($request, ...$anonymousArgs); + } catch (Throwable $e) { + return static::exceptionResponse($e, $request); + } + if (!$response instanceof Response) { + if (!is_string($response)) { + $response = static::stringify($response); + } + $response = new Response(200, [], $response); + } + return $response; + }; + } + $callback = array_reduce($middlewares, function ($carry, $pipe) { + return function ($request) use ($carry, $pipe) { + try { + return $pipe($request, $carry); + } catch (Throwable $e) { + return static::exceptionResponse($e, $request); + } + }; + }, $innermost); + } else { + if (!$anonymousArgs) { + $callback = $call; + } else { + $callback = function ($request) use ($call, $anonymousArgs) { + return $call($request, ...$anonymousArgs); + }; + } + } + return $callback; + } + + /** + * ResolveInject. + * @param ContainerInterface $container + * @param array|Closure $call + * @param array $args + * @param bool $debug + * @return Closure + * @see Dependency injection through reflection information + */ + protected static function resolveInject(ContainerInterface $container, $call, array $args, bool $debug): Closure + { + // Pre-compute metadata at closure creation time (once), not at execution time (every request) + $metadataList = static::getMethodParameterMetadata(static::getReflector($call)); + + return function (Request $request) use ($container, $call, $args, $metadataList, $debug) { + $inputs = $args ? array_merge($request->all(), $args) : $request->all(); + $resolvedArgs = array_values(static::resolveMethodDependenciesFromMetadata( + $container, $request, $inputs, $metadataList, $debug + )); + return $call(...$resolvedArgs); + }; + } + + /** + * Check whether inject is required. + * @param $call + * @param array $args + * @return bool + * @throws ReflectionException + */ + protected static function isNeedInject($call, array &$args): bool + { + if (is_array($call) && !method_exists($call[0], $call[1])) { + return false; + } + $reflector = static::getReflector($call); + $reflectionParameters = $reflector->getParameters(); + if (!$reflectionParameters) { + return false; + } + $firstParameter = current($reflectionParameters); + unset($reflectionParameters[key($reflectionParameters)]); + $adaptersList = ['int', 'string', 'bool', 'array', 'object', 'float', 'mixed', 'resource']; + $keys = []; + $needInject = false; + foreach ($reflectionParameters as $parameter) { + $parameterName = $parameter->name; + $keys[] = $parameterName; + if ($parameter->hasType()) { + $type = $parameter->getType(); + if (!$type instanceof \ReflectionNamedType) { + throw new \RuntimeException( + sprintf('Union/intersection types are not supported for controller parameter $%s. Use a single type instead.', $parameter->name) + ); + } + $typeName = $type->getName(); + if (!in_array($typeName, $adaptersList)) { + $needInject = true; + continue; + } + if (!array_key_exists($parameterName, $args)) { + $needInject = true; + continue; + } + switch ($typeName) { + case 'int': + case 'float': + if (!is_numeric($args[$parameterName])) { + return true; + } + $args[$parameterName] = $typeName === 'int' ? (int)$args[$parameterName]: (float)$args[$parameterName]; + break; + case 'bool': + $args[$parameterName] = (bool)$args[$parameterName]; + break; + case 'array': + case 'object': + if (!is_array($args[$parameterName])) { + return true; + } + $args[$parameterName] = $typeName === 'array' ? $args[$parameterName] : (object)$args[$parameterName]; + break; + case 'string': + case 'mixed': + case 'resource': + break; + } + } + } + if (array_keys($args) !== $keys) { + return true; + } + if (!$firstParameter->hasType()) { + return $firstParameter->getName() !== 'request'; + } + $firstType = $firstParameter->getType(); + if (!$firstType instanceof \ReflectionNamedType) { + return true; + } + if (!is_a(static::$requestClass, $firstType->getName(), true)) { + return true; + } + + return $needInject; + } + + /** + * Get reflector. + * @param $call + * @return ReflectionFunction|ReflectionMethod + * @throws ReflectionException + */ + protected static function getReflector($call) + { + $cacheKey = static::getReflectorCacheKey($call); + if ($cacheKey !== null && isset(static::$reflectorCache[$cacheKey])) { + return static::$reflectorCache[$cacheKey]; + } + + if ($call instanceof Closure || is_string($call)) { + $reflector = new ReflectionFunction($call); + } else { + $reflector = new ReflectionMethod($call[0], $call[1]); + } + + if ($cacheKey !== null) { + static::$reflectorCache[$cacheKey] = $reflector; + if (count(static::$reflectorCache) > 1024) { + unset(static::$reflectorCache[key(static::$reflectorCache)]); + } + } + + return $reflector; + } + + /** + * Get reflector cache key. + * @param mixed $call + * @return string|null + */ + protected static function getReflectorCacheKey($call): ?string + { + if (is_string($call)) { + return 'func:' . $call; + } + if (is_array($call) && isset($call[0], $call[1])) { + $class = is_object($call[0]) ? get_class($call[0]) : $call[0]; + return 'method:' . $class . '::' . $call[1]; + } + // Closures may be short-lived; avoid caching to prevent key reuse risks. + return null; + } + + /** + * Return dependent parameters + * @param ContainerInterface $container + * @param Request $request + * @param array $inputs + * @param ReflectionFunctionAbstract $reflector + * @param bool $debug + * @return array + * @throws ReflectionException + */ + protected static function resolveMethodDependencies(ContainerInterface $container, Request $request, array $inputs, ReflectionFunctionAbstract $reflector, bool $debug): array + { + $metadataList = static::getMethodParameterMetadata($reflector); + return static::resolveMethodDependenciesFromMetadata($container, $request, $inputs, $metadataList, $debug); + } + + /** + * Return dependent parameters from pre-computed metadata. + * @param ContainerInterface $container + * @param Request $request + * @param array $inputs + * @param array $metadataList + * @param bool $debug + * @return array + * @throws ReflectionException + */ + protected static function resolveMethodDependenciesFromMetadata(ContainerInterface $container, Request $request, array $inputs, array $metadataList, bool $debug): array + { + $parameters = []; + foreach ($metadataList as $metadata) { + $parameterName = $metadata['name']; + $typeName = $metadata['type']; + + if (!empty($metadata['isRequest'])) { + $parameters[$parameterName] = $request; + continue; + } + + if (!array_key_exists($parameterName, $inputs)) { + if (!$metadata['hasDefault']) { + if (!$typeName || (!$metadata['isClass'] && !$metadata['isEnum']) || $metadata['isEnum']) { + throw (new MissingInputException())->data([ + 'parameter' => $parameterName, + ])->debug($debug); + } + } else { + $parameters[$parameterName] = $metadata['default']; + continue; + } + } + + $parameterValue = $inputs[$parameterName] ?? null; + + switch ($typeName) { + case 'int': + case 'float': + if (!is_numeric($parameterValue)) { + throw (new InputTypeException())->data([ + 'parameter' => $parameterName, + 'exceptType' => $typeName, + 'actualType' => gettype($parameterValue), + ])->debug($debug); + } + $parameters[$parameterName] = $typeName === 'float' ? (float)$parameterValue : (int)$parameterValue; + break; + case 'bool': + $parameters[$parameterName] = (bool)$parameterValue; + break; + case 'array': + case 'object': + if (!is_array($parameterValue)) { + throw (new InputTypeException())->data([ + 'parameter' => $parameterName, + 'exceptType' => $typeName, + 'actualType' => gettype($parameterValue), + ])->debug($debug); + } + $parameters[$parameterName] = $typeName === 'object' ? (object)$parameterValue : $parameterValue; + break; + case 'string': + case 'mixed': + case 'resource': + case null: + $parameters[$parameterName] = $parameterValue; + break; + default: + $subInputs = is_array($parameterValue) ? $parameterValue : []; + if (!empty($metadata['isModel'])) { + $parameters[$parameterName] = $container->make($typeName, [ + 'attributes' => $subInputs + ]); + break; + } + if (!empty($metadata['isThinkModel'])) { + $parameters[$parameterName] = $container->make($typeName, [ + 'data' => $subInputs + ]); + break; + } + if (!empty($metadata['isEnum'])) { + // Use pre-computed enum case mappings (avoids per-request ReflectionEnum) + if (isset($metadata['enumCases'][$parameterValue])) { + $parameters[$parameterName] = $metadata['enumCases'][$parameterValue]; + break; + } + if (!empty($metadata['enumIsBacked']) && isset($metadata['enumBackedValues'][$parameterValue])) { + $parameters[$parameterName] = $metadata['enumBackedValues'][$parameterValue]; + break; + } + throw (new InputValueException())->data([ + 'parameter' => $parameterName, + 'enum' => $typeName + ])->debug($debug); + } + if (is_array($subInputs) && !empty($metadata['hasConstructor'])) { + $constructorReflector = static::getReflector([$typeName, '__construct']); + $parameters[$parameterName] = $container->make($typeName, static::resolveMethodDependencies($container, $request, $subInputs, $constructorReflector, $debug)); + } else { + $parameters[$parameterName] = $container->make($typeName); + } + break; + } + } + return $parameters; + } + + /** + * Get method parameter metadata from cache. + * @param ReflectionFunctionAbstract $reflector + * @return array<int, array<string, mixed>> + * @throws ReflectionException + */ + protected static function getMethodParameterMetadata(ReflectionFunctionAbstract $reflector): array + { + $cacheKey = static::getParameterMetadataCacheKey($reflector); + if ($cacheKey !== null && isset(static::$parameterMetadataCache[$cacheKey])) { + return static::$parameterMetadataCache[$cacheKey]; + } + + $metadataList = []; + foreach ($reflector->getParameters() as $parameter) { + $type = $parameter->getType(); + if ($type !== null && !$type instanceof \ReflectionNamedType) { + throw new \RuntimeException( + sprintf('Union/intersection types are not supported for controller parameter $%s. Use a single type instead.', $parameter->name) + ); + } + $typeName = $type?->getName(); + $hasDefault = $parameter->isDefaultValueAvailable(); + $isEnum = $typeName && enum_exists($typeName); + $isClass = $typeName && class_exists($typeName); + $isRequest = $typeName && is_a(static::$requestClass, $typeName, true); + $isModel = $typeName && is_a($typeName, Model::class, true); + $isThinkModel = $typeName && is_a($typeName, ThinkModel::class, true); + $metadata = [ + 'name' => $parameter->name, + 'type' => $typeName, + 'hasDefault' => $hasDefault, + 'default' => $hasDefault ? $parameter->getDefaultValue() : null, + 'isRequest' => $isRequest, + 'isEnum' => $isEnum, + 'isClass' => $isClass, + 'isModel' => $isModel, + 'isThinkModel' => $isThinkModel, + ]; + // Pre-compute enum case mappings to avoid per-request ReflectionEnum + if ($isEnum) { + $enumReflection = new ReflectionEnum($typeName); + $enumCases = []; + $enumBackedValues = []; + $isBacked = $enumReflection->isBacked(); + foreach ($enumReflection->getCases() as $case) { + $caseValue = $case->getValue(); + $enumCases[$case->getName()] = $caseValue; + if ($isBacked) { + $enumBackedValues[$caseValue->value] = $caseValue; + } + } + $metadata['enumCases'] = $enumCases; + $metadata['enumBackedValues'] = $enumBackedValues; + $metadata['enumIsBacked'] = $isBacked; + } + // Pre-compute class constructor info to avoid per-request ReflectionClass + if ($isClass && !$isRequest && !$isEnum && !$isModel && !$isThinkModel) { + $classRef = new ReflectionClass($typeName); + $constructor = $classRef->getConstructor(); + $metadata['hasConstructor'] = $constructor !== null; + if ($constructor) { + // Pre-cache constructor reflector for use by getReflector() + $constructorKey = 'method:' . $typeName . '::__construct'; + if (!isset(static::$reflectorCache[$constructorKey])) { + static::$reflectorCache[$constructorKey] = $constructor; + } + } + } + $metadataList[] = $metadata; + } + + if ($cacheKey !== null) { + static::$parameterMetadataCache[$cacheKey] = $metadataList; + if (count(static::$parameterMetadataCache) > 1024) { + unset(static::$parameterMetadataCache[key(static::$parameterMetadataCache)]); + } + } + + return $metadataList; + } + + /** + * Get parameter metadata cache key. + * @param ReflectionFunctionAbstract $reflector + * @return string|null + */ + protected static function getParameterMetadataCacheKey(ReflectionFunctionAbstract $reflector): ?string + { + if ($reflector instanceof ReflectionMethod) { + return 'method:' . $reflector->getDeclaringClass()->getName() . '::' . $reflector->getName(); + } + if ($reflector instanceof ReflectionFunction && $reflector->isClosure()) { + return null; + } + if ($reflector instanceof ReflectionFunction) { + return 'func:' . $reflector->getName(); + } + return null; + } + + /** + * Container. + * @param string $plugin + * @return ContainerInterface + */ + public static function container(string $plugin = '') + { + return static::config($plugin, 'container'); + } + + /** + * Get request. + * @return Request|\support\Request + */ + public static function request() + { + return Context::get(Request::class); + } + + /** + * Get worker. + * @return Worker + */ + public static function worker(): ?Worker + { + return static::$worker; + } + + /** + * Find Route. + * @param TcpConnection $connection + * @param string $path + * @param string $key + * @param $request + * @param $status + * @return bool + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws ReflectionException|Throwable + */ + protected static function findRoute(TcpConnection $connection, string $path, string $key, $request, &$status): bool + { + $routeInfo = \Webman\Route::dispatch($request->method(), $path); + if ($routeInfo[0] === Dispatcher::FOUND) { + $status = 200; + $routeInfo[0] = 'route'; + $callback = $routeInfo[1]['callback']; + $route = clone $routeInfo[1]['route']; + $app = $controller = $action = ''; + $args = !empty($routeInfo[2]) ? $routeInfo[2] : []; + if ($args) { + $route->setParams($args); + } + $args = array_merge($route->param(), $args); + if (is_array($callback)) { + $controller = $callback[0]; + $plugin = static::getPluginByClass($controller); + $app = static::getAppByController($controller); + $action = static::getRealMethod($controller, $callback[1]) ?? ''; + } else { + $plugin = static::getPluginByPath($path); + } + $callback = static::getCallback($plugin, $app, $callback, $args, true, $route); + static::collectCallbacks($key, [$callback, $plugin, $app, $controller ?: '', $action, $route]); + [$callback, $request->plugin, $request->app, $request->controller, $request->action, $request->route] = static::$callbacks[$key]; + static::send($connection, $callback($request), $request); + return true; + } + $status = $routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED ? 405 : 404; + return false; + } + + /** + * Find File. + * @param TcpConnection $connection + * @param string $path + * @param string $key + * @param $request + * @return bool + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws ReflectionException + */ + protected static function findFile(TcpConnection $connection, string $path, string $key, $request): bool + { + if (preg_match('/%[0-9a-f]{2}/i', $path)) { + $path = urldecode($path); + if (static::unsafeUri($connection, $path, $request)) { + return true; + } + } + + $pathExplodes = explode('/', trim($path, '/')); + $plugin = ''; + if (isset($pathExplodes[1]) && $pathExplodes[0] === 'app') { + $plugin = $pathExplodes[1]; + $publicDir = static::config($plugin, 'app.public_path') ?: BASE_PATH . "/plugin/$pathExplodes[1]/public"; + $path = substr($path, strlen("/app/$pathExplodes[1]/")); + } else { + $publicDir = static::$publicPath; + } + $file = "$publicDir/$path"; + if (!is_file($file)) { + return false; + } + + if (pathinfo($file, PATHINFO_EXTENSION) === 'php') { + if (!static::config($plugin, 'app.support_php_files', false)) { + return false; + } + static::collectCallbacks($key, [function () use ($file) { + return static::execPhpFile($file); + }, $plugin, '', '', '', null]); + [, $request->plugin, $request->app, $request->controller, $request->action, $request->route] = static::$callbacks[$key]; + static::send($connection, static::execPhpFile($file), $request); + return true; + } + + if (!static::config($plugin, 'static.enable', false)) { + return false; + } + + static::collectCallbacks($key, [static::getCallback($plugin, '__static__', function ($request) use ($file, $plugin) { + clearstatcache(true, $file); + if (!is_file($file)) { + $callback = static::getFallback($plugin); + return $callback($request); + } + $fileSize = (int) filesize($file); + $range = static::parseRangeHeader($request->header('range'), $fileSize); + if ($range === false) { + return (new Response(416, [ + 'Content-Range' => "bytes */$fileSize", + 'Accept-Ranges' => 'bytes', + ])); + } + if ($range !== null) { + [$offset, $length] = $range; + return (new Response())->withFile($file, $offset, $length); + } + return (new Response())->file($file); + }, [], false), '', '', '', '', null]); + [$callback, $request->plugin, $request->app, $request->controller, $request->action, $request->route] = static::$callbacks[$key]; + static::send($connection, $callback($request), $request); + return true; + } + + /** + * Parse a single HTTP byte range. + * + * @param string|null $rangeHeader + * @param int $fileSize + * @return array{0:int,1:int}|false|null + */ + protected static function parseRangeHeader(?string $rangeHeader, int $fileSize): array|false|null + { + if ($rangeHeader === null || $rangeHeader === '' || $fileSize <= 0) { + return null; + } + if (!preg_match('/^bytes=(\d*)-(\d*)$/', trim($rangeHeader), $matches)) { + return null; + } + + $start = $matches[1]; + $end = $matches[2]; + if ($start === '' && $end === '') { + return false; + } + + if ($start === '') { + $suffixLength = (int) $end; + if ($suffixLength <= 0) { + return false; + } + $offset = max(0, $fileSize - $suffixLength); + return [$offset, $fileSize - $offset]; + } + + $offset = (int) $start; + if ($offset >= $fileSize) { + return false; + } + + $offsetEnd = $end === '' ? $fileSize - 1 : min((int) $end, $fileSize - 1); + if ($offsetEnd < $offset) { + return false; + } + + return [$offset, $offsetEnd - $offset + 1]; + } + + /** + * Send. + * @param TcpConnection|mixed $connection + * @param mixed|Response $response + * @param Request|mixed $request + * @return void + */ + protected static function send($connection, $response, $request) + { + Context::destroy(); + // Remove the reference of request to session. + unset($request->context['session']); + $keepAlive = $request->header('connection'); + if ($keepAlive === null) { + if ($request->protocolVersion() === '1.1') { + $connection->send($response); + return; + } + } elseif (\strcasecmp($keepAlive, 'keep-alive') === 0) { + $connection->send($response); + return; + } + if ($response instanceof Response && $response->getHeader('Transfer-Encoding') === 'chunked') { + $connection->send($response); + return; + } + $connection->close($response); + } + + /** + * ParseControllerAction. + * @param string $path + * @return array|false + * @throws ReflectionException + */ + protected static function parseControllerAction(string $path) + { + $path = str_replace(['-', '//'], ['', '/'], $path); + if (static::containsPathTraversal($path)) { + return false; + } + static $cache = []; + if (isset($cache[$path])) { + return $cache[$path]; + } + $pathExplode = explode('/', trim($path, '/')); + $isPlugin = isset($pathExplode[1]) && $pathExplode[0] === 'app'; + $configPrefix = $isPlugin ? "plugin.$pathExplode[1]." : ''; + $pathPrefix = $isPlugin ? "/app/$pathExplode[1]" : ''; + $classPrefix = $isPlugin ? "plugin\\$pathExplode[1]" : ''; + $suffix = Config::get("{$configPrefix}app.controller_suffix", ''); + $relativePath = trim(substr($path, strlen($pathPrefix)), '/'); + $pathExplode = $relativePath ? explode('/', $relativePath) : []; + + $action = 'index'; + if (!$controllerAction = static::guessControllerAction($pathExplode, $action, $suffix, $classPrefix)) { + if (count($pathExplode) <= 1) { + return false; + } + $action = end($pathExplode); + unset($pathExplode[count($pathExplode) - 1]); + $controllerAction = static::guessControllerAction($pathExplode, $action, $suffix, $classPrefix); + } + if ($controllerAction && !isset($path[256])) { + $cache[$path] = $controllerAction; + if (count($cache) > 1024) { + unset($cache[key($cache)]); + } + } + return $controllerAction; + } + + /** + * GuessControllerAction. + * @param $pathExplode + * @param $action + * @param $suffix + * @param $classPrefix + * @return array|false + * @throws ReflectionException + */ + protected static function guessControllerAction($pathExplode, $action, $suffix, $classPrefix) + { + $map[] = trim("$classPrefix\\app\\controller\\" . implode('\\', $pathExplode), '\\'); + foreach ($pathExplode as $index => $section) { + $tmp = $pathExplode; + array_splice($tmp, $index, 1, [$section, 'controller']); + $map[] = trim("$classPrefix\\" . implode('\\', array_merge(['app'], $tmp)), '\\'); + } + foreach ($map as $item) { + $map[] = $item . '\\index'; + } + foreach ($map as $controllerClass) { + // Remove xx\xx\controller + if (substr($controllerClass, -11) === '\\controller') { + continue; + } + $controllerClass .= $suffix; + if ($controllerAction = static::getControllerAction($controllerClass, $action)) { + return $controllerAction; + } + } + return false; + } + + /** + * GetControllerAction. + * @param string $controllerClass + * @param string $action + * @return array|false + * @throws ReflectionException + */ + protected static function getControllerAction(string $controllerClass, string $action) + { + // Disable calling magic methods + if (strpos($action, '__') === 0) { + return false; + } + if (($controllerClass = static::getController($controllerClass)) && ($action = static::getAction($controllerClass, $action))) { + return [ + 'plugin' => static::getPluginByClass($controllerClass), + 'app' => static::getAppByController($controllerClass), + 'controller' => $controllerClass, + 'action' => $action + ]; + } + return false; + } + + /** + * GetController. + * @param string $controllerClass + * @return string|false + * @throws ReflectionException + */ + protected static function getController(string $controllerClass) + { + if (class_exists($controllerClass)) { + return (new ReflectionClass($controllerClass))->name; + } + $explodes = explode('\\', strtolower(ltrim($controllerClass, '\\'))); + $basePath = $explodes[0] === 'plugin' ? BASE_PATH . '/plugin' : static::$appPath; + unset($explodes[0]); + $fileName = array_pop($explodes) . '.php'; + $found = true; + foreach ($explodes as $pathSection) { + if (!$found) { + break; + } + $dirs = Util::scanDir($basePath, false); + $found = false; + foreach ($dirs as $name) { + $path = "$basePath/$name"; + + if (is_dir($path) && strtolower($name) === $pathSection) { + $basePath = $path; + $found = true; + break; + } + } + } + if (!$found) { + return false; + } + foreach (scandir($basePath) ?: [] as $name) { + if (strtolower($name) === $fileName) { + require_once "$basePath/$name"; + if (class_exists($controllerClass, false)) { + return (new ReflectionClass($controllerClass))->name; + } + } + } + return false; + } + + /** + * GetAction. + * @param string $controllerClass + * @param string $action + * @return string|false + */ + protected static function getAction(string $controllerClass, string $action) + { + $methods = get_class_methods($controllerClass); + $lowerAction = strtolower($action); + $found = false; + foreach ($methods as $candidate) { + if (strtolower($candidate) === $lowerAction) { + $action = $candidate; + $found = true; + break; + } + } + if ($found) { + return $action; + } + // Action is not public method + if (method_exists($controllerClass, $action)) { + return false; + } + if (method_exists($controllerClass, '__call')) { + return $action; + } + return false; + } + + /** + * GetPluginByClass. + * @param string $controllerClass + * @return mixed|string + */ + public static function getPluginByClass(string $controllerClass) + { + $controllerClass = trim($controllerClass, '\\'); + $tmp = explode('\\', $controllerClass, 3); + if ($tmp[0] !== 'plugin') { + return ''; + } + return $tmp[1] ?? ''; + } + + /** + * GetPluginByPath. + * @param string $path + * @return mixed|string + */ + public static function getPluginByPath(string $path) + { + $path = trim($path, '/'); + $tmp = explode('/', $path, 3); + if ($tmp[0] !== 'app') { + return ''; + } + $plugin = $tmp[1] ?? ''; + if ($plugin && !static::config('', "plugin.$plugin.app")) { + return ''; + } + return $plugin; + } + + /** + * GetAppByController. + * @param string $controllerClass + * @return mixed|string + */ + protected static function getAppByController(string $controllerClass) + { + $controllerClass = trim($controllerClass, '\\'); + $tmp = explode('\\', $controllerClass, 5); + $pos = $tmp[0] === 'plugin' ? 3 : 1; + if (!isset($tmp[$pos])) { + return ''; + } + return strtolower($tmp[$pos]) === 'controller' ? '' : $tmp[$pos]; + } + + /** + * ExecPhpFile. + * @param string $file + * @return false|string + */ + public static function execPhpFile(string $file) + { + ob_start(); + // Try to include php file. + try { + include $file; + } catch (Throwable $e) { + ob_get_clean(); + throw $e; + } + return ob_get_clean(); + } + + /** + * GetRealMethod. + * @param string $class + * @param string $method + * @return string + */ + protected static function getRealMethod(string $class, string $method): string + { + $method = strtolower($method); + $methods = get_class_methods($class); + foreach ($methods as $candidate) { + if (strtolower($candidate) === $method) { + return $candidate; + } + } + return $method; + } + + /** + * Config. + * @param string $plugin + * @param string $key + * @param mixed $default + * @return mixed + */ + protected static function config(string $plugin, string $key, mixed $default = null) + { + return Config::get($plugin ? "plugin.$plugin.$key" : $key, $default); + } + + + /** + * @param mixed $data + * @return string + */ + protected static function stringify($data): string + { + $type = gettype($data); + switch ($type) { + case 'boolean': + return $data ? 'true' : 'false'; + case 'NULL': + return 'NULL'; + case 'array': + return 'Array'; + case 'object': + if (!method_exists($data, '__toString')) { + return 'Object'; + } + default: + return (string)$data; + } + } +} diff --git a/vendor/workerman/webman-framework/src/Bootstrap.php b/vendor/workerman/webman-framework/src/Bootstrap.php new file mode 100644 index 0000000..50774a1 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Bootstrap.php @@ -0,0 +1,28 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + +use Workerman\Worker; + +interface Bootstrap +{ + /** + * onWorkerStart + * + * @param Worker|null $worker + * @return mixed + */ + public static function start(?Worker $worker); +} diff --git a/vendor/workerman/webman-framework/src/Config.php b/vendor/workerman/webman-framework/src/Config.php new file mode 100644 index 0000000..2d00435 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Config.php @@ -0,0 +1,322 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + +use FilesystemIterator; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; +use function array_replace_recursive; +use function array_reverse; +use function count; +use function explode; +use function in_array; +use function is_array; +use function is_dir; +use function is_file; +use function key; +use function str_replace; + +class Config +{ + + /** + * @var array + */ + protected static $config = []; + + /** + * @var string + */ + protected static $configPath = ''; + + /** + * @var bool + */ + protected static $loaded = false; + + /** + * @var array Flat cache for repeated get() lookups. + */ + protected static $flatCache = []; + + /** + * Load. + * @param string $configPath + * @param array $excludeFile + * @param string|null $key + * @return void + */ + public static function load(string $configPath, array $excludeFile = [], ?string $key = null) + { + static::$configPath = $configPath; + static::$flatCache = []; + if (!$configPath) { + return; + } + static::$loaded = false; + $config = static::loadFromDir($configPath, $excludeFile); + if (!$config) { + static::$loaded = true; + return; + } + if ($key !== null) { + foreach (array_reverse(explode('.', $key)) as $k) { + $config = [$k => $config]; + } + } + static::$config = array_replace_recursive(static::$config, $config); + static::formatConfig(); + static::$loaded = true; + } + + /** + * This deprecated method will certainly be removed in the future. + * @param string $configPath + * @param array $excludeFile + * @return void + * @deprecated + */ + public static function reload(string $configPath, array $excludeFile = []) + { + static::load($configPath, $excludeFile); + } + + /** + * Clear. + * @return void + */ + public static function clear() + { + static::$config = []; + static::$flatCache = []; + } + + /** + * FormatConfig. + * @return void + */ + protected static function formatConfig() + { + $config = static::$config; + // Merge log config + foreach ($config['plugin'] ?? [] as $firm => $projects) { + if (isset($projects['app'])) { + foreach ($projects['log'] ?? [] as $key => $item) { + $config['log']["plugin.$firm.$key"] = $item; + } + } + foreach ($projects as $name => $project) { + if (!is_array($project)) { + continue; + } + foreach ($project['log'] ?? [] as $key => $item) { + $config['log']["plugin.$firm.$name.$key"] = $item; + } + } + } + // Merge database config + foreach ($config['plugin'] ?? [] as $firm => $projects) { + if (isset($projects['app'])) { + foreach ($projects['database']['connections'] ?? [] as $key => $connection) { + $config['database']['connections']["plugin.$firm.$key"] = $connection; + } + } + foreach ($projects as $name => $project) { + if (!is_array($project)) { + continue; + } + foreach ($project['database']['connections'] ?? [] as $key => $connection) { + $config['database']['connections']["plugin.$firm.$name.$key"] = $connection; + } + } + } + if (!empty($config['database']['connections'])) { + $config['database']['default'] = $config['database']['default'] ?? key($config['database']['connections']); + } + // Merge thinkorm config + foreach ($config['plugin'] ?? [] as $firm => $projects) { + if (isset($projects['app'])) { + foreach ($projects['thinkorm']['connections'] ?? [] as $key => $connection) { + $config['thinkorm']['connections']["plugin.$firm.$key"] = $connection; + } + foreach ($projects['think-orm']['connections'] ?? [] as $key => $connection) { + $config['think-orm']['connections']["plugin.$firm.$key"] = $connection; + } + } + foreach ($projects as $name => $project) { + if (!is_array($project)) { + continue; + } + foreach ($project['thinkorm']['connections'] ?? [] as $key => $connection) { + $config['thinkorm']['connections']["plugin.$firm.$name.$key"] = $connection; + } + foreach ($project['think-orm']['connections'] ?? [] as $key => $connection) { + $config['think-orm']['connections']["plugin.$firm.$name.$key"] = $connection; + } + } + } + if (!empty($config['thinkorm']['connections'])) { + $config['thinkorm']['default'] = $config['thinkorm']['default'] ?? key($config['thinkorm']['connections']); + } + if (!empty($config['think-orm']['connections'])) { + $config['think-orm']['default'] = $config['think-orm']['default'] ?? key($config['think-orm']['connections']); + } + // Merge redis config + foreach ($config['plugin'] ?? [] as $firm => $projects) { + if (isset($projects['app'])) { + foreach ($projects['redis'] ?? [] as $key => $connection) { + $config['redis']["plugin.$firm.$key"] = $connection; + } + } + foreach ($projects as $name => $project) { + if (!is_array($project)) { + continue; + } + foreach ($project['redis'] ?? [] as $key => $connection) { + $config['redis']["plugin.$firm.$name.$key"] = $connection; + } + } + } + static::$config = $config; + } + + /** + * LoadFromDir. + * @param string $configPath + * @param array $excludeFile + * @return array + */ + public static function loadFromDir(string $configPath, array $excludeFile = []): array + { + $allConfig = []; + $dirIterator = new RecursiveDirectoryIterator($configPath, FilesystemIterator::FOLLOW_SYMLINKS); + $iterator = new RecursiveIteratorIterator($dirIterator); + foreach ($iterator as $file) { + /** var SplFileInfo $file */ + if ($file->isDir() || $file->getExtension() != 'php' || in_array($file->getBaseName('.php'), $excludeFile)) { + continue; + } + $filePath = $file->getPathname(); + $appConfigFile = $file->getPath() . '/app.php'; + if (!is_file($appConfigFile)) { + continue; + } + $relativePath = str_replace($configPath . DIRECTORY_SEPARATOR, '', substr($filePath, 0, -4)); + $explode = array_reverse(explode(DIRECTORY_SEPARATOR, $relativePath)); + if (count($explode) >= 2) { + $appConfig = include $appConfigFile; + if (empty($appConfig['enable'])) { + continue; + } + } + $config = include $filePath; + foreach ($explode as $section) { + $tmp = []; + $tmp[$section] = $config; + $config = $tmp; + } + $allConfig = array_replace_recursive($allConfig, $config); + } + return $allConfig; + } + + /** + * Get. + * @param string|null $key + * @param mixed $default + * @return mixed + */ + public static function get(?string $key = null, mixed $default = null) + { + if ($key === null) { + return static::$config; + } + if (isset(static::$flatCache[$key])) { + return static::$flatCache[$key]; + } + $keyArray = explode('.', $key); + $value = static::$config; + $found = true; + foreach ($keyArray as $index) { + if (!isset($value[$index])) { + if (static::$loaded) { + return $default; + } + $found = false; + break; + } + $value = $value[$index]; + } + if ($found) { + if (static::$loaded) { + static::$flatCache[$key] = $value; + if (count(static::$flatCache) > 1024) { + unset(static::$flatCache[key(static::$flatCache)]); + } + } + return $value; + } + return static::read($key, $default); + } + + /** + * Read. + * @param string $key + * @param mixed $default + * @return mixed + */ + protected static function read(string $key, mixed $default = null) + { + $path = static::$configPath; + if ($path === '') { + return $default; + } + $keys = $keyArray = explode('.', $key); + foreach ($keyArray as $index => $section) { + unset($keys[$index]); + if (is_file($file = "$path/$section.php")) { + $config = include $file; + return static::find($keys, $config, $default); + } + if (!is_dir($path = "$path/$section")) { + return $default; + } + } + return $default; + } + + /** + * Find. + * @param array $keyArray + * @param mixed $stack + * @param mixed $default + * @return array|mixed + */ + protected static function find(array $keyArray, $stack, $default) + { + if (!is_array($stack)) { + return $default; + } + $value = $stack; + foreach ($keyArray as $index) { + if (!isset($value[$index])) { + return $default; + } + $value = $value[$index]; + } + return $value; + } + +} diff --git a/vendor/workerman/webman-framework/src/Container.php b/vendor/workerman/webman-framework/src/Container.php new file mode 100644 index 0000000..ef39377 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Container.php @@ -0,0 +1,84 @@ +<?php + +namespace Webman; + +use Psr\Container\ContainerInterface; +use Webman\Exception\NotFoundException; +use function array_key_exists; +use function class_exists; + +/** + * Class Container + * @package Webman + */ +class Container implements ContainerInterface +{ + + /** + * @var array + */ + protected $instances = []; + /** + * @var array + */ + protected $definitions = []; + + /** + * Get. + * @param string $name + * @return mixed + * @throws NotFoundException + */ + public function get(string $name) + { + if (!isset($this->instances[$name])) { + if (isset($this->definitions[$name])) { + $this->instances[$name] = call_user_func($this->definitions[$name], $this); + } else { + if (!class_exists($name)) { + throw new NotFoundException("Class '$name' not found"); + } + $this->instances[$name] = new $name(); + } + } + return $this->instances[$name]; + } + + /** + * Has. + * @param string $name + * @return bool + */ + public function has(string $name): bool + { + return array_key_exists($name, $this->instances) + || array_key_exists($name, $this->definitions); + } + + /** + * Make. + * @param string $name + * @param array $constructor + * @return mixed + * @throws NotFoundException + */ + public function make(string $name, array $constructor = []) + { + if (!class_exists($name)) { + throw new NotFoundException("Class '$name' not found"); + } + return new $name(... array_values($constructor)); + } + + /** + * AddDefinitions. + * @param array $definitions + * @return $this + */ + public function addDefinitions(array $definitions): Container + { + $this->definitions = array_merge($this->definitions, $definitions); + return $this; + } + +} diff --git a/vendor/workerman/webman-framework/src/Context.php b/vendor/workerman/webman-framework/src/Context.php new file mode 100644 index 0000000..8e3b9fa --- /dev/null +++ b/vendor/workerman/webman-framework/src/Context.php @@ -0,0 +1,24 @@ +<?php + +namespace Webman; + +use Workerman\Coroutine\Context as WorkermanContext; +use Workerman\Coroutine\Utils\DestructionWatcher; +use Closure; + +/** + * Class Context + * @package Webman + */ +class Context extends WorkermanContext +{ + public static function onDestroy(Closure $closure): void + { + $obj = static::get('context.onDestroy'); + if (!$obj) { + $obj = new \stdClass(); + static::set('context.onDestroy', $obj); + } + DestructionWatcher::watch($obj, $closure); + } +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/Exception/BusinessException.php b/vendor/workerman/webman-framework/src/Exception/BusinessException.php new file mode 100644 index 0000000..d1fae1d --- /dev/null +++ b/vendor/workerman/webman-framework/src/Exception/BusinessException.php @@ -0,0 +1,117 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Exception; + +use RuntimeException; +use Throwable; +use Webman\Http\Request; +use Webman\Http\Response; +use function json_encode; + +/** + * Class BusinessException + * @package support\exception + */ +class BusinessException extends RuntimeException +{ + + /** + * @var array + */ + protected $data = []; + + /** + * @var bool + */ + protected $debug = false; + + /** + * Render an exception into an HTTP response. + * @param Request $request + * @return Response|null + */ + public function render(Request $request): ?Response + { + if ($request->expectsJson()) { + $code = $this->getCode(); + $json = ['code' => $code ?: 500, 'msg' => $this->getMessage(), 'data' => $this->data]; + return new Response(200, ['Content-Type' => 'application/json'], + json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + } + return new Response(200, [], $this->getMessage()); + } + + /** + * Set data. + * @param array|null $data + * @return array|$this + */ + public function data(?array $data = null): array|static + { + if ($data === null) { + return $this->data; + } + $this->data = $data; + return $this; + } + + /** + * Set debug. + * @param bool|null $value + * @return $this|bool + */ + public function debug(?bool $value = null): bool|static + { + if ($value === null) { + return $this->debug; + } + $this->debug = $value; + return $this; + } + + /** + * Get data. + * @return array + */ + public function getData(): array + { + return $this->data; + } + + /** + * Translate message. + * @param string $message + * @param array $parameters + * @param string|null $domain + * @param string|null $locale + * @return string + */ + protected function trans(string $message, array $parameters = [], ?string $domain = null, ?string $locale = null): string + { + $args = []; + foreach ($parameters as $key => $parameter) { + $args[":$key"] = $parameter; + } + try { + $message = trans($message, $args, $domain, $locale); + } catch (Throwable $e) { + } + foreach ($parameters as $key => $value) { + $message = str_replace(":$key", $value, $message); + } + return $message; + } + +} diff --git a/vendor/workerman/webman-framework/src/Exception/ExceptionHandler.php b/vendor/workerman/webman-framework/src/Exception/ExceptionHandler.php new file mode 100644 index 0000000..ea8de87 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Exception/ExceptionHandler.php @@ -0,0 +1,121 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Exception; + +use Psr\Log\LoggerInterface; +use Throwable; +use Webman\Http\Request; +use Webman\Http\Response; +use function json_encode; +use function nl2br; +use function trim; + +/** + * Class Handler + * @package support\exception + */ +class ExceptionHandler implements ExceptionHandlerInterface +{ + /** + * @var LoggerInterface + */ + protected $logger = null; + + /** + * @var bool + */ + protected $debug = false; + + /** + * @var array + */ + public $dontReport = []; + + /** + * ExceptionHandler constructor. + * @param $logger + * @param $debug + */ + public function __construct($logger, $debug) + { + $this->logger = $logger; + $this->debug = $debug; + } + + /** + * @param Throwable $exception + * @return void + */ + public function report(Throwable $exception) + { + if ($this->shouldntReport($exception)) { + return; + } + $logs = ''; + if ($request = \request()) { + $logs = $request->getRealIp() . ' ' . $request->method() . ' ' . trim($request->fullUrl(), '/'); + } + $this->logger->error($logs . PHP_EOL . $exception); + } + + /** + * @param Request $request + * @param Throwable $exception + * @return Response + */ + public function render(Request $request, Throwable $exception): Response + { + if (method_exists($exception, 'render') && ($response = $exception->render($request))) { + return $response; + } + $code = $exception->getCode(); + if ($request->expectsJson()) { + $json = ['code' => $code ?: 500, 'msg' => $this->debug ? $exception->getMessage() : 'Server internal error']; + $this->debug && $json['traces'] = (string)$exception; + return new Response(200, ['Content-Type' => 'application/json'], + json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + } + $error = $this->debug ? nl2br((string)$exception) : 'Server internal error'; + return new Response(500, [], $error); + } + + /** + * @param Throwable $e + * @return bool + */ + protected function shouldntReport(Throwable $e): bool + { + foreach ($this->dontReport as $type) { + if ($e instanceof $type) { + return true; + } + } + return false; + } + + /** + * Compatible $this->_debug + * + * @param string $name + * @return bool|null + */ + public function __get(string $name) + { + if ($name === '_debug') { + return $this->debug; + } + return null; + } +} diff --git a/vendor/workerman/webman-framework/src/Exception/ExceptionHandlerInterface.php b/vendor/workerman/webman-framework/src/Exception/ExceptionHandlerInterface.php new file mode 100644 index 0000000..8868707 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Exception/ExceptionHandlerInterface.php @@ -0,0 +1,35 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Exception; + +use Throwable; +use Webman\Http\Request; +use Webman\Http\Response; + +interface ExceptionHandlerInterface +{ + /** + * @param Throwable $exception + * @return mixed + */ + public function report(Throwable $exception); + + /** + * @param Request $request + * @param Throwable $exception + * @return Response + */ + public function render(Request $request, Throwable $exception): Response; +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/Exception/FileException.php b/vendor/workerman/webman-framework/src/Exception/FileException.php new file mode 100644 index 0000000..fa5dbe6 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Exception/FileException.php @@ -0,0 +1,25 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Exception; + +use RuntimeException; + +/** + * Class FileException + * @package Webman\Exception + */ +class FileException extends RuntimeException +{ +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/Exception/NotFoundException.php b/vendor/workerman/webman-framework/src/Exception/NotFoundException.php new file mode 100644 index 0000000..735c1d4 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Exception/NotFoundException.php @@ -0,0 +1,25 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Exception; + +use Psr\Container\NotFoundExceptionInterface; + +/** + * Class NotFoundException + * @package Webman\Exception + */ +class NotFoundException extends \Exception implements NotFoundExceptionInterface +{ +} diff --git a/vendor/workerman/webman-framework/src/File.php b/vendor/workerman/webman-framework/src/File.php new file mode 100644 index 0000000..a43328c --- /dev/null +++ b/vendor/workerman/webman-framework/src/File.php @@ -0,0 +1,56 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + +use SplFileInfo; +use Webman\Exception\FileException; +use function chmod; +use function is_dir; +use function mkdir; +use function pathinfo; +use function restore_error_handler; +use function set_error_handler; +use function sprintf; +use function strip_tags; +use function umask; + +class File extends SplFileInfo +{ + + /** + * Move. + * @param string $destination + * @return File + */ + public function move(string $destination): File + { + set_error_handler(function ($type, $msg) use (&$error) { + $error = $msg; + }); + $path = pathinfo($destination, PATHINFO_DIRNAME); + if (!is_dir($path) && !mkdir($path, 0777, true)) { + restore_error_handler(); + throw new FileException(sprintf('Unable to create the "%s" directory (%s)', $path, strip_tags($error))); + } + if (!rename($this->getPathname(), $destination)) { + restore_error_handler(); + throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $destination, strip_tags($error))); + } + restore_error_handler(); + @chmod($destination, 0666 & ~umask()); + return new self($destination); + } + +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/Finder/ControllerFinder.php b/vendor/workerman/webman-framework/src/Finder/ControllerFinder.php new file mode 100644 index 0000000..7b9cecd --- /dev/null +++ b/vendor/workerman/webman-framework/src/Finder/ControllerFinder.php @@ -0,0 +1,239 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Finder; + +use InvalidArgumentException; +use Webman\Config; + +use function is_array; +use function is_dir; +use function preg_match; +use function preg_quote; +use function scandir; +use function str_starts_with; + +/** + * ControllerFinder + * + * Discover controller files in main app and/or plugins. + * + * Scope examples: + * - null : main app only + * - '*' : main app + all enabled plugins + * - 'plugin.*' : all enabled plugins + * - 'plugin.xxx': single plugin (strict: throws when plugin directory/config missing) + */ +class ControllerFinder +{ + /** + * Find controller files by scope. + * + * @param string|null $scope + * @param bool $attributesOnly When false, all controller files are returned (attribute filtering skipped). + * @return FileInfo[] + */ + public static function files(?string $scope = null, bool $attributesOnly = true): array + { + $roots = static::resolveRoots($scope); + if (!$roots) { + return []; + } + + $resultsByPath = []; + foreach ($roots as $root) { + $dir = $root['dir']; + $suffix = $root['suffix'] ?? ''; + $controllerFiles = static::findControllerFiles($dir, $suffix, $attributesOnly); + foreach ($controllerFiles as $file) { + $resultsByPath[$file->getPathname()] = $file; + } + } + + return array_values($resultsByPath); + } + + /** + * Resolve search roots by scope. + * + * @param string|null $scope + * @return array<int, array{dir: string, suffix: string}> + */ + protected static function resolveRoots(?string $scope): array + { + if ($scope === null) { + return static::mainAppRoots(); + } + + if ($scope === '*') { + return array_merge(static::mainAppRoots(), static::allPluginRoots()); + } + + if ($scope === 'plugin.*') { + return static::allPluginRoots(); + } + + if (str_starts_with($scope, 'plugin.')) { + $plugin = substr($scope, strlen('plugin.')); + if ($plugin === '' || $plugin === '*') { + throw new InvalidArgumentException("Invalid controller scope: $scope"); + } + return static::singlePluginRoots($plugin); + } + + throw new InvalidArgumentException("Invalid controller scope: $scope"); + } + + /** + * Main app roots. + * + * @return array<int, array{dir: string, suffix: string}> + */ + protected static function mainAppRoots(): array + { + $roots = []; + $appRoot = app_path(); + if (is_dir($appRoot)) { + $roots[] = [ + 'dir' => $appRoot, + 'suffix' => (string)Config::get('app.controller_suffix', ''), + ]; + } + return $roots; + } + + /** + * Roots for all enabled plugins. + * + * Rule (A): if plugin app config is missing/empty, skip it silently. + * + * @return array<int, array{dir: string, suffix: string}> + */ + protected static function allPluginRoots(): array + { + $roots = []; + $pluginBase = base_path('plugin'); + if (!is_dir($pluginBase)) { + return []; + } + + foreach (scandir($pluginBase) ?: [] as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + if (!static::isValidIdentifier($entry)) { + continue; + } + + $pluginDir = $pluginBase . DIRECTORY_SEPARATOR . $entry; + if (!is_dir($pluginDir)) { + continue; + } + + // Only load enabled plugins (same semantics as Route::loadAnnotationRoutes()). + $pluginAppConfig = Config::get("plugin.$entry.app"); + if (!$pluginAppConfig) { + continue; + } + + $pluginAppDir = $pluginDir . DIRECTORY_SEPARATOR . 'app'; + if (!is_dir($pluginAppDir)) { + continue; + } + + $roots[] = [ + 'dir' => $pluginAppDir, + 'suffix' => is_array($pluginAppConfig) + ? (string)($pluginAppConfig['controller_suffix'] ?? '') + : (string)Config::get("plugin.$entry.app.controller_suffix", ''), + ]; + } + + return $roots; + } + + /** + * Roots for a single plugin (strict). + * + * @param string $plugin + * @return array<int, array{dir: string, suffix: string}> + */ + protected static function singlePluginRoots(string $plugin): array + { + if (!static::isValidIdentifier($plugin)) { + throw new InvalidArgumentException("Invalid plugin identifier: $plugin"); + } + + $pluginBase = base_path('plugin'); + $pluginDir = $pluginBase . DIRECTORY_SEPARATOR . $plugin; + if (!is_dir($pluginDir)) { + throw new InvalidArgumentException("Plugin directory not found: $plugin"); + } + + $pluginAppConfig = Config::get("plugin.$plugin.app"); + if (!$pluginAppConfig) { + throw new InvalidArgumentException("Plugin app config not found or empty: plugin.$plugin.app"); + } + + $pluginAppDir = $pluginDir . DIRECTORY_SEPARATOR . 'app'; + if (!is_dir($pluginAppDir)) { + throw new InvalidArgumentException("Plugin app directory not found: plugin/$plugin/app"); + } + + return [[ + 'dir' => $pluginAppDir, + 'suffix' => is_array($pluginAppConfig) + ? (string)($pluginAppConfig['controller_suffix'] ?? '') + : (string)Config::get("plugin.$plugin.app.controller_suffix", ''), + ]]; + } + + /** + * Find controller files. + * + * @param string $rootDir + * @param string $controllerSuffix + * @param bool $attributesOnly + * @return FileInfo[] + */ + protected static function findControllerFiles(string $rootDir, string $controllerSuffix = '', bool $attributesOnly = true): array + { + $controllerPathRegex = $controllerSuffix !== '' + ? ('/(^|[\/\\\\])controller[\/\\\\].*' . preg_quote($controllerSuffix, '/') . '\.php$/i') + : '/(^|[\/\\\\])controller[\/\\\\].+\.php$/i'; + + $finder = Finder::in($rootDir) + ->files() + ->path($controllerPathRegex) + ->typeIn(['class']) + ->psr4(true); + if ($attributesOnly) { + $finder->hasAttributes(true); + } + + return $finder->find(); + } + + /** + * Is valid identifier (plugin name). + * + * @param string $name + * @return bool + */ + protected static function isValidIdentifier(string $name): bool + { + return $name !== '' && (bool)preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/Finder/FileInfo.php b/vendor/workerman/webman-framework/src/Finder/FileInfo.php new file mode 100644 index 0000000..1f82f3f --- /dev/null +++ b/vendor/workerman/webman-framework/src/Finder/FileInfo.php @@ -0,0 +1,142 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Finder; + +use Webman\File; + +/** + * Class FileInfo + * @package Webman\Finder + */ +class FileInfo extends File +{ + /** + * @var array PHP file meta info (hasAttributes, type, class, psr4, etc.) + */ + protected array $meta = []; + + /** + * @var string Root directory this file belongs to + */ + protected string $rootDir = ''; + + // Root namespace is intentionally not stored. + /** + * Constructor. + * @param string $path + * @param array $meta + * @param string $rootDir + */ + public function __construct(string $path, array $meta = [], string $rootDir = '') + { + parent::__construct($path); + $this->meta = $meta; + $this->rootDir = $rootDir; + } + + /** + * Get PHP file meta info. + * @return array + */ + public function meta(): array + { + return $this->meta; + } + + /** + * Get declared class (FQCN) from meta. + * Example: "App\\Controller\\IndexController" + * + * @return string|null + */ + public function class(): ?string + { + $class = $this->meta['class'] ?? null; + if (!is_string($class) || $class === '') { + return null; + } + return ltrim($class, '\\'); + } + + /** + * Get declared short class name (without namespace). + * Example: "IndexController" + * + * @return string|null + */ + public function className(): ?string + { + $fqcn = $this->class(); + if ($fqcn === null) { + return null; + } + $pos = strrpos($fqcn, '\\'); + return $pos === false ? $fqcn : substr($fqcn, $pos + 1); + } + + /** + * Get declared namespace. + * Example: "App\\Controller" + * + * @return string|null + */ + public function namespace(): ?string + { + $fqcn = $this->class(); + if ($fqcn === null) { + return null; + } + $pos = strrpos($fqcn, '\\'); + return $pos === false ? null : substr($fqcn, 0, $pos); + } + + /** + * Set meta info. + * @param array $meta + * @return $this + */ + public function setMeta(array $meta): static + { + $this->meta = $meta; + return $this; + } + + /** + * Get root directory. + * @return string + */ + public function rootDir(): string + { + return $this->rootDir; + } + + /** + * Get relative pathname from root directory. + * @return string + */ + public function relativePathname(): string + { + if ($this->rootDir === '') { + return $this->getPathname(); + } + $rootDir = rtrim(str_replace('\\', '/', $this->rootDir), '/'); + $pathname = str_replace('\\', '/', $this->getPathname()); + $rootLen = strlen($rootDir); + if (strncasecmp($pathname, $rootDir, $rootLen) === 0) { + return ltrim(substr($pathname, $rootLen), '/'); + } + return $this->getPathname(); + } +} diff --git a/vendor/workerman/webman-framework/src/Finder/Finder.php b/vendor/workerman/webman-framework/src/Finder/Finder.php new file mode 100644 index 0000000..7b43168 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Finder/Finder.php @@ -0,0 +1,912 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Finder; + +use support\Log; + +/** + * Class Finder + * File finder with PHP file caching support. + * @package Webman\Finder + */ +class Finder +{ + /** + * @var string[] Root directories + */ + protected array $roots = []; + + /** + * @var bool Only match files (not directories) + */ + protected bool $onlyFiles = false; + + /** + * @var array File name patterns (glob or regex) + */ + protected array $names = []; + + /** + * @var array Path patterns (regex) + */ + protected array $paths = []; + + /** + * @var array Directories to exclude + */ + protected array $excludeDirs = ['vendor', 'runtime', '.git', 'storage', 'tests', 'node_modules']; + + /** + * @var bool Enable PHP meta analysis + */ + protected bool $phpMetaEnabled = false; + + /** + * @var bool|null Filter by hasAttributes + */ + protected ?bool $filterHasAttributes = null; + + /** + * @var array|null Filter by type + */ + protected ?array $filterTypes = null; + + /** + * @var bool|null Filter by psr4 + */ + protected ?bool $filterPsr4 = null; + + /** + * @var array<string, array> PHP file cache: [path => meta, ...] + */ + protected static array $phpCache = []; + + /** + * @var array<string, bool> Cache dirty flags by root + */ + protected static array $cacheDirty = []; + + /** + * @var string Cache directory + */ + protected static string $cacheDir = ''; + + /** + * Create a new Finder instance with root directories. + * @param string|array $dirs + * @return static + */ + public static function in(string|array $dirs): static + { + $instance = new static(); + foreach ((array)$dirs as $dir) { + if (is_dir($dir)) { + $instance->roots[] = static::normalizePath($dir); + } + } + return $instance; + } + + /** + * Create a new Finder instance. + * Use in() to set search directories. + * @return static + */ + public static function create(): static + { + return new static(); + } + + /** + * Set cache directory. + * @param string $dir + * @return void + */ + public static function setCacheDir(string $dir): void + { + static::$cacheDir = rtrim($dir, '/\\'); + } + + /** + * Get cache directory. + * @return string + */ + protected static function getCacheDir(): string + { + if (static::$cacheDir === '') { + static::$cacheDir = rtrim(runtime_path('cache/framework/finder'), '/\\'); + if (!is_dir(static::$cacheDir)) { + @mkdir(static::$cacheDir, 0755, true); + } + } + return static::$cacheDir; + } + + /** + * Only match files. + * @return $this + */ + public function files(): static + { + $this->onlyFiles = true; + return $this; + } + + /** + * Filter by file name pattern (glob or regex). + * @param string|array $patterns + * @return $this + */ + public function name(string|array $patterns): static + { + $this->names = array_merge($this->names, (array)$patterns); + return $this; + } + + /** + * Filter by path pattern (regex). + * @param string|array $patterns + * @return $this + */ + public function path(string|array $patterns): static + { + $this->paths = array_merge($this->paths, (array)$patterns); + return $this; + } + + /** + * Exclude directories. + * @param string|array $dirs + * @return $this + */ + public function exclude(string|array $dirs): static + { + $this->excludeDirs = array_merge($this->excludeDirs, (array)$dirs); + return $this; + } + + /** + * Set exclude directories (replace default). + * @param array $dirs + * @return $this + */ + public function excludeDirs(array $dirs): static + { + $this->excludeDirs = $dirs; + return $this; + } + + /** + * Enable PHP meta analysis and caching. + * @return $this + */ + public function withPhpMeta(): static + { + $this->phpMetaEnabled = true; + return $this; + } + + /** + * Whether any PHP meta filters are requested. + * @return bool + */ + protected function phpFiltersRequested(): bool + { + return $this->filterHasAttributes !== null + || $this->filterTypes !== null + || $this->filterPsr4 !== null; + } + + /** + * Filter by hasAttributes. + * @param bool $value + * @return $this + */ + public function hasAttributes(bool $value): static + { + // PHP-specific filter: enable PHP meta automatically. + $this->phpMetaEnabled = true; + $this->filterHasAttributes = $value; + return $this; + } + + /** + * Filter by type (class, interface, trait, enum, non_class). + * @param array $types + * @return $this + */ + public function typeIn(array $types): static + { + // PHP-specific filter: enable PHP meta automatically. + $this->phpMetaEnabled = true; + $this->filterTypes = $types; + return $this; + } + + /** + * Filter by PSR-4 compliance. + * @param bool $value + * @return $this + */ + public function psr4(bool $value): static + { + // PHP-specific filter: enable PHP meta automatically. + $this->phpMetaEnabled = true; + $this->filterPsr4 = $value; + return $this; + } + + /** + * Find files and return FileInfo array. + * @return FileInfo[] + */ + public function find(): array + { + $results = []; + $phpFiltersRequested = $this->phpFiltersRequested(); + // phpMetaEnabled can be turned on explicitly (withPhpMeta) or implicitly (by PHP filters). + $phpMetaEnabled = $this->phpMetaEnabled || $phpFiltersRequested; + + foreach ($this->roots as $rootDir) { + + // Load cache for this root + if ($phpMetaEnabled) { + $this->loadCache($rootDir); + } + + // Scan directory + $files = $this->scanDirectory($rootDir); + + // Apply filters + foreach ($files as $filePath) { + // Apply name filter + if (!$this->matchesName($filePath)) { + continue; + } + + // Apply path filter + if (!$this->matchesPath($filePath, $rootDir)) { + continue; + } + + // Get or compute PHP meta + $meta = []; + if ($phpMetaEnabled) { + // If any PHP filters were requested, skip non-PHP files. + if ($phpFiltersRequested && !$this->isPhpFile($filePath)) { + continue; + } + if ($this->isPhpFile($filePath)) { + $meta = $this->getPhpMeta($filePath, $rootDir); + + // Apply PHP meta filters + if ($phpFiltersRequested && !$this->matchesPhpFilters($meta, $filePath, $rootDir)) { + continue; + } + } + } + + $results[] = new FileInfo($filePath, $meta, $rootDir); + } + + // Save cache if dirty + if ($phpMetaEnabled) { + $this->saveCache($rootDir); + } + } + + return $results; + } + + /** + * Find files and return paths array. + * @return string[] + */ + public function findPaths(): array + { + return array_map(fn(FileInfo $f) => $f->getPathname(), $this->find()); + } + + /** + * Scan directory recursively. + * @param string $dir + * @return array + */ + protected function scanDirectory(string $dir): array + { + $files = []; + $excludeSet = array_flip($this->excludeDirs); + + $this->scanDirectoryRecursive($dir, $excludeSet, $files); + + return $files; + } + + /** + * Scan a directory recursively. + * @param string $dir + * @param array $excludeSet + * @param array $files + * @return void + */ + protected function scanDirectoryRecursive(string $dir, array $excludeSet, array &$files): void + { + try { + $entries = scandir($dir, SCANDIR_SORT_NONE); + if ($entries === false) { + Log::error("Failed to scan directory $dir"); + return; + } + + foreach ($entries as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + + $path = $dir . DIRECTORY_SEPARATOR . $entry; + if (is_dir($path)) { + if (!isset($excludeSet[$entry]) && !is_link($path)) { + $this->scanDirectoryRecursive($path, $excludeSet, $files); + } + continue; + } + + // Skip if only files mode and not a file + if ($this->onlyFiles && !is_file($path)) { + continue; + } + + $files[] = static::normalizePath($path); + } + } catch (\Throwable $e) { + Log::error("Failed to scan directory $dir: {$e->getMessage()}"); + } + } + + /** + * Check if file matches name patterns. + * @param string $filePath + * @return bool + */ + protected function matchesName(string $filePath): bool + { + if (empty($this->names)) { + return true; + } + + $basename = basename($filePath); + foreach ($this->names as $pattern) { + if ($this->matchPattern($basename, $pattern)) { + return true; + } + } + return false; + } + + /** + * Check if file matches path patterns. + * @param string $filePath + * @param string $rootDir + * @return bool + */ + protected function matchesPath(string $filePath, string $rootDir): bool + { + if (empty($this->paths)) { + return true; + } + + // Use relative path for matching + $relativePath = $this->getRelativePath($filePath, $rootDir); + + foreach ($this->paths as $pattern) { + if ($this->isRegex($pattern) && preg_match($pattern, $relativePath)) { + return true; + } + if (!$this->isRegex($pattern) && stripos($relativePath, $pattern) !== false) { + return true; + } + } + return false; + } + + /** + * Match a pattern (glob or regex). + * @param string $value + * @param string $pattern + * @return bool + */ + protected function matchPattern(string $value, string $pattern): bool + { + // Regex pattern + if ($this->isRegex($pattern)) { + return (bool)preg_match($pattern, $value); + } + + // Glob pattern + return fnmatch($pattern, $value, FNM_CASEFOLD); + } + + /** + * Check if pattern is a regex. + * @param string $pattern + * @return bool + */ + protected function isRegex(string $pattern): bool + { + if ($pattern === '') { + return false; + } + $delimiter = $pattern[0]; + if (!in_array($delimiter, ['/', '#', '~', '%'], true)) { + return false; + } + return (bool)preg_match('/^' . preg_quote($delimiter, '/') . '.*' . preg_quote($delimiter, '/') . '[imsxuADU]*$/', $pattern); + } + + /** + * Check if file is a PHP file. + * @param string $filePath + * @return bool + */ + protected function isPhpFile(string $filePath): bool + { + return strtolower(pathinfo($filePath, PATHINFO_EXTENSION)) === 'php'; + } + + /** + * Get PHP file meta, using cache when possible. + * @param string $filePath + * @param string $rootDir + * @return array + */ + protected function getPhpMeta(string $filePath, string $rootDir): array + { + $cacheKey = $this->getCacheKey($rootDir); + $mtime = @filemtime($filePath); + + // Check cache + if (isset(static::$phpCache[$cacheKey][$filePath])) { + $cached = static::$phpCache[$cacheKey][$filePath]; + if (isset($cached['mtime']) && $cached['mtime'] === $mtime) { + return $cached; + } + } + + // Compute new meta + $meta = $this->computePhpMeta($filePath, $mtime); + + // Update cache + static::$phpCache[$cacheKey][$filePath] = $meta; + static::$cacheDirty[$cacheKey] = true; + + return $meta; + } + + /** + * Ensure psr4 is computed and cached in meta. + * Only computes once per (file, mtime) cache entry. + * @param string $filePath + * @param string $rootDir + * @param array $meta + * @return array Updated meta + */ + protected function ensurePsr4Cached(string $filePath, string $rootDir, array $meta): array + { + if (array_key_exists('psr4', $meta)) { + return $meta; + } + + $psr4 = $this->checkPsr4($filePath, $rootDir, $meta['class'] ?? null); + $meta['psr4'] = $psr4; + + $cacheKey = $this->getCacheKey($rootDir); + static::$phpCache[$cacheKey][$filePath] = $meta; + static::$cacheDirty[$cacheKey] = true; + + return $meta; + } + + /** + * Compute PHP file meta info. + * @param string $filePath + * @param int|false $mtime + * @return array + */ + protected function computePhpMeta(string $filePath, int|false $mtime): array + { + $meta = [ + 'mtime' => $mtime ?: 0, + 'hasAttributes' => false, + 'class' => null, + ]; + + $code = @file_get_contents($filePath); + if ($code === false || $code === '') { + $meta['type'] = 'non_class'; + return $meta; + } + + // Fast check for attributes + $meta['hasAttributes'] = str_contains($code, '#['); + + // Parse to get type and declared class + $parseResult = $this->parsePhpFile($code); + $meta['type'] = $parseResult['type']; + $meta['class'] = $parseResult['class']; + + return $meta; + } + + /** + * Parse PHP file to extract type and declared class. + * @param string $code + * @return array{type: string, class: string|null} + */ + protected function parsePhpFile(string $code): array + { + $result = [ + 'type' => 'non_class', + 'class' => null, + ]; + + try { + $tokens = token_get_all($code); + } catch (\Throwable $e) { + return $result; + } + + $namespace = ''; + $count = count($tokens); + $prevSignificant = null; + + for ($i = 0; $i < $count; $i++) { + $token = $tokens[$i]; + $id = is_array($token) ? $token[0] : null; + + // Extract namespace + if ($id === T_NAMESPACE) { + $ns = ''; + for ($j = $i + 1; $j < $count; $j++) { + $t = $tokens[$j]; + if (is_array($t)) { + if ($t[0] === T_STRING || $t[0] === T_NS_SEPARATOR) { + $ns .= $t[1]; + continue; + } + if (defined('T_NAME_QUALIFIED') && $t[0] === T_NAME_QUALIFIED) { + $ns .= $t[1]; + continue; + } + if ($t[0] === T_WHITESPACE) { + continue; + } + } else { + if ($t === ';' || $t === '{') { + break; + } + } + } + $namespace = trim($ns, '\\'); + continue; + } + + // Detect class/interface/trait/enum + if ($id === T_CLASS || $id === T_INTERFACE || $id === T_TRAIT || (defined('T_ENUM') && $id === T_ENUM)) { + // Skip ::class usage + if ($prevSignificant === T_DOUBLE_COLON) { + $prevSignificant = null; + continue; + } + // Skip anonymous class + if ($id === T_CLASS && $prevSignificant === T_NEW) { + continue; + } + + // Determine type + $type = match ($id) { + T_CLASS => 'class', + T_INTERFACE => 'interface', + T_TRAIT => 'trait', + default => defined('T_ENUM') && $id === T_ENUM ? 'enum' : 'class', + }; + + // Extract class name + for ($j = $i + 1; $j < $count; $j++) { + $t = $tokens[$j]; + if (!is_array($t)) { + continue; + } + if ($t[0] === T_WHITESPACE) { + continue; + } + if ($t[0] === T_STRING) { + $className = $t[1]; + $result['type'] = $type; + $result['class'] = $namespace !== '' ? ($namespace . '\\' . $className) : $className; + return $result; // Return first declaration only + } + break; + } + } + + // Track previous significant token + if (is_array($token)) { + if ($id !== T_WHITESPACE && $id !== T_COMMENT && $id !== T_DOC_COMMENT) { + $prevSignificant = $id; + } + } else { + if (trim($token) !== '') { + $prevSignificant = $token; + } + } + } + + return $result; + } + + /** + * Check if meta matches PHP filters. + * @param array $meta + * @param string $filePath + * @param string $rootDir + * @return bool + */ + protected function matchesPhpFilters(array $meta, string $filePath, string $rootDir): bool + { + // Filter by hasAttributes + if ($this->filterHasAttributes !== null && $meta['hasAttributes'] !== $this->filterHasAttributes) { + return false; + } + + // Filter by type + if ($this->filterTypes !== null && !in_array($meta['type'], $this->filterTypes, true)) { + return false; + } + + // Filter by PSR-4 + if ($this->filterPsr4 !== null) { + $meta = $this->ensurePsr4Cached($filePath, $rootDir, $meta); + $psr4Ok = $meta['psr4']; + if ($psr4Ok !== $this->filterPsr4) { + return false; + } + } + + return true; + } + + /** + * Check if file complies with PSR-4. + * @param string $filePath + * @param string $rootDir + * @param string|null $declaredClass + * @return bool + */ + protected function checkPsr4(string $filePath, string $rootDir, ?string $declaredClass): bool + { + if ($declaredClass === null) { + return false; + } + + // Namespace-agnostic check: + // declared class must end with the PSR-4 relative class path derived from file path. + $relativePath = $this->getRelativePath($filePath, $rootDir); + if ($relativePath === '' || !str_ends_with($relativePath, '.php')) { + return false; + } + $relativeClassPath = substr($relativePath, 0, -4); + $relativeClassPath = str_replace('/', '\\', $relativeClassPath); + if (!$this->isValidPsr4ClassPath($relativeClassPath)) { + return false; + } + + $declaredClass = ltrim($declaredClass, '\\'); + $suffix = '\\' . $relativeClassPath; + return $declaredClass === $relativeClassPath || str_ends_with($declaredClass, $suffix); + } + + /** + * Derive expected class name from file path (PSR-4 style). + * @param string $filePath + * @param string $rootDir + * @param string $rootNamespace + * @return string|null + */ + protected function classFromFile(string $filePath, string $rootDir, string $rootNamespace): ?string + { + $rootDir = rtrim(static::normalizePath($rootDir), '/'); + $filePath = static::normalizePath($filePath); + + $rootLen = strlen($rootDir); + if (strncasecmp($filePath, $rootDir, $rootLen) !== 0) { + return null; + } + + $relative = ltrim(substr($filePath, $rootLen), '/'); + if ($relative === '' || !str_ends_with($relative, '.php')) { + return null; + } + + $relative = substr($relative, 0, -4); // Remove .php + $relative = str_replace('/', '\\', $relative); + + if (!$this->isValidPsr4ClassPath($relative)) { + return null; + } + + return rtrim($rootNamespace, '\\') . '\\' . $relative; + } + + /** + * Check if relative class path is valid PSR-4. + * @param string $relativeClassPath + * @return bool + */ + protected function isValidPsr4ClassPath(string $relativeClassPath): bool + { + return (bool)preg_match('/^[A-Za-z_][A-Za-z0-9_]*(\\\\[A-Za-z_][A-Za-z0-9_]*)*$/', $relativeClassPath); + } + + /** + * Get relative path from root directory. + * @param string $filePath + * @param string $rootDir + * @return string + */ + protected function getRelativePath(string $filePath, string $rootDir): string + { + $rootDir = rtrim(static::normalizePath($rootDir), '/'); + $filePath = static::normalizePath($filePath); + $rootLen = strlen($rootDir); + + if (strncasecmp($filePath, $rootDir, $rootLen) === 0) { + return ltrim(substr($filePath, $rootLen), '/'); + } + + return $filePath; + } + + /** + * Get cache key for a root directory. + * @param string $rootDir + * @return string + */ + protected function getCacheKey(string $rootDir): string + { + return hash('sha256', $rootDir); + } + + /** + * Get cache file path for a root directory. + * @param string $rootDir + * @return string + */ + protected function getCacheFile(string $rootDir): string + { + $cacheKey = $this->getCacheKey($rootDir); + return static::getCacheDir() . DIRECTORY_SEPARATOR . "php_files_{$cacheKey}.php"; + } + + /** + * Load cache for a root directory. + * @param string $rootDir + * @return void + */ + protected function loadCache(string $rootDir): void + { + $cacheKey = $this->getCacheKey($rootDir); + if (isset(static::$phpCache[$cacheKey])) { + return; // Already loaded + } + + $cacheFile = $this->getCacheFile($rootDir); + if (is_file($cacheFile)) { + try { + $data = include $cacheFile; + if (is_array($data)) { + static::$phpCache[$cacheKey] = $data; + return; + } + } catch (\Throwable $e) { + // Ignore corrupted cache + } + } + + static::$phpCache[$cacheKey] = []; + } + + /** + * Save cache for a root directory. + * @param string $rootDir + * @return void + */ + protected function saveCache(string $rootDir): void + { + $cacheKey = $this->getCacheKey($rootDir); + if (empty(static::$cacheDirty[$cacheKey])) { + return; + } + + $cacheFile = $this->getCacheFile($rootDir); + $cacheDir = dirname($cacheFile); + + if (!is_dir($cacheDir)) { + @mkdir($cacheDir, 0755, true); + } + + $data = static::$phpCache[$cacheKey] ?? []; + + // Clean up deleted files + foreach ($data as $path => $meta) { + if (!is_file($path)) { + unset($data[$path]); + } + } + + static::$phpCache[$cacheKey] = $data; + + $content = "<?php\nreturn " . var_export($data, true) . ";\n"; + $suffix = (string)getmypid(); + try { + $suffix .= '.' . bin2hex(random_bytes(6)); + } catch (\Throwable $e) { + $suffix .= '.' . uniqid('', true); + } + $tempFile = $cacheFile . '.tmp.' . $suffix; + + // No locks: write temp file then atomic rename. + if (@file_put_contents($tempFile, $content) !== false) { + // On Windows, rename() fails if target exists. Use a backup to swap. + if (!@rename($tempFile, $cacheFile)) { + $backupFile = $cacheFile . '.bak.' . $suffix; + // Best-effort: move old cache away, then move new cache in. + @rename($cacheFile, $backupFile); + if (@rename($tempFile, $cacheFile)) { + @unlink($backupFile); + } else { + // Restore old cache if possible. + @rename($backupFile, $cacheFile); + @unlink($tempFile); + } + } + } + + static::$cacheDirty[$cacheKey] = false; + } + + /** + * Clear all caches. + * @return void + */ + public static function clearCache(): void + { + static::$phpCache = []; + static::$cacheDirty = []; + } + + /** + * Normalize path separators. + * @param string $path + * @return string + */ + protected static function normalizePath(string $path): string + { + $realPath = realpath($path); + if ($realPath !== false) { + return str_replace('\\', '/', $realPath); + } + return str_replace('\\', '/', $path); + } +} diff --git a/vendor/workerman/webman-framework/src/Http/Request.php b/vendor/workerman/webman-framework/src/Http/Request.php new file mode 100644 index 0000000..fe326c3 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Http/Request.php @@ -0,0 +1,433 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Http; + +use Webman\Route\Route; +use function current; +use function filter_var; +use function inet_ntop; +use function inet_pton; +use function ip2long; +use function is_array; +use function strlen; +use function strpos; +use function substr; +use const FILTER_FLAG_IPV4; +use const FILTER_FLAG_NO_PRIV_RANGE; +use const FILTER_FLAG_NO_RES_RANGE; +use const FILTER_VALIDATE_IP; + +/** + * Class Request + * @package Webman\Http + */ +class Request extends \Workerman\Protocols\Http\Request +{ + /** + * @var string + */ + public $plugin = null; + + /** + * @var string + */ + public $app = null; + + /** + * @var string + */ + public $controller = null; + + /** + * @var string + */ + public $action = null; + + /** + * @var Route + */ + public $route = null; + + /** + * @var bool + */ + protected $isDirty = false; + + /** + * @return mixed|null + */ + public function all() + { + return $this->get() + $this->post(); + } + + /** + * Input + * @param string $name + * @param mixed $default + * @return mixed + */ + public function input(string $name, mixed $default = null) + { + return $this->get($name, $this->post($name, $default)); + } + + /** + * Only + * @param array $keys + * @return array + */ + public function only(array $keys): array + { + $all = $this->all(); + $result = []; + foreach ($keys as $key) { + if (array_key_exists($key, $all)) { + $result[$key] = $all[$key]; + } + } + return $result; + } + + /** + * Except + * @param array $keys + * @return mixed|null + */ + public function except(array $keys) + { + $all = $this->all(); + foreach ($keys as $key) { + unset($all[$key]); + } + return $all; + } + + /** + * File + * @param string|null $name + * @return UploadFile|UploadFile[]|null + */ + public function file(?string $name = null): array|null|UploadFile + { + $files = parent::file($name); + if (null === $files) { + return $name === null ? [] : null; + } + if ($name !== null) { + // Multi files + if (is_array(current($files))) { + return $this->parseFiles($files); + } + return $this->parseFile($files); + } + $uploadFiles = []; + foreach ($files as $name => $file) { + // Multi files + if (is_array(current($file))) { + $uploadFiles[$name] = $this->parseFiles($file); + } else { + $uploadFiles[$name] = $this->parseFile($file); + } + } + return $uploadFiles; + } + + /** + * ParseFile + * @param array $file + * @return UploadFile + */ + protected function parseFile(array $file): UploadFile + { + return new UploadFile($file['tmp_name'], $file['name'], $file['type'], $file['error']); + } + + /** + * ParseFiles + * @param array $files + * @return array + */ + protected function parseFiles(array $files): array + { + $uploadFiles = []; + foreach ($files as $key => $file) { + if (is_array(current($file))) { + $uploadFiles[$key] = $this->parseFiles($file); + } else { + $uploadFiles[$key] = $this->parseFile($file); + } + } + return $uploadFiles; + } + + /** + * GetRemoteIp + * @return string + */ + public function getRemoteIp(): string + { + return $this->connection ? $this->connection->getRemoteIp() : '0.0.0.0'; + } + + /** + * GetRemotePort + * @return int + */ + public function getRemotePort(): int + { + return $this->connection ? $this->connection->getRemotePort() : 0; + } + + /** + * GetLocalIp + * @return string + */ + public function getLocalIp(): string + { + return $this->connection ? $this->connection->getLocalIp() : '0.0.0.0'; + } + + /** + * GetLocalPort + * @return int + */ + public function getLocalPort(): int + { + return $this->connection ? $this->connection->getLocalPort() : 0; + } + + /** + * GetRealIp + * @param bool $safeMode + * @return string + */ + public function getRealIp(bool $safeMode = true): string + { + $remoteIp = $this->getRemoteIp(); + if ($safeMode && !static::isIntranetIp($remoteIp)) { + return $remoteIp; + } + $ip = $this->header('x-forwarded-for') + ?? $this->header('x-real-ip') + ?? $this->header('client-ip') + ?? $this->header('x-client-ip') + ?? $this->header('via') + ?? $remoteIp; + if (is_string($ip)) { + $ip = current(explode(',', $ip)); + } + return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : $remoteIp; + } + + /** + * Url + * @return string + */ + public function url(): string + { + return '//' . $this->host() . $this->path(); + } + + /** + * FullUrl + * @return string + */ + public function fullUrl(): string + { + return '//' . $this->host() . $this->uri(); + } + + /** + * IsAjax + * @return bool + */ + public function isAjax(): bool + { + return $this->header('X-Requested-With') === 'XMLHttpRequest'; + } + + /** + * IsGet + * @return bool + */ + public function isGet(): bool + { + return $this->method() === 'GET'; + } + + + /** + * IsPost + * @return bool + */ + public function isPost(): bool + { + return $this->method() === 'POST'; + } + + + /** + * IsPjax + * @return bool + */ + public function isPjax(): bool + { + return (bool)$this->header('X-PJAX'); + } + + /** + * ExpectsJson + * @return bool + */ + public function expectsJson(): bool + { + return ($this->isAjax() && !$this->isPjax()) || $this->acceptJson(); + } + + /** + * AcceptJson + * @return bool + */ + public function acceptJson(): bool + { + return false !== strpos($this->header('accept', ''), 'json'); + } + + /** + * IsIntranetIp + * @param string $ip + * @return bool + */ + public static function isIntranetIp(string $ip): bool + { + // TcpConnection may return an IPv6 address enclosed in brackets. + if (strlen($ip) > 2 + && $ip[0] === '[' + && substr($ip, -1) === ']' + && strpos($ip, ':') !== false + ) { + $ip = substr($ip, 1, -1); + } + // Not validate ip . + if (!filter_var($ip, FILTER_VALIDATE_IP)) { + return false; + } + // Convert IPv4-mapped IPv6 addresses so their embedded IPv4 address + // is checked against the IPv4 private and reserved ranges below. + $binaryIp = inet_pton($ip); + if ($binaryIp !== false + && strlen($binaryIp) === 16 + && substr($binaryIp, 0, 12) === "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff" + ) { + $mappedIp = inet_ntop(substr($binaryIp, 12)); + if ($mappedIp !== false) { + $ip = $mappedIp; + } + } + // Is intranet ip ? For IPv4, the result of false may not be accurate, so we need to check it manually later . + if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { + return true; + } + // Manual check only for IPv4 . + if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return false; + } + // Manual check . + $reservedIps = [ + 1681915904 => 1686110207, // 100.64.0.0 - 100.127.255.255 + 3221225472 => 3221225727, // 192.0.0.0 - 192.0.0.255 + 3221225984 => 3221226239, // 192.0.2.0 - 192.0.2.255 + 3227017984 => 3227018239, // 192.88.99.0 - 192.88.99.255 + 3323068416 => 3323199487, // 198.18.0.0 - 198.19.255.255 + 3325256704 => 3325256959, // 198.51.100.0 - 198.51.100.255 + 3405803776 => 3405804031, // 203.0.113.0 - 203.0.113.255 + 3758096384 => 4026531839, // 224.0.0.0 - 239.255.255.255 + ]; + $ipLong = ip2long($ip); + foreach ($reservedIps as $ipStart => $ipEnd) { + if (($ipLong >= $ipStart) && ($ipLong <= $ipEnd)) { + return true; + } + } + return false; + } + + /** + * Set get. + * @param array|string $input + * @param mixed $value + * @return Request + */ + public function setGet(array|string $input, mixed $value = null): Request + { + $this->isDirty = true; + $input = is_array($input) ? $input : array_merge($this->get(), [$input => $value]); + if (isset($this->data)) { + $this->data['get'] = $input; + } else { + $this->_data['get'] = $input; + } + return $this; + } + + /** + * Set post. + * @param array|string $input + * @param mixed $value + * @return Request + */ + public function setPost(array|string $input, mixed $value = null): Request + { + $this->isDirty = true; + $input = is_array($input) ? $input : array_merge($this->post(), [$input => $value]); + if (isset($this->data)) { + $this->data['post'] = $input; + } else { + $this->_data['post'] = $input; + } + return $this; + } + + /** + * Set header. + * @param array|string $input + * @param mixed $value + * @return Request + */ + public function setHeader(array|string $input, mixed $value = null): Request + { + $this->isDirty = true; + $input = is_array($input) ? $input : array_merge($this->header(), [$input => $value]); + if (isset($this->data)) { + $this->data['headers'] = $input; + } else { + $this->_data['headers'] = $input; + } + return $this; + } + + /** + * Destroy + */ + public function destroy(): void + { + if ($this->isDirty) { + unset($this->data['get'], $this->data['post'], $this->data['headers']); + } + parent::destroy(); + } + +} diff --git a/vendor/workerman/webman-framework/src/Http/Response.php b/vendor/workerman/webman-framework/src/Http/Response.php new file mode 100644 index 0000000..621cfa7 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Http/Response.php @@ -0,0 +1,89 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Http; + +use Throwable; +use Webman\App; +use function filemtime; +use function gmdate; + +/** + * Class Response + * @package Webman\Http + */ +class Response extends \Workerman\Protocols\Http\Response +{ + /** + * @var Throwable + */ + protected $exception = null; + + /** + * File + * @param string $file + * @return $this + */ + public function file(string $file): Response + { + if ($this->notModifiedSince($file)) { + return $this->withStatus(304); + } + return $this->withFile($file); + } + + /** + * Download + * @param string $file + * @param string $downloadName + * @return $this + */ + public function download(string $file, string $downloadName = ''): Response + { + $this->withFile($file); + if ($downloadName) { + // Sanitize to prevent header injection + $downloadName = str_replace(['"', "\r", "\n", "\0"], '', $downloadName); + $this->header('Content-Disposition', "attachment; filename=\"$downloadName\""); + } + return $this; + } + + /** + * NotModifiedSince + * @param string $file + * @return bool + */ + protected function notModifiedSince(string $file): bool + { + $ifModifiedSince = App::request()->header('if-modified-since'); + if ($ifModifiedSince === null || !is_file($file) || !($mtime = filemtime($file))) { + return false; + } + return $ifModifiedSince === gmdate('D, d M Y H:i:s', $mtime) . ' GMT'; + } + + /** + * Exception + * @param Throwable|null $exception + * @return Throwable|null + */ + public function exception(?Throwable $exception = null): ?Throwable + { + if ($exception) { + $this->exception = $exception; + } + return $this->exception; + } +} diff --git a/vendor/workerman/webman-framework/src/Http/UploadFile.php b/vendor/workerman/webman-framework/src/Http/UploadFile.php new file mode 100644 index 0000000..8a63421 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Http/UploadFile.php @@ -0,0 +1,111 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Http; + +use Webman\File; +use function pathinfo; + +/** + * Class UploadFile + * @package Webman\Http + */ +class UploadFile extends File +{ + /** + * @var string + */ + protected $uploadName = null; + + /** + * @var string + */ + protected $uploadMimeType = null; + + /** + * @var int + */ + protected $uploadErrorCode = null; + + /** + * UploadFile constructor. + * + * @param string $fileName + * @param string $uploadName + * @param string $uploadMimeType + * @param int $uploadErrorCode + */ + public function __construct(string $fileName, string $uploadName, string $uploadMimeType, int $uploadErrorCode) + { + $this->uploadName = $uploadName; + $this->uploadMimeType = $uploadMimeType; + $this->uploadErrorCode = $uploadErrorCode; + parent::__construct($fileName); + } + + /** + * GetUploadName + * @return string + */ + public function getUploadName(): ?string + { + return $this->uploadName; + } + + /** + * GetUploadMimeType + * @return string + */ + public function getUploadMimeType(): ?string + { + return $this->uploadMimeType; + } + + /** + * GetUploadExtension + * @return string + */ + public function getUploadExtension(): string + { + return pathinfo($this->uploadName, PATHINFO_EXTENSION); + } + + /** + * GetUploadErrorCode + * @return int + */ + public function getUploadErrorCode(): ?int + { + return $this->uploadErrorCode; + } + + /** + * IsValid + * @return bool + */ + public function isValid(): bool + { + return $this->uploadErrorCode === UPLOAD_ERR_OK; + } + + /** + * GetUploadMineType + * @return string + * @deprecated + */ + public function getUploadMineType(): ?string + { + return $this->uploadMimeType; + } +} diff --git a/vendor/workerman/webman-framework/src/Install.php b/vendor/workerman/webman-framework/src/Install.php new file mode 100644 index 0000000..e6fe1ee --- /dev/null +++ b/vendor/workerman/webman-framework/src/Install.php @@ -0,0 +1,59 @@ +<?php + +namespace Webman; + +class Install +{ + const WEBMAN_PLUGIN = true; + + /** + * @var array + */ + protected static $pathRelation = [ + 'start.php' => 'start.php', + 'windows.php' => 'windows.php', + ]; + + /** + * Install + * @return void + */ + public static function install() + { + static::installByRelation(); + } + + /** + * Uninstall + * @return void + */ + public static function uninstall() + { + + } + + /** + * InstallByRelation + * @return void + */ + public static function installByRelation() + { + foreach (static::$pathRelation as $source => $dest) { + $parentDir = base_path(dirname($dest)); + if (!is_dir($parentDir)) { + mkdir($parentDir, 0777, true); + } + $sourceFile = __DIR__ . "/$source"; + copy_dir($sourceFile, base_path($dest), true); + echo "Create $dest\r\n"; + if (is_file($sourceFile)) { + @unlink($sourceFile); + } + } + if (is_file($file = base_path('support/helpers.php'))) { + file_put_contents($file, "<?php\n// This file is generated by Webman, please don't modify it.\n"); + echo "Clear helpers.php\r\n"; + } + } + +} diff --git a/vendor/workerman/webman-framework/src/Middleware.php b/vendor/workerman/webman-framework/src/Middleware.php new file mode 100644 index 0000000..3a54c23 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Middleware.php @@ -0,0 +1,162 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + + +use Closure; +use ReflectionAttribute; +use support\annotation\Middleware as MiddlewareAttribute; +use Webman\Route\Route; +use ReflectionClass; +use ReflectionMethod; +use RuntimeException; +use function array_merge; +use function array_reverse; +use function is_array; +use function method_exists; + +class Middleware +{ + + /** + * @var array + */ + protected static $instances = []; + + /** + * @var array Cache for controller middleware resolved via reflection/attributes. + */ + protected static $controllerMiddlewareCache = []; + + /** + * @param mixed $allMiddlewares + * @param string $plugin + * @return void + */ + public static function load($allMiddlewares, string $plugin = '') + { + if (!is_array($allMiddlewares)) { + return; + } + foreach ($allMiddlewares as $appName => $middlewares) { + if (!is_array($middlewares)) { + throw new RuntimeException('Bad middleware config'); + } + $pluginKey = $plugin; + $appKey = $appName; + if ($appKey === '@') { + $pluginKey = ''; + } elseif (strpos($appKey, 'plugin.') !== false) { + $explode = explode('.', $appKey, 4); + $pluginKey = $explode[1]; + $appKey = $explode[2] ?? ''; + } + foreach ($middlewares as $className) { + if (method_exists($className, 'process')) { + static::$instances[$pluginKey][$appKey][] = [$className, 'process']; + } else { + // @todo Log + echo "middleware $className::process not exsits\n"; + } + } + } + } + + /** + * @param string $plugin + * @param string $appName + * @param string|array|Closure $controller + * @param Route|null $route + * @param bool $withGlobalMiddleware + * @return array + */ + public static function getMiddleware(string $plugin, string $appName, string|array|Closure $controller, Route|null $route, bool $withGlobalMiddleware = true): array + { + $isController = is_array($controller) && is_string($controller[0]); + $globalMiddleware = $withGlobalMiddleware ? static::$instances['']['@'] ?? [] : []; + $appGlobalMiddleware = $withGlobalMiddleware && isset(static::$instances[$plugin]['']) ? static::$instances[$plugin][''] : []; + $middlewares = $routeMiddlewares = []; + // Route middleware + if ($route) { + foreach (array_reverse($route->getMiddleware()) as $className) { + $routeMiddlewares[] = [$className, 'process']; + } + } + if ($isController && $controller[0] && class_exists($controller[0])) { + $cacheKey = $controller[0] . '::' . $controller[1]; + if (isset(static::$controllerMiddlewareCache[$cacheKey])) { + $cached = static::$controllerMiddlewareCache[$cacheKey]; + $middlewares = array_merge($cached['before_route'], $routeMiddlewares, $cached['after_route']); + } else { + $beforeRoute = []; + $afterRoute = []; + // Controller middleware annotation + $reflectionClass = new ReflectionClass($controller[0]); + static::prepareAttributeMiddlewares($beforeRoute, $reflectionClass); + // Controller middleware property + if ($reflectionClass->hasProperty('middleware')) { + $defaultProperties = $reflectionClass->getDefaultProperties(); + $middlewaresClasses = $defaultProperties['middleware']; + foreach ((array)$middlewaresClasses as $className) { + $beforeRoute[] = [$className, 'process']; + } + } + // Method middleware annotation (route must be between controller and method) + if ($reflectionClass->hasMethod($controller[1])) { + static::prepareAttributeMiddlewares($afterRoute, $reflectionClass->getMethod($controller[1])); + } + $middlewares = array_merge($beforeRoute, $routeMiddlewares, $afterRoute); + static::$controllerMiddlewareCache[$cacheKey] = ['before_route' => $beforeRoute, 'after_route' => $afterRoute]; + if (count(static::$controllerMiddlewareCache) > 1024) { + unset(static::$controllerMiddlewareCache[key(static::$controllerMiddlewareCache)]); + } + } + } else { + // Route middleware + $middlewares = array_merge($middlewares, $routeMiddlewares); + } + if ($appName === '') { + return array_reverse(array_merge($globalMiddleware, $appGlobalMiddleware, $middlewares)); + } + $appMiddleware = static::$instances[$plugin][$appName] ?? []; + return array_reverse(array_merge($globalMiddleware, $appGlobalMiddleware, $appMiddleware, $middlewares)); + } + + /** + * @param array $middlewares + * @param ReflectionClass|ReflectionMethod $reflection + * @return void + */ + protected static function prepareAttributeMiddlewares(array &$middlewares, ReflectionClass|ReflectionMethod $reflection): void + { + if ($reflection instanceof ReflectionClass && $parent_ref = $reflection->getParentClass()) { + static::prepareAttributeMiddlewares($middlewares, $parent_ref); + } + $middlewareAttributes = $reflection->getAttributes(MiddlewareAttribute::class, ReflectionAttribute::IS_INSTANCEOF); + foreach ($middlewareAttributes as $middlewareAttribute) { + $middlewareAttributeInstance = $middlewareAttribute->newInstance(); + $middlewares = array_merge($middlewares, $middlewareAttributeInstance->getMiddlewares()); + } + } + + /** + * @return void + * @deprecated + */ + public static function container($_) + { + + } +} diff --git a/vendor/workerman/webman-framework/src/MiddlewareInterface.php b/vendor/workerman/webman-framework/src/MiddlewareInterface.php new file mode 100644 index 0000000..47c6d51 --- /dev/null +++ b/vendor/workerman/webman-framework/src/MiddlewareInterface.php @@ -0,0 +1,30 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + +use Webman\Http\Request; +use Webman\Http\Response; + +interface MiddlewareInterface +{ + /** + * Process an incoming server request. + * + * Processes an incoming server request in order to produce a response. + * If unable to produce the response itself, it may delegate to the provided + * request handler to do so. + */ + public function process(Request $request, callable $handler): Response; +} diff --git a/vendor/workerman/webman-framework/src/Route.php b/vendor/workerman/webman-framework/src/Route.php new file mode 100644 index 0000000..71913a1 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Route.php @@ -0,0 +1,858 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + +use FastRoute\Dispatcher\GroupCountBased; +use FastRoute\RouteCollector; +use FilesystemIterator; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; +use ReflectionAttribute; +use ReflectionClass; +use ReflectionException; +use ReflectionMethod; +use RuntimeException; +use support\annotation\Middleware as MiddlewareAttribute; +use support\annotation\route\DisableDefaultRoute; +use support\annotation\route\Route as RouteAttribute; +use support\annotation\route\RouteGroup as RouteGroupAttribute; +use Webman\Finder\FileInfo; +use Webman\Finder\ControllerFinder; +use Webman\Route\Route as RouteObject; +use function array_diff; +use function array_values; +use function class_exists; +use function explode; +use function FastRoute\simpleDispatcher; +use function in_array; +use function is_array; +use function is_callable; +use function is_file; +use function is_scalar; +use function is_string; +use function json_encode; +use function method_exists; +use function strpos; + +/** + * Class Route + * @package Webman + */ +class Route +{ + /** + * @var Route + */ + protected static $instance = null; + + /** + * @var GroupCountBased + */ + protected static $dispatcher = null; + + /** + * @var RouteCollector + */ + protected static $collector = null; + + /** + * @var RouteObject[] + */ + protected static $fallbackRoutes = []; + + /** + * @var array + */ + protected static $fallback = []; + + /** + * @var array + */ + protected static $nameList = []; + + /** + * @var string + */ + protected static $groupPrefix = ''; + + /** + * @var bool + */ + protected static $disabledDefaultRoutes = []; + + /** + * @var array + */ + protected static $disabledDefaultRouteControllers = []; + + /** + * @var array + */ + protected static $disabledDefaultRouteActions = []; + + /** + * @var RouteObject[] + */ + protected static $allRoutes = []; + + /** + * Index for conflict detection: ["METHOD path" => "callback string"] + * @var array<string, string> + */ + protected static array $methodPathIndex = []; + + /** + * @var string|null + */ + protected static ?string $registeringSource = null; + + /** + * @var RouteObject[] + */ + protected $routes = []; + + /** + * @var Route[] + */ + protected $children = []; + + /** + * Add GET route. + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function get(string $path, $callback): RouteObject + { + return static::addRoute('GET', $path, $callback); + } + + /** + * Add POST route. + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function post(string $path, $callback): RouteObject + { + return static::addRoute('POST', $path, $callback); + } + + /** + * Add PUT route. + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function put(string $path, $callback): RouteObject + { + return static::addRoute('PUT', $path, $callback); + } + + /** + * Add PATCH route. + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function patch(string $path, $callback): RouteObject + { + return static::addRoute('PATCH', $path, $callback); + } + + /** + * Add DELETE route. + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function delete(string $path, $callback): RouteObject + { + return static::addRoute('DELETE', $path, $callback); + } + + /** + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function head(string $path, $callback): RouteObject + { + return static::addRoute('HEAD', $path, $callback); + } + + /** + * Add HEAD route. + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function options(string $path, $callback): RouteObject + { + return static::addRoute('OPTIONS', $path, $callback); + } + + /** + * Add OPTIONS route. + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function any(string $path, $callback): RouteObject + { + return static::addRoute(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'], $path, $callback); + } + + /** + * Add route. + * @param $method + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + public static function add($method, string $path, $callback): RouteObject + { + return static::addRoute($method, $path, $callback); + } + + /** + * Add group. + * @param string|callable $path + * @param callable|null $callback + * @return static + */ + public static function group($path, ?callable $callback = null): Route + { + if ($callback === null) { + $callback = $path; + $path = ''; + } + $previousGroupPrefix = static::$groupPrefix; + static::$groupPrefix = $previousGroupPrefix . $path; + $previousInstance = static::$instance; + $instance = static::$instance = new static; + static::$collector->addGroup($path, $callback); + static::$groupPrefix = $previousGroupPrefix; + static::$instance = $previousInstance; + if ($previousInstance) { + $previousInstance->addChild($instance); + } + return $instance; + } + + /** + * Add resource. + * @param string $name + * @param string $controller + * @param array $options + * @return void + */ + public static function resource(string $name, string $controller, array $options = []) + { + $name = trim($name, '/'); + if (is_array($options) && !empty($options)) { + $diffOptions = array_diff($options, ['index', 'create', 'store', 'update', 'show', 'edit', 'destroy', 'recovery']); + if (!empty($diffOptions)) { + foreach ($diffOptions as $action) { + static::any("/$name/{$action}[/{id}]", [$controller, $action])->name("$name.{$action}"); + } + } + // 注册路由 由于顺序不同会导致路由无效 因此不适用循环注册 + if (in_array('index', $options)) static::get("/$name", [$controller, 'index'])->name("$name.index"); + if (in_array('create', $options)) static::get("/$name/create", [$controller, 'create'])->name("$name.create"); + if (in_array('store', $options)) static::post("/$name", [$controller, 'store'])->name("$name.store"); + if (in_array('update', $options)) static::put("/$name/{id}", [$controller, 'update'])->name("$name.update"); + if (in_array('patch', $options)) static::patch("/$name/{id}", [$controller, 'patch'])->name("$name.patch"); + if (in_array('show', $options)) static::get("/$name/{id}", [$controller, 'show'])->name("$name.show"); + if (in_array('edit', $options)) static::get("/$name/{id}/edit", [$controller, 'edit'])->name("$name.edit"); + if (in_array('destroy', $options)) static::delete("/$name/{id}", [$controller, 'destroy'])->name("$name.destroy"); + if (in_array('recovery', $options)) static::put("/$name/{id}/recovery", [$controller, 'recovery'])->name("$name.recovery"); + } else { + //为空时自动注册所有常用路由 + if (method_exists($controller, 'index')) static::get("/$name", [$controller, 'index'])->name("$name.index"); + if (method_exists($controller, 'create')) static::get("/$name/create", [$controller, 'create'])->name("$name.create"); + if (method_exists($controller, 'store')) static::post("/$name", [$controller, 'store'])->name("$name.store"); + if (method_exists($controller, 'update')) static::put("/$name/{id}", [$controller, 'update'])->name("$name.update"); + if (method_exists($controller, 'patch')) static::patch("/$name/{id}", [$controller, 'patch'])->name("$name.patch"); + if (method_exists($controller, 'show')) static::get("/$name/{id}", [$controller, 'show'])->name("$name.show"); + if (method_exists($controller, 'edit')) static::get("/$name/{id}/edit", [$controller, 'edit'])->name("$name.edit"); + if (method_exists($controller, 'destroy')) static::delete("/$name/{id}", [$controller, 'destroy'])->name("$name.destroy"); + if (method_exists($controller, 'recovery')) static::put("/$name/{id}/recovery", [$controller, 'recovery'])->name("$name.recovery"); + } + } + + /** + * Get routes. + * @return RouteObject[] + */ + public static function getRoutes(): array + { + return static::$allRoutes; + } + + /** + * Disable default route. + * @param array|string $plugin + * @param string|null $app + * @return bool + */ + public static function disableDefaultRoute(array|string $plugin = '', ?string $app = null): bool + { + // Is [controller action] + if (is_array($plugin)) { + $controllerAction = $plugin; + if (!isset($controllerAction[0]) || !is_string($controllerAction[0]) || + !isset($controllerAction[1]) || !is_string($controllerAction[1])) { + return false; + } + $controller = $controllerAction[0]; + $action = $controllerAction[1]; + static::$disabledDefaultRouteActions[$controller][$action] = $action; + return true; + } + // Is plugin + if (is_string($plugin) && (preg_match('/^[a-zA-Z0-9_]+$/', $plugin) || $plugin === '')) { + if (!isset(static::$disabledDefaultRoutes[$plugin])) { + static::$disabledDefaultRoutes[$plugin] = []; + } + $app = $app ?? '*'; + static::$disabledDefaultRoutes[$plugin][$app] = $app; + return true; + } + // Is controller + if (is_string($plugin) && class_exists($plugin)) { + static::$disabledDefaultRouteControllers[$plugin] = $plugin; + return true; + } + return false; + } + + /** + * Is default route disabled. + * @param array|string $plugin + * @param string|null $app + * @return bool + */ + public static function isDefaultRouteDisabled(array|string $plugin = '', ?string $app = null): bool + { + // Is [controller action] + if (is_array($plugin)) { + if (!isset($plugin[0]) || !is_string($plugin[0]) || + !isset($plugin[1]) || !is_string($plugin[1])) { + return false; + } + return isset(static::$disabledDefaultRouteActions[$plugin[0]][$plugin[1]]) || static::isDefaultRouteDisabledByAnnotation($plugin[0], $plugin[1]); + } + // Is plugin + if (is_string($plugin) && (preg_match('/^[a-zA-Z0-9_]+$/', $plugin) || $plugin === '')) { + $app = $app ?? '*'; + return isset(static::$disabledDefaultRoutes[$plugin]['*']) || isset(static::$disabledDefaultRoutes[$plugin][$app]); + } + // Is controller + if (is_string($plugin) && class_exists($plugin)) { + return isset(static::$disabledDefaultRouteControllers[$plugin]); + } + return false; + } + + /** + * Is default route disabled by annotation. + * @param string $controller + * @param string|null $action + * @return bool + */ + protected static function isDefaultRouteDisabledByAnnotation(string $controller, ?string $action = null): bool + { + if (class_exists($controller)) { + $reflectionClass = new ReflectionClass($controller); + if (static::isRefHasDefaultRouteDisabledAnnotation($reflectionClass)) { + return true; + } + if ($action && $reflectionClass->hasMethod($action)) { + $reflectionMethod = $reflectionClass->getMethod($action); + if ($reflectionMethod->getAttributes(DisableDefaultRoute::class, ReflectionAttribute::IS_INSTANCEOF)) { + return true; + } + } + } + return false; + } + + /** + * Is reflection class has default route disabled annotation. + * @param ReflectionClass $reflectionClass + * @return bool + */ + protected static function isRefHasDefaultRouteDisabledAnnotation(ReflectionClass $reflectionClass): bool + { + $has = $reflectionClass->getAttributes(DisableDefaultRoute::class, ReflectionAttribute::IS_INSTANCEOF); + if ($has) { + return true; + } + if (method_exists($reflectionClass, 'getParentClass')) { + $parent = $reflectionClass->getParentClass(); + if ($parent) { + return static::isRefHasDefaultRouteDisabledAnnotation($parent); + } + } + return false; + } + + /** + * Add middleware. + * @param $middleware + * @return $this + */ + public function middleware($middleware): Route + { + foreach ($this->routes as $route) { + $route->middleware($middleware); + } + foreach ($this->getChildren() as $child) { + $child->middleware($middleware); + } + return $this; + } + + /** + * Collect route. + * @param RouteObject $route + */ + public function collect(RouteObject $route) + { + $this->routes[] = $route; + } + + /** + * Set by name. + * @param string $name + * @param RouteObject $instance + */ + public static function setByName(string $name, RouteObject $instance) + { + static::$nameList[$name] = $instance; + } + + /** + * Get by name. + * @param string $name + * @return null|RouteObject + */ + public static function getByName(string $name): ?RouteObject + { + return static::$nameList[$name] ?? null; + } + + /** + * Add child. + * @param Route $route + * @return void + */ + public function addChild(Route $route) + { + $this->children[] = $route; + } + + /** + * Get children. + * @return Route[] + */ + public function getChildren() + { + return $this->children; + } + + /** + * Dispatch. + * @param string $method + * @param string $path + * @return array + */ + public static function dispatch(string $method, string $path): array + { + return static::$dispatcher->dispatch($method, $path); + } + + /** + * Convert to callable. + * @param string $path + * @param callable|mixed $callback + * @return callable|false|string[] + */ + public static function convertToCallable(string $path, $callback) + { + if (is_string($callback) && strpos($callback, '@')) { + $callback = explode('@', $callback, 2); + } + + if (!is_array($callback)) { + if (!is_callable($callback)) { + $callStr = is_scalar($callback) ? $callback : 'Closure'; + echo "Route $path $callStr is not callable\n"; + return false; + } + } else { + $callback = array_values($callback); + if (!isset($callback[1]) || !class_exists($callback[0]) || !method_exists($callback[0], $callback[1])) { + echo "Route $path " . json_encode($callback) . " is not callable\n"; + return false; + } + } + + return $callback; + } + + /** + * Add route. + * @param array|string $methods + * @param string $path + * @param callable|mixed $callback + * @return RouteObject + */ + protected static function addRoute($methods, string $path, $callback): RouteObject + { + $fullPath = static::$groupPrefix . $path; + foreach ((array)$methods as $method) { + $method = strtoupper((string)$method); + $key = $method . ' ' . $fullPath; + if (isset(static::$methodPathIndex[$key])) { + $old = static::$methodPathIndex[$key]; + $new = static::callbackToString($callback); + $source = static::$registeringSource ? (' from ' . static::$registeringSource) : ''; + throw new RuntimeException("Route conflict: [$key] already registered as $old, cannot register $new$source"); + } + static::$methodPathIndex[$key] = static::callbackToString($callback); + } + + $route = new RouteObject($methods, static::$groupPrefix . $path, $callback); + static::$allRoutes[] = $route; + + if ($callback = static::convertToCallable($path, $callback)) { + static::$collector->addRoute($methods, $path, ['callback' => $callback, 'route' => $route]); + } + if (static::$instance) { + static::$instance->collect($route); + } + return $route; + } + + /** + * Load. + * @param mixed $paths + * @return void + */ + public static function load($paths) + { + if (!is_array($paths)) { + return; + } + static::$dispatcher = null; + static::$collector = null; + static::$fallbackRoutes = []; + static::$fallback = []; + static::$nameList = []; + static::$disabledDefaultRoutes = []; + static::$disabledDefaultRouteControllers = []; + static::$disabledDefaultRouteActions = []; + static::$allRoutes = []; + static::$methodPathIndex = []; + static::$registeringSource = null; + + static::$dispatcher = simpleDispatcher(function (RouteCollector $route) use ($paths) { + static::setCollector($route); + foreach ($paths as $configPath) { + $routeConfigFile = $configPath . '/route.php'; + if (is_file($routeConfigFile)) { + require_once $routeConfigFile; + } + if (!is_dir($pluginConfigPath = $configPath . '/plugin')) { + continue; + } + $dirIterator = new RecursiveDirectoryIterator($pluginConfigPath, FilesystemIterator::FOLLOW_SYMLINKS); + $iterator = new RecursiveIteratorIterator($dirIterator); + foreach ($iterator as $file) { + if ($file->getBaseName('.php') !== 'route') { + continue; + } + $filePath = $file->getPathname(); + $appConfigFile = pathinfo($filePath, PATHINFO_DIRNAME) . '/app.php'; + if (!is_file($appConfigFile)) { + continue; + } + $appConfig = include $appConfigFile; + if (empty($appConfig['enable'])) { + continue; + } + require_once $filePath; + } + } + static::loadAnnotationRoutes(); + }); + } + + /** + * SetCollector. + * @param RouteCollector $route + * @return void + */ + public static function setCollector(RouteCollector $route) + { + static::$collector = $route; + } + + /** + * Fallback. + * @param callable|mixed $callback + * @param string $plugin + * @return RouteObject + */ + public static function fallback(callable $callback, string $plugin = '') + { + $route = new RouteObject([], '', $callback); + static::$fallbackRoutes[$plugin] = $route; + return $route; + } + + /** + * GetFallBack. + * @param string $plugin + * @param int $status + * @return callable|null + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws ReflectionException + */ + public static function getFallback(string $plugin = '', int $status = 404) + { + if (!isset(static::$fallback[$plugin])) { + $callback = null; + $route = static::$fallbackRoutes[$plugin] ?? null; + static::$fallback[$plugin] = $route ? App::getCallback($plugin, 'NOT_FOUND', $route->getCallback(), ['status' => $status], false, $route) : null; + } + return static::$fallback[$plugin]; + } + + /** + * Load annotation routes. + * @return void + */ + protected static function loadAnnotationRoutes(): void + { + $controllerFiles = ControllerFinder::files('*', false); + if (!$controllerFiles) { + return; + } + $routes = static::buildAnnotationRouteDefinitions($controllerFiles); + static::registerAnnotationRouteDefinitions($routes); + + } + + /** + * Build annotation route definitions. + * @param FileInfo[] $controllerFiles + * @return array<int,array{methods: string[], path: string, callback: array{0:string,1:string}, name: ?string, middlewares: array}> + */ + protected static function buildAnnotationRouteDefinitions(array $controllerFiles): array + { + $definitions = []; + + foreach ($controllerFiles as $foundFile) { + $meta = $foundFile->meta(); + $controllerClass = $meta['class'] ?? null; + if (!$controllerClass) { + continue; + } + + $file = $foundFile->getPathname(); + if (!class_exists($controllerClass)) { + require_once $file; + } + if (!class_exists($controllerClass)) { + continue; + } + + $ref = new ReflectionClass($controllerClass); + if ($ref->isAbstract() || $ref->isInterface()) { + continue; + } + + $prefix = ''; + $groupAttrs = $ref->getAttributes(RouteGroupAttribute::class, ReflectionAttribute::IS_INSTANCEOF); + if ($groupAttrs) { + /** @var RouteGroupAttribute $group */ + $group = $groupAttrs[0]->newInstance(); + $prefix = static::normalizeRoutePrefix($group->prefix); + } + + foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + if ($method->isConstructor() || $method->isDestructor()) { + continue; + } + if ($method->getDeclaringClass()->getName() !== $controllerClass) { + continue; + } + + $routeAttrs = $method->getAttributes(RouteAttribute::class, ReflectionAttribute::IS_INSTANCEOF); + if (!$routeAttrs) { + continue; + } + + foreach ($routeAttrs as $routeAttr) { + /** @var RouteAttribute $route */ + $route = $routeAttr->newInstance(); + if ($route->path === null) { + // Null path means "method restriction only" for default route, do not register. + continue; + } + $source = $controllerClass . '::' . $method->getName(); + $path = static::normalizeRoutePath($route->path, $source); + $fullPath = $prefix . $path; + if ($fullPath === '') { + throw new RuntimeException("Annotation route resolves to empty path: #[Get('')] requires a #[RouteGroup] prefix ($source)"); + } + + $methods = []; + foreach ($route->methods as $m) { + $methods[] = strtoupper((string)$m); + } + + $definitions[] = [ + 'methods' => $methods, + 'path' => $fullPath, + 'callback' => [$controllerClass, $method->getName()], + 'name' => $route->name, + ]; + } + } + } + + return $definitions; + } + + /** + * Collect middlewares from attributes. + * @param array<ReflectionAttribute> $attributes + * @return array + */ + protected static function collectMiddlewaresFromAttributes(array $attributes): array + { + $middlewares = []; + foreach ($attributes as $attribute) { + /** @var MiddlewareAttribute $instance */ + $instance = $attribute->newInstance(); + foreach ($instance->getMiddlewares() as $middleware) { + if (is_string($middleware)) { + $middlewares[] = $middleware; + continue; + } + if (is_array($middleware) && isset($middleware[0]) && is_string($middleware[0])) { + $middlewares[] = $middleware[0]; + } + } + } + return $middlewares; + } + + /** + * Register annotation route definitions. + * @param array $definitions + * @return void + */ + protected static function registerAnnotationRouteDefinitions(array $definitions): void + { + foreach ($definitions as $definition) { + static::$registeringSource = 'annotation ' . $definition['callback'][0] . '::' . $definition['callback'][1]; + $route = static::add($definition['methods'], $definition['path'], $definition['callback']); + if (!empty($definition['name'])) { + $route->name($definition['name']); + } + if (!empty($definition['middlewares'])) { + $route->middleware($definition['middlewares']); + } + static::$registeringSource = null; + } + } + + /** + * Normalize route prefix. + * @param string $prefix + * @return string + */ + protected static function normalizeRoutePrefix(string $prefix): string + { + $prefix = trim($prefix); + if ($prefix === '') { + return ''; + } + if ($prefix[0] !== '/') { + $prefix = '/' . $prefix; + } + return rtrim($prefix, '/'); + } + + /** + * Normalize route path. + * Empty string is allowed (means "use group prefix only"). + * Non-empty path must start with '/'. + * @param string $path + * @param string $source + * @return string + */ + protected static function normalizeRoutePath(string $path, string $source): string + { + $path = trim($path); + if ($path === '') { + return ''; + } + if ($path[0] !== '/') { + throw new RuntimeException("Annotation route path must start with '/': '$path' ($source)"); + } + return $path; + } + + /** + * Callback to string. + * @param mixed $callback + * @return string + */ + protected static function callbackToString(mixed $callback): string + { + if (is_array($callback)) { + $callback = array_values($callback); + $class = $callback[0] ?? ''; + $method = $callback[1] ?? ''; + return $class && $method ? ($class . '::' . $method) : json_encode($callback); + } + if ($callback instanceof \Closure) { + return 'Closure'; + } + if (is_string($callback)) { + return $callback; + } + return get_debug_type($callback); + } + + /** + * @return void + * @deprecated + */ + public static function container() + { + + } + +} diff --git a/vendor/workerman/webman-framework/src/Route/Route.php b/vendor/workerman/webman-framework/src/Route/Route.php new file mode 100644 index 0000000..f95aed7 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Route/Route.php @@ -0,0 +1,199 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Route; + +use Webman\Route as Router; +use function array_merge; +use function count; +use function preg_replace_callback; +use function str_replace; + +/** + * Class Route + * @package Webman + */ +class Route +{ + /** + * @var string|null + */ + protected $name = null; + + /** + * @var array + */ + protected $methods = []; + + /** + * @var string + */ + protected $path = ''; + + /** + * @var callable + */ + protected $callback = null; + + /** + * @var array + */ + protected $middlewares = []; + + /** + * @var array + */ + protected $params = []; + + /** + * Route constructor. + * @param array $methods + * @param string $path + * @param callable $callback + */ + public function __construct($methods, string $path, $callback) + { + $this->methods = (array)$methods; + $this->path = $path; + $this->callback = $callback; + } + + /** + * Get name. + * @return string|null + */ + public function getName(): ?string + { + return $this->name ?? null; + } + + /** + * Name. + * @param string $name + * @return $this + */ + public function name(string $name): Route + { + $this->name = $name; + Router::setByName($name, $this); + return $this; + } + + /** + * Middleware. + * @param mixed $middleware + * @return $this|array + */ + public function middleware(mixed $middleware = null) + { + if ($middleware === null) { + return $this->middlewares; + } + $this->middlewares = array_merge($this->middlewares, is_array($middleware) ? array_reverse($middleware) : [$middleware]); + return $this; + } + + /** + * GetPath. + * @return string + */ + public function getPath(): string + { + return $this->path; + } + + /** + * GetMethods. + * @return array + */ + public function getMethods(): array + { + return $this->methods; + } + + /** + * GetCallback. + * @return callable|null + */ + public function getCallback() + { + return $this->callback; + } + + /** + * GetMiddleware. + * @return array + */ + public function getMiddleware(): array + { + return $this->middlewares; + } + + /** + * Param. + * @param string|null $name + * @param mixed $default + * @return mixed + */ + public function param(?string $name = null, mixed $default = null) + { + if ($name === null) { + return $this->params; + } + return $this->params[$name] ?? $default; + } + + /** + * SetParams. + * @param array $params + * @return $this + */ + public function setParams(array $params): Route + { + $this->params = array_merge($this->params, $params); + return $this; + } + + /** + * Url. + * @param array $parameters + * @return string + */ + public function url(array $parameters = []): string + { + if (empty($parameters)) { + return $this->path; + } + $path = str_replace(['[', ']'], '', $this->path); + $path = preg_replace_callback('/\{(.*?)(?:\:[^\}]*?)*?\}/', function ($matches) use (&$parameters) { + if (!$parameters) { + return $matches[0]; + } + if (isset($parameters[$matches[1]])) { + $value = $parameters[$matches[1]]; + unset($parameters[$matches[1]]); + return $value; + } + $key = key($parameters); + if (is_int($key)) { + $value = $parameters[$key]; + unset($parameters[$key]); + return $value; + } + return $matches[0]; + }, $path); + return count($parameters) > 0 ? $path . '?' . http_build_query($parameters) : $path; + } + +} diff --git a/vendor/workerman/webman-framework/src/Session/FileSessionHandler.php b/vendor/workerman/webman-framework/src/Session/FileSessionHandler.php new file mode 100644 index 0000000..10fda70 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Session/FileSessionHandler.php @@ -0,0 +1,26 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Session; + +use Workerman\Protocols\Http\Session\FileSessionHandler as FileHandler; + +/** + * Class FileSessionHandler + * @package Webman + */ +class FileSessionHandler extends FileHandler +{ + +} diff --git a/vendor/workerman/webman-framework/src/Session/RedisClusterSessionHandler.php b/vendor/workerman/webman-framework/src/Session/RedisClusterSessionHandler.php new file mode 100644 index 0000000..c00efae --- /dev/null +++ b/vendor/workerman/webman-framework/src/Session/RedisClusterSessionHandler.php @@ -0,0 +1,22 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Session; + +use Workerman\Protocols\Http\Session\RedisClusterSessionHandler as RedisClusterHandler; + +class RedisClusterSessionHandler extends RedisClusterHandler +{ + +} diff --git a/vendor/workerman/webman-framework/src/Session/RedisSessionHandler.php b/vendor/workerman/webman-framework/src/Session/RedisSessionHandler.php new file mode 100644 index 0000000..c124cbd --- /dev/null +++ b/vendor/workerman/webman-framework/src/Session/RedisSessionHandler.php @@ -0,0 +1,26 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman\Session; + +use Workerman\Protocols\Http\Session\RedisSessionHandler as RedisHandler; + +/** + * Class FileSessionHandler + * @package Webman + */ +class RedisSessionHandler extends RedisHandler +{ + +} diff --git a/vendor/workerman/webman-framework/src/Util.php b/vendor/workerman/webman-framework/src/Util.php new file mode 100644 index 0000000..2084605 --- /dev/null +++ b/vendor/workerman/webman-framework/src/Util.php @@ -0,0 +1,44 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + +use function array_diff; +use function array_map; +use function scandir; + +/** + * Class Util + * @package Webman + */ +class Util +{ + /** + * ScanDir. + * @param string $basePath + * @param bool $withBasePath + * @return array + */ + public static function scanDir(string $basePath, bool $withBasePath = true): array + { + if (!is_dir($basePath)) { + return []; + } + $paths = array_diff(scandir($basePath), array('.', '..')) ?: []; + return $withBasePath ? array_map(static function ($path) use ($basePath) { + return $basePath . DIRECTORY_SEPARATOR . $path; + }, $paths) : $paths; + } + +} diff --git a/vendor/workerman/webman-framework/src/View.php b/vendor/workerman/webman-framework/src/View.php new file mode 100644 index 0000000..7539621 --- /dev/null +++ b/vendor/workerman/webman-framework/src/View.php @@ -0,0 +1,27 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace Webman; + +interface View +{ + /** + * Render. + * @param string $template + * @param array $vars + * @param string|null $app + * @return string + */ + public static function render(string $template, array $vars, ?string $app = null): string; +} diff --git a/vendor/workerman/webman-framework/src/start.php b/vendor/workerman/webman-framework/src/start.php new file mode 100755 index 0000000..41ad7ef --- /dev/null +++ b/vendor/workerman/webman-framework/src/start.php @@ -0,0 +1,5 @@ +#!/usr/bin/env php +<?php +chdir(__DIR__); +require_once __DIR__ . '/vendor/autoload.php'; +support\App::run(); diff --git a/vendor/workerman/webman-framework/src/support/App.php b/vendor/workerman/webman-framework/src/support/App.php new file mode 100644 index 0000000..6afc6ad --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/App.php @@ -0,0 +1,167 @@ +<?php + +namespace support; + +use Dotenv\Dotenv; +use RuntimeException; +use Throwable; +use Webman\Config; +use Webman\Util; +use Workerman\Connection\TcpConnection; +use Workerman\Worker; +use function base_path; +use function call_user_func; +use function is_dir; +use function opcache_get_status; +use function opcache_invalidate; +use const DIRECTORY_SEPARATOR; + +class App +{ + /** + * Run. + * @return void + * @throws Throwable + */ + public static function run() + { + ini_set('display_errors', 'on'); + error_reporting(E_ALL); + + if (class_exists(Dotenv::class) && file_exists(run_path('.env'))) { + if (method_exists(Dotenv::class, 'createUnsafeImmutable')) { + Dotenv::createUnsafeImmutable(run_path())->load(); + } else { + Dotenv::createMutable(run_path())->load(); + } + } + + if (!$appConfigFile = config_path('app.php')) { + throw new RuntimeException('Config file not found: app.php'); + } + $appConfig = require $appConfigFile; + if ($timezone = $appConfig['default_timezone'] ?? '') { + date_default_timezone_set($timezone); + } + + static::loadAllConfig(['route', 'container']); + + if (!is_phar() && DIRECTORY_SEPARATOR === '\\' && empty(config('server.listen'))) { + echo "Please run 'php windows.php' on windows system." . PHP_EOL; + exit; + } + + $errorReporting = config('app.error_reporting'); + if (isset($errorReporting)) { + error_reporting($errorReporting); + } + + $runtimeLogsPath = runtime_path() . DIRECTORY_SEPARATOR . 'logs'; + if (!file_exists($runtimeLogsPath) || !is_dir($runtimeLogsPath)) { + if (!mkdir($runtimeLogsPath, 0777, true)) { + throw new RuntimeException("Failed to create runtime logs directory. Please check the permission."); + } + } + + $runtimeViewsPath = runtime_path() . DIRECTORY_SEPARATOR . 'views'; + if (!file_exists($runtimeViewsPath) || !is_dir($runtimeViewsPath)) { + if (!mkdir($runtimeViewsPath, 0777, true)) { + throw new RuntimeException("Failed to create runtime views directory. Please check the permission."); + } + } + + Worker::$onMasterReload = function () { + if (function_exists('opcache_get_status')) { + if ($status = opcache_get_status()) { + if (isset($status['scripts']) && $scripts = $status['scripts']) { + foreach (array_keys($scripts) as $file) { + opcache_invalidate($file, true); + } + } + } + } + }; + + $config = config('server'); + Worker::$pidFile = $config['pid_file']; + Worker::$stdoutFile = $config['stdout_file']; + Worker::$logFile = $config['log_file']; + Worker::$eventLoopClass = $config['event_loop'] ?? ''; + TcpConnection::$defaultMaxPackageSize = $config['max_package_size'] ?? 10 * 1024 * 1024; + if (property_exists(Worker::class, 'statusFile')) { + Worker::$statusFile = $config['status_file'] ?? ''; + } + if (property_exists(Worker::class, 'stopTimeout')) { + Worker::$stopTimeout = $config['stop_timeout'] ?? 2; + } + + if ($config['listen'] ?? false) { + $worker = new Worker($config['listen'], $config['context'] ?? []); + $propertyMap = [ + 'name', + 'count', + 'user', + 'group', + 'reusePort', + 'transport', + 'protocol' + ]; + foreach ($propertyMap as $property) { + if (isset($config[$property])) { + $worker->$property = $config[$property]; + } + } + + $worker->onWorkerStart = function ($worker) { + require_once base_path() . '/support/bootstrap.php'; + $app = new \Webman\App(config('app.request_class', Request::class), Log::channel('default'), app_path(), public_path()); + $worker->onMessage = [$app, 'onMessage']; + call_user_func([$app, 'onWorkerStart'], $worker); + }; + } + + $windowsWithoutServerListen = is_phar() && DIRECTORY_SEPARATOR === '\\' && empty($config['listen']); + $process = config('process', []); + if ($windowsWithoutServerListen && $process) { + $processName = isset($process['webman']) ? 'webman' : key($process); + worker_start($processName, $process[$processName]); + } else if (DIRECTORY_SEPARATOR === '/') { + foreach (config('process', []) as $processName => $config) { + worker_start($processName, $config); + } + foreach (config('plugin', []) as $firm => $projects) { + foreach ($projects as $name => $project) { + if (!is_array($project)) { + continue; + } + foreach ($project['process'] ?? [] as $processName => $config) { + worker_start("plugin.$firm.$name.$processName", $config); + } + } + foreach ($projects['process'] ?? [] as $processName => $config) { + worker_start("plugin.$firm.$processName", $config); + } + } + } + + Worker::runAll(); + } + + /** + * LoadAllConfig. + * @param array $excludes + * @return void + */ + public static function loadAllConfig(array $excludes = []) + { + Config::load(config_path(), $excludes); + $directory = base_path() . '/plugin'; + foreach (Util::scanDir($directory, false) as $name) { + $dir = "$directory/$name/config"; + if (is_dir($dir)) { + Config::load($dir, $excludes, "plugin.$name"); + } + } + } + +} diff --git a/vendor/workerman/webman-framework/src/support/Container.php b/vendor/workerman/webman-framework/src/support/Container.php new file mode 100644 index 0000000..7a44734 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/Container.php @@ -0,0 +1,47 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support; + +use Webman\Config; + +/** + * Class Container + * @package support + * @method static mixed get($name) + * @method static mixed make($name, array $parameters) + * @method static bool has($name) + */ +class Container +{ + /** + * Instance + * @param string $plugin + * @return array|mixed|void|null + */ + public static function instance(string $plugin = '') + { + return Config::get($plugin ? "plugin.$plugin.container" : 'container') ?: new \Webman\Container(); + } + + /** + * @param string $name + * @param array $arguments + * @return mixed + */ + public static function __callStatic(string $name, array $arguments) + { + return static::instance()->{$name}(... $arguments); + } +} diff --git a/vendor/workerman/webman-framework/src/support/Context.php b/vendor/workerman/webman-framework/src/support/Context.php new file mode 100644 index 0000000..7a8348b --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/Context.php @@ -0,0 +1,25 @@ +<?php + +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support; + +/** + * Class Context + * @package Webman + */ +class Context extends \Webman\Context +{ + +} diff --git a/vendor/workerman/webman-framework/src/support/Log.php b/vendor/workerman/webman-framework/src/support/Log.php new file mode 100644 index 0000000..b384862 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/Log.php @@ -0,0 +1,143 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Handler\FormattableHandlerInterface; +use Monolog\Handler\HandlerInterface; +use Monolog\Logger; +use function array_values; +use function config; +use function is_array; + +/** + * Class Log + * @package support + * + * @method static void log($level, $message, array $context = []) + * @method static void debug($message, array $context = []) + * @method static void info($message, array $context = []) + * @method static void notice($message, array $context = []) + * @method static void warning($message, array $context = []) + * @method static void error($message, array $context = []) + * @method static void critical($message, array $context = []) + * @method static void alert($message, array $context = []) + * @method static void emergency($message, array $context = []) + */ +class Log +{ + /** + * @var array + */ + protected static $instance = []; + + /** + * Channel. + * @param string $name + * @return Logger + */ + public static function channel(string $name = 'default'): Logger + { + if (!isset(static::$instance[$name])) { + $config = config('log', [])[$name]; + $handlers = self::handlers($config); + $processors = self::processors($config); + $logger = new Logger($name, $handlers, $processors); + if (method_exists($logger, 'useLoggingLoopDetection')) { + $logger->useLoggingLoopDetection(false); + } + static::$instance[$name] = $logger; + } + return static::$instance[$name]; + } + + /** + * Handlers. + * @param array $config + * @return array + */ + protected static function handlers(array $config): array + { + $handlerConfigs = $config['handlers'] ?? [[]]; + $handlers = []; + foreach ($handlerConfigs as $value) { + $class = $value['class'] ?? []; + $constructor = $value['constructor'] ?? []; + + $formatterConfig = $value['formatter'] ?? []; + + $class && $handlers[] = self::handler($class, $constructor, $formatterConfig); + } + + return $handlers; + } + + /** + * Handler. + * @param string $class + * @param array $constructor + * @param array $formatterConfig + * @return HandlerInterface + */ + protected static function handler(string $class, array $constructor, array $formatterConfig): HandlerInterface + { + /** @var HandlerInterface $handler */ + $handler = new $class(... array_values($constructor)); + + if ($handler instanceof FormattableHandlerInterface && $formatterConfig) { + $formatterClass = $formatterConfig['class']; + $formatterConstructor = $formatterConfig['constructor']; + + /** @var FormatterInterface $formatter */ + $formatter = new $formatterClass(... array_values($formatterConstructor)); + + $handler->setFormatter($formatter); + } + + return $handler; + } + + /** + * Processors. + * @param array $config + * @return array + */ + protected static function processors(array $config): array + { + $result = []; + if (!isset($config['processors']) && isset($config['processor'])) { + $config['processors'] = [$config['processor']]; + } + + foreach ($config['processors'] ?? [] as $value) { + if (is_array($value) && isset($value['class'])) { + $value = new $value['class'](... array_values($value['constructor'] ?? [])); + } + $result[] = $value; + } + + return $result; + } + + /** + * @param string $name + * @param array $arguments + * @return mixed + */ + public static function __callStatic(string $name, array $arguments) + { + return static::channel()->{$name}(... $arguments); + } +} diff --git a/vendor/workerman/webman-framework/src/support/PharStream.php b/vendor/workerman/webman-framework/src/support/PharStream.php new file mode 100644 index 0000000..e04e496 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/PharStream.php @@ -0,0 +1,368 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support; + +use Phar; +use RuntimeException; + +/** + * Serializes access to the running phar across forked processes. + * + * The phar extension reads an entry by seeking the archive descriptor and then + * reading from it. That descriptor stays open for the whole process lifetime + * when the archive is compressed (it is a decompressed temp file) or tar/zip + * based (the running stub keeps it referenced), so after fork all workers + * share one file offset and interleaved seek/read pairs return foreign bytes. + * + * Every native phar call is wrapped in an exclusive flock on the archive file. + * The lock covers a single call, never the lifetime of an open stream, so a + * long-lived handle (e.g. a file being sent to a slow client) does not block + * other workers. + * + * The lock alone is not enough. PHP satisfies a forward seek from its read + * buffer and then continues with read() at the kernel offset. After fork that + * offset belongs to whichever worker used the descriptor last, so a read is + * preceded by a seek that PHP cannot satisfy from the buffer. + */ +final class PharStream +{ + private const LOCK_ATTEMPTS = 10; + + /** @var resource|null */ + public $context; + + /** @var resource|null */ + private $stream = null; + + /** @var resource|null */ + private $directory = null; + + private static string $archive = ''; + + /** @var resource|null */ + private static $lock = null; + + private static int $lockPid = 0; + + private static bool $locked = false; + + private static bool $native = false; + + /** + * Only needed where workers are forked. Windows has no fork, and its + * mandatory file locks would make the archive unreadable while locked. + */ + public static function register(): void + { + if (self::$archive !== '' || !function_exists('pcntl_fork')) { + return; + } + $archive = Phar::running(false); + if ($archive === '' || !in_array('phar', stream_get_wrappers(), true)) { + return; + } + stream_wrapper_unregister('phar'); + if (!stream_wrapper_register('phar', self::class)) { + stream_wrapper_restore('phar'); + trigger_error('Unable to register phar stream wrapper', E_USER_WARNING); + return; + } + self::$archive = $archive; + self::checkSwowAsyncIo(); + } + + /** + * Swow's async file IO cannot be switched off at runtime, so a coroutine + * would yield inside flock or fread and let another one enter. + */ + private static function checkSwowAsyncIo(): void + { + if (!extension_loaded('swow') || !filter_var(ini_get('swow.enable'), FILTER_VALIDATE_BOOL)) { + return; + } + if (filter_var(ini_get('swow.async_file'), FILTER_VALIDATE_BOOL) || filter_var(ini_get('swow.async_tty'), FILTER_VALIDATE_BOOL)) { + $config = PHP_SAPI === 'micro' ? 'custom_ini of the webman/console build config' : 'php.ini'; + trigger_error("Swow async IO interleaves phar reads across coroutines, set swow.async_file=0 and swow.async_tty=0 in $config", E_USER_WARNING); + } + } + + /** + * @param callable $operation + * @return mixed + */ + private static function locked(callable $operation): mixed + { + if (self::$locked) { + return $operation(); + } + $hooks = self::suspendFileHooks(); + try { + $lock = self::acquire(); + self::$locked = true; + try { + return $operation(); + } finally { + self::$locked = false; + flock($lock, LOCK_UN); + } + } finally { + self::resumeFileHooks($hooks); + } + } + + /** + * Run a path based operation with the original phar wrapper in place. + * + * The user wrapper is unregistered before the original one is restored: + * restoring over it directly never frees the user wrapper and leaks memory + * on every call. + * + * @param callable $operation + * @return mixed + */ + private static function native(callable $operation): mixed + { + return self::locked(static function () use ($operation) { + if (self::$native) { + return $operation(); + } + stream_wrapper_unregister('phar'); + stream_wrapper_restore('phar'); + self::$native = true; + try { + return $operation(); + } finally { + self::$native = false; + stream_wrapper_unregister('phar'); + stream_wrapper_register('phar', self::class); + } + }); + } + + /** + * flock() locks belong to the open file description, which forked + * processes share, so every process needs its own handle. + * + * PHP closes resources newest first on shutdown, so a phar stream opened + * before this process created its handle is closed after the handle. + * + * @return resource + */ + private static function acquire() + { + $pid = getmypid(); + if (self::$lockPid !== $pid || !is_resource(self::$lock)) { + $lock = fopen(self::$archive, 'rb'); + if ($lock === false) { + throw new RuntimeException('Unable to open ' . self::$archive . ' for locking'); + } + if (is_resource(self::$lock)) { + fclose(self::$lock); + } + self::$lock = $lock; + self::$lockPid = $pid; + } + // A signal handler installed without SA_RESTART interrupts a blocking flock. + for ($attempt = 1; !flock(self::$lock, LOCK_EX); $attempt++) { + if ($attempt === self::LOCK_ATTEMPTS) { + throw new RuntimeException('Unable to lock ' . self::$archive); + } + } + return self::$lock; + } + + /** + * Swoole's file hook makes newly opened plain files yield, and its stdio + * hook swaps the ops of every plain file stream, including the archive + * descriptor and the lock handle. Either one lets another coroutine of + * this process enter the critical section inside flock or fread. + * + * Hooked calls only yield inside a coroutine. Outside one the flags are + * left alone, which also keeps away from the Swoole runtime while PHP + * closes the remaining streams on shutdown, where changing them crashes. + */ + private static function suspendFileHooks(): int + { + if (!defined('SWOOLE_HOOK_STDIO') || \Swoole\Coroutine::getCid() < 0) { + return 0; + } + $flags = \Swoole\Runtime::getHookFlags(); + $fileHooks = $flags & (SWOOLE_HOOK_FILE | SWOOLE_HOOK_STDIO); + if ($fileHooks === 0) { + return 0; + } + \Swoole\Runtime::setHookFlags($flags & ~$fileHooks); + return $flags; + } + + private static function resumeFileHooks(int $flags): void + { + if ($flags !== 0) { + \Swoole\Runtime::setHookFlags($flags); + } + } + + /** + * The original wrapper reports normalized entry paths, which become + * __FILE__ of included files and keys of include_once. + */ + private static function normalize(string $path): string + { + $prefix = 'phar://' . self::$archive . '/'; + if (!str_starts_with($path, $prefix)) { + return $path; + } + $segments = []; + foreach (explode('/', substr($path, strlen($prefix))) as $segment) { + if ($segment === '..') { + array_pop($segments); + } elseif ($segment !== '' && $segment !== '.') { + $segments[] = $segment; + } + } + return $prefix . implode('/', $segments); + } + + public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool + { + $context = $this->context; + $stream = self::native(static fn() => $options & STREAM_REPORT_ERRORS + ? fopen($path, $mode, false, $context) + : @fopen($path, $mode, false, $context)); + if ($stream === false) { + return false; + } + $this->stream = $stream; + $openedPath = self::normalize($path); + return true; + } + + public function stream_read(int $count): string|false + { + return self::locked(function () use ($count) { + $this->resync(); + return fread($this->stream, $count); + }); + } + + public function stream_write(string $data): int + { + return self::locked(fn() => (int)fwrite($this->stream, $data)); + } + + /** + * Move the shared descriptor to this stream's position with a real lseek. + * + * Only a forward seek can be served from PHP's read buffer. Seeking to the + * end of the entry first makes the seek back to the current position + * reach the descriptor and drop whatever was buffered before the lock. + */ + private function resync(): void + { + $position = (int)ftell($this->stream); + fseek($this->stream, 0, SEEK_END); + fseek($this->stream, $position); + } + + public function stream_seek(int $offset, int $whence): bool + { + return self::locked(fn() => fseek($this->stream, $offset, $whence) === 0); + } + + public function stream_flush(): bool + { + return self::locked(fn() => fflush($this->stream)); + } + + public function stream_close(): void + { + self::locked(fn() => fclose($this->stream)); + $this->stream = null; + } + + public function stream_tell(): int + { + return (int)ftell($this->stream); + } + + public function stream_eof(): bool + { + return feof($this->stream); + } + + public function stream_stat(): array|false + { + return fstat($this->stream); + } + + public function stream_set_option(int $option, int $arg1, int $arg2): bool + { + return false; + } + + public function url_stat(string $path, int $flags): array|false + { + $stat = $flags & STREAM_URL_STAT_LINK ? 'lstat' : 'stat'; + return self::native(static fn() => $flags & STREAM_URL_STAT_QUIET ? @$stat($path) : $stat($path)); + } + + public function dir_opendir(string $path, int $options): bool + { + $directory = self::native(static fn() => opendir($path)); + if ($directory === false) { + return false; + } + $this->directory = $directory; + return true; + } + + public function dir_readdir(): string|false + { + return readdir($this->directory); + } + + public function dir_rewinddir(): bool + { + rewinddir($this->directory); + return true; + } + + public function dir_closedir(): bool + { + closedir($this->directory); + $this->directory = null; + return true; + } + + public function mkdir(string $path, int $mode, int $options): bool + { + return self::native(static fn() => mkdir($path, $mode, (bool)($options & STREAM_MKDIR_RECURSIVE))); + } + + public function rmdir(string $path, int $options): bool + { + return self::native(static fn() => rmdir($path)); + } + + public function rename(string $pathFrom, string $pathTo): bool + { + return self::native(static fn() => rename($pathFrom, $pathTo)); + } + + public function unlink(string $path): bool + { + return self::native(static fn() => unlink($path)); + } +} diff --git a/vendor/workerman/webman-framework/src/support/Plugin.php b/vendor/workerman/webman-framework/src/support/Plugin.php new file mode 100644 index 0000000..3062442 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/Plugin.php @@ -0,0 +1,124 @@ +<?php + +namespace support; + +use function current; +use function defined; +use function is_array; +use function is_callable; +use function is_file; +use function method_exists; + +class Plugin +{ + /** + * Install. + * @param mixed $event + * @return void + */ + public static function install($event) + { + static::findHelper(); + $psr4 = static::getPsr4($event); + foreach ($psr4 as $namespace => $path) { + static::findInstallFile($event, $path); + $pluginConst = "\\{$namespace}Install::WEBMAN_PLUGIN"; + if (!defined($pluginConst)) { + continue; + } + $installFunction = "\\{$namespace}Install::install"; + if (is_callable($installFunction)) { + $installFunction(true); + } + } + } + + /** + * Update. + * @param mixed $event + * @return void + */ + public static function update($event) + { + static::findHelper(); + $psr4 = static::getPsr4($event); + foreach ($psr4 as $namespace => $path) { + static::findInstallFile($event, $path); + $pluginConst = "\\{$namespace}Install::WEBMAN_PLUGIN"; + if (!defined($pluginConst)) { + continue; + } + $updateFunction = "\\{$namespace}Install::update"; + if (is_callable($updateFunction)) { + $updateFunction(); + continue; + } + $installFunction = "\\{$namespace}Install::install"; + if (is_callable($installFunction)) { + $installFunction(false); + } + } + } + + /** + * Uninstall. + * @param mixed $event + * @return void + */ + public static function uninstall($event) + { + static::findHelper(); + $psr4 = static::getPsr4($event); + foreach ($psr4 as $namespace => $path) { + static::findInstallFile($event, $path); + $pluginConst = "\\{$namespace}Install::WEBMAN_PLUGIN"; + if (!defined($pluginConst)) { + continue; + } + $uninstallFunction = "\\{$namespace}Install::uninstall"; + if (is_callable($uninstallFunction)) { + $uninstallFunction(); + } + } + } + + /** + * FindInstallFile. + * @param mixed $event + * @param mixed $path + * @return void + */ + protected static function findInstallFile($event, $path) + { + $operation = $event->getOperation(); + $package = method_exists($operation, 'getPackage') ? $operation->getPackage() : $operation->getTargetPackage(); + $srcPath = is_array($path) ? current($path) : $path; + $file = base_path() . "/vendor/{$package->getName()}/$srcPath/Install.php"; + if (is_file($file)) { + require_once $file; + } + } + + /** + * Get psr-4 info + * + * @param mixed $event + * @return array + */ + protected static function getPsr4($event) + { + $operation = $event->getOperation(); + $autoload = method_exists($operation, 'getPackage') ? $operation->getPackage()->getAutoload() : $operation->getTargetPackage()->getAutoload(); + return $autoload['psr-4'] ?? []; + } + + /** + * FindHelper. + * @return void + */ + protected static function findHelper() + { + // Plugin.php in webman + require_once __DIR__ . '/helpers.php'; + } +} diff --git a/vendor/workerman/webman-framework/src/support/Request.php b/vendor/workerman/webman-framework/src/support/Request.php new file mode 100644 index 0000000..e3f6ac3 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/Request.php @@ -0,0 +1,24 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support; + +/** + * Class Request + * @package support + */ +class Request extends \Webman\Http\Request +{ + +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/Response.php b/vendor/workerman/webman-framework/src/support/Response.php new file mode 100644 index 0000000..9bc4e1e --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/Response.php @@ -0,0 +1,24 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support; + +/** + * Class Response + * @package support + */ +class Response extends \Webman\Http\Response +{ + +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/Translation.php b/vendor/workerman/webman-framework/src/support/Translation.php new file mode 100644 index 0000000..b5d33ac --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/Translation.php @@ -0,0 +1,108 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support; + +use FilesystemIterator; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; +use RegexIterator; +use Symfony\Component\Translation\Translator; +use Webman\Exception\NotFoundException; +use function basename; +use function config; +use function get_realpath; +use function pathinfo; +use function request; +use function substr; + +/** + * Class Translation + * @package support + * @method static string trans(?string $id, array $parameters = [], string $domain = null, string $locale = null) + * @method static void setLocale(string $locale) + * @method static string getLocale() + */ +class Translation +{ + + /** + * @var Translator[] + */ + protected static $instance = []; + + /** + * Instance. + * @param string $plugin + * @param array|null $config + * @return Translator + * @throws NotFoundException + */ + public static function instance(string $plugin = '', ?array $config = null): Translator + { + if (!isset(static::$instance[$plugin])) { + $config = $config ?? config($plugin ? "plugin.$plugin.translation" : 'translation', []); + $paths = (array)($config['path'] ?? []); + + static::$instance[$plugin] = $translator = new Translator($config['locale']); + $translator->setFallbackLocales($config['fallback_locale']); + + $classes = $config['loader'] ?? [ + 'Symfony\Component\Translation\Loader\PhpFileLoader' => [ + 'extension' => '.php', + 'format' => 'phpfile' + ], + 'Symfony\Component\Translation\Loader\PoFileLoader' => [ + 'extension' => '.po', + 'format' => 'pofile' + ] + ]; + foreach ($paths as $path) { + // Phar support. Compatible with the 'realpath' function in the phar file. + if (!$translationsPath = get_realpath($path)) { + continue; + } + + foreach ($classes as $class => $opts) { + $translator->addLoader($opts['format'], new $class); + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($translationsPath, FilesystemIterator::SKIP_DOTS)); + $files = new RegexIterator($iterator, '/^.+' . preg_quote($opts['extension']) . '$/i', RegexIterator::GET_MATCH); + foreach ($files as $file) { + $file = $file[0]; + $domain = basename($file, $opts['extension']); + $dirName = pathinfo($file, PATHINFO_DIRNAME); + $locale = substr(strrchr($dirName, DIRECTORY_SEPARATOR), 1); + if ($domain && $locale) { + $translator->addResource($opts['format'], $file, $locale, $domain); + } + } + } + } + } + return static::$instance[$plugin]; + } + + /** + * @param string $name + * @param array $arguments + * @return mixed + * @throws NotFoundException + */ + public static function __callStatic(string $name, array $arguments) + { + $request = request(); + $plugin = $request->plugin ?? ''; + return static::instance($plugin)->{$name}(... $arguments); + } +} diff --git a/vendor/workerman/webman-framework/src/support/View.php b/vendor/workerman/webman-framework/src/support/View.php new file mode 100644 index 0000000..ceddc7b --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/View.php @@ -0,0 +1,35 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support; + +use function config; +use function request; + +class View +{ + /** + * Assign. + * @param mixed $name + * @param mixed $value + * @return void + */ + public static function assign($name, mixed $value = null) + { + $request = request(); + $plugin = $request->plugin ?? ''; + $handler = config($plugin ? "plugin.$plugin.view.handler" : 'view.handler'); + $handler::assign($name, $value); + } +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/annotation/DisableDefaultRoute.php b/vendor/workerman/webman-framework/src/support/annotation/DisableDefaultRoute.php new file mode 100644 index 0000000..a951504 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/DisableDefaultRoute.php @@ -0,0 +1,13 @@ +<?php + +namespace support\annotation; + +use Attribute; + +/** + * @deprecated Use support\annotation\route\DisableDefaultRoute instead. + */ +#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)] +class DisableDefaultRoute extends \support\annotation\route\DisableDefaultRoute +{ +} diff --git a/vendor/workerman/webman-framework/src/support/annotation/Middleware.php b/vendor/workerman/webman-framework/src/support/annotation/Middleware.php new file mode 100644 index 0000000..98cbb77 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/Middleware.php @@ -0,0 +1,41 @@ +<?php + +namespace support\annotation; + +use Attribute; + +/** + * Attach middlewares to routes/controllers/functions via attributes. + * + * Example: + * #[Middleware(AuthMiddleware::class, RateLimitMiddleware::class)] + */ +#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)] +class Middleware +{ + /** + * @var array + */ + protected array $middlewares = []; + + /** + * @param mixed ...$middlewares Middleware class names. + */ + public function __construct(...$middlewares) + { + $this->middlewares = $middlewares; + } + + /** + * Convert to webman middleware callable format: [MiddlewareClass, 'process']. + * @return array + */ + public function getMiddlewares(): array + { + $middlewares = []; + foreach ($this->middlewares as $middleware) { + $middlewares[] = [$middleware, 'process']; + } + return $middlewares; + } +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Any.php b/vendor/workerman/webman-framework/src/support/annotation/route/Any.php new file mode 100644 index 0000000..1112fca --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Any.php @@ -0,0 +1,22 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Shortcut for #[Route(methods: ['GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS'], ...)]. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Any extends Route +{ + /** + * @param string|null $path Route path. Null means default-route method restriction only. + * @param string|null $name Route name + */ + public function __construct(?string $path = null, ?string $name = null) + { + parent::__construct($path, ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'], $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Delete.php b/vendor/workerman/webman-framework/src/support/annotation/route/Delete.php new file mode 100644 index 0000000..ffa673c --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Delete.php @@ -0,0 +1,22 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Shortcut for #[Route(methods: 'DELETE', ...)]. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Delete extends Route +{ + /** + * @param string|null $path Route path. Null means default-route method restriction only. + * @param string|null $name Route name + */ + public function __construct(?string $path = null, ?string $name = null) + { + parent::__construct($path, 'DELETE', $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/DisableDefaultRoute.php b/vendor/workerman/webman-framework/src/support/annotation/route/DisableDefaultRoute.php new file mode 100644 index 0000000..74ea923 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/DisableDefaultRoute.php @@ -0,0 +1,13 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Disable webman's default route mapping for a controller or action. + */ +#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)] +class DisableDefaultRoute +{ +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Get.php b/vendor/workerman/webman-framework/src/support/annotation/route/Get.php new file mode 100644 index 0000000..fa29b89 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Get.php @@ -0,0 +1,22 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Shortcut for #[Route(methods: 'GET', ...)]. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Get extends Route +{ + /** + * @param string|null $path Route path. Null means default-route method restriction only. + * @param string|null $name Route name + */ + public function __construct(?string $path = null, ?string $name = null) + { + parent::__construct($path, 'GET', $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Head.php b/vendor/workerman/webman-framework/src/support/annotation/route/Head.php new file mode 100644 index 0000000..d6bb271 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Head.php @@ -0,0 +1,22 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Shortcut for #[Route(methods: 'HEAD', ...)]. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Head extends Route +{ + /** + * @param string|null $path Route path. Null means default-route method restriction only. + * @param string|null $name Route name + */ + public function __construct(?string $path = null, ?string $name = null) + { + parent::__construct($path, 'HEAD', $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Options.php b/vendor/workerman/webman-framework/src/support/annotation/route/Options.php new file mode 100644 index 0000000..7b982e0 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Options.php @@ -0,0 +1,22 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Shortcut for #[Route(methods: 'OPTIONS', ...)]. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Options extends Route +{ + /** + * @param string|null $path Route path. Null means default-route method restriction only. + * @param string|null $name Route name + */ + public function __construct(?string $path = null, ?string $name = null) + { + parent::__construct($path, 'OPTIONS', $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Patch.php b/vendor/workerman/webman-framework/src/support/annotation/route/Patch.php new file mode 100644 index 0000000..09f879b --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Patch.php @@ -0,0 +1,22 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Shortcut for #[Route(methods: 'PATCH', ...)]. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Patch extends Route +{ + /** + * @param string|null $path Route path. Null means default-route method restriction only. + * @param string|null $name Route name + */ + public function __construct(?string $path = null, ?string $name = null) + { + parent::__construct($path, 'PATCH', $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Post.php b/vendor/workerman/webman-framework/src/support/annotation/route/Post.php new file mode 100644 index 0000000..895b5d2 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Post.php @@ -0,0 +1,22 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Shortcut for #[Route(methods: 'POST', ...)]. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Post extends Route +{ + /** + * @param string|null $path Route path. Null means default-route method restriction only. + * @param string|null $name Route name + */ + public function __construct(?string $path = null, ?string $name = null) + { + parent::__construct($path, 'POST', $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Put.php b/vendor/workerman/webman-framework/src/support/annotation/route/Put.php new file mode 100644 index 0000000..6ee8841 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Put.php @@ -0,0 +1,22 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Shortcut for #[Route(methods: 'PUT', ...)]. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Put extends Route +{ + /** + * @param string|null $path Route path. Null means default-route method restriction only. + * @param string|null $name Route name + */ + public function __construct(?string $path = null, ?string $name = null) + { + parent::__construct($path, 'PUT', $name); + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/Route.php b/vendor/workerman/webman-framework/src/support/annotation/route/Route.php new file mode 100644 index 0000000..d239f97 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/Route.php @@ -0,0 +1,40 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Define an explicit route, or restrict allowed HTTP methods for default route when path is null. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +class Route +{ + /** + * Route path. Null means "method restriction only" for default route. + */ + public ?string $path; + + /** + * @var string[] + */ + public array $methods; + + /** + * Route name for URL generation. + */ + public ?string $name; + + /** + * @param string|null $path Route path, must start with "/". Null means "method restriction only" for default route. + * @param string|string[] $methods HTTP methods + * @param string|null $name Route name + */ + public function __construct(?string $path = null, array|string $methods = ['GET'], ?string $name = null) + { + $this->path = $path; + $this->methods = is_array($methods) ? $methods : [$methods]; + $this->name = $name; + } +} + diff --git a/vendor/workerman/webman-framework/src/support/annotation/route/RouteGroup.php b/vendor/workerman/webman-framework/src/support/annotation/route/RouteGroup.php new file mode 100644 index 0000000..c0ac38a --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/annotation/route/RouteGroup.php @@ -0,0 +1,26 @@ +<?php + +namespace support\annotation\route; + +use Attribute; + +/** + * Group routes by controller-level prefix. + */ +#[Attribute(Attribute::TARGET_CLASS)] +class RouteGroup +{ + /** + * Prefix for all routes in this controller. + */ + public string $prefix; + + /** + * @param string $prefix Route group prefix, e.g. "/api/v1" + */ + public function __construct(string $prefix = '') + { + $this->prefix = $prefix; + } +} + diff --git a/vendor/workerman/webman-framework/src/support/bootstrap.php b/vendor/workerman/webman-framework/src/support/bootstrap.php new file mode 100644 index 0000000..d913def --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/bootstrap.php @@ -0,0 +1,139 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +use Dotenv\Dotenv; +use support\Log; +use Webman\Bootstrap; +use Webman\Config; +use Webman\Middleware; +use Webman\Route; +use Webman\Util; +use Workerman\Events\Select; +use Workerman\Worker; + +$worker = $worker ?? null; + +if (empty(Worker::$eventLoopClass)) { + Worker::$eventLoopClass = Select::class; +} + +set_error_handler(function ($level, $message, $file = '', $line = 0) { + if (error_reporting() & $level) { + throw new ErrorException($message, 0, $level, $file, $line); + } +}); + +if ($worker) { + register_shutdown_function(function ($startTime) { + if (time() - $startTime <= 0.1) { + sleep(1); + } + }, time()); +} + +if (class_exists('Dotenv\Dotenv') && file_exists(base_path(false) . '/.env')) { + if (method_exists('Dotenv\Dotenv', 'createUnsafeMutable')) { + Dotenv::createUnsafeMutable(base_path(false))->load(); + } else { + Dotenv::createMutable(base_path(false))->load(); + } +} + +Config::clear(); +support\App::loadAllConfig(['route']); +if ($timezone = config('app.default_timezone')) { + date_default_timezone_set($timezone); +} + +foreach (config('autoload.files', []) as $file) { + include_once $file; +} +foreach (config('plugin', []) as $firm => $projects) { + foreach ($projects as $name => $project) { + if (!is_array($project)) { + continue; + } + foreach ($project['autoload']['files'] ?? [] as $file) { + include_once $file; + } + } + foreach ($projects['autoload']['files'] ?? [] as $file) { + include_once $file; + } +} + +Middleware::load(config('middleware', [])); +foreach (config('plugin', []) as $firm => $projects) { + foreach ($projects as $name => $project) { + if (!is_array($project) || $name === 'static') { + continue; + } + Middleware::load($project['middleware'] ?? []); + } + Middleware::load($projects['middleware'] ?? [], $firm); + if ($staticMiddlewares = config("plugin.$firm.static.middleware")) { + Middleware::load(['__static__' => $staticMiddlewares], $firm); + } +} +Middleware::load(['__static__' => config('static.middleware', [])]); + +foreach (config('bootstrap', []) as $className) { + if (!class_exists($className)) { + $log = "Warning: Class $className setting in config/bootstrap.php not found\r\n"; + echo $log; + Log::error($log); + continue; + } + /** @var Bootstrap $className */ + $className::start($worker); +} + +foreach (config('plugin', []) as $firm => $projects) { + foreach ($projects as $name => $project) { + if (!is_array($project)) { + continue; + } + foreach ($project['bootstrap'] ?? [] as $className) { + if (!class_exists($className)) { + $log = "Warning: Class $className setting in config/plugin/$firm/$name/bootstrap.php not found\r\n"; + echo $log; + Log::error($log); + continue; + } + /** @var Bootstrap $className */ + $className::start($worker); + } + } + foreach ($projects['bootstrap'] ?? [] as $className) { + /** @var string $className */ + if (!class_exists($className)) { + $log = "Warning: Class $className setting in plugin/$firm/config/bootstrap.php not found\r\n"; + echo $log; + Log::error($log); + continue; + } + /** @var Bootstrap $className */ + $className::start($worker); + } +} + +$directory = base_path() . '/plugin'; +$paths = [config_path()]; +foreach (Util::scanDir($directory) as $path) { + if (is_dir($path = "$path/config")) { + $paths[] = $path; + } +} +Route::load($paths); + diff --git a/vendor/workerman/webman-framework/src/support/bootstrap/Session.php b/vendor/workerman/webman-framework/src/support/bootstrap/Session.php new file mode 100644 index 0000000..7360d0e --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/bootstrap/Session.php @@ -0,0 +1,61 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\bootstrap; + +use Webman\Bootstrap; +use Workerman\Protocols\Http; +use Workerman\Protocols\Http\Session as SessionBase; +use Workerman\Worker; +use function config; +use function property_exists; + +/** + * Class Session + * @package support + */ +class Session implements Bootstrap +{ + + /** + * @param Worker|null $worker + * @return void + */ + public static function start(?Worker $worker) + { + $config = config('session'); + if (property_exists(SessionBase::class, 'name')) { + SessionBase::$name = $config['session_name']; + } else { + Http::sessionName($config['session_name']); + } + SessionBase::handlerClass($config['handler'], $config['config'][$config['type']]); + $map = [ + 'auto_update_timestamp' => 'autoUpdateTimestamp', + 'cookie_lifetime' => 'cookieLifetime', + 'gc_probability' => 'gcProbability', + 'cookie_path' => 'cookiePath', + 'http_only' => 'httpOnly', + 'same_site' => 'sameSite', + 'lifetime' => 'lifetime', + 'domain' => 'domain', + 'secure' => 'secure', + ]; + foreach ($map as $key => $name) { + if (isset($config[$key]) && property_exists(SessionBase::class, $name)) { + SessionBase::${$name} = $config[$key]; + } + } + } +} diff --git a/vendor/workerman/webman-framework/src/support/exception/BusinessException.php b/vendor/workerman/webman-framework/src/support/exception/BusinessException.php new file mode 100644 index 0000000..b72d488 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/exception/BusinessException.php @@ -0,0 +1,24 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\exception; + +/** + * Class BusinessException + * @package support\exception + */ +class BusinessException extends \Webman\Exception\BusinessException +{ + +} diff --git a/vendor/workerman/webman-framework/src/support/exception/Handler.php b/vendor/workerman/webman-framework/src/support/exception/Handler.php new file mode 100644 index 0000000..985413f --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/exception/Handler.php @@ -0,0 +1,43 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\exception; + +use Throwable; +use Webman\Exception\ExceptionHandler; +use Webman\Http\Request; +use Webman\Http\Response; +use Webman\Exception\BusinessException; + +/** + * Class Handler + * @package support\exception + */ +class Handler extends ExceptionHandler +{ + public $dontReport = [ + BusinessException::class, + ]; + + public function report(Throwable $exception) + { + parent::report($exception); + } + + public function render(Request $request, Throwable $exception): Response + { + return parent::render($request, $exception); + } + +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/exception/InputTypeException.php b/vendor/workerman/webman-framework/src/support/exception/InputTypeException.php new file mode 100644 index 0000000..eed54fa --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/exception/InputTypeException.php @@ -0,0 +1,24 @@ +<?php + +namespace support\exception; + +use Throwable; + +class InputTypeException extends PageNotFoundException +{ + + /** + * @var string + */ + protected $template = '/app/view/400'; + + /** + * InputTypeException constructor. + * @param string $message + * @param int $code + * @param Throwable|null $previous + */ + public function __construct(string $message = 'Input :parameter must be of type :exceptType, :actualType given', int $code = 400, ?Throwable $previous = null) { + parent::__construct($message, $code, $previous); + } +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/exception/InputValueException.php b/vendor/workerman/webman-framework/src/support/exception/InputValueException.php new file mode 100644 index 0000000..df76b5b --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/exception/InputValueException.php @@ -0,0 +1,24 @@ +<?php + +namespace support\exception; + +use Throwable; + +class InputValueException extends PageNotFoundException +{ + + /** + * @var string + */ + protected $template = '/app/view/400'; + + /** + * InputTypeException constructor. + * @param string $message + * @param int $code + * @param Throwable|null $previous + */ + public function __construct(string $message = 'Input :parameter is invalid.', int $code = 400, ?Throwable $previous = null) { + parent::__construct($message, $code, $previous); + } +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/exception/MissingInputException.php b/vendor/workerman/webman-framework/src/support/exception/MissingInputException.php new file mode 100644 index 0000000..15e00db --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/exception/MissingInputException.php @@ -0,0 +1,46 @@ +<?php + +namespace support\exception; + +use Throwable; +use Webman\Http\Request; +use Webman\Http\Response; + +class MissingInputException extends PageNotFoundException +{ + /** + * @var string + */ + protected $template = '/app/view/400'; + + /** + * MissingInputException constructor. + * @param string $message + * @param int $code + * @param Throwable|null $previous + */ + public function __construct(string $message = 'Missing input parameter :parameter', int $code = 400, ?Throwable $previous = null) { + parent::__construct($message, $code, $previous); + } + + /** + * Render an exception into an HTTP response. + * @param Request $request + * @return Response|null + * @throws Throwable + */ + public function render(Request $request): ?Response + { + $code = $this->getCode() ?: 404; + $debug = config($request->plugin ? "plugin.$request->plugin.app.debug" : 'app.debug'); + $data = $debug ? $this->data : ['parameter' => '']; + $message = $this->trans($this->getMessage(), $data); + if ($request->expectsJson()) { + $json = ['code' => $code, 'msg' => $message, 'data' => $data]; + return new Response(200, ['Content-Type' => 'application/json'], + json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + } + return new Response($code, [], $this->html($message)); + } + +} \ No newline at end of file diff --git a/vendor/workerman/webman-framework/src/support/exception/NotFoundException.php b/vendor/workerman/webman-framework/src/support/exception/NotFoundException.php new file mode 100644 index 0000000..016741d --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/exception/NotFoundException.php @@ -0,0 +1,20 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\exception; + +class NotFoundException extends BusinessException +{ + +} diff --git a/vendor/workerman/webman-framework/src/support/exception/PageNotFoundException.php b/vendor/workerman/webman-framework/src/support/exception/PageNotFoundException.php new file mode 100644 index 0000000..cd76376 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/exception/PageNotFoundException.php @@ -0,0 +1,93 @@ +<?php +/** + * This file is part of webman. + * + * Licensed under The MIT License + * For full copyright and license information, please see the MIT-LICENSE.txt + * Redistributions of files must retain the above copyright notice. + * + * @author walkor<walkor@workerman.net> + * @copyright walkor<walkor@workerman.net> + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\exception; + +use Throwable; +use Webman\Http\Request; +use Webman\Http\Response; + +class PageNotFoundException extends NotFoundException +{ + + /** + * @var string + */ + protected $template = '/app/view/404'; + + /** + * PageNotFoundException constructor. + * @param string $message + * @param int $code + * @param Throwable|null $previous + */ + public function __construct(string $message = '404 Not Found', int $code = 404, ?Throwable $previous = null) { + parent::__construct($message, $code, $previous); + } + + /** + * Render an exception into an HTTP response. + * @param Request $request + * @return Response|null + * @throws Throwable + */ + public function render(Request $request): ?Response + { + $code = $this->getCode() ?: 404; + $data = $this->data; + $message = $this->trans($this->getMessage(), $data); + if ($request->expectsJson()) { + $json = ['code' => $code, 'msg' => $message, 'data' => $data]; + return new Response(200, ['Content-Type' => 'application/json'], + json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + } + return new Response($code, [], $this->html($message)); + } + + /** + * Get the HTML representation of the exception. + * @param string $message + * @return string + * @throws Throwable + */ + protected function html(string $message): string + { + $message = htmlspecialchars($message); + if (is_file(base_path("$this->template.html"))) { + return raw_view($this->template, ['message' => $message])->rawBody(); + } + return <<<EOF +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>$message + + + +

$message

+
+
webman
+ + +EOF; + + } + +} diff --git a/vendor/workerman/webman-framework/src/support/helpers.php b/vendor/workerman/webman-framework/src/support/helpers.php new file mode 100644 index 0000000..e61c112 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/helpers.php @@ -0,0 +1,681 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +use support\Container; +use support\PharStream; +use support\Request; +use support\Response; +use support\Translation; +use support\view\Blade; +use support\view\Raw; +use support\view\ThinkPHP; +use support\view\Twig; +use Twig\Error\LoaderError; +use Twig\Error\RuntimeError; +use Twig\Error\SyntaxError; +use Webman\App; +use Webman\Config; +use Webman\Route; +use Workerman\Protocols\Http\Session; +use Workerman\Worker; + +/** + * Get the base path of the application + */ +if (!defined('BASE_PATH')) { + if (!$basePath = Phar::running()) { + $basePath = getcwd(); + while ($basePath !== dirname($basePath)) { + if (is_dir("$basePath/vendor") && is_file("$basePath/start.php")) { + break; + } + $basePath = dirname($basePath); + } + if ($basePath === dirname($basePath)) { + $basePath = __DIR__ . '/../../../../../'; + } + } + define('BASE_PATH', realpath($basePath) ?: $basePath); +} + +if (!function_exists('run_path')) { + /** + * return the program execute directory + * @param string $path + * @return string + */ + function run_path(string $path = ''): string + { + static $runPath = ''; + if (!$runPath) { + $runPath = is_phar() ? dirname(Phar::running(false)) : BASE_PATH; + } + return path_combine($runPath, $path); + } +} + +if (!function_exists('base_path')) { + /** + * if the param $path equal false,will return this program current execute directory + * @param string|false $path + * @return string + */ + function base_path($path = ''): string + { + if (false === $path) { + return run_path(); + } + return path_combine(BASE_PATH, $path); + } +} + +if (!function_exists('app_path')) { + /** + * App path + * @param string $path + * @return string + */ + function app_path(string $path = ''): string + { + return path_combine(BASE_PATH . DIRECTORY_SEPARATOR . 'app', $path); + } +} + +if (!function_exists('public_path')) { + /** + * Public path + * @param string $path + * @param string|null $plugin + * @return string + */ + function public_path(string $path = '', ?string $plugin = null): string + { + static $publicPaths = []; + $plugin = $plugin ?? ''; + if (isset($publicPaths[$plugin])) { + $publicPath = $publicPaths[$plugin]; + } else { + $prefix = $plugin ? "plugin.$plugin." : ''; + $pathPrefix = $plugin ? 'plugin' . DIRECTORY_SEPARATOR . $plugin . DIRECTORY_SEPARATOR : ''; + $publicPath = \config("{$prefix}app.public_path", run_path("{$pathPrefix}public")); + if (count($publicPaths) > 32) { + $publicPaths = []; + } + $publicPaths[$plugin] = $publicPath; + } + return $path === '' ? $publicPath : path_combine($publicPath, $path); + } +} + +if (!function_exists('config_path')) { + /** + * Config path + * @param string $path + * @return string + */ + function config_path(string $path = ''): string + { + return path_combine(BASE_PATH . DIRECTORY_SEPARATOR . 'config', $path); + } +} + +if (!function_exists('runtime_path')) { + /** + * Runtime path + * @param string $path + * @return string + */ + function runtime_path(string $path = ''): string + { + static $runtimePath = ''; + if (!$runtimePath) { + $runtimePath = \config('app.runtime_path') ?: run_path('runtime'); + } + return path_combine($runtimePath, $path); + } +} + +if (!function_exists('path_combine')) { + /** + * Generate paths based on given information + * @param string $front + * @param string $back + * @return string + */ + function path_combine(string $front, string $back): string + { + return $front . ($back ? (DIRECTORY_SEPARATOR . ltrim($back, DIRECTORY_SEPARATOR)) : $back); + } +} + +if (!function_exists('response')) { + /** + * Response + * @param int $status + * @param array $headers + * @param string $body + * @return Response + */ + function response(string $body = '', int $status = 200, array $headers = []): Response + { + return new Response($status, $headers, $body); + } +} + +if (!function_exists('json')) { + /** + * Json response + * @param $data + * @param int $options + * @return Response + */ + function json($data, int $options = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR): Response + { + return new Response(200, ['Content-Type' => 'application/json'], json_encode($data, $options)); + } +} + +if (!function_exists('xml')) { + /** + * Xml response + * @param $xml + * @return Response + */ + function xml($xml): Response + { + if ($xml instanceof SimpleXMLElement) { + $xml = $xml->asXML(); + } + return new Response(200, ['Content-Type' => 'text/xml'], $xml); + } +} + +if (!function_exists('jsonp')) { + /** + * Jsonp response + * @param $data + * @param string $callbackName + * @return Response + */ + function jsonp($data, string $callbackName = 'callback'): Response + { + if (!is_scalar($data) && null !== $data) { + $data = json_encode($data); + } + return new Response(200, [], "$callbackName($data)"); + } +} + +if (!function_exists('redirect')) { + /** + * Redirect response + * @param string $location + * @param int $status + * @param array $headers + * @return Response + */ + function redirect(string $location, int $status = 302, array $headers = []): Response + { + $response = new Response($status, ['Location' => $location]); + if (!empty($headers)) { + $response->withHeaders($headers); + } + return $response; + } +} + +if (!function_exists('view')) { + /** + * View response + * @param mixed $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return Response + */ + function view(mixed $template = null, array $vars = [], ?string $app = null, ?string $plugin = null): Response + { + [$template, $vars, $app, $plugin] = template_inputs($template, $vars, $app, $plugin); + $handler = \config($plugin ? "plugin.$plugin.view.handler" : 'view.handler'); + return new Response(200, [], $handler::render($template, $vars, $app, $plugin)); + } +} + +if (!function_exists('raw_view')) { + /** + * Raw view response + * @param mixed $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return Response + * @throws Throwable + */ + function raw_view(mixed $template = null, array $vars = [], ?string $app = null, ?string $plugin = null): Response + { + return new Response(200, [], Raw::render(...template_inputs($template, $vars, $app, $plugin))); + } +} + +if (!function_exists('blade_view')) { + /** + * Blade view response + * @param mixed $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return Response + */ + function blade_view(mixed $template = null, array $vars = [], ?string $app = null, ?string $plugin = null): Response + { + return new Response(200, [], Blade::render(...template_inputs($template, $vars, $app, $plugin))); + } +} + +if (!function_exists('think_view')) { + /** + * Think view response + * @param mixed $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return Response + */ + function think_view(mixed $template = null, array $vars = [], ?string $app = null, ?string $plugin = null): Response + { + return new Response(200, [], ThinkPHP::render(...template_inputs($template, $vars, $app, $plugin))); + } +} + +if (!function_exists('twig_view')) { + /** + * Twig view response + * @param mixed $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return Response + */ + function twig_view(mixed $template = null, array $vars = [], ?string $app = null, ?string $plugin = null): Response + { + return new Response(200, [], Twig::render(...template_inputs($template, $vars, $app, $plugin))); + } +} + +if (!function_exists('request')) { + /** + * Get request + * @return \Webman\Http\Request|Request|null + */ + function request() + { + return App::request(); + } +} + +if (!function_exists('config')) { + /** + * Get config + * @param string|null $key + * @param mixed $default + * @return mixed + */ + function config(?string $key = null, mixed $default = null) + { + return Config::get($key, $default); + } +} + +if (!function_exists('route')) { + /** + * Create url + * @param string $name + * @param ...$parameters + * @return string + */ + function route(string $name, ...$parameters): string + { + $route = Route::getByName($name); + if (!$route) { + return ''; + } + + if (!$parameters) { + return $route->url(); + } + + if (is_array(current($parameters))) { + $parameters = current($parameters); + } + + return $route->url($parameters); + } +} + +if (!function_exists('session')) { + /** + * Session + * @param array|string|null $key + * @param mixed $default + * @return mixed|bool|Session + * @throws Exception + */ + function session(array|string|null $key = null, mixed $default = null): mixed + { + $request = \request(); + if (!$request) { + return $default; + } + $session = $request->session(); + if (null === $key) { + return $session; + } + if (is_array($key)) { + $session->put($key); + return null; + } + if (strpos($key, '.')) { + $keyArray = explode('.', $key); + $value = $session->all(); + foreach ($keyArray as $index) { + if (!isset($value[$index])) { + return $default; + } + $value = $value[$index]; + } + return $value; + } + return $session->get($key, $default); + } +} + +if (!function_exists('trans')) { + /** + * Translation + * @param string $id + * @param array $parameters + * @param string|null $domain + * @param string|null $locale + * @return string + */ + function trans(string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string + { + $res = Translation::trans($id, $parameters, $domain, $locale); + return $res === '' ? $id : $res; + } +} + +if (!function_exists('locale')) { + /** + * Locale + * @param string|null $locale + * @return string + */ + function locale(?string $locale = null): string + { + if (!$locale) { + return Translation::getLocale(); + } + Translation::setLocale($locale); + return $locale; + } +} + +if (!function_exists('not_found')) { + /** + * 404 not found + * @return Response + */ + function not_found(): Response + { + return new Response(404, [], file_get_contents(public_path() . '/404.html')); + } +} + +if (!function_exists('copy_dir')) { + /** + * Copy dir + * @param string $source + * @param string $dest + * @param bool $overwrite + * @return void + */ + function copy_dir(string $source, string $dest, bool $overwrite = false) + { + if (is_dir($source)) { + if (!is_dir($dest)) { + mkdir($dest); + } + $files = scandir($source); + foreach ($files as $file) { + if ($file !== "." && $file !== "..") { + copy_dir("$source/$file", "$dest/$file", $overwrite); + } + } + } else if (file_exists($source) && ($overwrite || !file_exists($dest))) { + copy($source, $dest); + } + } +} + +if (!function_exists('remove_dir')) { + /** + * Remove dir + * @param string $dir + * @return bool + */ + function remove_dir(string $dir): bool + { + if (is_link($dir) || is_file($dir)) { + return unlink($dir); + } + $files = array_diff(scandir($dir), array('.', '..')); + foreach ($files as $file) { + (is_dir("$dir/$file") && !is_link($dir)) ? remove_dir("$dir/$file") : unlink("$dir/$file"); + } + return rmdir($dir); + } +} + +if (!function_exists('worker_bind')) { + /** + * Bind worker + * @param $worker + * @param $class + */ + function worker_bind($worker, $class) + { + $callbackMap = [ + 'onConnect', + 'onMessage', + 'onClose', + 'onError', + 'onBufferFull', + 'onBufferDrain', + 'onWorkerStop', + 'onWebSocketConnect', + 'onWorkerReload' + ]; + foreach ($callbackMap as $name) { + if (method_exists($class, $name)) { + $worker->$name = [$class, $name]; + } + } + if (method_exists($class, 'onWorkerStart')) { + call_user_func([$class, 'onWorkerStart'], $worker); + } + } +} + +if (!function_exists('worker_start')) { + /** + * Start worker + * @param $processName + * @param $config + * @return void + */ + function worker_start($processName, $config) + { + if (isset($config['enable']) && !$config['enable']) { + return; + } + // feat:custom worker class [default: Workerman\Worker] + $class = is_a($class = $config['workerClass'] ?? '', Worker::class, true) ? $class : Worker::class; + $worker = new $class($config['listen'] ?? null, $config['context'] ?? []); + $properties = [ + 'count', + 'user', + 'group', + 'reloadable', + 'reusePort', + 'transport', + 'protocol', + 'eventLoop', + ]; + $worker->name = $processName; + foreach ($properties as $property) { + if (isset($config[$property])) { + $worker->$property = $config[$property]; + } + } + + $worker->onWorkerStart = function ($worker) use ($config) { + require_once base_path('/support/bootstrap.php'); + if (isset($config['handler'])) { + if (!class_exists($config['handler'])) { + echo "process error: class {$config['handler']} not exists\r\n"; + return; + } + + $instance = Container::make($config['handler'], $config['constructor'] ?? []); + worker_bind($worker, $instance); + } + }; + } +} + +if (!function_exists('get_realpath')) { + /** + * Get realpath + * @param string $filePath + * @return string + */ + function get_realpath(string $filePath): string + { + if (strpos($filePath, 'phar://') === 0) { + return $filePath; + } else { + return realpath($filePath); + } + } +} + +if (!function_exists('is_phar')) { + /** + * Is phar + * @return bool + */ + function is_phar(): bool + { + return class_exists(Phar::class, false) && Phar::running(); + } +} + +if (!function_exists('template_inputs')) { + /** + * Get template vars + * @param mixed $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return array + */ + function template_inputs(mixed $template, array $vars, ?string $app, ?string $plugin): array + { + $request = \request(); + $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin; + if (is_array($template)) { + $vars = $template; + $template = null; + } + if ($template === null && $controller = $request->controller) { + $controllerSuffix = config($plugin ? "plugin.$plugin.app.controller_suffix" : "app.controller_suffix", ''); + $controllerName = $controllerSuffix !== '' ? substr($controller, 0, -strlen($controllerSuffix)) : $controller; + $path = str_replace(['controller', 'Controller', '\\'], ['view', 'view', '/'], $controllerName); + $path = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $path)); + $action = $request->action; + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + foreach ($backtrace as $backtraceItem) { + if (!isset($backtraceItem['class']) || !isset($backtraceItem['function'])) { + continue; + } + if ($backtraceItem['class'] === App::class) { + break; + } + if (preg_match('/\\\\controller\\\\/i', $backtraceItem['class'])) { + $action = $backtraceItem['function']; + break; + } + } + $actionFileBaseName = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $action)); + $template = "/$path/$actionFileBaseName"; + } + return [$template, $vars, $app, $plugin]; + } +} + +if (!function_exists('cpu_count')) { + /** + * Get cpu count + * @return int + */ + function cpu_count(): int + { + // Windows does not support the number of processes setting. + if (DIRECTORY_SEPARATOR === '\\') { + return 1; + } + $count = 4; + if (is_callable('shell_exec')) { + if (strtolower(PHP_OS) === 'darwin') { + $count = (int)shell_exec('sysctl -n machdep.cpu.core_count'); + } else { + try { + $count = (int)shell_exec('nproc'); + } catch (\Throwable $ex) { + // Do nothing + } + } + } + return $count > 0 ? $count : 4; + } +} + +if (!function_exists('input')) { + /** + * Get request parameters, if no parameter name is passed, an array of all values is returned, default values is supported + * @param string|null $param param's name + * @param mixed $default default value + * @return mixed + */ + function input(?string $param = null, mixed $default = null): mixed + { + return is_null($param) ? \request()->all() : \request()->input($param, $default); + } +} + +if (is_phar()) { + PharStream::register(); +} diff --git a/vendor/workerman/webman-framework/src/support/view/Blade.php b/vendor/workerman/webman-framework/src/support/view/Blade.php new file mode 100644 index 0000000..c604b3c --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/view/Blade.php @@ -0,0 +1,84 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\view; + +use Jenssegers\Blade\Blade as BladeView; +use Webman\View; +use function app_path; +use function array_merge; +use function base_path; +use function config; +use function is_array; +use function request; +use function runtime_path; + +/** + * Class Blade + * composer require jenssegers/blade + * @package support\view + */ +class Blade implements View +{ + /** + * Assign. + * @param string|array $name + * @param mixed $value + */ + public static function assign(string|array $name, mixed $value = null): void + { + $request = request(); + $request->_view_vars = array_merge((array) $request->_view_vars, is_array($name) ? $name : [$name => $value]); + } + + /** + * Render. + * @param string $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return string + */ + public static function render(string $template, array $vars, ?string $app = null, ?string $plugin = null): string + { + static $views = []; + $request = request(); + $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin; + $app = $app === null ? ($request->app ?? '') : $app; + $configPrefix = $plugin ? "plugin.$plugin." : ''; + $baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path(); + if ($template[0] === '/') { + if (strpos($template, '/view/') !== false) { + [$viewPath, $template] = explode('/view/', $template, 2); + $viewPath = base_path("$viewPath/view"); + } else { + $viewPath = base_path(); + $template = ltrim($template, '/'); + } + } else { + $viewPath = $app === '' ? "$baseViewPath/view" : "$baseViewPath/$app/view"; + } + if (!isset($views[$viewPath])) { + $views[$viewPath] = new BladeView($viewPath, runtime_path() . '/views'); + $extension = config("{$configPrefix}view.extension"); + if ($extension) { + $extension($views[$viewPath]); + } + } + if(isset($request->_view_vars)) { + $vars = array_merge((array)$request->_view_vars, $vars); + } + return $views[$viewPath]->render($template, $vars); + } +} diff --git a/vendor/workerman/webman-framework/src/support/view/Raw.php b/vendor/workerman/webman-framework/src/support/view/Raw.php new file mode 100644 index 0000000..9747650 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/view/Raw.php @@ -0,0 +1,79 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\view; + +use Throwable; +use Webman\View; +use function app_path; +use function array_merge; +use function base_path; +use function config; +use function extract; +use function is_array; +use function ob_end_clean; +use function ob_get_clean; +use function ob_start; +use function request; + +/** + * Class Raw + * @package support\view + */ +class Raw implements View +{ + /** + * Assign. + * @param string|array $name + * @param mixed $value + */ + public static function assign(string|array $name, mixed $value = null): void + { + $request = request(); + $request->_view_vars = array_merge((array) $request->_view_vars, is_array($name) ? $name : [$name => $value]); + } + + /** + * Render. + * @param string $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return string + */ + public static function render(string $template, array $vars, ?string $app = null, ?string $plugin = null): string + { + $request = request(); + $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin; + $configPrefix = $plugin ? "plugin.$plugin." : ''; + $viewSuffix = config("{$configPrefix}view.options.view_suffix", 'html'); + $app = $app === null ? ($request->app ?? '') : $app; + $baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path(); + $__template_path__ = $template[0] === '/' ? base_path() . "$template.$viewSuffix" : ($app === '' ? "$baseViewPath/view/$template.$viewSuffix" : "$baseViewPath/$app/view/$template.$viewSuffix"); + if(isset($request->_view_vars)) { + extract((array)$request->_view_vars); + } + extract($vars); + ob_start(); + // Try to include php file. + try { + include $__template_path__; + } catch (Throwable $e) { + ob_end_clean(); + throw $e; + } + + return ob_get_clean(); + } +} diff --git a/vendor/workerman/webman-framework/src/support/view/ThinkPHP.php b/vendor/workerman/webman-framework/src/support/view/ThinkPHP.php new file mode 100644 index 0000000..64b6737 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/view/ThinkPHP.php @@ -0,0 +1,87 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\view; + +use think\Template; +use Webman\View; +use function app_path; +use function array_merge; +use function base_path; +use function config; +use function is_array; +use function ob_get_clean; +use function ob_start; +use function request; +use function runtime_path; + +/** + * Class Blade + * @package support\view + */ +class ThinkPHP implements View +{ + /** + * Assign. + * @param string|array $name + * @param mixed $value + */ + public static function assign(string|array $name, mixed $value = null): void + { + $request = request(); + $request->_view_vars = array_merge((array) $request->_view_vars, is_array($name) ? $name : [$name => $value]); + } + + /** + * Render. + * @param string $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return string + */ + public static function render(string $template, array $vars, ?string $app = null, ?string $plugin = null): string + { + $request = request(); + $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin; + $app = $app === null ? ($request->app ?? '') : $app; + $configPrefix = $plugin ? "plugin.$plugin." : ''; + $viewSuffix = config("{$configPrefix}view.options.view_suffix", 'html'); + $baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path(); + if ($template[0] === '/') { + if (strpos($template, '/view/') !== false) { + [$viewPath, $template] = explode('/view/', $template, 2); + $viewPath = base_path("$viewPath/view/"); + } else { + $viewPath = base_path() . dirname($template) . '/'; + $template = basename($template); + } + } else { + $viewPath = $app === '' ? "$baseViewPath/view/" : "$baseViewPath/$app/view/"; + } + $defaultOptions = [ + 'view_path' => $viewPath, + 'cache_path' => runtime_path() . '/views/', + 'view_suffix' => $viewSuffix + ]; + $options = array_merge($defaultOptions, config("{$configPrefix}view.options", [])); + $views = new Template($options); + ob_start(); + if(isset($request->_view_vars)) { + $vars = array_merge((array)$request->_view_vars, $vars); + } + $views->fetch($template, $vars); + return ob_get_clean(); + } +} diff --git a/vendor/workerman/webman-framework/src/support/view/Twig.php b/vendor/workerman/webman-framework/src/support/view/Twig.php new file mode 100644 index 0000000..a8532e9 --- /dev/null +++ b/vendor/workerman/webman-framework/src/support/view/Twig.php @@ -0,0 +1,87 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +namespace support\view; + +use Twig\Environment; +use Twig\Error\LoaderError; +use Twig\Error\RuntimeError; +use Twig\Error\SyntaxError; +use Twig\Loader\FilesystemLoader; +use Webman\View; +use function app_path; +use function array_merge; +use function base_path; +use function config; +use function is_array; +use function request; + +/** + * Class Blade + * @package support\view + */ +class Twig implements View +{ + /** + * Assign. + * @param string|array $name + * @param mixed $value + */ + public static function assign(string|array $name, mixed $value = null): void + { + $request = request(); + $request->_view_vars = array_merge((array) $request->_view_vars, is_array($name) ? $name : [$name => $value]); + } + + /** + * Render. + * @param string $template + * @param array $vars + * @param string|null $app + * @param string|null $plugin + * @return string + */ + public static function render(string $template, array $vars, ?string $app = null, ?string $plugin = null): string + { + static $views = []; + $request = request(); + $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin; + $app = $app === null ? ($request->app ?? '') : $app; + $configPrefix = $plugin ? "plugin.$plugin." : ''; + $viewSuffix = config("{$configPrefix}view.options.view_suffix", 'html'); + $baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path(); + if ($template[0] === '/') { + $template = ltrim($template, '/'); + if (strpos($template, '/view/') !== false) { + [$viewPath, $template] = explode('/view/', $template, 2); + $viewPath = base_path("$viewPath/view"); + } else { + $viewPath = base_path(); + } + } else { + $viewPath = $app === '' ? "$baseViewPath/view/" : "$baseViewPath/$app/view/"; + } + if (!isset($views[$viewPath])) { + $views[$viewPath] = new Environment(new FilesystemLoader($viewPath), config("{$configPrefix}view.options", [])); + $extension = config("{$configPrefix}view.extension"); + if ($extension) { + $extension($views[$viewPath]); + } + } + if(isset($request->_view_vars)) { + $vars = array_merge((array)$request->_view_vars, $vars); + } + return $views[$viewPath]->render("$template.$viewSuffix", $vars); + } +} diff --git a/vendor/workerman/webman-framework/src/windows.php b/vendor/workerman/webman-framework/src/windows.php new file mode 100644 index 0000000..f37a72c --- /dev/null +++ b/vendor/workerman/webman-framework/src/windows.php @@ -0,0 +1,136 @@ +load(); + } else { + Dotenv::createMutable(base_path())->load(); + } +} + +App::loadAllConfig(['route']); + +$errorReporting = config('app.error_reporting'); +if (isset($errorReporting)) { + error_reporting($errorReporting); +} + +$runtimeProcessPath = runtime_path() . DIRECTORY_SEPARATOR . '/windows'; +$paths = [ + $runtimeProcessPath, + runtime_path('logs'), + runtime_path('views') +]; +foreach ($paths as $path) { + if (!is_dir($path)) { + mkdir($path, 0777, true); + } +} + +$processFiles = []; +if (config('server.listen')) { + $processFiles[] = __DIR__ . DIRECTORY_SEPARATOR . 'start.php'; +} +foreach (config('process', []) as $processName => $config) { + $processFiles[] = write_process_file($runtimeProcessPath, $processName, ''); +} + +foreach (config('plugin', []) as $firm => $projects) { + foreach ($projects as $name => $project) { + if (!is_array($project)) { + continue; + } + foreach ($project['process'] ?? [] as $processName => $config) { + $processFiles[] = write_process_file($runtimeProcessPath, $processName, "$firm.$name"); + } + } + foreach ($projects['process'] ?? [] as $processName => $config) { + $processFiles[] = write_process_file($runtimeProcessPath, $processName, $firm); + } +} + +function write_process_file($runtimeProcessPath, $processName, $firm): string +{ + $processParam = $firm ? "plugin.$firm.$processName" : $processName; + $configParam = $firm ? "config('plugin.$firm.process')['$processName']" : "config('process')['$processName']"; + $fileContent = << true]); + if (!$resource) { + exit("Can not execute $cmd\r\n"); + } + return $resource; +} + +$resource = popen_processes($processFiles); +echo "\r\n"; +while (1) { + sleep(1); + if (!empty($monitor) && $monitor->checkAllFilesChange()) { + $status = proc_get_status($resource); + $pid = $status['pid']; + shell_exec("taskkill /F /T /PID $pid"); + proc_close($resource); + $resource = popen_processes($processFiles); + } +} diff --git a/vendor/workerman/webman-framework/tests/CoroutineControllerLoadTest.php b/vendor/workerman/webman-framework/tests/CoroutineControllerLoadTest.php new file mode 100644 index 0000000..559d629 --- /dev/null +++ b/vendor/workerman/webman-framework/tests/CoroutineControllerLoadTest.php @@ -0,0 +1,117 @@ +setValue(null, $appPath); + +$autoloadEntries = 0; +$autoloads = 0; +spl_autoload_register(function ($class) use ($base, &$autoloadEntries, &$autoloads) { + if (!str_starts_with($class, 'app\\')) { + return; + } + $file = $base . '/' . str_replace('\\', '/', $class) . '.php'; + if (!is_file($file)) { + return; + } + if (Fiber::getCurrent() !== null) { + $autoloads++; + if ($autoloadEntries === 0) { + $autoloadEntries++; + Fiber::suspend(); + } + } + include $file; +}); + +Route::load([$base . '/config']); + +$preloaded = class_exists('app\controller\FooController', false) + && class_exists('app\controller\BaseController', false); +echo 'preloaded at worker start: ' . var_export($preloaded, true) . "\n"; + +$getController = new ReflectionMethod(App::class, 'getController'); + +$results = []; +$fibers = []; +for ($i = 0; $i < 2; $i++) { + $fibers[$i] = new Fiber(function () use ($getController, &$results, $i) { + $results[$i] = $getController->invoke(null, 'app\controller\FooController'); + }); +} +$fibers[0]->start(); +$fibers[1]->start(); +foreach ($fibers as $fiber) { + while ($fiber->isSuspended()) { + $fiber->resume(); + } +} + +foreach ($results as $i => $result) { + echo 'fiber ' . $i . ' getController: ' . var_export($result, true) . "\n"; +} +echo 'autoloader entered at request time: ' . var_export($autoloads > 0, true) . "\n"; + +register_shutdown_function(function () use ($base) { + if (is_dir($base)) { + exec('rm -rf ' . escapeshellarg($base)); + } +}); + +if (!$preloaded) { + $failures[] = 'controllers were not loaded during Route::load at worker start'; +} +if ($results[0] === false || $results[1] === false) { + $failures[] = 'concurrent first resolution dropped a request: getController returned false'; +} +if ($results[0] !== 'app\controller\FooController' || $results[1] !== 'app\controller\FooController') { + $failures[] = 'both fibers must resolve the controller class name'; +} +if ($autoloads > 0) { + $failures[] = 'controller class loading must not happen at request time'; +} + +if ($failures) { + foreach ($failures as $failure) { + echo 'FAIL: ' . $failure . "\n"; + } + exit(1); +} +echo "PASS\n"; diff --git a/vendor/workerman/workerman/MIT-LICENSE.txt b/vendor/workerman/workerman/MIT-LICENSE.txt new file mode 100644 index 0000000..6f6ce35 --- /dev/null +++ b/vendor/workerman/workerman/MIT-LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2009-2025 walkor and contributors (see https://github.com/walkor/workerman/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/workerman/workerman/README.md b/vendor/workerman/workerman/README.md new file mode 100644 index 0000000..58cc9a6 --- /dev/null +++ b/vendor/workerman/workerman/README.md @@ -0,0 +1,477 @@ +# Workerman +[![Gitter](https://badges.gitter.im/walkor/Workerman.svg)](https://gitter.im/walkor/Workerman?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge) +[![Latest Stable Version](https://poser.pugx.org/workerman/workerman/v/stable)](https://packagist.org/packages/workerman/workerman) +[![Total Downloads](https://poser.pugx.org/workerman/workerman/downloads)](https://packagist.org/packages/workerman/workerman) +[![Monthly Downloads](https://poser.pugx.org/workerman/workerman/d/monthly)](https://packagist.org/packages/workerman/workerman) +[![Daily Downloads](https://poser.pugx.org/workerman/workerman/d/daily)](https://packagist.org/packages/workerman/workerman) +[![License](https://poser.pugx.org/workerman/workerman/license)](https://packagist.org/packages/workerman/workerman) + +## What is it +Workerman is an asynchronous event-driven PHP framework with high performance to build fast and scalable network applications. It supports HTTP, WebSocket, custom protocols, coroutines, and connection pools, making it ideal for handling high-concurrency scenarios efficiently. + +## Requires +A POSIX compatible operating system (Linux, OSX, BSD) +POSIX and PCNTL extensions required +Event/Swoole/Swow extension recommended for better performance + +## Installation + +``` +composer require workerman/workerman +``` + +## Documentation + +[https://manual.workerman.net](https://manual.workerman.net) + +## Basic Usage + +### A websocket server +```php +onConnect = function ($connection) { + echo "New connection\n"; +}; + +// Emitted when data received +$ws_worker->onMessage = function ($connection, $data) { + // Send hello $data + $connection->send('Hello ' . $data); +}; + +// Emitted when connection closed +$ws_worker->onClose = function ($connection) { + echo "Connection closed\n"; +}; + +// Run worker +Worker::runAll(); +``` + +### An http server +```php +use Workerman\Worker; + +require_once __DIR__ . '/vendor/autoload.php'; + +// #### http worker #### +$http_worker = new Worker('http://0.0.0.0:2345'); + +// 4 processes +$http_worker->count = 4; + +// Emitted when data received +$http_worker->onMessage = function ($connection, $request) { + //$request->get(); + //$request->post(); + //$request->header(); + //$request->cookie(); + //$request->session(); + //$request->uri(); + //$request->path(); + //$request->method(); + + // Send data to client + $connection->send("Hello World"); +}; + +// Run all workers +Worker::runAll(); +``` + +### A tcp server +```php +use Workerman\Worker; + +require_once __DIR__ . '/vendor/autoload.php'; + +// #### create socket and listen 1234 port #### +$tcp_worker = new Worker('tcp://0.0.0.0:1234'); + +// 4 processes +$tcp_worker->count = 4; + +// Emitted when new connection come +$tcp_worker->onConnect = function ($connection) { + echo "New Connection\n"; +}; + +// Emitted when data received +$tcp_worker->onMessage = function ($connection, $data) { + // Send data to client + $connection->send("Hello $data \n"); +}; + +// Emitted when connection is closed +$tcp_worker->onClose = function ($connection) { + echo "Connection closed\n"; +}; + +Worker::runAll(); +``` + +### Enable SSL +```php + [ + 'local_cert' => '/your/path/of/server.pem', + 'local_pk' => '/your/path/of/server.key', + 'verify_peer' => false, + ] +]; + +// Create a Websocket server with ssl context. +$ws_worker = new Worker('websocket://0.0.0.0:2346', $context); + +// Enable SSL. WebSocket+SSL means that Secure WebSocket (wss://). +// The similar approaches for Https etc. +$ws_worker->transport = 'ssl'; + +$ws_worker->onMessage = function ($connection, $data) { + // Send hello $data + $connection->send('Hello ' . $data); +}; + +Worker::runAll(); +``` + +### AsyncTcpConnection (tcp/ws/text/frame etc...) +```php + +use Workerman\Worker; +use Workerman\Connection\AsyncTcpConnection; + +require_once __DIR__ . '/vendor/autoload.php'; + +$worker = new Worker(); +$worker->onWorkerStart = function () { + // Websocket protocol for client. + $ws_connection = new AsyncTcpConnection('ws://echo.websocket.org:80'); + $ws_connection->onConnect = function ($connection) { + $connection->send('Hello'); + }; + $ws_connection->onMessage = function ($connection, $data) { + echo "Recv: $data\n"; + }; + $ws_connection->onError = function ($connection, $code, $msg) { + echo "Error: $msg\n"; + }; + $ws_connection->onClose = function ($connection) { + echo "Connection closed\n"; + }; + $ws_connection->connect(); +}; + +Worker::runAll(); +``` + +### Coroutine + +Coroutine is used to create coroutines, enabling the execution of asynchronous tasks to improve concurrency performance. + +```php +eventLoop = Swoole::class; // Or Swow::class or Fiber::class + +$worker->onMessage = function (TcpConnection $connection, Request $request) { + Coroutine::create(function () { + echo file_get_contents("http://www.example.com/event/notify"); + }); + $connection->send('ok'); +}; + +Worker::runAll(); +``` + +> Note: Coroutine require Swoole extension or Swow extension or [Fiber revolt/event-loop](https://github.com/revoltphp/event-loop), and the same applies below + +### Barrier +Barrier is used to manage concurrency and synchronization in coroutines. It allows tasks to run concurrently and waits until all tasks are completed, ensuring process synchronization. + +```php +eventLoop = Swoole::class; // Or Swow::class or Fiber::class +$worker->onMessage = function (TcpConnection $connection, Request $request) { + $barrier = Barrier::create(); + for ($i=1; $i<5; $i++) { + Coroutine::create(function () use ($barrier, $i) { + file_get_contents("http://127.0.0.1:8002?task_id=$i"); + }); + } + // Wait all coroutine done + Barrier::wait($barrier); + $connection->send('All Task Done'); +}; + +// Task Server +$task = new Worker('http://0.0.0.0:8002'); +$task->onMessage = function (TcpConnection $connection, Request $request) { + $task_id = $request->get('task_id'); + $message = "Task $task_id Done"; + echo $message . PHP_EOL; + $connection->close($message); +}; + +Worker::runAll(); +``` + +### Parallel +Parallel executes multiple tasks concurrently and collects results. Use add to add tasks and wait to wait for completion and get results. Unlike Barrier, Parallel directly returns the results of each task. + +```php +eventLoop = Swoole::class; // Or Swow::class or Fiber::class +$worker->onMessage = function (TcpConnection $connection, Request $request) { + $parallel = new Parallel(); + for ($i=1; $i<5; $i++) { + $parallel->add(function () use ($i) { + return file_get_contents("http://127.0.0.1:8002?task_id=$i"); + }); + } + $results = $parallel->wait(); + $connection->send(json_encode($results)); // Response: ["Task 1 Done","Task 2 Done","Task 3 Done","Task 4 Done"] +}; + +// Task Server +$task = new Worker('http://0.0.0.0:8002'); +$task->onMessage = function (TcpConnection $connection, Request $request) { + $task_id = $request->get('task_id'); + $message = "Task $task_id Done"; + $connection->close($message); +}; + +Worker::runAll(); +``` + +### Channel + +Channel is a mechanism for communication between coroutines. One coroutine can push data into the channel, while another can pop data from it, enabling synchronization and data sharing between coroutines. + +```php +eventLoop = Swoole::class; // Or Swow::class or Fiber::class +$worker->onMessage = function (TcpConnection $connection, Request $request) { + $channel = new Channel(2); + Coroutine::create(function () use ($channel) { + $channel->push('Task 1 Done'); + }); + Coroutine::create(function () use ($channel) { + $channel->push('Task 2 Done'); + }); + $result = []; + for ($i = 0; $i < 2; $i++) { + $result[] = $channel->pop(); + } + $connection->send(json_encode($result)); // Response: ["Task 1 Done","Task 2 Done"] +}; +Worker::runAll(); +``` + +### Pool + +Pool is used to manage connection or resource pools, improving performance by reusing resources (e.g., database connections). It supports acquiring, returning, creating, and destroying resources. + +```php +setConnectionCreator(function () use ($host, $port) { + $redis = new \Redis(); + $redis->connect($host, $port); + return $redis; + }); + $pool->setConnectionCloser(function ($redis) { + $redis->close(); + }); + $pool->setHeartbeatChecker(function ($redis) { + $redis->ping(); + }); + $this->pool = $pool; + } + public function get(): \Redis + { + return $this->pool->get(); + } + public function put($redis): void + { + $this->pool->put($redis); + } +} + +// Http Server +$worker = new Worker('http://0.0.0.0:8001'); +$worker->eventLoop = Swoole::class; // Or Swow::class or Fiber::class +$worker->onMessage = function (TcpConnection $connection, Request $request) { + static $pool; + if (!$pool) { + $pool = new RedisPool('127.0.0.1', 6379, 10); + } + $redis = $pool->get(); + $redis->set('key', 'hello'); + $value = $redis->get('key'); + $pool->put($redis); + $connection->send($value); +}; + +Worker::runAll(); +``` + + +### Pool for automatic acquisition and release + +```php +get(); + Context::set('pdo', $pdo); + // When the coroutine is destroyed, return the connection to the pool + Coroutine::defer(function () use ($pdo) { + self::$pool->put($pdo); + }); + } + return call_user_func_array([$pdo, $name], $arguments); + } + private static function initializePool(): void + { + self::$pool = new Pool(10); + self::$pool->setConnectionCreator(function () { + return new \PDO('mysql:host=127.0.0.1;dbname=your_database', 'your_username', 'your_password'); + }); + self::$pool->setConnectionCloser(function ($pdo) { + $pdo = null; + }); + self::$pool->setHeartbeatChecker(function ($pdo) { + $pdo->query('SELECT 1'); + }); + } +} + +// Http Server +$worker = new Worker('http://0.0.0.0:8001'); +$worker->eventLoop = Swoole::class; // Or Swow::class or Fiber::class +$worker->onMessage = function (TcpConnection $connection, Request $request) { + $value = Db::query('SELECT NOW() as now')->fetchAll(); + $connection->send(json_encode($value)); +}; + +Worker::runAll(); +``` + +## Available commands +```php start.php start ``` +```php start.php start -d ``` +```php start.php status ``` +```php start.php status -d ``` +```php start.php connections``` +```php start.php stop ``` +```php start.php stop -g ``` +```php start.php restart ``` +```php start.php reload ``` +```php start.php reload -g ``` + +# Benchmarks +https://www.techempower.com/benchmarks/#section=data-r19&hw=ph&test=plaintext&l=zik073-1r + + +### Supported by + +[![JetBrains logo.](https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.svg)](https://jb.gg/OpenSourceSupport) + + +## Other links with workerman + +[webman](https://github.com/walkor/webman) +[AdapterMan](https://github.com/joanhey/AdapterMan) + +## Donate +PayPal + +## LICENSE + +Workerman is released under the [MIT license](https://github.com/walkor/workerman/blob/master/MIT-LICENSE.txt). diff --git a/vendor/workerman/workerman/SECURITY.md b/vendor/workerman/workerman/SECURITY.md new file mode 100644 index 0000000..c910997 --- /dev/null +++ b/vendor/workerman/workerman/SECURITY.md @@ -0,0 +1,6 @@ +# Security Policy + + +## Reporting a Vulnerability + +Please contact by email walkor@workerman.net diff --git a/vendor/workerman/workerman/composer.json b/vendor/workerman/workerman/composer.json new file mode 100644 index 0000000..2dea8d2 --- /dev/null +++ b/vendor/workerman/workerman/composer.json @@ -0,0 +1,65 @@ +{ + "name": "workerman/workerman", + "type": "library", + "keywords": [ + "event-loop", + "asynchronous", + "http", + "framework" + ], + "homepage": "https://www.workerman.net", + "license": "MIT", + "description": "An asynchronous event driven PHP framework for easily building fast, scalable network applications.", + "authors": [ + { + "name": "walkor", + "email": "walkor@workerman.net", + "homepage": "https://www.workerman.net", + "role": "Developer" + } + ], + "support": { + "email": "walkor@workerman.net", + "issues": "https://github.com/walkor/workerman/issues", + "forum": "https://www.workerman.net/questions", + "wiki": "https://www.workerman.net/doc/workerman/", + "source": "https://github.com/walkor/workerman" + }, + "require": { + "php": ">=8.1", + "ext-json": "*", + "workerman/coroutine": "^1.1 || dev-main" + }, + "suggest": { + "ext-event": "For better performance. " + }, + "autoload": { + "psr-4": { + "Workerman\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/" + } + }, + "minimum-stability": "dev", + "conflict": { + "ext-swow": " + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Connection; + +use Exception; +use RuntimeException; +use stdClass; +use Throwable; +use Workerman\Events\Swoole; +use Workerman\Timer; +use Workerman\Worker; +use function class_exists; +use function explode; +use function function_exists; +use function is_resource; +use function method_exists; +use function microtime; +use function parse_url; +use function socket_import_stream; +use function socket_set_option; +use function stream_context_create; +use function stream_set_blocking; +use function stream_set_read_buffer; +use function stream_socket_client; +use function stream_socket_get_name; +use function ucfirst; +use const DIRECTORY_SEPARATOR; +use const PHP_INT_MAX; +use const SO_KEEPALIVE; +use const SOL_SOCKET; +use const SOL_TCP; +use const STREAM_CLIENT_ASYNC_CONNECT; +use const TCP_NODELAY; + +/** + * AsyncTcpConnection. + */ +class AsyncTcpConnection extends TcpConnection +{ + /** + * PHP built-in protocols. + * + * @var array + */ + public const BUILD_IN_TRANSPORTS = [ + 'tcp' => 'tcp', + 'udp' => 'udp', + 'unix' => 'unix', + 'ssl' => 'ssl', + 'sslv2' => 'sslv2', + 'sslv3' => 'sslv3', + 'tls' => 'tls' + ]; + + /** + * Emitted when socket connection is successfully established. + * + * @var ?callable + */ + public $onConnect = null; + + /** + * Emitted when websocket handshake completed (Only work when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketConnect = null; + + /** + * Transport layer protocol. + * + * @var string + */ + public string $transport = 'tcp'; + + /** + * Socks5 proxy. + * + * @var string + */ + public string $proxySocks5 = ''; + + /** + * Http proxy. + * + * @var string + */ + public string $proxyHttp = ''; + + /** + * Http proxy authorization header value. + * + * @var string + */ + public string $proxyAuthorization = ''; + + /** + * Socks5 proxy username. + * + * @var string + */ + public string $proxySocks5Username = ''; + + /** + * Socks5 proxy password. + * + * @var string + */ + public string $proxySocks5Password = ''; + + /** + * Status. + * + * @var int + */ + protected int $status = self::STATUS_INITIAL; + + /** + * Remote host. + * + * @var string + */ + protected string $remoteHost = ''; + + /** + * Remote port. + * + * @var int + */ + protected int $remotePort = 80; + + /** + * Connect start time. + * + * @var float + */ + protected float $connectStartTime = 0; + + /** + * Remote URI. + * + * @var string + */ + protected string $remoteURI = ''; + + /** + * Context option. + * + * @var array + */ + protected array $socketContext = []; + + /** + * Reconnect timer. + * + * @var int + */ + protected int $reconnectTimer = 0; + + /** + * Construct. + * + * @param string $remoteAddress + * @param array $socketContext + */ + public function __construct(string $remoteAddress, array $socketContext = []) + { + $addressInfo = parse_url($remoteAddress); + if (!$addressInfo) { + [$scheme, $this->remoteAddress] = explode(':', $remoteAddress, 2); + if ('unix' === strtolower($scheme)) { + $this->remoteAddress = substr($remoteAddress, strpos($remoteAddress, '/') + 2); + } + if (!$this->remoteAddress) { + throw new RuntimeException('Bad remoteAddress'); + } + } else { + $addressInfo['port'] ??= 0; + $addressInfo['path'] ??= '/'; + if (!isset($addressInfo['query'])) { + $addressInfo['query'] = ''; + } else { + $addressInfo['query'] = '?' . $addressInfo['query']; + } + $this->remoteHost = $addressInfo['host']; + $this->remotePort = $addressInfo['port']; + $this->remoteURI = "{$addressInfo['path']}{$addressInfo['query']}"; + $scheme = $addressInfo['scheme'] ?? 'tcp'; + $this->remoteAddress = 'unix' === strtolower($scheme) + ? substr($remoteAddress, strpos($remoteAddress, '/') + 2) + : $this->remoteHost . ':' . $this->remotePort; + } + + $this->id = $this->realId = self::$idRecorder++; + if (PHP_INT_MAX === self::$idRecorder) { + self::$idRecorder = 0; + } + // Check application layer protocol class. + if (!isset(self::BUILD_IN_TRANSPORTS[$scheme])) { + // Validate scheme contains only safe characters for class name resolution. + if (!preg_match('/^[a-zA-Z][a-zA-Z0-9]*$/', $scheme)) { + throw new RuntimeException("Invalid protocol scheme '$scheme'"); + } + $scheme = ucfirst($scheme); + $this->protocol = '\\Protocols\\' . $scheme; + if (!class_exists($this->protocol)) { + $this->protocol = "\\Workerman\\Protocols\\$scheme"; + if (!class_exists($this->protocol)) { + throw new RuntimeException("class \\Protocols\\$scheme not exist"); + } + } + } else { + $this->transport = self::BUILD_IN_TRANSPORTS[$scheme]; + } + + // For statistics. + ++self::$statistics['connection_count']; + $this->maxSendBufferSize = self::$defaultMaxSendBufferSize; + $this->maxPackageSize = self::$defaultMaxPackageSize; + $this->socketContext = $socketContext; + static::$connections[$this->realId] = $this; + $this->context = new stdClass; + } + + /** + * Reconnect. + * + * @param int $after + * @return void + */ + public function reconnect(int $after = 0): void + { + $this->status = self::STATUS_INITIAL; + static::$connections[$this->realId] = $this; + if ($this->reconnectTimer) { + Timer::del($this->reconnectTimer); + } + if ($after > 0) { + $this->reconnectTimer = Timer::add($after, $this->connect(...), null, false); + return; + } + $this->connect(); + } + + /** + * Do connect. + * + * @return void + */ + public function connect(): void + { + if ($this->status !== self::STATUS_INITIAL && $this->status !== self::STATUS_CLOSING && + $this->status !== self::STATUS_CLOSED) { + return; + } + + $this->eventLoop ??= Worker::getEventLoop(); + + $this->status = self::STATUS_CONNECTING; + $this->connectStartTime = microtime(true); + if ($this->eventLoop instanceof Swoole) { + // The Swoole hook turns stream_socket_client() into a blocking connect that yields to other coroutines + // (DNS lookup included). A process-wide error handler installed around it would swallow every warning + // those coroutines raise meanwhile, bypassing the application's handler; "@" is saved per coroutine. + $this->socket = @$this->openSocket($errno, $err_str); + } else { + set_error_handler(static fn(...$args): bool => false); + $this->socket = $this->openSocket($errno, $err_str); + restore_error_handler(); + } + // If failed attempt to emit onError callback. + if (!$this->socket || !is_resource($this->socket)) { + $this->emitError(static::CONNECT_FAIL, $err_str); + if ($this->status === self::STATUS_CLOSING) { + $this->destroy(); + } + if ($this->status === self::STATUS_CLOSED) { + $this->onConnect = null; + } + return; + } + + $this->eventLoop ??= Worker::getEventLoop(); + + // Add socket to global event loop waiting connection is successfully established or failed. + $this->eventLoop->onWritable($this->socket, $this->checkConnection(...)); + // For windows. + if (DIRECTORY_SEPARATOR === '\\' && method_exists($this->eventLoop, 'onExcept')) { + $this->eventLoop->onExcept($this->socket, $this->checkConnection(...)); + } + } + + /** + * Open the client socket asynchronously. + * + * @param int|null $errno + * @param string|null $errStr + * @return resource|false + */ + private function openSocket(?int &$errno, ?string &$errStr) + { + if ($this->transport === 'unix') { + return stream_socket_client("$this->transport://$this->remoteAddress", $errno, $errStr, 0, + STREAM_CLIENT_ASYNC_CONNECT); + } + if (!$this->remotePort) { + $this->remotePort = $this->transport === 'ssl' ? 443 : 80; + $this->remoteAddress = $this->remoteHost . ':' . $this->remotePort; + } + if ($this->proxySocks5) { + $this->socketContext['ssl']['peer_name'] = $this->remoteHost; + $context = stream_context_create($this->socketContext); + return stream_socket_client("tcp://$this->proxySocks5", $errno, $errStr, 0, STREAM_CLIENT_ASYNC_CONNECT, $context); + } + if ($this->proxyHttp) { + $this->socketContext['ssl']['peer_name'] = $this->remoteHost; + $context = stream_context_create($this->socketContext); + return stream_socket_client("tcp://$this->proxyHttp", $errno, $errStr, 0, STREAM_CLIENT_ASYNC_CONNECT, $context); + } + if ($this->socketContext) { + $context = stream_context_create($this->socketContext); + return stream_socket_client("tcp://$this->remoteHost:$this->remotePort", + $errno, $errStr, 0, STREAM_CLIENT_ASYNC_CONNECT, $context); + } + return stream_socket_client("tcp://$this->remoteHost:$this->remotePort", + $errno, $errStr, 0, STREAM_CLIENT_ASYNC_CONNECT); + } + + /** + * Try to emit onError callback. + * + * @param int $code + * @param mixed $msg + * @return void + */ + protected function emitError(int $code, mixed $msg): void + { + $this->status = self::STATUS_CLOSING; + if ($this->onError) { + try { + ($this->onError)($this, $code, $msg); + } catch (Throwable $e) { + $this->error($e); + } + } + } + + /** + * CancelReconnect. + */ + public function cancelReconnect(): void + { + if ($this->reconnectTimer) { + Timer::del($this->reconnectTimer); + $this->reconnectTimer = 0; + } + } + + /** + * Get remote address. + * + * @return string + */ + public function getRemoteHost(): string + { + return $this->remoteHost; + } + + /** + * Get remote URI. + * + * @return string + */ + public function getRemoteURI(): string + { + return $this->remoteURI; + } + + /** + * Check connection is successfully established or failed. + * + * @return void + */ + public function checkConnection(): void + { + // Remove EV_EXPECT for windows. + if (DIRECTORY_SEPARATOR === '\\' && method_exists($this->eventLoop, 'offExcept')) { + $this->eventLoop->offExcept($this->socket); + } + // Remove write listener. + $this->eventLoop->offWritable($this->socket); + + if ($this->status !== self::STATUS_CONNECTING) { + return; + } + + // Check socket state. + if ($address = stream_socket_get_name($this->socket, true)) { + // Proxy + if ($this->proxySocks5) { + if ($this->proxySocks5Username !== '' || $this->proxySocks5Password !== '') { + fwrite($this->socket, chr(5) . chr(2) . chr(0) . chr(2)); + $response = fread($this->socket, 512); + if (!$response || ord($response[1]) !== 2) { + $this->emitError(static::CONNECT_FAIL, 'SOCKS5 authentication method negotiation failed'); + if ($this->status === self::STATUS_CLOSING) { + $this->destroy(); + } + if ($this->status === self::STATUS_CLOSED) { + $this->onConnect = null; + } + return; + } + $user = $this->proxySocks5Username; + $pass = $this->proxySocks5Password; + fwrite($this->socket, chr(1) . chr(strlen($user)) . $user . chr(strlen($pass)) . $pass); + $authResponse = fread($this->socket, 512); + if (!$authResponse || ord($authResponse[1]) !== 0) { + $this->emitError(static::CONNECT_FAIL, 'SOCKS5 authentication failed'); + if ($this->status === self::STATUS_CLOSING) { + $this->destroy(); + } + if ($this->status === self::STATUS_CLOSED) { + $this->onConnect = null; + } + return; + } + } else { + fwrite($this->socket, chr(5) . chr(1) . chr(0)); + fread($this->socket, 512); + } + fwrite($this->socket, chr(5) . chr(1) . chr(0) . chr(3) . chr(strlen($this->remoteHost)) . $this->remoteHost . pack("n", $this->remotePort)); + fread($this->socket, 512); + } elseif ($this->proxyHttp) { + $str = "CONNECT $this->remoteHost:$this->remotePort HTTP/1.1\r\n"; + $str .= "Host: $this->remoteHost:$this->remotePort\r\n"; + if ($this->proxyAuthorization !== '') { + $str .= "Proxy-Authorization: $this->proxyAuthorization\r\n"; + } + $str .= "Proxy-Connection: keep-alive\r\n\r\n"; + fwrite($this->socket, $str); + $proxyResponse = fread($this->socket, 512); + if ($proxyResponse && preg_match('/^HTTP\/\d\.\d\s+(\d{3})(?:\s+([^\r\n]+))?/i', $proxyResponse, $match)) { + if ((int)$match[1] !== 200) { + $reason = $match[2] ?? 'Proxy CONNECT failed'; + $this->emitError(static::CONNECT_FAIL, "Proxy CONNECT failed: {$match[1]} $reason"); + if ($this->status === self::STATUS_CLOSING) { + $this->destroy(); + } + if ($this->status === self::STATUS_CLOSED) { + $this->onConnect = null; + } + return; + } + } + } + if (!is_resource($this->socket)) { + $this->emitError(static::CONNECT_FAIL, 'connect ' . $this->remoteAddress . ' fail after ' . round(microtime(true) - $this->connectStartTime, 4) . ' seconds'); + if ($this->status === self::STATUS_CLOSING) { + $this->destroy(); + } + if ($this->status === self::STATUS_CLOSED) { + $this->onConnect = null; + } + return; + } + // Nonblocking. + stream_set_blocking($this->socket, false); + stream_set_read_buffer($this->socket, 0); + // Try to open keepalive for tcp and disable Nagle algorithm. + if (function_exists('socket_import_stream') && $this->transport === 'tcp') { + $socket = socket_import_stream($this->socket); + socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); + socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); + if (defined('TCP_KEEPIDLE') && defined('TCP_KEEPINTVL') && defined('TCP_KEEPCNT')) { + socket_set_option($socket, SOL_TCP, TCP_KEEPIDLE, static::TCP_KEEPALIVE_INTERVAL); + socket_set_option($socket, SOL_TCP, TCP_KEEPINTVL, static::TCP_KEEPALIVE_INTERVAL); + socket_set_option($socket, SOL_TCP, TCP_KEEPCNT, 1); + } + } + // SSL handshake. + if ($this->transport === 'ssl') { + $this->sslHandshakeCompleted = $this->doSslHandshake($this->socket); + if ($this->sslHandshakeCompleted === 0) { + // Keep the connection in CONNECTING until TLS is actually established. Retrying + // through checkConnection() would repeat proxy negotiation, while also watching a + // connected socket for writes would keep level-triggered loops permanently awake. + $this->eventLoop->onReadable( + $this->socket, + fn ($socket) => $this->checkSslHandshake($socket, $address) + ); + return; + } + if ($this->sslHandshakeCompleted === false) { + return; + } + } + $this->markEstablished($address); + } else { + // Connection failed. + $this->emitError(static::CONNECT_FAIL, 'connect ' . $this->remoteAddress . ' fail after ' . round(microtime(true) - $this->connectStartTime, 4) . ' seconds'); + if ($this->status === self::STATUS_CLOSING) { + $this->destroy(); + } + if ($this->status === self::STATUS_CLOSED) { + $this->onConnect = null; + } + } + } + + /** + * Continue an asynchronous SSL handshake after the peer supplied more data. + * + * @param resource $socket + * @param string $address + * @return void + */ + private function checkSslHandshake($socket, string $address): void + { + if ($this->status !== self::STATUS_CONNECTING) { + return; + } + + $this->sslHandshakeCompleted = $this->doSslHandshake($socket); + if ($this->sslHandshakeCompleted !== true) { + return; + } + + $this->markEstablished($address); + } + + /** + * Finish connection setup after TCP and, when applicable, SSL are established. + * + * @param string $address + * @return void + */ + private function markEstablished(string $address): void + { + // Register a listener waiting read event. + $this->eventLoop->onReadable($this->socket, $this->baseRead(...)); + + $this->status = self::STATUS_ESTABLISHED; + $this->remoteAddress = $address; + + // Flush data queued before the connection (and SSL handshake) completed. + if ($this->sendBuffer) { + $this->eventLoop->onWritable($this->socket, $this->baseWrite(...)); + } + + // Try to emit onConnect callback. + if ($this->onConnect) { + try { + ($this->onConnect)($this); + } catch (Throwable $e) { + $this->error($e); + } + } + // Try to emit protocol::onConnect + if ($this->protocol && method_exists($this->protocol, 'onConnect')) { + try { + $this->protocol::onConnect($this); + } catch (Throwable $e) { + $this->error($e); + } + } + } +} diff --git a/vendor/workerman/workerman/src/Connection/AsyncUdpConnection.php b/vendor/workerman/workerman/src/Connection/AsyncUdpConnection.php new file mode 100644 index 0000000..97b72f8 --- /dev/null +++ b/vendor/workerman/workerman/src/Connection/AsyncUdpConnection.php @@ -0,0 +1,222 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Connection; + +use Exception; +use RuntimeException; +use Throwable; +use Workerman\Protocols\ProtocolInterface; +use Workerman\Worker; +use function class_exists; +use function is_resource; +use function explode; +use function fclose; +use function stream_context_create; +use function stream_set_blocking; +use function stream_socket_client; +use function stream_socket_recvfrom; +use function stream_socket_sendto; +use function strlen; +use function substr; +use function ucfirst; +use const STREAM_CLIENT_CONNECT; + +/** + * AsyncUdpConnection. + */ +class AsyncUdpConnection extends UdpConnection +{ + /** + * Emitted when socket connection is successfully established. + * + * @var ?callable + */ + public $onConnect = null; + + /** + * Emitted when socket connection closed. + * + * @var ?callable + */ + public $onClose = null; + + /** + * Connected or not. + * + * @var bool + */ + protected bool $connected = false; + + /** + * Context option. + * + * @var array + */ + protected array $contextOption = []; + + /** + * Construct. + * + * @param string $remoteAddress + * @throws Throwable + */ + public function __construct($remoteAddress, $contextOption = []) + { + // Get the application layer communication protocol and listening address. + [$scheme, $address] = explode(':', $remoteAddress, 2); + // Check application layer protocol class. + if ($scheme !== 'udp') { + // Validate scheme contains only safe characters for class name resolution. + if (!preg_match('/^[a-zA-Z][a-zA-Z0-9]*$/', $scheme)) { + throw new RuntimeException("Invalid protocol scheme '$scheme'"); + } + $scheme = ucfirst($scheme); + $this->protocol = '\\Protocols\\' . $scheme; + if (!class_exists($this->protocol)) { + $this->protocol = "\\Workerman\\Protocols\\$scheme"; + if (!class_exists($this->protocol)) { + throw new RuntimeException("class \\Protocols\\$scheme not exist"); + } + } + } + + $this->remoteAddress = substr($address, 2); + $this->contextOption = $contextOption; + } + + /** + * For udp package. + * + * @param resource $socket + * @return void + */ + public function baseRead($socket): void + { + $recvBuffer = stream_socket_recvfrom($socket, static::MAX_UDP_PACKAGE_SIZE, 0, $remoteAddress); + if (false === $recvBuffer || empty($remoteAddress)) { + return; + } + + if ($this->onMessage) { + if ($this->protocol) { + $recvBuffer = $this->protocol::decode($recvBuffer, $this); + } + ++ConnectionInterface::$statistics['total_request']; + try { + ($this->onMessage)($this, $recvBuffer); + } catch (Throwable $e) { + $this->error($e); + } + } + } + + /** + * Close connection. + * + * @param mixed $data + * @param bool $raw + * @return void + */ + public function close(mixed $data = null, bool $raw = false): void + { + if ($data !== null) { + $this->send($data, $raw); + } + if ($this->eventLoop) { + $this->eventLoop->offReadable($this->socket); + } + if (is_resource($this->socket)) { + fclose($this->socket); + } + $this->socket = null; // intentionally nullable to mark closed state + $this->connected = false; + // Try to emit onClose callback. + if ($this->onClose) { + try { + ($this->onClose)($this); + } catch (Throwable $e) { + $this->error($e); + } + } + $this->onConnect = $this->onMessage = $this->onClose = $this->eventLoop = $this->errorHandler = null; + } + + /** + * Sends data on the connection. + * + * @param mixed $sendBuffer + * @param bool $raw + * @return bool|null + */ + public function send(mixed $sendBuffer, bool $raw = false): bool|null + { + if (false === $raw && $this->protocol) { + $sendBuffer = $this->protocol::encode($sendBuffer, $this); + if ($sendBuffer === '') { + return null; + } + } + if ($this->connected === false) { + $this->connect(); + } + return strlen($sendBuffer) === stream_socket_sendto($this->socket, $sendBuffer); + } + + /** + * Connect. + * + * @return void + */ + public function connect(): void + { + if ($this->connected === true) { + return; + } + + $this->eventLoop ??= Worker::getEventLoop(); + + if ($this->contextOption) { + $context = stream_context_create($this->contextOption); + $this->socket = stream_socket_client("udp://$this->remoteAddress", $errno, $errmsg, + 30, STREAM_CLIENT_CONNECT, $context); + } else { + $this->socket = stream_socket_client("udp://$this->remoteAddress", $errno, $errmsg); + } + + if (!$this->socket) { + Worker::safeEcho((string)(new Exception($errmsg))); + $this->eventLoop = null; + return; + } + + $this->eventLoop ??= Worker::getEventLoop(); + + stream_set_blocking($this->socket, false); + if ($this->onMessage) { + $this->eventLoop->onReadable($this->socket, $this->baseRead(...)); + } + $this->connected = true; + // Try to emit onConnect callback. + if ($this->onConnect) { + try { + ($this->onConnect)($this); + } catch (Throwable $e) { + $this->error($e); + } + } + } +} diff --git a/vendor/workerman/workerman/src/Connection/ConnectionInterface.php b/vendor/workerman/workerman/src/Connection/ConnectionInterface.php new file mode 100644 index 0000000..a120442 --- /dev/null +++ b/vendor/workerman/workerman/src/Connection/ConnectionInterface.php @@ -0,0 +1,187 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Connection; + +use Throwable; +use Workerman\Events\Event; +use Workerman\Events\EventInterface; +use Workerman\Worker; +use AllowDynamicProperties; + +/** + * ConnectionInterface. + */ +#[AllowDynamicProperties] +abstract class ConnectionInterface +{ + /** + * Connect failed. + * + * @var int + */ + public const CONNECT_FAIL = 1; + + /** + * Send failed. + * + * @var int + */ + public const SEND_FAIL = 2; + + /** + * Statistics for status command. + * + * @var array + */ + public static array $statistics = [ + 'connection_count' => 0, + 'total_request' => 0, + 'throw_exception' => 0, + 'send_fail' => 0, + ]; + + /** + * Application layer protocol. + * The format is like this Workerman\\Protocols\\Http. + * + * @var ?class-string + */ + public ?string $protocol = null; + + /** + * Emitted when data is received. + * + * @var ?callable + */ + public $onMessage = null; + + /** + * Emitted when the other end of the socket sends a FIN packet. + * + * @var ?callable + */ + public $onClose = null; + + /** + * Emitted when an error occurs with connection. + * + * @var ?callable + */ + public $onError = null; + + /** + * @var ?EventInterface + */ + public ?EventInterface $eventLoop = null; + + /** + * @var ?callable + */ + public $errorHandler = null; + + /** + * Sends data on the connection. + * + * @param mixed $sendBuffer + * @param bool $raw + * @return bool|null + */ + abstract public function send(mixed $sendBuffer, bool $raw = false): bool|null; + + /** + * Get remote IP. + * + * @return string + */ + abstract public function getRemoteIp(): string; + + /** + * Get remote port. + * + * @return int + */ + abstract public function getRemotePort(): int; + + /** + * Get remote address. + * + * @return string + */ + abstract public function getRemoteAddress(): string; + + /** + * Get local IP. + * + * @return string + */ + abstract public function getLocalIp(): string; + + /** + * Get local port. + * + * @return int + */ + abstract public function getLocalPort(): int; + + /** + * Get local address. + * + * @return string + */ + abstract public function getLocalAddress(): string; + + /** + * Close connection. + * + * @param mixed $data + * @param bool $raw + * @return void + */ + abstract public function close(mixed $data = null, bool $raw = false): void; + + /** + * Is ipv4. + * + * return bool. + */ + abstract public function isIpV4(): bool; + + /** + * Is ipv6. + * + * return bool. + */ + abstract public function isIpV6(): bool; + + /** + * @param Throwable $exception + * @return void + */ + public function error(Throwable $exception): void + { + if (!$this->errorHandler) { + Worker::stopAll(250, $exception); + return; + } + try { + ($this->errorHandler)($exception); + } catch (Throwable $exception) { + Worker::stopAll(250, $exception); + return; + } + } +} diff --git a/vendor/workerman/workerman/src/Connection/TcpConnection.php b/vendor/workerman/workerman/src/Connection/TcpConnection.php new file mode 100644 index 0000000..78d1526 --- /dev/null +++ b/vendor/workerman/workerman/src/Connection/TcpConnection.php @@ -0,0 +1,1339 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ +declare(strict_types=1); + +namespace Workerman\Connection; + +use JsonSerializable; +use RuntimeException; +use stdClass; +use Throwable; +use Workerman\Events\EventInterface; +use Workerman\Events\Swoole; +use Workerman\Protocols\Http; +use Workerman\Protocols\Http\Request; +use Workerman\Timer; +use Workerman\Worker; + +use function ceil; +use function count; +use function fclose; +use function feof; +use function fread; +use function function_exists; +use function fwrite; +use function is_object; +use function is_resource; +use function key; +use function method_exists; +use function posix_getpid; +use function restore_error_handler; +use function set_error_handler; +use function stream_set_blocking; +use function stream_set_read_buffer; +use function stream_socket_shutdown; +use function stream_socket_enable_crypto; +use function stream_socket_get_name; +use function strlen; +use function strrchr; +use function strrpos; +use function substr; +use function var_export; + +use const PHP_INT_MAX; +use const STREAM_CRYPTO_METHOD_SSLv23_CLIENT; +use const STREAM_CRYPTO_METHOD_SSLv23_SERVER; +use const STREAM_CRYPTO_METHOD_SSLv2_CLIENT; +use const STREAM_CRYPTO_METHOD_SSLv2_SERVER; +use const STREAM_SHUT_WR; + +/** + * TcpConnection. + * @property string $websocketType + * @property string|null $websocketClientProtocol + * @property string|null $websocketOrigin + */ +class TcpConnection extends ConnectionInterface implements JsonSerializable +{ + /** + * Read buffer size. + * + * @var int + */ + public const READ_BUFFER_SIZE = 87380; + + /** + * Status initial. + * + * @var int + */ + public const STATUS_INITIAL = 0; + + /** + * Status connecting. + * + * @var int + */ + public const STATUS_CONNECTING = 1; + + /** + * Status connection established. + * + * @var int + */ + public const STATUS_ESTABLISHED = 2; + + /** + * Status ending (graceful close: write -> FIN -> linger/drain -> close). + * + * @var int + */ + public const STATUS_ENDING = 4; + + /** + * Status closing. + * + * @var int + */ + public const STATUS_CLOSING = 8; + + /** + * Status closed. + * + * @var int + */ + public const STATUS_CLOSED = 16; + + /** + * Maximum string length for cache + * + * @var int + */ + public const MAX_CACHE_STRING_LENGTH = 2048; + + /** + * Maximum cache size. + * + * @var int + */ + public const MAX_CACHE_SIZE = 512; + + /** + * Tcp keepalive interval. + */ + public const TCP_KEEPALIVE_INTERVAL = 55; + + /** + * Emitted when socket connection is successfully established. + * + * @var ?callable + */ + public $onConnect = null; + + /** + * Emitted before websocket handshake (Only called when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketConnect = null; + + /** + * Emitted after websocket handshake (Only called when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketConnected = null; + + /** + * Emitted when websocket connection is closed (Only called when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketClose = null; + + /** + * Emitted when a websocket ping frame is received (Only called when protocol is ws). + * Without a handler the ping is answered with a pong automatically. + * + * @var ?callable + */ + public $onWebSocketPing = null; + + /** + * Emitted when a websocket pong frame is received (Only called when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketPong = null; + + /** + * Emitted when data is received. + * + * @var ?callable + */ + public $onMessage = null; + + /** + * Emitted when the other end of the socket sends a FIN packet. + * + * @var ?callable + */ + public $onClose = null; + + /** + * Emitted when an error occurs with connection. + * + * @var ?callable + */ + public $onError = null; + + /** + * Emitted when the send buffer becomes full. + * + * @var ?callable + */ + public $onBufferFull = null; + + /** + * Emitted when send buffer becomes empty. + * + * @var ?callable + */ + public $onBufferDrain = null; + + /** + * Transport (tcp/udp/unix/ssl). + * + * @var string + */ + public string $transport = 'tcp'; + + /** + * Which worker belong to. + * + * @var ?Worker + */ + public ?Worker $worker = null; + + /** + * Bytes read. + * + * @var int + */ + public int $bytesRead = 0; + + /** + * Bytes written. + * + * @var int + */ + public int $bytesWritten = 0; + + /** + * Connection->id. + * + * @var int + */ + public int $id = 0; + + /** + * A copy of $worker->id which used to clean up the connection in worker->connections + * + * @var int + */ + protected int $realId = 0; + + /** + * Sets the maximum send buffer size for the current connection. + * OnBufferFull callback will be emitted When send buffer is full. + * + * @var int + */ + public int $maxSendBufferSize = 1048576; + + /** + * Context. + * + * @var ?stdClass + */ + public ?stdClass $context = null; + + /** + * Internal use only. Do not access or modify from application code. + * + * @internal Framework internal API + * @deprecated Do not set this property, use $response->header() or $response->widthHeaders() instead + * @var array + */ + public array $headers = []; + + /** + * Is safe. + * + * @var bool + */ + protected bool $isSafe = true; + + /** + * Default send buffer size. + * + * @var int + */ + public static int $defaultMaxSendBufferSize = 1048576; + + /** + * Sets the maximum acceptable packet size for the current connection. + * + * @var int + */ + public int $maxPackageSize = 1048576; + + /** + * Default maximum acceptable packet size. + * + * @var int + */ + public static int $defaultMaxPackageSize = 10485760; + + /** + * Default linger timeout for graceful end (seconds). + * + * @var float + */ + public static float $defaultLingerTimeout = 1.0; + + /** + * Linger timeout for graceful end (seconds). + * + * @var float + */ + public float $lingerTimeout = 1.0; + + /** + * Id recorder. + * + * @var int + */ + protected static int $idRecorder = 1; + + /** + * Socket + * + * @var resource + */ + protected $socket = null; + + /** + * Send buffer. + * + * @var string + */ + protected string $sendBuffer = ''; + + /** + * Receive buffer. + * + * @var string + */ + protected string $recvBuffer = ''; + + /** + * Current package length. + * + * @var int + */ + protected int $currentPackageLength = 0; + + /** + * Connection status. + * + * @var int + */ + protected int $status = self::STATUS_ESTABLISHED; + + /** + * Linger timer id for end(). + * + * @var int + */ + protected int $endLingerTimerId = 0; + + /** + * Whether write side has been shutdown (FIN sent) during end(). + * + * @var bool + */ + protected bool $endWriteShutdown = false; + + /** + * Remote address. + * + * @var string + */ + protected string $remoteAddress = ''; + + /** + * Is paused. + * + * @var bool + */ + protected bool $isPaused = false; + + /** + * SSL handshake completed or not. + * + * @var bool + */ + protected bool|int $sslHandshakeCompleted = false; + + /** + * All connection instances. + * + * @var array + */ + public static array $connections = []; + + /** + * Status to string. + * + * @var array + */ + public const STATUS_TO_STRING = [ + self::STATUS_INITIAL => 'INITIAL', + self::STATUS_CONNECTING => 'CONNECTING', + self::STATUS_ESTABLISHED => 'ESTABLISHED', + self::STATUS_CLOSING => 'CLOSING', + self::STATUS_ENDING => 'ENDING', + self::STATUS_CLOSED => 'CLOSED', + ]; + + /** + * Construct. + * + * @param EventInterface $eventLoop + * @param resource $socket + * @param string $remoteAddress + */ + public function __construct(EventInterface $eventLoop, $socket, string $remoteAddress = '') + { + ++self::$statistics['connection_count']; + $this->id = $this->realId = self::$idRecorder++; + if (self::$idRecorder === PHP_INT_MAX) { + self::$idRecorder = 0; + } + $this->socket = $socket; + stream_set_blocking($this->socket, false); + stream_set_read_buffer($this->socket, 0); + $this->eventLoop = $eventLoop; + $this->eventLoop->onReadable($this->socket, $this->baseRead(...)); + $this->maxSendBufferSize = self::$defaultMaxSendBufferSize; + $this->maxPackageSize = self::$defaultMaxPackageSize; + $this->lingerTimeout = self::$defaultLingerTimeout; + $this->remoteAddress = $remoteAddress; + static::$connections[$this->id] = $this; + $this->context = new stdClass(); + } + + /** + * Get status. + * + * @param bool $rawOutput + * + * @return int|string + */ + public function getStatus(bool $rawOutput = true): int|string + { + if ($rawOutput) { + return $this->status; + } + return self::STATUS_TO_STRING[$this->status]; + } + + /** + * Sends data on the connection. + * + * @param mixed $sendBuffer + * @param bool $raw + * @return bool|null + */ + public function send(mixed $sendBuffer, bool $raw = false): bool|null + { + if ($this->status === self::STATUS_ENDING || $this->status === self::STATUS_CLOSING || $this->status === self::STATUS_CLOSED) { + return false; + } + + // Try to call protocol::encode($sendBuffer) before sending. + if (false === $raw && $this->protocol !== null) { + try { + $sendBuffer = $this->protocol::encode($sendBuffer, $this); + } catch(Throwable $e) { + $this->error($e); + } + if ($sendBuffer === '') { + return null; + } + } + + if ($this->status !== self::STATUS_ESTABLISHED || + ($this->transport === 'ssl' && $this->sslHandshakeCompleted !== true) + ) { + if ($this->sendBuffer && $this->bufferIsFull()) { + ++self::$statistics['send_fail']; + return false; + } + $this->sendBuffer .= $sendBuffer; + $this->checkBufferWillFull(); + return null; + } + + // Attempt to send data directly. + if ($this->sendBuffer === '') { + $len = 0; + try { + $len = @fwrite($this->socket, $sendBuffer); + } catch (Throwable $e) { + Worker::log($e); + } + // send successful. + if ($len === strlen($sendBuffer)) { + $this->bytesWritten += $len; + return true; + } + // Send only part of the data. + if ($len > 0) { + $this->sendBuffer = substr($sendBuffer, $len); + $this->bytesWritten += $len; + } else { + // Connection closed? + if (!is_resource($this->socket) || feof($this->socket)) { + ++self::$statistics['send_fail']; + if ($this->onError) { + try { + ($this->onError)($this, static::SEND_FAIL, 'client closed'); + } catch (Throwable $e) { + $this->error($e); + } + } + $this->destroy(); + return false; + } + $this->sendBuffer = $sendBuffer; + } + $this->eventLoop->onWritable($this->socket, $this->baseWrite(...)); + // Check if send buffer will be full. + $this->checkBufferWillFull(); + return null; + } + + if ($this->bufferIsFull()) { + ++self::$statistics['send_fail']; + return false; + } + + $this->sendBuffer .= $sendBuffer; + // Check if send buffer is full. + $this->checkBufferWillFull(); + return null; + } + + /** + * Get remote IP. + * + * @return string + */ + public function getRemoteIp(): string + { + $pos = strrpos($this->remoteAddress, ':'); + if ($pos) { + return substr($this->remoteAddress, 0, $pos); + } + return ''; + } + + /** + * Get remote port. + * + * @return int + */ + public function getRemotePort(): int + { + if ($this->remoteAddress) { + return (int)substr(strrchr($this->remoteAddress, ':'), 1); + } + return 0; + } + + /** + * Get remote address. + * + * @return string + */ + public function getRemoteAddress(): string + { + return $this->remoteAddress; + } + + /** + * Get local IP. + * + * @return string + */ + public function getLocalIp(): string + { + $address = $this->getLocalAddress(); + $pos = strrpos($address, ':'); + if (!$pos) { + return ''; + } + return substr($address, 0, $pos); + } + + /** + * Get local port. + * + * @return int + */ + public function getLocalPort(): int + { + $address = $this->getLocalAddress(); + $pos = strrpos($address, ':'); + if (!$pos) { + return 0; + } + return (int)substr(strrchr($address, ':'), 1); + } + + /** + * Get local address. + * + * @return string + */ + public function getLocalAddress(): string + { + if (!is_resource($this->socket)) { + return ''; + } + return (string)@stream_socket_get_name($this->socket, false); + } + + /** + * Get send buffer queue size. + * + * @return integer + */ + public function getSendBufferQueueSize(): int + { + return strlen($this->sendBuffer); + } + + /** + * Get receive buffer queue size. + * + * @return integer + */ + public function getRecvBufferQueueSize(): int + { + return strlen($this->recvBuffer); + } + + /** + * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload. + * + * @return void + */ + public function pauseRecv(): void + { + if($this->eventLoop !== null){ + $this->eventLoop->offReadable($this->socket); + } + $this->isPaused = true; + } + + /** + * Resumes reading after a call to pauseRecv. + * + * @return void + */ + public function resumeRecv(): void + { + if ($this->isPaused === true) { + $this->eventLoop->onReadable($this->socket, $this->baseRead(...)); + $this->isPaused = false; + $this->baseRead($this->socket, false); + } + } + + + /** + * Base read handler. + * + * @param resource $socket + * @param bool $checkEof + * @return void + */ + public function baseRead($socket, bool $checkEof = true): void + { + static $requests = []; + $buffer = ''; + try { + if ($this->transport !== 'ssl') { + $buffer = @fread($socket, self::READ_BUFFER_SIZE); + } else { + // SSL handshake. + if ($this->sslHandshakeCompleted !== true) { + if (!$this->doSslHandshake($socket)) { + return; + } + $this->sslHandshakeCompleted = true; + if ($this->sendBuffer) { + $this->eventLoop->onWritable($socket, $this->baseWrite(...)); + } + } + $buffer = @fread($socket, self::READ_BUFFER_SIZE); + // Swoole's TLS hook returns at most one chunk per fread() and enables OpenSSL read-ahead, so decrypted + // data may stay inside OpenSSL while the fd is no longer readable and the event loop never fires again. + // Drain it here. PHP's native openssl stream has neither behaviour, so other event loops are untouched. + if ($buffer !== '' && $buffer !== false && $this->eventLoop instanceof Swoole) { + while (($chunk = @fread($socket, self::READ_BUFFER_SIZE)) !== '' && $chunk !== false) { + $buffer .= $chunk; + } + } + } + } catch (Throwable) { + // do nothing + } + + // Check connection closed. + if ($buffer === '' || $buffer === false) { + if ($checkEof && (!is_resource($socket) || feof($socket) || $buffer === false)) { + $this->destroy(); + return; + } + } else { + $this->bytesRead += strlen($buffer); + if ($this->status === self::STATUS_ENDING) { + return; + } + if ($this->recvBuffer === '') { + if (!isset($buffer[static::MAX_CACHE_STRING_LENGTH]) && isset($requests[$buffer])) { + ++self::$statistics['total_request']; + if ($this->protocol === Http::class) { + $request = $requests[$buffer]; + $request->connection = $this; + try { + ($this->onMessage)($this, $request); + } catch (Throwable $e) { + $this->error($e); + } + $request = clone $request; + $request->destroy(); + $requests[$buffer] = $request; + return; + } + $request = $requests[$buffer]; + try { + ($this->onMessage)($this, $request); + } catch (Throwable $e) { + $this->error($e); + } + return; + } + $this->recvBuffer = $buffer; + } else { + $this->recvBuffer .= $buffer; + } + } + + // If the application layer protocol has been set up. + if ($this->protocol !== null) { + while ($this->recvBuffer !== '' && !$this->isPaused) { + // The current packet length is known. + if ($this->currentPackageLength) { + // Data is not enough for a package. + $recvBufferLength = strlen($this->recvBuffer); + if ($this->currentPackageLength > $recvBufferLength) { + break; + } + } else { + // Get current package length. + try { + $this->currentPackageLength = $this->protocol::input($this->recvBuffer, $this); + } catch (Throwable $e) { + $this->currentPackageLength = -1; + Worker::safeEcho((string)$e); + } + // The packet length is unknown. + if ($this->currentPackageLength === 0) { + break; + } elseif ($this->currentPackageLength > 0 && $this->currentPackageLength <= $this->maxPackageSize) { + // Data is not enough for a package. + // Note: recalculate length here since protocol::input() may call consumeRecvBuffer(). + $recvBufferLength = strlen($this->recvBuffer); + if ($this->currentPackageLength > $recvBufferLength) { + break; + } + } // Wrong package. + else { + Worker::safeEcho((string)(new RuntimeException("Protocol $this->protocol Error package. package_length=" . var_export($this->currentPackageLength, true)))); + $this->destroy(); + return; + } + } + + // The data is enough for a packet. + ++self::$statistics['total_request']; + // The current packet length is equal to the length of the buffer. + if ($recvBufferLength === $this->currentPackageLength) { + $oneRequestBuffer = $this->recvBuffer; + $this->recvBuffer = ''; + } else { + // Get a full package from the buffer. + $oneRequestBuffer = substr($this->recvBuffer, 0, $this->currentPackageLength); + // Remove the current package from receive buffer. + $this->recvBuffer = substr($this->recvBuffer, $this->currentPackageLength); + } + // Reset the current packet length to 0. + $this->currentPackageLength = 0; + try { + if (!isset($oneRequestBuffer[static::MAX_CACHE_STRING_LENGTH]) && isset($requests[$oneRequestBuffer])) { + $request = $requests[$oneRequestBuffer]; + if ($request instanceof Request) { + $request->connection = $this; + ($this->onMessage)($this, $request); + $request = clone $request; + $request->destroy(); + $requests[$oneRequestBuffer] = $request; + } else { + ($this->onMessage)($this, $request); + } + continue; + } + // Decode request buffer before Emitting onMessage callback. + $request = $this->protocol::decode($oneRequestBuffer, $this); + // The protocol closed the connection while decoding, so there is nothing to deliver. + if ($this->status === self::STATUS_CLOSING || $this->status === self::STATUS_CLOSED) { + return; + } + if ((!is_object($request) || $request instanceof Request) && !isset($oneRequestBuffer[static::MAX_CACHE_STRING_LENGTH])) { + ($this->onMessage)($this, $request); + if ($request instanceof Request) { + $request = clone $request; + $request->destroy(); + } + $requests[$oneRequestBuffer] = $request; + if (count($requests) > static::MAX_CACHE_SIZE) { + unset($requests[key($requests)]); + } + continue; + } + ($this->onMessage)($this, $request); + } catch (Throwable $e) { + $this->error($e); + } + } + return; + } + + if ($this->recvBuffer === '' || $this->isPaused) { + return; + } + + // Application protocol is not set. + ++self::$statistics['total_request']; + try { + ($this->onMessage)($this, $this->recvBuffer); + } catch (Throwable $e) { + $this->error($e); + } + // Clean receive buffer. + $this->recvBuffer = ''; + } + + /** + * Base write handler. + * + * @return void + */ + public function baseWrite(): void + { + $len = 0; + try { + // Always retry with the whole buffer. OpenSSL must be given at least the length of the + // record it could not flush last time (otherwise SSL_R_BAD_LENGTH kills the session), and + // send() may already have queued a partially written 16KB record. + $len = @fwrite($this->socket, $this->sendBuffer); + } catch (Throwable) { + } + if ($len === strlen($this->sendBuffer)) { + $this->bytesWritten += $len; + $this->eventLoop->offWritable($this->socket); + $this->sendBuffer = ''; + // Try to emit onBufferDrain callback when send buffer becomes empty. + if ($this->onBufferDrain) { + try { + ($this->onBufferDrain)($this); + } catch (Throwable $e) { + $this->error($e); + } + } + if ($this->status === self::STATUS_ENDING) { + $this->endMaybeShutdownWrite(); + } + if ($this->status === self::STATUS_CLOSING) { + if (!empty($this->context->streamSending)) { + return; + } + $this->destroy(); + } + return; + } + if ($len > 0) { + $this->bytesWritten += $len; + $this->sendBuffer = substr($this->sendBuffer, $len); + return; + } + // fwrite() returns 0 when the socket would block (e.g. SSL_ERROR_WANT_WRITE while the + // kernel send buffer is full). That is back-pressure, not an error: keep the buffer and + // wait for the next writable event. + if ($len === 0 && is_resource($this->socket) && !feof($this->socket)) { + return; + } + ++self::$statistics['send_fail']; + $this->destroy(); + } + + /** + * SSL handshake. + * + * @param resource $socket + * @return bool|int + */ + public function doSslHandshake($socket): bool|int + { + if (!is_resource($socket) || feof($socket)) { + $this->emitSslHandshakeFailure('connection closed during SSL handshake'); + return false; + } + $async = $this instanceof AsyncTcpConnection; + + /** + * We disabled ssl3 because https://blog.qualys.com/ssllabs/2014/10/15/ssl-3-is-dead-killed-by-the-poodle-attack. + * You can enable ssl3 by the codes below. + */ + /*if($async){ + $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_CLIENT; + }else{ + $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER | STREAM_CRYPTO_METHOD_SSLv3_SERVER; + }*/ + + if ($async) { + $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT; + } else { + $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER; + } + + // Hidden error. + $reason = ''; + if ($this->eventLoop instanceof Swoole) { + // The Swoole hook performs the handshake while yielding to other coroutines, and reports failures to its own + // log rather than as PHP warnings. A process-wide error handler installed here would only catch warnings raised + // by those other coroutines, hiding them from the application and reporting them as this handshake's reason. + $ret = @stream_socket_enable_crypto($socket, true, $type); + } else { + set_error_handler(static function (int $code, string $msg, ...$args) use (&$reason): bool { + $reason = $msg; + return true; + }); + try { + $ret = stream_socket_enable_crypto($socket, true, $type); + } finally { + restore_error_handler(); + } + } + // Negotiation has failed. + if (false === $ret) { + $this->emitSslHandshakeFailure($reason); + return false; + } + if (0 === $ret) { + // There isn't enough data and should try again. + return 0; + } + return true; + } + + /** + * Report a failed SSL negotiation to the application, then tear the connection down. + * + * onError has to fire before destroy() so the application sees the reason ahead of onClose, + * otherwise a client only observes an unexplained disconnect and waits out its own timeout. + * + * @param string $reason + * @return void + */ + private function emitSslHandshakeFailure(string $reason): void + { + $message = sprintf('SSL handshake with %s failed', $this->getRemoteAddress()); + if ($reason !== '') { + $message .= ": $reason"; + } + if (!Worker::$daemonize) { + Worker::safeEcho("$message\n"); + } + $this->status = self::STATUS_CLOSING; + if ($this->onError) { + try { + ($this->onError)($this, static::CONNECT_FAIL, $message); + } catch (Throwable $e) { + $this->error($e); + } + } + if ($this->status === self::STATUS_CLOSING) { + $this->destroy(); + } + if ($this instanceof AsyncTcpConnection && $this->status === self::STATUS_CLOSED) { + $this->onConnect = null; + } + } + + /** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination. + * + * @param self $dest + * @return void + */ + public function pipe(self $dest): void + { + $this->onMessage = fn ($source, $data) => $dest->send($data); + $this->onClose = fn () => $dest->close(); + $dest->onBufferFull = fn () => $this->pauseRecv(); + $dest->onBufferDrain = fn() => $this->resumeRecv(); + } + + /** + * Remove $length of data from receive buffer. + * + * @param int $length + * @return void + */ + public function consumeRecvBuffer(int $length): void + { + $this->recvBuffer = substr($this->recvBuffer, $length); + } + + /** + * Close connection. + * + * @param mixed $data + * @param bool $raw + * @return void + */ + public function close(mixed $data = null, bool $raw = false): void + { + if ($this->status === self::STATUS_INITIAL || $this->status === self::STATUS_CONNECTING) { + $this->destroy(); + return; + } + + if ($this->status === self::STATUS_CLOSING || $this->status === self::STATUS_CLOSED) { + return; + } + + if ($data !== null) { + $this->send($data, $raw); + } + + $this->status = self::STATUS_CLOSING; + + if ($this->sendBuffer === '') { + $this->destroy(); + } else { + $this->pauseRecv(); + } + } + + /** + * Graceful end connection. + * It tries to: send response -> wait sendBuffer empty -> shutdown write(FIN) -> linger/drain reads -> close(). + * + * @param mixed $data + * @param bool $raw + * @return void + */ + public function end(mixed $data = null, bool $raw = false): void + { + if ($this->status === self::STATUS_INITIAL || $this->status === self::STATUS_CONNECTING) { + $this->destroy(); + return; + } + + if ($this->status === self::STATUS_ENDING || $this->status === self::STATUS_CLOSING || $this->status === self::STATUS_CLOSED) { + return; + } + + if ($data !== null) { + $this->send($data, $raw); + } + + // Enter ending mode: stop protocol parsing and only drain incoming data. + $this->status = self::STATUS_ENDING; + // Disable business callback after end(). + $this->onMessage = static function (self $connection, mixed $data = null): void {}; + $this->recvBuffer = ''; + $this->currentPackageLength = 0; + + // If already flushed to kernel, shutdown write now. Otherwise, baseWrite() will call endMaybeShutdownWrite() + // when sendBuffer becomes empty. + if ($this->sendBuffer === '') { + $this->endMaybeShutdownWrite(); + return; + } + } + + /** + * If in ENDING and sendBuffer is empty, shutdown write side and start linger timer. + * + * @return void + */ + protected function endMaybeShutdownWrite(): void + { + if ($this->status !== self::STATUS_ENDING || $this->endWriteShutdown || $this->sendBuffer !== '') { + return; + } + + if (is_resource($this->socket)) { + try { + @stream_socket_shutdown($this->socket, STREAM_SHUT_WR); + } catch (Throwable) { + // ignore + } + } + $this->endWriteShutdown = true; + + $timeout = $this->lingerTimeout; + if ($timeout <= 0) { + $this->close(); + return; + } + + $this->endLingerTimerId = Timer::delay($timeout, function (): void { + $this->endLingerTimerId = 0; + if ($this->status === self::STATUS_CLOSED) { + return; + } + $this->close(); + }); + } + + /** + * Is ipv4. + * + * return bool. + */ + public function isIpV4(): bool + { + if ($this->transport === 'unix') { + return false; + } + return !str_contains($this->getRemoteIp(), ':'); + } + + /** + * Is ipv6. + * + * return bool. + */ + public function isIpV6(): bool + { + if ($this->transport === 'unix') { + return false; + } + return str_contains($this->getRemoteIp(), ':'); + } + + /** + * Get the real socket. + * + * @return resource + */ + public function getSocket() + { + return $this->socket; + } + + /** + * Check whether send buffer will be full. + * + * @return void + */ + protected function checkBufferWillFull(): void + { + if ($this->onBufferFull && $this->maxSendBufferSize <= strlen($this->sendBuffer)) { + try { + ($this->onBufferFull)($this); + } catch (Throwable $e) { + $this->error($e); + } + } + } + + /** + * Whether send buffer is full. + * + * @return bool + */ + protected function bufferIsFull(): bool + { + // Buffer has been marked as full but still has data to send then the packet is discarded. + if ($this->maxSendBufferSize <= strlen($this->sendBuffer)) { + if ($this->onError) { + try { + ($this->onError)($this, static::SEND_FAIL, 'send buffer full and drop package'); + } catch (Throwable $e) { + $this->error($e); + } + } + return true; + } + return false; + } + + /** + * Whether send buffer is Empty. + * + * @return bool + */ + public function bufferIsEmpty(): bool + { + return empty($this->sendBuffer); + } + + /** + * Destroy connection. + * + * @return void + */ + public function destroy(): void + { + // Avoid repeated calls. + if ($this->status === self::STATUS_CLOSED) { + return; + } + // Remove event listener. + if($this->eventLoop !== null){ + $this->eventLoop->offReadable($this->socket); + $this->eventLoop->offWritable($this->socket); + if (DIRECTORY_SEPARATOR === '\\' && method_exists($this->eventLoop, 'offExcept')) { + $this->eventLoop->offExcept($this->socket); + } + } + + // Close socket. + try { + @fclose($this->socket); + } catch (Throwable) { + } + + $this->status = self::STATUS_CLOSED; + // Try to emit onClose callback. + if ($this->onClose) { + try { + ($this->onClose)($this); + } catch (Throwable $e) { + $this->error($e); + } + } + // Try to emit protocol::onClose + if ($this->protocol && method_exists($this->protocol, 'onClose')) { + try { + $this->protocol::onClose($this); + } catch (Throwable $e) { + $this->error($e); + } + } + $this->sendBuffer = $this->recvBuffer = ''; + $this->currentPackageLength = 0; + $this->isPaused = $this->sslHandshakeCompleted = false; + $this->endWriteShutdown = false; + if ($this->status === self::STATUS_CLOSED) { + // Cleaning up the callback to avoid memory leaks. + $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = $this->eventLoop = $this->errorHandler = null; + // Remove from worker->connections. + if ($this->worker) { + unset($this->worker->connections[$this->realId]); + } + $this->worker = null; + unset(static::$connections[$this->realId]); + } + } + + /** + * Get the json_encode information. + * + * @return array + */ + public function jsonSerialize(): array + { + return [ + 'id' => $this->id, + 'status' => $this->getStatus(), + 'transport' => $this->transport, + 'getRemoteIp' => $this->getRemoteIp(), + 'remotePort' => $this->getRemotePort(), + 'getRemoteAddress' => $this->getRemoteAddress(), + 'getLocalIp' => $this->getLocalIp(), + 'getLocalPort' => $this->getLocalPort(), + 'getLocalAddress' => $this->getLocalAddress(), + 'isIpV4' => $this->isIpV4(), + 'isIpV6' => $this->isIpV6(), + ]; + } + + /** + * __unserialize. + * + * @param array $data + * @return void + */ + public function __unserialize(array $data): void + { + $this->isSafe = false; + } + + /** + * Destruct. + * + * @return void + */ + public function __destruct() + { + static $mod; + if (!$this->isSafe) { + return; + } + self::$statistics['connection_count']--; + if (Worker::getGracefulStop()) { + $mod ??= ceil((self::$statistics['connection_count'] + 1) / 3); + + if (0 === self::$statistics['connection_count'] % $mod) { + $pid = function_exists('posix_getpid') ? posix_getpid() : 0; + Worker::log('worker[' . $pid . '] remains ' . self::$statistics['connection_count'] . ' connection(s)'); + } + + if (0 === self::$statistics['connection_count']) { + Worker::stopAll(); + } + } + } +} diff --git a/vendor/workerman/workerman/src/Connection/UdpConnection.php b/vendor/workerman/workerman/src/Connection/UdpConnection.php new file mode 100644 index 0000000..5e85121 --- /dev/null +++ b/vendor/workerman/workerman/src/Connection/UdpConnection.php @@ -0,0 +1,246 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Connection; + +use JsonSerializable; +use Workerman\Protocols\ProtocolInterface; +use function stream_socket_get_name; +use function stream_socket_sendto; +use function strlen; +use function strrchr; +use function strrpos; +use function substr; +use function trim; + +/** + * UdpConnection. + */ +class UdpConnection extends ConnectionInterface implements JsonSerializable +{ + /** + * Max udp package size. + * + * @var int + */ + public const MAX_UDP_PACKAGE_SIZE = 65535; + + /** + * Transport layer protocol. + * + * @var string + */ + public string $transport = 'udp'; + + /** + * Whether the socket is connected (created via stream_socket_client). + * On BSD/macOS, sendto() on a connected UDP socket with a destination address + * returns EISCONN(-1). We must omit the address for connected sockets. + */ + protected bool $connected = false; + + /** + * @param resource|null $socket + */ + public function __construct( + /** @var resource|null */ protected $socket, + protected string $remoteAddress) + { + if (is_resource($socket) && stream_socket_get_name($socket, true) !== false) { + $this->connected = true; + } + } + + /** + * Sends data on the connection. + * + * @param mixed $sendBuffer + * @param bool $raw + * @return bool|null + */ + public function send(mixed $sendBuffer, bool $raw = false): bool|null + { + if (false === $raw && $this->protocol) { + $sendBuffer = $this->protocol::encode($sendBuffer, $this); + if ($sendBuffer === '') { + return null; + } + } + if ($this->connected) { + return strlen($sendBuffer) === stream_socket_sendto($this->socket, $sendBuffer); + } + return strlen($sendBuffer) === stream_socket_sendto($this->socket, $sendBuffer, 0, $this->isIpV6() ? '[' . $this->getRemoteIp() . ']:' . $this->getRemotePort() : $this->remoteAddress); + } + + /** + * Get remote IP. + * + * @return string + */ + public function getRemoteIp(): string + { + $pos = strrpos($this->remoteAddress, ':'); + if ($pos) { + return trim(substr($this->remoteAddress, 0, $pos), '[]'); + } + return ''; + } + + /** + * Get remote port. + * + * @return int + */ + public function getRemotePort(): int + { + if ($this->remoteAddress) { + return (int)substr(strrchr($this->remoteAddress, ':'), 1); + } + return 0; + } + + /** + * Get remote address. + * + * @return string + */ + public function getRemoteAddress(): string + { + return $this->remoteAddress; + } + + /** + * Get local IP. + * + * @return string + */ + public function getLocalIp(): string + { + $address = $this->getLocalAddress(); + $pos = strrpos($address, ':'); + if (!$pos) { + return ''; + } + return substr($address, 0, $pos); + } + + /** + * Get local port. + * + * @return int + */ + public function getLocalPort(): int + { + $address = $this->getLocalAddress(); + $pos = strrpos($address, ':'); + if (!$pos) { + return 0; + } + return (int)substr(strrchr($address, ':'), 1); + } + + /** + * Get local address. + * + * @return string + */ + public function getLocalAddress(): string + { + return is_resource($this->socket) ? (string)@stream_socket_get_name($this->socket, false) : ''; + } + + + /** + * Close connection. + * + * @param mixed $data + * @param bool $raw + * @return void + */ + public function close(mixed $data = null, bool $raw = false): void + { + if ($data !== null) { + $this->send($data, $raw); + } + if ($this->eventLoop) { + $this->eventLoop->offReadable($this->socket); + } + if (is_resource($this->socket)) { + @fclose($this->socket); + } + $this->socket = null; + $this->eventLoop = $this->errorHandler = null; + } + + /** + * Is ipv4. + * + * return bool. + */ + public function isIpV4(): bool + { + if ($this->transport === 'unix') { + return false; + } + return !str_contains($this->getRemoteIp(), ':'); + } + + /** + * Is ipv6. + * + * return bool. + */ + public function isIpV6(): bool + { + if ($this->transport === 'unix') { + return false; + } + return str_contains($this->getRemoteIp(), ':'); + } + + /** + * Get the real socket. + * + * @return resource + */ + /** + * @return resource|null + */ + public function getSocket() + { + return $this->socket; + } + + /** + * Get the json_encode information. + * + * @return array + */ + public function jsonSerialize(): array + { + return [ + 'transport' => $this->transport, + 'getRemoteIp' => $this->getRemoteIp(), + 'remotePort' => $this->getRemotePort(), + 'getRemoteAddress' => $this->getRemoteAddress(), + 'getLocalIp' => $this->getLocalIp(), + 'getLocalPort' => $this->getLocalPort(), + 'getLocalAddress' => $this->getLocalAddress(), + 'isIpV4' => $this->isIpV4(), + 'isIpV6' => $this->isIpV6(), + ]; + } +} diff --git a/vendor/workerman/workerman/src/Events/Ev.php b/vendor/workerman/workerman/src/Events/Ev.php new file mode 100644 index 0000000..67c1652 --- /dev/null +++ b/vendor/workerman/workerman/src/Events/Ev.php @@ -0,0 +1,238 @@ + + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Events; + +/** + * Ev eventloop + */ +final class Ev implements EventInterface +{ + /** + * All listeners for read event. + * + * @var array + */ + private array $readEvents = []; + + /** + * All listeners for write event. + * + * @var array + */ + private array $writeEvents = []; + + /** + * Event listeners of signal. + * + * @var array + */ + private array $eventSignal = []; + + /** + * All timer event listeners. + * + * @var array + */ + private array $eventTimer = []; + + /** + * @var ?callable + */ + private $errorHandler = null; + + /** + * Timer id. + * + * @var int + */ + private static int $timerId = 1; + + /** + * {@inheritdoc} + */ + public function delay(float $delay, callable $func, array $args = []): int + { + $timerId = self::$timerId; + $event = new \EvTimer($delay, 0, function () use ($func, $args, $timerId) { + unset($this->eventTimer[$timerId]); + $this->safeCall($func, $args); + }); + $this->eventTimer[self::$timerId] = $event; + return self::$timerId++; + } + + /** + * {@inheritdoc} + */ + public function offDelay(int $timerId): bool + { + if (isset($this->eventTimer[$timerId])) { + $this->eventTimer[$timerId]->stop(); + unset($this->eventTimer[$timerId]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function offRepeat(int $timerId): bool + { + return $this->offDelay($timerId); + } + + /** + * {@inheritdoc} + */ + public function repeat(float $interval, callable $func, array $args = []): int + { + $event = new \EvTimer($interval, $interval, fn () => $this->safeCall($func, $args)); + $this->eventTimer[self::$timerId] = $event; + return self::$timerId++; + } + + /** + * {@inheritdoc} + */ + public function onReadable($stream, callable $func): void + { + $fdKey = (int)$stream; + $event = new \EvIo($stream, \Ev::READ, fn () => $this->safeCall($func, [$stream])); + $this->readEvents[$fdKey] = $event; + } + + /** + * {@inheritdoc} + */ + public function offReadable($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->readEvents[$fdKey])) { + $this->readEvents[$fdKey]->stop(); + unset($this->readEvents[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onWritable($stream, callable $func): void + { + $fdKey = (int)$stream; + $event = new \EvIo($stream, \Ev::WRITE, fn () => $this->safeCall($func, [$stream])); + $this->writeEvents[$fdKey] = $event; + } + + /** + * {@inheritdoc} + */ + public function offWritable($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->writeEvents[$fdKey])) { + $this->writeEvents[$fdKey]->stop(); + unset($this->writeEvents[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onSignal(int $signal, callable $func): void + { + $event = new \EvSignal($signal, fn () => $this->safeCall($func, [$signal])); + $this->eventSignal[$signal] = $event; + } + + /** + * {@inheritdoc} + */ + public function offSignal(int $signal): bool + { + if (isset($this->eventSignal[$signal])) { + $this->eventSignal[$signal]->stop(); + unset($this->eventSignal[$signal]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function deleteAllTimer(): void + { + foreach ($this->eventTimer as $event) { + $event->stop(); + } + $this->eventTimer = []; + } + + /** + * {@inheritdoc} + */ + public function run(): void + { + \Ev::run(); + } + + /** + * {@inheritdoc} + */ + public function stop(): void + { + \Ev::stop(); + } + + /** + * {@inheritdoc} + */ + public function getTimerCount(): int + { + return count($this->eventTimer); + } + + /** + * {@inheritdoc} + */ + public function setErrorHandler(callable $errorHandler): void + { + $this->errorHandler = $errorHandler; + } + + /** + * @param callable $func + * @param array $args + * @return void + */ + private function safeCall(callable $func, array $args = []): void + { + try { + $func(...$args); + } catch (\Throwable $e) { + if ($this->errorHandler === null) { + echo $e; + } else { + ($this->errorHandler)($e); + } + } + } +} diff --git a/vendor/workerman/workerman/src/Events/Event.php b/vendor/workerman/workerman/src/Events/Event.php new file mode 100644 index 0000000..d7d908e --- /dev/null +++ b/vendor/workerman/workerman/src/Events/Event.php @@ -0,0 +1,294 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Events; + +/** + * libevent eventloop + */ +final class Event implements EventInterface +{ + /** + * Event base. + * + * @var \EventBase + */ + private \EventBase $eventBase; + + /** + * All listeners for read event. + * + * @var array + */ + private array $readEvents = []; + + /** + * All listeners for write event. + * + * @var array + */ + private array $writeEvents = []; + + /** + * Event listeners of signal. + * + * @var array + */ + private array $eventSignal = []; + + /** + * All timer event listeners. + * + * @var array + */ + private array $eventTimer = []; + + /** + * Timer id. + * + * @var int + */ + private int $timerId = 0; + + /** + * Event class name. + * + * @var string + */ + private string $eventClassName = ''; + + /** + * @var ?callable + */ + private $errorHandler = null; + + /** + * Construct. + */ + public function __construct() + { + if (\class_exists('\\\\Event', false)) { + $className = '\\\\Event'; + } else { + $className = '\Event'; + } + $this->eventClassName = $className; + if (\class_exists('\\\\EventBase', false)) { + $className = '\\\\EventBase'; + } else { + $className = '\EventBase'; + } + $this->eventBase = new $className(); + } + + /** + * {@inheritdoc} + */ + public function delay(float $delay, callable $func, array $args = []): int + { + $className = $this->eventClassName; + $timerId = $this->timerId++; + $event = new $className($this->eventBase, -1, $className::TIMEOUT, function () use ($func, $args, $timerId) { + unset($this->eventTimer[$timerId]); + $this->safeCall($func, $args); + }); + if (!$event->addTimer($delay)) { + throw new \RuntimeException("Event::addTimer($delay) failed"); + } + $this->eventTimer[$timerId] = $event; + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function offDelay(int $timerId): bool + { + if (isset($this->eventTimer[$timerId])) { + $this->eventTimer[$timerId]->del(); + unset($this->eventTimer[$timerId]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function offRepeat(int $timerId): bool + { + return $this->offDelay($timerId); + } + + /** + * {@inheritdoc} + */ + public function repeat(float $interval, callable $func, array $args = []): int + { + $className = $this->eventClassName; + $timerId = $this->timerId++; + $event = new $className($this->eventBase, -1, $className::TIMEOUT | $className::PERSIST, function () use ($func, $args) { + $this->safeCall($func, $args); + }); + if (!$event->addTimer($interval)) { + throw new \RuntimeException("Event::addTimer($interval) failed"); + } + $this->eventTimer[$timerId] = $event; + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function onReadable($stream, callable $func): void + { + $className = $this->eventClassName; + $fdKey = (int)$stream; + $event = new $className($this->eventBase, $stream, $className::READ | $className::PERSIST, $func); + if ($event->add()) { + $this->readEvents[$fdKey] = $event; + } + } + + /** + * {@inheritdoc} + */ + public function offReadable($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->readEvents[$fdKey])) { + $this->readEvents[$fdKey]->del(); + unset($this->readEvents[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onWritable($stream, callable $func): void + { + $className = $this->eventClassName; + $fdKey = (int)$stream; + $event = new $className($this->eventBase, $stream, $className::WRITE | $className::PERSIST, $func); + if ($event->add()) { + $this->writeEvents[$fdKey] = $event; + } + } + + /** + * {@inheritdoc} + */ + public function offWritable($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->writeEvents[$fdKey])) { + $this->writeEvents[$fdKey]->del(); + unset($this->writeEvents[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onSignal(int $signal, callable $func): void + { + $className = $this->eventClassName; + $fdKey = $signal; + $event = $className::signal($this->eventBase, $signal, fn () => $this->safeCall($func, [$signal])); + if ($event->add()) { + $this->eventSignal[$fdKey] = $event; + } + } + + /** + * {@inheritdoc} + */ + public function offSignal(int $signal): bool + { + $fdKey = $signal; + if (isset($this->eventSignal[$fdKey])) { + $this->eventSignal[$fdKey]->del(); + unset($this->eventSignal[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function deleteAllTimer(): void + { + foreach ($this->eventTimer as $event) { + $event->del(); + } + $this->eventTimer = []; + } + + /** + * {@inheritdoc} + */ + public function run(): void + { + $this->eventBase->loop(); + } + + /** + * {@inheritdoc} + */ + public function stop(): void + { + $this->eventBase->exit(); + } + + /** + * {@inheritdoc} + */ + public function getTimerCount(): int + { + return \count($this->eventTimer); + } + + /** + * {@inheritdoc} + */ + public function setErrorHandler(callable $errorHandler): void + { + $this->errorHandler = $errorHandler; + } + + /** + * @param callable $func + * @param array $args + * @return void + */ + private function safeCall(callable $func, array $args = []): void + { + try { + $func(...$args); + } catch (\Throwable $e) { + if ($this->errorHandler === null) { + echo $e; + } else { + ($this->errorHandler)($e); + } + } + } +} diff --git a/vendor/workerman/workerman/src/Events/EventInterface.php b/vendor/workerman/workerman/src/Events/EventInterface.php new file mode 100644 index 0000000..4d538c6 --- /dev/null +++ b/vendor/workerman/workerman/src/Events/EventInterface.php @@ -0,0 +1,143 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Events; + +interface EventInterface +{ + /** + * Delay the execution of a callback. + * + * @param float $delay + * @param callable(mixed...): void $func + * @param array $args + * @return int + */ + public function delay(float $delay, callable $func, array $args = []): int; + + /** + * Delete a delay timer. + * + * @param int $timerId + * @return bool + */ + public function offDelay(int $timerId): bool; + + /** + * Repeatedly execute a callback. + * + * @param float $interval + * @param callable(mixed...): void $func + * @param array $args + * @return int + */ + public function repeat(float $interval, callable $func, array $args = []): int; + + /** + * Delete a repeat timer. + * + * @param int $timerId + * @return bool + */ + public function offRepeat(int $timerId): bool; + + /** + * Execute a callback when a stream resource becomes readable or is closed for reading. + * + * @param resource $stream + * @param callable(resource): void $func + * @return void + */ + public function onReadable($stream, callable $func): void; + + /** + * Cancel a callback of stream readable. + * + * @param resource $stream + * @return bool + */ + public function offReadable($stream): bool; + + /** + * Execute a callback when a stream resource becomes writable or is closed for writing. + * + * @param resource $stream + * @param callable(resource): void $func + * @return void + */ + public function onWritable($stream, callable $func): void; + + /** + * Cancel a callback of stream writable. + * + * @param resource $stream + * @return bool + */ + public function offWritable($stream): bool; + + /** + * Execute a callback when a signal is received. + * + * @param int $signal + * @param callable(int): void $func + * @return void + */ + public function onSignal(int $signal, callable $func): void; + + /** + * Cancel a callback of signal. + * + * @param int $signal + * @return bool + */ + public function offSignal(int $signal): bool; + + /** + * Delete all timer. + * + * @return void + */ + public function deleteAllTimer(): void; + + /** + * Run the event loop. + * + * @return void + */ + public function run(): void; + + /** + * Stop event loop. + * + * @return void + */ + public function stop(): void; + + /** + * Get Timer count. + * + * @return int + */ + public function getTimerCount(): int; + + /** + * Set error handler. + * + * @param callable(\Throwable): void $errorHandler + * @return void + */ + public function setErrorHandler(callable $errorHandler): void; +} diff --git a/vendor/workerman/workerman/src/Events/Fiber.php b/vendor/workerman/workerman/src/Events/Fiber.php new file mode 100644 index 0000000..133f2cc --- /dev/null +++ b/vendor/workerman/workerman/src/Events/Fiber.php @@ -0,0 +1,276 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Events; + +use Fiber as BaseFiber; +use Revolt\EventLoop; +use Revolt\EventLoop\Driver; +use function count; +use function function_exists; +use function pcntl_signal; + +/** + * Revolt eventloop + */ +final class Fiber implements EventInterface +{ + /** + * @var Driver + */ + private Driver $driver; + + /** + * All listeners for read event. + * + * @var array + */ + private array $readEvents = []; + + /** + * All listeners for write event. + * + * @var array + */ + private array $writeEvents = []; + + /** + * Event listeners of signal. + * + * @var array + */ + private array $eventSignal = []; + + /** + * Event listeners of timer. + * + * @var array + */ + private array $eventTimer = []; + + /** + * Timer id. + * + * @var int + */ + private int $timerId = 1; + + /** + * Construct. + */ + public function __construct() + { + $this->driver = EventLoop::getDriver(); + } + + /** + * Get driver. + * + * @return Driver + */ + public function driver(): Driver + { + return $this->driver; + } + + /** + * {@inheritdoc} + */ + public function run(): void + { + $this->driver->run(); + } + + /** + * {@inheritdoc} + */ + public function stop(): void + { + foreach ($this->eventSignal as $cbId) { + $this->driver->cancel($cbId); + } + $this->driver->stop(); + if (function_exists('pcntl_signal')) { + pcntl_signal(SIGINT, SIG_IGN); + } + } + + /** + * {@inheritdoc} + */ + public function delay(float $delay, callable $func, array $args = []): int + { + $timerId = $this->timerId++; + $closure = function () use ($func, $args, $timerId) { + unset($this->eventTimer[$timerId]); + $this->safeCall($func, ...$args); + }; + $cbId = $this->driver->delay($delay, $closure); + $this->eventTimer[$timerId] = $cbId; + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function repeat(float $interval, callable $func, array $args = []): int + { + $timerId = $this->timerId++; + $cbId = $this->driver->repeat($interval, fn() => $this->safeCall($func, ...$args)); + $this->eventTimer[$timerId] = $cbId; + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function onReadable($stream, callable $func): void + { + $fdKey = (int)$stream; + if (isset($this->readEvents[$fdKey])) { + $this->driver->cancel($this->readEvents[$fdKey]); + } + + $this->readEvents[$fdKey] = $this->driver->onReadable($stream, fn() => $this->safeCall($func, $stream)); + } + + /** + * {@inheritdoc} + */ + public function offReadable($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->readEvents[$fdKey])) { + $this->driver->cancel($this->readEvents[$fdKey]); + unset($this->readEvents[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onWritable($stream, callable $func): void + { + $fdKey = (int)$stream; + if (isset($this->writeEvents[$fdKey])) { + $this->driver->cancel($this->writeEvents[$fdKey]); + unset($this->writeEvents[$fdKey]); + } + $this->writeEvents[$fdKey] = $this->driver->onWritable($stream, fn() => $this->safeCall($func, $stream)); + } + + /** + * {@inheritdoc} + */ + public function offWritable($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->writeEvents[$fdKey])) { + $this->driver->cancel($this->writeEvents[$fdKey]); + unset($this->writeEvents[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onSignal(int $signal, callable $func): void + { + $fdKey = $signal; + if (isset($this->eventSignal[$fdKey])) { + $this->driver->cancel($this->eventSignal[$fdKey]); + unset($this->eventSignal[$fdKey]); + } + $this->eventSignal[$fdKey] = $this->driver->onSignal($signal, fn() => $this->safeCall($func, $signal)); + } + + /** + * {@inheritdoc} + */ + public function offSignal(int $signal): bool + { + $fdKey = $signal; + if (isset($this->eventSignal[$fdKey])) { + $this->driver->cancel($this->eventSignal[$fdKey]); + unset($this->eventSignal[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function offDelay(int $timerId): bool + { + if (isset($this->eventTimer[$timerId])) { + $this->driver->cancel($this->eventTimer[$timerId]); + unset($this->eventTimer[$timerId]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function offRepeat(int $timerId): bool + { + return $this->offDelay($timerId); + } + + /** + * {@inheritdoc} + */ + public function deleteAllTimer(): void + { + foreach ($this->eventTimer as $cbId) { + $this->driver->cancel($cbId); + } + $this->eventTimer = []; + } + + /** + * {@inheritdoc} + */ + public function getTimerCount(): int + { + return count($this->eventTimer); + } + + /** + * {@inheritdoc} + */ + public function setErrorHandler(callable $errorHandler): void + { + $this->driver->setErrorHandler($errorHandler); + } + + /** + * @param callable $func + * @param ...$args + * @return void + * @throws \Throwable + */ + protected function safeCall(callable $func, ...$args): void + { + (new BaseFiber(fn() => $func(...$args)))->start(); + } +} diff --git a/vendor/workerman/workerman/src/Events/Select.php b/vendor/workerman/workerman/src/Events/Select.php new file mode 100644 index 0000000..6b0d56c --- /dev/null +++ b/vendor/workerman/workerman/src/Events/Select.php @@ -0,0 +1,492 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Events; + +use SplPriorityQueue; +use Throwable; +use function count; +use function max; +use function microtime; +use function pcntl_signal; +use function pcntl_signal_dispatch; +use const DIRECTORY_SEPARATOR; + +/** + * select eventloop + */ +final class Select implements EventInterface +{ + /** + * Running. + * + * @var bool + */ + private bool $running = true; + + /** + * All listeners for read/write event. + * + * @var array + */ + private array $readEvents = []; + + /** + * All listeners for read/write event. + * + * @var array + */ + private array $writeEvents = []; + + /** + * @var array + */ + private array $exceptEvents = []; + + /** + * Event listeners of signal. + * + * @var array + */ + private array $signalEvents = []; + + /** + * Fds waiting for read event. + * + * @var array + */ + private array $readFds = []; + + /** + * Fds waiting for write event. + * + * @var array + */ + private array $writeFds = []; + + /** + * Fds waiting for except event. + * + * @var array + */ + private array $exceptFds = []; + + /** + * Timer scheduler. + * {['data':timer_id, 'priority':run_timestamp], ..} + * + * @var SplPriorityQueue + */ + private SplPriorityQueue $scheduler; + + /** + * All timer event listeners. + * [[func, args, flag, timer_interval], ..] + * + * @var array + */ + private array $eventTimer = []; + + /** + * Timer id. + * + * @var int + */ + private int $timerId = 1; + + /** + * Select timeout. + * + * @var int + */ + private int $selectTimeout = self::MAX_SELECT_TIMOUT_US; + + /** + * Next run time of the timer. + * + * @var float + */ + private float $nextTickTime = 0; + + /** + * @var ?callable + */ + private $errorHandler = null; + + /** + * Select timeout. + * + * @var int + */ + const MAX_SELECT_TIMOUT_US = 800000; + + /** + * Construct. + */ + public function __construct() + { + $this->scheduler = new SplPriorityQueue(); + $this->scheduler->setExtractFlags(SplPriorityQueue::EXTR_BOTH); + } + + /** + * {@inheritdoc} + */ + public function delay(float $delay, callable $func, array $args = []): int + { + $timerId = $this->timerId++; + $runTime = microtime(true) + $delay; + $this->scheduler->insert($timerId, -$runTime); + $this->eventTimer[$timerId] = [$func, $args]; + if ($this->nextTickTime == 0 || $this->nextTickTime > $runTime) { + $this->setNextTickTime($runTime); + } + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function repeat(float $interval, callable $func, array $args = []): int + { + $timerId = $this->timerId++; + $runTime = microtime(true) + $interval; + $this->scheduler->insert($timerId, -$runTime); + $this->eventTimer[$timerId] = [$func, $args, $interval]; + if ($this->nextTickTime == 0 || $this->nextTickTime > $runTime) { + $this->setNextTickTime($runTime); + } + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function offDelay(int $timerId): bool + { + if (isset($this->eventTimer[$timerId])) { + unset($this->eventTimer[$timerId]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function offRepeat(int $timerId): bool + { + return $this->offDelay($timerId); + } + + /** + * {@inheritdoc} + */ + public function onReadable($stream, callable $func): void + { + $count = count($this->readFds); + if ($count >= 1024) { + trigger_error("System call select exceeded the maximum number of connections 1024, please install event extension for more connections.", E_USER_WARNING); + } else if (DIRECTORY_SEPARATOR !== '/' && $count >= 256) { + trigger_error("System call select exceeded the maximum number of connections 256.", E_USER_WARNING); + } + $fdKey = (int)$stream; + $this->readEvents[$fdKey] = $func; + $this->readFds[$fdKey] = $stream; + } + + /** + * {@inheritdoc} + */ + public function offReadable($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->readEvents[$fdKey])) { + unset($this->readEvents[$fdKey], $this->readFds[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onWritable($stream, callable $func): void + { + $count = count($this->writeFds); + if ($count >= 1024) { + trigger_error("System call select exceeded the maximum number of connections 1024, please install event/libevent extension for more connections.", E_USER_WARNING); + } else if (DIRECTORY_SEPARATOR !== '/' && $count >= 256) { + trigger_error("System call select exceeded the maximum number of connections 256.", E_USER_WARNING); + } + $fdKey = (int)$stream; + $this->writeEvents[$fdKey] = $func; + $this->writeFds[$fdKey] = $stream; + } + + /** + * {@inheritdoc} + */ + public function offWritable($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->writeEvents[$fdKey])) { + unset($this->writeEvents[$fdKey], $this->writeFds[$fdKey]); + return true; + } + return false; + } + + /** + * On except. + * + * @param resource $stream + * @param callable $func + */ + public function onExcept($stream, callable $func): void + { + $fdKey = (int)$stream; + $this->exceptEvents[$fdKey] = $func; + $this->exceptFds[$fdKey] = $stream; + } + + /** + * Off except. + * + * @param resource $stream + * @return bool + */ + public function offExcept($stream): bool + { + $fdKey = (int)$stream; + if (isset($this->exceptEvents[$fdKey])) { + unset($this->exceptEvents[$fdKey], $this->exceptFds[$fdKey]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onSignal(int $signal, callable $func): void + { + if (!function_exists('pcntl_signal')) { + return; + } + $this->signalEvents[$signal] = $func; + pcntl_signal($signal, fn (...$args) => $this->safeCall($this->signalEvents[$signal], [$signal])); + } + + /** + * {@inheritdoc} + */ + public function offSignal(int $signal): bool + { + if (!function_exists('pcntl_signal')) { + return false; + } + pcntl_signal($signal, SIG_IGN); + if (isset($this->signalEvents[$signal])) { + unset($this->signalEvents[$signal]); + return true; + } + return false; + } + + /** + * Tick for timer. + * + * @return void + */ + protected function tick(): void + { + $tasksToInsert = []; + while (!$this->scheduler->isEmpty()) { + $schedulerData = $this->scheduler->top(); + $timerId = $schedulerData['data']; + $nextRunTime = -$schedulerData['priority']; + $timeNow = microtime(true); + $this->selectTimeout = (int)(($nextRunTime - $timeNow) * 1000000); + + if ($this->selectTimeout <= 0) { + $this->scheduler->extract(); + + if (!isset($this->eventTimer[$timerId])) { + continue; + } + + // [func, args, timer_interval] + $taskData = $this->eventTimer[$timerId]; + if (isset($taskData[2])) { + $nextRunTime = $timeNow + $taskData[2]; + $tasksToInsert[] = [$timerId, -$nextRunTime]; + } else { + unset($this->eventTimer[$timerId]); + } + $this->safeCall($taskData[0], $taskData[1]); + } else { + break; + } + } + foreach ($tasksToInsert as $item) { + $this->scheduler->insert($item[0], $item[1]); + } + if (!$this->scheduler->isEmpty()) { + $schedulerData = $this->scheduler->top(); + $nextRunTime = -$schedulerData['priority']; + $this->setNextTickTime($nextRunTime); + return; + } + $this->setNextTickTime(0); + } + + /** + * Set next tick time. + * + * @param float $nextTickTime + * @return void + */ + protected function setNextTickTime(float $nextTickTime): void + { + $this->nextTickTime = $nextTickTime; + if ($nextTickTime == 0) { + $this->selectTimeout = self::MAX_SELECT_TIMOUT_US; + return; + } + $this->selectTimeout = min(max((int)(($nextTickTime - microtime(true)) * 1000000), 0), self::MAX_SELECT_TIMOUT_US); + } + + /** + * {@inheritdoc} + */ + public function deleteAllTimer(): void + { + $this->scheduler = new SplPriorityQueue(); + $this->scheduler->setExtractFlags(SplPriorityQueue::EXTR_BOTH); + $this->eventTimer = []; + } + + /** + * {@inheritdoc} + */ + public function run(): void + { + while ($this->running) { + $read = $this->readFds; + $write = $this->writeFds; + $except = $this->exceptFds; + if ($read || $write || $except) { + // Waiting read/write/signal/timeout events. + try { + @stream_select($read, $write, $except, 0, $this->selectTimeout); + } catch (Throwable) { + // do nothing + } + } else { + $this->selectTimeout >= 1 && usleep($this->selectTimeout); + } + + foreach ($read as $fd) { + $fdKey = (int)$fd; + if (isset($this->readEvents[$fdKey])) { + $this->readEvents[$fdKey]($fd); + } + } + + foreach ($write as $fd) { + $fdKey = (int)$fd; + if (isset($this->writeEvents[$fdKey])) { + $this->writeEvents[$fdKey]($fd); + } + } + + foreach ($except as $fd) { + $fdKey = (int)$fd; + if (isset($this->exceptEvents[$fdKey])) { + $this->exceptEvents[$fdKey]($fd); + } + } + + if ($this->nextTickTime > 0) { + if (microtime(true) >= $this->nextTickTime) { + $this->tick(); + } else { + $this->selectTimeout = (int)(($this->nextTickTime - microtime(true)) * 1000000); + } + } + + // The $this->signalEvents are empty under Windows, make sure not to call pcntl_signal_dispatch. + if ($this->signalEvents) { + // Calls signal handlers for pending signals + pcntl_signal_dispatch(); + } + } + } + + /** + * {@inheritdoc} + */ + public function stop(): void + { + $this->running = false; + $this->deleteAllTimer(); + foreach ($this->signalEvents as $signal => $item) { + $this->offsignal($signal); + } + $this->readFds = []; + $this->writeFds = []; + $this->exceptFds = []; + $this->readEvents = []; + $this->writeEvents = []; + $this->exceptEvents = []; + $this->signalEvents = []; + } + + /** + * {@inheritdoc} + */ + public function getTimerCount(): int + { + return count($this->eventTimer); + } + + /** + * {@inheritdoc} + */ + public function setErrorHandler(callable $errorHandler): void + { + $this->errorHandler = $errorHandler; + } + + /** + * @param callable $func + * @param array $args + * @return void + */ + private function safeCall(callable $func, array $args = []): void + { + try { + $func(...$args); + } catch (Throwable $e) { + if ($this->errorHandler === null) { + echo $e; + } else { + ($this->errorHandler)($e); + } + } + } +} diff --git a/vendor/workerman/workerman/src/Events/Swoole.php b/vendor/workerman/workerman/src/Events/Swoole.php new file mode 100644 index 0000000..329c87e --- /dev/null +++ b/vendor/workerman/workerman/src/Events/Swoole.php @@ -0,0 +1,298 @@ + + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Events; + +use Swoole\Coroutine; +use Swoole\Event; +use Swoole\Process; +use Swoole\Timer; +use Throwable; + +final class Swoole implements EventInterface +{ + /** + * All listeners for read timer + * + * @var array + */ + private array $eventTimer = []; + + /** + * All listeners for read event. + * + * @var array + */ + private array $readEvents = []; + + /** + * All listeners for write event. + * + * @var array + */ + private array $writeEvents = []; + + /** + * @var ?callable + */ + private $errorHandler = null; + + private bool $stopping = false; + + /** + * Constructor. + */ + public function __construct() + { + Coroutine::set(['hook_flags' => SWOOLE_HOOK_ALL]); + } + + /** + * {@inheritdoc} + */ + public function delay(float $delay, callable $func, array $args = []): int + { + $t = (int)($delay * 1000); + $t = max($t, 1); + $timerId = Timer::after($t, function () use ($func, $args, &$timerId) { + unset($this->eventTimer[$timerId]); + $this->safeCall($func, $args); + }); + $this->eventTimer[$timerId] = $timerId; + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function offDelay(int $timerId): bool + { + if (isset($this->eventTimer[$timerId])) { + Timer::clear($timerId); + unset($this->eventTimer[$timerId]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function offRepeat(int $timerId): bool + { + return $this->offDelay($timerId); + } + + /** + * {@inheritdoc} + */ + public function repeat(float $interval, callable $func, array $args = []): int + { + $t = (int)($interval * 1000); + $t = max($t, 1); + $timerId = Timer::tick($t, function () use ($func, $args) { + $this->safeCall($func, $args); + }); + $this->eventTimer[$timerId] = $timerId; + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function onReadable($stream, callable $func): void + { + $fd = (int)$stream; + if (!isset($this->readEvents[$fd]) && !isset($this->writeEvents[$fd])) { + Event::add($stream, fn () => $this->callRead($fd), null, SWOOLE_EVENT_READ); + } elseif (isset($this->writeEvents[$fd])) { + Event::set($stream, fn () => $this->callRead($fd), null, SWOOLE_EVENT_READ | SWOOLE_EVENT_WRITE); + } else { + Event::set($stream, fn () => $this->callRead($fd), null, SWOOLE_EVENT_READ); + } + + $this->readEvents[$fd] = [$func, [$stream]]; + } + + /** + * {@inheritdoc} + */ + public function offReadable($stream): bool + { + $fd = (int)$stream; + if (!isset($this->readEvents[$fd])) { + return false; + } + unset($this->readEvents[$fd]); + if (!isset($this->writeEvents[$fd])) { + Event::del($stream); + return true; + } + Event::set($stream, null, null, SWOOLE_EVENT_WRITE); + return true; + } + + /** + * {@inheritdoc} + */ + public function onWritable($stream, callable $func): void + { + $fd = (int)$stream; + if (!isset($this->readEvents[$fd]) && !isset($this->writeEvents[$fd])) { + Event::add($stream, null, fn () => $this->callWrite($fd), SWOOLE_EVENT_WRITE); + } elseif (isset($this->readEvents[$fd])) { + Event::set($stream, null, fn () => $this->callWrite($fd), SWOOLE_EVENT_WRITE | SWOOLE_EVENT_READ); + } else { + Event::set($stream, null, fn () =>$this->callWrite($fd), SWOOLE_EVENT_WRITE); + } + + $this->writeEvents[$fd] = [$func, [$stream]]; + } + + /** + * {@inheritdoc} + */ + public function offWritable($stream): bool + { + $fd = (int)$stream; + if (!isset($this->writeEvents[$fd])) { + return false; + } + unset($this->writeEvents[$fd]); + if (!isset($this->readEvents[$fd])) { + Event::del($stream); + return true; + } + Event::set($stream, null, null, SWOOLE_EVENT_READ); + return true; + } + + /** + * {@inheritdoc} + */ + public function onSignal(int $signal, callable $func): void + { + Process::signal($signal, fn () => $this->safeCall($func, [$signal])); + } + + /** + * Please see https://wiki.swoole.com/#/process/process?id=signal + * {@inheritdoc} + */ + public function offSignal(int $signal): bool + { + return Process::signal($signal, null); + } + + /** + * {@inheritdoc} + */ + public function deleteAllTimer(): void + { + foreach ($this->eventTimer as $timerId) { + Timer::clear($timerId); + } + } + + /** + * {@inheritdoc} + */ + public function run(): void + { + // Avoid process exit due to no listening + Timer::tick(100000000, static fn() => null); + Event::wait(); + } + + /** + * Destroy loop. + * + * @return void + */ + public function stop(): void + { + if ($this->stopping) { + return; + } + $this->stopping = true; + // Cancel all coroutines before Event::exit + foreach (Coroutine::listCoroutines() as $coroutine) { + Coroutine::cancel($coroutine); + } + // Wait for coroutines to exit + usleep(200000); + Event::exit(); + } + + /** + * Get timer count. + * + * @return integer + */ + public function getTimerCount(): int + { + return count($this->eventTimer); + } + + /** + * {@inheritdoc} + */ + public function setErrorHandler(callable $errorHandler): void + { + $this->errorHandler = $errorHandler; + } + + /** + * @param $fd + * @return void + */ + private function callRead($fd) + { + if (isset($this->readEvents[$fd])) { + $this->safeCall($this->readEvents[$fd][0], $this->readEvents[$fd][1]); + } + } + + /** + * @param $fd + * @return void + */ + private function callWrite($fd) + { + if (isset($this->writeEvents[$fd])) { + $this->safeCall($this->writeEvents[$fd][0], $this->writeEvents[$fd][1]); + } + } + + /** + * @param callable $func + * @param array $args + * @return void + */ + private function safeCall(callable $func, array $args = []): void + { + Coroutine::create(function() use ($func, $args) { + try { + $func(...$args); + } catch (Throwable $e) { + if ($this->errorHandler === null) { + echo $e; + } else { + ($this->errorHandler)($e); + } + } + }); + } +} diff --git a/vendor/workerman/workerman/src/Events/Swow.php b/vendor/workerman/workerman/src/Events/Swow.php new file mode 100644 index 0000000..de53435 --- /dev/null +++ b/vendor/workerman/workerman/src/Events/Swow.php @@ -0,0 +1,307 @@ + + */ + private array $eventTimer = []; + + /** + * All listeners for read event. + * + * @var array + */ + private array $readEvents = []; + + /** + * All listeners for write event. + * + * @var array + */ + private array $writeEvents = []; + + /** + * All listeners for signal. + * + * @var array + */ + private array $signalListener = []; + + /** + * @var ?callable + */ + private $errorHandler = null; + + /** + * Get timer count. + * + * @return integer + */ + public function getTimerCount(): int + { + return count($this->eventTimer); + } + + /** + * {@inheritdoc} + */ + public function delay(float $delay, callable $func, array $args = []): int + { + $t = (int)($delay * 1000); + $t = max($t, 1); + $coroutine = Coroutine::run(function () use ($t, $func, $args): void { + msleep($t); + unset($this->eventTimer[Coroutine::getCurrent()->getId()]); + $this->safeCall($func, $args); + }); + $timerId = $coroutine->getId(); + $this->eventTimer[$timerId] = $timerId; + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function repeat(float $interval, callable $func, array $args = []): int + { + $t = (int)($interval * 1000); + $t = max($t, 1); + $coroutine = Coroutine::run(function () use ($t, $func, $args): void { + // @phpstan-ignore-next-line While loop condition is always true. + while (true) { + msleep($t); + $this->safeCall($func, $args); + } + }); + $timerId = $coroutine->getId(); + $this->eventTimer[$timerId] = $timerId; + return $timerId; + } + + /** + * {@inheritdoc} + */ + public function offDelay(int $timerId): bool + { + if (isset($this->eventTimer[$timerId])) { + try { + (Coroutine::getAll()[$timerId])->kill(); + return true; + } finally { + unset($this->eventTimer[$timerId]); + } + } + return false; + } + + /** + * {@inheritdoc} + */ + public function offRepeat(int $timerId): bool + { + return $this->offDelay($timerId); + } + + /** + * {@inheritdoc} + */ + public function deleteAllTimer(): void + { + foreach ($this->eventTimer as $timerId) { + $this->offDelay($timerId); + } + } + + /** + * {@inheritdoc} + */ + public function onReadable($stream, callable $func): void + { + $fd = (int)$stream; + if (isset($this->readEvents[$fd])) { + $this->offReadable($stream); + } + Coroutine::run(function () use ($stream, $func, $fd): void { + try { + $this->readEvents[$fd] = Coroutine::getCurrent(); + while (true) { + if (!is_resource($stream)) { + $this->offReadable($stream); + break; + } + // Under Windows, setting a timeout is necessary; otherwise, the accept cannot be listened to. + // Setting it to 1000ms will result in a 1-second delay for the first accept under Windows. + if (!isset($this->readEvents[$fd]) || $this->readEvents[$fd] !== Coroutine::getCurrent()) { + break; + } + $rEvent = stream_poll_one($stream, STREAM_POLLIN | STREAM_POLLHUP, 1000); + if ($rEvent !== STREAM_POLLNONE) { + $this->safeCall($func, [$stream]); + } + if ($rEvent !== STREAM_POLLIN && $rEvent !== STREAM_POLLNONE) { + $this->offReadable($stream); + break; + } + } + } catch (RuntimeException) { + $this->offReadable($stream); + } + }); + } + + /** + * {@inheritdoc} + */ + public function offReadable($stream): bool + { + // 在当前协程执行 $coroutine->kill() 会导致不可预知问题,所以没有使用$coroutine->kill() + $fd = (int)$stream; + if (isset($this->readEvents[$fd])) { + unset($this->readEvents[$fd]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onWritable($stream, callable $func): void + { + $fd = (int)$stream; + if (isset($this->writeEvents[$fd])) { + $this->offWritable($stream); + } + Coroutine::run(function () use ($stream, $func, $fd): void { + try { + $this->writeEvents[$fd] = Coroutine::getCurrent(); + while (true) { + if (!is_resource($stream)) { + $this->offWritable($stream); + break; + } + if (!isset($this->writeEvents[$fd]) || $this->writeEvents[$fd] !== Coroutine::getCurrent()) { + break; + } + $rEvent = stream_poll_one($stream, STREAM_POLLOUT | STREAM_POLLHUP, 1000); + if ($rEvent !== STREAM_POLLNONE) { + $this->safeCall($func, [$stream]); + } + if ($rEvent !== STREAM_POLLOUT && $rEvent !== STREAM_POLLNONE) { + $this->offWritable($stream); + break; + } + } + } catch (RuntimeException) { + $this->offWritable($stream); + } + }); + } + + /** + * {@inheritdoc} + */ + public function offWritable($stream): bool + { + $fd = (int)$stream; + if (isset($this->writeEvents[$fd])) { + unset($this->writeEvents[$fd]); + return true; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function onSignal(int $signal, callable $func): void + { + Coroutine::run(function () use ($signal, $func): void { + $this->signalListener[$signal] = Coroutine::getCurrent(); + while (1) { + try { + Signal::wait($signal); + if (!isset($this->signalListener[$signal]) || + $this->signalListener[$signal] !== Coroutine::getCurrent()) { + break; + } + $this->safeCall($func, [$signal]); + } catch (SignalException) { + // do nothing + } + } + }); + } + + /** + * {@inheritdoc} + */ + public function offSignal(int $signal): bool + { + if (!isset($this->signalListener[$signal])) { + return false; + } + unset($this->signalListener[$signal]); + return true; + } + + /** + * {@inheritdoc} + */ + public function run(): void + { + waitAll(); + } + + /** + * Destroy loop. + * + * @return void + */ + public function stop(): void + { + Coroutine::killAll(); + } + + /** + * {@inheritdoc} + */ + public function setErrorHandler(callable $errorHandler): void + { + $this->errorHandler = $errorHandler; + } + + /** + * @param callable $func + * @param array $args + * @return void + */ + private function safeCall(callable $func, array $args = []): void + { + Coroutine::run(function () use ($func, $args): void { + try { + $func(...$args); + } catch (\Throwable $e) { + if ($this->errorHandler === null) { + echo $e; + } else { + ($this->errorHandler)($e); + } + } + }); + } + +} diff --git a/vendor/workerman/workerman/src/Protocols/Frame.php b/vendor/workerman/workerman/src/Protocols/Frame.php new file mode 100644 index 0000000..c8ce71c --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Frame.php @@ -0,0 +1,66 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols; + +use function pack; +use function strlen; +use function substr; +use function unpack; + +/** + * Frame Protocol. + */ +class Frame +{ + /** + * Check the integrity of the package. + * + * @param string $buffer + * @return int + */ + public static function input(string $buffer): int + { + if (strlen($buffer) < 4) { + return 0; + } + $unpackData = unpack('Ntotal_length', $buffer); + return $unpackData['total_length']; + } + + /** + * Decode. + * + * @param string $buffer + * @return string + */ + public static function decode(string $buffer): string + { + return substr($buffer, 4); + } + + /** + * Encode. + * + * @param string $data + * @return string + */ + public static function encode(string $data): string + { + $totalLength = 4 + strlen($data); + return pack('N', $totalLength) . $data; + } +} diff --git a/vendor/workerman/workerman/src/Protocols/Http.php b/vendor/workerman/workerman/src/Protocols/Http.php new file mode 100644 index 0000000..8a64fc7 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http.php @@ -0,0 +1,518 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols; + +use Workerman\Connection\TcpConnection; +use Workerman\Protocols\Http\Request; +use Workerman\Protocols\Http\Response; +use function clearstatcache; +use function count; +use function ctype_digit; +use function ctype_xdigit; +use function explode; +use function filesize; +use function fopen; +use function fread; +use function fseek; +use function ftell; +use function hexdec; +use function ini_get; +use function is_array; +use function is_object; +use function ltrim; +use function preg_match; +use function preg_replace; +use function strlen; +use function strpos; +use function strtolower; +use function substr; +use function sys_get_temp_dir; +use function trim; + +/** + * Class Http. + * @package Workerman\Protocols + */ +class Http +{ + /** + * Request class name. + * + * @var string + */ + protected static string $requestClass = Request::class; + + /** + * Upload tmp dir. + * + * @var string + */ + protected static string $uploadTmpDir = ''; + + /** + * Bad request. + * + * @var string + */ + protected const HTTP_400 = "HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"; + + /** + * Payload too large. + * + * @var string + */ + protected const HTTP_413 = "HTTP/1.1 413 Payload Too Large\r\nConnection: close\r\n\r\n"; + + /** + * Request Header Fields Too Large. + * + * @var string + */ + protected const HTTP_431 = "HTTP/1.1 431 Request Header Fields Too Large\r\nConnection: close\r\n\r\n"; + + /** + * Max bytes buffered while waiting for end of headers, and max offset of "\r\n\r\n" (header block size limit). + */ + + protected const MAX_HEADER_LENGTH = 16384; + + /** + * Get or set the request class name. + * + * @param class-string|null $className + * @return string + */ + public static function requestClass(?string $className = null): string + { + if ($className !== null) { + static::$requestClass = $className; + } + return static::$requestClass; + } + + /** + * Check the integrity of the package. + * + * @param string $buffer + * @param TcpConnection $connection + * @return int + */ + public static function input(string $buffer, TcpConnection $connection): int + { + static $cache = []; + + $crlfPos = strpos($buffer, "\r\n\r\n"); + if (false === $crlfPos) { + if (strlen($buffer) >= static::MAX_HEADER_LENGTH) { + $connection->end(static::HTTP_431, true); + } + return 0; + } + + $length = $crlfPos + 4; + if ($crlfPos >= static::MAX_HEADER_LENGTH) { + $connection->end(static::HTTP_431, true); + return 0; + } + $header = isset($buffer[$length + 1]) ? substr($buffer, 0, $length) : $buffer; + + if ($length <= TcpConnection::MAX_CACHE_STRING_LENGTH && isset($cache[$header])) { + return $cache[$header]; + } + + // Validate request line: METHOD SP origin-form SP HTTP/1.x + $firstLineEnd = strpos($header, "\r\n"); + if (!preg_match( + '~^(?-i:GET|POST|OPTIONS|HEAD|DELETE|PUT|PATCH) /[^\x00-\x20\x7f]* (?-i:HTTP)/1\.(?[0-9])$~', + substr($header, 0, $firstLineEnd), + $matches + )) { + $connection->end(static::HTTP_400, true); + return 0; + } + + // Parse headers + $headers = []; + $headerBody = substr($header, $firstLineEnd + 2, $crlfPos - $firstLineEnd - 2); + foreach (explode("\r\n", $headerBody) as $line) { + if ($line === '') { + continue; + } + $parts = explode(':', $line, 2); + // field-name must be a token: 1*tchar (RFC 7230 §3.2.6) + if (!isset($parts[1]) || !preg_match('/^[a-zA-Z0-9!#$%&\'*+\-.^_`|~]+$/', $parts[0])) { + $connection->end(static::HTTP_400, true); + return 0; + } + $headers[strtolower($parts[0])][] = trim($parts[1], " \t"); + } + + // Host: required for HTTP/1.1, must not be duplicated for any version (RFC 9112 Section 3.2) + $hostCount = count($headers['host'] ?? []); + if ($hostCount > 1 || ((int)$matches['minor'] > 0 && $hostCount === 0)) { + $connection->end(static::HTTP_400, true); + return 0; + } + if ($hostCount === 1 && !preg_match('/^(?:\[[^\]\r\n]+\]|[^\s:\/\[\]\r\n]+)(?::[0-9]+)?$/', $headers['host'][0])) { + $connection->end(static::HTTP_400, true); + return 0; + } + + // Transfer-Encoding: must be sole header with value "chunked", no Content-Length + if (isset($headers['transfer-encoding'])) { + if (isset($headers['content-length']) + || count($headers['transfer-encoding']) !== 1 + || strtolower($headers['transfer-encoding'][0]) !== 'chunked') { + $connection->end(static::HTTP_400, true); + return 0; + } + return static::inputChunked($buffer, $connection, $length); + } + + // Content-Length: must be single header with pure-digit value + if (isset($headers['content-length'])) { + if (count($headers['content-length']) !== 1 || !ctype_digit($headers['content-length'][0])) { + $connection->end(static::HTTP_400, true); + return 0; + } + $length += (int)$headers['content-length'][0]; + } + + if ($length > $connection->maxPackageSize) { + $connection->end(static::HTTP_413, true); + return 0; + } + + if ($length <= TcpConnection::MAX_CACHE_STRING_LENGTH) { + $cache[$header] = $length; + if (count($cache) > TcpConnection::MAX_CACHE_SIZE) { + unset($cache[key($cache)]); + } + } + return $length; + } + + /** + * Check the integrity of a chunked transfer-encoded request body. + * + * @param string $buffer + * @param TcpConnection $connection + * @param int $headerLength + * @return int + */ + protected static function inputChunked(string $buffer, TcpConnection $connection, int $headerLength): int + { + $connection->context ??= new \stdClass(); + $connection->context->chunked = true; + + $pos = $headerLength; + $bufLen = strlen($buffer); + $maxSize = $connection->maxPackageSize; + + while (true) { + $lineEnd = strpos($buffer, "\r\n", $pos); + if ($lineEnd === false) { + return 0; + } + + $semiPos = strpos($buffer, ';', $pos); + $hexEnd = ($semiPos !== false && $semiPos < $lineEnd) ? $semiPos : $lineEnd; + $hexStr = substr($buffer, $pos, $hexEnd - $pos); + + if ($hexStr === '' || !ctype_xdigit($hexStr) || isset($hexStr[16])) { + $connection->end(static::HTTP_400, true); + return 0; + } + + $chunkSize = hexdec($hexStr); + if (is_float($chunkSize)) { + $connection->end(static::HTTP_400, true); + return 0; + } + $pos = $lineEnd + 2; + + if ($chunkSize === 0) { + while (true) { + $lineEnd = strpos($buffer, "\r\n", $pos); + if ($lineEnd === false) { + return 0; + } + if ($lineEnd === $pos) { + $totalLength = $pos + 2; + if ($totalLength > $maxSize) { + $connection->end(static::HTTP_413, true); + return 0; + } + return $totalLength; + } + $pos = $lineEnd + 2; + } + } + + if ($pos + $chunkSize + 2 > $bufLen) { + return 0; + } + if (substr($buffer, $pos + $chunkSize, 2) !== "\r\n") { + $connection->end(static::HTTP_400, true); + return 0; + } + $pos += $chunkSize + 2; + + if ($pos > $maxSize) { + $connection->end(static::HTTP_413, true); + return 0; + } + } + } + + /** + * Http decode. + * + * @param string $buffer + * @param TcpConnection $connection + * @return mixed + */ + public static function decode(string $buffer, TcpConnection $connection): mixed + { + $trailers = []; + if (isset($connection->context->chunked)) { + unset($connection->context->chunked); + [$buffer, $trailers] = static::decodeChunked($buffer, strpos($buffer, "\r\n\r\n")); + } + + $request = new static::$requestClass($buffer); + if ($trailers !== []) { + $request->setChunkTrailers($trailers); + } + $request->connection = $connection; + return $request; + } + + /** + * Decode a chunked transfer-encoded request into a normalized buffer. + * + * @param string $buffer + * @param int $headerEnd + * @return array{string, array} + */ + protected static function decodeChunked(string $buffer, int $headerEnd): array + { + $header = preg_replace('~\r\nTransfer-Encoding[ \t]*:[^\r]*~i', '', substr($buffer, 0, $headerEnd), 1); + $body = ''; + $trailers = []; + $pos = $headerEnd + 4; + $bufLen = strlen($buffer); + + while (true) { + $lineEnd = strpos($buffer, "\r\n", $pos); + if ($lineEnd === false) { + break; + } + + $semiPos = strpos($buffer, ';', $pos); + $hexEnd = ($semiPos !== false && $semiPos < $lineEnd) ? $semiPos : $lineEnd; + $hexStr = substr($buffer, $pos, $hexEnd - $pos); + if ($hexStr === '' || !ctype_xdigit($hexStr) || isset($hexStr[16])) { + break; + } + + $chunkSize = hexdec($hexStr); + if (is_float($chunkSize)) { + break; + } + $pos = $lineEnd + 2; + + if ($chunkSize === 0) { + while (true) { + $lineEnd = strpos($buffer, "\r\n", $pos); + if ($lineEnd === false) { + break 2; + } + if ($lineEnd === $pos) { + $pos += 2; + break; + } + $colonPos = strpos($buffer, ':', $pos); + if ($colonPos !== false && $colonPos < $lineEnd) { + $trailers[strtolower(substr($buffer, $pos, $colonPos - $pos))] = ltrim(substr($buffer, $colonPos + 1, $lineEnd - $colonPos - 1)); + } + $pos = $lineEnd + 2; + } + break; + } + + if ($pos + $chunkSize + 2 > $bufLen) { + break; + } + if (substr($buffer, $pos + $chunkSize, 2) !== "\r\n") { + break; + } + $body .= substr($buffer, $pos, $chunkSize); + $pos += $chunkSize + 2; + } + + return [$header . "\r\nContent-Length: " . strlen($body) . "\r\n\r\n" . $body, $trailers]; + } + + /** + * Http encode. + * + * @param string|Response $response + * @param TcpConnection $connection + * @return string + */ + public static function encode(mixed $response, TcpConnection $connection): string + { + if (!is_object($response)) { + $extHeader = ''; + $contentType = 'text/html;charset=utf-8'; + foreach ($connection->headers as $name => $value) { + if ($name === 'Content-Type') { + $contentType = $value; + continue; + } + if (is_array($value)) { + foreach ($value as $item) { + $extHeader .= "$name: $item\r\n"; + } + } else { + $extHeader .= "$name: $value\r\n"; + } + } + $connection->headers = []; + $response = (string)$response; + $bodyLen = strlen($response); + return "HTTP/1.1 200 OK\r\n{$extHeader}Connection: keep-alive\r\nContent-Type: $contentType\r\nContent-Length: $bodyLen\r\n\r\n$response"; + } + + if ($connection->headers) { + $response->withHeaders($connection->headers); + $connection->headers = []; + } + + if (isset($response->file)) { + $file = $response->file['file']; + $offset = $response->file['offset'] ?: 0; + $length = $response->file['length'] ?: 0; + clearstatcache(); + $fileSize = (int)filesize($file); + $bodyLen = $length > 0 ? $length : $fileSize - $offset; + $response->withHeaders([ + 'Content-Length' => $bodyLen, + 'Accept-Ranges' => 'bytes', + ]); + + if ($offset || $length) { + $offsetEnd = $offset + $bodyLen - 1; + $response->header('Content-Range', "bytes $offset-$offsetEnd/$fileSize"); + $response->withStatus(206); + } + if ($bodyLen < 2 * 1024 * 1024) { + $connection->send($response . file_get_contents($file, false, null, $offset, $bodyLen), true); + return ''; + } + $handler = fopen($file, 'r'); + if (false === $handler) { + $connection->close(new Response(403, [], '403 Forbidden')); + return ''; + } + $connection->send((string)$response, true); + static::sendStream($connection, $handler, $offset, $length); + return ''; + } + + return (string)$response; + } + + /** + * Send remainder of a stream to client. + * + * @param TcpConnection $connection + * @param resource $handler + * @param int $offset + * @param int $length + */ + protected static function sendStream(TcpConnection $connection, $handler, int $offset = 0, int $length = 0): void + { + $connection->context->bufferFull = false; + $connection->context->streamSending = true; + if ($offset !== 0) { + fseek($handler, $offset); + } + $offsetEnd = $offset + $length; + // Read file content from disk piece by piece and send to client. + $doWrite = function () use ($connection, $handler, $length, $offsetEnd) { + // Send buffer not full. + /** @phpstan-ignore-next-line */ + while ($connection->context->bufferFull === false) { + // Read from disk. + $size = 1024 * 1024; + if ($length !== 0) { + $tell = ftell($handler); + $remainSize = $offsetEnd - $tell; + if ($remainSize <= 0) { + fclose($handler); + $connection->onBufferDrain = null; + return; + } + $size = min($remainSize, $size); + } + + $buffer = fread($handler, $size); + // Read eof. + if ($buffer === '' || $buffer === false) { + fclose($handler); + $connection->onBufferDrain = null; + $connection->context->streamSending = false; + return; + } + $connection->send($buffer, true); + } + }; + // Send buffer full. + $connection->onBufferFull = function ($connection) { + $connection->context->bufferFull = true; + }; + // Send buffer drain. + $connection->onBufferDrain = function ($connection) use ($doWrite) { + $connection->context->bufferFull = false; + $doWrite(); + }; + $doWrite(); + } + + /** + * Set or get uploadTmpDir. + * + * @param string|null $dir + * @return string + */ + public static function uploadTmpDir(string|null $dir = null): string + { + if (null !== $dir) { + static::$uploadTmpDir = $dir; + } + if (static::$uploadTmpDir === '') { + if ($uploadTmpDir = ini_get('upload_tmp_dir')) { + static::$uploadTmpDir = $uploadTmpDir; + } else if ($uploadTmpDir = sys_get_temp_dir()) { + static::$uploadTmpDir = $uploadTmpDir; + } + } + return static::$uploadTmpDir; + } +} diff --git a/vendor/workerman/workerman/src/Protocols/Http/Chunk.php b/vendor/workerman/workerman/src/Protocols/Http/Chunk.php new file mode 100644 index 0000000..2c7a2a8 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/Chunk.php @@ -0,0 +1,37 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http; + +use Stringable; + +use function dechex; +use function strlen; + +/** + * Class Chunk + * @package Workerman\Protocols\Http + */ +class Chunk implements Stringable +{ + + public function __construct(protected string $buffer) {} + + public function __toString(): string + { + return dechex(strlen($this->buffer)) . "\r\n$this->buffer\r\n"; + } +} diff --git a/vendor/workerman/workerman/src/Protocols/Http/Request.php b/vendor/workerman/workerman/src/Protocols/Http/Request.php new file mode 100644 index 0000000..a00b6a2 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/Request.php @@ -0,0 +1,847 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http; + +use Exception; +use RuntimeException; +use Stringable; +use Workerman\Connection\TcpConnection; +use Workerman\Protocols\Http; +use function array_walk_recursive; +use function bin2hex; +use function clearstatcache; +use function count; +use function explode; +use function file_put_contents; +use function is_file; +use function json_decode; +use function ltrim; +use function microtime; +use function pack; +use function parse_str; +use function parse_url; +use function preg_match; +use function preg_replace; +use function strlen; +use function strpos; +use function strstr; +use function strtolower; +use function substr; +use function tempnam; +use function trim; +use function unlink; +use function urlencode; + +/** + * Class Request + * @package Workerman\Protocols\Http + */ +class Request implements Stringable +{ + /** + * Connection. + * + * @var ?TcpConnection + */ + public ?TcpConnection $connection = null; + + /** + * @var int + */ + public static int $maxFileUploads = 1024; + + /** + * Maximum string length for cache + * + * @var int + */ + public const MAX_CACHE_STRING_LENGTH = 4096; + + /** + * Maximum cache size. + * + * @var int + */ + public const MAX_CACHE_SIZE = 256; + + /** + * Properties. + * + * @var array + */ + public array $properties = []; + + /** + * Request data. + * + * @var array + */ + protected array $data = []; + + /** + * Is safe. + * + * @var bool + */ + protected bool $isSafe = true; + + /** + * Context. + * + * @var array + */ + public array $context = []; + + /** + * HTTP/1.1 chunked trailers (field names lowercased), set once by the protocol layer. + * + * @var ?array + */ + protected ?array $chunkTrailers = null; + + /** + * Request constructor. + */ + public function __construct(protected string $buffer) {} + + /** + * @internal Set by {@see Http::decode()} for chunked requests; first call wins. + * + * @param array $trailers + * @return void + */ + public function setChunkTrailers(array $trailers): void + { + if ($this->chunkTrailers !== null) { + return; + } + $this->chunkTrailers = $trailers; + } + + /** + * Get query. + * + * @param string|null $name + * @param mixed $default + * @return mixed + */ + public function get(?string $name = null, mixed $default = null): mixed + { + if (!isset($this->data['get'])) { + $this->parseGet(); + } + if (null === $name) { + return $this->data['get']; + } + return $this->data['get'][$name] ?? $default; + } + + /** + * Get post. + * + * @param string|null $name + * @param mixed $default + * @return mixed + */ + public function post(?string $name = null, mixed $default = null): mixed + { + if (!isset($this->data['post'])) { + $this->parsePost(); + } + if (null === $name) { + return $this->data['post']; + } + return $this->data['post'][$name] ?? $default; + } + + /** + * Get header item by name. + * + * @param string|null $name + * @param mixed $default + * @return mixed + */ + public function header(?string $name = null, mixed $default = null): mixed + { + if (!isset($this->data['headers'])) { + $this->parseHeaders(); + } + if (null === $name) { + return $this->data['headers']; + } + $name = strtolower($name); + return $this->data['headers'][$name] ?? $default; + } + + /** + * Get trailer item by name. + * + * @param string|null $name + * @param mixed $default + * @return mixed + */ + public function trailer(?string $name = null, mixed $default = null): mixed + { + $all = $this->chunkTrailers ?? []; + if (null === $name) { + return $all; + } + return $all[strtolower($name)] ?? $default; + } + + /** + * Get cookie item by name. + * + * @param string|null $name + * @param mixed $default + * @return mixed + */ + public function cookie(?string $name = null, mixed $default = null): mixed + { + if (!isset($this->data['cookie'])) { + $cookies = explode(';', $this->header('cookie', '')); + $mapped = []; + + foreach ($cookies as $cookie) { + $cookie = explode('=', $cookie, 2); + if (count($cookie) !== 2) { + continue; + } + $mapped[trim($cookie[0])] = $cookie[1]; + } + $this->data['cookie'] = $mapped; + } + if ($name === null) { + return $this->data['cookie']; + } + return $this->data['cookie'][$name] ?? $default; + } + + /** + * Get upload files. + * + * @param string|null $name + * @return array|null + */ + public function file(?string $name = null): mixed + { + clearstatcache(); + if (!empty($this->data['files'])) { + array_walk_recursive($this->data['files'], function ($value, $key) { + if ($key === 'tmp_name' && !is_file($value)) { + $this->data['files'] = []; + } + }); + } + if (empty($this->data['files'])) { + $this->parsePost(); + } + if (null === $name) { + return $this->data['files']; + } + return $this->data['files'][$name] ?? null; + } + + /** + * Get method. + * + * @return string + */ + public function method(): string + { + if (!isset($this->data['method'])) { + $this->parseHeadFirstLine(); + } + return $this->data['method']; + } + + /** + * Get http protocol version. + * + * @return string + */ + public function protocolVersion(): string + { + if (!isset($this->data['protocolVersion'])) { + $this->parseProtocolVersion(); + } + return $this->data['protocolVersion']; + } + + /** + * Get host. + * + * @param bool $withoutPort + * @return string|null + */ + public function host(bool $withoutPort = false): ?string + { + $host = $this->header('host'); + if ($host && $withoutPort) { + return preg_replace('/:\d{1,5}$/', '', $host); + } + return $host; + } + + /** + * Get uri. + * + * @return string + */ + public function uri(): string + { + if (!isset($this->data['uri'])) { + $this->parseHeadFirstLine(); + } + return $this->data['uri']; + } + + /** + * Get path. + * + * @return string + */ + public function path(): string + { + if (!isset($this->data['path'])) { + $this->parseUriComponents(); + } + return $this->data['path']; + } + + /** + * Get query string. + * + * @return string + */ + public function queryString(): string + { + if (!isset($this->data['query_string'])) { + $this->parseUriComponents(); + } + return $this->data['query_string']; + } + + /** + * Parse URI into path and query string components (single parse_url call). + * + * @return void + */ + protected function parseUriComponents(): void + { + $uri = $this->uri(); + $parsed = parse_url($uri); + $this->data['path'] = $parsed['path'] ?? '/'; + $this->data['query_string'] = $parsed['query'] ?? ''; + } + + /** + * Get session. + * + * @return Session + * @throws Exception + */ + public function session(): Session + { + return $this->context['session'] ??= new Session($this->sessionId()); + } + + /** + * Get/Set session id. + * + * @param string|null $sessionId + * @return string + * @throws Exception + */ + public function sessionId(?string $sessionId = null): string + { + if ($sessionId) { + unset($this->context['sid'], $this->context['session']); + } + if (!isset($this->context['sid'])) { + $sessionName = Session::$name; + $sid = $sessionId ? '' : $this->cookie($sessionName); + // Strip surrounding double quotes (RFC 6265 allows DQUOTE-wrapped cookie values). + if (is_string($sid) && isset($sid[1]) && $sid[0] === '"' && $sid[-1] === '"') { + $sid = substr($sid, 1, -1); + } + $sid = $this->isValidSessionId($sid) ? $sid : ''; + if ($sid === '') { + if (!$this->connection) { + throw new RuntimeException('Request->session() fail, header already send'); + } + $sid = $sessionId ?: static::createSessionId(); + $cookieParams = Session::getCookieParams(); + $this->setSidCookie($sessionName, $sid, $cookieParams); + } + $this->context['sid'] = $sid; + } + return $this->context['sid']; + } + + /** + * Check if session id is valid. + * + * @param mixed $sessionId + * @return bool + */ + public function isValidSessionId(mixed $sessionId): bool + { + return is_string($sessionId) && preg_match('/^[a-zA-Z0-9,-]{16,256}$/', $sessionId); + } + + /** + * Session regenerate id. + * + * @param bool $deleteOldSession + * @return string + * @throws Exception + */ + public function sessionRegenerateId(bool $deleteOldSession = false): string + { + $session = $this->session(); + $sessionData = $session->all(); + if ($deleteOldSession) { + $session->flush(); + } + $newSid = static::createSessionId(); + $session = new Session($newSid); + $session->put($sessionData); + $cookieParams = Session::getCookieParams(); + $sessionName = Session::$name; + $this->setSidCookie($sessionName, $newSid, $cookieParams); + $this->context['sid'] = $newSid; + $this->context['session'] = $session; + return $newSid; + } + + /** + * Get http raw head. + * + * @return string + */ + public function rawHead(): string + { + return $this->data['head'] ??= strstr($this->buffer, "\r\n\r\n", true); + } + + /** + * Get http raw body. + * + * @return string + */ + public function rawBody(): string + { + return substr($this->buffer, strpos($this->buffer, "\r\n\r\n") + 4); + } + + /** + * Get raw buffer. + * + * @return string + */ + public function rawBuffer(): string + { + return $this->buffer; + } + + /** + * Parse first line of http header buffer. + * + * @return void + */ + protected function parseHeadFirstLine(): void + { + $firstLine = strstr($this->buffer, "\r\n", true); + $tmp = explode(' ', $firstLine, 3); + $this->data['method'] = $tmp[0]; + $this->data['uri'] = $tmp[1] ?? '/'; + } + + /** + * Parse protocol version. + * + * @return void + */ + protected function parseProtocolVersion(): void + { + $firstLine = strstr($this->buffer, "\r\n", true); + $httpStr = strstr($firstLine, 'HTTP/'); + $protocolVersion = $httpStr ? substr($httpStr, 5) : '1.0'; + $this->data['protocolVersion'] = $protocolVersion; + } + + /** + * Parse headers. + * + * @return void + */ + protected function parseHeaders(): void + { + static $cache = []; + $this->data['headers'] = []; + $rawHead = $this->rawHead(); + $endLinePosition = strpos($rawHead, "\r\n"); + if ($endLinePosition === false) { + return; + } + $headBuffer = substr($rawHead, $endLinePosition + 2); + $cacheable = !isset($headBuffer[static::MAX_CACHE_STRING_LENGTH]); + if ($cacheable && isset($cache[$headBuffer])) { + $this->data['headers'] = $cache[$headBuffer]; + return; + } + $headData = explode("\r\n", $headBuffer); + foreach ($headData as $content) { + if ($content === '') { + continue; + } + $parts = explode(':', $content, 2); + if (!isset($parts[1])) { + continue; + } + $key = strtolower($parts[0]); + $value = trim($parts[1], " \t"); + if (isset($this->data['headers'][$key])) { + $this->data['headers'][$key] = "{$this->data['headers'][$key]},$value"; + } else { + $this->data['headers'][$key] = $value; + } + } + if ($cacheable) { + $cache[$headBuffer] = $this->data['headers']; + if (count($cache) > static::MAX_CACHE_SIZE) { + unset($cache[key($cache)]); + } + } + } + + /** + * Parse head. + * + * @return void + */ + protected function parseGet(): void + { + static $cache = []; + $queryString = $this->queryString(); + $this->data['get'] = []; + if ($queryString === '') { + return; + } + $cacheable = !isset($queryString[static::MAX_CACHE_STRING_LENGTH]); + if ($cacheable && isset($cache[$queryString])) { + $this->data['get'] = $cache[$queryString]; + return; + } + parse_str($queryString, $this->data['get']); + if ($cacheable) { + $cache[$queryString] = $this->data['get']; + if (count($cache) > static::MAX_CACHE_SIZE) { + unset($cache[key($cache)]); + } + } + } + + /** + * Parse post. + * + * @return void + */ + protected function parsePost(): void + { + static $cache = []; + $this->data['post'] = $this->data['files'] = []; + $contentType = $this->header('content-type', ''); + if (preg_match('/boundary=(?|"([^"]+)"|([^\s";,]+))/i', $contentType, $match)) { + $httpPostBoundary = '--' . $match[1]; + $this->parseUploadFiles($httpPostBoundary); + return; + } + $bodyBuffer = $this->rawBody(); + if ($bodyBuffer === '') { + return; + } + $isJson = str_contains($contentType, 'json'); + $cacheable = !isset($bodyBuffer[static::MAX_CACHE_STRING_LENGTH]); + $cacheKey = $cacheable ? ($isJson ? 'json:' : 'form:') . $bodyBuffer : ''; + if ($cacheable && isset($cache[$cacheKey])) { + $this->data['post'] = $cache[$cacheKey]; + return; + } + if ($isJson) { + $this->data['post'] = (array)json_decode($bodyBuffer, true); + } else { + parse_str($bodyBuffer, $this->data['post']); + } + if ($cacheable) { + $cache[$cacheKey] = $this->data['post']; + if (count($cache) > static::MAX_CACHE_SIZE) { + unset($cache[key($cache)]); + } + } + } + + /** + * Parse upload files. + * + * @param string $httpPostBoundary + * @return void + */ + protected function parseUploadFiles(string $httpPostBoundary): void + { + $buffer = $this->buffer; + $postEncodeString = ''; + $filesEncodeString = ''; + $files = []; + $bodyPosition = strpos($buffer, "\r\n\r\n") + 4; + $offset = $bodyPosition + strlen($httpPostBoundary) + 2; + $maxCount = static::$maxFileUploads; + while ($maxCount-- > 0 && $offset) { + $offset = $this->parseUploadFile($httpPostBoundary, $offset, $postEncodeString, $filesEncodeString, $files); + } + if ($postEncodeString) { + parse_str($postEncodeString, $this->data['post']); + } + + if ($filesEncodeString) { + parse_str($filesEncodeString, $this->data['files']); + array_walk_recursive($this->data['files'], function (&$value) use ($files) { + $value = $files[$value]; + }); + } + } + + /** + * Parse upload file. + * + * @param string $boundary + * @param int $sectionStartOffset + * @param string $postEncodeString + * @param string $filesEncodeStr + * @param array $files + * @return int + */ + protected function parseUploadFile(string $boundary, int $sectionStartOffset, string &$postEncodeString, string &$filesEncodeStr, array &$files): int + { + $file = []; + $boundary = "\r\n$boundary"; + if (strlen($this->buffer) < $sectionStartOffset) { + return 0; + } + $sectionEndOffset = strpos($this->buffer, $boundary, $sectionStartOffset); + if (!$sectionEndOffset) { + return 0; + } + $contentLinesEndOffset = strpos($this->buffer, "\r\n\r\n", $sectionStartOffset); + if (!$contentLinesEndOffset || $contentLinesEndOffset + 4 > $sectionEndOffset) { + return 0; + } + $contentLinesStr = substr($this->buffer, $sectionStartOffset, $contentLinesEndOffset - $sectionStartOffset); + $contentLines = explode("\r\n", trim($contentLinesStr . "\r\n")); + $boundaryValue = substr($this->buffer, $contentLinesEndOffset + 4, $sectionEndOffset - $contentLinesEndOffset - 4); + $uploadKey = false; + foreach ($contentLines as $contentLine) { + if (!strpos($contentLine, ': ')) { + return 0; + } + [$key, $value] = explode(': ', $contentLine); + switch (strtolower($key)) { + + case "content-disposition": + // Is file data. + if (preg_match('/name="(.*?)"; filename="(.*?)"/i', $value, $match)) { + $error = 0; + $tmpFile = ''; + $fileName = $match[1]; + $size = strlen($boundaryValue); + $tmpUploadDir = HTTP::uploadTmpDir(); + if (!$tmpUploadDir) { + $error = UPLOAD_ERR_NO_TMP_DIR; + } else if ($boundaryValue === '' && $fileName === '') { + $error = UPLOAD_ERR_NO_FILE; + } else { + $tmpFile = tempnam($tmpUploadDir, 'workerman.upload.'); + if ($tmpFile === false || false === file_put_contents($tmpFile, $boundaryValue)) { + $error = UPLOAD_ERR_CANT_WRITE; + } + } + $uploadKey = $fileName; + // Parse upload files. + $file = [...$file, 'name' => $match[2], 'tmp_name' => $tmpFile, 'size' => $size, 'error' => $error, 'full_path' => $match[2]]; + $file['type'] ??= ''; + break; + } + // Is post field. + // Parse $POST. + if (preg_match('/name="(.*?)"$/', $value, $match)) { + $k = $match[1]; + $postEncodeString .= urlencode($k) . "=" . urlencode($boundaryValue) . '&'; + } + return $sectionEndOffset + strlen($boundary) + 2; + + case "content-type": + $file['type'] = trim($value); + break; + + case "webkitrelativepath": + $file['full_path'] = trim($value); + break; + } + } + if ($uploadKey === false) { + return 0; + } + $filesEncodeStr .= urlencode($uploadKey) . '=' . count($files) . '&'; + $files[] = $file; + + return $sectionEndOffset + strlen($boundary) + 2; + } + + /** + * Create session id. + * + * @return string + * @throws RuntimeException + */ + public static function createSessionId(): string + { + $sid = session_create_id(); + if ($sid === false) { + throw new RuntimeException('session_create_id() failed'); + } + return $sid; + } + + /** + * @param string $sessionName + * @param string $sid + * @param array $cookieParams + * @return void + */ + protected function setSidCookie(string $sessionName, string $sid, array $cookieParams): void + { + if (!$this->connection) { + throw new RuntimeException('Request->setSidCookie() fail, header already send'); + } + $this->connection->headers['Set-Cookie'] = [$sessionName . '=' . $sid + . (empty($cookieParams['domain']) ? '' : '; Domain=' . $cookieParams['domain']) + . (empty($cookieParams['lifetime']) ? '' : '; Max-Age=' . $cookieParams['lifetime']) + . (empty($cookieParams['path']) ? '' : '; Path=' . $cookieParams['path']) + . (empty($cookieParams['samesite']) ? '' : '; SameSite=' . $cookieParams['samesite']) + . (!$cookieParams['secure'] ? '' : '; Secure') + . (!$cookieParams['httponly'] ? '' : '; HttpOnly')]; + } + + /** + * __toString. + */ + public function __toString(): string + { + return $this->buffer; + } + + /** + * Setter. + * + * @param string $name + * @param mixed $value + * @return void + */ + public function __set(string $name, mixed $value): void + { + $this->properties[$name] = $value; + } + + /** + * Getter. + * + * @param string $name + * @return mixed + */ + public function __get(string $name): mixed + { + return $this->properties[$name] ?? null; + } + + /** + * Isset. + * + * @param string $name + * @return bool + */ + public function __isset(string $name): bool + { + return isset($this->properties[$name]); + } + + /** + * Unset. + * + * @param string $name + * @return void + */ + public function __unset(string $name): void + { + unset($this->properties[$name]); + } + + /** + * __unserialize. + * + * @param array $data + * @return void + */ + public function __unserialize(array $data): void + { + $this->isSafe = false; + } + + /** + * Destroy. + * + * @return void + */ + public function destroy(): void + { + if ($this->context) { + $this->context = []; + } + if ($this->properties) { + $this->properties = []; + } + $this->connection = null; + } + + /** + * Destructor. + * + * @return void + */ + public function __destruct() + { + if (!empty($this->data['files']) && $this->isSafe) { + clearstatcache(); + array_walk_recursive($this->data['files'], function ($value, $key) { + if ($key === 'tmp_name' && is_file($value)) { + unlink($value); + } + }); + } + } + +} diff --git a/vendor/workerman/workerman/src/Protocols/Http/Response.php b/vendor/workerman/workerman/src/Protocols/Http/Response.php new file mode 100644 index 0000000..76c901b --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/Response.php @@ -0,0 +1,591 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http; + +use Stringable; + +use function array_merge_recursive; +use function filemtime; +use function gmdate; +use function is_array; +use function is_file; +use function pathinfo; +use function rawurlencode; +use function strlen; + +/** + * Class Response + * @package Workerman\Protocols\Http + */ +class Response implements Stringable +{ + + /** + * Http reason. + * + * @var ?string + */ + protected ?string $reason = null; + + /** + * Http version. + * + * @var string + */ + protected string $version = '1.1'; + + /** + * Send file info + * + * @var ?array + */ + public ?array $file = null; + + /** + * Mime Type map. + * @var array + */ + protected static array $mimeTypeMap = [ + // text + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'css' => 'text/css', + 'xml' => 'text/xml', + 'mml' => 'text/mathml', + 'txt' => 'text/plain', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'wml' => 'text/vnd.wap.wml', + 'htc' => 'text/x-component', + + // image + 'gif' => 'image/gif', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'png' => 'image/png', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'wbmp' => 'image/vnd.wap.wbmp', + 'ico' => 'image/x-icon', + 'jng' => 'image/x-jng', + 'bmp' => 'image/x-ms-bmp', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + + // application + 'js' => 'application/javascript', + 'atom' => 'application/atom+xml', + 'rss' => 'application/rss+xml', + 'wasm' => 'application/wasm', + 'jar' => 'application/java-archive', + 'war' => 'application/java-archive', + 'ear' => 'application/java-archive', + 'json' => 'application/json', + 'hqx' => 'application/mac-binhex40', + 'doc' => 'application/msword', + 'pdf' => 'application/pdf', + 'ps' => 'application/postscript', + 'eps' => 'application/postscript', + 'ai' => 'application/postscript', + 'rtf' => 'application/rtf', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'xls' => 'application/vnd.ms-excel', + 'eot' => 'application/vnd.ms-fontobject', + 'ppt' => 'application/vnd.ms-powerpoint', + 'wmlc' => 'application/vnd.wap.wmlc', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + '7z' => 'application/x-7z-compressed', + 'cco' => 'application/x-cocoa', + 'jardiff' => 'application/x-java-archive-diff', + 'jnlp' => 'application/x-java-jnlp-file', + 'run' => 'application/x-makeself', + 'pl' => 'application/x-perl', + 'pm' => 'application/x-perl', + 'prc' => 'application/x-pilot', + 'pdb' => 'application/x-pilot', + 'rar' => 'application/x-rar-compressed', + 'rpm' => 'application/x-redhat-package-manager', + 'sea' => 'application/x-sea', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tcl' => 'application/x-tcl', + 'tk' => 'application/x-tcl', + 'der' => 'application/x-x509-ca-cert', + 'pem' => 'application/x-x509-ca-cert', + 'crt' => 'application/x-x509-ca-cert', + 'xpi' => 'application/x-xpinstall', + 'xhtml' => 'application/xhtml+xml', + 'xspf' => 'application/xspf+xml', + 'zip' => 'application/zip', + 'bin' => 'application/octet-stream', + 'exe' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'deb' => 'application/octet-stream', + 'dmg' => 'application/octet-stream', + 'iso' => 'application/octet-stream', + 'img' => 'application/octet-stream', + 'msi' => 'application/octet-stream', + 'msp' => 'application/octet-stream', + 'msm' => 'application/octet-stream', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + + // audio + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'kar' => 'audio/midi', + 'mp3' => 'audio/mpeg', + 'ogg' => 'audio/ogg', + 'm4a' => 'audio/x-m4a', + 'ra' => 'audio/x-realaudio', + + // video + '3gpp' => 'video/3gpp', + '3gp' => 'video/3gpp', + 'ts' => 'video/mp2t', + 'mp4' => 'video/mp4', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mov' => 'video/quicktime', + 'webm' => 'video/webm', + 'flv' => 'video/x-flv', + 'm4v' => 'video/x-m4v', + 'mng' => 'video/x-mng', + 'asx' => 'video/x-ms-asf', + 'asf' => 'video/x-ms-asf', + 'wmv' => 'video/x-ms-wmv', + 'avi' => 'video/x-msvideo', + + // font + 'ttf' => 'font/ttf', + 'woff' => 'font/woff', + 'woff2' => 'font/woff2', + ]; + + /** + * Phrases. + * + * @var array + * + * @link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes + */ + public const PHRASES = [ + 100 => 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', // WebDAV; RFC 2518 + 103 => 'Early Hints', // RFC 8297 + + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', // since HTTP/1.1 + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', // RFC 7233 + 207 => 'Multi-Status', // WebDAV; RFC 4918 + 208 => 'Already Reported', // WebDAV; RFC 5842 + 226 => 'IM Used', // RFC 3229 + + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', // Previously "Moved temporarily" + 303 => 'See Other', // since HTTP/1.1 + 304 => 'Not Modified', // RFC 7232 + 305 => 'Use Proxy', // since HTTP/1.1 + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', // since HTTP/1.1 + 308 => 'Permanent Redirect', // RFC 7538 + + 400 => 'Bad Request', + 401 => 'Unauthorized', // RFC 7235 + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', // RFC 7235 + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', // RFC 7232 + 413 => 'Payload Too Large', // RFC 7231 + 414 => 'URI Too Long', // RFC 7231 + 415 => 'Unsupported Media Type', // RFC 7231 + 416 => 'Range Not Satisfiable', // RFC 7233 + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', // RFC 2324, RFC 7168 + 421 => 'Misdirected Request', // RFC 7540 + 422 => 'Unprocessable Entity', // WebDAV; RFC 4918 + 423 => 'Locked', // WebDAV; RFC 4918 + 424 => 'Failed Dependency', // WebDAV; RFC 4918 + 425 => 'Too Early', // RFC 8470 + 426 => 'Upgrade Required', + 428 => 'Precondition Required', // RFC 6585 + 429 => 'Too Many Requests', // RFC 6585 + 431 => 'Request Header Fields Too Large', // RFC 6585 + 451 => 'Unavailable For Legal Reasons', // RFC 7725 + + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 506 => 'Variant Also Negotiates', // RFC 2295 + 507 => 'Insufficient Storage', // WebDAV; RFC 4918 + 508 => 'Loop Detected', // WebDAV; RFC 5842 + 510 => 'Not Extended', // RFC 2774 + 511 => 'Network Authentication Required', // RFC 6585 + ]; + + /** + * Response constructor. + * + * @param int $status + * @param array $headers + * @param string $body + */ + public function __construct( + protected int $status = 200, + protected array $headers = [], + protected string $body = '' + ) {} + + /** + * Set header. + * + * @param string $name + * @param string $value + * @return $this + */ + public function header(string $name, string $value): static + { + $this->headers[$name] = $value; + return $this; + } + + /** + * Set header. + * + * @param string $name + * @param string $value + * @return $this + */ + public function withHeader(string $name, string $value): static + { + return $this->header($name, $value); + } + + /** + * Set headers. + * + * @param array $headers + * @return $this + */ + public function withHeaders(array $headers): static + { + $this->headers = array_merge_recursive($this->headers, $headers); + return $this; + } + + /** + * Remove header. + * + * @param string $name + * @return $this + */ + public function withoutHeader(string $name): static + { + unset($this->headers[$name]); + return $this; + } + + /** + * Get header. + * + * @param string $name + * @return null|array|string + */ + public function getHeader(string $name): array|string|null + { + return $this->headers[$name] ?? null; + } + + /** + * Get headers. + * + * @return array + */ + public function getHeaders(): array + { + return $this->headers; + } + + /** + * Get Mime Type from extension. + * + * @param string $ext + * @return string + */ + public function getMimeType(string $ext): string + { + return self::$mimeTypeMap[$ext] ?? 'application/octet-stream'; + } + + /** + * Set status. + * + * @param int $code + * @param string|null $reasonPhrase + * @return $this + */ + public function withStatus(int $code, ?string $reasonPhrase = null): static + { + $this->status = $code; + $this->reason = $reasonPhrase !== null ? str_replace(["\r", "\n"], '', $reasonPhrase) : null; + return $this; + } + + /** + * Get status code. + * + * @return int + */ + public function getStatusCode(): int + { + return $this->status; + } + + /** + * Get reason phrase. + * + * @return ?string + */ + public function getReasonPhrase(): ?string + { + return $this->reason; + } + + /** + * Set protocol version. + * + * @param string $version + * @return $this + */ + public function withProtocolVersion(string $version): static + { + $this->version = str_replace(["\r", "\n"], '', $version); + return $this; + } + + /** + * Set http body. + * + * @param string $body + * @return $this + */ + public function withBody(string $body): static + { + $this->body = $body; + return $this; + } + + /** + * Get http raw body. + * + * @return string + */ + public function rawBody(): string + { + return $this->body; + } + + /** + * Send file. + * + * @param string $file + * @param int $offset + * @param int $length + * @return $this + */ + public function withFile(string $file, int $offset = 0, int $length = 0): static + { + if (!is_file($file)) { + return $this->withStatus(404)->withBody('

404 Not Found

'); + } + $this->file = ['file' => $file, 'offset' => $offset, 'length' => $length]; + return $this; + } + + /** + * Set cookie. + * + * @param string $name + * @param string $value + * @param int|null $maxAge + * @param string $path + * @param string $domain + * @param bool $secure + * @param bool $httpOnly + * @param string $sameSite + * @return $this + */ + public function cookie(string $name, string $value = '', ?int $maxAge = null, string $path = '', string $domain = '', bool $secure = false, bool $httpOnly = false, string $sameSite = ''): static + { + $this->headers['Set-Cookie'][] = $name . '=' . rawurlencode($value) + . (empty($domain) ? '' : '; Domain=' . $domain) + . ($maxAge === null ? '' : '; Max-Age=' . $maxAge) + . (empty($path) ? '' : '; Path=' . $path) + . (!$secure ? '' : '; Secure') + . (!$httpOnly ? '' : '; HttpOnly') + . (empty($sameSite) ? '' : '; SameSite=' . $sameSite); + return $this; + } + + /** + * Create header for file. + * + * @param array $fileInfo + * @return string + */ + protected function createHeadForFile(array $fileInfo): string + { + $file = $fileInfo['file']; + $reason = $this->reason ?: self::PHRASES[$this->status]; + $head = "HTTP/$this->version $this->status $reason\r\n"; + $headers = $this->headers; + foreach ($headers as $name => $value) { + // Skip unsafe header names + if (strpbrk((string)$name, ":\r\n") !== false) { + continue; + } + if (is_array($value)) { + foreach ($value as $item) { + // Skip unsafe header values + if (strpbrk((string)$item, "\r\n") !== false) { + continue; + } + $head .= "$name: $item\r\n"; + } + continue; + } + // Skip unsafe header values + if (strpbrk((string)$value, "\r\n") !== false) { + continue; + } + $head .= "$name: $value\r\n"; + } + + if (!isset($headers['Connection'])) { + $head .= "Connection: keep-alive\r\n"; + } + + $fileInfo = pathinfo($file); + $extension = $fileInfo['extension'] ?? ''; + $baseName = $fileInfo['basename'] ?: 'unknown'; + // Remove ASCII control characters (0x00-0x1F, 0x7F) and unsafe quotes/backslashes to avoid breaking header formatting + $baseName = preg_replace('/["\\\\\x00-\x1F\x7F]/', '', $baseName); + if ($baseName === '') { + $baseName = 'unknown'; + } + $mime = ''; + if (!isset($headers['Content-Type'])) { + $mime = $this->getMimeType($extension); + $head .= "Content-Type: " . $mime . "\r\n"; + } + + if (!isset($headers['Content-Disposition']) && $mime === 'application/octet-stream') { + $head .= "Content-Disposition: attachment; filename=\"$baseName\"\r\n"; + } + + if (!isset($headers['Last-Modified']) && $mtime = filemtime($file)) { + $head .= 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT' . "\r\n"; + } + + return "$head\r\n"; + } + + /** + * __toString. + * + * @return string + */ + public function __toString(): string + { + if ($this->file) { + return $this->createHeadForFile($this->file); + } + + $reason = $this->reason ?: self::PHRASES[$this->status] ?? ''; + $bodyLen = strlen($this->body); + if (empty($this->headers)) { + return "HTTP/$this->version $this->status $reason\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $bodyLen\r\nConnection: keep-alive\r\n\r\n$this->body"; + } + + $head = "HTTP/$this->version $this->status $reason\r\n"; + $headers = $this->headers; + foreach ($headers as $name => $value) { + // Skip unsafe header names + if (strpbrk((string)$name, ":\r\n") !== false) { + continue; + } + if (is_array($value)) { + foreach ($value as $item) { + // Skip unsafe header values + if (strpbrk((string)$item, "\r\n") !== false) { + continue; + } + $head .= "$name: $item\r\n"; + } + continue; + } + // Skip unsafe header values + if (strpbrk((string)$value, "\r\n") !== false) { + continue; + } + $head .= "$name: $value\r\n"; + } + + if (!isset($headers['Connection'])) { + $head .= "Connection: keep-alive\r\n"; + } + + if (!isset($headers['Content-Type'])) { + $head .= "Content-Type: text/html;charset=utf-8\r\n"; + } else if ($headers['Content-Type'] === 'text/event-stream') { + // For Server-Sent Events, send headers once and keep the connection open. + // Headers must be terminated by an empty line; ignore any preset body to avoid + // polluting the event stream with extra bytes or OS-specific newlines. + return $head . "\r\n"; + } + + if (!isset($headers['Transfer-Encoding'])) { + $head .= "Content-Length: $bodyLen\r\n\r\n"; + } else { + return $bodyLen ? "$head\r\n" . dechex($bodyLen) . "\r\n$this->body\r\n" : "$head\r\n"; + } + + // The whole http package + return $head . $this->body; + } + +} diff --git a/vendor/workerman/workerman/src/Protocols/Http/ServerSentEvents.php b/vendor/workerman/workerman/src/Protocols/Http/ServerSentEvents.php new file mode 100644 index 0000000..6b70b10 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/ServerSentEvents.php @@ -0,0 +1,56 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http; + +use Stringable; + +use function str_replace; + +/** + * Class ServerSentEvents + * @package Workerman\Protocols\Http + */ +class ServerSentEvents implements Stringable +{ + /** + * ServerSentEvents constructor. + * $data for example ['event'=>'ping', 'data' => 'some thing', 'id' => 1000, 'retry' => 5000] + */ + public function __construct(protected array $data) {} + + public function __toString(): string + { + $buffer = ''; + $data = $this->data; + if (isset($data[''])) { + $buffer = ": {$data['']}\n"; + } + if (isset($data['event'])) { + $buffer .= "event: {$data['event']}\n"; + } + if (isset($data['id'])) { + $buffer .= "id: {$data['id']}\n"; + } + if (isset($data['retry'])) { + $buffer .= "retry: {$data['retry']}\n"; + } + if (isset($data['data'])) { + $buffer .= 'data: ' . str_replace("\n", "\ndata: ", $data['data']) . "\n"; + } + return "$buffer\n"; + } +} diff --git a/vendor/workerman/workerman/src/Protocols/Http/Session.php b/vendor/workerman/workerman/src/Protocols/Http/Session.php new file mode 100644 index 0000000..9a9d924 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/Session.php @@ -0,0 +1,464 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http; + +use Exception; +use RuntimeException; +use Throwable; +use Workerman\Protocols\Http\Session\FileSessionHandler; +use Workerman\Protocols\Http\Session\SessionHandlerInterface; +use function array_key_exists; +use function ini_get; +use function is_array; +use function is_scalar; +use function random_int; +use function session_get_cookie_params; + +/** + * Class Session + * @package Workerman\Protocols\Http + */ +class Session +{ + /** + * Session andler class which implements SessionHandlerInterface. + * + * @var string + */ + protected static string $handlerClass = FileSessionHandler::class; + + /** + * Parameters of __constructor for session handler class. + * + * @var mixed + */ + protected static mixed $handlerConfig = null; + + /** + * Session name. + * + * @var string + */ + public static string $name = 'PHPSID'; + + /** + * Auto update timestamp. + * + * @var bool + */ + public static bool $autoUpdateTimestamp = false; + + /** + * Session lifetime. + * + * @var int + */ + public static int $lifetime = 1440; + + /** + * Cookie lifetime. + * + * @var int + */ + public static int $cookieLifetime = 1440; + + /** + * Session cookie path. + * + * @var string + */ + public static string $cookiePath = '/'; + + /** + * Session cookie domain. + * + * @var string + */ + public static string $domain = ''; + + /** + * HTTPS only cookies. + * + * @var bool + */ + public static bool $secure = false; + + /** + * HTTP access only. + * + * @var bool + */ + public static bool $httpOnly = true; + + /** + * Same-site cookies. + * + * @var string + */ + public static string $sameSite = ''; + + /** + * Gc probability. + * + * @var int[] + */ + public static array $gcProbability = [1, 20000]; + + /** + * Session handler instance. + * + * @var ?SessionHandlerInterface + */ + protected static ?SessionHandlerInterface $handler = null; + + /** + * Session data. + * + * @var array + */ + protected mixed $data = []; + + /** + * Session changed and need to save. + * + * @var bool + */ + protected bool $needSave = false; + + /** + * Session id. + * + * @var string + */ + protected string $sessionId; + + /** + * Is safe. + * + * @var bool + */ + protected bool $isSafe = true; + + /** + * Session constructor. + * + * @param string $sessionId + */ + public function __construct(string $sessionId) + { + if (static::$handler === null) { + static::initHandler(); + } + $this->sessionId = $sessionId; + if ($data = static::$handler->read($sessionId)) { + $this->data = $this->safeDeserialize($data); + } + } + + /** + * Get session id. + * + * @return string + */ + public function getId(): string + { + return $this->sessionId; + } + + /** + * Get session. + * + * @param string $name + * @param mixed $default + * @return mixed + */ + public function get(string $name, mixed $default = null): mixed + { + return $this->data[$name] ?? $default; + } + + /** + * Store data in the session. + * + * @param string $name + * @param mixed $value + */ + public function set(string $name, mixed $value): void + { + $this->data[$name] = $value; + $this->needSave = true; + } + + /** + * Delete an item from the session. + * + * @param string $name + */ + public function delete(string $name): void + { + unset($this->data[$name]); + $this->needSave = true; + } + + /** + * Retrieve and delete an item from the session. + * + * @param string $name + * @param mixed $default + * @return mixed + */ + public function pull(string $name, mixed $default = null): mixed + { + $value = $this->get($name, $default); + $this->delete($name); + return $value; + } + + /** + * Store data in the session. + * + * @param array|string $key + * @param mixed $value + */ + public function put(array|string $key, mixed $value = null): void + { + if (!is_array($key)) { + $this->set($key, $value); + return; + } + + foreach ($key as $k => $v) { + $this->data[$k] = $v; + } + $this->needSave = true; + } + + /** + * Remove a piece of data from the session. + * + * @param array|string $name + */ + public function forget(array|string $name): void + { + if (is_scalar($name)) { + $this->delete($name); + return; + } + foreach ($name as $key) { + unset($this->data[$key]); + } + $this->needSave = true; + } + + /** + * Retrieve all the data in the session. + * + * @return array + */ + public function all(): array + { + return $this->data; + } + + /** + * Remove all data from the session. + * + * @return void + */ + public function flush(): void + { + $this->needSave = true; + $this->data = []; + } + + /** + * Determining If An Item Exists In The Session. + * + * @param string $name + * @return bool + */ + public function has(string $name): bool + { + return isset($this->data[$name]); + } + + /** + * To determine if an item is present in the session, even if its value is null. + * + * @param string $name + * @return bool + */ + public function exists(string $name): bool + { + return array_key_exists($name, $this->data); + } + + /** + * Save session to store. + * + * @return void + */ + public function save(): void + { + if ($this->needSave) { + if (empty($this->data)) { + static::$handler->destroy($this->sessionId); + } else { + static::$handler->write($this->sessionId, serialize($this->data)); + } + } elseif (static::$autoUpdateTimestamp) { + $this->refresh(); + } + $this->needSave = false; + } + + /** + * Refresh session expire time. + * + * @return bool + */ + public function refresh(): bool + { + return static::$handler->updateTimestamp($this->getId()); + } + + /** + * Init. + * + * @return void + */ + public static function init(): void + { + if (($gcProbability = (int)ini_get('session.gc_probability')) && ($gcDivisor = (int)ini_get('session.gc_divisor'))) { + static::$gcProbability = [$gcProbability, $gcDivisor]; + } + + if ($gcMaxLifeTime = ini_get('session.gc_maxlifetime')) { + self::$lifetime = (int)$gcMaxLifeTime; + } + + $sessionCookieParams = session_get_cookie_params(); + static::$cookieLifetime = $sessionCookieParams['lifetime']; + static::$cookiePath = $sessionCookieParams['path']; + static::$domain = $sessionCookieParams['domain']; + static::$secure = $sessionCookieParams['secure']; + static::$httpOnly = $sessionCookieParams['httponly']; + } + + /** + * Set session handler class. + * + * @param mixed $className + * @param mixed $config + * @return string + */ + public static function handlerClass(mixed $className = null, mixed $config = null): string + { + if ($className) { + static::$handlerClass = $className; + } + if ($config) { + static::$handlerConfig = $config; + } + return static::$handlerClass; + } + + /** + * Get cookie params. + * + * @return array + */ + public static function getCookieParams(): array + { + return [ + 'lifetime' => static::$cookieLifetime, + 'path' => static::$cookiePath, + 'domain' => static::$domain, + 'secure' => static::$secure, + 'httponly' => static::$httpOnly, + 'samesite' => static::$sameSite, + ]; + } + + /** + * Init handler. + * + * @return void + */ + protected static function initHandler(): void + { + if (static::$handlerConfig === null) { + static::$handler = new static::$handlerClass(); + } else { + static::$handler = new static::$handlerClass(static::$handlerConfig); + } + } + + /** + * Safely deserialize session data, preventing object instantiation. + * + * @param string $data + * @return array + */ + protected function safeDeserialize(string $data): array + { + $result = unserialize($data, ['allowed_classes' => false]); + return is_array($result) ? $result : []; + } + + /** + * GC sessions. + * + * @return void + */ + public function gc(): void + { + static::$handler->gc(static::$lifetime); + } + + /** + * __unserialize. + * + * @param array $data + * @return void + */ + public function __unserialize(array $data): void + { + $this->isSafe = false; + } + + /** + * __destruct. + * + * @return void + * @throws Throwable + */ + public function __destruct() + { + if (!$this->isSafe) { + return; + } + $this->save(); + if (random_int(1, static::$gcProbability[1]) <= static::$gcProbability[0]) { + $this->gc(); + } + } + +} + +// Init session. +Session::init(); diff --git a/vendor/workerman/workerman/src/Protocols/Http/Session/FileSessionHandler.php b/vendor/workerman/workerman/src/Protocols/Http/Session/FileSessionHandler.php new file mode 100644 index 0000000..219171c --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/Session/FileSessionHandler.php @@ -0,0 +1,209 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http\Session; + +use Exception; +use Workerman\Protocols\Http\Session; +use function clearstatcache; +use function file_get_contents; +use function file_put_contents; +use function filemtime; +use function glob; +use function is_dir; +use function is_file; +use function mkdir; +use function rename; +use function session_save_path; +use function strlen; +use function sys_get_temp_dir; +use function time; +use function touch; +use function unlink; + +/** + * Class FileSessionHandler + * @package Workerman\Protocols\Http\Session + */ +class FileSessionHandler implements SessionHandlerInterface +{ + /** + * Session save path. + * + * @var string + */ + protected static string $sessionSavePath; + + /** + * Session file prefix. + * + * @var string + */ + protected static string $sessionFilePrefix = 'session_'; + + /** + * Init. + */ + public static function init() + { + $savePath = @session_save_path(); + if (!$savePath || str_starts_with($savePath, 'tcp://')) { + $savePath = sys_get_temp_dir(); + } + static::sessionSavePath($savePath); + } + + /** + * FileSessionHandler constructor. + * @param array $config + */ + public function __construct(array $config = []) + { + if (isset($config['save_path'])) { + static::sessionSavePath($config['save_path']); + } + } + + /** + * {@inheritdoc} + */ + public function open(string $savePath, string $name): bool + { + return true; + } + + /** + * {@inheritdoc} + */ + public function read(string $sessionId): string|false + { + $sessionFile = static::sessionFile($sessionId); + clearstatcache(); + if (is_file($sessionFile)) { + if (time() - filemtime($sessionFile) > Session::$lifetime) { + unlink($sessionFile); + return false; + } + $data = file_get_contents($sessionFile); + return $data ?: false; + } + return false; + } + + /** + * {@inheritdoc} + * @throws Exception + */ + public function write(string $sessionId, string $sessionData): bool + { + $tempFile = static::$sessionSavePath . uniqid(bin2hex(random_bytes(8)), true); + if (!file_put_contents($tempFile, $sessionData)) { + return false; + } + return rename($tempFile, static::sessionFile($sessionId)); + } + + /** + * Update session modify time. + * + * @see https://www.php.net/manual/en/class.sessionupdatetimestamphandlerinterface.php + * @see https://www.php.net/manual/zh/function.touch.php + * + * @param string $sessionId Session id. + * @param string $data Session Data. + * + * @return bool + */ + public function updateTimestamp(string $sessionId, string $data = ""): bool + { + $sessionFile = static::sessionFile($sessionId); + if (!file_exists($sessionFile)) { + return false; + } + // set file modify time to current time + $setModifyTime = touch($sessionFile); + // clear file stat cache + clearstatcache(); + return $setModifyTime; + } + + /** + * {@inheritdoc} + */ + public function close(): bool + { + return true; + } + + /** + * {@inheritdoc} + */ + public function destroy(string $sessionId): bool + { + $sessionFile = static::sessionFile($sessionId); + if (is_file($sessionFile)) { + unlink($sessionFile); + } + return true; + } + + /** + * {@inheritdoc} + */ + public function gc(int $maxLifetime): bool + { + $timeNow = time(); + foreach (glob(static::$sessionSavePath . static::$sessionFilePrefix . '*') as $file) { + if (is_file($file) && $timeNow - filemtime($file) > $maxLifetime) { + unlink($file); + } + } + return true; + } + + /** + * Get session file path. + * + * @param string $sessionId + * @return string + */ + protected static function sessionFile(string $sessionId): string + { + return static::$sessionSavePath . static::$sessionFilePrefix . $sessionId; + } + + /** + * Get or set session file path. + * + * @param string $path + * @return string + */ + public static function sessionSavePath(string $path): string + { + if ($path) { + if ($path[strlen($path) - 1] !== DIRECTORY_SEPARATOR) { + $path .= DIRECTORY_SEPARATOR; + } + static::$sessionSavePath = $path; + if (!is_dir($path)) { + mkdir($path, 0777, true); + } + } + return $path; + } +} + +FileSessionHandler::init(); \ No newline at end of file diff --git a/vendor/workerman/workerman/src/Protocols/Http/Session/RedisClusterSessionHandler.php b/vendor/workerman/workerman/src/Protocols/Http/Session/RedisClusterSessionHandler.php new file mode 100644 index 0000000..8580d0d --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/Session/RedisClusterSessionHandler.php @@ -0,0 +1,59 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http\Session; + +use Redis; +use RedisCluster; +use RedisClusterException; +use RedisException; + +class RedisClusterSessionHandler extends RedisSessionHandler +{ + /** + * @param array $config + * @throws RedisClusterException + * @throws RedisException + */ + public function __construct(array $config) + { + parent::__construct($config); + } + + /** + * Create redis connection. + * @param array $config + * @return Redis|RedisCluster + * @throws RedisClusterException + */ + protected function createRedisConnection(array $config): Redis|RedisCluster + { + $timeout = $config['timeout'] ?? 2; + $readTimeout = $config['read_timeout'] ?? $timeout; + $persistent = $config['persistent'] ?? false; + $auth = $config['auth'] ?? ''; + $args = [null, $config['host'], $timeout, $readTimeout, $persistent]; + if ($auth) { + $args[] = $auth; + } + $redis = new RedisCluster(...$args); + if (empty($config['prefix'])) { + $config['prefix'] = 'redis_session_'; + } + $redis->setOption(Redis::OPT_PREFIX, $config['prefix']); + return $redis; + } +} diff --git a/vendor/workerman/workerman/src/Protocols/Http/Session/RedisSessionHandler.php b/vendor/workerman/workerman/src/Protocols/Http/Session/RedisSessionHandler.php new file mode 100644 index 0000000..e62af13 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/Session/RedisSessionHandler.php @@ -0,0 +1,220 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http\Session; + +use Redis; +use RedisCluster; +use RedisException; +use RuntimeException; +use Throwable; +use Workerman\Coroutine\Utils\DestructionWatcher; +use Workerman\Events\Fiber; +use Workerman\Protocols\Http\Session; +use Workerman\Timer; +use Workerman\Coroutine\Pool; +use Workerman\Coroutine\Context; +use Workerman\Worker; + +/** + * Class RedisSessionHandler + * @package Workerman\Protocols\Http\Session + */ +class RedisSessionHandler implements SessionHandlerInterface +{ + /** + * @var Redis|RedisCluster + */ + protected Redis|RedisCluster|null $connection = null; + + /** + * @var array + */ + protected array $config; + + /** + * @var Pool|null + */ + protected static ?Pool $pool = null; + + /** + * RedisSessionHandler constructor. + * @param array $config = [ + * 'host' => '127.0.0.1', + * 'port' => 6379, + * 'timeout' => 2, + * 'auth' => '******', + * 'database' => 2, + * 'prefix' => 'redis_session_', + * 'ping' => 55, + * ] + * @throws RedisException + */ + public function __construct(array $config) + { + if (false === extension_loaded('redis')) { + throw new RuntimeException('Please install redis extension.'); + } + + $config['timeout'] ??= 2; + $this->config = $config; + } + + /** + * Get connection. + * @return Redis + * @throws Throwable + */ + protected function connection(): Redis|RedisCluster + { + // Cannot switch fibers in current execution context when PHP < 8.4 + if (Worker::$eventLoopClass === Fiber::class && PHP_VERSION_ID < 80400) { + if (!$this->connection) { + $this->connection = $this->createRedisConnection($this->config); + Timer::delay($this->config['pool']['heartbeat_interval'] ?? 55, function () { + $this->connection->ping(); + }); + } + return $this->connection; + } + + $key = 'session.redis.connection'; + /** @var Redis|null $connection */ + $connection = Context::get($key); + if (!$connection) { + if (!static::$pool) { + $poolConfig = $this->config['pool'] ?? []; + static::$pool = new Pool($poolConfig['max_connections'] ?? 10, $poolConfig); + static::$pool->setConnectionCreator(function () { + return $this->createRedisConnection($this->config); + }); + static::$pool->setConnectionCloser(function (Redis|RedisCluster $connection) { + $connection->close(); + }); + static::$pool->setHeartbeatChecker(function (Redis|RedisCluster $connection) { + $connection->ping(); + }); + } + try { + $connection = static::$pool->get(); + Context::set($key, $connection); + } finally { + $closure = function () use ($connection) { + try { + $connection && static::$pool && static::$pool->put($connection); + } catch (Throwable) { + // ignore + } + }; + $obj = Context::get('context.onDestroy'); + if (!$obj) { + $obj = new \stdClass(); + Context::set('context.onDestroy', $obj); + } + DestructionWatcher::watch($obj, $closure); + } + } + return $connection; + } + + /** + * Create redis connection. + * @param array $config + * @return Redis + */ + protected function createRedisConnection(array $config): Redis|RedisCluster + { + $redis = new Redis(); + if (false === $redis->connect($config['host'], $config['port'], $config['timeout'])) { + throw new RuntimeException("Redis connect {$config['host']}:{$config['port']} fail."); + } + if (!empty($config['auth'])) { + $redis->auth($config['auth']); + } + if (!empty($config['database'])) { + $redis->select((int)$config['database']); + } + if (empty($config['prefix'])) { + $config['prefix'] = 'redis_session_'; + } + $redis->setOption(Redis::OPT_PREFIX, $config['prefix']); + return $redis; + } + + /** + * {@inheritdoc} + */ + public function open(string $savePath, string $name): bool + { + return true; + } + + /** + * {@inheritdoc} + * @param string $sessionId + * @return string|false + * @throws RedisException + * @throws Throwable + */ + public function read(string $sessionId): string|false + { + return $this->connection()->get($sessionId); + } + + /** + * {@inheritdoc} + * @throws RedisException + */ + public function write(string $sessionId, string $sessionData): bool + { + return true === $this->connection()->setex($sessionId, Session::$lifetime, $sessionData); + } + + /** + * {@inheritdoc} + * @throws RedisException + */ + public function updateTimestamp(string $sessionId, string $data = ""): bool + { + return true === $this->connection()->expire($sessionId, Session::$lifetime); + } + + /** + * {@inheritdoc} + * @throws RedisException + */ + public function destroy(string $sessionId): bool + { + $this->connection()->del($sessionId); + return true; + } + + /** + * {@inheritdoc} + */ + public function close(): bool + { + return true; + } + + /** + * {@inheritdoc} + */ + public function gc(int $maxLifetime): bool + { + return true; + } +} diff --git a/vendor/workerman/workerman/src/Protocols/Http/Session/SessionHandlerInterface.php b/vendor/workerman/workerman/src/Protocols/Http/Session/SessionHandlerInterface.php new file mode 100644 index 0000000..03f6b35 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Http/Session/SessionHandlerInterface.php @@ -0,0 +1,117 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols\Http\Session; + +interface SessionHandlerInterface +{ + /** + * Close the session + * @link http://php.net/manual/en/sessionhandlerinterface.close.php + * @return bool

+ * The return value (usually TRUE on success, FALSE on failure). + * Note this value is returned internally to PHP for processing. + *

+ * @since 5.4.0 + */ + public function close(): bool; + + /** + * Destroy a session + * @link http://php.net/manual/en/sessionhandlerinterface.destroy.php + * @param string $sessionId The session ID being destroyed. + * @return bool

+ * The return value (usually TRUE on success, FALSE on failure). + * Note this value is returned internally to PHP for processing. + *

+ * @since 5.4.0 + */ + public function destroy(string $sessionId): bool; + + /** + * Cleanup old sessions + * @link http://php.net/manual/en/sessionhandlerinterface.gc.php + * @param int $maxLifetime

+ * Sessions that have not updated for + * the last maxlifetime seconds will be removed. + *

+ * @return bool

+ * The return value (usually TRUE on success, FALSE on failure). + * Note this value is returned internally to PHP for processing. + *

+ * @since 5.4.0 + */ + public function gc(int $maxLifetime): bool; + + /** + * Initialize session + * @link http://php.net/manual/en/sessionhandlerinterface.open.php + * @param string $savePath The path where to store/retrieve the session. + * @param string $name The session name. + * @return bool

+ * The return value (usually TRUE on success, FALSE on failure). + * Note this value is returned internally to PHP for processing. + *

+ * @since 5.4.0 + */ + public function open(string $savePath, string $name): bool; + + + /** + * Read session data + * @link http://php.net/manual/en/sessionhandlerinterface.read.php + * @param string $sessionId The session id to read data for. + * @return string|false

+ * Returns an encoded string of the read data. + * If nothing was read, it must return false. + * Note this value is returned internally to PHP for processing. + *

+ * @since 5.4.0 + */ + public function read(string $sessionId): string|false; + + /** + * Write session data + * @link http://php.net/manual/en/sessionhandlerinterface.write.php + * @param string $sessionId The session id. + * @param string $sessionData

+ * The encoded session data. This data is the + * result of the PHP internally encoding + * the $SESSION superglobal to a serialized + * string and passing it as this parameter. + * Please note sessions use an alternative serialization method. + *

+ * @return bool

+ * The return value (usually TRUE on success, FALSE on failure). + * Note this value is returned internally to PHP for processing. + *

+ * @since 5.4.0 + */ + public function write(string $sessionId, string $sessionData): bool; + + /** + * Update session modify time. + * + * @see https://www.php.net/manual/en/class.sessionupdatetimestamphandlerinterface.php + * + * @param string $sessionId + * @param string $data Session Data. + * + * @return bool + */ + public function updateTimestamp(string $sessionId, string $data = ""): bool; + +} diff --git a/vendor/workerman/workerman/src/Protocols/ProtocolInterface.php b/vendor/workerman/workerman/src/Protocols/ProtocolInterface.php new file mode 100644 index 0000000..f60aa95 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/ProtocolInterface.php @@ -0,0 +1,55 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols; + +use Workerman\Connection\ConnectionInterface; + +/** + * Protocol interface + */ +interface ProtocolInterface +{ + /** + * Check the integrity of the package. + * Please return the length of package. + * If length is unknown please return 0 that means waiting for more data. + * If the package has something wrong please return -1 the connection will be closed. + * + * @param string $buffer + * @param ConnectionInterface $connection + * @return int + */ + public static function input(string $buffer, ConnectionInterface $connection): int; + + /** + * Decode package and emit onMessage($message) callback, $message is the result that decode returned. + * + * @param string $buffer + * @param ConnectionInterface $connection + * @return mixed + */ + public static function decode(string $buffer, ConnectionInterface $connection): mixed; + + /** + * Encode package before sending to client. + * + * @param mixed $data + * @param ConnectionInterface $connection + * @return string + */ + public static function encode(mixed $data, ConnectionInterface $connection): string; +} diff --git a/vendor/workerman/workerman/src/Protocols/Text.php b/vendor/workerman/workerman/src/Protocols/Text.php new file mode 100644 index 0000000..df32ebe --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Text.php @@ -0,0 +1,76 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols; + +use Workerman\Connection\ConnectionInterface; +use function rtrim; +use function strlen; +use function strpos; + +/** + * Text Protocol. + */ +class Text +{ + /** + * Check the integrity of the package. + * + * @param string $buffer + * @param ConnectionInterface $connection + * @return int + */ + public static function input(string $buffer, ConnectionInterface $connection): int + { + // Judge whether the package length exceeds the limit. + if (isset($connection->maxPackageSize) && strlen($buffer) >= $connection->maxPackageSize) { + $connection->close(); + return 0; + } + // Find the position of "\n". + $pos = strpos($buffer, "\n"); + // No "\n", packet length is unknown, continue to wait for the data so return 0. + if ($pos === false) { + return 0; + } + // Return the current package length. + return $pos + 1; + } + + /** + * Encode. + * + * @param string $buffer + * @return string + */ + public static function encode(string $buffer): string + { + // Add "\n" + return $buffer . "\n"; + } + + /** + * Decode. + * + * @param string $buffer + * @return string + */ + public static function decode(string $buffer): string + { + // Remove "\n" + return rtrim($buffer, "\r\n"); + } +} \ No newline at end of file diff --git a/vendor/workerman/workerman/src/Protocols/Websocket.php b/vendor/workerman/workerman/src/Protocols/Websocket.php new file mode 100644 index 0000000..8cee1a7 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Websocket.php @@ -0,0 +1,581 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols; + +use Throwable; +use Workerman\Connection\ConnectionInterface; +use Workerman\Connection\TcpConnection; +use Workerman\Protocols\Http\Request; +use Workerman\Worker; +use function base64_encode; +use function chr; +use function deflate_add; +use function deflate_init; +use function floor; +use function inflate_add; +use function inflate_init; +use function is_scalar; +use function ord; +use function pack; +use function preg_match; +use function sha1; +use function str_repeat; +use function stripos; +use function strlen; +use function strpos; +use function substr; +use function unpack; +use const ZLIB_DEFAULT_STRATEGY; +use const ZLIB_ENCODING_RAW; + +/** + * WebSocket protocol. + */ +class Websocket +{ + /** + * Websocket blob type. + * + * @var string + */ + public const BINARY_TYPE_BLOB = "\x81"; + + /** + * Websocket blob type. + * + * @var string + */ + const BINARY_TYPE_BLOB_DEFLATE = "\xc1"; + + /** + * Websocket arraybuffer type. + * + * @var string + */ + public const BINARY_TYPE_ARRAYBUFFER = "\x82"; + + /** + * Websocket arraybuffer type. + * + * @var string + */ + const BINARY_TYPE_ARRAYBUFFER_DEFLATE = "\xc2"; + + private const ZLIB_INIT_OPTIONS = [ + ZLIB_ENCODING_RAW, + [ + 'level' => -1, + 'memory' => 8, + 'window' => 15, + 'strategy' => ZLIB_DEFAULT_STRATEGY + ] + ]; + + /** + * Inflating in chunks of this size keeps the maxPackageSize check running as the output grows, + * instead of only after a whole frame has been expanded. + */ + private const INFLATE_CHUNK_SIZE = 1024; + + /** + * Max size of the handshake headers. maxPackageSize only applies to frames, so the header block + * gets its own limit, mirroring Http::MAX_HEADER_LENGTH. + */ + private const MAX_HANDSHAKE_LENGTH = 16384; + + private const HTTP_431 = "HTTP/1.1 431 Request Header Fields Too Large\r\nConnection: close\r\n\r\n"; + + /** + * Reset the per-connection frame parser state to what a freshly handshaken connection looks like. + * tmpWebsocketData is deliberately left alone: it may already hold frames the application queued + * before the handshake completed, and dealHandshake() flushes those once the response is sent. + */ + public static function initContext(TcpConnection $connection): void + { + // Payload of the fragments received so far for the current message. + $connection->context->websocketDataBuffer = ''; + // Length of the frame currently being received, 0 when no fragment is pending. + $connection->context->websocketCurrentFrameLength = 0; + // Whether the message being received is permessage-deflate compressed. + $connection->context->websocketCompressed = false; + // Whether permessage-deflate was accepted in the handshake response. + $connection->context->websocketPermessageDeflate = false; + // Whether a fragmented message is currently being received. + $connection->context->websocketFragmented = false; + } + + public static function input(string $buffer, TcpConnection $connection): int + { + // Receive length. + $recvLen = strlen($buffer); + // We need more data. + if ($recvLen < 6) { + return 0; + } + + // Has not yet completed the handshake. + if (empty($connection->context->websocketHandshake)) { + return static::dealHandshake($buffer, $connection); + } + + // Buffer websocket frame data. + if ($connection->context->websocketCurrentFrameLength) { + // We need more frame data. + if ($connection->context->websocketCurrentFrameLength > $recvLen) { + // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1. + return 0; + } + } else { + $firstByte = ord($buffer[0]); + $secondByte = ord($buffer[1]); + $dataLen = $secondByte & 127; + $isFinFrame = $firstByte >> 7; + $masked = $secondByte >> 7; + $opcode = $firstByte & 0xf; + + if (!$masked) { + Worker::safeEcho("frame not masked so close the connection\n"); + $connection->close(); + return 0; + } + + // RFC 6455 section 5.2: rsv bits must be zero unless a negotiated extension defines them. + // permessage-deflate is the only extension supported here and it only defines rsv1 on data frames. + $rsv = $firstByte & 0x70; + if ($rsv !== 0 && ($rsv !== 0x40 || $opcode >= 0x8 || !$connection->context->websocketPermessageDeflate)) { + Worker::safeEcho("frame sets rsv bits without a negotiated extension so close the connection\n"); + $connection->close(); + return 0; + } + + // RFC 6455 section 5.5: control frames must not be fragmented and carry at most 125 bytes. + if ($opcode >= 0x8 && ($dataLen > 125 || !$isFinFrame)) { + Worker::safeEcho("invalid control frame so close the connection\n"); + $connection->close(); + return 0; + } + + // RFC 6455 section 5.4: a continuation frame needs a message in progress, and a new data + // frame must not interrupt one. + if ($opcode < 0x8 && ($opcode === 0x0) !== $connection->context->websocketFragmented) { + Worker::safeEcho("unexpected message fragmentation so close the connection\n"); + $connection->close(); + return 0; + } + + switch ($opcode) { + case 0x0: + // Blob type. + case 0x1: + // Arraybuffer type. + case 0x2: + // Ping package. + case 0x9: + // Pong package. + case 0xa: + break; + // Close package. + case 0x8: + // A masked control frame is always $dataLen + 6 bytes. + if ($recvLen < $dataLen + 6) { + return 0; + } + // The frame is handled here, so take it out of the receive buffer. + $connection->consumeRecvBuffer($dataLen + 6); + // Try to emit onWebSocketClose callback. + $closeCb = $connection->onWebSocketClose ?? $connection->worker->onWebSocketClose ?? false; + if ($closeCb) { + try { + $closeCb($connection); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } // Close connection. + else { + $connection->close("\x88\x02\x03\xe8", true); + } + return 0; + // Wrong opcode. + default : + Worker::safeEcho("error opcode $opcode and close websocket connection. Buffer:" . bin2hex($buffer) . "\n"); + $connection->close(); + return 0; + } + + // Calculate packet length. + $headLen = 6; + if ($dataLen === 126) { + $headLen = 8; + if ($headLen > $recvLen) { + return 0; + } + $dataLen = unpack('nn/ntotal_len', $buffer)['total_len']; + } else { + if ($dataLen === 127) { + $headLen = 14; + if ($headLen > $recvLen) { + return 0; + } + $arr = unpack('n/N2c', $buffer); + $dataLen = $arr['c1'] * 4294967296 + $arr['c2']; + } + } + $currentFrameLength = $headLen + $dataLen; + + $totalPackageSize = strlen($connection->context->websocketDataBuffer) + $currentFrameLength; + if ($totalPackageSize > $connection->maxPackageSize) { + Worker::safeEcho("error package. package_length=$totalPackageSize\n"); + $connection->close(); + return 0; + } + + // Past every early return, so the frame is accepted and the message state can advance. + if ($opcode < 0x8) { + $connection->context->websocketFragmented = !$isFinFrame; + } + + if ($isFinFrame) { + if ($opcode === 0x9) { + if ($recvLen >= $currentFrameLength) { + $pingData = static::decode(substr($buffer, 0, $currentFrameLength), $connection); + $connection->consumeRecvBuffer($currentFrameLength); + $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB; + $connection->websocketType = "\x8a"; + $pingCb = $connection->onWebSocketPing ?? $connection->worker->onWebSocketPing ?? false; + if ($pingCb) { + try { + $pingCb($connection, $pingData); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } else { + $connection->send($pingData); + } + $connection->websocketType = $tmpConnectionType; + if ($recvLen > $currentFrameLength) { + return static::input(substr($buffer, $currentFrameLength), $connection); + } + } + return 0; + } + + if ($opcode === 0xa) { + if ($recvLen >= $currentFrameLength) { + $pongData = static::decode(substr($buffer, 0, $currentFrameLength), $connection); + $connection->consumeRecvBuffer($currentFrameLength); + $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB; + $connection->websocketType = "\x8a"; + // Try to emit onWebSocketPong callback. + $pongCb = $connection->onWebSocketPong ?? $connection->worker->onWebSocketPong ?? false; + if ($pongCb) { + try { + $pongCb($connection, $pongData); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + $connection->websocketType = $tmpConnectionType; + if ($recvLen > $currentFrameLength) { + return static::input(substr($buffer, $currentFrameLength), $connection); + } + } + return 0; + } + return $currentFrameLength; + } + + $connection->context->websocketCurrentFrameLength = $currentFrameLength; + } + + // Received just a frame length data. + if ($connection->context->websocketCurrentFrameLength === $recvLen) { + static::decode($buffer, $connection); + $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength); + $connection->context->websocketCurrentFrameLength = 0; + return 0; + } + + // The length of the received data is greater than the length of a frame. + if ($connection->context->websocketCurrentFrameLength < $recvLen) { + static::decode(substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection); + $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength); + $currentFrameLength = $connection->context->websocketCurrentFrameLength; + $connection->context->websocketCurrentFrameLength = 0; + // Continue to read next frame. + return static::input(substr($buffer, $currentFrameLength), $connection); + } + + // The length of the received data is less than the length of a frame. + return 0; + } + + public static function encode(mixed $buffer, TcpConnection $connection): string + { + if (!is_scalar($buffer)) { + $buffer = json_encode($buffer, JSON_UNESCAPED_UNICODE); + } + + $connection->websocketType ??= static::BINARY_TYPE_BLOB; + + if (ord($connection->websocketType) & 64) { + $buffer = static::deflate($connection, $buffer); + } + + $firstByte = $connection->websocketType; + $len = strlen($buffer); + + $encodeBuffer = match(true) { + $len <= 125 => $firstByte . chr($len) . $buffer, + $len <= 65535 => $firstByte . chr(126) . pack("n", $len) . $buffer, + default => $firstByte . chr(127) . pack("xxxxN", $len) . $buffer, + }; + + // Handshake not completed so temporary buffer websocket data waiting for send. + if (empty($connection->context->websocketHandshake)) { + if (empty($connection->context->tmpWebsocketData)) { + $connection->context->tmpWebsocketData = ''; + } + // If buffer has already full then discard the current package. + if (strlen($connection->context->tmpWebsocketData) > $connection->maxSendBufferSize) { + if ($connection->onError) { + try { + ($connection->onError)($connection, ConnectionInterface::SEND_FAIL, 'send buffer full and drop package'); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + return ''; + } + $connection->context->tmpWebsocketData .= $encodeBuffer; + // Check buffer is full. + if ($connection->onBufferFull && $connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) { + try { + ($connection->onBufferFull)($connection); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + // Return empty string. + return ''; + } + + return $encodeBuffer; + } + + public static function decode(string $buffer, TcpConnection $connection): string + { + $firstByte = ord($buffer[0]); + $secondByte = ord($buffer[1]); + $len = $secondByte & 127; + $opcode = $firstByte & 0xf; + + [$masks, $data] = match(true) { + $len === 126 => [substr($buffer, 4, 4), substr($buffer, 8)], + $len === 127 => [substr($buffer, 10, 4), substr($buffer, 14)], + default => [substr($buffer, 2, 4), substr($buffer, 6)], + }; + + $dataLength = strlen($data); + $masks = str_repeat($masks, (int)floor($dataLength / 4)) . substr($masks, 0, $dataLength % 4); + $decoded = $data ^ $masks; + + // Control frames may be interleaved with a fragmented message, they carry no message data. + if ($opcode >= 0x8) { + return $decoded; + } + + // RFC 7692 section 6: rsv1 on the first frame marks the whole message as compressed. + if ($opcode !== 0x0) { + $connection->context->websocketCompressed = 64 === ($firstByte & 64); + } + + // More fragments are coming, buffer the payload until the fin frame arrives. + if ($connection->context->websocketCurrentFrameLength) { + $connection->context->websocketDataBuffer .= $decoded; + return ''; + } + + if ($connection->context->websocketDataBuffer !== '') { + $decoded = $connection->context->websocketDataBuffer . $decoded; + $connection->context->websocketDataBuffer = ''; + } + + if ($connection->context->websocketCompressed) { + return static::inflate($connection, $decoded); + } + + return $decoded; + } + + protected static function inflate(TcpConnection $connection, string $buffer): string + { + $connection->context->inflator ??= inflate_init(...self::ZLIB_INIT_OPTIONS); + $buffer .= "\x00\x00\xff\xff"; + + $result = ''; + $bufferLength = strlen($buffer); + for ($offset = 0; $offset < $bufferLength; $offset += self::INFLATE_CHUNK_SIZE) { + // Silenced because a decode failure is an expected outcome and is handled below. + $chunk = @inflate_add( + $connection->context->inflator, + substr($buffer, $offset, self::INFLATE_CHUNK_SIZE) + ); + if ($chunk === false) { + Worker::safeEcho("websocket inflate failed so close the connection\n"); + $connection->close(); + return ''; + } + if (strlen($chunk) > $connection->maxPackageSize - strlen($result)) { + Worker::safeEcho("websocket inflate data exceeds maxPackageSize limit so close the connection\n"); + $connection->close(); + return ''; + } + $result .= $chunk; + } + + return $result; + } + + protected static function deflate(TcpConnection $connection, string $buffer): string + { + $connection->context->deflator ??= deflate_init(...self::ZLIB_INIT_OPTIONS); + + return substr(deflate_add($connection->context->deflator, $buffer), 0, -4); + } + + /** + * Websocket handshake. + * + */ + public static function dealHandshake(string $buffer, TcpConnection $connection): int + { + $HTTP_400 = "HTTP/1.1 400 Bad Request\r\n\r\n

400 Bad Request


workerman
"; + + // HTTP protocol. + if (!str_starts_with($buffer, 'GET')) { + // Bad websocket handshake request. + $connection->close($HTTP_400, true); + return 0; + } + + // Find \r\n\r\n. + $headerEndPos = strpos($buffer, "\r\n\r\n"); + if ($headerEndPos === false) { + if (strlen($buffer) >= self::MAX_HANDSHAKE_LENGTH) { + $connection->close(self::HTTP_431, true); + } + return 0; + } + if ($headerEndPos >= self::MAX_HANDSHAKE_LENGTH) { + $connection->close(self::HTTP_431, true); + return 0; + } + $headerLength = $headerEndPos + 4; + // Parse the header block only, anything after it is already websocket frame data. + $header = substr($buffer, 0, $headerLength); + + // Check WebSocket version - RFC 6455 Section 4.4 + if (preg_match("/Sec-WebSocket-Version: *(.*?)\r\n/i", $header, $match)) { + if($match[1] !== '13') { + $_426 = "HTTP/1.1 426 Upgrade Required\r\n" + . "Connection: Upgrade\r\n" + . "Upgrade: WebSocket\r\n" + . "Sec-WebSocket-Version: 13\r\n\r\n"; + + $connection->close($_426, true); + return 0; + } + } else { + $connection->close( + "HTTP/1.1 400 Bad Request\r\nSec-WebSocket-Version: 13\r\n\r\n", true); + return 0; + } + + // Get Sec-WebSocket-Key. + if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $header, $match)) { + $SecWebSocketKey = $match[1]; + } else { + $connection->close($HTTP_400, true); + return 0; + } + // Calculation websocket key. + $newKey = base64_encode(sha1($SecWebSocketKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true)); + // Handshake response data. + $handshakeMessage = "HTTP/1.1 101 Switching Protocol\r\n" + . "Upgrade: websocket\r\n" + . "Sec-WebSocket-Version: 13\r\n" + . "Connection: Upgrade\r\n" + . "Sec-WebSocket-Accept: $newKey\r\n"; + + static::initContext($connection); + // Consume handshake data. + $connection->consumeRecvBuffer($headerLength); + // Request from buffer + $request = new Request($header); + + // Try to emit onWebSocketConnect callback. + $onWebsocketConnect = $connection->onWebSocketConnect ?? $connection->worker->onWebSocketConnect ?? false; + if ($onWebsocketConnect) { + try { + $onWebsocketConnect($connection, $request); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + + // blob or arraybuffer + $connection->websocketType ??= static::BINARY_TYPE_BLOB; + + if ($connection->headers) { + foreach ($connection->headers as $header) { + if (strpbrk($header, "\r\n") !== false) { + continue; + } + // Accepting the extension is what enables rsv1 compressed frames on this connection. + if (stripos($header, 'Sec-WebSocket-Extensions:') === 0 && stripos($header, 'permessage-deflate') !== false) { + $connection->context->websocketPermessageDeflate = true; + } + $handshakeMessage .= "$header\r\n"; + } + } + $handshakeMessage .= "\r\n"; + // Send handshake response. + $connection->send($handshakeMessage, true); + // Mark handshake complete. + $connection->context->websocketHandshake = true; + + // Try to emit onWebSocketConnected callback. + $onWebsocketConnected = $connection->onWebSocketConnected ?? $connection->worker->onWebSocketConnected ?? false; + if ($onWebsocketConnected) { + try { + $onWebsocketConnected($connection, $request); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + + // There are data waiting to be sent. + if (!empty($connection->context->tmpWebsocketData)) { + $connection->send($connection->context->tmpWebsocketData, true); + $connection->context->tmpWebsocketData = ''; + } + if (strlen($buffer) > $headerLength) { + return static::input(substr($buffer, $headerLength), $connection); + } + return 0; + } +} diff --git a/vendor/workerman/workerman/src/Protocols/Ws.php b/vendor/workerman/workerman/src/Protocols/Ws.php new file mode 100644 index 0000000..4473e54 --- /dev/null +++ b/vendor/workerman/workerman/src/Protocols/Ws.php @@ -0,0 +1,546 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman\Protocols; + +use Throwable; +use Workerman\Connection\AsyncTcpConnection; +use Workerman\Connection\ConnectionInterface; +use Workerman\Protocols\Http\Response; +use Workerman\Timer; +use Workerman\Worker; +use function base64_encode; +use function bin2hex; +use function explode; +use function floor; +use function ord; +use function pack; +use function preg_match; +use function sha1; +use function str_repeat; +use function strlen; +use function strpos; +use function substr; +use function trim; +use function unpack; + +/** + * Websocket protocol for client. + */ +class Ws +{ + /** + * Websocket blob type. + * + * @var string + */ + public const BINARY_TYPE_BLOB = "\x81"; + + /** + * Websocket arraybuffer type. + * + * @var string + */ + public const BINARY_TYPE_ARRAYBUFFER = "\x82"; + + /** + * Max size of the handshake response headers. maxPackageSize only applies to frames, so the + * header block gets its own limit, mirroring Http::MAX_HEADER_LENGTH. + */ + private const MAX_HANDSHAKE_LENGTH = 16384; + + /** + * Reset the per-connection frame parser state. Only safe at the start or the end of a connection + * because it drops queued frames; handshakeStep is left untouched so the caller decides which of + * the two it is. + */ + public static function initContext(AsyncTcpConnection $connection): void + { + // Payload of the fragments received so far for the current message. + $connection->context->websocketDataBuffer = ''; + // Length of the frame currently being received, 0 when no fragment is pending. + $connection->context->websocketCurrentFrameLength = 0; + // Whether a fragmented message is currently being received. + $connection->context->websocketFragmented = false; + // Frames encoded before the handshake completed, flushed once it does. + $connection->context->tmpWebsocketData = ''; + } + + public static function input(string $buffer, AsyncTcpConnection $connection): int + { + if (!isset($connection->context->handshakeStep)) { + Worker::safeEcho("recv data before handshake. Buffer:" . bin2hex($buffer) . "\n"); + return -1; + } + // Recv handshake response + if ($connection->context->handshakeStep === 1) { + return self::dealHandshake($buffer, $connection); + } + $recvLen = strlen($buffer); + if ($recvLen < 2) { + return 0; + } + // Buffer websocket frame data. + if ($connection->context->websocketCurrentFrameLength) { + // We need more frame data. + if ($connection->context->websocketCurrentFrameLength > $recvLen) { + // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1. + return 0; + } + } else { + + $firstByte = ord($buffer[0]); + $secondByte = ord($buffer[1]); + $dataLen = $secondByte & 127; + $isFinFrame = $firstByte >> 7; + $masked = $secondByte >> 7; + + if ($masked) { + Worker::safeEcho("frame masked so close the connection\n"); + $connection->close(); + return 0; + } + + $opcode = $firstByte & 0xf; + + // RFC 6455 section 5.2: this client negotiates no extension, so all rsv bits must be zero. + if (($firstByte & 0x70) !== 0) { + Worker::safeEcho("frame sets rsv bits without a negotiated extension so close the connection\n"); + $connection->close(); + return 0; + } + + // RFC 6455 section 5.5: control frames must not be fragmented and carry at most 125 bytes. + if ($opcode >= 0x8 && ($dataLen > 125 || !$isFinFrame)) { + Worker::safeEcho("invalid control frame so close the connection\n"); + $connection->close(); + return 0; + } + + // RFC 6455 section 5.4: a continuation frame needs a message in progress, and a new data + // frame must not interrupt one. + if ($opcode < 0x8 && ($opcode === 0x0) !== $connection->context->websocketFragmented) { + Worker::safeEcho("unexpected message fragmentation so close the connection\n"); + $connection->close(); + return 0; + } + + switch ($opcode) { + case 0x0: + // Blob type. + case 0x1: + // Arraybuffer type. + case 0x2: + // Ping package. + case 0x9: + // Pong package. + case 0xa: + break; + // Close package. + case 0x8: + // An unmasked control frame is always $dataLen + 2 bytes. + if ($recvLen < $dataLen + 2) { + return 0; + } + $closeFrame = substr($buffer, 0, $dataLen + 2); + // The frame is handled here, so take it out of the receive buffer. + $connection->consumeRecvBuffer($dataLen + 2); + // Try to emit onWebSocketClose callback. + if (isset($connection->onWebSocketClose)) { + try { + ($connection->onWebSocketClose)($connection, self::decode($closeFrame, $connection)); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } else { // Close connection. + $connection->close(); + } + + return 0; + // Wrong opcode. + default : + Worker::safeEcho("error opcode $opcode and close websocket connection. Buffer:" . $buffer . "\n"); + $connection->close(); + return 0; + } + // Calculate packet length. + if ($dataLen === 126) { + if (strlen($buffer) < 4) { + return 0; + } + $currentFrameLength = unpack('nn/ntotal_len', $buffer)['total_len'] + 4; + } else if ($dataLen === 127) { + if (strlen($buffer) < 10) { + return 0; + } + $arr = unpack('n/N2c', $buffer); + $currentFrameLength = $arr['c1'] * 4294967296 + $arr['c2'] + 10; + } else { + $currentFrameLength = $dataLen + 2; + } + + $totalPackageSize = strlen($connection->context->websocketDataBuffer) + $currentFrameLength; + if ($totalPackageSize > $connection->maxPackageSize) { + Worker::safeEcho("error package. package_length=$totalPackageSize\n"); + $connection->close(); + return 0; + } + + // Past every early return, so the frame is accepted and the message state can advance. + if ($opcode < 0x8) { + $connection->context->websocketFragmented = !$isFinFrame; + } + + if ($isFinFrame) { + if ($opcode === 0x9) { + if ($recvLen >= $currentFrameLength) { + $pingData = static::decode(substr($buffer, 0, $currentFrameLength), $connection); + $connection->consumeRecvBuffer($currentFrameLength); + $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB; + $connection->websocketType = "\x8a"; + if (isset($connection->onWebSocketPing)) { + try { + ($connection->onWebSocketPing)($connection, $pingData); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } else { + $connection->send($pingData); + } + $connection->websocketType = $tmpConnectionType; + if ($recvLen > $currentFrameLength) { + return static::input(substr($buffer, $currentFrameLength), $connection); + } + } + return 0; + + } + + if ($opcode === 0xa) { + if ($recvLen >= $currentFrameLength) { + $pongData = static::decode(substr($buffer, 0, $currentFrameLength), $connection); + $connection->consumeRecvBuffer($currentFrameLength); + $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB; + $connection->websocketType = "\x8a"; + // Try to emit onWebSocketPong callback. + if (isset($connection->onWebSocketPong)) { + try { + ($connection->onWebSocketPong)($connection, $pongData); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + $connection->websocketType = $tmpConnectionType; + if ($recvLen > $currentFrameLength) { + return static::input(substr($buffer, $currentFrameLength), $connection); + } + } + return 0; + } + return $currentFrameLength; + } + + $connection->context->websocketCurrentFrameLength = $currentFrameLength; + } + // Received just a frame length data. + if ($connection->context->websocketCurrentFrameLength === $recvLen) { + self::decode($buffer, $connection); + $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength); + $connection->context->websocketCurrentFrameLength = 0; + return 0; + } // The length of the received data is greater than the length of a frame. + else if ($connection->context->websocketCurrentFrameLength < $recvLen) { + self::decode(substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection); + $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength); + $currentFrameLength = $connection->context->websocketCurrentFrameLength; + $connection->context->websocketCurrentFrameLength = 0; + // Continue to read next frame. + return self::input(substr($buffer, $currentFrameLength), $connection); + } // The length of the received data is less than the length of a frame. + + return 0; + + } + + /** + * Websocket encode. + * + * @param string $payload + * @param AsyncTcpConnection $connection + * @return string + * @throws Throwable + */ + public static function encode(string $payload, AsyncTcpConnection $connection): string + { + $connection->websocketType ??= self::BINARY_TYPE_BLOB; + + $connection->websocketOrigin ??= null; + $connection->websocketClientProtocol ??= null; + if (!isset($connection->context->handshakeStep)) { + static::sendHandshake($connection); + } + + $maskKey = "\x00\x00\x00\x00"; + $length = strlen($payload); + + $head = match(true) { + $length < 126 => chr(0x80 | $length), + $length < 0xFFFF => chr(0x80 | 126) . pack("n", $length), + default => chr(0x80 | 127) . pack("N", 0) . pack("N", $length), + }; + + $frame = $connection->websocketType . $head . $maskKey; + // append payload to frame: + $maskKey = str_repeat($maskKey, (int)floor($length / 4)) . substr($maskKey, 0, $length % 4); + $frame .= $payload ^ $maskKey; + if ($connection->context->handshakeStep === 1) { + // If buffer has already full then discard the current package. + if (strlen($connection->context->tmpWebsocketData) > $connection->maxSendBufferSize) { + if ($connection->onError) { + try { + ($connection->onError)($connection, ConnectionInterface::SEND_FAIL, 'send buffer full and drop package'); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + return ''; + } + $connection->context->tmpWebsocketData .= $frame; + // Check buffer is full. + if ($connection->onBufferFull && $connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) { + try { + ($connection->onBufferFull)($connection); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + return ''; + } + return $frame; + } + + /** + * Websocket decode. + * + * @param string $bytes + * @param AsyncTcpConnection $connection + * @return string + */ + public static function decode(string $bytes, AsyncTcpConnection $connection): string + { + $decodedData = match(ord($bytes[1])) { // data length + 126 => substr($bytes, 4), + 127 => substr($bytes, 10), + default => substr($bytes, 2), + }; + + // Control frames may be interleaved with a fragmented message, they carry no message data. + if ((ord($bytes[0]) & 0xf) >= 0x8) { + return $decodedData; + } + + // More fragments are coming, buffer the payload until the fin frame arrives. + if ($connection->context->websocketCurrentFrameLength) { + $connection->context->websocketDataBuffer .= $decodedData; + return ''; + } + + if ($connection->context->websocketDataBuffer !== '') { + $decodedData = $connection->context->websocketDataBuffer . $decodedData; + $connection->context->websocketDataBuffer = ''; + } + return $decodedData; + } + + /** + * Send websocket handshake data. + * + * @param AsyncTcpConnection $connection + * @return void + * @throws Throwable + */ + public static function onConnect(AsyncTcpConnection $connection): void + { + $connection->websocketOrigin = $connection->websocketOrigin ?? null; + $connection->websocketClientProtocol = $connection->websocketClientProtocol ?? null; + static::sendHandshake($connection); + } + + /** + * Clean + * + * @param AsyncTcpConnection $connection + */ + public static function onClose(AsyncTcpConnection $connection): void + { + unset($connection->context->handshakeStep); + static::initContext($connection); + if (!empty($connection->context->websocketPingTimer)) { + Timer::del($connection->context->websocketPingTimer); + $connection->context->websocketPingTimer = null; + } + } + + /** + * Send websocket handshake. + * + * @throws Throwable + */ + public static function sendHandshake(AsyncTcpConnection $connection): void + { + if (!empty($connection->context->handshakeStep)) { + return; + } + // Get Host. + $port = $connection->getRemotePort(); + $host = match($port) { + 80, 443 => $connection->getRemoteHost(), + default => $connection->getRemoteHost() . ":$port", + }; + // Handshake header. + $connection->context->websocketSecKey = base64_encode(random_bytes(16)); + $userHeader = $connection->headers ?? null; + $userHeaderStr = ''; + if (!empty($userHeader)) { + foreach ($userHeader as $k => $v) { + // Skip unsafe header names or values containing CR/LF + if (strpbrk((string)$k, ":\r\n") !== false) { + continue; + } + if (strpbrk((string)$v, "\r\n") !== false) { + continue; + } + $userHeaderStr .= "$k: $v\r\n"; + } + $userHeaderStr = $userHeaderStr !== '' ? "\r\n" . trim($userHeaderStr) : ''; + } + $requestUri = str_replace(["\r", "\n"], '', $connection->getRemoteURI()); + // Sanitize Origin and Sec-WebSocket-Protocol + $origin = $connection->websocketOrigin ?? null; + $origin = $origin !== null ? str_replace(["\r", "\n"], '', $origin) : null; + $clientProtocol = $connection->websocketClientProtocol ?? null; + $clientProtocol = $clientProtocol !== null ? str_replace(["\r", "\n"], '', $clientProtocol) : null; + $header = 'GET ' . $requestUri . " HTTP/1.1\r\n" . + (!preg_match("/\nHost:/i", $userHeaderStr) ? "Host: $host\r\n" : '') . + "Connection: Upgrade\r\n" . + "Upgrade: websocket\r\n" . + ($origin ? "Origin: " . $origin . "\r\n" : '') . + ($clientProtocol ? "Sec-WebSocket-Protocol: $clientProtocol\r\n" : '') . + "Sec-WebSocket-Version: 13\r\n" . + "Sec-WebSocket-Key: " . $connection->context->websocketSecKey . "$userHeaderStr\r\n\r\n"; + $connection->send($header, true); + static::initContext($connection); + $connection->context->handshakeStep = 1; + } + + /** + * Websocket handshake. + * + * @param string $buffer + * @param AsyncTcpConnection $connection + * @return int + */ + public static function dealHandshake(string $buffer, AsyncTcpConnection $connection): int + { + $pos = strpos($buffer, "\r\n\r\n"); + if ($pos === false) { + // Until the handshake completes maxPackageSize does not apply, so bound the buffer here. + if (strlen($buffer) >= self::MAX_HANDSHAKE_LENGTH) { + Worker::safeEcho("handshake response headers too large so close the connection\n"); + $connection->close(); + } + return 0; + } + if ($pos >= self::MAX_HANDSHAKE_LENGTH) { + Worker::safeEcho("handshake response headers too large so close the connection\n"); + $connection->close(); + return 0; + } + + $handshakeResponseLength = $pos + 4; + $header = substr($buffer, 0, $handshakeResponseLength); + + //checking Sec-WebSocket-Accept + if (preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $header, $match)) { + if ($match[1] !== base64_encode(sha1($connection->context->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) { + Worker::safeEcho("Sec-WebSocket-Accept not match. Header:\n" . substr($buffer, 0, $pos) . "\n"); + $connection->close(); + return 0; + } + } else { + Worker::safeEcho("Sec-WebSocket-Accept not found. Header:\n" . substr($buffer, 0, $pos) . "\n"); + $connection->close(); + return 0; + } + + // handshake complete + $connection->context->handshakeStep = 2; + $response = static::parseResponse($header); + // Try to emit onWebSocketConnect callback. + if (isset($connection->onWebSocketConnect)) { + try { + ($connection->onWebSocketConnect)($connection, $response); + } catch (Throwable $e) { + Worker::stopAll(250, $e); + } + } + // Headbeat. + if (!empty($connection->websocketPingInterval)) { + $connection->context->websocketPingTimer = Timer::add($connection->websocketPingInterval, function () use ($connection) { + if (false === $connection->send(pack('H*', '898000000000'), true)) { + Timer::del($connection->context->websocketPingTimer); + $connection->context->websocketPingTimer = null; + } + }); + } + + $connection->consumeRecvBuffer($handshakeResponseLength); + if (!empty($connection->context->tmpWebsocketData)) { + $connection->send($connection->context->tmpWebsocketData, true); + $connection->context->tmpWebsocketData = ''; + } + if (strlen($buffer) > $handshakeResponseLength) { + return self::input(substr($buffer, $handshakeResponseLength), $connection); + } + + return 0; + } + + /** + * Parse response. + * + * @param string $buffer + * @return Response + */ + protected static function parseResponse(string $buffer): Response + { + [$http_header, ] = explode("\r\n\r\n", $buffer, 2); + $header_data = explode("\r\n", $http_header); + [$protocol, $status, $phrase] = explode(' ', $header_data[0], 3); + $protocolVersion = substr($protocol, 5); + unset($header_data[0]); + $headers = []; + foreach ($header_data as $content) { + // \r\n\r\n + if (empty($content)) { + continue; + } + [$key, $value] = explode(':', $content, 2); + $headers[$key] = trim($value); + } + return (new Response())->withStatus((int)$status, $phrase)->withHeaders($headers)->withProtocolVersion($protocolVersion); + } +} diff --git a/vendor/workerman/workerman/src/Timer.php b/vendor/workerman/workerman/src/Timer.php new file mode 100644 index 0000000..5f4213b --- /dev/null +++ b/vendor/workerman/workerman/src/Timer.php @@ -0,0 +1,274 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman; + +use RuntimeException; +use Throwable; +use Workerman\Events\EventInterface; +use Workerman\Events\Fiber; +use Workerman\Events\Swoole; +use Revolt\EventLoop; +use Swoole\Coroutine\System; +use function function_exists; +use function pcntl_alarm; +use function pcntl_signal; +use function time; +use const PHP_INT_MAX; +use const SIGALRM; + +/** + * Timer. + */ +class Timer +{ + /** + * Tasks that based on ALARM signal. + * [ + * run_time => [[$func, $args, $persistent, time_interval],[$func, $args, $persistent, time_interval],..]], + * run_time => [[$func, $args, $persistent, time_interval],[$func, $args, $persistent, time_interval],..]], + * .. + * ] + * + * @var array + */ + protected static array $tasks = []; + + /** + * Event + * + * @var ?EventInterface + */ + protected static ?EventInterface $event = null; + + /** + * Timer id + * + * @var int + */ + protected static int $timerId = 0; + + /** + * Timer status + * [ + * timer_id1 => bool, + * timer_id2 => bool, + * ...................., + * ] + * + * @var array + */ + protected static array $status = []; + + /** + * Init. + * + * @param EventInterface|null $event + * @return void + */ + public static function init(?EventInterface $event = null): void + { + if ($event) { + self::$event = $event; + return; + } + if (function_exists('pcntl_signal')) { + pcntl_signal(SIGALRM, self::signalHandle(...), false); + } + } + + /** + * Repeat. + * + * @param float $timeInterval + * @param callable $func + * @param array $args + * @return int + */ + public static function repeat(float $timeInterval, callable $func, array $args = []): int + { + return self::$event->repeat($timeInterval, $func, $args); + } + + /** + * Delay. + * + * @param float $timeInterval + * @param callable $func + * @param array $args + * @return int + */ + public static function delay(float $timeInterval, callable $func, array $args = []): int + { + return self::$event->delay($timeInterval, $func, $args); + } + + /** + * ALARM signal handler. + * + * @param mixed ...$args + * @return void + */ + public static function signalHandle(mixed ...$args): void + { + if (!self::$event) { + pcntl_alarm(1); + self::tick(); + } + } + + /** + * Add a timer. + * + * @param float $timeInterval + * @param callable $func + * @param null|array $args + * @param bool $persistent + * @return int + */ + public static function add(float $timeInterval, callable $func, ?array $args = [], bool $persistent = true): int + { + if ($timeInterval < 0) { + throw new RuntimeException('$timeInterval can not less than 0'); + } + + if ($args === null) { + $args = []; + } + + if (self::$event) { + return $persistent ? self::$event->repeat($timeInterval, $func, $args) : self::$event->delay($timeInterval, $func, $args); + } + + // If not workerman runtime just return. + if (!Worker::getAllWorkers()) { + throw new RuntimeException('Timer can only be used in workerman running environment'); + } + + if (empty(self::$tasks)) { + pcntl_alarm(1); + } + + $runTime = (int)floor(time() + $timeInterval); + if (!isset(self::$tasks[$runTime])) { + self::$tasks[$runTime] = []; + } + + self::$timerId = self::$timerId == PHP_INT_MAX ? 1 : ++self::$timerId; + self::$status[self::$timerId] = true; + self::$tasks[$runTime][self::$timerId] = [$func, (array)$args, $persistent, $timeInterval]; + + return self::$timerId; + } + + /** + * Coroutine sleep. + * + * @param float $delay + * @return void + */ + public static function sleep(float $delay): void + { + switch (Worker::$eventLoopClass) { + // Fiber + case Fiber::class: + $suspension = EventLoop::getSuspension(); + static::add($delay, function () use ($suspension) { + $suspension->resume(); + }, null, false); + $suspension->suspend(); + return; + // Swoole + case Swoole::class: + System::sleep($delay); + return; + } + usleep((int)($delay * 1000 * 1000)); + } + + /** + * Tick. + * + * @return void + */ + protected static function tick(): void + { + if (empty(self::$tasks)) { + pcntl_alarm(0); + return; + } + $timeNow = time(); + foreach (self::$tasks as $runTime => $taskData) { + if ($timeNow >= $runTime) { + foreach ($taskData as $index => $oneTask) { + $taskFunc = $oneTask[0]; + $taskArgs = $oneTask[1]; + $persistent = $oneTask[2]; + $timeInterval = $oneTask[3]; + try { + $taskFunc(...$taskArgs); + } catch (Throwable $e) { + Worker::safeEcho((string)$e); + } + if ($persistent && !empty(self::$status[$index])) { + $newRunTime = (int)floor(time() + $timeInterval); + if (!isset(self::$tasks[$newRunTime])) { + self::$tasks[$newRunTime] = []; + } + self::$tasks[$newRunTime][$index] = [$taskFunc, (array)$taskArgs, $persistent, $timeInterval]; + } + } + unset(self::$tasks[$runTime]); + } + } + } + + /** + * Remove a timer. + * + * @param int $timerId + * @return bool + */ + public static function del(int $timerId): bool + { + if (self::$event) { + return self::$event->offDelay($timerId); + } + foreach (self::$tasks as $runTime => $taskData) { + if (array_key_exists($timerId, $taskData)) { + unset(self::$tasks[$runTime][$timerId]); + } + } + if (array_key_exists($timerId, self::$status)) { + unset(self::$status[$timerId]); + } + return true; + } + + /** + * Remove all timers. + * + * @return void + */ + public static function delAll(): void + { + self::$tasks = self::$status = []; + if (function_exists('pcntl_alarm')) { + pcntl_alarm(0); + } + self::$event?->deleteAllTimer(); + } +} diff --git a/vendor/workerman/workerman/src/Worker.php b/vendor/workerman/workerman/src/Worker.php new file mode 100644 index 0000000..63083ef --- /dev/null +++ b/vendor/workerman/workerman/src/Worker.php @@ -0,0 +1,2876 @@ + + * @copyright walkor + * @link http://www.workerman.net/ + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + +declare(strict_types=1); + +namespace Workerman; + +use AllowDynamicProperties; +use Exception; +use RuntimeException; +use stdClass; +use Stringable; +use Throwable; +use Workerman\Connection\ConnectionInterface; +use Workerman\Connection\TcpConnection; +use Workerman\Connection\UdpConnection; +use Workerman\Coroutine; +use Workerman\Coroutine\Context; +use Workerman\Events\Event; +use Workerman\Events\EventInterface; +use Workerman\Events\Fiber; +use Workerman\Events\Select; +use Workerman\Events\Swoole; +use Workerman\Events\Swow; +use function defined; +use function function_exists; +use function is_resource; +use function method_exists; +use function restore_error_handler; +use function set_error_handler; +use function stream_socket_accept; +use function stream_socket_recvfrom; +use function substr; +use function array_walk; +use function get_class; +use const DIRECTORY_SEPARATOR; +use const PHP_SAPI; +use const PHP_VERSION; +use const STDOUT; + +/** + * Worker class + * A container for listening ports + */ +#[AllowDynamicProperties] +class Worker +{ + /** + * Version. + * + * @var string + */ + final public const VERSION = '5.2.4'; + + /** + * Status initial. + * + * @var int + */ + public const STATUS_INITIAL = 0; + + /** + * Status starting. + * + * @var int + */ + public const STATUS_STARTING = 1; + + /** + * Status running. + * + * @var int + */ + public const STATUS_RUNNING = 2; + + /** + * Status shutdown. + * + * @var int + */ + public const STATUS_SHUTDOWN = 4; + + /** + * Status reloading. + * + * @var int + */ + public const STATUS_RELOADING = 8; + + /** + * Default backlog. Backlog is the maximum length of the queue of pending connections. + * + * @var int + */ + public const DEFAULT_BACKLOG = 102400; + + /** + * The safe distance for columns adjacent + * + * @var int + */ + public const UI_SAFE_LENGTH = 4; + + /** + * Worker id. + * + * @var int + */ + public int $id = 0; + + /** + * Name of the worker processes. + * + * @var string + */ + public string $name = 'none'; + + /** + * Number of worker processes. + * + * @var int + */ + public int $count = 1; + + /** + * Unix user of processes, needs appropriate privileges (usually root). + * + * @var string + */ + public string $user = ''; + + /** + * Unix group of processes, needs appropriate privileges (usually root). + * + * @var string + */ + public string $group = ''; + + /** + * reloadable. + * + * @var bool + */ + public bool $reloadable = true; + + /** + * reuse port. + * + * @var bool + */ + public bool $reusePort = false; + + /** + * Emitted when worker processes is starting. + * + * @var ?callable + */ + public $onWorkerStart = null; + + /** + * Emitted when a socket connection is successfully established. + * + * @var ?callable + */ + public $onConnect = null; + + /** + * Emitted before websocket handshake (Only works when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketConnect = null; + + /** + * Emitted after websocket handshake (Only works when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketConnected = null; + + /** + * Emitted when a websocket connection is closed by the peer (Only works when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketClose = null; + + /** + * Emitted when a websocket ping frame is received (Only works when protocol is ws). + * Without a handler the ping is answered with a pong automatically. + * + * @var ?callable + */ + public $onWebSocketPing = null; + + /** + * Emitted when a websocket pong frame is received (Only works when protocol is ws). + * + * @var ?callable + */ + public $onWebSocketPong = null; + + /** + * Emitted when data is received. + * + * @var ?callable + */ + public $onMessage = null; + + /** + * Emitted when the other end of the socket sends a FIN packet. + * + * @var ?callable + */ + public $onClose = null; + + /** + * Emitted when an error occurs with connection. + * + * @var ?callable + */ + public $onError = null; + + /** + * Emitted when the send buffer becomes full. + * + * @var ?callable + */ + public $onBufferFull = null; + + /** + * Emitted when the send buffer becomes empty. + * + * @var ?callable + */ + public $onBufferDrain = null; + + /** + * Emitted when worker processes has stopped. + * + * @var ?callable + */ + public $onWorkerStop = null; + + /** + * Emitted when worker processes receives reload signal. + * + * @var ?callable + */ + public $onWorkerReload = null; + + /** + * Transport layer protocol. + * + * @var string + */ + public string $transport = 'tcp'; + + /** + * Store all connections of clients. + * + * @internal Framework internal API + * + * @var TcpConnection[] + */ + public array $connections = []; + + /** + * Application layer protocol. + * + * @var ?string + */ + public ?string $protocol = null; + + /** + * Pause accept new connections or not. + * + * @var bool + */ + protected ?bool $pauseAccept = null; + + /** + * Is worker stopping ? + * + * @var bool + */ + public bool $stopping = false; + + /** + * EventLoop class. + * + * @var ?string + */ + public ?string $eventLoop = null; + + /** + * Daemonize. + * + * @var bool + */ + public static bool $daemonize = false; + + /** + * Standard output stream + * + * @var resource + */ + public static $outputStream; + + /** + * Stdout file. + * + * @var string + */ + public static string $stdoutFile = '/dev/null'; + + /** + * The file to store master process PID. + * + * @var string + */ + public static string $pidFile = ''; + + /** + * The file used to store the master process status. + * + * @var string + */ + public static string $statusFile = ''; + + /** + * Log file. + * + * @var string + */ + public static string $logFile = ''; + + /** + * Log file maximum size in bytes, default 10M. + * + * @var int + */ + public static int $logFileMaxSize = 10_485_760; + + /** + * Global event loop. + * + * @var ?EventInterface + */ + public static ?EventInterface $globalEvent = null; + + /** + * Emitted when the master process gets a reload signal. + * + * @var ?callable + */ + public static $onMasterReload = null; + + /** + * Emitted when the master process terminated. + * + * @var ?callable + */ + public static $onMasterStop = null; + + /** + * Emitted when worker processes exited. + * + * @var ?callable + */ + public static $onWorkerExit = null; + + /** + * EventLoopClass + * + * @var ?class-string + */ + public static ?string $eventLoopClass = null; + + /** + * After sending the stop command to the child process stopTimeout seconds, + * if the process is still living then forced to kill. + * + * @var int + */ + public static int $stopTimeout = 2; + + /** + * Command + * + * @var string + */ + public static string $command = ''; + + /** + * The PID of master process. + * + * @var int + */ + protected static int $masterPid = 0; + + /** + * Listening socket. + * + * @var ?resource + */ + protected $mainSocket = null; + + /** + * Socket name. The format is like this http://0.0.0.0:80 . + * + * @var string + */ + protected string $socketName = ''; + + /** + * Context of socket. + * + * @var resource + */ + protected $socketContext = null; + + /** + * @var stdClass + */ + protected stdClass $context; + + /** + * All worker instances. + * + * @var Worker[] + */ + protected static array $workers = []; + + /** + * All worker processes pid. + * The format is like this [worker_id=>[pid=>pid, pid=>pid, ..], ..] + * + * @var array + */ + protected static array $pidMap = []; + + /** + * All worker processes waiting for restart. + * The format is like this [pid=>pid, pid=>pid]. + * + * @var array + */ + protected static array $pidsToRestart = []; + + /** + * Mapping from PID to worker process ID. + * The format is like this [worker_id=>[0=>$pid, 1=>$pid, ..], ..]. + * + * @var array + */ + protected static array $idMap = []; + + /** + * Current status. + * + * @var int + */ + protected static int $status = self::STATUS_INITIAL; + + /** + * UI data. + * + * @var array|int[] + */ + protected static array $uiLengthData = []; + + /** + * The file to store status info of current worker process. + * + * @var string + */ + protected static string $statisticsFile = ''; + + /** + * The file to store status info of connections. + * + * @var string + */ + protected static string $connectionsFile = ''; + + /** + * Start file. + * + * @var string + */ + protected static string $startFile = ''; + + /** + * Processes for windows. + * + * @var array + */ + protected static array $processForWindows = []; + + /** + * Status info of current worker process. + * + * @var array + */ + protected static array $globalStatistics = [ + 'start_timestamp' => 0, + 'worker_exit_info' => [] + ]; + + /** + * PHP built-in protocols. + * + * @var array + */ + public const BUILD_IN_TRANSPORTS = [ + 'tcp' => 'tcp', + 'udp' => 'udp', + 'unix' => 'unix', + 'ssl' => 'tcp' + ]; + + /** + * PHP built-in error types. + * + * @var array + */ + public const ERROR_TYPE = [ + E_ERROR => 'E_ERROR', + E_WARNING => 'E_WARNING', + E_PARSE => 'E_PARSE', + E_NOTICE => 'E_NOTICE', + E_CORE_ERROR => 'E_CORE_ERROR', + E_CORE_WARNING => 'E_CORE_WARNING', + E_COMPILE_ERROR => 'E_COMPILE_ERROR', + E_COMPILE_WARNING => 'E_COMPILE_WARNING', + E_USER_ERROR => 'E_USER_ERROR', + E_USER_WARNING => 'E_USER_WARNING', + E_USER_NOTICE => 'E_USER_NOTICE', + E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', + E_DEPRECATED => 'E_DEPRECATED', + E_USER_DEPRECATED => 'E_USER_DEPRECATED' + ]; + + /** + * Graceful stop or not. + * + * @var bool + */ + protected static bool $gracefulStop = false; + + /** + * If $outputStream support decorated + * + * @var bool + */ + protected static bool $outputDecorated; + + /** + * Worker object's id(unique identifier). + * + * @var ?int + */ + protected ?int $workerId = null; + + /** + * Constructor. + * + * @param string|null $socketName + * @param array $socketContext + */ + public function __construct(?string $socketName = null, array $socketContext = []) + { + // Save all worker instances. + $this->workerId = spl_object_id($this); + $this->context = new stdClass(); + static::$workers[$this->workerId] = $this; + static::$pidMap[$this->workerId] = []; + + // Context for socket. + if ($socketName) { + $this->socketName = $socketName; + $socketContext['socket']['backlog'] ??= static::DEFAULT_BACKLOG; + $this->socketContext = stream_context_create($socketContext); + } + + // Set an empty onMessage callback. + $this->onMessage = function () { + // Empty. + }; + + } + + /** + * Run all worker instances. + * + * @return void + */ + public static function runAll(): void + { + try { + static::checkSapiEnv(); + static::initStdOut(); + static::init(); + static::parseCommand(); + static::checkPortAvailable(); + static::lock(); + static::daemonize(); + static::initWorkers(); + static::installSignal(); + static::saveMasterPid(); + static::lock(LOCK_UN); + static::displayUI(); + static::forkWorkers(); + static::resetStd(); + static::monitorWorkers(); + } catch (Throwable $e) { + static::log($e); + } + } + + /** + * Check sapi. + * + * @return void + */ + protected static function checkSapiEnv(): void + { + // Only for cli, micro and embed. + if (!in_array(PHP_SAPI, ['cli', 'micro', 'embed'])) { + exit("Only run in command line mode" . PHP_EOL); + } + // Check pcntl and posix extension for unix. + if (DIRECTORY_SEPARATOR === '/') { + foreach (['pcntl', 'posix'] as $name) { + if (!extension_loaded($name)) { + exit("Please install $name extension" . PHP_EOL); + } + } + } + // Check disable functions. + $disabledFunctions = explode(',', ini_get('disable_functions')); + $disabledFunctions = array_map('trim', $disabledFunctions); + $functionsToCheck = [ + 'stream_socket_server', + 'stream_socket_accept', + 'stream_socket_client', + 'pcntl_signal_dispatch', + 'pcntl_signal', + 'pcntl_alarm', + 'pcntl_fork', + 'pcntl_wait', + 'posix_getuid', + 'posix_getpwuid', + 'posix_kill', + 'posix_setsid', + 'posix_getpid', + 'posix_getpwnam', + 'posix_getgrnam', + 'posix_getgid', + 'posix_setgid', + 'posix_initgroups', + 'posix_setuid', + 'posix_isatty', + 'proc_open', + 'proc_get_status', + 'proc_close', + 'shell_exec', + 'exec', + 'putenv', + 'getenv', + ]; + $disabled = array_intersect($functionsToCheck, $disabledFunctions); + if (!empty($disabled)) { + $iniFilePath = (string)php_ini_loaded_file(); + exit('Notice: '. implode(',', $disabled) . " are disabled by disable_functions. " . PHP_EOL + . "Please remove them from disable_functions in $iniFilePath" . PHP_EOL); + } + } + + /** + * Init stdout. + * + * @return void + */ + protected static function initStdOut(): void + { + $defaultStream = fn () => defined('STDOUT') ? STDOUT : (@fopen('php://stdout', 'w') ?: fopen('php://output', 'w')); + static::$outputStream ??= $defaultStream(); //@phpstan-ignore-line + if (!is_resource(self::$outputStream) || get_resource_type(self::$outputStream) !== 'stream') { + $type = get_debug_type(self::$outputStream); + static::$outputStream = $defaultStream(); + throw new RuntimeException(sprintf('The $outputStream must to be a stream, %s given', $type)); + } + + static::$outputDecorated ??= self::hasColorSupport(); + } + + /** + * Borrowed from the symfony console + * @link https://github.com/symfony/console/blob/0d14a9f6d04d4ac38a8cea1171f4554e325dae92/Output/StreamOutput.php#L92 + */ + private static function hasColorSupport(): bool + { + // Follow https://no-color.org/ + if (getenv('NO_COLOR') !== false) { + return false; + } + + if (getenv('TERM_PROGRAM') === 'Hyper') { + return true; + } + + if (DIRECTORY_SEPARATOR === '\\') { + return (function_exists('sapi_windows_vt100_support') && @sapi_windows_vt100_support(self::$outputStream)) + || getenv('ANSICON') !== false + || getenv('ConEmuANSI') === 'ON' + || getenv('TERM') === 'xterm'; + } + + return stream_isatty(self::$outputStream); + } + + /** + * Init. + * + * @return void + */ + protected static function init(): void + { + set_error_handler(static function (int $code, string $msg, string $file, int $line): bool { + // A custom handler is called even for diagnostics silenced with @, so honour the mask ourselves. + if (!(error_reporting() & $code)) { + return true; + } + static::safeEcho(sprintf("%s \"%s\" in file %s on line %d\n", static::getErrorType($code), $msg, $file, $line)); + return true; + }); + + // $_SERVER. + $_SERVER['SERVER_SOFTWARE'] = 'Workerman/' . static::VERSION; + $_SERVER['SERVER_START_TIME'] = time(); + + // Start file. + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + static::$startFile = static::$startFile ?: end($backtrace)['file']; + $startFilePrefix = basename(static::$startFile); + $startFileDir = dirname(static::$startFile); + + // Compatible with older workerman versions for pid file. + if (empty(static::$pidFile)) { + $unique_prefix = \str_replace('/', '_', static::$startFile); + $file = __DIR__ . "/../../$unique_prefix.pid"; + if (is_file($file)) { + static::$pidFile = $file; + } + } + + // Pid file. + static::$pidFile = static::$pidFile ?: sprintf('%s/workerman.%s.pid', $startFileDir, $startFilePrefix); + + // Status file. + static::$statusFile = static::$statusFile ?: sprintf('%s/workerman.%s.status', $startFileDir, $startFilePrefix); + static::$statisticsFile = static::$statisticsFile ?: static::$statusFile; + static::$connectionsFile = static::$connectionsFile ?: static::$statusFile . '.connection'; + + // Log file. + static::$logFile = static::$logFile ?: sprintf('%s/workerman.log', $startFileDir); + + if (static::$logFile !== '/dev/null' && !is_file(static::$logFile) && !str_contains(static::$logFile, '://')) { + // if /runtime/logs default folder not exists + if (!is_dir(dirname(static::$logFile))) { + mkdir(dirname(static::$logFile), 0777, true); + } + touch(static::$logFile); + chmod(static::$logFile, 0644); + } + + // State. + static::$status = static::STATUS_STARTING; + + // Init global event. + static::initGlobalEvent(); + + // For statistics. + static::$globalStatistics['start_timestamp'] = time(); + + // Process title. + static::setProcessTitle('WorkerMan: master process start_file=' . static::$startFile); + + // Init data for worker id. + static::initId(); + + // Timer init. + Timer::init(); + + restore_error_handler(); + } + + /** + * Init global event. + * + * @return void + */ + protected static function initGlobalEvent(): void + { + if (static::$globalEvent !== null) { + static::$eventLoopClass = get_class(static::$globalEvent); + static::$globalEvent = null; + return; + } + + if (!empty(static::$eventLoopClass)) { + if (!is_subclass_of(static::$eventLoopClass, EventInterface::class)) { + throw new RuntimeException(sprintf('%s::$eventLoopClass must implement %s', static::class, EventInterface::class)); + } + return; + } + + static::$eventLoopClass = match (true) { + extension_loaded('event') => Event::class, + default => Select::class, + }; + } + + /** + * Lock. + * + * @param int $flag + * @return void + */ + protected static function lock(int $flag = LOCK_EX): void + { + static $fd; + if (DIRECTORY_SEPARATOR !== '/') { + return; + } + $lockFile = static::$pidFile . '.lock'; + $fd = $fd ?: fopen($lockFile, 'a+'); + if ($fd) { + flock($fd, $flag); + if ($flag === LOCK_UN) { + fclose($fd); + $fd = null; + clearstatcache(); + if (is_file($lockFile)) { + unlink($lockFile); + } + } + } + } + + /** + * Init All worker instances. + * + * @return void + */ + protected static function initWorkers(): void + { + if (DIRECTORY_SEPARATOR !== '/') { + return; + } + + foreach (static::$workers as $worker) { + // Worker name. + if (empty($worker->name)) { + $worker->name = 'none'; + } + + // Get unix user of the worker process. + if (empty($worker->user)) { + $worker->user = static::getCurrentUser(); + } else { + if (posix_getuid() !== 0 && $worker->user !== static::getCurrentUser()) { + static::log('Warning: You must have the root privileges to change uid and gid.'); + } + } + + // Socket name. + $worker->context->statusSocket = $worker->getSocketName(); + + // Event-loop name. + $eventLoopName = $worker->eventLoop ?: static::$eventLoopClass; + $worker->context->eventLoopName = strtolower(substr($eventLoopName, strrpos($eventLoopName, '\\') + 1)); + + // Status name. + $worker->context->statusState = ' [OK] '; + + // Get column mapping for UI + foreach (static::getUiColumns() as $columnName => $prop) { + !isset($worker->$prop) && !isset($worker->context->$prop) && $worker->context->$prop = 'NNNN'; + $propLength = strlen((string)($worker->$prop ?? $worker->context->$prop)); + $key = 'max' . ucfirst(strtolower($columnName)) . 'NameLength'; + static::$uiLengthData[$key] = max(static::$uiLengthData[$key] ?? 2 * static::UI_SAFE_LENGTH, $propLength); + } + + // Listen. + if (!$worker->reusePort) { + $worker->listen(false); + } + } + } + + /** + * Get all worker instances. + * + * @return Worker[] + */ + public static function getAllWorkers(): array + { + return static::$workers; + } + + /** + * Get global event-loop instance. + * + * @return EventInterface + */ + public static function getEventLoop(): EventInterface + { + return static::$globalEvent; + } + + /** + * Get main socket resource + * + * @return resource + */ + public function getMainSocket(): mixed + { + return $this->mainSocket; + } + + /** + * Init idMap. + * + * @return void + */ + protected static function initId(): void + { + foreach (static::$workers as $workerId => $worker) { + $newIdMap = []; + $worker->count = max($worker->count, 1); + for ($key = 0; $key < $worker->count; $key++) { + $newIdMap[$key] = static::$idMap[$workerId][$key] ?? 0; + } + static::$idMap[$workerId] = $newIdMap; + } + } + + /** + * Get unix user of current process. + * + * @return string + */ + protected static function getCurrentUser(): string + { + $userInfo = posix_getpwuid(posix_getuid()); + return $userInfo['name'] ?? 'unknown'; + } + + /** + * Display staring UI. + * + * @return void + */ + protected static function displayUI(): void + { + $tmpArgv = static::getArgv(); + if (in_array('-q', $tmpArgv)) { + return; + } + + + $lineVersion = static::getVersionLine(); + // For windows + if (DIRECTORY_SEPARATOR !== '/') { + static::safeEcho("---------------------------------------------- WORKERMAN -----------------------------------------------\r\n"); + static::safeEcho($lineVersion); + static::safeEcho("----------------------------------------------- WORKERS ------------------------------------------------\r\n"); + static::safeEcho("worker listen processes status\r\n"); + return; + } + + // For unix + !defined('LINE_VERSION_LENGTH') && define('LINE_VERSION_LENGTH', strlen($lineVersion)); + $totalLength = static::getSingleLineTotalLength(); + $lineOne = '' . str_pad(' WORKERMAN ', $totalLength + strlen(''), '-', STR_PAD_BOTH) . '' . PHP_EOL; + $lineTwo = str_pad(' WORKERS ', $totalLength + strlen(''), '-', STR_PAD_BOTH) . PHP_EOL; + static::safeEcho($lineOne . $lineVersion . $lineTwo); + + //Show title + $title = ''; + foreach (static::getUiColumns() as $columnName => $prop) { + $key = 'max' . ucfirst(strtolower($columnName)) . 'NameLength'; + //just keep compatible with listen name + $columnName === 'socket' && $columnName = 'listen'; + $title .= "$columnName" . str_pad('', static::getUiColumnLength($key) + static::UI_SAFE_LENGTH - strlen($columnName)); + } + $title && static::safeEcho($title . PHP_EOL); + + //Show content + foreach (static::$workers as $worker) { + $content = ''; + foreach (static::getUiColumns() as $columnName => $prop) { + $propValue = (string)($worker->$prop ?? $worker->context->$prop); + $key = 'max' . ucfirst(strtolower($columnName)) . 'NameLength'; + preg_match_all("/(|<\/n>||<\/w>||<\/g>)/i", $propValue, $matches); + $placeHolderLength = !empty($matches[0]) ? strlen(implode('', $matches[0])) : 0; + $content .= str_pad($propValue, static::getUiColumnLength($key) + static::UI_SAFE_LENGTH + $placeHolderLength); + } + $content && static::safeEcho($content . PHP_EOL); + } + + //Show last line + $lineLast = str_pad('', static::getSingleLineTotalLength(), '-') . PHP_EOL; + !empty($content) && static::safeEcho($lineLast); + + if (static::$daemonize) { + static::safeEcho('Input "php ' . basename(static::$startFile) . ' stop" to stop. Start success.' . "\n\n"); + } else if (!empty(static::$command)) { + static::safeEcho("Start success.\n"); // Workerman used as library + } else { + static::safeEcho("Press Ctrl+C to stop. Start success.\n"); + } + } + + /** + * @return string + */ + protected static function getVersionLine(): string + { + //Show version + $jitStatus = function_exists('opcache_get_status') && (opcache_get_status()['jit']['on'] ?? false) === true ? 'on' : 'off'; + $version = str_pad('Workerman/' . static::VERSION, 24); + $version .= str_pad('PHP/' . PHP_VERSION . ' (JIT ' . $jitStatus . ')', 30); + $version .= php_uname('s') . '/' . php_uname('r') . PHP_EOL; + return $version; + } + + /** + * Get UI columns to be shown in terminal + * + * 1. $columnMap: ['ui_column_name' => 'clas_property_name'] + * 2. Consider move into configuration in future + * + * @return array + */ + public static function getUiColumns(): array + { + return [ + 'event-loop' => 'eventLoopName', + 'proto' => 'transport', + 'user' => 'user', + 'worker' => 'name', + 'socket' => 'statusSocket', + 'count' => 'count', + 'state' => 'statusState', + ]; + } + + /** + * Get single line total length for ui + * + * @return int + */ + public static function getSingleLineTotalLength(): int + { + $totalLength = 0; + + foreach (static::getUiColumns() as $columnName => $prop) { + $key = 'max' . ucfirst(strtolower($columnName)) . 'NameLength'; + $totalLength += static::getUiColumnLength($key) + static::UI_SAFE_LENGTH; + } + + //Keep beauty when show less columns + !defined('LINE_VERSION_LENGTH') && define('LINE_VERSION_LENGTH', 0); + $totalLength <= LINE_VERSION_LENGTH && $totalLength = LINE_VERSION_LENGTH; + + return $totalLength; + } + + /** + * Parse command. + * + * @return void + */ + protected static function parseCommand(): void + { + if (DIRECTORY_SEPARATOR !== '/') { + return; + } + + // Check argv; + $startFile = basename(static::$startFile); + $usage = "Usage: php yourfile [mode]\nCommands: \nstart\t\tStart worker in DEBUG mode.\n\t\tUse mode -d to start in DAEMON mode.\nstop\t\tStop worker.\n\t\tUse mode -g to stop gracefully.\nrestart\t\tRestart workers.\n\t\tUse mode -d to start in DAEMON mode.\n\t\tUse mode -g to stop gracefully.\nreload\t\tReload codes.\n\t\tUse mode -g to reload gracefully.\nstatus\t\tGet worker status.\n\t\tUse mode -d to show live status.\nconnections\tGet worker connections.\n"; + $availableCommands = [ + 'start', + 'stop', + 'restart', + 'reload', + 'status', + 'connections', + ]; + $availableMode = [ + '-d', + '-g' + ]; + $command = $mode = ''; + foreach (static::getArgv() as $value) { + if (!$command && in_array($value, $availableCommands)) { + $command = $value; + } + if (!$mode && in_array($value, $availableMode)) { + $mode = $value; + } + } + + if (!$command) { + exit($usage); + } + + // Start command. + $modeStr = ''; + if ($command === 'start') { + if ($mode === '-d' || static::$daemonize) { + $modeStr = 'in DAEMON mode'; + } else { + $modeStr = 'in DEBUG mode'; + } + } + static::log("Workerman[$startFile] $command $modeStr"); + + // Get master process PID. + $masterPid = is_file(static::$pidFile) ? (int)file_get_contents(static::$pidFile) : 0; + // Master is still alive? + if (static::checkMasterIsAlive($masterPid)) { + if ($command === 'start') { + static::log("Workerman[$startFile] already running"); + exit; + } + } elseif ($command !== 'start' && $command !== 'restart') { + static::log("Workerman[$startFile] not run"); + exit; + } + + // execute command. + switch ($command) { + case 'start': + if ($mode === '-d') { + static::$daemonize = true; + } + break; + case 'status': + // Delete status file on shutdown + register_shutdown_function(static function () { + if (is_file(static::$statisticsFile)) { + @unlink(static::$statisticsFile); + } + }); + while (1) { + // Master process will send SIGIOT signal to all child processes. + posix_kill($masterPid, SIGIOT); + // Waiting a moment. + sleep(1); + // Clear terminal. + if ($mode === '-d') { + static::safeEcho("\33[H\33[2J\33(B\33[m", true); + } + // Echo status data. + static::safeEcho(static::formatProcessStatusData()); + if ($mode !== '-d') { + exit(0); + } + static::safeEcho("\nPress Ctrl+C to quit.\n\n"); + } + case 'connections': + // Delete status file on shutdown + register_shutdown_function(static function () { + if (is_file(static::$connectionsFile)) { + @unlink(static::$connectionsFile); + } + }); + // Master process will send SIGIO signal to all child processes. + posix_kill($masterPid, SIGIO); + // Waiting a moment. + usleep(500000); + // Display statistics data from a disk file. + static::safeEcho(static::formatConnectionStatusData()); + exit(0); + case 'restart': + case 'stop': + if ($mode === '-g') { + static::$gracefulStop = true; + $sig = SIGQUIT; + static::log("Workerman[$startFile] is gracefully stopping ..."); + } else { + static::$gracefulStop = false; + $sig = SIGINT; + static::log("Workerman[$startFile] is stopping ..."); + } + // Send stop signal to master process. + $masterPid && posix_kill($masterPid, $sig); + // Timeout. + $timeout = static::$stopTimeout + 3; + $startTime = time(); + // Check master process is still alive? + while (1) { + $masterIsAlive = $masterPid && posix_kill($masterPid, 0); + if ($masterIsAlive) { + // Timeout? + if (!static::getGracefulStop() && time() - $startTime >= $timeout) { + static::log("Workerman[$startFile] stop fail"); + exit; + } + // Waiting a moment. + usleep(10000); + continue; + } + // Stop success. + static::log("Workerman[$startFile] stop success"); + if ($command === 'stop') { + exit(0); + } + if ($mode === '-d') { + static::$daemonize = true; + } + break; + } + break; + case 'reload': + if ($mode === '-g') { + $sig = SIGUSR2; + } else { + $sig = SIGUSR1; + } + posix_kill($masterPid, $sig); + exit; + default : + static::safeEcho('Unknown command: ' . $command . "\n"); + exit($usage); + } + } + + /** + * Get argv. + * + * @return array + */ + public static function getArgv(): array + { + global $argv; + return static::$command ? [...$argv, ...explode(' ', static::$command)] : $argv; + } + + /** + * Format status data. + * + * @return string + */ + protected static function formatProcessStatusData(): string + { + static $totalRequestCache = []; + if (!is_readable(static::$statisticsFile)) { + return ''; + } + $info = file(static::$statisticsFile, FILE_IGNORE_NEW_LINES); + if (!$info) { + return ''; + } + $statusStr = ''; + $currentTotalRequest = []; + $workerInfo = []; + try { + $workerInfo = unserialize($info[0], ['allowed_classes' => false]); + } catch (Throwable) { + // do nothing + } + if (!is_array($workerInfo)) { + $workerInfo = []; + } + ksort($workerInfo, SORT_NUMERIC); + unset($info[0]); + $dataWaitingSort = []; + $readProcessStatus = false; + $totalRequests = 0; + $totalQps = 0; + $totalConnections = 0; + $totalFails = 0; + $totalMemory = 0; + $totalTimers = 0; + $maxLen1 = max(static::getUiColumnLength('maxSocketNameLength'), 2 * static::UI_SAFE_LENGTH); + $maxLen2 = max(static::getUiColumnLength('maxWorkerNameLength'), 2 * static::UI_SAFE_LENGTH); + foreach ($info as $value) { + if (!$readProcessStatus) { + $statusStr .= $value . "\n"; + if (preg_match('/^pid.*?memory.*?listening/', $value)) { + $readProcessStatus = true; + } + continue; + } + if (preg_match('/^[0-9]+/', $value, $pidMath)) { + $pid = $pidMath[0]; + $dataWaitingSort[$pid] = $value; + if (preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) { + $totalMemory += (float)str_ireplace('M', '', $match[1]); + $maxLen1 = max($maxLen1, strlen($match[2])); + $maxLen2 = max($maxLen2, strlen($match[3])); + $totalConnections += (int)$match[4]; + $totalFails += (int)$match[5]; + $totalTimers += (int)$match[6]; + $currentTotalRequest[$pid] = $match[7]; + $totalRequests += (int)$match[7]; + } + } + } + foreach ($workerInfo as $pid => $info) { + if (!isset($dataWaitingSort[$pid])) { + $statusStr .= "$pid\t" . str_pad('N/A', 7) . " " + . str_pad($info['listen'], $maxLen1) . " " + . str_pad((string)$info['name'], $maxLen2) . " " + . str_pad('N/A', 11) . " " . str_pad('N/A', 9) . " " + . str_pad('N/A', 7) . " " . str_pad('N/A', 13) . " N/A [busy] \n"; + continue; + } + //$qps = isset($totalRequestCache[$pid]) ? $currentTotalRequest[$pid] + if (!isset($totalRequestCache[$pid], $currentTotalRequest[$pid])) { + $qps = 0; + } else { + $qps = $currentTotalRequest[$pid] - $totalRequestCache[$pid]; + $totalQps += $qps; + } + $statusStr .= $dataWaitingSort[$pid] . " " . str_pad((string)$qps, 6) . " [idle]\n"; + } + $totalRequestCache = $currentTotalRequest; + $statusStr .= "---------------------------------------------------PROCESS STATUS--------------------------------------------------------\n"; + $statusStr .= "Summary\t" . str_pad($totalMemory . 'M', 7) . " " + . str_pad('-', $maxLen1) . " " + . str_pad('-', $maxLen2) . " " + . str_pad((string)$totalConnections, 11) . " " . str_pad((string)$totalFails, 9) . " " + . str_pad((string)$totalTimers, 7) . " " . str_pad((string)$totalRequests, 13) . " " + . str_pad((string)$totalQps, 6) . " [Summary] \n"; + return $statusStr; + } + + protected static function formatConnectionStatusData(): string + { + return file_get_contents(static::$connectionsFile); + } + + /** + * Install signal handler. + * + * @return void + */ + protected static function installSignal(): void + { + if (DIRECTORY_SEPARATOR !== '/') { + return; + } + $signals = [SIGINT, SIGTERM, SIGHUP, SIGTSTP, SIGQUIT, SIGUSR1, SIGUSR2, SIGIOT, SIGIO]; + foreach ($signals as $signal) { + pcntl_signal($signal, static::signalHandler(...), false); + } + // ignore + pcntl_signal(SIGPIPE, SIG_IGN, false); + } + + /** + * Reinstall signal handler. + * + * @return void + */ + protected static function reinstallSignal(): void + { + if (DIRECTORY_SEPARATOR !== '/') { + return; + } + $signals = [SIGINT, SIGTERM, SIGHUP, SIGTSTP, SIGQUIT, SIGUSR1, SIGUSR2, SIGIOT, SIGIO]; + foreach ($signals as $signal) { + // Rewrite master process signal. + static::$globalEvent->onSignal($signal, static::signalHandler(...)); + } + } + + /** + * Signal handler. + * + * @param int $signal + * @param mixed ...$args + */ + public static function signalHandler(int $signal, mixed ...$args): void + { + switch ($signal) { + // Stop. + case SIGINT: + case SIGTERM: + case SIGHUP: + case SIGTSTP: + static::$gracefulStop = false; + static::stopAll(0, 'received signal ' . static::getSignalName($signal)); + break; + // Graceful stop. + case SIGQUIT: + static::$gracefulStop = true; + static::stopAll(0, 'received signal ' . static::getSignalName($signal)); + break; + // Reload. + case SIGUSR2: + case SIGUSR1: + if (static::$status === static::STATUS_RELOADING || static::$status === static::STATUS_SHUTDOWN) { + return; + } + static::$gracefulStop = $signal === SIGUSR2; + static::$pidsToRestart = static::getAllWorkerPids(); + static::reload(); + break; + // Show status. + case SIGIOT: + static::writeStatisticsToStatusFile(); + break; + // Show connection status. + case SIGIO: + static::writeConnectionsStatisticsToStatusFile(); + break; + } + } + + /** + * Get signal name. + * + * @param int $signal + * @return string + */ + protected static function getSignalName(int $signal): string + { + return match ($signal) { + SIGINT => 'SIGINT', + SIGTERM => 'SIGTERM', + SIGHUP => 'SIGHUP', + SIGTSTP => 'SIGTSTP', + SIGQUIT => 'SIGQUIT', + SIGUSR1 => 'SIGUSR1', + SIGUSR2 => 'SIGUSR2', + SIGIOT => 'SIGIOT', + SIGIO => 'SIGIO', + default => $signal, + }; + } + + /** + * Run as daemon mode. + */ + protected static function daemonize(): void + { + if (!static::$daemonize || DIRECTORY_SEPARATOR !== '/') { + return; + } + umask(0); + $pid = pcntl_fork(); + if (-1 === $pid) { + throw new RuntimeException('Fork fail'); + } elseif ($pid > 0) { + exit(0); + } + if (-1 === posix_setsid()) { + throw new RuntimeException("Setsid fail"); + } + // Fork again avoid SVR4 system regain the control of terminal. + $pid = pcntl_fork(); + if (-1 === $pid) { + throw new RuntimeException("Fork fail"); + } elseif (0 !== $pid) { + exit(0); + } + } + + /** + * Redirect standard output to stdoutFile. + * + * @return void + */ + public static function resetStd(): void + { + if (!static::$daemonize || DIRECTORY_SEPARATOR !== '/') { + return; + } + + if (defined('STDOUT') && is_resource(STDOUT) && get_resource_type(STDOUT) === 'stream') { + try { + @fclose(STDOUT); + } catch (Throwable) {} + } + + if (defined('STDERR') && is_resource(STDERR) && get_resource_type(STDERR) === 'stream') { + try { + @fclose(STDERR); + } catch (Throwable) {} + } + + if (is_resource(static::$outputStream) && get_resource_type(static::$outputStream) === 'stream') { + try { + @fclose(static::$outputStream); + } catch (Throwable) {} + } + + set_error_handler(static fn (...$args): bool => true); + $stdOutStream = fopen(static::$stdoutFile, 'a'); + restore_error_handler(); + + if ($stdOutStream !== false) { + static::$outputStream = $stdOutStream; + } + + // Fix standard output cannot redirect of PHP 8.1.8's bug + if (function_exists('posix_isatty') && posix_isatty(2)) { + ob_start(function (string $string, ...$args) { + file_put_contents(static::$stdoutFile, $string, FILE_APPEND); + }, 1); + } + } + + /** + * Save pid. + */ + protected static function saveMasterPid(): void + { + if (DIRECTORY_SEPARATOR !== '/') { + return; + } + + static::$masterPid = posix_getpid(); + if (false === file_put_contents(static::$pidFile, static::$masterPid)) { + throw new RuntimeException('can not save pid to ' . static::$pidFile); + } + } + + /** + * Get all pids of worker processes. + * + * @return array + */ + protected static function getAllWorkerPids(): array + { + $pidArray = []; + foreach (static::$pidMap as $workerPidArray) { + foreach ($workerPidArray as $workerPid) { + $pidArray[$workerPid] = $workerPid; + } + } + return $pidArray; + } + + /** + * Fork some worker processes. + * + * @return void + */ + protected static function forkWorkers(): void + { + if (DIRECTORY_SEPARATOR === '/') { + static::forkWorkersForLinux(); + } else { + static::forkWorkersForWindows(); + } + } + + /** + * Fork some worker processes. + * + * @return void + */ + protected static function forkWorkersForLinux(): void + { + foreach (static::$workers as $worker) { + if (static::$status === static::STATUS_STARTING) { + if (empty($worker->name)) { + $worker->name = $worker->getSocketName(); + } + } + while (count(static::$pidMap[$worker->workerId]) < $worker->count) { + static::forkOneWorkerForLinux($worker); + } + } + } + + /** + * Fork some worker processes. + * + * @return void + */ + protected static function forkWorkersForWindows(): void + { + $files = static::getStartFilesForWindows(); + if (count($files) === 1 || in_array('-q', static::getArgv())) { + if (count(static::$workers) > 1) { + static::safeEcho("@@@ Error: multi workers init in one php file are not support @@@\r\n"); + static::safeEcho("@@@ See https://www.workerman.net/doc/workerman/faq/multi-woker-for-windows.html @@@\r\n"); + } elseif (count(static::$workers) <= 0) { + exit("@@@no worker inited@@@\r\n\r\n"); + } + + reset(static::$workers); + /** @var Worker $worker */ + $worker = current(static::$workers); + + Timer::delAll(); + + //Update process state. + static::$status = static::STATUS_RUNNING; + + // Register shutdown function for checking errors. + register_shutdown_function(static::checkErrors(...)); + + // Create a global event loop. + if (static::$globalEvent === null) { + static::$eventLoopClass = $worker->eventLoop ?: static::$eventLoopClass; + static::$globalEvent = new static::$eventLoopClass(); + static::$globalEvent->setErrorHandler(function ($exception) { + static::stopAll(250, $exception); + }); + } + + // Reinstall signal. + static::reinstallSignal(); + + // Init Timer. + Timer::init(static::$globalEvent); + + restore_error_handler(); + + // Add an empty timer to prevent the event-loop from exiting. + Timer::add(0.8, function (){}); + + // Compatibility with the bug in Swow where the first request on Windows fails to trigger stream_select. + if (extension_loaded('swow')) { + Timer::delay(0.1 , function(){ + $stream = tmpfile(); + static::$globalEvent->onReadable($stream, function($stream) { + static::$globalEvent->offReadable($stream); + }); + }); + } + + // Display UI. + static::safeEcho(str_pad($worker->name, 48) . str_pad($worker->getSocketName(), 36) . str_pad('1', 10) . " [ok]\n"); + $worker->run(); + static::$globalEvent->run(); + if (static::$status !== self::STATUS_SHUTDOWN) { + $err = new RuntimeException('event-loop exited'); + static::log($err); + exit(250); + } + exit(0); + } + + static::$globalEvent = new Select(); + static::$globalEvent->setErrorHandler(function ($exception) { + static::stopAll(250, $exception); + }); + Timer::init(static::$globalEvent); + foreach ($files as $startFile) { + static::forkOneWorkerForWindows($startFile); + } + } + + /** + * Get start files for windows. + * + * @return array + */ + public static function getStartFilesForWindows(): array + { + $files = []; + foreach (static::getArgv() as $file) { + if (is_file($file)) { + $files[$file] = $file; + } + } + return $files; + } + + /** + * Fork one worker process. + * + * @param string $startFile + */ + public static function forkOneWorkerForWindows(string $startFile): void + { + $startFile = realpath($startFile); + $descriptorSpec = [STDIN, STDOUT, STDOUT]; + $pipes = []; + $process = proc_open('"' . PHP_BINARY . '" ' . " \"$startFile\" -q", $descriptorSpec, $pipes, null, null, ['bypass_shell' => true]); + + if (static::$globalEvent === null) { + static::$globalEvent = new Select(); + static::$globalEvent->setErrorHandler(function ($exception) { + static::stopAll(250, $exception); + }); + Timer::init(static::$globalEvent); + } + + // 保存子进程句柄 + static::$processForWindows[$startFile] = [$process, $startFile]; + } + + /** + * check worker status for windows. + * + * @return void + */ + protected static function checkWorkerStatusForWindows(): void + { + foreach (static::$processForWindows as $processData) { + $process = $processData[0]; + $startFile = $processData[1]; + $status = proc_get_status($process); + if (!$status['running']) { + static::safeEcho("process $startFile terminated and try to restart\n"); + proc_close($process); + static::forkOneWorkerForWindows($startFile); + } + } + } + + /** + * Fork one worker process. + * + * @param self $worker + */ + protected static function forkOneWorkerForLinux(self $worker): void + { + // Get available worker id. + $id = static::getId($worker->workerId, 0); + $pid = pcntl_fork(); + // For master process. + if ($pid > 0) { + static::$pidMap[$worker->workerId][$pid] = $pid; + static::$idMap[$worker->workerId][$id] = $pid; + } // For child processes. + elseif (0 === $pid) { + srand(); + mt_srand(); + static::$gracefulStop = false; + if (static::$status === static::STATUS_STARTING) { + static::resetStd(); + } + static::$pidsToRestart = static::$pidMap = []; + // Remove other listener. + foreach (static::$workers as $key => $oneWorker) { + if ($oneWorker->workerId !== $worker->workerId) { + $oneWorker->unlisten(); + unset(static::$workers[$key]); + } + } + Timer::delAll(); + + //Update process state. + static::$status = static::STATUS_RUNNING; + + // Register shutdown function for checking errors. + register_shutdown_function(static::checkErrors(...)); + + // Create a global event loop. + if (static::$globalEvent === null) { + static::$eventLoopClass = $worker->eventLoop ?: static::$eventLoopClass; + static::$globalEvent = new static::$eventLoopClass(); + static::$globalEvent->setErrorHandler(function ($exception) { + static::stopAll(250, $exception); + }); + } + + // Reinstall signal. + static::reinstallSignal(); + + // Init Timer. + Timer::init(static::$globalEvent); + + restore_error_handler(); + + static::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName()); + $worker->setUserAndGroup(); + $worker->id = $id; + $worker->run(); + // Main loop. + static::$globalEvent->run(); + if (static::$status !== self::STATUS_SHUTDOWN) { + $err = new Exception('event-loop exited'); + static::log($err); + exit(250); + } + exit(0); + } else { + throw new RuntimeException("forkOneWorker fail"); + } + } + + /** + * Get worker id. + * + * @param int $workerId + * @param int $pid + * @return false|int|string + */ + protected static function getId(int $workerId, int $pid): false|int|string + { + return array_search($pid, static::$idMap[$workerId]); + } + + /** + * Set unix user and group for current process. + * + * @return void + */ + public function setUserAndGroup(): void + { + // Get uid. + $userInfo = posix_getpwnam($this->user); + if (!$userInfo) { + static::log("Warning: User $this->user not exists"); + return; + } + $uid = $userInfo['uid']; + // Get gid. + if ($this->group) { + $groupInfo = posix_getgrnam($this->group); + if (!$groupInfo) { + static::log("Warning: Group $this->group not exists"); + return; + } + $gid = $groupInfo['gid']; + } else { + $gid = $userInfo['gid']; + } + + // Set uid and gid. + if ($uid !== posix_getuid() || $gid !== posix_getgid()) { + if (!posix_setgid($gid) || !posix_initgroups($userInfo['name'], $gid) || !posix_setuid($uid)) { + static::log("Warning: change gid or uid fail."); + } + } + } + + /** + * Set process name. + * + * @param string $title + * @return void + */ + protected static function setProcessTitle(string $title): void + { + set_error_handler(static fn (...$args): bool => true); + cli_set_process_title($title); + restore_error_handler(); + } + + /** + * Monitor all child processes. + * + * @return void + * @throws Throwable + */ + protected static function monitorWorkers(): void + { + if (DIRECTORY_SEPARATOR === '/') { + static::monitorWorkersForLinux(); + } else { + static::monitorWorkersForWindows(); + } + } + + /** + * Monitor all child processes. + * + * @return void + */ + protected static function monitorWorkersForLinux(): void + { + static::$status = static::STATUS_RUNNING; + // @phpstan-ignore-next-line While loop condition is always true. + while (1) { + // Calls signal handlers for pending signals. + pcntl_signal_dispatch(); + // Suspends execution of the current process until a child has exited, or until a signal is delivered + $status = 0; + $pid = pcntl_wait($status, WUNTRACED); + // Calls signal handlers for pending signals again. + pcntl_signal_dispatch(); + // If a child has already exited. + if ($pid > 0) { + // Find out which worker process exited. + foreach (static::$pidMap as $workerId => $workerPidArray) { + if (isset($workerPidArray[$pid])) { + $worker = static::$workers[$workerId]; + // Fix exit with status 2 for php8.2 + if ($status === SIGINT && static::$status === static::STATUS_SHUTDOWN) { + $status = 0; + } + // Exit status. + if ($status !== 0) { + static::log("worker[$worker->name:$pid] exit with status $status"); + } + + // onWorkerExit + if (static::$onWorkerExit) { + try { + (static::$onWorkerExit)($worker, $status, $pid); + } catch (Throwable $exception) { + static::log("worker[$worker->name] onWorkerExit $exception"); + } + } + + // For Statistics. + static::$globalStatistics['worker_exit_info'][$workerId][$status] ??= 0; + static::$globalStatistics['worker_exit_info'][$workerId][$status]++; + + // Clear process data. + unset(static::$pidMap[$workerId][$pid]); + + // Mark id is available. + $id = static::getId($workerId, $pid); + if ($id !== false) { + static::$idMap[$workerId][$id] = 0; + } + + break; + } + } + // Is still running state then fork a new worker process. + if (static::$status !== static::STATUS_SHUTDOWN) { + static::forkWorkers(); + // If reloading continue. + if (isset(static::$pidsToRestart[$pid])) { + unset(static::$pidsToRestart[$pid]); + static::reload(); + } + } + } + + // If shutdown state and all child processes exited, then master process exit. + if (static::$status === static::STATUS_SHUTDOWN && empty(static::getAllWorkerPids())) { + static::exitAndClearAll(); + } + } + } + + /** + * Monitor all child processes. + * + * @return void + */ + protected static function monitorWorkersForWindows(): void + { + Timer::add(1, static::checkWorkerStatusForWindows(...)); + + static::$globalEvent->run(); + } + + /** + * Exit current process. + */ + protected static function exitAndClearAll(): void + { + clearstatcache(); + foreach (static::$workers as $worker) { + $socketName = $worker->getSocketName(); + if ($worker->transport === 'unix' && $socketName) { + [, $address] = explode(':', $socketName, 2); + $address = substr($address, strpos($address, '/') + 2); + if (file_exists($address)) { + @unlink($address); + } + } + } + if (file_exists(static::$pidFile)) { + @unlink(static::$pidFile); + } + static::log("Workerman[" . basename(static::$startFile) . "] has been stopped"); + if (static::$onMasterStop) { + (static::$onMasterStop)(); + } + exit(0); + } + + /** + * Execute reload. + * + * @return void + */ + protected static function reload(): void + { + // For master process. + if (static::$masterPid === posix_getpid()) { + $sig = static::getGracefulStop() ? SIGUSR2 : SIGUSR1; + // Set reloading state. + if (static::$status === static::STATUS_RUNNING) { + static::log("Workerman[" . basename(static::$startFile) . "] reloading"); + static::$status = static::STATUS_RELOADING; + + static::resetStd(); + // Try to emit onMasterReload callback. + if (static::$onMasterReload) { + try { + (static::$onMasterReload)(); + } catch (Throwable $e) { + static::stopAll(250, $e); + } + static::initId(); + } + + // Send reload signal to all child processes. + $reloadablePidArray = []; + foreach (static::$pidMap as $workerId => $workerPidArray) { + $worker = static::$workers[$workerId]; + if ($worker->reloadable) { + $reloadablePidArray += $workerPidArray; + continue; + } + // Send reload signal to a worker process which reloadable is false. + array_walk($workerPidArray, static fn ($pid) => posix_kill($pid, $sig)); + } + // Get all pids that are waiting reload. + static::$pidsToRestart = array_intersect(static::$pidsToRestart, $reloadablePidArray); + } + + // Reload complete. + if (empty(static::$pidsToRestart)) { + if (static::$status !== static::STATUS_SHUTDOWN) { + static::$status = static::STATUS_RUNNING; + } + return; + } + // Continue reload. + $oneWorkerPid = current(static::$pidsToRestart); + // Send reload signal to a worker process. + posix_kill($oneWorkerPid, $sig); + // If the process does not exit after stopTimeout seconds try to kill it. + if (!static::getGracefulStop()) { + Timer::add(static::$stopTimeout, posix_kill(...), [$oneWorkerPid, SIGKILL], false); + } + } // For child processes. + else { + reset(static::$workers); + $worker = current(static::$workers); + // Try to emit onWorkerReload callback. + if ($worker->onWorkerReload) { + try { + ($worker->onWorkerReload)($worker); + } catch (Throwable $e) { + static::stopAll(250, $e); + } + } + + if ($worker->reloadable) { + static::stopAll(); + } else { + static::resetStd(); + } + } + } + + /** + * Stop all. + * + * @param int $code + * @param mixed $log + */ + public static function stopAll(int $code = 0, mixed $log = ''): void + { + static::$status = static::STATUS_SHUTDOWN; + // For master process. + if (DIRECTORY_SEPARATOR === '/' && static::$masterPid === posix_getpid()) { + if ($log) { + static::log("Workerman[" . basename(static::$startFile) . "] $log"); + } + static::log("Workerman[" . basename(static::$startFile) . "] stopping" . ($code ? ", code [$code]" : '')); + $workerPidArray = static::getAllWorkerPids(); + // Send stop signal to all child processes. + $sig = static::getGracefulStop() ? SIGQUIT : SIGINT; + foreach ($workerPidArray as $workerPid) { + // Fix exit with status 2 for php8.2 + if ($sig === SIGINT && !static::$daemonize) { + Timer::add(1, posix_kill(...), [$workerPid, SIGINT], false); + } else { + posix_kill($workerPid, $sig); + } + if (!static::getGracefulStop()) { + Timer::add(ceil(static::$stopTimeout), posix_kill(...), [$workerPid, SIGKILL], false); + } + } + Timer::add(1, static::checkIfChildRunning(...)); + } // For child processes. + else { + if ($code && $log) { + static::log($log); + } + // Execute exit. + $workers = array_reverse(static::$workers); + array_walk($workers, static fn (Worker $worker, mixed ...$args) => $worker->stop(false)); + + $callback = function () use ($code, $workers) { + $allWorkerConnectionClosed = true; + if (!static::getGracefulStop()) { + foreach ($workers as $worker) { + foreach ($worker->connections as $connection) { + // Delay closing, waiting for data to be sent. + if (!$connection->getRecvBufferQueueSize() && !isset($connection->context->closeTimer)) { + $connection->context->closeTimer = Timer::delay(0.01, static fn () => $connection->close()); + } + $allWorkerConnectionClosed = false; + } + } + } + if ((!static::getGracefulStop() && $allWorkerConnectionClosed) || ConnectionInterface::$statistics['connection_count'] <= 0) { + static::$globalEvent?->stop(); + try { + // Ignore Swoole ExitException: Swoole exit. + exit($code); + /** @phpstan-ignore-next-line */ + } catch (Throwable) { + // do nothing + } + } + }; + Timer::repeat(0.01, $callback); + } + } + + /** + * check if child processes is really running + */ + public static function checkIfChildRunning(): void + { + foreach (static::$pidMap as $workerId => $workerPidArray) { + foreach ($workerPidArray as $pid => $workerPid) { + if (!posix_kill($pid, 0)) { + unset(static::$pidMap[$workerId][$pid]); + } + } + } + } + + /** + * Get process status. + * + * @return int + */ + public static function getStatus(): int + { + return static::$status; + } + + /** + * If stop gracefully. + * + * @return bool + */ + public static function getGracefulStop(): bool + { + return static::$gracefulStop; + } + + /** + * + * Write statistics data to disk. + * + * @return void + */ + protected static function writeStatisticsToStatusFile(): void + { + // For master process. + if (static::$masterPid === posix_getpid()) { + $allWorkerInfo = []; + foreach (static::$pidMap as $workerId => $pidArray) { + $worker = static::$workers[$workerId]; + foreach ($pidArray as $pid) { + $allWorkerInfo[$pid] = ['name' => $worker->name, 'listen' => $worker->getSocketName()]; + } + } + file_put_contents(static::$statisticsFile, ''); + chmod(static::$statisticsFile, 0722); + file_put_contents(static::$statisticsFile, serialize($allWorkerInfo) . "\n", FILE_APPEND); + $loadavg = function_exists('sys_getloadavg') ? array_map(round(...), sys_getloadavg(), [2, 2, 2]) : ['-', '-', '-']; + file_put_contents(static::$statisticsFile, + (static::$daemonize ? "Start worker in DAEMON mode." : "Start worker in DEBUG mode.") . "\n", FILE_APPEND); + file_put_contents(static::$statisticsFile, + "---------------------------------------------------GLOBAL STATUS---------------------------------------------------------\n", FILE_APPEND); + file_put_contents(static::$statisticsFile, static::getVersionLine(), FILE_APPEND); + file_put_contents(static::$statisticsFile, 'start time:' . date('Y-m-d H:i:s', + static::$globalStatistics['start_timestamp']) + . ' run ' . floor((time() - static::$globalStatistics['start_timestamp']) / (24 * 60 * 60)) + . ' days ' . floor(((time() - static::$globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) + . " hours " . 'load average: ' . implode(", ", $loadavg) . "\n", FILE_APPEND); + file_put_contents(static::$statisticsFile, + count(static::$pidMap) . ' workers ' . count(static::getAllWorkerPids()) . " processes\n", + FILE_APPEND); + file_put_contents(static::$statisticsFile, + str_pad('name', static::getUiColumnLength('maxWorkerNameLength')) . " event-loop exit_status exit_count\n", FILE_APPEND); + foreach (static::$pidMap as $workerId => $workerPidArray) { + $worker = static::$workers[$workerId]; + if (isset(static::$globalStatistics['worker_exit_info'][$workerId])) { + foreach (static::$globalStatistics['worker_exit_info'][$workerId] as $workerExitStatus => $workerExitCount) { + file_put_contents(static::$statisticsFile, + str_pad($worker->name, static::getUiColumnLength('maxWorkerNameLength')) . " " . + str_pad($worker->context->eventLoopName, 14) . " " . + str_pad((string)$workerExitStatus, 16) . str_pad((string)$workerExitCount, 16) . "\n", FILE_APPEND); + } + } else { + file_put_contents(static::$statisticsFile, + str_pad($worker->name, static::getUiColumnLength('maxWorkerNameLength')) . " " . + str_pad($worker->context->eventLoopName, 14) . " " . + str_pad('0', 16) . str_pad('0', 16) . "\n", FILE_APPEND); + } + } + file_put_contents(static::$statisticsFile, + "---------------------------------------------------PROCESS STATUS--------------------------------------------------------\n", + FILE_APPEND); + file_put_contents(static::$statisticsFile, + "pid\tmemory " . str_pad('listening', static::getUiColumnLength('maxSocketNameLength')) . " " . str_pad('name', + static::getUiColumnLength('maxWorkerNameLength')) . " connections " . str_pad('send_fail', 9) . " " + . str_pad('timers', 8) . str_pad('total_request', 13) . " qps status\n", FILE_APPEND); + + foreach (static::getAllWorkerPids() as $workerPid) { + posix_kill($workerPid, SIGIOT); + } + return; + } + + reset(static::$workers); + /** @var static $worker */ + $worker = current(static::$workers); + $workerStatusStr = posix_getpid() . "\t" . str_pad(round(memory_get_usage() / (1024 * 1024), 2) . "M", 7) + . " " . str_pad($worker->getSocketName(), static::getUiColumnLength('maxSocketNameLength')) . " " + . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::getUiColumnLength('maxWorkerNameLength')) + . " "; + $workerStatusStr .= str_pad((string)ConnectionInterface::$statistics['connection_count'], 11) + . " " . str_pad((string)ConnectionInterface::$statistics['send_fail'], 9) + . " " . str_pad((string)static::$globalEvent->getTimerCount(), 7) + . " " . str_pad((string)ConnectionInterface::$statistics['total_request'], 13) . "\n"; + file_put_contents(static::$statisticsFile, $workerStatusStr, FILE_APPEND); + } + + /** + * Get UI column length + * + * @param $name + * @return int + */ + protected static function getUiColumnLength($name): int + { + return static::$uiLengthData[$name] ?? 0; + } + + /** + * Write statistics data to disk. + * + * @return void + */ + protected static function writeConnectionsStatisticsToStatusFile(): void + { + // For master process. + if (static::$masterPid === posix_getpid()) { + file_put_contents(static::$connectionsFile, ''); + chmod(static::$connectionsFile, 0722); + file_put_contents(static::$connectionsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", FILE_APPEND); + file_put_contents(static::$connectionsFile, "PID Worker CID Trans Protocol ipv4 ipv6 Recv-Q Send-Q Bytes-R Bytes-W Status Local Address Foreign Address\n", FILE_APPEND); + foreach (static::getAllWorkerPids() as $workerPid) { + posix_kill($workerPid, SIGIO); + } + return; + } + + // For child processes. + $bytesFormat = function ($bytes) { + if ($bytes > 1024 * 1024 * 1024 * 1024) { + return round($bytes / (1024 * 1024 * 1024 * 1024), 1) . "TB"; + } + if ($bytes > 1024 * 1024 * 1024) { + return round($bytes / (1024 * 1024 * 1024), 1) . "GB"; + } + if ($bytes > 1024 * 1024) { + return round($bytes / (1024 * 1024), 1) . "MB"; + } + if ($bytes > 1024) { + return round($bytes / (1024), 1) . "KB"; + } + return $bytes . "B"; + }; + + $pid = posix_getpid(); + $str = ''; + reset(static::$workers); + $currentWorker = current(static::$workers); + $defaultWorkerName = $currentWorker->name; + + foreach (TcpConnection::$connections as $connection) { + /** @var TcpConnection $connection */ + $transport = $connection->transport; + $ipv4 = $connection->isIpV4() ? ' 1' : ' 0'; + $ipv6 = $connection->isIpV6() ? ' 1' : ' 0'; + $recvQ = $bytesFormat($connection->getRecvBufferQueueSize()); + $sendQ = $bytesFormat($connection->getSendBufferQueueSize()); + $localAddress = trim($connection->getLocalAddress()); + $remoteAddress = trim($connection->getRemoteAddress()); + $state = $connection->getStatus(false); + $bytesRead = $bytesFormat($connection->bytesRead); + $bytesWritten = $bytesFormat($connection->bytesWritten); + $id = $connection->id; + $protocol = $connection->protocol ?: $connection->transport; + $pos = strrpos($protocol, '\\'); + if ($pos) { + $protocol = substr($protocol, $pos + 1); + } + if (strlen($protocol) > 15) { + $protocol = substr($protocol, 0, 13) . '..'; + } + $workerName = isset($connection->worker) ? $connection->worker->name : $defaultWorkerName; + if (strlen($workerName) > 14) { + $workerName = substr($workerName, 0, 12) . '..'; + } + $str .= str_pad((string)$pid, 9) . str_pad($workerName, 16) . str_pad((string)$id, 10) . str_pad($transport, 8) + . str_pad($protocol, 16) . str_pad($ipv4, 7) . str_pad($ipv6, 7) . str_pad($recvQ, 13) + . str_pad($sendQ, 13) . str_pad($bytesRead, 13) . str_pad($bytesWritten, 13) . ' ' + . str_pad($state, 14) . ' ' . str_pad($localAddress, 22) . ' ' . str_pad($remoteAddress, 22) . "\n"; + } + if ($str) { + file_put_contents(static::$connectionsFile, $str, FILE_APPEND); + } + } + + /** + * Check errors when current process exited. + * + * @param mixed ...$args + * @return void + */ + public static function checkErrors(mixed ...$args): void + { + if (static::STATUS_SHUTDOWN !== static::$status) { + $errorMsg = DIRECTORY_SEPARATOR === '/' ? 'Worker[' . posix_getpid() . '] process terminated' : 'Worker process terminated'; + $errors = error_get_last(); + if ($errors && ($errors['type'] === E_ERROR || + $errors['type'] === E_PARSE || + $errors['type'] === E_CORE_ERROR || + $errors['type'] === E_COMPILE_ERROR || + $errors['type'] === E_RECOVERABLE_ERROR) + ) { + $errorMsg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\""; + } + static::log($errorMsg); + } + } + + /** + * Get error message by error code. + * + * @param int $type + * @return string + */ + protected static function getErrorType(int $type): string + { + return self::ERROR_TYPE[$type] ?? ''; + } + + /** + * Log. + * + * @param Stringable|string $msg + * @param bool $decorated + * @return void + */ + public static function log(Stringable|string $msg, bool $decorated = false): void + { + $msg = trim((string)$msg); + + if (!static::$daemonize) { + static::safeEcho("$msg\n", $decorated); + } + + if (isset(static::$logFile)) { + $pid = DIRECTORY_SEPARATOR === '/' ? posix_getpid() : 1; + file_put_contents(static::$logFile, sprintf("%s pid:%d %s\n", date('Y-m-d H:i:s'), $pid, $msg), FILE_APPEND | LOCK_EX); + + // Check the file size and truncate if it exceeds max size + if (!empty(static::$logFileMaxSize) && ($fileSize = filesize(static::$logFile)) > static::$logFileMaxSize) { + // Open files + $source = fopen(static::$logFile, 'r'); + + if (!$source) { + return; + } else if (!flock($source, LOCK_EX)) { + fclose($source); + return; + } + + $newFile = static::$logFile . '.tmp'; + $destination = fopen($newFile, 'w'); + + if (!$destination) { + flock($source, LOCK_UN); + fclose($source); + return; + } + + // Move to the halfway point in the source file + $halfwayPoint = (int)($fileSize / 2); + fseek($source, $halfwayPoint); + + // Find the next newline character to ensure we don't cut in the middle of a line + while (($char = fgetc($source)) !== false) { + if ($char === "\n") { + break; + } + } + + // Copy the second half into the new file + while (!feof($source)) { + fwrite($destination, fread($source, 8192)); // Read and write 8KB chunks + } + + // Replace the old file with the new truncated file + rename($newFile, static::$logFile); + + // Close both files + flock($source, LOCK_UN); + fclose($source); + fclose($destination); + } + } + } + + /** + * Safe Echo. + * + * @param string $msg + * @param bool $decorated + * @return void + */ + public static function safeEcho(string $msg, bool $decorated = false): void + { + if ((static::$outputDecorated ?? false) && $decorated) { + $line = "\033[1A\n\033[K"; + $white = "\033[47;30m"; + $green = "\033[32;40m"; + $end = "\033[0m"; + } else { + $line = ''; + $white = ''; + $green = ''; + $end = ''; + } + + $msg = str_replace(['', '', ''], [$line, $white, $green], $msg); + $msg = str_replace(['', '', ''], $end, $msg); + // The stream is normally set up by runAll(), but safeEcho() is also reachable from plain + // client scripts. The resource check also handles a closed handle without another warning. + if (static::$outputStream === null) { + static::initStdOut(); + } + set_error_handler(static fn (...$args): bool => true); + if (is_resource(self::$outputStream) && !feof(self::$outputStream)) { + fwrite(self::$outputStream, $msg); + fflush(self::$outputStream); + } + restore_error_handler(); + } + + /** + * Listen. + * + * @param bool $autoAccept + * @return void + */ + public function listen(bool $autoAccept = true): void + { + if (!$this->socketName) { + return; + } + + if (!$this->mainSocket) { + + $localSocket = $this->parseSocketAddress(); + + // Flag. + $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN; + $errNo = 0; + $errMsg = ''; + // SO_REUSEPORT. + if ($this->reusePort && DIRECTORY_SEPARATOR !== '\\') { + stream_context_set_option($this->socketContext, 'socket', 'so_reuseport', 1); + } + + // Create an Internet or Unix domain server socket. + $this->mainSocket = stream_socket_server($localSocket, $errNo, $errMsg, $flags, $this->socketContext); + if (!$this->mainSocket) { + throw new RuntimeException($errMsg); + } + + if ($this->transport === 'ssl') { + stream_socket_enable_crypto($this->mainSocket, false); + } elseif ($this->transport === 'unix') { + $socketFile = substr($localSocket, 7); + if ($this->user) { + chown($socketFile, $this->user); + } + if ($this->group) { + chgrp($socketFile, $this->group); + } + } + + // Try to open keepalive for tcp and disable Nagle algorithm. + if (function_exists('socket_import_stream') && self::BUILD_IN_TRANSPORTS[$this->transport] === 'tcp') { + set_error_handler(static fn (...$args): bool => true); + $socket = socket_import_stream($this->mainSocket); + socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); + socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); + if (defined('TCP_KEEPIDLE') && defined('TCP_KEEPINTVL') && defined('TCP_KEEPCNT')) { + socket_set_option($socket, SOL_TCP, TCP_KEEPIDLE, TcpConnection::TCP_KEEPALIVE_INTERVAL); + socket_set_option($socket, SOL_TCP, TCP_KEEPINTVL, TcpConnection::TCP_KEEPALIVE_INTERVAL); + socket_set_option($socket, SOL_TCP, TCP_KEEPCNT, 1); + } + restore_error_handler(); + } + + // Non blocking. + stream_set_blocking($this->mainSocket, false); + } + + if ($autoAccept) { + $this->resumeAccept(); + } + } + + /** + * Unlisten. + * + * @return void + */ + public function unlisten(): void + { + $this->pauseAccept(); + if ($this->mainSocket) { + set_error_handler(static fn (...$args): bool => true); + fclose($this->mainSocket); + restore_error_handler(); + $this->mainSocket = null; + } + } + + /** + * Check port available. + * + * @return void + */ + protected static function checkPortAvailable(): void + { + foreach (static::$workers as $worker) { + $socketName = $worker->getSocketName(); + if (DIRECTORY_SEPARATOR === '/' // if linux + && static::$status === static::STATUS_STARTING // only for starting status + && $worker->transport === 'tcp' // if tcp socket + && !str_starts_with($socketName, 'unix') // if not unix socket + && !str_starts_with($socketName, 'udp')) { // if not udp socket + + $address = parse_url($socketName); + if (isset($address['host']) && isset($address['port'])) { + $address = "tcp://{$address['host']}:{$address['port']}"; + $server = null; + set_error_handler(function ($code, $msg, ...$args) { + throw new RuntimeException($msg); + }); + $server = stream_socket_server($address, $code, $msg); + if ($server) { + fclose($server); + } + restore_error_handler(); + } + } + } + } + + /** + * Parse local socket address. + */ + protected function parseSocketAddress(): ?string + { + if (!$this->socketName) { + return null; + } + // Get the application layer communication protocol and listening address. + [$scheme, $address] = explode(':', $this->socketName, 2); + // Check application layer protocol class. + if (!isset(self::BUILD_IN_TRANSPORTS[$scheme])) { + // Validate scheme contains only safe characters for class name resolution. + if (!preg_match('/^[a-zA-Z][a-zA-Z0-9]*$/', $scheme)) { + throw new RuntimeException("Invalid protocol scheme '$scheme'"); + } + $scheme = ucfirst($scheme); + $this->protocol = 'Protocols\\' . $scheme; + if (!class_exists($this->protocol)) { + $this->protocol = "Workerman\\Protocols\\$scheme"; + if (!class_exists($this->protocol)) { + throw new RuntimeException("class \\Protocols\\$scheme not exist"); + } + } + + if (!isset(self::BUILD_IN_TRANSPORTS[$this->transport])) { + throw new RuntimeException('Bad worker->transport ' . var_export($this->transport, true)); + } + } else if ($this->transport === 'tcp') { + $this->transport = $scheme; + } + //local socket + return self::BUILD_IN_TRANSPORTS[$this->transport] . ":" . $address; + } + + /** + * Pause accept new connections. + * + * @return void + */ + public function pauseAccept(): void + { + if (static::$globalEvent !== null && !$this->pauseAccept && $this->mainSocket !== null) { + static::$globalEvent->offReadable($this->mainSocket); + $this->pauseAccept = true; + } + } + + /** + * Resume accept new connections. + * + * @return void + */ + public function resumeAccept(): void + { + // Register a listener to be notified when server socket is ready to read. + if (static::$globalEvent !== null && ($this->pauseAccept === null || $this->pauseAccept === true) && $this->mainSocket !== null) { + if ($this->transport !== 'udp') { + static::$globalEvent->onReadable($this->mainSocket, $this->acceptTcpConnection(...)); + } else { + static::$globalEvent->onReadable($this->mainSocket, $this->acceptUdpConnection(...)); + } + $this->pauseAccept = false; + } + } + + /** + * Get socket name. + * + * @return string + */ + public function getSocketName(): string + { + return $this->socketName ? lcfirst($this->socketName) : 'none'; + } + + /** + * Run worker instance. + * + * @return void + * @throws Throwable + */ + public function run(): void + { + $this->listen(!$this->onWorkerStart); + + if (!$this->onWorkerStart) { + return; + } + + // Try to emit onWorkerStart callback. + $callback = function() { + try { + ($this->onWorkerStart)($this); + } catch (Throwable $e) { + // Avoid rapid infinite loop exit. + sleep(1); + static::stopAll(250, $e); + } finally { + if ($this->pauseAccept === null) { + $this->resumeAccept(); + } + Context::destroy(); + } + }; + + match (Worker::$eventLoopClass) { + Swoole::class, + Swow::class, + Fiber::class => Coroutine::create($callback), + + default => (new \Fiber($callback))->start(), + }; + } + + /** + * Stop current worker instance. + * + * @param bool $force + * @return void + */ + public function stop(bool $force = true): void + { + if ($this->stopping === true) { + return; + } + // Try to emit onWorkerStop callback. + if ($this->onWorkerStop) { + try { + ($this->onWorkerStop)($this); + } catch (Throwable $e) { + static::log($e); + } + } + // Remove listener for server socket. + $this->unlisten(); + // Close all connections for the worker. + if (!static::getGracefulStop()) { + foreach ($this->connections as $connection) { + if ($force || !$connection->getRecvBufferQueueSize()) { + $connection->close(); + } + } + } + // Clear callback. + $this->onMessage = $this->onClose = $this->onError = $this->onBufferDrain = $this->onBufferFull = null; + $this->stopping = true; + } + + /** + * Accept a connection. + * + * @param resource $socket + * @return void + */ + public function acceptTcpConnection(mixed $socket): void + { + // Accept a connection on server socket. + set_error_handler(static fn (...$args): bool => true); + $newSocket = stream_socket_accept($socket, 0, $remoteAddress); + restore_error_handler(); + + // Thundering herd. + if (!$newSocket) { + return; + } + + // TcpConnection. + $connection = new TcpConnection(static::$globalEvent, $newSocket, $remoteAddress); + $this->connections[$connection->id] = $connection; + $connection->worker = $this; + $connection->protocol = $this->protocol; + $connection->transport = $this->transport; + $connection->onMessage = $this->onMessage; + $connection->onClose = $this->onClose; + $connection->onError = $this->onError; + $connection->onBufferDrain = $this->onBufferDrain; + $connection->onBufferFull = $this->onBufferFull; + + // Try to emit onConnect callback. + if ($this->onConnect) { + try { + ($this->onConnect)($connection); + } catch (Throwable $e) { + static::stopAll(250, $e); + } + } + } + + /** + * For udp package. + * + * @param resource $socket + * @return void + */ + public function acceptUdpConnection(mixed $socket): void + { + set_error_handler(static fn (...$args): bool => true); + $recvBuffer = stream_socket_recvfrom($socket, UdpConnection::MAX_UDP_PACKAGE_SIZE, 0, $remoteAddress); + restore_error_handler(); + if (false === $recvBuffer || empty($remoteAddress)) { + return; + } + // UdpConnection. + $connection = new UdpConnection($socket, $remoteAddress); + $connection->protocol = $this->protocol; + $messageCallback = $this->onMessage; + if ($messageCallback) { + try { + if ($this->protocol !== null) { + $parser = $this->protocol; + if ($parser && method_exists($parser, 'input')) { + while ($recvBuffer !== '') { + $len = $parser::input($recvBuffer, $connection); + if ($len === 0) { + return; + } + $package = substr($recvBuffer, 0, $len); + $recvBuffer = substr($recvBuffer, $len); + $data = $parser::decode($package, $connection); + if ($data === false) { + continue; + } + $messageCallback($connection, $data); + } + } else { + $data = $parser::decode($recvBuffer, $connection); + // Discard bad packets. + if ($data === false) { + return; + } + $messageCallback($connection, $data); + } + } else { + $messageCallback($connection, $recvBuffer); + } + ConnectionInterface::$statistics['total_request']++; + } catch (Throwable $e) { + static::stopAll(250, $e); + } + } + } + + /** + * Check master process is alive + * + * @param int $masterPid + * @return bool + */ + protected static function checkMasterIsAlive(int $masterPid): bool + { + if (empty($masterPid)) { + return false; + } + + $masterIsAlive = posix_kill($masterPid, 0) && posix_getpid() !== $masterPid; + if (!$masterIsAlive) { + static::log("Master pid:$masterPid is not alive"); + return false; + } + + $cmdline = "/proc/$masterPid/cmdline"; + if (!is_readable($cmdline)) { + return true; + } + + $content = file_get_contents($cmdline); + if (empty($content)) { + return true; + } + + return str_contains($content, 'WorkerMan') || str_contains($content, 'php'); + } + + /** + * If worker is running. + * + * @return bool + */ + public static function isRunning(): bool + { + return Worker::$status !== Worker::STATUS_INITIAL; + } +}