repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpUnauthorizedException.php
Slim/Exception/HttpUnauthorizedException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; /** @api */ class HttpUnauthorizedException extends HttpSpecializedException { /** * @var int */ protected $code = 401; /** * @var string */ protected $message = 'Unauthorized.'; protected string $title = '401 Unauthorized'; protected string $description = 'The request requires valid user authentication.'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpSpecializedException.php
Slim/Exception/HttpSpecializedException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; use Psr\Http\Message\ServerRequestInterface; use Throwable; abstract class HttpSpecializedException extends HttpException { /** * @param ServerRequestInterface $request * @param string|null $message * @param Throwable|null $previous */ public function __construct(ServerRequestInterface $request, ?string $message = null, ?Throwable $previous = null) { if ($message !== null) { $this->message = $message; } // @phpstan-ignore-next-line parent::__construct($request, $this->message, $this->code, $previous); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Middleware/RoutingMiddleware.php
Slim/Middleware/RoutingMiddleware.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\Exception\HttpMethodNotAllowedException; use Slim\Exception\HttpNotFoundException; use Slim\Interfaces\RouteParserInterface; use Slim\Interfaces\RouteResolverInterface; use Slim\Routing\RouteContext; use Slim\Routing\RoutingResults; class RoutingMiddleware implements MiddlewareInterface { protected RouteResolverInterface $routeResolver; protected RouteParserInterface $routeParser; public function __construct(RouteResolverInterface $routeResolver, RouteParserInterface $routeParser) { $this->routeResolver = $routeResolver; $this->routeParser = $routeParser; } /** * @throws HttpNotFoundException * @throws HttpMethodNotAllowedException * @throws RuntimeException */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $request = $this->performRouting($request); return $handler->handle($request); } /** * Perform routing * * @param ServerRequestInterface $request PSR7 Server Request * * @throws HttpNotFoundException * @throws HttpMethodNotAllowedException * @throws RuntimeException */ public function performRouting(ServerRequestInterface $request): ServerRequestInterface { $request = $request->withAttribute(RouteContext::ROUTE_PARSER, $this->routeParser); $routingResults = $this->resolveRoutingResultsFromRequest($request); $routeStatus = $routingResults->getRouteStatus(); $request = $request->withAttribute(RouteContext::ROUTING_RESULTS, $routingResults); switch ($routeStatus) { case RoutingResults::FOUND: $routeArguments = $routingResults->getRouteArguments(); $routeIdentifier = $routingResults->getRouteIdentifier() ?? ''; $route = $this->routeResolver ->resolveRoute($routeIdentifier) ->prepare($routeArguments); return $request->withAttribute(RouteContext::ROUTE, $route); case RoutingResults::NOT_FOUND: throw new HttpNotFoundException($request); case RoutingResults::METHOD_NOT_ALLOWED: $exception = new HttpMethodNotAllowedException($request); $exception->setAllowedMethods($routingResults->getAllowedMethods()); throw $exception; default: throw new RuntimeException('An unexpected error occurred while performing routing.'); } } /** * Resolves the route from the given request */ protected function resolveRoutingResultsFromRequest(ServerRequestInterface $request): RoutingResults { return $this->routeResolver->computeRoutingResults( $request->getUri()->getPath(), $request->getMethod() ); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Middleware/OutputBufferingMiddleware.php
Slim/Middleware/OutputBufferingMiddleware.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Middleware; use InvalidArgumentException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Throwable; use function in_array; use function ob_end_clean; use function ob_get_clean; use function ob_start; /** @api */ class OutputBufferingMiddleware implements MiddlewareInterface { public const APPEND = 'append'; public const PREPEND = 'prepend'; protected StreamFactoryInterface $streamFactory; protected string $style; /** * @param string $style Either "append" or "prepend" */ public function __construct(StreamFactoryInterface $streamFactory, string $style = 'append') { $this->streamFactory = $streamFactory; $this->style = $style; if (!in_array($style, [static::APPEND, static::PREPEND], true)) { throw new InvalidArgumentException("Invalid style `{$style}`. Must be `append` or `prepend`"); } } /** * @throws Throwable */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { try { ob_start(); $response = $handler->handle($request); $output = ob_get_clean(); } catch (Throwable $e) { ob_end_clean(); throw $e; } if (!empty($output)) { if ($this->style === static::PREPEND) { $body = $this->streamFactory->createStream(); $body->write($output . $response->getBody()); $response = $response->withBody($body); } elseif ($this->style === static::APPEND && $response->getBody()->isWritable()) { $response->getBody()->write($output); } } return $response; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Middleware/MethodOverrideMiddleware.php
Slim/Middleware/MethodOverrideMiddleware.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use function is_array; use function strtoupper; /** @api */ class MethodOverrideMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $methodHeader = $request->getHeaderLine('X-Http-Method-Override'); if ($methodHeader) { $request = $request->withMethod($methodHeader); } elseif (strtoupper($request->getMethod()) === 'POST') { $body = $request->getParsedBody(); if (is_array($body) && !empty($body['_METHOD']) && is_string($body['_METHOD'])) { $request = $request->withMethod($body['_METHOD']); } if ($request->getBody()->eof()) { $request->getBody()->rewind(); } } return $handler->handle($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Middleware/ContentLengthMiddleware.php
Slim/Middleware/ContentLengthMiddleware.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** @api */ class ContentLengthMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = $handler->handle($request); // Add Content-Length header if not already added $size = $response->getBody()->getSize(); if ($size !== null && !$response->hasHeader('Content-Length')) { $response = $response->withHeader('Content-Length', (string) $size); } return $response; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Middleware/BodyParsingMiddleware.php
Slim/Middleware/BodyParsingMiddleware.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use function count; use function explode; use function is_array; use function is_object; use function is_string; use function json_decode; use function libxml_clear_errors; use function libxml_disable_entity_loader; use function libxml_use_internal_errors; use function parse_str; use function simplexml_load_string; use function strtolower; use function trim; use const LIBXML_VERSION; /** @api */ class BodyParsingMiddleware implements MiddlewareInterface { /** * @var callable[] */ protected array $bodyParsers; /** * @param callable[] $bodyParsers list of body parsers as an associative array of mediaType => callable */ public function __construct(array $bodyParsers = []) { $this->registerDefaultBodyParsers(); foreach ($bodyParsers as $mediaType => $parser) { $this->registerBodyParser($mediaType, $parser); } } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $parsedBody = $request->getParsedBody(); if (empty($parsedBody)) { $parsedBody = $this->parseBody($request); $request = $request->withParsedBody($parsedBody); } return $handler->handle($request); } /** * @param string $mediaType A HTTP media type (excluding content-type params). * @param callable $callable A callable that returns parsed contents for media type. */ public function registerBodyParser(string $mediaType, callable $callable): self { $this->bodyParsers[$mediaType] = $callable; return $this; } /** * @param string $mediaType A HTTP media type (excluding content-type params). */ public function hasBodyParser(string $mediaType): bool { return isset($this->bodyParsers[$mediaType]); } /** * @param string $mediaType A HTTP media type (excluding content-type params). * @throws RuntimeException */ public function getBodyParser(string $mediaType): callable { if (!isset($this->bodyParsers[$mediaType])) { throw new RuntimeException('No parser for type ' . $mediaType); } return $this->bodyParsers[$mediaType]; } protected function registerDefaultBodyParsers(): void { $this->registerBodyParser('application/json', static function ($input) { /** @var string $input */ $result = json_decode($input, true); if (!is_array($result)) { return null; } return $result; }); $this->registerBodyParser('application/x-www-form-urlencoded', static function ($input) { /** @var string $input */ parse_str($input, $data); return $data; }); $xmlCallable = static function ($input) { /** @var string $input */ $backup = self::disableXmlEntityLoader(true); $backup_errors = libxml_use_internal_errors(true); $result = simplexml_load_string($input); self::disableXmlEntityLoader($backup); libxml_clear_errors(); libxml_use_internal_errors($backup_errors); if ($result === false) { return null; } return $result; }; $this->registerBodyParser('application/xml', $xmlCallable); $this->registerBodyParser('text/xml', $xmlCallable); } /** * @return null|array<mixed>|object */ protected function parseBody(ServerRequestInterface $request) { $mediaType = $this->getMediaType($request); if ($mediaType === null) { return null; } // Check if this specific media type has a parser registered first if (!isset($this->bodyParsers[$mediaType])) { // If not, look for a media type with a structured syntax suffix (RFC 6839) $parts = explode('+', $mediaType); if (count($parts) >= 2) { $mediaType = 'application/' . $parts[count($parts) - 1]; } } if (isset($this->bodyParsers[$mediaType])) { $body = (string)$request->getBody(); $parsed = $this->bodyParsers[$mediaType]($body); if ($parsed !== null && !is_object($parsed) && !is_array($parsed)) { throw new RuntimeException( 'Request body media type parser return value must be an array, an object, or null' ); } return $parsed; } return null; } /** * @return string|null The serverRequest media type, minus content-type params */ protected function getMediaType(ServerRequestInterface $request): ?string { $contentType = $request->getHeader('Content-Type')[0] ?? null; if (is_string($contentType) && trim($contentType) !== '') { $contentTypeParts = explode(';', $contentType); return strtolower(trim($contentTypeParts[0])); } return null; } protected static function disableXmlEntityLoader(bool $disable): bool { if (LIBXML_VERSION >= 20900) { // libxml >= 2.9.0 disables entity loading by default, so it is // safe to skip the real call (deprecated in PHP 8). return true; } // @codeCoverageIgnoreStart return libxml_disable_entity_loader($disable); // @codeCoverageIgnoreEnd } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Middleware/ErrorMiddleware.php
Slim/Middleware/ErrorMiddleware.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Middleware; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use Slim\Exception\HttpException; use Slim\Handlers\ErrorHandler; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\ErrorHandlerInterface; use Throwable; use function get_class; use function is_subclass_of; /** @api */ class ErrorMiddleware implements MiddlewareInterface { protected CallableResolverInterface $callableResolver; protected ResponseFactoryInterface $responseFactory; protected bool $displayErrorDetails; protected bool $logErrors; protected bool $logErrorDetails; protected ?LoggerInterface $logger = null; /** * @var ErrorHandlerInterface[]|callable[]|string[] */ protected array $handlers = []; /** * @var ErrorHandlerInterface[]|callable[]|string[] */ protected array $subClassHandlers = []; /** * @var ErrorHandlerInterface|callable|string|null */ protected $defaultErrorHandler; public function __construct( CallableResolverInterface $callableResolver, ResponseFactoryInterface $responseFactory, bool $displayErrorDetails, bool $logErrors, bool $logErrorDetails, ?LoggerInterface $logger = null ) { $this->callableResolver = $callableResolver; $this->responseFactory = $responseFactory; $this->displayErrorDetails = $displayErrorDetails; $this->logErrors = $logErrors; $this->logErrorDetails = $logErrorDetails; $this->logger = $logger; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { try { return $handler->handle($request); } catch (Throwable $e) { return $this->handleException($request, $e); } } public function handleException(ServerRequestInterface $request, Throwable $exception): ResponseInterface { if ($exception instanceof HttpException) { $request = $exception->getRequest(); } $exceptionType = get_class($exception); $handler = $this->getErrorHandler($exceptionType); /** @var ResponseInterface */ return $handler($request, $exception, $this->displayErrorDetails, $this->logErrors, $this->logErrorDetails); } /** * Get callable to handle scenarios where an error * occurs when processing the current request. * * @param string $type Exception/Throwable name. ie: RuntimeException::class * @return callable|ErrorHandler */ public function getErrorHandler(string $type) { if (isset($this->handlers[$type])) { return $this->callableResolver->resolve($this->handlers[$type]); } if (isset($this->subClassHandlers[$type])) { return $this->callableResolver->resolve($this->subClassHandlers[$type]); } foreach ($this->subClassHandlers as $class => $handler) { if (is_subclass_of($type, $class)) { return $this->callableResolver->resolve($handler); } } return $this->getDefaultErrorHandler(); } /** * Get default error handler * * @return ErrorHandler|callable */ public function getDefaultErrorHandler() { if ($this->defaultErrorHandler === null) { $this->defaultErrorHandler = new ErrorHandler( $this->callableResolver, $this->responseFactory, $this->logger ); } return $this->callableResolver->resolve($this->defaultErrorHandler); } /** * Set callable as the default Slim application error handler. * * The callable signature MUST match the ErrorHandlerInterface * * @param string|callable|ErrorHandler $handler * @see ErrorHandlerInterface * * 1. Instance of \Psr\Http\Message\ServerRequestInterface * 2. Instance of \Throwable * 3. Boolean $displayErrorDetails * 4. Boolean $logErrors * 5. Boolean $logErrorDetails * * The callable MUST return an instance of * \Psr\Http\Message\ResponseInterface. * */ public function setDefaultErrorHandler($handler): self { $this->defaultErrorHandler = $handler; return $this; } /** * Set callable to handle scenarios where an error * occurs when processing the current request. * * The callable signature MUST match the ErrorHandlerInterface * * Pass true to $handleSubclasses to make the handler handle all subclasses of * the type as well. Pass an array of classes to make the same function handle multiple exceptions. * * @param string|string[] $typeOrTypes Exception/Throwable name. * ie: RuntimeException::class or an array of classes * ie: [HttpNotFoundException::class, HttpMethodNotAllowedException::class] * @param string|callable|ErrorHandlerInterface $handler * * @see ErrorHandlerInterface * * 1. Instance of \Psr\Http\Message\ServerRequestInterface * 2. Instance of \Throwable * 3. Boolean $displayErrorDetails * 4. Boolean $logErrors * 5. Boolean $logErrorDetails * * The callable MUST return an instance of * \Psr\Http\Message\ResponseInterface. * */ public function setErrorHandler($typeOrTypes, $handler, bool $handleSubclasses = false): self { if (is_array($typeOrTypes)) { foreach ($typeOrTypes as $type) { $this->addErrorHandler($type, $handler, $handleSubclasses); } } else { $this->addErrorHandler($typeOrTypes, $handler, $handleSubclasses); } return $this; } /** * Used internally to avoid code repetition when passing multiple exceptions to setErrorHandler(). * @param string|callable|ErrorHandlerInterface $handler */ private function addErrorHandler(string $type, $handler, bool $handleSubclasses): void { if ($handleSubclasses) { $this->subClassHandlers[$type] = $handler; } else { $this->handlers[$type] = $handler; } } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Error/AbstractErrorRenderer.php
Slim/Error/AbstractErrorRenderer.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Error; use Slim\Exception\HttpException; use Slim\Interfaces\ErrorRendererInterface; use Throwable; /** * Abstract Slim application error renderer * * It outputs the error message and diagnostic information in one of the following formats: * JSON, XML, Plain Text or HTML */ abstract class AbstractErrorRenderer implements ErrorRendererInterface { protected string $defaultErrorTitle = 'Slim Application Error'; protected string $defaultErrorDescription = 'A website error has occurred. Sorry for the temporary inconvenience.'; protected function getErrorTitle(Throwable $exception): string { if ($exception instanceof HttpException) { return $exception->getTitle(); } return $this->defaultErrorTitle; } protected function getErrorDescription(Throwable $exception): string { if ($exception instanceof HttpException) { return $exception->getDescription(); } return $this->defaultErrorDescription; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Error/Renderers/XmlErrorRenderer.php
Slim/Error/Renderers/XmlErrorRenderer.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Error\Renderers; use Slim\Error\AbstractErrorRenderer; use Throwable; use function get_class; use function sprintf; use function str_replace; /** * Default Slim application XML Error Renderer */ class XmlErrorRenderer extends AbstractErrorRenderer { public function __invoke(Throwable $exception, bool $displayErrorDetails): string { $xml = '<' . '?xml version="1.0" encoding="UTF-8" standalone="yes"?' . ">\n"; $xml .= "<error>\n <message>" . $this->createCdataSection($this->getErrorTitle($exception)) . "</message>\n"; if ($displayErrorDetails) { do { $xml .= " <exception>\n"; $xml .= ' <type>' . get_class($exception) . "</type>\n"; $xml .= ' <code>' . $exception->getCode() . "</code>\n"; $xml .= ' <message>' . $this->createCdataSection($exception->getMessage()) . "</message>\n"; $xml .= ' <file>' . $exception->getFile() . "</file>\n"; $xml .= ' <line>' . $exception->getLine() . "</line>\n"; $xml .= " </exception>\n"; } while ($exception = $exception->getPrevious()); } $xml .= '</error>'; return $xml; } /** * Returns a CDATA section with the given content. */ private function createCdataSection(string $content): string { return sprintf('<![CDATA[%s]]>', str_replace(']]>', ']]]]><![CDATA[>', $content)); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Error/Renderers/HtmlErrorRenderer.php
Slim/Error/Renderers/HtmlErrorRenderer.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Error\Renderers; use Slim\Error\AbstractErrorRenderer; use Throwable; use function get_class; use function htmlentities; use function sprintf; /** * Default Slim application HTML Error Renderer */ class HtmlErrorRenderer extends AbstractErrorRenderer { public function __invoke(Throwable $exception, bool $displayErrorDetails): string { if ($displayErrorDetails) { $html = '<p>The application could not run because of the following error:</p>'; $html .= '<h2>Details</h2>'; $html .= $this->renderExceptionFragment($exception); } else { $html = "<p>{$this->getErrorDescription($exception)}</p>"; } return $this->renderHtmlBody($this->getErrorTitle($exception), $html); } private function renderExceptionFragment(Throwable $exception): string { $html = sprintf('<div><strong>Type:</strong> %s</div>', get_class($exception)); $code = $exception->getCode(); $html .= sprintf('<div><strong>Code:</strong> %s</div>', $code); $html .= sprintf('<div><strong>Message:</strong> %s</div>', htmlentities($exception->getMessage())); $html .= sprintf('<div><strong>File:</strong> %s</div>', $exception->getFile()); $html .= sprintf('<div><strong>Line:</strong> %s</div>', $exception->getLine()); $html .= '<h2>Trace</h2>'; $html .= sprintf('<pre>%s</pre>', htmlentities($exception->getTraceAsString())); return $html; } public function renderHtmlBody(string $title = '', string $html = ''): string { return sprintf( '<!doctype html>' . '<html lang="en">' . ' <head>' . ' <meta charset="utf-8">' . ' <meta name="viewport" content="width=device-width, initial-scale=1">' . ' <title>%s</title>' . ' <style>' . ' body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif}' . ' h1{margin:0;font-size:48px;font-weight:normal;line-height:48px}' . ' strong{display:inline-block;width:65px}' . ' </style>' . ' </head>' . ' <body>' . ' <h1>%s</h1>' . ' <div>%s</div>' . ' <a href="#" onclick="window.history.go(-1)">Go Back</a>' . ' </body>' . '</html>', $title, $title, $html ); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Error/Renderers/PlainTextErrorRenderer.php
Slim/Error/Renderers/PlainTextErrorRenderer.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Error\Renderers; use Slim\Error\AbstractErrorRenderer; use Throwable; use function get_class; use function htmlentities; use function sprintf; /** * Default Slim application Plain Text Error Renderer */ class PlainTextErrorRenderer extends AbstractErrorRenderer { public function __invoke(Throwable $exception, bool $displayErrorDetails): string { $text = "{$this->getErrorTitle($exception)}\n"; if ($displayErrorDetails) { $text .= $this->formatExceptionFragment($exception); while ($exception = $exception->getPrevious()) { $text .= "\nPrevious Error:\n"; $text .= $this->formatExceptionFragment($exception); } } return $text; } private function formatExceptionFragment(Throwable $exception): string { $text = sprintf("Type: %s\n", get_class($exception)); $code = $exception->getCode(); $text .= sprintf("Code: %s\n", $code); $text .= sprintf("Message: %s\n", $exception->getMessage()); $text .= sprintf("File: %s\n", $exception->getFile()); $text .= sprintf("Line: %s\n", $exception->getLine()); $text .= sprintf('Trace: %s', $exception->getTraceAsString()); return $text; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Error/Renderers/JsonErrorRenderer.php
Slim/Error/Renderers/JsonErrorRenderer.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Error\Renderers; use Slim\Error\AbstractErrorRenderer; use Throwable; use function get_class; use function json_encode; use const JSON_PRETTY_PRINT; use const JSON_UNESCAPED_SLASHES; /** * Default Slim application JSON Error Renderer */ class JsonErrorRenderer extends AbstractErrorRenderer { public function __invoke(Throwable $exception, bool $displayErrorDetails): string { $error = ['message' => $this->getErrorTitle($exception)]; if ($displayErrorDetails) { $error['exception'] = []; do { $error['exception'][] = $this->formatExceptionFragment($exception); } while ($exception = $exception->getPrevious()); } return (string) json_encode($error, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); } /** * @return array<string|int> */ private function formatExceptionFragment(Throwable $exception): array { $code = $exception->getCode(); return [ 'type' => get_class($exception), 'code' => $code, 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), ]; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Handlers/ErrorHandler.php
Slim/Handlers/ErrorHandler.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Handlers; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LoggerInterface; use RuntimeException; use Slim\Error\Renderers\HtmlErrorRenderer; use Slim\Error\Renderers\JsonErrorRenderer; use Slim\Error\Renderers\PlainTextErrorRenderer; use Slim\Error\Renderers\XmlErrorRenderer; use Slim\Exception\HttpException; use Slim\Exception\HttpMethodNotAllowedException; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\ErrorHandlerInterface; use Slim\Interfaces\ErrorRendererInterface; use Slim\Logger; use Throwable; use function array_intersect; use function array_key_exists; use function array_keys; use function call_user_func; use function count; use function current; use function explode; use function implode; use function next; use function preg_match; /** * Default Slim application error handler * * It outputs the error message and diagnostic information in one of the following formats: * JSON, XML, Plain Text or HTML based on the Accept header. * @api */ class ErrorHandler implements ErrorHandlerInterface { protected string $defaultErrorRendererContentType = 'text/html'; /** * @var ErrorRendererInterface|string|callable */ protected $defaultErrorRenderer = HtmlErrorRenderer::class; /** * @var ErrorRendererInterface|string|callable */ protected $logErrorRenderer = PlainTextErrorRenderer::class; /** * @var array<string|callable> */ protected array $errorRenderers = [ 'application/json' => JsonErrorRenderer::class, 'application/xml' => XmlErrorRenderer::class, 'text/xml' => XmlErrorRenderer::class, 'text/html' => HtmlErrorRenderer::class, 'text/plain' => PlainTextErrorRenderer::class, ]; protected bool $displayErrorDetails = false; protected bool $logErrors; protected bool $logErrorDetails = false; protected ?string $contentType = null; protected ?string $method = null; protected ServerRequestInterface $request; protected Throwable $exception; protected int $statusCode; protected CallableResolverInterface $callableResolver; protected ResponseFactoryInterface $responseFactory; protected LoggerInterface $logger; public function __construct( CallableResolverInterface $callableResolver, ResponseFactoryInterface $responseFactory, ?LoggerInterface $logger = null ) { $this->callableResolver = $callableResolver; $this->responseFactory = $responseFactory; $this->logger = $logger ?: $this->getDefaultLogger(); } /** * Invoke error handler * * @param ServerRequestInterface $request The most recent Request object * @param Throwable $exception The caught Exception object * @param bool $displayErrorDetails Whether or not to display the error details * @param bool $logErrors Whether or not to log errors * @param bool $logErrorDetails Whether or not to log error details */ public function __invoke( ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails, bool $logErrors, bool $logErrorDetails ): ResponseInterface { $this->displayErrorDetails = $displayErrorDetails; $this->logErrors = $logErrors; $this->logErrorDetails = $logErrorDetails; $this->request = $request; $this->exception = $exception; $this->method = $request->getMethod(); $this->statusCode = $this->determineStatusCode(); if ($this->contentType === null) { $this->contentType = $this->determineContentType($request); } if ($logErrors) { $this->writeToErrorLog(); } return $this->respond(); } /** * Force the content type for all error handler responses. * * @param string|null $contentType The content type */ public function forceContentType(?string $contentType): void { $this->contentType = $contentType; } protected function determineStatusCode(): int { if ($this->method === 'OPTIONS') { return 200; } if ($this->exception instanceof HttpException) { return $this->exception->getCode(); } return 500; } /** * Determine which content type we know about is wanted using Accept header * * Note: This method is a bare-bones implementation designed specifically for * Slim's error handling requirements. Consider a fully-feature solution such * as willdurand/negotiation for any other situation. */ protected function determineContentType(ServerRequestInterface $request): ?string { $acceptHeader = $request->getHeaderLine('Accept'); $selectedContentTypes = array_intersect( explode(',', $acceptHeader), array_keys($this->errorRenderers) ); $count = count($selectedContentTypes); if ($count) { $current = current($selectedContentTypes); /** * Ensure other supported content types take precedence over text/plain * when multiple content types are provided via Accept header. */ if ($current === 'text/plain' && $count > 1) { $next = next($selectedContentTypes); if (is_string($next)) { return $next; } } // @phpstan-ignore-next-line if (is_string($current)) { return $current; } } if (preg_match('/\+(json|xml)/', $acceptHeader, $matches)) { $mediaType = 'application/' . $matches[1]; if (array_key_exists($mediaType, $this->errorRenderers)) { return $mediaType; } } return null; } /** * Determine which renderer to use based on content type * * @throws RuntimeException */ protected function determineRenderer(): callable { if ($this->contentType !== null && array_key_exists($this->contentType, $this->errorRenderers)) { $renderer = $this->errorRenderers[$this->contentType]; } else { $renderer = $this->defaultErrorRenderer; } return $this->callableResolver->resolve($renderer); } /** * Register an error renderer for a specific content-type * * @param string $contentType The content-type this renderer should be registered to * @param ErrorRendererInterface|string|callable $errorRenderer The error renderer */ public function registerErrorRenderer(string $contentType, $errorRenderer): void { $this->errorRenderers[$contentType] = $errorRenderer; } /** * Set the default error renderer * * @param string $contentType The content type of the default error renderer * @param ErrorRendererInterface|string|callable $errorRenderer The default error renderer */ public function setDefaultErrorRenderer(string $contentType, $errorRenderer): void { $this->defaultErrorRendererContentType = $contentType; $this->defaultErrorRenderer = $errorRenderer; } /** * Set the renderer for the error logger * * @param ErrorRendererInterface|string|callable $logErrorRenderer */ public function setLogErrorRenderer($logErrorRenderer): void { $this->logErrorRenderer = $logErrorRenderer; } /** * Write to the error log if $logErrors has been set to true */ protected function writeToErrorLog(): void { $renderer = $this->callableResolver->resolve($this->logErrorRenderer); /** @var string $error */ $error = $renderer($this->exception, $this->logErrorDetails); if ($this->logErrorRenderer === PlainTextErrorRenderer::class && !$this->displayErrorDetails) { $error .= "\nTips: To display error details in HTTP response "; $error .= 'set "displayErrorDetails" to true in the ErrorHandler constructor.'; } $this->logError($error); } /** * Wraps the error_log function so that this can be easily tested */ protected function logError(string $error): void { $this->logger->error($error); } /** * Returns a default logger implementation. */ protected function getDefaultLogger(): LoggerInterface { return new Logger(); } protected function respond(): ResponseInterface { $response = $this->responseFactory->createResponse($this->statusCode); if ($this->contentType !== null && array_key_exists($this->contentType, $this->errorRenderers)) { $response = $response->withHeader('Content-type', $this->contentType); } else { $response = $response->withHeader('Content-type', $this->defaultErrorRendererContentType); } if ($this->exception instanceof HttpMethodNotAllowedException) { $allowedMethods = implode(', ', $this->exception->getAllowedMethods()); $response = $response->withHeader('Allow', $allowedMethods); } $renderer = $this->determineRenderer(); $body = call_user_func($renderer, $this->exception, $this->displayErrorDetails); if ($body !== false) { /** @var string $body */ $response->getBody()->write($body); } return $response; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Handlers/Strategies/RequestResponse.php
Slim/Handlers/Strategies/RequestResponse.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Handlers\Strategies; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Slim\Interfaces\InvocationStrategyInterface; /** * Default route callback strategy with route parameters as an array of arguments. */ class RequestResponse implements InvocationStrategyInterface { /** * Invoke a route callable with request, response, and all route parameters * as an array of arguments. * * @param array<string, string> $routeArguments */ public function __invoke( callable $callable, ServerRequestInterface $request, ResponseInterface $response, array $routeArguments ): ResponseInterface { foreach ($routeArguments as $k => $v) { $request = $request->withAttribute($k, $v); } /** @var ResponseInterface */ return $callable($request, $response, $routeArguments); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Handlers/Strategies/RequestHandler.php
Slim/Handlers/Strategies/RequestHandler.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Handlers\Strategies; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Slim\Interfaces\RequestHandlerInvocationStrategyInterface; /** * PSR-15 RequestHandler invocation strategy */ class RequestHandler implements RequestHandlerInvocationStrategyInterface { protected bool $appendRouteArgumentsToRequestAttributes; public function __construct(bool $appendRouteArgumentsToRequestAttributes = false) { $this->appendRouteArgumentsToRequestAttributes = $appendRouteArgumentsToRequestAttributes; } /** * Invoke a route callable that implements RequestHandlerInterface * * @param array<string, string> $routeArguments */ public function __invoke( callable $callable, ServerRequestInterface $request, ResponseInterface $response, array $routeArguments ): ResponseInterface { if ($this->appendRouteArgumentsToRequestAttributes) { foreach ($routeArguments as $k => $v) { $request = $request->withAttribute($k, $v); } } /** @var ResponseInterface */ return $callable($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Handlers/Strategies/RequestResponseArgs.php
Slim/Handlers/Strategies/RequestResponseArgs.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Handlers\Strategies; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Slim\Interfaces\InvocationStrategyInterface; use function array_values; /** * Route callback strategy with route parameters as individual arguments. * @api */ class RequestResponseArgs implements InvocationStrategyInterface { /** * Invoke a route callable with request, response and all route parameters * as individual arguments. * * @param array<string, string> $routeArguments */ public function __invoke( callable $callable, ServerRequestInterface $request, ResponseInterface $response, array $routeArguments ): ResponseInterface { /** @var ResponseInterface */ return $callable($request, $response, ...array_values($routeArguments)); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Handlers/Strategies/RequestResponseNamedArgs.php
Slim/Handlers/Strategies/RequestResponseNamedArgs.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Handlers\Strategies; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Slim\Interfaces\InvocationStrategyInterface; use RuntimeException; /** * Route callback strategy with route parameters as individual arguments. * @api */ class RequestResponseNamedArgs implements InvocationStrategyInterface { /** * Invoke a route callable with request, response and all route parameters * as individual arguments. * * @param array<string, string> $routeArguments */ public function __invoke( callable $callable, ServerRequestInterface $request, ResponseInterface $response, array $routeArguments ): ResponseInterface { /** @var ResponseInterface */ return $callable($request, $response, ...$routeArguments); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/AppFactory.php
Slim/Factory/AppFactory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use RuntimeException; use Slim\App; use Slim\Factory\Psr17\Psr17Factory; use Slim\Factory\Psr17\Psr17FactoryProvider; use Slim\Factory\Psr17\SlimHttpPsr17Factory; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\MiddlewareDispatcherInterface; use Slim\Interfaces\Psr17FactoryProviderInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteResolverInterface; /** @api */ class AppFactory { protected static ?Psr17FactoryProviderInterface $psr17FactoryProvider = null; protected static ?ResponseFactoryInterface $responseFactory = null; protected static ?StreamFactoryInterface $streamFactory = null; protected static ?ContainerInterface $container = null; protected static ?CallableResolverInterface $callableResolver = null; protected static ?RouteCollectorInterface $routeCollector = null; protected static ?RouteResolverInterface $routeResolver = null; protected static ?MiddlewareDispatcherInterface $middlewareDispatcher = null; protected static bool $slimHttpDecoratorsAutomaticDetectionEnabled = true; /** * @template TContainerInterface of (ContainerInterface|null) * @param TContainerInterface $container * @return (TContainerInterface is ContainerInterface ? App<TContainerInterface> : App<ContainerInterface|null>) */ public static function create( ?ResponseFactoryInterface $responseFactory = null, ?ContainerInterface $container = null, ?CallableResolverInterface $callableResolver = null, ?RouteCollectorInterface $routeCollector = null, ?RouteResolverInterface $routeResolver = null, ?MiddlewareDispatcherInterface $middlewareDispatcher = null ): App { static::$responseFactory = $responseFactory ?? static::$responseFactory; return new App( self::determineResponseFactory(), $container ?? static::$container, $callableResolver ?? static::$callableResolver, $routeCollector ?? static::$routeCollector, $routeResolver ?? static::$routeResolver, $middlewareDispatcher ?? static::$middlewareDispatcher ); } /** * @template TContainerInterface of (ContainerInterface) * @param TContainerInterface $container * @return App<TContainerInterface> */ public static function createFromContainer(ContainerInterface $container): App { $responseFactory = $container->has(ResponseFactoryInterface::class) && ( $responseFactoryFromContainer = $container->get(ResponseFactoryInterface::class) ) instanceof ResponseFactoryInterface ? $responseFactoryFromContainer : self::determineResponseFactory(); $callableResolver = $container->has(CallableResolverInterface::class) && ( $callableResolverFromContainer = $container->get(CallableResolverInterface::class) ) instanceof CallableResolverInterface ? $callableResolverFromContainer : null; $routeCollector = $container->has(RouteCollectorInterface::class) && ( $routeCollectorFromContainer = $container->get(RouteCollectorInterface::class) ) instanceof RouteCollectorInterface ? $routeCollectorFromContainer : null; $routeResolver = $container->has(RouteResolverInterface::class) && ( $routeResolverFromContainer = $container->get(RouteResolverInterface::class) ) instanceof RouteResolverInterface ? $routeResolverFromContainer : null; $middlewareDispatcher = $container->has(MiddlewareDispatcherInterface::class) && ( $middlewareDispatcherFromContainer = $container->get(MiddlewareDispatcherInterface::class) ) instanceof MiddlewareDispatcherInterface ? $middlewareDispatcherFromContainer : null; return new App( $responseFactory, $container, $callableResolver, $routeCollector, $routeResolver, $middlewareDispatcher ); } /** * @throws RuntimeException */ public static function determineResponseFactory(): ResponseFactoryInterface { if (static::$responseFactory) { if (static::$streamFactory) { return static::attemptResponseFactoryDecoration(static::$responseFactory, static::$streamFactory); } return static::$responseFactory; } $psr17FactoryProvider = static::$psr17FactoryProvider ?? new Psr17FactoryProvider(); /** @var Psr17Factory $psr17factory */ foreach ($psr17FactoryProvider->getFactories() as $psr17factory) { if ($psr17factory::isResponseFactoryAvailable()) { $responseFactory = $psr17factory::getResponseFactory(); if (static::$streamFactory || $psr17factory::isStreamFactoryAvailable()) { $streamFactory = static::$streamFactory ?? $psr17factory::getStreamFactory(); return static::attemptResponseFactoryDecoration($responseFactory, $streamFactory); } return $responseFactory; } } throw new RuntimeException( "Could not detect any PSR-17 ResponseFactory implementations. " . "Please install a supported implementation in order to use `AppFactory::create()`. " . "See https://github.com/slimphp/Slim/blob/4.x/README.md for a list of supported implementations." ); } protected static function attemptResponseFactoryDecoration( ResponseFactoryInterface $responseFactory, StreamFactoryInterface $streamFactory ): ResponseFactoryInterface { if ( static::$slimHttpDecoratorsAutomaticDetectionEnabled && SlimHttpPsr17Factory::isResponseFactoryAvailable() ) { return SlimHttpPsr17Factory::createDecoratedResponseFactory($responseFactory, $streamFactory); } return $responseFactory; } public static function setPsr17FactoryProvider(Psr17FactoryProviderInterface $psr17FactoryProvider): void { static::$psr17FactoryProvider = $psr17FactoryProvider; } public static function setResponseFactory(ResponseFactoryInterface $responseFactory): void { static::$responseFactory = $responseFactory; } public static function setStreamFactory(StreamFactoryInterface $streamFactory): void { static::$streamFactory = $streamFactory; } public static function setContainer(ContainerInterface $container): void { static::$container = $container; } public static function setCallableResolver(CallableResolverInterface $callableResolver): void { static::$callableResolver = $callableResolver; } public static function setRouteCollector(RouteCollectorInterface $routeCollector): void { static::$routeCollector = $routeCollector; } public static function setRouteResolver(RouteResolverInterface $routeResolver): void { static::$routeResolver = $routeResolver; } public static function setMiddlewareDispatcher(MiddlewareDispatcherInterface $middlewareDispatcher): void { static::$middlewareDispatcher = $middlewareDispatcher; } public static function setSlimHttpDecoratorsAutomaticDetection(bool $enabled): void { static::$slimHttpDecoratorsAutomaticDetectionEnabled = $enabled; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/ServerRequestCreatorFactory.php
Slim/Factory/ServerRequestCreatorFactory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory; use RuntimeException; use Slim\Factory\Psr17\Psr17Factory; use Slim\Factory\Psr17\Psr17FactoryProvider; use Slim\Factory\Psr17\SlimHttpServerRequestCreator; use Slim\Interfaces\Psr17FactoryProviderInterface; use Slim\Interfaces\ServerRequestCreatorInterface; /** @api */ class ServerRequestCreatorFactory { protected static ?Psr17FactoryProviderInterface $psr17FactoryProvider = null; protected static ?ServerRequestCreatorInterface $serverRequestCreator = null; protected static bool $slimHttpDecoratorsAutomaticDetectionEnabled = true; public static function create(): ServerRequestCreatorInterface { return static::determineServerRequestCreator(); } /** * @throws RuntimeException */ public static function determineServerRequestCreator(): ServerRequestCreatorInterface { if (static::$serverRequestCreator) { return static::attemptServerRequestCreatorDecoration(static::$serverRequestCreator); } $psr17FactoryProvider = static::$psr17FactoryProvider ?? new Psr17FactoryProvider(); /** @var Psr17Factory $psr17Factory */ foreach ($psr17FactoryProvider->getFactories() as $psr17Factory) { if ($psr17Factory::isServerRequestCreatorAvailable()) { $serverRequestCreator = $psr17Factory::getServerRequestCreator(); return static::attemptServerRequestCreatorDecoration($serverRequestCreator); } } throw new RuntimeException( "Could not detect any ServerRequest creator implementations. " . "Please install a supported implementation in order to use `App::run()` " . "without having to pass in a `ServerRequest` object. " . "See https://github.com/slimphp/Slim/blob/4.x/README.md for a list of supported implementations." ); } protected static function attemptServerRequestCreatorDecoration( ServerRequestCreatorInterface $serverRequestCreator ): ServerRequestCreatorInterface { if ( static::$slimHttpDecoratorsAutomaticDetectionEnabled && SlimHttpServerRequestCreator::isServerRequestDecoratorAvailable() ) { return new SlimHttpServerRequestCreator($serverRequestCreator); } return $serverRequestCreator; } public static function setPsr17FactoryProvider(Psr17FactoryProviderInterface $psr17FactoryProvider): void { static::$psr17FactoryProvider = $psr17FactoryProvider; } public static function setServerRequestCreator(ServerRequestCreatorInterface $serverRequestCreator): void { self::$serverRequestCreator = $serverRequestCreator; } public static function setSlimHttpDecoratorsAutomaticDetection(bool $enabled): void { static::$slimHttpDecoratorsAutomaticDetectionEnabled = $enabled; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/SlimPsr17Factory.php
Slim/Factory/Psr17/SlimPsr17Factory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; class SlimPsr17Factory extends Psr17Factory { protected static string $responseFactoryClass = 'Slim\Psr7\Factory\ResponseFactory'; protected static string $streamFactoryClass = 'Slim\Psr7\Factory\StreamFactory'; protected static string $serverRequestCreatorClass = 'Slim\Psr7\Factory\ServerRequestFactory'; protected static string $serverRequestCreatorMethod = 'createFromGlobals'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/SlimHttpServerRequestCreator.php
Slim/Factory/Psr17/SlimHttpServerRequestCreator.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; use Psr\Http\Message\ServerRequestInterface; use RuntimeException; use Slim\Interfaces\ServerRequestCreatorInterface; use function class_exists; class SlimHttpServerRequestCreator implements ServerRequestCreatorInterface { protected ServerRequestCreatorInterface $serverRequestCreator; protected static string $serverRequestDecoratorClass = 'Slim\Http\ServerRequest'; public function __construct(ServerRequestCreatorInterface $serverRequestCreator) { $this->serverRequestCreator = $serverRequestCreator; } /** * {@inheritdoc} */ public function createServerRequestFromGlobals(): ServerRequestInterface { if (!static::isServerRequestDecoratorAvailable()) { throw new RuntimeException('The Slim-Http ServerRequest decorator is not available.'); } $request = $this->serverRequestCreator->createServerRequestFromGlobals(); if ( !(( $decoratedServerRequest = new static::$serverRequestDecoratorClass($request) ) instanceof ServerRequestInterface) ) { throw new RuntimeException(get_called_class() . ' could not instantiate a decorated server request.'); } return $decoratedServerRequest; } public static function isServerRequestDecoratorAvailable(): bool { return class_exists(static::$serverRequestDecoratorClass); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/ServerRequestCreator.php
Slim/Factory/Psr17/ServerRequestCreator.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; use Closure; use Psr\Http\Message\ServerRequestInterface; use Slim\Interfaces\ServerRequestCreatorInterface; class ServerRequestCreator implements ServerRequestCreatorInterface { /** * @var object|string */ protected $serverRequestCreator; protected string $serverRequestCreatorMethod; /** * @param object|string $serverRequestCreator */ public function __construct($serverRequestCreator, string $serverRequestCreatorMethod) { $this->serverRequestCreator = $serverRequestCreator; $this->serverRequestCreatorMethod = $serverRequestCreatorMethod; } /** * {@inheritdoc} */ public function createServerRequestFromGlobals(): ServerRequestInterface { /** @var callable $callable */ $callable = [$this->serverRequestCreator, $this->serverRequestCreatorMethod]; /** @var ServerRequestInterface */ return (Closure::fromCallable($callable))(); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/NyholmPsr17Factory.php
Slim/Factory/Psr17/NyholmPsr17Factory.php
<?php declare(strict_types=1); namespace Slim\Factory\Psr17; use Slim\Interfaces\ServerRequestCreatorInterface; class NyholmPsr17Factory extends Psr17Factory { protected static string $responseFactoryClass = 'Nyholm\Psr7\Factory\Psr17Factory'; protected static string $streamFactoryClass = 'Nyholm\Psr7\Factory\Psr17Factory'; protected static string $serverRequestCreatorClass = 'Nyholm\Psr7Server\ServerRequestCreator'; protected static string $serverRequestCreatorMethod = 'fromGlobals'; /** * {@inheritdoc} */ public static function getServerRequestCreator(): ServerRequestCreatorInterface { /* * Nyholm Psr17Factory implements all factories in one unified * factory which implements all of the PSR-17 factory interfaces */ $psr17Factory = new static::$responseFactoryClass(); $serverRequestCreator = new static::$serverRequestCreatorClass( $psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory ); return new ServerRequestCreator($serverRequestCreator, static::$serverRequestCreatorMethod); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/Psr17Factory.php
Slim/Factory/Psr17/Psr17Factory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use RuntimeException; use Slim\Interfaces\Psr17FactoryInterface; use Slim\Interfaces\ServerRequestCreatorInterface; use function class_exists; use function get_called_class; abstract class Psr17Factory implements Psr17FactoryInterface { protected static string $responseFactoryClass; protected static string $streamFactoryClass; protected static string $serverRequestCreatorClass; protected static string $serverRequestCreatorMethod; /** * {@inheritdoc} */ public static function getResponseFactory(): ResponseFactoryInterface { if ( !static::isResponseFactoryAvailable() || !(($responseFactory = new static::$responseFactoryClass()) instanceof ResponseFactoryInterface) ) { throw new RuntimeException(get_called_class() . ' could not instantiate a response factory.'); } return $responseFactory; } /** * {@inheritdoc} */ public static function getStreamFactory(): StreamFactoryInterface { if ( !static::isStreamFactoryAvailable() || !(($streamFactory = new static::$streamFactoryClass()) instanceof StreamFactoryInterface) ) { throw new RuntimeException(get_called_class() . ' could not instantiate a stream factory.'); } return $streamFactory; } /** * {@inheritdoc} */ public static function getServerRequestCreator(): ServerRequestCreatorInterface { if (!static::isServerRequestCreatorAvailable()) { throw new RuntimeException(get_called_class() . ' could not instantiate a server request creator.'); } return new ServerRequestCreator(static::$serverRequestCreatorClass, static::$serverRequestCreatorMethod); } /** * {@inheritdoc} */ public static function isResponseFactoryAvailable(): bool { return static::$responseFactoryClass && class_exists(static::$responseFactoryClass); } /** * {@inheritdoc} */ public static function isStreamFactoryAvailable(): bool { return static::$streamFactoryClass && class_exists(static::$streamFactoryClass); } /** * {@inheritdoc} */ public static function isServerRequestCreatorAvailable(): bool { return ( static::$serverRequestCreatorClass && static::$serverRequestCreatorMethod && class_exists(static::$serverRequestCreatorClass) ); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/Psr17FactoryProvider.php
Slim/Factory/Psr17/Psr17FactoryProvider.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; use Slim\Interfaces\Psr17FactoryProviderInterface; use function array_unshift; class Psr17FactoryProvider implements Psr17FactoryProviderInterface { /** * @var string[] */ protected static array $factories = [ SlimPsr17Factory::class, HttpSoftPsr17Factory::class, NyholmPsr17Factory::class, LaminasDiactorosPsr17Factory::class, GuzzlePsr17Factory::class, ]; /** * {@inheritdoc} */ public static function getFactories(): array { return static::$factories; } /** * {@inheritdoc} */ public static function setFactories(array $factories): void { static::$factories = $factories; } /** * {@inheritdoc} */ public static function addFactory(string $factory): void { array_unshift(static::$factories, $factory); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/GuzzlePsr17Factory.php
Slim/Factory/Psr17/GuzzlePsr17Factory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; class GuzzlePsr17Factory extends Psr17Factory { protected static string $responseFactoryClass = 'GuzzleHttp\Psr7\HttpFactory'; protected static string $streamFactoryClass = 'GuzzleHttp\Psr7\HttpFactory'; protected static string $serverRequestCreatorClass = 'GuzzleHttp\Psr7\ServerRequest'; protected static string $serverRequestCreatorMethod = 'fromGlobals'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/HttpSoftPsr17Factory.php
Slim/Factory/Psr17/HttpSoftPsr17Factory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; class HttpSoftPsr17Factory extends Psr17Factory { protected static string $responseFactoryClass = 'HttpSoft\Message\ResponseFactory'; protected static string $streamFactoryClass = 'HttpSoft\Message\StreamFactory'; protected static string $serverRequestCreatorClass = 'HttpSoft\ServerRequest\ServerRequestCreator'; protected static string $serverRequestCreatorMethod = 'createFromGlobals'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/SlimHttpPsr17Factory.php
Slim/Factory/Psr17/SlimHttpPsr17Factory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use RuntimeException; class SlimHttpPsr17Factory extends Psr17Factory { protected static string $responseFactoryClass = 'Slim\Http\Factory\DecoratedResponseFactory'; /** * @throws RuntimeException when the factory could not be instantiated */ public static function createDecoratedResponseFactory( ResponseFactoryInterface $responseFactory, StreamFactoryInterface $streamFactory ): ResponseFactoryInterface { if ( !(( $decoratedResponseFactory = new static::$responseFactoryClass($responseFactory, $streamFactory) ) instanceof ResponseFactoryInterface ) ) { throw new RuntimeException(get_called_class() . ' could not instantiate a decorated response factory.'); } return $decoratedResponseFactory; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Factory/Psr17/LaminasDiactorosPsr17Factory.php
Slim/Factory/Psr17/LaminasDiactorosPsr17Factory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Factory\Psr17; class LaminasDiactorosPsr17Factory extends Psr17Factory { protected static string $responseFactoryClass = 'Laminas\Diactoros\ResponseFactory'; protected static string $streamFactoryClass = 'Laminas\Diactoros\StreamFactory'; protected static string $serverRequestCreatorClass = 'Laminas\Diactoros\ServerRequestFactory'; protected static string $serverRequestCreatorMethod = 'fromGlobals'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/.phpstorm.meta.php
.phpstorm.meta.php
<?php namespace PHPSTORM_META { registerArgumentsSet("date_units", "millenania", "millennium", "century", "centuries", "decade", "decades", "year", "years", "y", "yr", "yrs", "quarter", "quarters", "month", "months", "mo", "mos", "week", "weeks", "w", "day", "days", "d", "hour", "hours", "h", "minute", "minutes", "m", "second", "seconds", "s", "millisecond", "milliseconds", "milli", "ms", "microsecond", "microseconds", "micro", "µs"); expectedArguments(\Carbon\Traits\Units::add(), 0, argumentsSet("date_units")); expectedArguments(\Carbon\Traits\Units::add(), 1, argumentsSet("date_units")); expectedArguments(\Carbon\CarbonInterface::add(), 0, argumentsSet("date_units")); expectedArguments(\Carbon\CarbonInterface::add(), 1, argumentsSet("date_units")); expectedArguments(\Carbon\CarbonInterface::getTimeFormatByPrecision(), 0, "minute", "second", "m", "millisecond", "µ", "microsecond", "minutes", "seconds", "ms", "milliseconds", "µs", "microseconds"); }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/build.php
build.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ chdir(__DIR__); $currentBranch = 'master'; if (preg_match('/On branch ([^\n]+)\n/', shell_exec('git status'), $match)) { $currentBranch = $match[1]; } shell_exec('git fetch --all --tags --prune'); $remotes = explode("\n", trim(shell_exec('git remote'))); $tagsCommand = \count($remotes) ? 'git ls-remote --tags '.(\in_array('upstream', $remotes, true) ? 'upstream' : (\in_array('origin', $remotes, true) ? 'origin' : $remotes[0])) : 'git tag'; $tags = array_map(function ($ref) { $ref = explode('refs/tags/', $ref); return $ref[1] ?? $ref[0]; }, array_filter(explode("\n", trim(shell_exec($tagsCommand))), function ($ref) { return substr($ref, -3) !== '^{}'; })); usort($tags, 'version_compare'); $tag = isset($argv[1]) && !\in_array($argv[1], ['last', 'latest']) ? $argv[1] : end($tags); if (strtolower($tag) !== 'all') { if (!\in_array($tag, $tags, true)) { echo "Tag must be one of remote tags available:\n"; foreach ($tags as $_tag) { echo " - $_tag\n"; } echo "\"$tag\" does not match.\n"; exit(1); } $tags = [$tag]; } function getPhpLevel($tag) { if (version_compare($tag, '2.0.0-dev', '<')) { return '5.3.9'; } if (version_compare($tag, '3.0.0-dev', '<')) { return '7.1.8'; } return '8.1.0'; } foreach ($tags as $tag) { $archive = "Carbon-$tag.zip"; if (isset($argv[2]) && $argv[2] === 'missing' && file_exists($archive)) { continue; } $branch = "build-$tag"; shell_exec('git stash'); shell_exec("git branch -d $branch"); shell_exec("git checkout tags/$tag -b $branch"); $phpVersion = getPhpLevel($tag); shell_exec("composer config platform.php $phpVersion"); shell_exec('composer remove friendsofphp/php-cs-fixer --dev'); shell_exec('composer remove kylekatarnls/multi-tester --dev'); shell_exec('composer remove phpmd/phpmd --dev'); shell_exec('composer remove phpstan/phpstan --dev'); shell_exec('composer remove phpunit/phpunit --dev'); shell_exec('composer remove squizlabs/php_codesniffer --dev'); shell_exec('composer update --no-interaction --no-dev --optimize-autoloader'); $zip = new ZipArchive(); $zip->open($archive, ZipArchive::CREATE | ZipArchive::OVERWRITE); foreach (['src', 'vendor', 'Carbon', 'lazy'] as $directory) { if (is_dir($directory)) { $directory = realpath($directory); $base = \dirname($directory); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($directory), RecursiveIteratorIterator::LEAVES_ONLY, ); foreach ($files as $name => $file) { if (!$file->isDir()) { $filePath = $file->getRealPath(); $zip->addFile($filePath, substr($filePath, \strlen($base) + 1)); } } } } $autoload = 'autoload.php'; file_put_contents($autoload, "<?php\n\n/**\n * @version $tag\n */\n\nrequire __DIR__.'/vendor/autoload.php';\n"); $zip->addFile($autoload, $autoload); $zip->close(); unlink($autoload); shell_exec('git checkout .'); shell_exec("git checkout $currentBranch"); shell_exec("git branch -d $branch"); shell_exec('git stash pop'); shell_exec('composer config platform.php 8.1.0'); shell_exec('composer update --no-interaction'); } exit(0);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/phpdoc.php
phpdoc.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Factory; use Carbon\FactoryImmutable; $tags = [ 'property', 'property-read', 'property-write', PHP_EOL, 'mode', ['call', 'is'], ['call', 'isDayOfWeek'], ['call', 'isSameUnit'], ['call', 'setUnit'], ['call', 'addUnit'], ['call', 'addUTCUnit'], ['call', 'roundUnit'], ['call', 'diffForHumans'], ]; $nativeMethods = [ 'getOffset' => 'int', 'getTimestamp' => 'int', ]; $noInterface = [ 'setMicrosecond', ]; $modes = []; $autoDocLines = []; $carbon = __DIR__.'/src/Carbon/Carbon.php'; $immutable = __DIR__.'/src/Carbon/CarbonImmutable.php'; $interface = __DIR__.'/src/Carbon/CarbonInterface.php'; $phpLevel = 7.1; file_put_contents($interface, preg_replace('/(\/\/ <methods[\s\S]*>)([\s\S]+)(<\/methods>)/mU', "$1\n\n // $3", file_get_contents($interface), 1)); require_once __DIR__.'/vendor/autoload.php'; $trait = __DIR__.'/src/Carbon/Traits/Date.php'; $code = ''; $overrideTyping = [ $carbon => [ // 'createFromImmutable' => ['static Carbon', 'DateTimeImmutable $dateTime', 'Create a new Carbon object from an immutable date.'], // 'createFromFormat' => ['static static', 'string $format, string $time, DateTimeZone|string|false|null $timezone = null', 'Parse a string into a new Carbon object according to the specified format.'], // '__set_state' => ['static static', 'array $array', 'https://php.net/manual/en/datetime.set-state.php'], ], $immutable => [ // 'createFromMutable' => ['static CarbonImmutable', 'DateTime $dateTime', 'Create a new CarbonImmutable object from an immutable date.'], // 'createFromFormat' => ['static static', 'string $format, string $time, DateTimeZone|string|false|null $timezone = null', 'Parse a string into a new CarbonImmutable object according to the specified format.'], // '__set_state' => ['static static', 'array $array', 'https://php.net/manual/en/datetime.set-state.php'], ], ]; foreach (glob(__DIR__.'/src/Carbon/Traits/*.php') as $file) { $code .= file_get_contents($file); } function unitName($unit) { return match ($unit) { 'milli' => 'millisecond', 'micro' => 'microsecond', default => $unit, }; } function pluralize($word) { if (preg_match('/(millenni)um$/i', $word)) { return preg_replace('/(millenni)um$/i', '$1a', $word); } return preg_replace('/(centur)y$/i', '$1ie', $word).'s'; } function dumpValue($value) { if ($value === null) { return 'null'; } if ($value === CarbonInterface::TRANSLATE_ALL) { return 'CarbonInterface::TRANSLATE_ALL'; } $value = preg_replace('/^array\s*\(\s*\)$/', '[]', var_export($value, true)); $value = preg_replace('/^array\s*\(([\s\S]+)\)$/', '[$1]', $value); return $value; } function cleanClassName($name) { if ($name === 'CarbonInterval') { throw new \Exception('stop'); } if (preg_match('/^[A-Z]/', $name)) { $name = "\\$name"; } if ($name === '\\Symfony\\Contracts\\Translation\\TranslatorInterface') { return 'TranslatorInterface'; } return preg_replace('/^\\\\(Date(?:Time(?:Immutable|Interface|Zone)?|Interval)|[a-z]*Exception|Closure)$/i', '$1', preg_replace('/^\\\\Carbon\\\\/', '', $name)); } function dumpType(ReflectionType $type, bool $deep = true, bool $allowsNull = false): string { if ($type instanceof ReflectionUnionType) { return ($deep ? '(' : '').implode('|', array_map( dumpType(...), $type->getTypes(), )).($deep ? ')' : ''); } if ($type instanceof ReflectionIntersectionType) { return ($deep ? '(' : '').implode('&', array_map( dumpType(...), $type->getTypes(), )).($deep ? ')' : ''); } $name = cleanClassName($type instanceof ReflectionNamedType ? $type->getName() : (string) $type); $nullable = $allowsNull && $name !== 'mixed'; return (!$deep && $nullable ? '?' : ''). $name. ($deep && $nullable ? '|null' : ''); } function dumpParameter(string $method, ReflectionParameter $parameter): string { global $defaultValues; $name = $parameter->getName(); $output = '$'.$name; if ($parameter->isVariadic()) { $output = "...$output"; } if ($parameter->hasType()) { $output = dumpType($parameter->getType(), false, $parameter->allowsNull())." $output"; } if (isset($defaultValues[$method])) { if (isset($defaultValues[$method][$name])) { $output .= ' = '.dumpValue($defaultValues[$method][$name]); } return $output; } if ($parameter->isDefaultValueAvailable()) { $output .= ' = '.dumpValue($parameter->getDefaultValue()); } return $output; } $deprecated = []; foreach ($tags as $tag) { if (\is_array($tag)) { [$tag, $pattern] = $tag; } $pattern ??= '\S+'; if ($tag === PHP_EOL) { $autoDocLines[] = ''; continue; } $unitOfUnit = []; preg_match_all('/\/\/ @'.$tag.'\s+(?<type>'.$pattern.')(?:\s+\$(?<name>\S+)(?:[^\S\n](?<description>.*))?\n|(?:[^\S\n](?<description2>.*))?\n(?<comments>(?:[ \t]+\/\/[^\n]*\n)*)[^\']*\'(?<name2>[^\']+)\')/', $code, $oneLine, PREG_SET_ORDER); preg_match_all('/\/\* *@'.$tag.'\s+(?<type>'.$pattern.') *\*\/[^\']*\'(?<name2>[^\']+)\'/', $code, $multiLine, PREG_SET_ORDER); foreach ([...$oneLine, ...$multiLine] as $match) { $vars = (object) $match; $deprecation = null; if (isset($vars->comments) && preg_match( '`^[ \t]+(//|/*|#)[ \t]*@deprecated(?:\s(?<deprecation>[\s\S]*))?$`', $vars->comments, $comments )) { ['deprecation' => $deprecation] = $comments; $deprecation = preg_replace('/^\s*(\/\/|#|\*) {0,3}/m', '', trim($deprecation)); if (preg_match('/^(?:[a-z]+:[^\n]+\n)+$/', "$deprecation\n")) { $data = []; foreach (explode("\n", $deprecation) as $line) { [$name, $value] = array_map('trim', explode(':', $line, 2)); $data[$name] = $value; } $deprecation = $data; } else { $deprecation = ['reason' => $deprecation]; } } $vars->name = ($vars->name ?? null) ?: ($vars->name2 ?? ''); $vars->description = ($vars->description ?? null) ?: ($vars->description2 ?? ''); if ($tag === 'mode') { $modes[$vars->type] ??= []; $modes[$vars->type][] = $vars->name; continue; } if ($tag === 'call') { switch ($vars->type) { case 'diffForHumans': foreach ($modes[$vars->type] as $mode) { $autoDocLines[] = [ '@method', 'string', "$mode{$vars->name}DiffForHumans(DateTimeInterface \$other = null, int \$parts = 1)", "Get the difference ($mode format, '{$vars->name}' mode) in a human readable format in the current locale. (\$other and \$parts parameters can be swapped.)", ]; } break; case 'isDayOfWeek': $autoDocLines[] = [ '@method', 'bool', 'is'.ucFirst($vars->name).'()', 'Checks if the instance day is '.unitName(strtolower($vars->name)).'.', ]; break; case 'is': $autoDocLines[] = [ '@method', 'bool', 'is'.ucFirst($vars->name).'()', $vars->description, ]; break; case 'isSameUnit': $unit = $vars->name; $unitName = unitName($unit); $method = 'isSame'.ucFirst($unit); if (!method_exists(Carbon::class, $method)) { $autoDocLines[] = [ '@method', 'bool', $method.'(DateTimeInterface|string $date)', "Checks if the given date is in the same $unitName as the instance. If null passed, compare to now (with the same timezone).", ]; } $autoDocLines[] = [ '@method', 'bool', 'isCurrent'.ucFirst($unit).'()', "Checks if the instance is in the same $unitName as the current moment.", ]; $autoDocLines[] = [ '@method', 'bool', 'isNext'.ucFirst($unit).'()', "Checks if the instance is in the same $unitName as the current moment next $unitName.", ]; $autoDocLines[] = [ '@method', 'bool', 'isLast'.ucFirst($unit).'()', "Checks if the instance is in the same $unitName as the current moment last $unitName.", ]; break; case 'setUnit': $unit = $vars->name; $unitName = unitName($unit); $plUnit = pluralize($unit); $enums = $unitName === 'month' ? 'Month|' : ''; $autoDocLines[] = [ '@method', 'self', "$plUnit({$enums}int \$value)", "Set current instance $unitName to the given value.", ]; $autoDocLines[] = [ '@method', 'self', "$unit({$enums}int \$value)", "Set current instance $unitName to the given value.", ]; $autoDocLines[] = [ '@method', 'self', 'set'.ucfirst($plUnit)."({$enums}int \$value)", "Set current instance $unitName to the given value.", ]; $autoDocLines[] = [ '@method', 'self', 'set'.ucfirst($unit)."({$enums}int \$value)", "Set current instance $unitName to the given value.", ]; break; case 'addUnit': $unit = $vars->name; $unitName = unitName($unit); $plUnit = pluralize($unit); $plUnitName = pluralize($unitName); $autoDocLines[] = [ '@method', 'self', 'add'.ucFirst($plUnit).'(int|float $value = 1)', "Add $plUnitName (the \$value count passed in) to the instance (using date interval).", ]; $autoDocLines[] = [ '@method', 'self', 'add'.ucFirst($unit).'()', "Add one $unitName to the instance (using date interval).", ]; $autoDocLines[] = [ '@method', 'self', 'sub'.ucFirst($plUnit).'(int|float $value = 1)', "Sub $plUnitName (the \$value count passed in) to the instance (using date interval).", ]; $autoDocLines[] = [ '@method', 'self', 'sub'.ucFirst($unit).'()', "Sub one $unitName to the instance (using date interval).", ]; if (\in_array($unit, [ 'month', 'quarter', 'year', 'decade', 'century', 'millennium', ])) { $autoDocLines[] = [ '@method', 'self', 'add'.ucFirst($plUnit).'WithOverflow(int|float $value = 1)', "Add $plUnitName (the \$value count passed in) to the instance (using date interval) with overflow explicitly allowed.", ]; $autoDocLines[] = [ '@method', 'self', 'add'.ucFirst($unit).'WithOverflow()', "Add one $unitName to the instance (using date interval) with overflow explicitly allowed.", ]; $autoDocLines[] = [ '@method', 'self', 'sub'.ucFirst($plUnit).'WithOverflow(int|float $value = 1)', "Sub $plUnitName (the \$value count passed in) to the instance (using date interval) with overflow explicitly allowed.", ]; $autoDocLines[] = [ '@method', 'self', 'sub'.ucFirst($unit).'WithOverflow()', "Sub one $unitName to the instance (using date interval) with overflow explicitly allowed.", ]; foreach (['WithoutOverflow', 'WithNoOverflow', 'NoOverflow'] as $alias) { $autoDocLines[] = [ '@method', 'self', 'add'.ucFirst($plUnit)."$alias(int|float \$value = 1)", "Add $plUnitName (the \$value count passed in) to the instance (using date interval) with overflow explicitly forbidden.", ]; $autoDocLines[] = [ '@method', 'self', 'add'.ucFirst($unit)."$alias()", "Add one $unitName to the instance (using date interval) with overflow explicitly forbidden.", ]; $autoDocLines[] = [ '@method', 'self', 'sub'.ucFirst($plUnit)."$alias(int|float \$value = 1)", "Sub $plUnitName (the \$value count passed in) to the instance (using date interval) with overflow explicitly forbidden.", ]; $autoDocLines[] = [ '@method', 'self', 'sub'.ucFirst($unit)."$alias()", "Sub one $unitName to the instance (using date interval) with overflow explicitly forbidden.", ]; } break; } break; case 'addUTCUnit': $unit = $vars->name; $unitName = unitName($unit); $plUnit = pluralize($unit); $plUnitName = pluralize($unitName); $autoDocLines[] = [ '@method', 'self', 'addUTC'.ucFirst($plUnit).'(int|float $value = 1)', "Add $plUnitName (the \$value count passed in) to the instance (using timestamp).", ]; $autoDocLines[] = [ '@method', 'self', 'addUTC'.ucFirst($unit).'()', "Add one $unitName to the instance (using timestamp).", ]; $autoDocLines[] = [ '@method', 'self', 'subUTC'.ucFirst($plUnit).'(int|float $value = 1)', "Sub $plUnitName (the \$value count passed in) to the instance (using timestamp).", ]; $autoDocLines[] = [ '@method', 'self', 'subUTC'.ucFirst($unit).'()', "Sub one $unitName to the instance (using timestamp).", ]; $autoDocLines[] = [ '@method', 'CarbonPeriod', $plUnit.'Until($endDate = null, int|float $factor = 1)', "Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each $unitName or every X $plUnitName if a factor is given.", ]; $autoDocLines[] = [ '@method', 'float', 'diffInUTC'.ucFirst($plUnit).'(DateTimeInterface|string|null $date, bool $absolute = false)', "Convert current and given date in UTC timezone and return a floating number of $plUnitName.", ]; break; case 'roundUnit': $unit = $vars->name; $unitName = unitName($unit); $plUnit = pluralize($unit); $autoDocLines[] = [ '@method', 'self', 'round'.ucFirst($unit).'(float $precision = 1, string $function = "round")', "Round the current instance $unitName with given precision using the given function.", ]; $autoDocLines[] = [ '@method', 'self', 'round'.ucFirst($plUnit).'(float $precision = 1, string $function = "round")', "Round the current instance $unitName with given precision using the given function.", ]; $autoDocLines[] = [ '@method', 'self', 'floor'.ucFirst($unit).'(float $precision = 1)', "Truncate the current instance $unitName with given precision.", ]; $autoDocLines[] = [ '@method', 'self', 'floor'.ucFirst($plUnit).'(float $precision = 1)', "Truncate the current instance $unitName with given precision.", ]; $autoDocLines[] = [ '@method', 'self', 'ceil'.ucFirst($unit).'(float $precision = 1)', "Ceil the current instance $unitName with given precision.", ]; $autoDocLines[] = [ '@method', 'self', 'ceil'.ucFirst($plUnit).'(float $precision = 1)', "Ceil the current instance $unitName with given precision.", ]; break; } continue; } $description = trim($vars->description); $variable = $vars->name; if (str_starts_with($description, '$')) { [$variable, $description] = explode(' ', $description, 2); $variable = ltrim($variable, '$'); $description = ltrim($description); } if ($deprecation !== null) { $deprecated[$tag] = $deprecated[$tag] ?? []; $deprecated[$tag][] = [ 'deprecation' => $deprecation, 'type' => $vars->type, 'variable' => $variable, 'description' => $description ?: '', ]; continue; } if ( \in_array($tag, ['property', 'property-read'], true) && preg_match('/^[a-z]{2,}(?<operator>In|Of)[A-Z][a-z]+$/', $vars->name, $match) ) { $unitOfUnit[$vars->name] = [ '@'.($match['operator'] === 'Of' ? 'property' : 'property-read'), $vars->type, '$'.$variable, $description ?: '', ]; continue; } $autoDocLines[] = [ '@'.$tag, $vars->type, '$'.$variable, $description ?: '', ]; } if ($tag === 'property') { $units = ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'quarters', 'years', 'decades', 'centuries', 'millennia']; foreach ($units as $small) { array_shift($units); foreach ($units as $big) { $singularSmall = Carbon::singularUnit($small); $singularBig = Carbon::singularUnit($big); $name = $singularSmall.'Of'.ucfirst($singularBig); $unitOfUnit[$name] ??= [ '@property', 'int', '$'.$name, 'The value of the '.$singularSmall.' starting from the beginning of the current '.$singularBig, ]; } } ksort($unitOfUnit); array_push($autoDocLines, ...array_values($unitOfUnit)); } if ($tag === 'property-read') { $units = ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'quarters', 'years', 'decades', 'centuries', 'millennia']; foreach ($units as $small) { array_shift($units); foreach ($units as $big) { $singularSmall = Carbon::singularUnit($small); $singularBig = Carbon::singularUnit($big); $name = $small.'In'.ucfirst($singularBig); $unitOfUnit[$name] ??= [ '@property-read', 'int', '$'.$name, 'The number of '.$small.' contained in the current '.$singularBig, ]; } } ksort($unitOfUnit); array_push($autoDocLines, ...array_values($unitOfUnit)); } } $units = ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'quarters', 'years', 'decades', 'centuries', 'millennia']; $unitOfUnit = [ 'dayOfYear' => false, 'weeksInYear' => false, ]; foreach ($units as $small) { array_shift($units); foreach ($units as $big) { $singularSmall = Carbon::singularUnit($small); $singularBig = Carbon::singularUnit($big); $name = $singularSmall.'Of'.ucfirst($singularBig); $unitOfUnit[$name] ??= [ '@method', 'int|static', $name.'(?int $'.$singularSmall.' = null)', 'Return the value of the '.$singularSmall.' starting from the beginning of the current '.$singularBig.' when called with no parameters, change the current '.$singularSmall.' when called with an integer value', ]; $name = $small.'In'.ucfirst($singularBig); $unitOfUnit[$name] ??= [ '@method', 'int', $name.'()', 'Return the number of '.$small.' contained in the current '.$singularBig, ]; } } ksort($unitOfUnit); array_push($autoDocLines, ...array_values(array_filter($unitOfUnit))); $propertyTemplate = ' /** * %description% * * @var %type% * * @deprecated %line1% * %line2% */ public $%variable%; '; $lineGlue = preg_replace('/^[\s\S]*%line1%([\s\S]*)%line2%[\s\S]*$/', '$1', $propertyTemplate); $propertyTemplate = preg_replace('/(%line1%[\s\S]*%line2%)/', '%deprecation%', $propertyTemplate); function compileDoc($autoDocLines, $file) { global $noInterface; $class = 'CarbonInterface'; if (preg_match('`[\\\\/](Carbon\w*)\.php$`', $file, $match)) { $class = $match[1]; } $autoDoc = ''; $columnsMaxLengths = []; foreach ($autoDocLines as &$editableLine) { if (\is_array($editableLine)) { [$method] = explode('(', $editableLine[2] ?? ''); if (\in_array($method, $noInterface)) { continue; } if (($editableLine[1] ?? '') === 'self') { $editableLine[1] = $class === 'Carbon' ? '$this' : $class; } foreach ($editableLine as $column => $text) { $length = \strlen($text); $max = $columnsMaxLengths[$column] ?? 0; if ($length > $max) { $columnsMaxLengths[$column] = $length; } } } } foreach ($autoDocLines as $line) { $autoDoc .= "\n *"; if (\is_string($line)) { if (!empty($line)) { $autoDoc .= " $line"; } continue; } $computedLine = ' '; foreach ($line as $column => $text) { $computedLine .= str_pad($text, $columnsMaxLengths[$column] + 1, ' ', STR_PAD_RIGHT); } $autoDoc .= rtrim($computedLine); } return $autoDoc; } $files = new stdClass(); foreach ([$trait, $carbon, $immutable, $interface] as $file) { $content = file_get_contents($file); $files->$file = preg_replace_callback('/(<autodoc[\s\S]*>)([\s\S]+)(<\/autodoc>)/mU', function ($matches) use ($file, $autoDocLines, $overrideTyping) { foreach (($overrideTyping[$file] ?? []) as $method => $line) { $line[1] = $method.'('.$line[1].')'; array_unshift($line, '@method'); $autoDocLines[] = $line; } $autoDoc = compileDoc($autoDocLines, $file); return $matches[1]."\n *$autoDoc\n *\n * ".$matches[3]; }, $content, 1); } $staticMethods = []; $staticImmutableMethods = []; $methods = ''; $carbonMethods = get_class_methods(Carbon::class); sort($carbonMethods); function getMethodReturnType(ReflectionMethod $method): string { $type = $method->getReturnType(); $type = $type ? dumpType($type, false, $type->allowsNull()) : null; return $type ? ': '.$type : ''; } foreach ($carbonMethods as $method) { if (!method_exists(CarbonImmutable::class, $method) || method_exists(DateTimeInterface::class, $method) || \in_array($method, ['diff', 'createFromInterface'], true) ) { continue; } $function = new ReflectionMethod(Carbon::class, $method); $static = $function->isStatic() ? ' static' : ''; $parameters = implode(', ', array_map(function (ReflectionParameter $parameter) use ($method) { return dumpParameter($method, $parameter); }, $function->getParameters())); $methodDocBlock = $function->getDocComment() ?: ''; if (!str_starts_with($method, '__') && $function->isStatic()) { $doc = preg_replace('/^\/\*+\n([\s\S]+)\s*\*\//', '$1', $methodDocBlock); $doc = preg_replace('/^\s*\*\s?/m', '', $doc); $doc = explode("\n@", $doc, 2); $doc = preg_split('/(\r\n|\r|\n)/', trim($doc[0])); $returnType = $function->getReturnType(); if ($returnType instanceof ReflectionType) { $returnType = dumpType($returnType, false, $returnType->allowsNull()); } if (!$returnType && preg_match('/\*\s*@returns?\s+(\S+)/', $methodDocBlock, $match)) { $returnType = $match[1]; } $returnType = str_replace('static|CarbonInterface', 'static', $returnType ?: 'static'); if (!method_exists(Factory::class, $method)) { $staticMethods[] = [ '@method', str_replace(['self', 'static'], 'Carbon', $returnType), "$method($parameters)", $doc[0], ]; for ($i = 1; $i < \count($doc); $i++) { $staticMethods[] = ['', '', '', $doc[$i]]; } } if (!method_exists(FactoryImmutable::class, $method)) { $staticImmutableMethods[] = [ '@method', str_replace(['self', 'static'], 'CarbonImmutable', $returnType), "$method($parameters)", $doc[0], ]; for ($i = 1; $i < \count($doc); $i++) { $staticImmutableMethods[] = ['', '', '', $doc[$i]]; } } } $return = getMethodReturnType($function); if (!empty($methodDocBlock)) { $methodDocBlock = "\n $methodDocBlock"; } elseif (isset($nativeMethods[$method])) { $link = strtolower($method); $methodDocBlock = "\n /**\n". " * Calls DateTime::$method if mutable or DateTimeImmutable::$method else.\n". " *\n". " * @see https://php.net/manual/en/datetime.$link.php\n". ' */'; } if (str_contains($return, 'self') && $phpLevel < 7.4) { $return = ''; } if ($method === '__toString' && $phpLevel < 8) { $return = ''; } if (method_exists($function, 'getAttributes') && ($attributes = $function->getAttributes())) { foreach ($attributes as $attribute) { $methodDocBlock .= "\n #[".$attribute->getName().']'; } } if (!\in_array($method, $noInterface)) { $methods .= "\n$methodDocBlock\n public$static function $method($parameters)$return;"; } } $files->$interface = strtr(preg_replace_callback( '/(\/\/ <methods[\s\S]*>)([\s\S]+)(<\/methods>)/mU', static fn ($matches) => "{$matches[1]}$methods\n\n // {$matches[3]}", $files->$interface, 1, ), [ '|CarbonInterface' => '|self', 'CarbonInterface::TRANSLATE_ALL' => 'self::TRANSLATE_ALL', ]); $factories = [ __DIR__.'/src/Carbon/Factory.php' => $staticMethods, __DIR__.'/src/Carbon/FactoryImmutable.php' => $staticImmutableMethods, ]; foreach ($factories as $file => $methods) { $autoDoc = compileDoc($methods, $file); $content = file_get_contents($file); $files->$file = preg_replace_callback( '/(<autodoc[\s\S]*>)([\s\S]+)(<\/autodoc>)/mU', static fn ($matches) => "{$matches[1]}\n *$autoDoc\n *\n * {$matches[3]}", $content, 1, ); } foreach ($files as $file => $contents) { file_put_contents($file, $contents); }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/.php-cs-fixer.dist.php
.php-cs-fixer.dist.php
<?php use PhpCsFixer\Config; use PhpCsFixer\Finder; $header = <<<'EOF' This file is part of the Carbon package. (c) Brian Nesbitt <brian@nesbot.com> For the full copyright and license information, please view the LICENSE file that was distributed with this source code. EOF; $rules = [ '@PSR2' => true, '@PSR12' => true, '@PHP71Migration' => true, 'array_syntax' => [ 'syntax' => 'short', ], 'blank_line_after_namespace' => true, 'blank_line_before_statement' => true, 'cast_spaces' => true, 'class_definition' => false, 'concat_space' => [ 'spacing' => 'none', ], 'ereg_to_preg' => true, 'general_phpdoc_tag_rename' => true, 'header_comment' => [ 'comment_type' => 'PHPDoc', 'header' => $header, 'location' => 'after_declare_strict', 'separate' => 'both', ], 'is_null' => true, 'line_ending' => true, 'modernize_types_casting' => true, 'native_function_invocation' => [ 'include' => ['@compiler_optimized', 'app'], ], 'no_blank_lines_after_phpdoc' => true, 'no_empty_phpdoc' => true, 'no_extra_blank_lines' => true, 'no_short_bool_cast' => true, 'no_unneeded_control_parentheses' => true, 'no_unused_imports' => true, 'no_whitespace_in_blank_line' => true, 'ordered_imports' => true, 'php_unit_method_casing' => [ 'case' => 'camel_case', ], 'php_unit_test_annotation' => [ 'style' => 'prefix', ], 'php_unit_test_case_static_method_calls' => [ 'call_type' => 'this', ], 'phpdoc_align' => [ 'align' => 'vertical', 'tags' => [ 'param', 'return', 'throws', 'type', 'var', ], ], 'phpdoc_indent' => true, 'phpdoc_inline_tag_normalizer' => true, 'phpdoc_no_access' => true, 'phpdoc_no_package' => true, 'phpdoc_order' => true, 'phpdoc_scalar' => true, 'phpdoc_separation' => true, 'phpdoc_tag_type' => [ 'tags' => [ 'inheritdoc' => 'inline', ], ], 'phpdoc_to_comment' => true, 'phpdoc_trim' => true, 'phpdoc_types' => true, 'phpdoc_var_without_name' => true, 'self_accessor' => true, 'single_quote' => true, 'space_after_semicolon' => true, 'standardize_not_equals' => true, 'ternary_operator_spaces' => true, 'trailing_comma_in_multiline' => true, 'trim_array_spaces' => true, 'unary_operator_spaces' => true, 'yoda_style' => [ 'always_move_variable' => false, 'equal' => false, 'identical' => false, 'less_and_greater' => false, ], ]; return (new Config())->setRules($rules) ->setFinder( Finder::create() ->in(__DIR__) ->notPath([ 'src/Carbon/Doctrine/DateTimeImmutableType.php', 'src/Carbon/Doctrine/DateTimeType.php', ]), ) ->setUsingCache(true) ->setRiskyAllowed(true);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/sponsors.php
sponsors.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Carbon\CarbonImmutable; require_once __DIR__.'/vendor/autoload.php'; function getMaxHistoryMonthsByAmount($amount): int { if ($amount >= 50) { return 6; } if ($amount >= 20) { return 4; } return 2; } function getHtmlAttribute($rawValue): string { return str_replace( ['​', "\r"], '', trim(htmlspecialchars((string) $rawValue), "  \n\r\t\v\0"), ); } function getOpenCollectiveSponsors(): string { $customSponsorOverride = [ // For consistency and equity among sponsors, as of now, we kindly ask our sponsors // to provide an image having a width/height ratio between 1/1 and 2/1. // By default, we'll show the member picture from OpenCollective, and will resize it if bigger 662698 => [ // alt attribute 'name' => 'Non Gamstop Casinos', // title attribute 'description' => 'Casinos not on Gamstop', // src attribute 'image' => 'https://lgcnews.com/wp-content/uploads/2018/01/LGC-logo-v8-temp.png', // href attribute 'website' => 'https://lgcnews.com/', ], 663069 => [ // alt attribute 'name' => 'Ставки на спорт Favbet', // href attribute 'website' => 'https://www.favbet.ua/uk/', ], 676798 => [ // alt attribute 'name' => 'Top Casinos Canada', // title attribute 'description' => 'Top Casinos Canada', // src attribute 'image' => 'https://topcasino.net/img/topcasino-logo-cover.png', // href attribute 'website' => 'https://topcasino.net/', ], ]; $members = json_decode(file_get_contents('https://opencollective.com/carbon/members/all.json'), true); foreach ($members as &$member) { $member = array_merge($member, $customSponsorOverride[$member['MemberId']] ?? []); } // Adding sponsors paying via other payment methods $members[] = [ 'MemberId' => 1, 'createdAt' => '2019-01-01 02:00', 'type' => 'ORGANIZATION', 'role' => 'BACKER', 'tier' => 'backer+', 'isActive' => true, 'totalAmountDonated' => 1000, 'currency' => 'USD', 'lastTransactionAt' => CarbonImmutable::now()->format('Y-m-d').' 02:00', 'lastTransactionAmount' => 25, 'profile' => 'https://tidelift.com/', 'name' => 'Tidelift', 'description' => 'Get professional support for Carbon', 'image' => 'https://carbonphp.github.io/carbon/sponsors/tidelift-brand.png', 'website' => 'https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=docs', ]; $members[] = [ 'MemberId' => 2, 'createdAt' => '2024-11-14 02:00', 'type' => 'ORGANIZATION', 'role' => 'BACKER', 'tier' => 'backer+ yearly', 'isActive' => true, 'totalAmountDonated' => 170, 'currency' => 'USD', 'lastTransactionAt' => '2024-11-14 02:00', 'lastTransactionAmount' => 170, 'profile' => 'https://www.slotozilla.com/nz/free-spins', 'name' => 'Slotozilla', 'description' => 'Slotozilla website', 'image' => 'https://carbonphp.github.io/carbon/sponsors/slotozilla.png', 'website' => 'https://www.slotozilla.com/nz/free-spins', ]; $list = array_filter($members, static fn (array $member): bool => $member['totalAmountDonated'] > 3 && $member['role'] !== 'HOST' && ( $member['totalAmountDonated'] > 100 || $member['lastTransactionAt'] > CarbonImmutable::now() ->subMonthsNoOverflow(getMaxHistoryMonthsByAmount($member['lastTransactionAmount'])) ->format('Y-m-d h:i') || $member['isActive'] && $member['lastTransactionAmount'] >= 30 )); $list = array_map(static function (array $member): array { $createdAt = CarbonImmutable::parse($member['createdAt']); $lastTransactionAt = CarbonImmutable::parse($member['lastTransactionAt']); if ($createdAt->format('d H:i:s.u') > $lastTransactionAt->format('d H:i:s.u')) { $createdAt = $createdAt ->setDay($lastTransactionAt->day) ->modify($lastTransactionAt->format('H:i:s.u')); } $isYearly = str_contains(strtolower($member['tier'] ?? ''), 'yearly'); $monthlyContribution = (float) ( ($isYearly && $lastTransactionAt > CarbonImmutable::parse('-1 year')) ? ($member['lastTransactionAmount'] / 11.2) // 11.2 instead of 12 to include the discount for yearly subscription : ($member['totalAmountDonated'] / ceil($createdAt->floatDiffInMonths())) ); if (!$isYearly) { if ( $lastTransactionAt->isAfter('last month') && $member['lastTransactionAmount'] > $monthlyContribution ) { $monthlyContribution = (float) $member['lastTransactionAmount']; } if ($lastTransactionAt->isBefore('-75 days')) { $days = min(120, $lastTransactionAt->diffInDays('now') - 70); $monthlyContribution *= 1 - $days / 240; } } $yearlyContribution = (float) ( $isYearly ? (12 * $monthlyContribution) : ($member['totalAmountDonated'] / max(1, $createdAt->floatDiffInYears())) ); $status = null; $rank = 0; if ($monthlyContribution > 50 || $yearlyContribution > 900) { $status = 'sponsor'; $rank = 5; } elseif ($monthlyContribution > 29 || $yearlyContribution > 700) { $status = 'sponsor'; $rank = 4; } elseif ($monthlyContribution > 14.5 || $yearlyContribution > 500) { $status = 'backerPlus'; $rank = 3; } elseif ($monthlyContribution > 4.5 || $yearlyContribution > 80) { $status = 'backer'; $rank = 2; } elseif ($member['totalAmountDonated'] > 0) { $status = 'helper'; $rank = 1; } return array_merge($member, [ 'star' => ($monthlyContribution > 98 || $yearlyContribution > 800), 'status' => $status, 'rank' => $rank, 'monthlyContribution' => $monthlyContribution, 'yearlyContribution' => $yearlyContribution, ]); }, $list); usort($list, static function (array $a, array $b): int { return ($b['star'] <=> $a['star']) ?: ($b['rank'] <=> $a['rank']) ?: ($b['monthlyContribution'] <=> $a['monthlyContribution']) ?: ($b['totalAmountDonated'] <=> $a['totalAmountDonated']); }); $membersByUrl = []; $output = ''; $extra = ''; foreach ($list as $member) { $url = $member['website'] ?? $member['profile']; if (isset($membersByUrl[$url]) || !\in_array($member['status'], ['sponsor', 'backerPlus'], true)) { continue; } $membersByUrl[$url] = $member; $href = htmlspecialchars($url); $src = $customSponsorImages[$member['MemberId'] ?? ''] ?? $member['image'] ?? (strtr($member['profile'], ['https://opencollective.com/' => 'https://images.opencollective.com/']).'/avatar/256.png'); [$x, $y] = @getimagesize($src) ?: [0, 0]; $validImage = ($x && $y); $src = $validImage ? htmlspecialchars($src) : 'https://opencollective.com/static/images/default-guest-logo.svg'; $height = match ($member['status']) { 'sponsor' => 64, 'backerPlus' => 42, 'backer' => 32, default => 24, }; $rel = match ($member['status']) { 'sponsor', 'backerPlus' => '', default => ' rel="sponsored"', }; $width = min($height * 2, $validImage ? round($x * $height / $y) : $height); if (!str_contains($href, 'utm_source') && !preg_match('/^https?:\/\/(?:www\.)?(?:onlinekasyno-polis\.pl|zonaminecraft\.net|slotozilla\.com)(\/.*)?/', $href)) { $href .= (!str_contains($href, '?') ? '?' : '&amp;').'utm_source=opencollective&amp;utm_medium=github&amp;utm_campaign=Carbon'; } $title = getHtmlAttribute(($member['description'] ?? null) ?: $member['name']); $alt = getHtmlAttribute($member['name']); if ($member['star']) { $width *= 1.5; $height *= 1.5; } $link = "\n".'<a title="'.$title.'" href="'.$href.'" target="_blank"'.$rel.'>'. '<img alt="'.$alt.'" src="'.$src.'" width="'.$width.'" height="'.$height.'">'. '</a>'; if ($member['rank'] >= 5) { $output .= $link; continue; } $extra .= $link; } $github = [ 8343178 => 'ssddanbrown', ]; foreach ($github as $avatar => $user) { $extra .= "\n".'<a title="'.$user.'" href="https://github.com/'.$user.'" target="_blank">'. '<img alt="'.$user.'" src="https://avatars.githubusercontent.com/u/'.$avatar.'?s=128&v=4" width="42" height="42">'. '</a>'; } return $output.'<details><summary>See more</summary>'.$extra.'</details>'; } file_put_contents('readme.md', preg_replace_callback( '/(<!-- <open-collective-sponsors> -->)[\s\S]+(<!-- <\/open-collective-sponsors> -->)/', static function (array $match): string { return $match[1].getOpenCollectiveSponsors().$match[2]; }, file_get_contents('readme.md'), ));
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/lazy/Carbon/UnprotectedDatePeriod.php
lazy/Carbon/UnprotectedDatePeriod.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use DatePeriod; if (!class_exists(DatePeriodBase::class, false)) { class DatePeriodBase extends DatePeriod { } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/lazy/Carbon/ProtectedDatePeriod.php
lazy/Carbon/ProtectedDatePeriod.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use DatePeriod; if (!class_exists(DatePeriodBase::class, false)) { class DatePeriodBase extends DatePeriod { /** * Period start in PHP < 8.2. * * @var CarbonInterface * * @deprecated PHP 8.2 this property is no longer in sync with the actual period start. */ protected $start; /** * Period end in PHP < 8.2. * * @var CarbonInterface|null * * @deprecated PHP 8.2 this property is no longer in sync with the actual period end. */ protected $end; /** * Period current iterated date in PHP < 8.2. * * @var CarbonInterface|null * * @deprecated PHP 8.2 this property is no longer in sync with the actual period current iterated date. */ protected $current; /** * Period interval in PHP < 8.2. * * @var CarbonInterval|null * * @deprecated PHP 8.2 this property is no longer in sync with the actual period interval. */ protected $interval; /** * Period recurrences in PHP < 8.2. * * @var int|float|null * * @deprecated PHP 8.2 this property is no longer in sync with the actual period recurrences. */ protected $recurrences; /** * Period start included option in PHP < 8.2. * * @var bool * * @deprecated PHP 8.2 this property is no longer in sync with the actual period start included option. */ protected $include_start_date; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/lazy/Carbon/TranslatorStrongType.php
lazy/Carbon/TranslatorStrongType.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Symfony\Component\Translation\MessageCatalogueInterface; if (!class_exists(LazyTranslator::class, false)) { class LazyTranslator extends AbstractTranslator implements TranslatorStrongTypeInterface { public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string { return $this->translate($id, $parameters, $domain, $locale); } public function getFromCatalogue(MessageCatalogueInterface $catalogue, string $id, string $domain = 'messages') { $messages = $this->getPrivateProperty($catalogue, 'messages'); if (isset($messages[$domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX][$id])) { return $messages[$domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX][$id]; } if (isset($messages[$domain][$id])) { return $messages[$domain][$id]; } $fallbackCatalogue = $this->getPrivateProperty($catalogue, 'fallbackCatalogue'); if ($fallbackCatalogue !== null) { return $this->getFromCatalogue($fallbackCatalogue, $id, $domain); } return $id; } private function getPrivateProperty($instance, string $field) { return (function (string $field) { return $this->$field; })->call($instance, $field); } } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/lazy/Carbon/TranslatorWeakType.php
lazy/Carbon/TranslatorWeakType.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; if (!class_exists(LazyTranslator::class, false)) { class LazyTranslator extends AbstractTranslator { /** * Returns the translation. * * @param string|null $id * @param array $parameters * @param string|null $domain * @param string|null $locale * * @return string */ public function trans($id, array $parameters = [], $domain = null, $locale = null) { return $this->translate($id, $parameters, $domain, $locale); } } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php
lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\MessageFormatter; use Symfony\Component\Translation\Formatter\ChoiceMessageFormatterInterface; use Symfony\Component\Translation\Formatter\MessageFormatterInterface; if (!class_exists(LazyMessageFormatter::class, false)) { abstract class LazyMessageFormatter implements MessageFormatterInterface, ChoiceMessageFormatterInterface { abstract protected function transformLocale(?string $locale): ?string; public function format($message, $locale, array $parameters = []) { return $this->formatter->format( $message, $this->transformLocale($locale), $parameters ); } public function choiceFormat($message, $number, $locale, array $parameters = []) { return $this->formatter->choiceFormat($message, $number, $locale, $parameters); } } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/lazy/Carbon/MessageFormatter/MessageFormatterMapperStrongType.php
lazy/Carbon/MessageFormatter/MessageFormatterMapperStrongType.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\MessageFormatter; use Symfony\Component\Translation\Formatter\MessageFormatterInterface; if (!class_exists(LazyMessageFormatter::class, false)) { abstract class LazyMessageFormatter implements MessageFormatterInterface { public function format(string $message, string $locale, array $parameters = []): string { return $this->formatter->format( $message, $this->transformLocale($locale), $parameters ); } } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Month.php
src/Carbon/Month.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidFormatException; enum Month: int { // Using constants is only safe starting from PHP 8.2 case January = 1; // CarbonInterface::JANUARY case February = 2; // CarbonInterface::FEBRUARY case March = 3; // CarbonInterface::MARCH case April = 4; // CarbonInterface::APRIL case May = 5; // CarbonInterface::MAY case June = 6; // CarbonInterface::JUNE case July = 7; // CarbonInterface::JULY case August = 8; // CarbonInterface::AUGUST case September = 9; // CarbonInterface::SEPTEMBER case October = 10; // CarbonInterface::OCTOBER case November = 11; // CarbonInterface::NOVEMBER case December = 12; // CarbonInterface::DECEMBER public static function int(self|int|null $value): ?int { return $value instanceof self ? $value->value : $value; } public static function fromNumber(int $number): self { $month = $number % CarbonInterface::MONTHS_PER_YEAR; return self::from($month + ($month < 1 ? CarbonInterface::MONTHS_PER_YEAR : 0)); } public static function fromName(string $name, ?string $locale = null): self { try { return self::from(CarbonImmutable::parseFromLocale("$name 1", $locale)->month); } catch (InvalidFormatException $exception) { // Possibly current language expect a dot after short name, but it's missing if ($locale !== null && !mb_strlen($name) < 4 && !str_ends_with($name, '.')) { try { return self::from(CarbonImmutable::parseFromLocale("$name. 1", $locale)->month); } catch (InvalidFormatException $e) { // Throw previous error } } throw $exception; } } public function ofTheYear(CarbonImmutable|int|null $now = null): CarbonImmutable { if (\is_int($now)) { return CarbonImmutable::create($now, $this->value); } $modifier = $this->name.' 1st'; return $now?->modify($modifier) ?? new CarbonImmutable($modifier); } public function locale(string $locale, ?CarbonImmutable $now = null): CarbonImmutable { return $this->ofTheYear($now)->locale($locale); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Translator.php
src/Carbon/Translator.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use ReflectionMethod; use Symfony\Component\Translation; use Symfony\Contracts\Translation\TranslatorInterface; $transMethod = new ReflectionMethod( class_exists(TranslatorInterface::class) ? TranslatorInterface::class : Translation\Translator::class, 'trans', ); require $transMethod->hasReturnType() ? __DIR__.'/../../lazy/Carbon/TranslatorStrongType.php' : __DIR__.'/../../lazy/Carbon/TranslatorWeakType.php'; class Translator extends LazyTranslator { // Proxy dynamically loaded LazyTranslator in a static way }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/CarbonConverterInterface.php
src/Carbon/CarbonConverterInterface.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use DateTimeInterface; interface CarbonConverterInterface { public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface; }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/CarbonPeriod.php
src/Carbon/CarbonPeriod.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
true
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/CarbonImmutable.php
src/Carbon/CarbonImmutable.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Traits\Date; use DateTimeImmutable; use DateTimeInterface; /** * A simple API extension for DateTimeImmutable. * * <autodoc generated by `composer phpdoc`> * * @property string $localeDayOfWeek the day of week in current locale * @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale * @property string $localeMonth the month in current locale * @property string $shortLocaleMonth the abbreviated month in current locale * @property int $year * @property int $yearIso * @property int $month * @property int $day * @property int $hour * @property int $minute * @property int $second * @property int $micro * @property int $microsecond * @property int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) * @property int|float|string $timestamp seconds since the Unix Epoch * @property string $englishDayOfWeek the day of week in English * @property string $shortEnglishDayOfWeek the abbreviated day of week in English * @property string $englishMonth the month in English * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli * @property int $week 1 through 53 * @property int $isoWeek 1 through 53 * @property int $weekYear year according to week format * @property int $isoWeekYear year according to ISO week format * @property int $age does a diffInYears() with default parameters * @property int $offset the timezone offset in seconds from UTC * @property int $offsetMinutes the timezone offset in minutes from UTC * @property int $offsetHours the timezone offset in hours from UTC * @property CarbonTimeZone $timezone the current timezone * @property CarbonTimeZone $tz alias of $timezone * @property int $centuryOfMillennium The value of the century starting from the beginning of the current millennium * @property int $dayOfCentury The value of the day starting from the beginning of the current century * @property int $dayOfDecade The value of the day starting from the beginning of the current decade * @property int $dayOfMillennium The value of the day starting from the beginning of the current millennium * @property int $dayOfMonth The value of the day starting from the beginning of the current month * @property int $dayOfQuarter The value of the day starting from the beginning of the current quarter * @property int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) * @property int $dayOfYear 1 through 366 * @property int $decadeOfCentury The value of the decade starting from the beginning of the current century * @property int $decadeOfMillennium The value of the decade starting from the beginning of the current millennium * @property int $hourOfCentury The value of the hour starting from the beginning of the current century * @property int $hourOfDay The value of the hour starting from the beginning of the current day * @property int $hourOfDecade The value of the hour starting from the beginning of the current decade * @property int $hourOfMillennium The value of the hour starting from the beginning of the current millennium * @property int $hourOfMonth The value of the hour starting from the beginning of the current month * @property int $hourOfQuarter The value of the hour starting from the beginning of the current quarter * @property int $hourOfWeek The value of the hour starting from the beginning of the current week * @property int $hourOfYear The value of the hour starting from the beginning of the current year * @property int $microsecondOfCentury The value of the microsecond starting from the beginning of the current century * @property int $microsecondOfDay The value of the microsecond starting from the beginning of the current day * @property int $microsecondOfDecade The value of the microsecond starting from the beginning of the current decade * @property int $microsecondOfHour The value of the microsecond starting from the beginning of the current hour * @property int $microsecondOfMillennium The value of the microsecond starting from the beginning of the current millennium * @property int $microsecondOfMillisecond The value of the microsecond starting from the beginning of the current millisecond * @property int $microsecondOfMinute The value of the microsecond starting from the beginning of the current minute * @property int $microsecondOfMonth The value of the microsecond starting from the beginning of the current month * @property int $microsecondOfQuarter The value of the microsecond starting from the beginning of the current quarter * @property int $microsecondOfSecond The value of the microsecond starting from the beginning of the current second * @property int $microsecondOfWeek The value of the microsecond starting from the beginning of the current week * @property int $microsecondOfYear The value of the microsecond starting from the beginning of the current year * @property int $millisecondOfCentury The value of the millisecond starting from the beginning of the current century * @property int $millisecondOfDay The value of the millisecond starting from the beginning of the current day * @property int $millisecondOfDecade The value of the millisecond starting from the beginning of the current decade * @property int $millisecondOfHour The value of the millisecond starting from the beginning of the current hour * @property int $millisecondOfMillennium The value of the millisecond starting from the beginning of the current millennium * @property int $millisecondOfMinute The value of the millisecond starting from the beginning of the current minute * @property int $millisecondOfMonth The value of the millisecond starting from the beginning of the current month * @property int $millisecondOfQuarter The value of the millisecond starting from the beginning of the current quarter * @property int $millisecondOfSecond The value of the millisecond starting from the beginning of the current second * @property int $millisecondOfWeek The value of the millisecond starting from the beginning of the current week * @property int $millisecondOfYear The value of the millisecond starting from the beginning of the current year * @property int $minuteOfCentury The value of the minute starting from the beginning of the current century * @property int $minuteOfDay The value of the minute starting from the beginning of the current day * @property int $minuteOfDecade The value of the minute starting from the beginning of the current decade * @property int $minuteOfHour The value of the minute starting from the beginning of the current hour * @property int $minuteOfMillennium The value of the minute starting from the beginning of the current millennium * @property int $minuteOfMonth The value of the minute starting from the beginning of the current month * @property int $minuteOfQuarter The value of the minute starting from the beginning of the current quarter * @property int $minuteOfWeek The value of the minute starting from the beginning of the current week * @property int $minuteOfYear The value of the minute starting from the beginning of the current year * @property int $monthOfCentury The value of the month starting from the beginning of the current century * @property int $monthOfDecade The value of the month starting from the beginning of the current decade * @property int $monthOfMillennium The value of the month starting from the beginning of the current millennium * @property int $monthOfQuarter The value of the month starting from the beginning of the current quarter * @property int $monthOfYear The value of the month starting from the beginning of the current year * @property int $quarterOfCentury The value of the quarter starting from the beginning of the current century * @property int $quarterOfDecade The value of the quarter starting from the beginning of the current decade * @property int $quarterOfMillennium The value of the quarter starting from the beginning of the current millennium * @property int $quarterOfYear The value of the quarter starting from the beginning of the current year * @property int $secondOfCentury The value of the second starting from the beginning of the current century * @property int $secondOfDay The value of the second starting from the beginning of the current day * @property int $secondOfDecade The value of the second starting from the beginning of the current decade * @property int $secondOfHour The value of the second starting from the beginning of the current hour * @property int $secondOfMillennium The value of the second starting from the beginning of the current millennium * @property int $secondOfMinute The value of the second starting from the beginning of the current minute * @property int $secondOfMonth The value of the second starting from the beginning of the current month * @property int $secondOfQuarter The value of the second starting from the beginning of the current quarter * @property int $secondOfWeek The value of the second starting from the beginning of the current week * @property int $secondOfYear The value of the second starting from the beginning of the current year * @property int $weekOfCentury The value of the week starting from the beginning of the current century * @property int $weekOfDecade The value of the week starting from the beginning of the current decade * @property int $weekOfMillennium The value of the week starting from the beginning of the current millennium * @property int $weekOfMonth 1 through 5 * @property int $weekOfQuarter The value of the week starting from the beginning of the current quarter * @property int $weekOfYear ISO-8601 week number of year, weeks starting on Monday * @property int $yearOfCentury The value of the year starting from the beginning of the current century * @property int $yearOfDecade The value of the year starting from the beginning of the current decade * @property int $yearOfMillennium The value of the year starting from the beginning of the current millennium * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read int $noZeroHour current hour from 1 to 24 * @property-read int $isoWeeksInYear 51 through 53 * @property-read int $weekNumberInMonth 1 through 5 * @property-read int $firstWeekDay 0 through 6 * @property-read int $lastWeekDay 0 through 6 * @property-read int $quarter the quarter of this instance, 1 - 4 * @property-read int $decade the decade of this instance * @property-read int $century the century of this instance * @property-read int $millennium the millennium of this instance * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise * @property-read bool $local checks if the timezone is local, true if local, false otherwise * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise * @property-read string $timezoneName the current timezone name * @property-read string $tzName alias of $timezoneName * @property-read string $locale locale of the current instance * @property-read int $centuriesInMillennium The number of centuries contained in the current millennium * @property-read int $daysInCentury The number of days contained in the current century * @property-read int $daysInDecade The number of days contained in the current decade * @property-read int $daysInMillennium The number of days contained in the current millennium * @property-read int $daysInMonth number of days in the given month * @property-read int $daysInQuarter The number of days contained in the current quarter * @property-read int $daysInWeek The number of days contained in the current week * @property-read int $daysInYear 365 or 366 * @property-read int $decadesInCentury The number of decades contained in the current century * @property-read int $decadesInMillennium The number of decades contained in the current millennium * @property-read int $hoursInCentury The number of hours contained in the current century * @property-read int $hoursInDay The number of hours contained in the current day * @property-read int $hoursInDecade The number of hours contained in the current decade * @property-read int $hoursInMillennium The number of hours contained in the current millennium * @property-read int $hoursInMonth The number of hours contained in the current month * @property-read int $hoursInQuarter The number of hours contained in the current quarter * @property-read int $hoursInWeek The number of hours contained in the current week * @property-read int $hoursInYear The number of hours contained in the current year * @property-read int $microsecondsInCentury The number of microseconds contained in the current century * @property-read int $microsecondsInDay The number of microseconds contained in the current day * @property-read int $microsecondsInDecade The number of microseconds contained in the current decade * @property-read int $microsecondsInHour The number of microseconds contained in the current hour * @property-read int $microsecondsInMillennium The number of microseconds contained in the current millennium * @property-read int $microsecondsInMillisecond The number of microseconds contained in the current millisecond * @property-read int $microsecondsInMinute The number of microseconds contained in the current minute * @property-read int $microsecondsInMonth The number of microseconds contained in the current month * @property-read int $microsecondsInQuarter The number of microseconds contained in the current quarter * @property-read int $microsecondsInSecond The number of microseconds contained in the current second * @property-read int $microsecondsInWeek The number of microseconds contained in the current week * @property-read int $microsecondsInYear The number of microseconds contained in the current year * @property-read int $millisecondsInCentury The number of milliseconds contained in the current century * @property-read int $millisecondsInDay The number of milliseconds contained in the current day * @property-read int $millisecondsInDecade The number of milliseconds contained in the current decade * @property-read int $millisecondsInHour The number of milliseconds contained in the current hour * @property-read int $millisecondsInMillennium The number of milliseconds contained in the current millennium * @property-read int $millisecondsInMinute The number of milliseconds contained in the current minute * @property-read int $millisecondsInMonth The number of milliseconds contained in the current month * @property-read int $millisecondsInQuarter The number of milliseconds contained in the current quarter * @property-read int $millisecondsInSecond The number of milliseconds contained in the current second * @property-read int $millisecondsInWeek The number of milliseconds contained in the current week * @property-read int $millisecondsInYear The number of milliseconds contained in the current year * @property-read int $minutesInCentury The number of minutes contained in the current century * @property-read int $minutesInDay The number of minutes contained in the current day * @property-read int $minutesInDecade The number of minutes contained in the current decade * @property-read int $minutesInHour The number of minutes contained in the current hour * @property-read int $minutesInMillennium The number of minutes contained in the current millennium * @property-read int $minutesInMonth The number of minutes contained in the current month * @property-read int $minutesInQuarter The number of minutes contained in the current quarter * @property-read int $minutesInWeek The number of minutes contained in the current week * @property-read int $minutesInYear The number of minutes contained in the current year * @property-read int $monthsInCentury The number of months contained in the current century * @property-read int $monthsInDecade The number of months contained in the current decade * @property-read int $monthsInMillennium The number of months contained in the current millennium * @property-read int $monthsInQuarter The number of months contained in the current quarter
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
true
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Language.php
src/Carbon/Language.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use JsonSerializable; class Language implements JsonSerializable { protected static ?array $languagesNames = null; protected static ?array $regionsNames = null; protected string $id; protected string $code; protected ?string $variant = null; protected ?string $region = null; protected ?array $names = null; protected ?string $isoName = null; protected ?string $nativeName = null; public function __construct(string $id) { $this->id = str_replace('-', '_', $id); $parts = explode('_', $this->id); $this->code = $parts[0]; if (isset($parts[1])) { if (!preg_match('/^[A-Z]+$/', $parts[1])) { $this->variant = $parts[1]; $parts[1] = $parts[2] ?? null; } if ($parts[1]) { $this->region = $parts[1]; } } } /** * Get the list of the known languages. * * @return array */ public static function all(): array { static::$languagesNames ??= require __DIR__.'/List/languages.php'; return static::$languagesNames; } /** * Get the list of the known regions. * * ⚠ ISO 3166-2 short name provided with no warranty, should not * be used for any purpose to show official state names. */ public static function regions(): array { static::$regionsNames ??= require __DIR__.'/List/regions.php'; return static::$regionsNames; } /** * Get both isoName and nativeName as an array. */ public function getNames(): array { $this->names ??= static::all()[$this->code] ?? [ 'isoName' => $this->code, 'nativeName' => $this->code, ]; return $this->names; } /** * Returns the original locale ID. */ public function getId(): string { return $this->id; } /** * Returns the code of the locale "en"/"fr". */ public function getCode(): string { return $this->code; } /** * Returns the variant code such as cyrl/latn. */ public function getVariant(): ?string { return $this->variant; } /** * Returns the variant such as Cyrillic/Latin. */ public function getVariantName(): ?string { if ($this->variant === 'Latn') { return 'Latin'; } if ($this->variant === 'Cyrl') { return 'Cyrillic'; } return $this->variant; } /** * Returns the region part of the locale. */ public function getRegion(): ?string { return $this->region; } /** * Returns the region name for the current language. * * ⚠ ISO 3166-2 short name provided with no warranty, should not * be used for any purpose to show official state names. */ public function getRegionName(): ?string { return $this->region ? (static::regions()[$this->region] ?? $this->region) : null; } /** * Returns the long ISO language name. */ public function getFullIsoName(): string { $this->isoName ??= $this->getNames()['isoName']; return $this->isoName; } /** * Set the ISO language name. */ public function setIsoName(string $isoName): static { $this->isoName = $isoName; return $this; } /** * Return the full name of the language in this language. */ public function getFullNativeName(): string { $this->nativeName ??= $this->getNames()['nativeName']; return $this->nativeName; } /** * Set the name of the language in this language. */ public function setNativeName(string $nativeName): static { $this->nativeName = $nativeName; return $this; } /** * Returns the short ISO language name. */ public function getIsoName(): string { $name = $this->getFullIsoName(); return trim(strstr($name, ',', true) ?: $name); } /** * Get the short name of the language in this language. */ public function getNativeName(): string { $name = $this->getFullNativeName(); return trim(strstr($name, ',', true) ?: $name); } /** * Get a string with short ISO name, region in parentheses if applicable, variant in parentheses if applicable. */ public function getIsoDescription(): string { $region = $this->getRegionName(); $variant = $this->getVariantName(); return $this->getIsoName().($region ? ' ('.$region.')' : '').($variant ? ' ('.$variant.')' : ''); } /** * Get a string with short native name, region in parentheses if applicable, variant in parentheses if applicable. */ public function getNativeDescription(): string { $region = $this->getRegionName(); $variant = $this->getVariantName(); return $this->getNativeName().($region ? ' ('.$region.')' : '').($variant ? ' ('.$variant.')' : ''); } /** * Get a string with long ISO name, region in parentheses if applicable, variant in parentheses if applicable. */ public function getFullIsoDescription(): string { $region = $this->getRegionName(); $variant = $this->getVariantName(); return $this->getFullIsoName().($region ? ' ('.$region.')' : '').($variant ? ' ('.$variant.')' : ''); } /** * Get a string with long native name, region in parentheses if applicable, variant in parentheses if applicable. */ public function getFullNativeDescription(): string { $region = $this->getRegionName(); $variant = $this->getVariantName(); return $this->getFullNativeName().($region ? ' ('.$region.')' : '').($variant ? ' ('.$variant.')' : ''); } /** * Returns the original locale ID. */ public function __toString(): string { return $this->getId(); } /** * Get a string with short ISO name, region in parentheses if applicable, variant in parentheses if applicable. */ public function jsonSerialize(): string { return $this->getIsoDescription(); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Unit.php
src/Carbon/Unit.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; enum Unit: string { case Microsecond = 'microsecond'; case Millisecond = 'millisecond'; case Second = 'second'; case Minute = 'minute'; case Hour = 'hour'; case Day = 'day'; case Week = 'week'; case Month = 'month'; case Quarter = 'quarter'; case Year = 'year'; case Decade = 'decade'; case Century = 'century'; case Millennium = 'millennium'; public static function toName(self|string $unit): string { return $unit instanceof self ? $unit->value : $unit; } /** @internal */ public static function toNameIfUnit(mixed $unit): mixed { return $unit instanceof self ? $unit->value : $unit; } public static function fromName(string $name, ?string $locale = null): self { if ($locale !== null) { $messages = Translator::get($locale)->getMessages($locale) ?? []; if ($messages !== []) { $lowerName = mb_strtolower($name); foreach (self::cases() as $unit) { foreach (['', '_from_now', '_ago', '_after', '_before'] as $suffix) { $message = $messages[$unit->value.$suffix] ?? null; if (\is_string($message)) { $words = explode('|', mb_strtolower(preg_replace( '/[{\[\]].+?[}\[\]]/', '', str_replace(':count', '', $message), ))); foreach ($words as $word) { if (trim($word) === $lowerName) { return $unit; } } } } } } } return self::from(CarbonImmutable::singularUnit($name)); } public function singular(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 1, ':count' => 1, ]), "1 \n\r\t\v\0"); } return $this->value; } public function plural(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 9, ':count' => 9, ]), "9 \n\r\t\v\0"); } return CarbonImmutable::pluralUnit($this->value); } public function interval(int|float $value = 1): CarbonInterval { return CarbonInterval::fromString("$value $this->name"); } public function locale(string $locale): CarbonInterval { return $this->interval()->locale($locale); } public function toPeriod(...$params): CarbonPeriod { return $this->interval()->toPeriod(...$params); } public function stepBy(mixed $interval, Unit|string|null $unit = null): CarbonPeriod { return $this->interval()->stepBy($interval, $unit); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/TranslatorImmutable.php
src/Carbon/TranslatorImmutable.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\ImmutableException; use Symfony\Component\Config\ConfigCacheFactoryInterface; use Symfony\Component\Translation\Formatter\MessageFormatterInterface; class TranslatorImmutable extends Translator { private bool $constructed = false; public function __construct($locale, ?MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false) { parent::__construct($locale, $formatter, $cacheDir, $debug); $this->constructed = true; } /** * @codeCoverageIgnore */ public function setDirectories(array $directories): static { $this->disallowMutation(__METHOD__); return parent::setDirectories($directories); } public function setLocale($locale): void { $this->disallowMutation(__METHOD__); parent::setLocale($locale); } /** * @codeCoverageIgnore */ public function setMessages(string $locale, array $messages): static { $this->disallowMutation(__METHOD__); return parent::setMessages($locale, $messages); } /** * @codeCoverageIgnore */ public function setTranslations(array $messages): static { $this->disallowMutation(__METHOD__); return parent::setTranslations($messages); } /** * @codeCoverageIgnore */ public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory): void { $this->disallowMutation(__METHOD__); parent::setConfigCacheFactory($configCacheFactory); } public function resetMessages(?string $locale = null): bool { $this->disallowMutation(__METHOD__); return parent::resetMessages($locale); } /** * @codeCoverageIgnore */ public function setFallbackLocales(array $locales): void { $this->disallowMutation(__METHOD__); parent::setFallbackLocales($locales); } private function disallowMutation($method) { if ($this->constructed) { throw new ImmutableException($method.' not allowed on '.static::class); } } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Carbon.php
src/Carbon/Carbon.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Traits\Date; use DateTime; use DateTimeInterface; /** * A simple API extension for DateTime. * * <autodoc generated by `composer phpdoc`> * * @property string $localeDayOfWeek the day of week in current locale * @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale * @property string $localeMonth the month in current locale * @property string $shortLocaleMonth the abbreviated month in current locale * @property int $year * @property int $yearIso * @property int $month * @property int $day * @property int $hour * @property int $minute * @property int $second * @property int $micro * @property int $microsecond * @property int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) * @property int|float|string $timestamp seconds since the Unix Epoch * @property string $englishDayOfWeek the day of week in English * @property string $shortEnglishDayOfWeek the abbreviated day of week in English * @property string $englishMonth the month in English * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli * @property int $week 1 through 53 * @property int $isoWeek 1 through 53 * @property int $weekYear year according to week format * @property int $isoWeekYear year according to ISO week format * @property int $age does a diffInYears() with default parameters * @property int $offset the timezone offset in seconds from UTC * @property int $offsetMinutes the timezone offset in minutes from UTC * @property int $offsetHours the timezone offset in hours from UTC * @property CarbonTimeZone $timezone the current timezone * @property CarbonTimeZone $tz alias of $timezone * @property int $centuryOfMillennium The value of the century starting from the beginning of the current millennium * @property int $dayOfCentury The value of the day starting from the beginning of the current century * @property int $dayOfDecade The value of the day starting from the beginning of the current decade * @property int $dayOfMillennium The value of the day starting from the beginning of the current millennium * @property int $dayOfMonth The value of the day starting from the beginning of the current month * @property int $dayOfQuarter The value of the day starting from the beginning of the current quarter * @property int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) * @property int $dayOfYear 1 through 366 * @property int $decadeOfCentury The value of the decade starting from the beginning of the current century * @property int $decadeOfMillennium The value of the decade starting from the beginning of the current millennium * @property int $hourOfCentury The value of the hour starting from the beginning of the current century * @property int $hourOfDay The value of the hour starting from the beginning of the current day * @property int $hourOfDecade The value of the hour starting from the beginning of the current decade * @property int $hourOfMillennium The value of the hour starting from the beginning of the current millennium * @property int $hourOfMonth The value of the hour starting from the beginning of the current month * @property int $hourOfQuarter The value of the hour starting from the beginning of the current quarter * @property int $hourOfWeek The value of the hour starting from the beginning of the current week * @property int $hourOfYear The value of the hour starting from the beginning of the current year * @property int $microsecondOfCentury The value of the microsecond starting from the beginning of the current century * @property int $microsecondOfDay The value of the microsecond starting from the beginning of the current day * @property int $microsecondOfDecade The value of the microsecond starting from the beginning of the current decade * @property int $microsecondOfHour The value of the microsecond starting from the beginning of the current hour * @property int $microsecondOfMillennium The value of the microsecond starting from the beginning of the current millennium * @property int $microsecondOfMillisecond The value of the microsecond starting from the beginning of the current millisecond * @property int $microsecondOfMinute The value of the microsecond starting from the beginning of the current minute * @property int $microsecondOfMonth The value of the microsecond starting from the beginning of the current month * @property int $microsecondOfQuarter The value of the microsecond starting from the beginning of the current quarter * @property int $microsecondOfSecond The value of the microsecond starting from the beginning of the current second * @property int $microsecondOfWeek The value of the microsecond starting from the beginning of the current week * @property int $microsecondOfYear The value of the microsecond starting from the beginning of the current year * @property int $millisecondOfCentury The value of the millisecond starting from the beginning of the current century * @property int $millisecondOfDay The value of the millisecond starting from the beginning of the current day * @property int $millisecondOfDecade The value of the millisecond starting from the beginning of the current decade * @property int $millisecondOfHour The value of the millisecond starting from the beginning of the current hour * @property int $millisecondOfMillennium The value of the millisecond starting from the beginning of the current millennium * @property int $millisecondOfMinute The value of the millisecond starting from the beginning of the current minute * @property int $millisecondOfMonth The value of the millisecond starting from the beginning of the current month * @property int $millisecondOfQuarter The value of the millisecond starting from the beginning of the current quarter * @property int $millisecondOfSecond The value of the millisecond starting from the beginning of the current second * @property int $millisecondOfWeek The value of the millisecond starting from the beginning of the current week * @property int $millisecondOfYear The value of the millisecond starting from the beginning of the current year * @property int $minuteOfCentury The value of the minute starting from the beginning of the current century * @property int $minuteOfDay The value of the minute starting from the beginning of the current day * @property int $minuteOfDecade The value of the minute starting from the beginning of the current decade * @property int $minuteOfHour The value of the minute starting from the beginning of the current hour * @property int $minuteOfMillennium The value of the minute starting from the beginning of the current millennium * @property int $minuteOfMonth The value of the minute starting from the beginning of the current month * @property int $minuteOfQuarter The value of the minute starting from the beginning of the current quarter * @property int $minuteOfWeek The value of the minute starting from the beginning of the current week * @property int $minuteOfYear The value of the minute starting from the beginning of the current year * @property int $monthOfCentury The value of the month starting from the beginning of the current century * @property int $monthOfDecade The value of the month starting from the beginning of the current decade * @property int $monthOfMillennium The value of the month starting from the beginning of the current millennium * @property int $monthOfQuarter The value of the month starting from the beginning of the current quarter * @property int $monthOfYear The value of the month starting from the beginning of the current year * @property int $quarterOfCentury The value of the quarter starting from the beginning of the current century * @property int $quarterOfDecade The value of the quarter starting from the beginning of the current decade * @property int $quarterOfMillennium The value of the quarter starting from the beginning of the current millennium * @property int $quarterOfYear The value of the quarter starting from the beginning of the current year * @property int $secondOfCentury The value of the second starting from the beginning of the current century * @property int $secondOfDay The value of the second starting from the beginning of the current day * @property int $secondOfDecade The value of the second starting from the beginning of the current decade * @property int $secondOfHour The value of the second starting from the beginning of the current hour * @property int $secondOfMillennium The value of the second starting from the beginning of the current millennium * @property int $secondOfMinute The value of the second starting from the beginning of the current minute * @property int $secondOfMonth The value of the second starting from the beginning of the current month * @property int $secondOfQuarter The value of the second starting from the beginning of the current quarter * @property int $secondOfWeek The value of the second starting from the beginning of the current week * @property int $secondOfYear The value of the second starting from the beginning of the current year * @property int $weekOfCentury The value of the week starting from the beginning of the current century * @property int $weekOfDecade The value of the week starting from the beginning of the current decade * @property int $weekOfMillennium The value of the week starting from the beginning of the current millennium * @property int $weekOfMonth 1 through 5 * @property int $weekOfQuarter The value of the week starting from the beginning of the current quarter * @property int $weekOfYear ISO-8601 week number of year, weeks starting on Monday * @property int $yearOfCentury The value of the year starting from the beginning of the current century * @property int $yearOfDecade The value of the year starting from the beginning of the current decade * @property int $yearOfMillennium The value of the year starting from the beginning of the current millennium * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read int $noZeroHour current hour from 1 to 24 * @property-read int $isoWeeksInYear 51 through 53 * @property-read int $weekNumberInMonth 1 through 5 * @property-read int $firstWeekDay 0 through 6 * @property-read int $lastWeekDay 0 through 6 * @property-read int $quarter the quarter of this instance, 1 - 4 * @property-read int $decade the decade of this instance * @property-read int $century the century of this instance * @property-read int $millennium the millennium of this instance * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise * @property-read bool $local checks if the timezone is local, true if local, false otherwise * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise * @property-read string $timezoneName the current timezone name * @property-read string $tzName alias of $timezoneName * @property-read string $locale locale of the current instance * @property-read int $centuriesInMillennium The number of centuries contained in the current millennium * @property-read int $daysInCentury The number of days contained in the current century * @property-read int $daysInDecade The number of days contained in the current decade * @property-read int $daysInMillennium The number of days contained in the current millennium * @property-read int $daysInMonth number of days in the given month * @property-read int $daysInQuarter The number of days contained in the current quarter * @property-read int $daysInWeek The number of days contained in the current week * @property-read int $daysInYear 365 or 366 * @property-read int $decadesInCentury The number of decades contained in the current century * @property-read int $decadesInMillennium The number of decades contained in the current millennium * @property-read int $hoursInCentury The number of hours contained in the current century * @property-read int $hoursInDay The number of hours contained in the current day * @property-read int $hoursInDecade The number of hours contained in the current decade * @property-read int $hoursInMillennium The number of hours contained in the current millennium * @property-read int $hoursInMonth The number of hours contained in the current month * @property-read int $hoursInQuarter The number of hours contained in the current quarter * @property-read int $hoursInWeek The number of hours contained in the current week * @property-read int $hoursInYear The number of hours contained in the current year * @property-read int $microsecondsInCentury The number of microseconds contained in the current century * @property-read int $microsecondsInDay The number of microseconds contained in the current day * @property-read int $microsecondsInDecade The number of microseconds contained in the current decade * @property-read int $microsecondsInHour The number of microseconds contained in the current hour * @property-read int $microsecondsInMillennium The number of microseconds contained in the current millennium * @property-read int $microsecondsInMillisecond The number of microseconds contained in the current millisecond * @property-read int $microsecondsInMinute The number of microseconds contained in the current minute * @property-read int $microsecondsInMonth The number of microseconds contained in the current month * @property-read int $microsecondsInQuarter The number of microseconds contained in the current quarter * @property-read int $microsecondsInSecond The number of microseconds contained in the current second * @property-read int $microsecondsInWeek The number of microseconds contained in the current week * @property-read int $microsecondsInYear The number of microseconds contained in the current year * @property-read int $millisecondsInCentury The number of milliseconds contained in the current century * @property-read int $millisecondsInDay The number of milliseconds contained in the current day * @property-read int $millisecondsInDecade The number of milliseconds contained in the current decade * @property-read int $millisecondsInHour The number of milliseconds contained in the current hour * @property-read int $millisecondsInMillennium The number of milliseconds contained in the current millennium * @property-read int $millisecondsInMinute The number of milliseconds contained in the current minute * @property-read int $millisecondsInMonth The number of milliseconds contained in the current month * @property-read int $millisecondsInQuarter The number of milliseconds contained in the current quarter * @property-read int $millisecondsInSecond The number of milliseconds contained in the current second * @property-read int $millisecondsInWeek The number of milliseconds contained in the current week * @property-read int $millisecondsInYear The number of milliseconds contained in the current year * @property-read int $minutesInCentury The number of minutes contained in the current century * @property-read int $minutesInDay The number of minutes contained in the current day * @property-read int $minutesInDecade The number of minutes contained in the current decade * @property-read int $minutesInHour The number of minutes contained in the current hour * @property-read int $minutesInMillennium The number of minutes contained in the current millennium * @property-read int $minutesInMonth The number of minutes contained in the current month * @property-read int $minutesInQuarter The number of minutes contained in the current quarter * @property-read int $minutesInWeek The number of minutes contained in the current week * @property-read int $minutesInYear The number of minutes contained in the current year * @property-read int $monthsInCentury The number of months contained in the current century * @property-read int $monthsInDecade The number of months contained in the current decade * @property-read int $monthsInMillennium The number of months contained in the current millennium * @property-read int $monthsInQuarter The number of months contained in the current quarter
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
true
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Callback.php
src/Carbon/Callback.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Closure; use DateInterval; use DatePeriod; use DateTime; use DateTimeInterface; use DateTimeZone; use ReflectionFunction; use ReflectionNamedType; use ReflectionType; final class Callback { private ?ReflectionFunction $function; private function __construct(private readonly Closure $closure) { } public static function fromClosure(Closure $closure): self { return new self($closure); } public static function parameter(mixed $closure, mixed $value, string|int $index = 0): mixed { if ($closure instanceof Closure) { return self::fromClosure($closure)->prepareParameter($value, $index); } return $value; } public function getReflectionFunction(): ReflectionFunction { return $this->function ??= new ReflectionFunction($this->closure); } public function prepareParameter(mixed $value, string|int $index = 0): mixed { $type = $this->getParameterType($index); if (!($type instanceof ReflectionNamedType)) { return $value; } $name = $type->getName(); if ($name === CarbonInterface::class) { $name = $value instanceof DateTime ? Carbon::class : CarbonImmutable::class; } if (!class_exists($name) || is_a($value, $name)) { return $value; } $class = $this->getPromotedClass($value); if ($class && is_a($name, $class, true)) { return $name::instance($value); } return $value; } public function call(mixed ...$arguments): mixed { foreach ($arguments as $index => &$value) { if ($this->getPromotedClass($value)) { $value = $this->prepareParameter($value, $index); } } return ($this->closure)(...$arguments); } private function getParameterType(string|int $index): ?ReflectionType { $parameters = $this->getReflectionFunction()->getParameters(); if (\is_int($index)) { return ($parameters[$index] ?? null)?->getType(); } foreach ($parameters as $parameter) { if ($parameter->getName() === $index) { return $parameter->getType(); } } return null; } /** @return class-string|null */ private function getPromotedClass(mixed $value): ?string { if ($value instanceof DateTimeInterface) { return CarbonInterface::class; } if ($value instanceof DateInterval) { return CarbonInterval::class; } if ($value instanceof DatePeriod) { return CarbonPeriod::class; } if ($value instanceof DateTimeZone) { return CarbonTimeZone::class; } return null; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/CarbonTimeZone.php
src/Carbon/CarbonTimeZone.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Traits\LocalFactory; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use Throwable; class CarbonTimeZone extends DateTimeZone { use LocalFactory; public const MAXIMUM_TIMEZONE_OFFSET = 99; public function __construct(string|int|float $timezone) { $this->initLocalFactory(); parent::__construct(static::getDateTimeZoneNameFromMixed($timezone)); } protected static function parseNumericTimezone(string|int|float $timezone): string { if (abs((float) $timezone) > static::MAXIMUM_TIMEZONE_OFFSET) { throw new InvalidTimeZoneException( 'Absolute timezone offset cannot be greater than '. static::MAXIMUM_TIMEZONE_OFFSET.'.', ); } return ($timezone >= 0 ? '+' : '').ltrim((string) $timezone, '+').':00'; } protected static function getDateTimeZoneNameFromMixed(string|int|float $timezone): string { if (\is_string($timezone)) { $timezone = preg_replace('/^\s*([+-]\d+)(\d{2})\s*$/', '$1:$2', $timezone); } if (is_numeric($timezone)) { return static::parseNumericTimezone($timezone); } return $timezone; } /** * Cast the current instance into the given class. * * @param class-string<DateTimeZone> $className The $className::instance() method will be called to cast the current object. * * @return DateTimeZone|mixed */ public function cast(string $className): mixed { if (!method_exists($className, 'instance')) { if (is_a($className, DateTimeZone::class, true)) { return new $className($this->getName()); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return static|null */ public static function instance( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?self { $timezone = $object; if ($timezone instanceof static) { return $timezone; } if ($timezone === null || $timezone === false) { return null; } try { if (!($timezone instanceof DateTimeZone)) { $name = static::getDateTimeZoneNameFromMixed($object); $timezone = new static($name); } return $timezone instanceof static ? $timezone : new static($timezone->getName()); } catch (Exception $exception) { throw new InvalidTimeZoneException( 'Unknown or bad timezone ('.($objectDump ?: $object).')', previous: $exception, ); } } /** * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbreviatedName(bool $dst = false): string { $name = $this->getName(); $date = new DateTimeImmutable($dst ? 'July 1' : 'January 1', $this); $timezone = $date->format('T'); $abbreviations = $this->listAbbreviations(); $matchingZones = array_merge($abbreviations[$timezone] ?? [], $abbreviations[strtolower($timezone)] ?? []); if ($matchingZones !== []) { foreach ($matchingZones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return $timezone; } } } foreach ($abbreviations as $abbreviation => $zones) { foreach ($zones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return strtoupper($abbreviation); } } } return 'unknown'; } /** * @alias getAbbreviatedName * * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbr(bool $dst = false): string { return $this->getAbbreviatedName($dst); } /** * Get the offset as string "sHH:MM" (such as "+00:00" or "-12:30"). */ public function toOffsetName(?DateTimeInterface $date = null): string { return static::getOffsetNameFromMinuteOffset( $this->getOffset($this->resolveCarbon($date)) / 60, ); } /** * Returns a new CarbonTimeZone object using the offset string instead of region string. */ public function toOffsetTimeZone(?DateTimeInterface $date = null): static { return new static($this->toOffsetName($date)); } /** * Returns the first region string (such as "America/Toronto") that matches the current timezone or * false if no match is found. * * @see timezone_name_from_abbr native PHP function. */ public function toRegionName(?DateTimeInterface $date = null, int $isDST = 1): ?string { $name = $this->getName(); $firstChar = substr($name, 0, 1); if ($firstChar !== '+' && $firstChar !== '-') { return $name; } $date = $this->resolveCarbon($date); // Integer construction no longer supported since PHP 8 // @codeCoverageIgnoreStart try { $offset = @$this->getOffset($date) ?: 0; } catch (Throwable) { $offset = 0; } // @codeCoverageIgnoreEnd $name = @timezone_name_from_abbr('', $offset, $isDST); if ($name) { return $name; } foreach (timezone_identifiers_list() as $timezone) { if (Carbon::instance($date)->setTimezone($timezone)->getOffset() === $offset) { return $timezone; } } return null; } /** * Returns a new CarbonTimeZone object using the region string instead of offset string. */ public function toRegionTimeZone(?DateTimeInterface $date = null): ?self { $timezone = $this->toRegionName($date); if ($timezone !== null) { return new static($timezone); } if (Carbon::isStrictModeEnabled()) { throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($this->resolveCarbon($date)).' seconds.'); } return null; } /** * Cast to string (get timezone name). * * @return string */ public function __toString() { return $this->getName(); } /** * Return the type number: * * Type 1; A UTC offset, such as -0300 * Type 2; A timezone abbreviation, such as GMT * Type 3: A timezone identifier, such as Europe/London */ public function getType(): int { return preg_match('/"timezone_type";i:(\d)/', serialize($this), $match) ? (int) $match[1] : 3; } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|null $object * * @return false|static */ public static function create($object = null) { return static::instance($object); } /** * Create a CarbonTimeZone from int/float hour offset. * * @param float $hourOffset number of hour of the timezone shift (can be decimal). * * @return false|static */ public static function createFromHourOffset(float $hourOffset) { return static::createFromMinuteOffset($hourOffset * Carbon::MINUTES_PER_HOUR); } /** * Create a CarbonTimeZone from int/float minute offset. * * @param float $minuteOffset number of total minutes of the timezone shift. * * @return false|static */ public static function createFromMinuteOffset(float $minuteOffset) { return static::instance(static::getOffsetNameFromMinuteOffset($minuteOffset)); } /** * Convert a total minutes offset into a standardized timezone offset string. * * @param float $minutes number of total minutes of the timezone shift. * * @return string */ public static function getOffsetNameFromMinuteOffset(float $minutes): string { $minutes = round($minutes); $unsignedMinutes = abs($minutes); return ($minutes < 0 ? '-' : '+'). str_pad((string) floor($unsignedMinutes / 60), 2, '0', STR_PAD_LEFT). ':'. str_pad((string) ($unsignedMinutes % 60), 2, '0', STR_PAD_LEFT); } private function resolveCarbon(?DateTimeInterface $date): DateTimeInterface { if ($date) { return $date; } if (isset($this->clock)) { return $this->clock->now()->setTimezone($this); } return Carbon::now($this); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/WeekDay.php
src/Carbon/WeekDay.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidFormatException; enum WeekDay: int { // Using constants is only safe starting from PHP 8.2 case Sunday = 0; // CarbonInterface::SUNDAY case Monday = 1; // CarbonInterface::MONDAY case Tuesday = 2; // CarbonInterface::TUESDAY case Wednesday = 3; // CarbonInterface::WEDNESDAY case Thursday = 4; // CarbonInterface::THURSDAY case Friday = 5; // CarbonInterface::FRIDAY case Saturday = 6; // CarbonInterface::SATURDAY public static function int(self|int|null $value): ?int { return $value instanceof self ? $value->value : $value; } public static function fromNumber(int $number): self { $day = $number % CarbonInterface::DAYS_PER_WEEK; return self::from($day + ($day < 0 ? CarbonInterface::DAYS_PER_WEEK : 0)); } public static function fromName(string $name, ?string $locale = null): self { try { return self::from(CarbonImmutable::parseFromLocale($name, $locale)->dayOfWeek); } catch (InvalidFormatException $exception) { // Possibly current language expect a dot after short name, but it's missing if ($locale !== null && !mb_strlen($name) < 4 && !str_ends_with($name, '.')) { try { return self::from(CarbonImmutable::parseFromLocale($name.'.', $locale)->dayOfWeek); } catch (InvalidFormatException) { // Throw previous error } } throw $exception; } } public function next(?CarbonImmutable $now = null): CarbonImmutable { return $now?->modify($this->name) ?? new CarbonImmutable($this->name); } public function locale(string $locale, ?CarbonImmutable $now = null): CarbonImmutable { return $this->next($now)->locale($locale); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/CarbonInterface.php
src/Carbon/CarbonInterface.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use BadMethodCallException; use Carbon\Constants\DiffOptions; use Carbon\Constants\Format; use Carbon\Constants\TranslationOptions; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\Exceptions\ImmutableException; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnknownSetterException; use Closure; use DateInterval; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * Common interface for Carbon and CarbonImmutable. * * <autodoc generated by `composer phpdoc`> * * @property string $localeDayOfWeek the day of week in current locale * @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale * @property string $localeMonth the month in current locale * @property string $shortLocaleMonth the abbreviated month in current locale * @property int $year * @property int $yearIso * @property int $month * @property int $day * @property int $hour * @property int $minute * @property int $second * @property int $micro * @property int $microsecond * @property int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) * @property int|float|string $timestamp seconds since the Unix Epoch * @property string $englishDayOfWeek the day of week in English * @property string $shortEnglishDayOfWeek the abbreviated day of week in English * @property string $englishMonth the month in English * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli * @property int $week 1 through 53 * @property int $isoWeek 1 through 53 * @property int $weekYear year according to week format * @property int $isoWeekYear year according to ISO week format * @property int $age does a diffInYears() with default parameters * @property int $offset the timezone offset in seconds from UTC * @property int $offsetMinutes the timezone offset in minutes from UTC * @property int $offsetHours the timezone offset in hours from UTC * @property CarbonTimeZone $timezone the current timezone * @property CarbonTimeZone $tz alias of $timezone * @property int $centuryOfMillennium The value of the century starting from the beginning of the current millennium * @property int $dayOfCentury The value of the day starting from the beginning of the current century * @property int $dayOfDecade The value of the day starting from the beginning of the current decade * @property int $dayOfMillennium The value of the day starting from the beginning of the current millennium * @property int $dayOfMonth The value of the day starting from the beginning of the current month * @property int $dayOfQuarter The value of the day starting from the beginning of the current quarter * @property int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) * @property int $dayOfYear 1 through 366 * @property int $decadeOfCentury The value of the decade starting from the beginning of the current century * @property int $decadeOfMillennium The value of the decade starting from the beginning of the current millennium * @property int $hourOfCentury The value of the hour starting from the beginning of the current century * @property int $hourOfDay The value of the hour starting from the beginning of the current day * @property int $hourOfDecade The value of the hour starting from the beginning of the current decade * @property int $hourOfMillennium The value of the hour starting from the beginning of the current millennium * @property int $hourOfMonth The value of the hour starting from the beginning of the current month * @property int $hourOfQuarter The value of the hour starting from the beginning of the current quarter * @property int $hourOfWeek The value of the hour starting from the beginning of the current week * @property int $hourOfYear The value of the hour starting from the beginning of the current year * @property int $microsecondOfCentury The value of the microsecond starting from the beginning of the current century * @property int $microsecondOfDay The value of the microsecond starting from the beginning of the current day * @property int $microsecondOfDecade The value of the microsecond starting from the beginning of the current decade * @property int $microsecondOfHour The value of the microsecond starting from the beginning of the current hour * @property int $microsecondOfMillennium The value of the microsecond starting from the beginning of the current millennium * @property int $microsecondOfMillisecond The value of the microsecond starting from the beginning of the current millisecond * @property int $microsecondOfMinute The value of the microsecond starting from the beginning of the current minute * @property int $microsecondOfMonth The value of the microsecond starting from the beginning of the current month * @property int $microsecondOfQuarter The value of the microsecond starting from the beginning of the current quarter * @property int $microsecondOfSecond The value of the microsecond starting from the beginning of the current second * @property int $microsecondOfWeek The value of the microsecond starting from the beginning of the current week * @property int $microsecondOfYear The value of the microsecond starting from the beginning of the current year * @property int $millisecondOfCentury The value of the millisecond starting from the beginning of the current century * @property int $millisecondOfDay The value of the millisecond starting from the beginning of the current day * @property int $millisecondOfDecade The value of the millisecond starting from the beginning of the current decade * @property int $millisecondOfHour The value of the millisecond starting from the beginning of the current hour * @property int $millisecondOfMillennium The value of the millisecond starting from the beginning of the current millennium * @property int $millisecondOfMinute The value of the millisecond starting from the beginning of the current minute * @property int $millisecondOfMonth The value of the millisecond starting from the beginning of the current month * @property int $millisecondOfQuarter The value of the millisecond starting from the beginning of the current quarter * @property int $millisecondOfSecond The value of the millisecond starting from the beginning of the current second * @property int $millisecondOfWeek The value of the millisecond starting from the beginning of the current week * @property int $millisecondOfYear The value of the millisecond starting from the beginning of the current year * @property int $minuteOfCentury The value of the minute starting from the beginning of the current century * @property int $minuteOfDay The value of the minute starting from the beginning of the current day * @property int $minuteOfDecade The value of the minute starting from the beginning of the current decade * @property int $minuteOfHour The value of the minute starting from the beginning of the current hour * @property int $minuteOfMillennium The value of the minute starting from the beginning of the current millennium * @property int $minuteOfMonth The value of the minute starting from the beginning of the current month * @property int $minuteOfQuarter The value of the minute starting from the beginning of the current quarter * @property int $minuteOfWeek The value of the minute starting from the beginning of the current week * @property int $minuteOfYear The value of the minute starting from the beginning of the current year * @property int $monthOfCentury The value of the month starting from the beginning of the current century * @property int $monthOfDecade The value of the month starting from the beginning of the current decade * @property int $monthOfMillennium The value of the month starting from the beginning of the current millennium * @property int $monthOfQuarter The value of the month starting from the beginning of the current quarter * @property int $monthOfYear The value of the month starting from the beginning of the current year * @property int $quarterOfCentury The value of the quarter starting from the beginning of the current century * @property int $quarterOfDecade The value of the quarter starting from the beginning of the current decade * @property int $quarterOfMillennium The value of the quarter starting from the beginning of the current millennium * @property int $quarterOfYear The value of the quarter starting from the beginning of the current year * @property int $secondOfCentury The value of the second starting from the beginning of the current century * @property int $secondOfDay The value of the second starting from the beginning of the current day * @property int $secondOfDecade The value of the second starting from the beginning of the current decade * @property int $secondOfHour The value of the second starting from the beginning of the current hour * @property int $secondOfMillennium The value of the second starting from the beginning of the current millennium * @property int $secondOfMinute The value of the second starting from the beginning of the current minute * @property int $secondOfMonth The value of the second starting from the beginning of the current month * @property int $secondOfQuarter The value of the second starting from the beginning of the current quarter * @property int $secondOfWeek The value of the second starting from the beginning of the current week * @property int $secondOfYear The value of the second starting from the beginning of the current year * @property int $weekOfCentury The value of the week starting from the beginning of the current century * @property int $weekOfDecade The value of the week starting from the beginning of the current decade * @property int $weekOfMillennium The value of the week starting from the beginning of the current millennium * @property int $weekOfMonth 1 through 5 * @property int $weekOfQuarter The value of the week starting from the beginning of the current quarter * @property int $weekOfYear ISO-8601 week number of year, weeks starting on Monday * @property int $yearOfCentury The value of the year starting from the beginning of the current century * @property int $yearOfDecade The value of the year starting from the beginning of the current decade * @property int $yearOfMillennium The value of the year starting from the beginning of the current millennium * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read int $noZeroHour current hour from 1 to 24 * @property-read int $isoWeeksInYear 51 through 53 * @property-read int $weekNumberInMonth 1 through 5 * @property-read int $firstWeekDay 0 through 6 * @property-read int $lastWeekDay 0 through 6 * @property-read int $quarter the quarter of this instance, 1 - 4 * @property-read int $decade the decade of this instance * @property-read int $century the century of this instance * @property-read int $millennium the millennium of this instance * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise * @property-read bool $local checks if the timezone is local, true if local, false otherwise * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise * @property-read string $timezoneName the current timezone name * @property-read string $tzName alias of $timezoneName * @property-read string $locale locale of the current instance * @property-read int $centuriesInMillennium The number of centuries contained in the current millennium * @property-read int $daysInCentury The number of days contained in the current century * @property-read int $daysInDecade The number of days contained in the current decade * @property-read int $daysInMillennium The number of days contained in the current millennium * @property-read int $daysInMonth number of days in the given month * @property-read int $daysInQuarter The number of days contained in the current quarter * @property-read int $daysInWeek The number of days contained in the current week * @property-read int $daysInYear 365 or 366 * @property-read int $decadesInCentury The number of decades contained in the current century * @property-read int $decadesInMillennium The number of decades contained in the current millennium * @property-read int $hoursInCentury The number of hours contained in the current century * @property-read int $hoursInDay The number of hours contained in the current day * @property-read int $hoursInDecade The number of hours contained in the current decade * @property-read int $hoursInMillennium The number of hours contained in the current millennium * @property-read int $hoursInMonth The number of hours contained in the current month * @property-read int $hoursInQuarter The number of hours contained in the current quarter * @property-read int $hoursInWeek The number of hours contained in the current week * @property-read int $hoursInYear The number of hours contained in the current year * @property-read int $microsecondsInCentury The number of microseconds contained in the current century * @property-read int $microsecondsInDay The number of microseconds contained in the current day * @property-read int $microsecondsInDecade The number of microseconds contained in the current decade * @property-read int $microsecondsInHour The number of microseconds contained in the current hour * @property-read int $microsecondsInMillennium The number of microseconds contained in the current millennium * @property-read int $microsecondsInMillisecond The number of microseconds contained in the current millisecond * @property-read int $microsecondsInMinute The number of microseconds contained in the current minute * @property-read int $microsecondsInMonth The number of microseconds contained in the current month * @property-read int $microsecondsInQuarter The number of microseconds contained in the current quarter * @property-read int $microsecondsInSecond The number of microseconds contained in the current second * @property-read int $microsecondsInWeek The number of microseconds contained in the current week * @property-read int $microsecondsInYear The number of microseconds contained in the current year * @property-read int $millisecondsInCentury The number of milliseconds contained in the current century * @property-read int $millisecondsInDay The number of milliseconds contained in the current day * @property-read int $millisecondsInDecade The number of milliseconds contained in the current decade * @property-read int $millisecondsInHour The number of milliseconds contained in the current hour * @property-read int $millisecondsInMillennium The number of milliseconds contained in the current millennium * @property-read int $millisecondsInMinute The number of milliseconds contained in the current minute * @property-read int $millisecondsInMonth The number of milliseconds contained in the current month * @property-read int $millisecondsInQuarter The number of milliseconds contained in the current quarter * @property-read int $millisecondsInSecond The number of milliseconds contained in the current second * @property-read int $millisecondsInWeek The number of milliseconds contained in the current week * @property-read int $millisecondsInYear The number of milliseconds contained in the current year * @property-read int $minutesInCentury The number of minutes contained in the current century * @property-read int $minutesInDay The number of minutes contained in the current day * @property-read int $minutesInDecade The number of minutes contained in the current decade * @property-read int $minutesInHour The number of minutes contained in the current hour * @property-read int $minutesInMillennium The number of minutes contained in the current millennium * @property-read int $minutesInMonth The number of minutes contained in the current month * @property-read int $minutesInQuarter The number of minutes contained in the current quarter * @property-read int $minutesInWeek The number of minutes contained in the current week * @property-read int $minutesInYear The number of minutes contained in the current year
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
true
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Factory.php
src/Carbon/Factory.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Closure; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use InvalidArgumentException; use ReflectionMethod; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A factory to generate Carbon instances with common settings. * * <autodoc generated by `composer phpdoc`> * * @method bool canBeCreatedFromFormat(?string $date, string $format) Checks if the (date)time string is in a given format and valid to create a * new instance. * @method ?Carbon create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null) Create a new Carbon instance from a specific date and time. * If any of $year, $month or $day are set to null their now() values will * be used. * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * If $hour is not null then the default values for $minute and $second * will be 0. * @method Carbon createFromDate($year = null, $month = null, $day = null, $timezone = null) Create a Carbon instance from just a date. The time portion is set to now. * @method ?Carbon createFromFormat($format, $time, $timezone = null) Create a Carbon instance from a specific format. * @method ?Carbon createFromIsoFormat(string $format, string $time, $timezone = null, ?string $locale = 'en', ?TranslatorInterface $translator = null) Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * @method ?Carbon createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null) Create a Carbon instance from a specific format and a string in a given language. * @method ?Carbon createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null) Create a Carbon instance from a specific ISO format and a string in a given language. * @method Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null) Create a Carbon instance from just a time. The date portion is set to today. * @method Carbon createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a time string. The date portion is set to today. * @method Carbon createFromTimestamp(string|int|float $timestamp, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a timestamp and set the timezone (UTC by default). * Timestamp input can be given as int, float or a string containing one or more numbers. * @method Carbon createFromTimestampMs(string|int|float $timestamp, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a timestamp in milliseconds. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method Carbon createFromTimestampMsUTC($timestamp) Create a Carbon instance from a timestamp in milliseconds. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method Carbon createFromTimestampUTC(string|int|float $timestamp) Create a Carbon instance from a timestamp keeping the timezone to UTC. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method Carbon createMidnightDate($year = null, $month = null, $day = null, $timezone = null) Create a Carbon instance from just a date. The time portion is set to midnight. * @method ?Carbon createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null) Create a new safe Carbon instance from a specific date and time. * If any of $year, $month or $day are set to null their now() values will * be used. * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * If $hour is not null then the default values for $minute and $second * will be 0. * If one of the set values is not valid, an InvalidDateException * will be thrown. * @method Carbon createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null) Create a new Carbon instance from a specific date and time using strict validation. * @method mixed executeWithLocale(string $locale, callable $func) Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * @method Carbon fromSerialized($value, array $options = []) Create an instance from a serialized string. * If $value is not from a trusted source, consider using the allowed_classes option to limit * the types of objects that can be built, for instance: * @method array getAvailableLocales() Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * @method Language[] getAvailableLocalesInfo() Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * @method array getDays() Get the days of the week. * @method ?string getFallbackLocale() Get the fallback locale. * @method array getFormatsToIsoReplacements() List of replacements from date() format to isoFormat(). * @method array getIsoUnits() Returns list of locale units for ISO formatting. * @method array|false getLastErrors() {@inheritdoc} * @method string getLocale() Get the current translator locale. * @method int getMidDayAt() get midday/noon hour * @method string getTimeFormatByPrecision(string $unitPrecision) Return a format from H:i to H:i:s.u according to given unit precision. * @method string|Closure|null getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) Returns raw translation message for a given key. * @method int getWeekEndsAt(?string $locale = null) Get the last day of week. * @method int getWeekStartsAt(?string $locale = null) Get the first day of week. * @method bool hasRelativeKeywords(?string $time) Determine if a time string will produce a relative date. * @method Carbon instance(DateTimeInterface $date) Create a Carbon instance from a DateTime one. * @method bool isImmutable() Returns true if the current class/instance is immutable. * @method bool isModifiableUnit($unit) Returns true if a property can be changed via setter. * @method bool isMutable() Returns true if the current class/instance is mutable. * @method bool localeHasDiffOneDayWords(string $locale) Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * @method bool localeHasDiffSyntax(string $locale) Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * @method bool localeHasDiffTwoDayWords(string $locale) Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * @method bool localeHasPeriodSyntax($locale) Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * @method bool localeHasShortUnits(string $locale) Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * @method ?Carbon make($var, DateTimeZone|string|null $timezone = null) Make a Carbon instance from given variable if possible. * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * @method void mixin(object|string $mixin) Mix another object into the class. * @method Carbon now(DateTimeZone|string|int|null $timezone = null) Get a Carbon instance for the current date and time. * @method Carbon parse(DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a string. * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * @method Carbon parseFromLocale(string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * @method string pluralUnit(string $unit) Returns standardized plural of a given singular/plural unit name (in English). * @method ?Carbon rawCreateFromFormat(string $format, string $time, $timezone = null) Create a Carbon instance from a specific format. * @method Carbon rawParse(DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a string. * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * @method void setFallbackLocale(string $locale) Set the fallback locale. * @method void setLocale(string $locale) Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * @method void setMidDayAt($hour) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider mid-day is always 12pm, then if you need to test if it's an other * hour, test it explicitly: * $date->format('G') == 13 * or to set explicitly to a given hour: * $date->setTime(13, 0, 0, 0) * Set midday/noon hour * @method string singularUnit(string $unit) Returns standardized singular of a given singular/plural unit name (in English). * @method void sleep(int|float $seconds) * @method Carbon today(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for today. * @method Carbon tomorrow(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for tomorrow. * @method string translateTimeString(string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL) Translate a time string from a locale to an other. * @method string translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null) Translate using translation string or callback available. * @method Carbon yesterday(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for yesterday. * * </autodoc> */ class Factory { protected string $className = Carbon::class; protected array $settings = []; /** * A test Carbon instance to be returned when now instances are created. */ protected Closure|CarbonInterface|null $testNow = null; /** * The timezone to restore to when clearing the time mock. */ protected ?string $testDefaultTimezone = null; /** * Is true when test-now is generated by a closure and timezone should be taken on the fly from it. */ protected bool $useTimezoneFromTestNow = false; /** * Default translator. */ protected TranslatorInterface $translator; /** * Days of weekend. */ protected array $weekendDays = [ CarbonInterface::SATURDAY, CarbonInterface::SUNDAY, ]; /** * Format regex patterns. * * @var array<string, string> */ protected array $regexFormats = [ 'd' => '(3[01]|[12][0-9]|0[1-9])', 'D' => '(Sun|Mon|Tue|Wed|Thu|Fri|Sat)', 'j' => '([123][0-9]|[1-9])', 'l' => '([a-zA-Z]{2,})', 'N' => '([1-7])', 'S' => '(st|nd|rd|th)', 'w' => '([0-6])', 'z' => '(36[0-5]|3[0-5][0-9]|[12][0-9]{2}|[1-9]?[0-9])', 'W' => '(5[012]|[1-4][0-9]|0?[1-9])', 'F' => '([a-zA-Z]{2,})', 'm' => '(1[012]|0[1-9])', 'M' => '([a-zA-Z]{3})', 'n' => '(1[012]|[1-9])', 't' => '(2[89]|3[01])', 'L' => '(0|1)', 'o' => '([1-9][0-9]{0,4})', 'Y' => '([1-9]?[0-9]{4})', 'y' => '([0-9]{2})', 'a' => '(am|pm)', 'A' => '(AM|PM)', 'B' => '([0-9]{3})', 'g' => '(1[012]|[1-9])', 'G' => '(2[0-3]|1?[0-9])', 'h' => '(1[012]|0[1-9])', 'H' => '(2[0-3]|[01][0-9])', 'i' => '([0-5][0-9])', 's' => '([0-5][0-9])', 'u' => '([0-9]{1,6})', 'v' => '([0-9]{1,3})', 'e' => '([a-zA-Z]{1,5})|([a-zA-Z]*\\/[a-zA-Z]*)', 'I' => '(0|1)', 'O' => '([+-](1[0123]|0[0-9])[0134][05])', 'P' => '([+-](1[0123]|0[0-9]):[0134][05])', 'p' => '(Z|[+-](1[0123]|0[0-9]):[0134][05])', 'T' => '([a-zA-Z]{1,5})', 'Z' => '(-?[1-5]?[0-9]{1,4})', 'U' => '([0-9]*)', // The formats below are combinations of the above formats. 'c' => '(([1-9]?[0-9]{4})-(1[012]|0[1-9])-(3[01]|[12][0-9]|0[1-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])[+-](1[012]|0[0-9]):([0134][05]))', // Y-m-dTH:i:sP 'r' => '(([a-zA-Z]{3}), ([123][0-9]|0[1-9]) ([a-zA-Z]{3}) ([1-9]?[0-9]{4}) (2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]) [+-](1[012]|0[0-9])([0134][05]))', // D, d M Y H:i:s O ]; /** * Format modifiers (such as available in createFromFormat) regex patterns. * * @var array */ protected array $regexFormatModifiers = [ '*' => '.+', ' ' => '[ ]', '#' => '[;:\\/.,()-]', '?' => '([^a]|[a])', '!' => '', '|' => '', '+' => '', ]; public function __construct(array $settings = [], ?string $className = null) { if ($className) { $this->className = $className; } $this->settings = $settings; } public function getClassName(): string { return $this->className; } public function setClassName(string $className): self { $this->className = $className; return $this; } public function className(?string $className = null): self|string { return $className === null ? $this->getClassName() : $this->setClassName($className); } public function getSettings(): array { return $this->settings; } public function setSettings(array $settings): self { $this->settings = $settings; return $this; } public function settings(?array $settings = null): self|array { return $settings === null ? $this->getSettings() : $this->setSettings($settings); } public function mergeSettings(array $settings): self { $this->settings = array_merge($this->settings, $settings); return $this; } public function setHumanDiffOptions(int $humanDiffOptions): void { $this->mergeSettings([ 'humanDiffOptions' => $humanDiffOptions, ]); } public function enableHumanDiffOption($humanDiffOption): void { $this->setHumanDiffOptions($this->getHumanDiffOptions() | $humanDiffOption); } public function disableHumanDiffOption(int $humanDiffOption): void { $this->setHumanDiffOptions($this->getHumanDiffOptions() & ~$humanDiffOption); } public function getHumanDiffOptions(): int { return (int) ($this->getSettings()['humanDiffOptions'] ?? 0); } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * $userSettings = [ * 'locale' => 'pt', * 'timezone' => 'America/Sao_Paulo', * ]; * $factory->macro('userFormat', function () use ($userSettings) { * return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar(); * }); * echo $factory->yesterday()->hours(11)->userFormat(); * ``` * * @param-closure-this static $macro */ public function macro(string $name, ?callable $macro): void { $macros = $this->getSettings()['macros'] ?? []; $macros[$name] = $macro; $this->mergeSettings([ 'macros' => $macros, ]); } /** * Remove all macros and generic macros. */ public function resetMacros(): void { $this->mergeSettings([ 'macros' => null, 'genericMacros' => null, ]); } /** * Register a custom macro. * * @param callable $macro * @param int $priority marco with higher priority is tried first * * @return void */ public function genericMacro(callable $macro, int $priority = 0): void { $genericMacros = $this->getSettings()['genericMacros'] ?? []; if (!isset($genericMacros[$priority])) { $genericMacros[$priority] = []; krsort($genericMacros, SORT_NUMERIC); } $genericMacros[$priority][] = $macro; $this->mergeSettings([ 'genericMacros' => $genericMacros, ]); } /** * Checks if macro is registered globally. */ public function hasMacro(string $name): bool { return isset($this->getSettings()['macros'][$name]); } /** * Get the raw callable macro registered globally for a given name. */ public function getMacro(string $name): ?callable { return $this->getSettings()['macros'][$name] ?? null; } /** * Set the default translator instance to use. */ public function setTranslator(TranslatorInterface $translator): void { $this->translator = $translator; } /** * Initialize the default translator instance if necessary. */ public function getTranslator(): TranslatorInterface { return $this->translator ??= Translator::get(); } /** * Reset the format used to the default when type juggling a Carbon instance to a string * * @return void */ public function resetToStringFormat(): void { $this->setToStringFormat(null); } /** * Set the default format used when type juggling a Carbon instance to a string. */ public function setToStringFormat(string|Closure|null $format): void { $this->mergeSettings([ 'toStringFormat' => $format, ]); } /** * JSON serialize all Carbon instances using the given callback. */ public function serializeUsing(string|callable|null $format): void { $this->mergeSettings([ 'toJsonFormat' => $format, ]); } /** * Enable the strict mode (or disable with passing false). */ public function useStrictMode(bool $strictModeEnabled = true): void { $this->mergeSettings([ 'strictMode' => $strictModeEnabled, ]); } /** * Returns true if the strict mode is globally in use, false else. * (It can be overridden in specific instances.) */ public function isStrictModeEnabled(): bool { return $this->getSettings()['strictMode'] ?? true; } /** * Indicates if months should be calculated with overflow. */ public function useMonthsOverflow(bool $monthsOverflow = true): void { $this->mergeSettings([ 'monthOverflow' => $monthsOverflow, ]); } /** * Reset the month overflow behavior. */ public function resetMonthsOverflow(): void { $this->useMonthsOverflow(); } /**
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
true
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/TranslatorStrongTypeInterface.php
src/Carbon/TranslatorStrongTypeInterface.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Symfony\Component\Translation\MessageCatalogueInterface; /** * Mark translator using strong type from symfony/translation >= 6. */ interface TranslatorStrongTypeInterface { public function getFromCatalogue(MessageCatalogueInterface $catalogue, string $id, string $domain = 'messages'); }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/WrapperClock.php
src/Carbon/WrapperClock.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Psr\Clock\ClockInterface as PsrClockInterface; use RuntimeException; use Symfony\Component\Clock\ClockInterface; final class WrapperClock implements ClockInterface { public function __construct( private PsrClockInterface|Factory|DateTimeInterface $currentClock, ) { } public function unwrap(): PsrClockInterface|Factory|DateTimeInterface { return $this->currentClock; } public function getFactory(): Factory { if ($this->currentClock instanceof Factory) { return $this->currentClock; } if ($this->currentClock instanceof DateTime) { $factory = new Factory(); $factory->setTestNowAndTimezone($this->currentClock); return $factory; } if ($this->currentClock instanceof DateTimeImmutable) { $factory = new FactoryImmutable(); $factory->setTestNowAndTimezone($this->currentClock); return $factory; } $factory = new FactoryImmutable(); $factory->setTestNowAndTimezone(fn () => $this->currentClock->now()); return $factory; } private function nowRaw(): DateTimeInterface { if ($this->currentClock instanceof DateTimeInterface) { return $this->currentClock; } if ($this->currentClock instanceof Factory) { return $this->currentClock->__call('now', []); } return $this->currentClock->now(); } public function now(): DateTimeImmutable { $now = $this->nowRaw(); return $now instanceof DateTimeImmutable ? $now : new CarbonImmutable($now); } /** * @template T of CarbonInterface * * @param class-string<T> $class * * @return T */ public function nowAs(string $class, DateTimeZone|string|int|null $timezone = null): CarbonInterface { $now = $this->nowRaw(); $date = $now instanceof $class ? $now : $class::instance($now); return $timezone === null ? $date : $date->setTimezone($timezone); } public function nowAsCarbon(DateTimeZone|string|int|null $timezone = null): CarbonInterface { $now = $this->nowRaw(); return $now instanceof CarbonInterface ? ($timezone === null ? $now : $now->setTimezone($timezone)) : $this->dateAsCarbon($now, $timezone); } private function dateAsCarbon(DateTimeInterface $date, DateTimeZone|string|int|null $timezone): CarbonInterface { return $date instanceof DateTimeImmutable ? new CarbonImmutable($date, $timezone) : new Carbon($date, $timezone); } public function sleep(float|int $seconds): void { if ($seconds === 0 || $seconds === 0.0) { return; } if ($seconds < 0) { throw new RuntimeException('Expected positive number of seconds, '.$seconds.' given'); } if ($this->currentClock instanceof DateTimeInterface) { $this->currentClock = $this->addSeconds($this->currentClock, $seconds); return; } if ($this->currentClock instanceof ClockInterface) { $this->currentClock->sleep($seconds); return; } $this->currentClock = $this->addSeconds($this->currentClock->now(), $seconds); } public function withTimeZone(DateTimeZone|string $timezone): static { if ($this->currentClock instanceof ClockInterface) { return new self($this->currentClock->withTimeZone($timezone)); } $now = $this->currentClock instanceof DateTimeInterface ? $this->currentClock : $this->currentClock->now(); if (!($now instanceof DateTimeImmutable)) { $now = clone $now; } if (\is_string($timezone)) { $timezone = new DateTimeZone($timezone); } return new self($now->setTimezone($timezone)); } private function addSeconds(DateTimeInterface $date, float|int $seconds): DateTimeInterface { $secondsPerHour = CarbonInterface::SECONDS_PER_MINUTE * CarbonInterface::MINUTES_PER_HOUR; $hours = number_format( floor($seconds / $secondsPerHour), thousands_separator: '', ); $microseconds = number_format( ($seconds - $hours * $secondsPerHour) * CarbonInterface::MICROSECONDS_PER_SECOND, thousands_separator: '', ); if (!($date instanceof DateTimeImmutable)) { $date = clone $date; } if ($hours !== '0') { $date = $date->modify("$hours hours"); } if ($microseconds !== '0') { $date = $date->modify("$microseconds microseconds"); } return $date; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/AbstractTranslator.php
src/Carbon/AbstractTranslator.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\MessageFormatter\MessageFormatterMapper; use Closure; use ReflectionException; use ReflectionFunction; use ReflectionProperty; use Symfony\Component\Translation\Formatter\MessageFormatterInterface; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Translator as SymfonyTranslator; use Throwable; abstract class AbstractTranslator extends SymfonyTranslator { public const REGION_CODE_LENGTH = 2; /** * Translator singletons for each language. * * @var array */ protected static array $singletons = []; /** * List of custom localized messages. * * @var array */ protected array $messages = []; /** * List of custom directories that contain translation files. * * @var string[] */ protected array $directories = []; /** * Set to true while constructing. */ protected bool $initializing = false; /** * List of locales aliases. * * @var array<string, string> */ protected array $aliases = [ 'me' => 'sr_Latn_ME', 'scr' => 'sh', ]; /** * Return a singleton instance of Translator. * * @param string|null $locale optional initial locale ("en" - english by default) * * @return static */ public static function get(?string $locale = null): static { $locale = $locale ?: 'en'; $key = static::class === Translator::class ? $locale : static::class.'|'.$locale; $count = \count(static::$singletons); // Remember only the last 10 translators created if ($count > 10) { foreach (\array_slice(array_keys(static::$singletons), 0, $count - 10) as $index) { unset(static::$singletons[$index]); } } static::$singletons[$key] ??= new static($locale); return static::$singletons[$key]; } public function __construct($locale, ?MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false) { $this->initialize($locale, $formatter, $cacheDir, $debug); } /** * Returns the list of directories translation files are searched in. */ public function getDirectories(): array { return $this->directories; } /** * Set list of directories translation files are searched in. * * @param array $directories new directories list * * @return $this */ public function setDirectories(array $directories): static { $this->directories = $directories; return $this; } /** * Add a directory to the list translation files are searched in. * * @param string $directory new directory * * @return $this */ public function addDirectory(string $directory): static { $this->directories[] = $directory; return $this; } /** * Remove a directory from the list translation files are searched in. * * @param string $directory directory path * * @return $this */ public function removeDirectory(string $directory): static { $search = rtrim(strtr($directory, '\\', '/'), '/'); return $this->setDirectories(array_filter( $this->getDirectories(), static fn ($item) => rtrim(strtr($item, '\\', '/'), '/') !== $search, )); } /** * Reset messages of a locale (all locale if no locale passed). * Remove custom messages and reload initial messages from matching * file in Lang directory. */ public function resetMessages(?string $locale = null): bool { if ($locale === null) { $this->messages = []; $this->catalogues = []; $this->modifyResources(static function (array $resources): array { foreach ($resources as &$list) { array_splice($list, 1); } return $resources; }); return true; } $this->assertValidLocale($locale); foreach ($this->getDirectories() as $directory) { $file = \sprintf('%s/%s.php', rtrim($directory, '\\/'), $locale); $data = @include $file; if ($data !== false) { $this->messages[$locale] = $data; unset($this->catalogues[$locale]); $this->modifyResources(static function (array $resources) use ($locale): array { unset($resources[$locale]); return $resources; }); $this->addResource('array', $this->messages[$locale], $locale); return true; } } return false; } /** * Returns the list of files matching a given locale prefix (or all if empty). * * @param string $prefix prefix required to filter result * * @return array */ public function getLocalesFiles(string $prefix = ''): array { $files = []; foreach ($this->getDirectories() as $directory) { foreach (self::getPhpFilesInDirectory(rtrim($directory, '\\/'), $prefix) as $file) { $files[] = $file; } } return array_unique($files); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @param string $prefix prefix required to filter result * * @return array */ public function getAvailableLocales(string $prefix = ''): array { return array_unique(array_merge( array_map( static fn (string $file) => substr($file, strrpos($file, '/') + 1, -4), $this->getLocalesFiles($prefix), ), array_keys($this->messages), )); } protected function translate(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string { $domain ??= 'messages'; $catalogue = $this->getCatalogue($locale); $format = $this instanceof TranslatorStrongTypeInterface ? $this->getFromCatalogue($catalogue, (string) $id, $domain) : $this->getCatalogue($locale)->get((string) $id, $domain); // @codeCoverageIgnore if ($format instanceof Closure) { // @codeCoverageIgnoreStart try { $count = (new ReflectionFunction($format))->getNumberOfRequiredParameters(); } catch (ReflectionException) { $count = 0; } // @codeCoverageIgnoreEnd return $format( ...array_values($parameters), ...array_fill(0, max(0, $count - \count($parameters)), null) ); } return parent::trans($id, $parameters, $domain, $locale); } /** * Init messages language from matching file in Lang directory. * * @param string $locale * * @return bool */ protected function loadMessagesFromFile(string $locale): bool { return isset($this->messages[$locale]) || $this->resetMessages($locale); } /** * Set messages of a locale and take file first if present. * * @param string $locale * @param array $messages * * @return $this */ public function setMessages(string $locale, array $messages): static { $this->loadMessagesFromFile($locale); $this->addResource('array', $messages, $locale); $this->messages[$locale] = array_merge( $this->messages[$locale] ?? [], $messages ); return $this; } /** * Set messages of the current locale and take file first if present. * * @param array $messages * * @return $this */ public function setTranslations(array $messages): static { return $this->setMessages($this->getLocale(), $messages); } /** * Get messages of a locale, if none given, return all the * languages. */ public function getMessages(?string $locale = null): array { return $locale === null ? $this->messages : $this->messages[$locale]; } /** * Set the current translator locale and indicate if the source locale file exists * * @param string $locale locale ex. en */ public function setLocale($locale): void { $locale = preg_replace_callback('/[-_]([a-z]{2,}|\d{2,})/', function ($matches) { // _2-letters or YUE is a region, _3+-letters is a variant $upper = strtoupper($matches[1]); if ($upper === 'YUE' || $upper === 'ISO' || \strlen($upper) <= static::REGION_CODE_LENGTH) { return "_$upper"; } return '_'.ucfirst($matches[1]); }, strtolower($locale)); $previousLocale = $this->getLocale(); if ($previousLocale === $locale && isset($this->messages[$locale])) { return; } unset(static::$singletons[$previousLocale]); if ($locale === 'auto') { $completeLocale = setlocale(LC_TIME, '0'); $locale = preg_replace('/^([^_.-]+).*$/', '$1', $completeLocale); $locales = $this->getAvailableLocales($locale); $completeLocaleChunks = preg_split('/[_.-]+/', $completeLocale); $getScore = static fn ($language) => self::compareChunkLists( $completeLocaleChunks, preg_split('/[_.-]+/', $language), ); usort($locales, static fn ($first, $second) => $getScore($second) <=> $getScore($first)); $locale = $locales[0] ?? 'en'; } if (isset($this->aliases[$locale])) { $locale = $this->aliases[$locale]; } // If the language is not provided by a Carbon file // and the tag contains a region (ex: en_CA), then // first load the macro (ex: en) to have a fallback if ( str_contains($locale, '_') && !\in_array($locale, self::getInternallySupportedLocales(), true) && $this->loadMessagesFromFile($macroLocale = preg_replace('/^([^_]+).*$/', '$1', $locale)) ) { parent::setLocale($macroLocale); } if (!$this->loadMessagesFromFile($locale) && !$this->initializing) { return; } parent::setLocale($locale); } /** * Show locale on var_dump(). * * @return array */ public function __debugInfo() { return [ 'locale' => $this->getLocale(), ]; } public function __serialize(): array { return [ 'locale' => $this->getLocale(), ]; } public function __unserialize(array $data): void { $this->initialize($data['locale'] ?? 'en'); } private function initialize($locale, ?MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false): void { parent::setLocale($locale); $this->initializing = true; $this->directories = [self::getDefaultLangDirectory()]; $this->addLoader('array', new ArrayLoader()); parent::__construct($locale, new MessageFormatterMapper($formatter), $cacheDir, $debug); $this->initializing = false; } private static function compareChunkLists($referenceChunks, $chunks) { $score = 0; foreach ($referenceChunks as $index => $chunk) { if (!isset($chunks[$index])) { $score++; continue; } if (strtolower($chunks[$index]) === strtolower($chunk)) { $score += 10; } } return $score; } /** @codeCoverageIgnore */ private function modifyResources(callable $callback): void { try { $resourcesProperty = new ReflectionProperty(SymfonyTranslator::class, 'resources'); $resources = $resourcesProperty->getValue($this); $resourcesProperty->setValue($this, $callback($resources)); } catch (Throwable) { // Clear resources if available, if not, then nothing to clean } } private static function getPhpFilesInDirectory(string $directory, string $prefix): array { if ($directory !== self::getDefaultLangDirectory()) { return glob("$directory/$prefix*.php") ?: []; } // If it's the internal Carbon directory we use a static list // which is faster than scanning the folder with glob() $locales = self::getInternallySupportedLocales(); if ($prefix !== '') { $locales = array_values(array_filter( self::getInternallySupportedLocales(), static fn (string $locale) => str_starts_with($locale, $prefix), )); } return array_map( static fn (string $locale) => "$directory/$locale.php", $locales, ); } private static function getDefaultLangDirectory(): string { return __DIR__.'/Lang'; } /** @return list<string> */ private static function getInternallySupportedLocales(): array { return [ 'aa', 'aa_DJ', 'aa_ER', 'aa_ER@saaho', 'aa_ET', 'af', 'af_NA', 'af_ZA', 'agq', 'agr', 'agr_PE', 'ak', 'ak_GH', 'am', 'am_ET', 'an', 'an_ES', 'anp', 'anp_IN', 'ar', 'ar_AE', 'ar_BH', 'ar_DJ', 'ar_DZ', 'ar_EG', 'ar_EH', 'ar_ER', 'ar_IL', 'ar_IN', 'ar_IQ', 'ar_JO', 'ar_KM', 'ar_KW', 'ar_LB', 'ar_LY', 'ar_MA', 'ar_MR', 'ar_OM', 'ar_PS', 'ar_QA', 'ar_SA', 'ar_SD', 'ar_SO', 'ar_SS', 'ar_SY', 'ar_Shakl', 'ar_TD', 'ar_TN', 'ar_YE', 'as', 'as_IN', 'asa', 'ast', 'ast_ES', 'ayc', 'ayc_PE', 'az', 'az_AZ', 'az_Arab', 'az_Cyrl', 'az_IR', 'az_Latn', 'bas', 'be', 'be_BY', 'be_BY@latin', 'bem', 'bem_ZM', 'ber', 'ber_DZ', 'ber_MA', 'bez', 'bg', 'bg_BG', 'bhb', 'bhb_IN', 'bho', 'bho_IN', 'bi', 'bi_VU', 'bm', 'bn', 'bn_BD', 'bn_IN', 'bo', 'bo_CN', 'bo_IN', 'br', 'br_FR', 'brx', 'brx_IN', 'bs', 'bs_BA', 'bs_Cyrl', 'bs_Latn', 'byn', 'byn_ER', 'ca', 'ca_AD', 'ca_ES', 'ca_ES_Valencia', 'ca_FR', 'ca_IT', 'ccp', 'ccp_IN', 'ce', 'ce_RU', 'cgg', 'chr', 'chr_US', 'ckb', 'cmn', 'cmn_TW', 'crh', 'crh_UA', 'cs', 'cs_CZ', 'csb', 'csb_PL', 'cu', 'cv', 'cv_RU', 'cy', 'cy_GB', 'da', 'da_DK', 'da_GL', 'dav', 'de', 'de_AT', 'de_BE', 'de_CH', 'de_DE', 'de_IT', 'de_LI', 'de_LU', 'dje', 'doi', 'doi_IN', 'dsb', 'dsb_DE', 'dua', 'dv', 'dv_MV', 'dyo', 'dz', 'dz_BT', 'ebu', 'ee', 'ee_TG', 'el', 'el_CY', 'el_GR', 'en', 'en_001', 'en_150', 'en_AG', 'en_AI', 'en_AS', 'en_AT', 'en_AU', 'en_BB', 'en_BE', 'en_BI', 'en_BM', 'en_BS', 'en_BW', 'en_BZ', 'en_CA', 'en_CC', 'en_CH', 'en_CK', 'en_CM', 'en_CX', 'en_CY', 'en_DE', 'en_DG', 'en_DK', 'en_DM', 'en_ER', 'en_FI', 'en_FJ', 'en_FK', 'en_FM', 'en_GB', 'en_GD', 'en_GG', 'en_GH', 'en_GI', 'en_GM', 'en_GU', 'en_GY', 'en_HK', 'en_IE', 'en_IL', 'en_IM', 'en_IN', 'en_IO', 'en_ISO', 'en_JE', 'en_JM', 'en_KE', 'en_KI', 'en_KN', 'en_KY', 'en_LC', 'en_LR', 'en_LS', 'en_MG', 'en_MH', 'en_MO', 'en_MP', 'en_MS', 'en_MT', 'en_MU', 'en_MW', 'en_MY', 'en_NA', 'en_NF', 'en_NG', 'en_NL', 'en_NR', 'en_NU', 'en_NZ', 'en_PG', 'en_PH', 'en_PK', 'en_PN', 'en_PR', 'en_PW', 'en_RW', 'en_SB', 'en_SC', 'en_SD', 'en_SE', 'en_SG', 'en_SH', 'en_SI', 'en_SL', 'en_SS', 'en_SX', 'en_SZ', 'en_TC', 'en_TK', 'en_TO', 'en_TT', 'en_TV', 'en_TZ', 'en_UG', 'en_UM', 'en_US', 'en_US_Posix', 'en_VC', 'en_VG', 'en_VI', 'en_VU', 'en_WS', 'en_ZA', 'en_ZM', 'en_ZW', 'eo', 'es', 'es_419', 'es_AR', 'es_BO', 'es_BR', 'es_BZ', 'es_CL', 'es_CO', 'es_CR', 'es_CU', 'es_DO', 'es_EA', 'es_EC', 'es_ES', 'es_GQ', 'es_GT', 'es_HN', 'es_IC', 'es_MX', 'es_NI', 'es_PA', 'es_PE', 'es_PH', 'es_PR', 'es_PY', 'es_SV', 'es_US', 'es_UY', 'es_VE', 'et', 'et_EE', 'eu', 'eu_ES', 'ewo', 'fa', 'fa_AF', 'fa_IR', 'ff', 'ff_CM', 'ff_GN', 'ff_MR', 'ff_SN', 'fi', 'fi_FI', 'fil', 'fil_PH', 'fo', 'fo_DK', 'fo_FO', 'fr', 'fr_BE', 'fr_BF', 'fr_BI', 'fr_BJ', 'fr_BL', 'fr_CA', 'fr_CD', 'fr_CF', 'fr_CG', 'fr_CH', 'fr_CI', 'fr_CM', 'fr_DJ', 'fr_DZ', 'fr_FR', 'fr_GA', 'fr_GF', 'fr_GN', 'fr_GP', 'fr_GQ', 'fr_HT', 'fr_KM', 'fr_LU', 'fr_MA', 'fr_MC', 'fr_MF', 'fr_MG', 'fr_ML', 'fr_MQ', 'fr_MR', 'fr_MU', 'fr_NC', 'fr_NE', 'fr_PF', 'fr_PM', 'fr_RE', 'fr_RW', 'fr_SC', 'fr_SN', 'fr_SY', 'fr_TD', 'fr_TG', 'fr_TN', 'fr_VU', 'fr_WF', 'fr_YT', 'fur', 'fur_IT', 'fy', 'fy_DE', 'fy_NL', 'ga', 'ga_IE', 'gd', 'gd_GB', 'gez', 'gez_ER', 'gez_ET', 'gl', 'gl_ES', 'gom', 'gom_Latn', 'gsw', 'gsw_CH', 'gsw_FR', 'gsw_LI', 'gu', 'gu_IN', 'guz', 'gv', 'gv_GB', 'ha', 'ha_GH', 'ha_NE', 'ha_NG', 'hak', 'hak_TW', 'haw', 'he', 'he_IL', 'hi', 'hi_IN', 'hif', 'hif_FJ', 'hne', 'hne_IN', 'hr', 'hr_BA', 'hr_HR', 'hsb', 'hsb_DE', 'ht', 'ht_HT', 'hu', 'hu_HU', 'hy', 'hy_AM', 'i18n', 'ia', 'ia_FR', 'id', 'id_ID', 'ig', 'ig_NG', 'ii', 'ik', 'ik_CA', 'in', 'is', 'is_IS', 'it', 'it_CH', 'it_IT', 'it_SM', 'it_VA', 'iu', 'iu_CA', 'iw', 'ja', 'ja_JP', 'jgo', 'jmc', 'jv', 'ka', 'ka_GE', 'kab', 'kab_DZ', 'kam', 'kde', 'kea', 'khq', 'ki', 'kk', 'kk_KZ', 'kkj', 'kl', 'kl_GL', 'kln', 'km', 'km_KH', 'kn', 'kn_IN', 'ko', 'ko_KP', 'ko_KR', 'kok', 'kok_IN', 'ks', 'ks_IN', 'ks_IN@devanagari', 'ksb', 'ksf', 'ksh', 'ku', 'ku_TR', 'kw', 'kw_GB', 'ky', 'ky_KG', 'lag', 'lb', 'lb_LU', 'lg', 'lg_UG', 'li', 'li_NL', 'lij', 'lij_IT', 'lkt', 'ln', 'ln_AO', 'ln_CD', 'ln_CF', 'ln_CG', 'lo', 'lo_LA', 'lrc', 'lrc_IQ', 'lt', 'lt_LT', 'lu', 'luo', 'luy', 'lv', 'lv_LV', 'lzh', 'lzh_TW', 'mag', 'mag_IN', 'mai', 'mai_IN', 'mas', 'mas_TZ', 'mer', 'mfe', 'mfe_MU', 'mg', 'mg_MG', 'mgh', 'mgo', 'mhr', 'mhr_RU', 'mi', 'mi_NZ', 'miq', 'miq_NI', 'mjw', 'mjw_IN', 'mk', 'mk_MK', 'ml', 'ml_IN', 'mn', 'mn_MN', 'mni', 'mni_IN', 'mo', 'mr', 'mr_IN', 'ms', 'ms_BN', 'ms_MY', 'ms_SG', 'mt', 'mt_MT', 'mua', 'my', 'my_MM', 'mzn', 'nan', 'nan_TW', 'nan_TW@latin', 'naq', 'nb', 'nb_NO', 'nb_SJ', 'nd', 'nds', 'nds_DE', 'nds_NL', 'ne', 'ne_IN', 'ne_NP', 'nhn', 'nhn_MX', 'niu', 'niu_NU', 'nl', 'nl_AW', 'nl_BE', 'nl_BQ', 'nl_CW', 'nl_NL', 'nl_SR', 'nl_SX', 'nmg', 'nn', 'nn_NO', 'nnh', 'no', 'nr', 'nr_ZA', 'nso', 'nso_ZA', 'nus', 'nyn', 'oc', 'oc_FR', 'om', 'om_ET', 'om_KE', 'or', 'or_IN', 'os', 'os_RU', 'pa', 'pa_Arab', 'pa_Guru', 'pa_IN', 'pa_PK', 'pap', 'pap_AW', 'pap_CW', 'pl', 'pl_PL', 'prg', 'ps', 'ps_AF', 'pt', 'pt_AO', 'pt_BR', 'pt_CH', 'pt_CV', 'pt_GQ', 'pt_GW', 'pt_LU', 'pt_MO', 'pt_MZ', 'pt_PT', 'pt_ST', 'pt_TL', 'qu', 'qu_BO', 'qu_EC', 'quz', 'quz_PE', 'raj', 'raj_IN', 'rm', 'rn', 'ro', 'ro_MD', 'ro_RO', 'rof', 'ru', 'ru_BY', 'ru_KG', 'ru_KZ', 'ru_MD', 'ru_RU', 'ru_UA', 'rw', 'rw_RW', 'rwk', 'sa', 'sa_IN', 'sah', 'sah_RU', 'saq', 'sat', 'sat_IN', 'sbp', 'sc', 'sc_IT', 'sd', 'sd_IN', 'sd_IN@devanagari', 'se', 'se_FI', 'se_NO', 'se_SE', 'seh', 'ses', 'sg', 'sgs', 'sgs_LT', 'sh', 'shi', 'shi_Latn', 'shi_Tfng', 'shn', 'shn_MM', 'shs', 'shs_CA', 'si', 'si_LK', 'sid', 'sid_ET', 'sk', 'sk_SK', 'sl', 'sl_SI', 'sm', 'sm_WS', 'smn', 'sn', 'so', 'so_DJ', 'so_ET', 'so_KE', 'so_SO', 'sq', 'sq_AL', 'sq_MK', 'sq_XK', 'sr', 'sr_Cyrl', 'sr_Cyrl_BA', 'sr_Cyrl_ME', 'sr_Cyrl_XK', 'sr_Latn', 'sr_Latn_BA', 'sr_Latn_ME', 'sr_Latn_XK', 'sr_ME', 'sr_RS', 'sr_RS@latin', 'ss', 'ss_ZA', 'st', 'st_ZA', 'sv', 'sv_AX', 'sv_FI', 'sv_SE', 'sw', 'sw_CD', 'sw_KE', 'sw_TZ', 'sw_UG', 'szl', 'szl_PL', 'ta', 'ta_IN', 'ta_LK', 'ta_MY', 'ta_SG', 'tcy', 'tcy_IN', 'te', 'te_IN', 'teo', 'teo_KE', 'tet', 'tg', 'tg_TJ', 'th', 'th_TH', 'the', 'the_NP', 'ti', 'ti_ER', 'ti_ET', 'tig', 'tig_ER', 'tk', 'tk_TM', 'tl', 'tl_PH', 'tlh', 'tn', 'tn_ZA', 'to', 'to_TO', 'tpi', 'tpi_PG', 'tr', 'tr_CY', 'tr_TR', 'ts', 'ts_ZA', 'tt', 'tt_RU', 'tt_RU@iqtelif', 'twq', 'tzl', 'tzm', 'tzm_Latn', 'ug', 'ug_CN', 'uk', 'uk_UA', 'unm', 'unm_US', 'ur', 'ur_IN', 'ur_PK', 'uz', 'uz_Arab', 'uz_Cyrl', 'uz_Latn', 'uz_UZ', 'uz_UZ@cyrillic', 'vai', 'vai_Latn', 'vai_Vaii', 've', 've_ZA', 'vi', 'vi_VN', 'vo', 'vun', 'wa', 'wa_BE', 'wae', 'wae_CH', 'wal', 'wal_ET', 'wo', 'wo_SN', 'xh', 'xh_ZA', 'xog', 'yav', 'yi', 'yi_US', 'yo', 'yo_BJ', 'yo_NG', 'yue', 'yue_HK', 'yue_Hans', 'yue_Hant', 'yuw', 'yuw_PG', 'zgh', 'zh', 'zh_CN', 'zh_HK', 'zh_Hans', 'zh_Hans_HK', 'zh_Hans_MO', 'zh_Hans_SG', 'zh_Hant', 'zh_Hant_HK', 'zh_Hant_MO', 'zh_Hant_TW', 'zh_MO', 'zh_SG', 'zh_TW', 'zh_YUE', 'zu', 'zu_ZA', ]; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/CarbonPeriodImmutable.php
src/Carbon/CarbonPeriodImmutable.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; class CarbonPeriodImmutable extends CarbonPeriod { /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = CarbonImmutable::class; /** * Date class of iteration items. */ protected string $dateClass = CarbonImmutable::class; /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this->constructed ? clone $this : $this; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/FactoryImmutable.php
src/Carbon/FactoryImmutable.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Closure; use DateTimeInterface; use DateTimeZone; use Symfony\Component\Clock\ClockInterface; use Symfony\Component\Clock\NativeClock; use Symfony\Contracts\Translation\TranslatorInterface; /** * A factory to generate CarbonImmutable instances with common settings. * * <autodoc generated by `composer phpdoc`> * * @method bool canBeCreatedFromFormat(?string $date, string $format) Checks if the (date)time string is in a given format and valid to create a * new instance. * @method ?CarbonImmutable create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null) Create a new Carbon instance from a specific date and time. * If any of $year, $month or $day are set to null their now() values will * be used. * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * If $hour is not null then the default values for $minute and $second * will be 0. * @method CarbonImmutable createFromDate($year = null, $month = null, $day = null, $timezone = null) Create a Carbon instance from just a date. The time portion is set to now. * @method ?CarbonImmutable createFromFormat($format, $time, $timezone = null) Create a Carbon instance from a specific format. * @method ?CarbonImmutable createFromIsoFormat(string $format, string $time, $timezone = null, ?string $locale = 'en', ?TranslatorInterface $translator = null) Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * @method ?CarbonImmutable createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null) Create a Carbon instance from a specific format and a string in a given language. * @method ?CarbonImmutable createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null) Create a Carbon instance from a specific ISO format and a string in a given language. * @method CarbonImmutable createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null) Create a Carbon instance from just a time. The date portion is set to today. * @method CarbonImmutable createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a time string. The date portion is set to today. * @method CarbonImmutable createFromTimestamp(string|int|float $timestamp, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a timestamp and set the timezone (UTC by default). * Timestamp input can be given as int, float or a string containing one or more numbers. * @method CarbonImmutable createFromTimestampMs(string|int|float $timestamp, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a timestamp in milliseconds. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method CarbonImmutable createFromTimestampMsUTC($timestamp) Create a Carbon instance from a timestamp in milliseconds. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method CarbonImmutable createFromTimestampUTC(string|int|float $timestamp) Create a Carbon instance from a timestamp keeping the timezone to UTC. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method CarbonImmutable createMidnightDate($year = null, $month = null, $day = null, $timezone = null) Create a Carbon instance from just a date. The time portion is set to midnight. * @method ?CarbonImmutable createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null) Create a new safe Carbon instance from a specific date and time. * If any of $year, $month or $day are set to null their now() values will * be used. * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * If $hour is not null then the default values for $minute and $second * will be 0. * If one of the set values is not valid, an InvalidDateException * will be thrown. * @method CarbonImmutable createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null) Create a new Carbon instance from a specific date and time using strict validation. * @method mixed executeWithLocale(string $locale, callable $func) Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * @method CarbonImmutable fromSerialized($value, array $options = []) Create an instance from a serialized string. * If $value is not from a trusted source, consider using the allowed_classes option to limit * the types of objects that can be built, for instance: * @method array getAvailableLocales() Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * @method Language[] getAvailableLocalesInfo() Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * @method array getDays() Get the days of the week. * @method ?string getFallbackLocale() Get the fallback locale. * @method array getFormatsToIsoReplacements() List of replacements from date() format to isoFormat(). * @method array getIsoUnits() Returns list of locale units for ISO formatting. * @method array|false getLastErrors() {@inheritdoc} * @method string getLocale() Get the current translator locale. * @method int getMidDayAt() get midday/noon hour * @method string getTimeFormatByPrecision(string $unitPrecision) Return a format from H:i to H:i:s.u according to given unit precision. * @method string|Closure|null getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) Returns raw translation message for a given key. * @method int getWeekEndsAt(?string $locale = null) Get the last day of week. * @method int getWeekStartsAt(?string $locale = null) Get the first day of week. * @method bool hasRelativeKeywords(?string $time) Determine if a time string will produce a relative date. * @method CarbonImmutable instance(DateTimeInterface $date) Create a Carbon instance from a DateTime one. * @method bool isImmutable() Returns true if the current class/instance is immutable. * @method bool isModifiableUnit($unit) Returns true if a property can be changed via setter. * @method bool isMutable() Returns true if the current class/instance is mutable. * @method bool localeHasDiffOneDayWords(string $locale) Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * @method bool localeHasDiffSyntax(string $locale) Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * @method bool localeHasDiffTwoDayWords(string $locale) Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * @method bool localeHasPeriodSyntax($locale) Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * @method bool localeHasShortUnits(string $locale) Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * @method ?CarbonImmutable make($var, DateTimeZone|string|null $timezone = null) Make a Carbon instance from given variable if possible. * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * @method void mixin(object|string $mixin) Mix another object into the class. * @method CarbonImmutable parse(DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a string. * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * @method CarbonImmutable parseFromLocale(string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * @method string pluralUnit(string $unit) Returns standardized plural of a given singular/plural unit name (in English). * @method ?CarbonImmutable rawCreateFromFormat(string $format, string $time, $timezone = null) Create a Carbon instance from a specific format. * @method CarbonImmutable rawParse(DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a string. * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * @method void setFallbackLocale(string $locale) Set the fallback locale. * @method void setLocale(string $locale) Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * @method void setMidDayAt($hour) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider mid-day is always 12pm, then if you need to test if it's an other * hour, test it explicitly: * $date->format('G') == 13 * or to set explicitly to a given hour: * $date->setTime(13, 0, 0, 0) * Set midday/noon hour * @method string singularUnit(string $unit) Returns standardized singular of a given singular/plural unit name (in English). * @method CarbonImmutable today(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for today. * @method CarbonImmutable tomorrow(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for tomorrow. * @method string translateTimeString(string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL) Translate a time string from a locale to an other. * @method string translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null) Translate using translation string or callback available. * @method CarbonImmutable yesterday(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for yesterday. * * </autodoc> */ class FactoryImmutable extends Factory implements ClockInterface { protected string $className = CarbonImmutable::class; private static ?self $defaultInstance = null; private static ?WrapperClock $currentClock = null; /** * @internal Instance used for static calls, such as Carbon::getTranslator(), CarbonImmutable::setTestNow(), etc. */ public static function getDefaultInstance(): self { return self::$defaultInstance ??= new self(); } /** * @internal Instance used for static calls possibly called by non-static methods. */ public static function getInstance(): Factory { return self::$currentClock?->getFactory() ?? self::getDefaultInstance(); } /** * @internal Set instance before creating new dates. */ public static function setCurrentClock(ClockInterface|Factory|DateTimeInterface|null $currentClock): void { if ($currentClock && !($currentClock instanceof WrapperClock)) { $currentClock = new WrapperClock($currentClock); } self::$currentClock = $currentClock; } /** * @internal Instance used to link new object to their factory creator. */ public static function getCurrentClock(): ?WrapperClock { return self::$currentClock; } /** * Get a Carbon instance for the current date and time. */ public function now(DateTimeZone|string|int|null $timezone = null): CarbonImmutable { return $this->__call('now', [$timezone]); } public function sleep(int|float $seconds): void { if ($this->hasTestNow()) { $this->setTestNow($this->getTestNow()->avoidMutation()->addSeconds($seconds)); return; } (new NativeClock('UTC'))->sleep($seconds); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/CarbonInterval.php
src/Carbon/CarbonInterval.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH],
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
true
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidPeriodParameterException.php
src/Carbon/Exceptions/InvalidPeriodParameterException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidPeriodParameterException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/UnsupportedUnitException.php
src/Carbon/Exceptions/UnsupportedUnitException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use Exception; /** * @codeCoverageIgnore */ class UnsupportedUnitException extends UnitException { public function __construct(string $unit, int $code = 0, ?Exception $previous = null) { parent::__construct("Unsupported unit '$unit'", $code, $previous); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/NotLocaleAwareException.php
src/Carbon/Exceptions/NotLocaleAwareException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; use Throwable; class NotLocaleAwareException extends BaseInvalidArgumentException implements InvalidArgumentException { /** * Constructor. * * @param mixed $object * @param int $code * @param Throwable|null $previous */ public function __construct($object, $code = 0, ?Throwable $previous = null) { $dump = \is_object($object) ? \get_class($object) : \gettype($object); parent::__construct("$dump does neither implements Symfony\Contracts\Translation\LocaleAwareInterface nor getLocale() method.", $code, $previous); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidFormatException.php
src/Carbon/Exceptions/InvalidFormatException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidFormatException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidIntervalException.php
src/Carbon/Exceptions/InvalidIntervalException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidIntervalException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/UnitException.php
src/Carbon/Exceptions/UnitException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class UnitException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/UnknownMethodException.php
src/Carbon/Exceptions/UnknownMethodException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use BadMethodCallException as BaseBadMethodCallException; use Throwable; class UnknownMethodException extends BaseBadMethodCallException implements BadMethodCallException { /** * The method. * * @var string */ protected $method; /** * Constructor. * * @param string $method * @param int $code * @param Throwable|null $previous */ public function __construct($method, $code = 0, ?Throwable $previous = null) { $this->method = $method; parent::__construct("Method $method does not exist.", $code, $previous); } /** * Get the method. * * @return string */ public function getMethod(): string { return $this->method; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/NotACarbonClassException.php
src/Carbon/Exceptions/NotACarbonClassException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use Carbon\CarbonInterface; use InvalidArgumentException as BaseInvalidArgumentException; use Throwable; class NotACarbonClassException extends BaseInvalidArgumentException implements InvalidArgumentException { /** * The className. * * @var string */ protected $className; /** * Constructor. * * @param string $className * @param int $code * @param Throwable|null $previous */ public function __construct($className, $code = 0, ?Throwable $previous = null) { $this->className = $className; parent::__construct(\sprintf( 'Given class does not implement %s: %s', CarbonInterface::class, $className, ), $code, $previous); } /** * Get the className. * * @return string */ public function getClassName(): string { return $this->className; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/NotAPeriodException.php
src/Carbon/Exceptions/NotAPeriodException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class NotAPeriodException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/UnknownGetterException.php
src/Carbon/Exceptions/UnknownGetterException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; use Throwable; class UnknownGetterException extends BaseInvalidArgumentException implements InvalidArgumentException { /** * The getter. * * @var string */ protected $getter; /** * Constructor. * * @param string $getter getter name * @param int $code * @param Throwable|null $previous */ public function __construct($getter, $code = 0, ?Throwable $previous = null) { $this->getter = $getter; parent::__construct("Unknown getter '$getter'", $code, $previous); } /** * Get the getter. * * @return string */ public function getGetter(): string { return $this->getter; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/OutOfRangeException.php
src/Carbon/Exceptions/OutOfRangeException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; use Throwable; // This will extends OutOfRangeException instead of InvalidArgumentException since 3.0.0 // use OutOfRangeException as BaseOutOfRangeException; class OutOfRangeException extends BaseInvalidArgumentException implements InvalidArgumentException { /** * The unit or name of the value. * * @var string */ private $unit; /** * The range minimum. * * @var mixed */ private $min; /** * The range maximum. * * @var mixed */ private $max; /** * The invalid value. * * @var mixed */ private $value; /** * Constructor. * * @param string $unit * @param mixed $min * @param mixed $max * @param mixed $value * @param int $code * @param Throwable|null $previous */ public function __construct($unit, $min, $max, $value, $code = 0, ?Throwable $previous = null) { $this->unit = $unit; $this->min = $min; $this->max = $max; $this->value = $value; parent::__construct("$unit must be between $min and $max, $value given", $code, $previous); } /** * @return mixed */ public function getMax() { return $this->max; } /** * @return mixed */ public function getMin() { return $this->min; } /** * @return mixed */ public function getUnit() { return $this->unit; } /** * @return mixed */ public function getValue() { return $this->value; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/BadComparisonUnitException.php
src/Carbon/Exceptions/BadComparisonUnitException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use Throwable; class BadComparisonUnitException extends UnitException { /** * The unit. * * @var string */ protected $unit; /** * Constructor. * * @param string $unit * @param int $code * @param Throwable|null $previous */ public function __construct($unit, $code = 0, ?Throwable $previous = null) { $this->unit = $unit; parent::__construct("Bad comparison unit: '$unit'", $code, $previous); } /** * Get the unit. * * @return string */ public function getUnit(): string { return $this->unit; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidTypeException.php
src/Carbon/Exceptions/InvalidTypeException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidTypeException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidTimeZoneException.php
src/Carbon/Exceptions/InvalidTimeZoneException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidTimeZoneException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidPeriodDateException.php
src/Carbon/Exceptions/InvalidPeriodDateException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidPeriodDateException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/UnknownUnitException.php
src/Carbon/Exceptions/UnknownUnitException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use Throwable; class UnknownUnitException extends UnitException { /** * The unit. * * @var string */ protected $unit; /** * Constructor. * * @param string $unit * @param int $code * @param Throwable|null $previous */ public function __construct($unit, $code = 0, ?Throwable $previous = null) { $this->unit = $unit; parent::__construct("Unknown unit '$unit'.", $code, $previous); } /** * Get the unit. * * @return string */ public function getUnit(): string { return $this->unit; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/Exception.php
src/Carbon/Exceptions/Exception.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; interface Exception { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/BadFluentConstructorException.php
src/Carbon/Exceptions/BadFluentConstructorException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use BadMethodCallException as BaseBadMethodCallException; use Throwable; class BadFluentConstructorException extends BaseBadMethodCallException implements BadMethodCallException { /** * The method. * * @var string */ protected $method; /** * Constructor. * * @param string $method * @param int $code * @param Throwable|null $previous */ public function __construct($method, $code = 0, ?Throwable $previous = null) { $this->method = $method; parent::__construct(\sprintf("Unknown fluent constructor '%s'.", $method), $code, $previous); } /** * Get the method. * * @return string */ public function getMethod(): string { return $this->method; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/UnknownSetterException.php
src/Carbon/Exceptions/UnknownSetterException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; use Throwable; class UnknownSetterException extends BaseInvalidArgumentException implements BadMethodCallException { /** * The setter. * * @var string */ protected $setter; /** * Constructor. * * @param string $setter setter name * @param int $code * @param Throwable|null $previous */ public function __construct($setter, $code = 0, ?Throwable $previous = null) { $this->setter = $setter; parent::__construct("Unknown setter '$setter'", $code, $previous); } /** * Get the setter. * * @return string */ public function getSetter(): string { return $this->setter; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/EndLessPeriodException.php
src/Carbon/Exceptions/EndLessPeriodException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use RuntimeException as BaseRuntimeException; final class EndLessPeriodException extends BaseRuntimeException implements RuntimeException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/UnreachableException.php
src/Carbon/Exceptions/UnreachableException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use RuntimeException as BaseRuntimeException; class UnreachableException extends BaseRuntimeException implements RuntimeException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/RuntimeException.php
src/Carbon/Exceptions/RuntimeException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; interface RuntimeException extends Exception { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/BadMethodCallException.php
src/Carbon/Exceptions/BadMethodCallException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; interface BadMethodCallException extends Exception { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidCastException.php
src/Carbon/Exceptions/InvalidCastException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidCastException extends BaseInvalidArgumentException implements InvalidArgumentException { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidArgumentException.php
src/Carbon/Exceptions/InvalidArgumentException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; interface InvalidArgumentException extends Exception { // }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/BadFluentSetterException.php
src/Carbon/Exceptions/BadFluentSetterException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use BadMethodCallException as BaseBadMethodCallException; use Throwable; class BadFluentSetterException extends BaseBadMethodCallException implements BadMethodCallException { /** * The setter. * * @var string */ protected $setter; /** * Constructor. * * @param string $setter * @param int $code * @param Throwable|null $previous */ public function __construct($setter, $code = 0, ?Throwable $previous = null) { $this->setter = $setter; parent::__construct(\sprintf("Unknown fluent setter '%s'", $setter), $code, $previous); } /** * Get the setter. * * @return string */ public function getSetter(): string { return $this->setter; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/ParseErrorException.php
src/Carbon/Exceptions/ParseErrorException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; use Throwable; class ParseErrorException extends BaseInvalidArgumentException implements InvalidArgumentException { /** * The expected. * * @var string */ protected $expected; /** * The actual. * * @var string */ protected $actual; /** * The help message. * * @var string */ protected $help; /** * Constructor. * * @param string $expected * @param string $actual * @param int $code * @param Throwable|null $previous */ public function __construct($expected, $actual, $help = '', $code = 0, ?Throwable $previous = null) { $this->expected = $expected; $this->actual = $actual; $this->help = $help; $actual = $actual === '' ? 'data is missing' : "get '$actual'"; parent::__construct(trim("Format expected $expected but $actual\n$help"), $code, $previous); } /** * Get the expected. * * @return string */ public function getExpected(): string { return $this->expected; } /** * Get the actual. * * @return string */ public function getActual(): string { return $this->actual; } /** * Get the help message. * * @return string */ public function getHelp(): string { return $this->help; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/ImmutableException.php
src/Carbon/Exceptions/ImmutableException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use RuntimeException as BaseRuntimeException; use Throwable; class ImmutableException extends BaseRuntimeException implements RuntimeException { /** * The value. * * @var string */ protected $value; /** * Constructor. * * @param string $value the immutable type/value * @param int $code * @param Throwable|null $previous */ public function __construct($value, $code = 0, ?Throwable $previous = null) { $this->value = $value; parent::__construct("$value is immutable.", $code, $previous); } /** * Get the value. * * @return string */ public function getValue(): string { return $this->value; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/InvalidDateException.php
src/Carbon/Exceptions/InvalidDateException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use InvalidArgumentException as BaseInvalidArgumentException; use Throwable; class InvalidDateException extends BaseInvalidArgumentException implements InvalidArgumentException { /** * The invalid field. * * @var string */ private $field; /** * The invalid value. * * @var mixed */ private $value; /** * Constructor. * * @param string $field * @param mixed $value * @param int $code * @param Throwable|null $previous */ public function __construct($field, $value, $code = 0, ?Throwable $previous = null) { $this->field = $field; $this->value = $value; parent::__construct($field.' : '.$value.' is not a valid value.', $code, $previous); } /** * Get the invalid field. * * @return string */ public function getField() { return $this->field; } /** * Get the invalid value. * * @return mixed */ public function getValue() { return $this->value; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Exceptions/UnitNotConfiguredException.php
src/Carbon/Exceptions/UnitNotConfiguredException.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Exceptions; use Throwable; class UnitNotConfiguredException extends UnitException { /** * The unit. * * @var string */ protected $unit; /** * Constructor. * * @param string $unit * @param int $code * @param Throwable|null $previous */ public function __construct($unit, $code = 0, ?Throwable $previous = null) { $this->unit = $unit; parent::__construct("Unit $unit have no configuration to get total from other units.", $code, $previous); } /** * Get the unit. * * @return string */ public function getUnit(): string { return $this->unit; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/MessageFormatter/MessageFormatterMapper.php
src/Carbon/MessageFormatter/MessageFormatterMapper.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\MessageFormatter; use ReflectionMethod; use Symfony\Component\Translation\Formatter\MessageFormatter; use Symfony\Component\Translation\Formatter\MessageFormatterInterface; // @codeCoverageIgnoreStart $transMethod = new ReflectionMethod(MessageFormatterInterface::class, 'format'); require $transMethod->getParameters()[0]->hasType() ? __DIR__.'/../../../lazy/Carbon/MessageFormatter/MessageFormatterMapperStrongType.php' : __DIR__.'/../../../lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php'; // @codeCoverageIgnoreEnd final class MessageFormatterMapper extends LazyMessageFormatter { /** * Wrapped formatter. * * @var MessageFormatterInterface */ protected $formatter; public function __construct(?MessageFormatterInterface $formatter = null) { $this->formatter = $formatter ?? new MessageFormatter(); } protected function transformLocale(?string $locale): ?string { return $locale ? preg_replace('/[_@][A-Za-z][a-z]{2,}/', '', $locale) : $locale; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Traits/Modifiers.php
src/Carbon/Traits/Modifiers.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidFormatException; use ReturnTypeWillChange; /** * Trait Modifiers. * * Returns dates relative to current date using modifier short-hand. */ trait Modifiers { /** * Midday/noon hour. * * @var int */ protected static $midDayAt = 12; /** * get midday/noon hour * * @return int */ public static function getMidDayAt() { return static::$midDayAt; } /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider mid-day is always 12pm, then if you need to test if it's an other * hour, test it explicitly: * $date->format('G') == 13 * or to set explicitly to a given hour: * $date->setTime(13, 0, 0, 0) * * Set midday/noon hour * * @param int $hour midday hour * * @return void */ public static function setMidDayAt($hour) { static::$midDayAt = $hour; } /** * Modify to midday, default to self::$midDayAt * * @return static */ public function midDay() { return $this->setTime(static::$midDayAt, 0, 0, 0); } /** * Modify to the next occurrence of a given modifier such as a day of * the week. If no modifier is provided, modify to the next occurrence * of the current day of the week. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param string|int|null $modifier * * @return static */ public function next($modifier = null) { if ($modifier === null) { $modifier = $this->dayOfWeek; } return $this->change( 'next '.(\is_string($modifier) ? $modifier : static::$days[$modifier]), ); } /** * Go forward or backward to the next week- or weekend-day. * * @param bool $weekday * @param bool $forward * * @return static */ private function nextOrPreviousDay($weekday = true, $forward = true) { /** @var CarbonInterface $date */ $date = $this; $step = $forward ? 1 : -1; do { $date = $date->addDays($step); } while ($weekday ? $date->isWeekend() : $date->isWeekday()); return $date; } /** * Go forward to the next weekday. * * @return static */ public function nextWeekday() { return $this->nextOrPreviousDay(); } /** * Go backward to the previous weekday. * * @return static */ public function previousWeekday() { return $this->nextOrPreviousDay(true, false); } /** * Go forward to the next weekend day. * * @return static */ public function nextWeekendDay() { return $this->nextOrPreviousDay(false); } /** * Go backward to the previous weekend day. * * @return static */ public function previousWeekendDay() { return $this->nextOrPreviousDay(false, false); } /** * Modify to the previous occurrence of a given modifier such as a day of * the week. If no dayOfWeek is provided, modify to the previous occurrence * of the current day of the week. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param string|int|null $modifier * * @return static */ public function previous($modifier = null) { if ($modifier === null) { $modifier = $this->dayOfWeek; } return $this->change( 'last '.(\is_string($modifier) ? $modifier : static::$days[$modifier]), ); } /** * Modify to the first occurrence of a given day of the week * in the current month. If no dayOfWeek is provided, modify to the * first day of the current month. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek * * @return static */ public function firstOfMonth($dayOfWeek = null) { $date = $this->startOfDay(); if ($dayOfWeek === null) { return $date->day(1); } return $date->modify('first '.static::$days[$dayOfWeek].' of '.$date->rawFormat('F').' '.$date->year); } /** * Modify to the last occurrence of a given day of the week * in the current month. If no dayOfWeek is provided, modify to the * last day of the current month. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek * * @return static */ public function lastOfMonth($dayOfWeek = null) { $date = $this->startOfDay(); if ($dayOfWeek === null) { return $date->day($date->daysInMonth); } return $date->modify('last '.static::$days[$dayOfWeek].' of '.$date->rawFormat('F').' '.$date->year); } /** * Modify to the given occurrence of a given day of the week * in the current month. If the calculated occurrence is outside the scope * of the current month, then return false and no modifications are made. * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int $nth * @param int $dayOfWeek * * @return mixed */ public function nthOfMonth($nth, $dayOfWeek) { $date = $this->avoidMutation()->firstOfMonth(); $check = $date->rawFormat('Y-m'); $date = $date->modify('+'.$nth.' '.static::$days[$dayOfWeek]); return $date->rawFormat('Y-m') === $check ? $this->modify((string) $date) : false; } /** * Modify to the first occurrence of a given day of the week * in the current quarter. If no dayOfWeek is provided, modify to the * first day of the current quarter. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek day of the week default null * * @return static */ public function firstOfQuarter($dayOfWeek = null) { return $this->setDate($this->year, $this->quarter * static::MONTHS_PER_QUARTER - 2, 1)->firstOfMonth($dayOfWeek); } /** * Modify to the last occurrence of a given day of the week * in the current quarter. If no dayOfWeek is provided, modify to the * last day of the current quarter. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek day of the week default null * * @return static */ public function lastOfQuarter($dayOfWeek = null) { return $this->setDate($this->year, $this->quarter * static::MONTHS_PER_QUARTER, 1)->lastOfMonth($dayOfWeek); } /** * Modify to the given occurrence of a given day of the week * in the current quarter. If the calculated occurrence is outside the scope * of the current quarter, then return false and no modifications are made. * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int $nth * @param int $dayOfWeek * * @return mixed */ public function nthOfQuarter($nth, $dayOfWeek) { $date = $this->avoidMutation()->day(1)->month($this->quarter * static::MONTHS_PER_QUARTER); $lastMonth = $date->month; $year = $date->year; $date = $date->firstOfQuarter()->modify('+'.$nth.' '.static::$days[$dayOfWeek]); return ($lastMonth < $date->month || $year !== $date->year) ? false : $this->modify((string) $date); } /** * Modify to the first occurrence of a given day of the week * in the current year. If no dayOfWeek is provided, modify to the * first day of the current year. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek day of the week default null * * @return static */ public function firstOfYear($dayOfWeek = null) { return $this->month(1)->firstOfMonth($dayOfWeek); } /** * Modify to the last occurrence of a given day of the week * in the current year. If no dayOfWeek is provided, modify to the * last day of the current year. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek day of the week default null * * @return static */ public function lastOfYear($dayOfWeek = null) { return $this->month(static::MONTHS_PER_YEAR)->lastOfMonth($dayOfWeek); } /** * Modify to the given occurrence of a given day of the week * in the current year. If the calculated occurrence is outside the scope * of the current year, then return false and no modifications are made. * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int $nth * @param int $dayOfWeek * * @return mixed */ public function nthOfYear($nth, $dayOfWeek) { $date = $this->avoidMutation()->firstOfYear()->modify('+'.$nth.' '.static::$days[$dayOfWeek]); return $this->year === $date->year ? $this->modify((string) $date) : false; } /** * Modify the current instance to the average of a given instance (default now) and the current instance * (second-precision). * * @param \Carbon\Carbon|\DateTimeInterface|null $date * * @return static */ public function average($date = null) { return $this->addRealMicroseconds((int) ($this->diffInMicroseconds($this->resolveCarbon($date), false) / 2)); } /** * Get the closest date from the instance (second-precision). * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 * * @return static */ public function closest($date1, $date2) { return $this->diffInMicroseconds($date1, true) < $this->diffInMicroseconds($date2, true) ? $date1 : $date2; } /** * Get the farthest date from the instance (second-precision). * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 * * @return static */ public function farthest($date1, $date2) { return $this->diffInMicroseconds($date1, true) > $this->diffInMicroseconds($date2, true) ? $date1 : $date2; } /** * Get the minimum instance between a given instance (default now) and the current instance. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date * * @return static */ public function min($date = null) { $date = $this->resolveCarbon($date); return $this->lt($date) ? $this : $date; } /** * Get the minimum instance between a given instance (default now) and the current instance. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date * * @see min() * * @return static */ public function minimum($date = null) { return $this->min($date); } /** * Get the maximum instance between a given instance (default now) and the current instance. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date * * @return static */ public function max($date = null) { $date = $this->resolveCarbon($date); return $this->gt($date) ? $this : $date; } /** * Get the maximum instance between a given instance (default now) and the current instance. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date * * @see max() * * @return static */ public function maximum($date = null) { return $this->max($date); } /** * Calls \DateTime::modify if mutable or \DateTimeImmutable::modify else. * * @see https://php.net/manual/en/datetime.modify.php * * @return static */ #[ReturnTypeWillChange] public function modify($modify) { return parent::modify((string) $modify) ?: throw new InvalidFormatException('Could not modify with: '.var_export($modify, true)); } /** * Similar to native modify() method of DateTime but can handle more grammars. * * @example * ``` * echo Carbon::now()->change('next 2pm'); * ``` * * @link https://php.net/manual/en/datetime.modify.php * * @param string $modifier * * @return static */ public function change($modifier) { return $this->modify(preg_replace_callback('/^(next|previous|last)\s+(\d{1,2}(h|am|pm|:\d{1,2}(:\d{1,2})?))$/i', function ($match) { $match[2] = str_replace('h', ':00', $match[2]); $test = $this->avoidMutation()->modify($match[2]); $method = $match[1] === 'next' ? 'lt' : 'gt'; $match[1] = $test->$method($this) ? $match[1].' day' : 'today'; return $match[1].' '.$match[2]; }, strtr(trim($modifier), [ ' at ' => ' ', 'just now' => 'now', 'after tomorrow' => 'tomorrow +1 day', 'before yesterday' => 'yesterday -1 day', ]))); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Traits/IntervalStep.php
src/Carbon/Traits/IntervalStep.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Callback; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Closure; use DateTimeImmutable; use DateTimeInterface; trait IntervalStep { /** * Step to apply instead of a fixed interval to get the new date. * * @var Closure|null */ protected $step; /** * Get the dynamic step in use. * * @return Closure */ public function getStep(): ?Closure { return $this->step; } /** * Set a step to apply instead of a fixed interval to get the new date. * * Or pass null to switch to fixed interval. * * @param Closure|null $step */ public function setStep(?Closure $step): void { $this->step = $step; } /** * Take a date and apply either the step if set, or the current interval else. * * The interval/step is applied negatively (typically subtraction instead of addition) if $negated is true. * * @param DateTimeInterface $dateTime * @param bool $negated * * @return CarbonInterface */ public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface { /** @var CarbonInterface $carbonDate */ $carbonDate = $dateTime instanceof CarbonInterface ? $dateTime : $this->resolveCarbon($dateTime); if ($this->step) { $carbonDate = Callback::parameter($this->step, $carbonDate->avoidMutation()); return $carbonDate->modify(($this->step)($carbonDate, $negated)->format('Y-m-d H:i:s.u e O')); } if ($negated) { return $carbonDate->rawSub($this); } return $carbonDate->rawAdd($this); } /** * Convert DateTimeImmutable instance to CarbonImmutable instance and DateTime instance to Carbon instance. */ private function resolveCarbon(DateTimeInterface $dateTime): Carbon|CarbonImmutable { if ($dateTime instanceof DateTimeImmutable) { return CarbonImmutable::instance($dateTime); } return Carbon::instance($dateTime); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Traits/Options.php
src/Carbon/Traits/Options.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use DateTimeInterface; use Throwable; /** * Trait Options. * * Embed base methods to change settings of Carbon classes. * * Depends on the following methods: * * @method static shiftTimezone($timezone) Set the timezone */ trait Options { use StaticOptions; use Localization; /** * Indicates if months should be calculated with overflow. * Specific setting. */ protected ?bool $localMonthsOverflow = null; /** * Indicates if years should be calculated with overflow. * Specific setting. */ protected ?bool $localYearsOverflow = null; /** * Indicates if the strict mode is in use. * Specific setting. */ protected ?bool $localStrictModeEnabled = null; /** * Options for diffForHumans and forHumans methods. */ protected ?int $localHumanDiffOptions = null; /** * Format to use on string cast. * * @var string|callable|null */ protected $localToStringFormat = null; /** * Format to use on JSON serialization. * * @var string|callable|null */ protected $localSerializer = null; /** * Instance-specific macros. */ protected ?array $localMacros = null; /** * Instance-specific generic macros. */ protected ?array $localGenericMacros = null; /** * Function to call instead of format. * * @var string|callable|null */ protected $localFormatFunction = null; /** * Set specific options. * - strictMode: true|false|null * - monthOverflow: true|false|null * - yearOverflow: true|false|null * - humanDiffOptions: int|null * - toStringFormat: string|Closure|null * - toJsonFormat: string|Closure|null * - locale: string|null * - timezone: \DateTimeZone|string|int|null * - macros: array|null * - genericMacros: array|null * * @param array $settings * * @return $this|static */ public function settings(array $settings): static { $this->localStrictModeEnabled = $settings['strictMode'] ?? null; $this->localMonthsOverflow = $settings['monthOverflow'] ?? null; $this->localYearsOverflow = $settings['yearOverflow'] ?? null; $this->localHumanDiffOptions = $settings['humanDiffOptions'] ?? null; $this->localToStringFormat = $settings['toStringFormat'] ?? null; $this->localSerializer = $settings['toJsonFormat'] ?? null; $this->localMacros = $settings['macros'] ?? null; $this->localGenericMacros = $settings['genericMacros'] ?? null; $this->localFormatFunction = $settings['formatFunction'] ?? null; if (isset($settings['locale'])) { $locales = $settings['locale']; if (!\is_array($locales)) { $locales = [$locales]; } $this->locale(...$locales); } elseif (isset($settings['translator']) && property_exists($this, 'localTranslator')) { $this->localTranslator = $settings['translator']; } if (isset($settings['innerTimezone'])) { return $this->setTimezone($settings['innerTimezone']); } if (isset($settings['timezone'])) { return $this->shiftTimezone($settings['timezone']); } return $this; } /** * Returns current local settings. */ public function getSettings(): array { $settings = []; $map = [ 'localStrictModeEnabled' => 'strictMode', 'localMonthsOverflow' => 'monthOverflow', 'localYearsOverflow' => 'yearOverflow', 'localHumanDiffOptions' => 'humanDiffOptions', 'localToStringFormat' => 'toStringFormat', 'localSerializer' => 'toJsonFormat', 'localMacros' => 'macros', 'localGenericMacros' => 'genericMacros', 'locale' => 'locale', 'tzName' => 'timezone', 'localFormatFunction' => 'formatFunction', ]; foreach ($map as $property => $key) { $value = $this->$property ?? null; if ($value !== null && ($key !== 'locale' || $value !== 'en' || $this->localTranslator)) { $settings[$key] = $value; } } return $settings; } /** * Show truthy properties on var_dump(). */ public function __debugInfo(): array { $infos = array_filter(get_object_vars($this), static function ($var) { return $var; }); foreach (['dumpProperties', 'constructedObjectId', 'constructed', 'originalInput'] as $property) { if (isset($infos[$property])) { unset($infos[$property]); } } $this->addExtraDebugInfos($infos); foreach (["\0*\0", ''] as $prefix) { $key = $prefix.'carbonRecurrences'; if (\array_key_exists($key, $infos)) { $infos['recurrences'] = $infos[$key]; unset($infos[$key]); } } return $infos; } protected function isLocalStrictModeEnabled(): bool { return $this->localStrictModeEnabled ?? $this->transmitFactory(static fn () => static::isStrictModeEnabled()); } protected function addExtraDebugInfos(array &$infos): void { if ($this instanceof DateTimeInterface) { try { $infos['date'] ??= $this->format(CarbonInterface::MOCK_DATETIME_FORMAT); $infos['timezone'] ??= $this->tzName ?? $this->timezoneSetting ?? $this->timezone ?? null; } catch (Throwable) { // noop } } } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Traits/Localization.php
src/Carbon/Traits/Localization.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $fallbackMessages = []; $preferredMessages = $translator->getMessages($preferredLocale); foreach (Translator::get($locale)->getMessages()[$locale] ?? [] as $key => $value) { if ( preg_match('/^(?:a_)?(.+)_(?:standalone|ago|from_now|before|after|short|min)$/', $key, $match) && isset($preferredMessages[$match[1]]) ) { continue; } $fallbackMessages[$key] = $value; } $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], $fallbackMessages, $preferredMessages, )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales(): array { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo(): array { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Traits/Macro.php
src/Carbon/Traits/Macro.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\FactoryImmutable; /** * Trait Macros. * * Allows users to register macros within the Carbon class. */ trait Macro { use Mixin; /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * $userSettings = [ * 'locale' => 'pt', * 'timezone' => 'America/Sao_Paulo', * ]; * Carbon::macro('userFormat', function () use ($userSettings) { * return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar(); * }); * echo Carbon::yesterday()->hours(11)->userFormat(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { FactoryImmutable::getDefaultInstance()->macro($name, $macro); } /** * Remove all macros and generic macros. */ public static function resetMacros(): void { FactoryImmutable::getDefaultInstance()->resetMacros(); } /** * Register a custom macro. * * @param callable $macro * @param int $priority marco with higher priority is tried first * * @return void */ public static function genericMacro(callable $macro, int $priority = 0): void { FactoryImmutable::getDefaultInstance()->genericMacro($macro, $priority); } /** * Checks if macro is registered globally. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return FactoryImmutable::getInstance()->hasMacro($name); } /** * Get the raw callable macro registered globally for a given name. */ public static function getMacro(string $name): ?callable { return FactoryImmutable::getInstance()->getMacro($name); } /** * Checks if macro is registered globally or locally. */ public function hasLocalMacro(string $name): bool { return ($this->localMacros && isset($this->localMacros[$name])) || $this->transmitFactory( static fn () => static::hasMacro($name), ); } /** * Get the raw callable macro registered globally or locally for a given name. */ public function getLocalMacro(string $name): ?callable { return ($this->localMacros ?? [])[$name] ?? $this->transmitFactory( static fn () => static::getMacro($name), ); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Traits/Creator.php
src/Carbon/Traits/Creator.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Traits/ObjectInitialisation.php
src/Carbon/Traits/ObjectInitialisation.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; trait ObjectInitialisation { /** * True when parent::__construct has been called. * * @var string */ protected $constructedObjectId; }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Traits/Week.php
src/Carbon/Traits/Week.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterval; /** * Trait Week. * * week and ISO week number, year and count in year. * * Depends on the following properties: * * @property int $daysInYear * @property int $dayOfWeek * @property int $dayOfYear * @property int $year * * Depends on the following methods: * * @method static addWeeks(int $weeks = 1) * @method static copy() * @method static dayOfYear(int $dayOfYear) * @method string getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) * @method static next(int|string $modifier = null) * @method static startOfWeek(int $day = null) * @method static subWeeks(int $weeks = 1) * @method static year(int $year = null) */ trait Week { /** * Set/get the week number of year using given first day of week and first * day of year included in the first week. Or use ISO format if no settings * given. * * @param int|null $year if null, act as a getter, if not null, set the year and return current instance. * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) * @param int|null $dayOfYear first day of year included in the week #1 * * @return int|static */ public function isoWeekYear($year = null, $dayOfWeek = null, $dayOfYear = null) { return $this->weekYear( $year, $dayOfWeek ?? static::MONDAY, $dayOfYear ?? static::THURSDAY, ); } /** * Set/get the week number of year using given first day of week and first * day of year included in the first week. Or use US format if no settings * given (Sunday / Jan 6). * * @param int|null $year if null, act as a getter, if not null, set the year and return current instance. * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) * @param int|null $dayOfYear first day of year included in the week #1 * * @return int|static */ public function weekYear($year = null, $dayOfWeek = null, $dayOfYear = null) { $dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? static::SUNDAY; $dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1; if ($year !== null) { $year = (int) round($year); if ($this->weekYear(null, $dayOfWeek, $dayOfYear) === $year) { return $this->avoidMutation(); } $week = $this->week(null, $dayOfWeek, $dayOfYear); $day = $this->dayOfWeek; $date = $this->year($year); $date = match ($date->weekYear(null, $dayOfWeek, $dayOfYear) - $year) { CarbonInterval::POSITIVE => $date->subWeeks(static::WEEKS_PER_YEAR / 2), CarbonInterval::NEGATIVE => $date->addWeeks(static::WEEKS_PER_YEAR / 2), default => $date, }; $date = $date ->addWeeks($week - $date->week(null, $dayOfWeek, $dayOfYear)) ->startOfWeek($dayOfWeek); if ($date->dayOfWeek === $day) { return $date; } return $date->next($day); } $year = $this->year; $day = $this->dayOfYear; $date = $this->avoidMutation()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); if ($date->year === $year && $day < $date->dayOfYear) { return $year - 1; } $date = $this->avoidMutation()->addYear()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); if ($date->year === $year && $day >= $date->dayOfYear) { return $year + 1; } return $year; } /** * Get the number of weeks of the current week-year using given first day of week and first * day of year included in the first week. Or use ISO format if no settings * given. * * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) * @param int|null $dayOfYear first day of year included in the week #1 * * @return int */ public function isoWeeksInYear($dayOfWeek = null, $dayOfYear = null) { return $this->weeksInYear( $dayOfWeek ?? static::MONDAY, $dayOfYear ?? static::THURSDAY, ); } /** * Get the number of weeks of the current week-year using given first day of week and first * day of year included in the first week. Or use US format if no settings * given (Sunday / Jan 6). * * @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday) * @param int|null $dayOfYear first day of year included in the week #1 * * @return int */ public function weeksInYear($dayOfWeek = null, $dayOfYear = null) { $dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? static::SUNDAY; $dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1; $year = $this->year; $start = $this->avoidMutation()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); $startDay = $start->dayOfYear; if ($start->year !== $year) { $startDay -= $start->daysInYear; } $end = $this->avoidMutation()->addYear()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); $endDay = $end->dayOfYear; if ($end->year !== $year) { $endDay += $this->daysInYear; } return (int) round(($endDay - $startDay) / static::DAYS_PER_WEEK); } /** * Get/set the week number using given first day of week and first * day of year included in the first week. Or use US format if no settings * given (Sunday / Jan 6). * * @param int|null $week * @param int|null $dayOfWeek * @param int|null $dayOfYear * * @return int|static */ public function week($week = null, $dayOfWeek = null, $dayOfYear = null) { $date = $this; $dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? 0; $dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1; if ($week !== null) { return $date->addWeeks(round($week) - $this->week(null, $dayOfWeek, $dayOfYear)); } $start = $date->avoidMutation()->shiftTimezone('UTC')->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); $end = $date->avoidMutation()->shiftTimezone('UTC')->startOfWeek($dayOfWeek); if ($start > $end) { $start = $start->subWeeks(static::WEEKS_PER_YEAR / 2)->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek); } $week = (int) ($start->diffInDays($end) / static::DAYS_PER_WEEK + 1); return $week > $end->weeksInYear($dayOfWeek, $dayOfYear) ? 1 : $week; } /** * Get/set the week number using given first day of week and first * day of year included in the first week. Or use ISO format if no settings * given. * * @param int|null $week * @param int|null $dayOfWeek * @param int|null $dayOfYear * * @return int|static */ public function isoWeek($week = null, $dayOfWeek = null, $dayOfYear = null) { return $this->week( $week, $dayOfWeek ?? static::MONDAY, $dayOfYear ?? static::THURSDAY, ); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false