repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
faustbrian/Laravel-Commentable
src/Traits/HasComments.php
HasComments.deleteComment
public function deleteComment($id): bool { $commentableModel = $this->commentableModel(); return (bool) (new $commentableModel())->deleteComment($id); }
php
public function deleteComment($id): bool { $commentableModel = $this->commentableModel(); return (bool) (new $commentableModel())->deleteComment($id); }
[ "public", "function", "deleteComment", "(", "$", "id", ")", ":", "bool", "{", "$", "commentableModel", "=", "$", "this", "->", "commentableModel", "(", ")", ";", "return", "(", "bool", ")", "(", "new", "$", "commentableModel", "(", ")", ")", "->", "del...
@param $id @return mixed
[ "@param", "$id" ]
train
https://github.com/faustbrian/Laravel-Commentable/blob/45a82e816499bb7bcb574013394bf68abdf9df7c/src/Traits/HasComments.php#L83-L88
php-service-bus/service-bus
src/Services/Configuration/AnnotationsBasedServiceHandlersLoader.php
AnnotationsBasedServiceHandlersLoader.load
public function load(object $service): \SplObjectStorage { $collection = new \SplObjectStorage(); /** @var \ServiceBus\AnnotationsReader\Annotation $annotation */ foreach ($this->loadMethodLevelAnnotations($service) as $annotation) { /** @var CommandHandler|EventListener $handlerAnnotation */ $handlerAnnotation = $annotation->annotationObject; /** @var \ReflectionMethod $handlerReflectionMethod */ $handlerReflectionMethod = $annotation->reflectionMethod; /** @psalm-var \Closure(object, \ServiceBus\Common\Context\ServiceBusContext):\Amp\Promise|null $closure */ $closure = $handlerReflectionMethod->getClosure($service); if (null === $closure) { throw new UnableCreateClosure( \sprintf( 'Unable to create a closure for the "%s" method', $annotation->reflectionMethod ? $annotation->reflectionMethod->getName() : 'n\a' ) ); } $isCommandHandler = $handlerAnnotation instanceof CommandHandler; /** * @var \ReflectionMethod $handlerReflectionMethod * @var MessageHandler $handler * @var CommandHandler|EventListener $handlerAnnotation */ $handler = MessageHandler::create( $this->extractMessageClass($handlerReflectionMethod->getParameters()), $closure, $handlerReflectionMethod, $this->createOptions($handlerAnnotation, $isCommandHandler) ); $factoryMethod = true === $isCommandHandler ? 'createCommandHandler' : 'createEventListener'; /** @var ServiceMessageHandler $serviceMessageHandler */ $serviceMessageHandler = ServiceMessageHandler::{$factoryMethod}($handler); $collection->attach($serviceMessageHandler); } /** @psalm-var \SplObjectStorage<\ServiceBus\Services\Configuration\ServiceMessageHandler, string> $collection */ return $collection; }
php
public function load(object $service): \SplObjectStorage { $collection = new \SplObjectStorage(); /** @var \ServiceBus\AnnotationsReader\Annotation $annotation */ foreach ($this->loadMethodLevelAnnotations($service) as $annotation) { /** @var CommandHandler|EventListener $handlerAnnotation */ $handlerAnnotation = $annotation->annotationObject; /** @var \ReflectionMethod $handlerReflectionMethod */ $handlerReflectionMethod = $annotation->reflectionMethod; /** @psalm-var \Closure(object, \ServiceBus\Common\Context\ServiceBusContext):\Amp\Promise|null $closure */ $closure = $handlerReflectionMethod->getClosure($service); if (null === $closure) { throw new UnableCreateClosure( \sprintf( 'Unable to create a closure for the "%s" method', $annotation->reflectionMethod ? $annotation->reflectionMethod->getName() : 'n\a' ) ); } $isCommandHandler = $handlerAnnotation instanceof CommandHandler; /** * @var \ReflectionMethod $handlerReflectionMethod * @var MessageHandler $handler * @var CommandHandler|EventListener $handlerAnnotation */ $handler = MessageHandler::create( $this->extractMessageClass($handlerReflectionMethod->getParameters()), $closure, $handlerReflectionMethod, $this->createOptions($handlerAnnotation, $isCommandHandler) ); $factoryMethod = true === $isCommandHandler ? 'createCommandHandler' : 'createEventListener'; /** @var ServiceMessageHandler $serviceMessageHandler */ $serviceMessageHandler = ServiceMessageHandler::{$factoryMethod}($handler); $collection->attach($serviceMessageHandler); } /** @psalm-var \SplObjectStorage<\ServiceBus\Services\Configuration\ServiceMessageHandler, string> $collection */ return $collection; }
[ "public", "function", "load", "(", "object", "$", "service", ")", ":", "\\", "SplObjectStorage", "{", "$", "collection", "=", "new", "\\", "SplObjectStorage", "(", ")", ";", "/** @var \\ServiceBus\\AnnotationsReader\\Annotation $annotation */", "foreach", "(", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/Configuration/AnnotationsBasedServiceHandlersLoader.php#L49-L100
php-service-bus/service-bus
src/Services/Configuration/AnnotationsBasedServiceHandlersLoader.php
AnnotationsBasedServiceHandlersLoader.createOptions
private function createOptions(ServicesAnnotationsMarker $annotation, bool $isCommandHandler): DefaultHandlerOptions { /** @var CommandHandler|EventListener $annotation */ $factoryMethod = true === $isCommandHandler ? 'createForCommandHandler' : 'createForEventListener'; /** @var DefaultHandlerOptions $options */ $options = DefaultHandlerOptions::{$factoryMethod}(); if (true === $annotation->validate) { $options = $options->enableValidation($annotation->groups); } if ('' !== (string) $annotation->defaultValidationFailedEvent) { /** * @psalm-suppress TypeCoercion * @psalm-suppress PossiblyNullArgument */ $options = $options->withDefaultValidationFailedEvent($annotation->defaultValidationFailedEvent); } if ('' !== (string) $annotation->defaultThrowableEvent) { /** * @psalm-suppress TypeCoercion * @psalm-suppress PossiblyNullArgument */ $options = $options->withDefaultThrowableEvent($annotation->defaultThrowableEvent); } return $options; }
php
private function createOptions(ServicesAnnotationsMarker $annotation, bool $isCommandHandler): DefaultHandlerOptions { /** @var CommandHandler|EventListener $annotation */ $factoryMethod = true === $isCommandHandler ? 'createForCommandHandler' : 'createForEventListener'; /** @var DefaultHandlerOptions $options */ $options = DefaultHandlerOptions::{$factoryMethod}(); if (true === $annotation->validate) { $options = $options->enableValidation($annotation->groups); } if ('' !== (string) $annotation->defaultValidationFailedEvent) { /** * @psalm-suppress TypeCoercion * @psalm-suppress PossiblyNullArgument */ $options = $options->withDefaultValidationFailedEvent($annotation->defaultValidationFailedEvent); } if ('' !== (string) $annotation->defaultThrowableEvent) { /** * @psalm-suppress TypeCoercion * @psalm-suppress PossiblyNullArgument */ $options = $options->withDefaultThrowableEvent($annotation->defaultThrowableEvent); } return $options; }
[ "private", "function", "createOptions", "(", "ServicesAnnotationsMarker", "$", "annotation", ",", "bool", "$", "isCommandHandler", ")", ":", "DefaultHandlerOptions", "{", "/** @var CommandHandler|EventListener $annotation */", "$", "factoryMethod", "=", "true", "===", "$", ...
Create options. @param ServicesAnnotationsMarker $annotation @param bool $isCommandHandler @throws \ServiceBus\Services\Exceptions\InvalidEventType @return DefaultHandlerOptions
[ "Create", "options", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/Configuration/AnnotationsBasedServiceHandlersLoader.php#L112-L144
php-service-bus/service-bus
src/Services/Configuration/AnnotationsBasedServiceHandlersLoader.php
AnnotationsBasedServiceHandlersLoader.loadMethodLevelAnnotations
private function loadMethodLevelAnnotations(object $service): AnnotationCollection { return $this->annotationReader ->extract(\get_class($service)) ->filter( static function(Annotation $annotation): ?Annotation { if ($annotation->annotationObject instanceof ServicesAnnotationsMarker) { return $annotation; } return null; } ) ->methodLevelAnnotations(); }
php
private function loadMethodLevelAnnotations(object $service): AnnotationCollection { return $this->annotationReader ->extract(\get_class($service)) ->filter( static function(Annotation $annotation): ?Annotation { if ($annotation->annotationObject instanceof ServicesAnnotationsMarker) { return $annotation; } return null; } ) ->methodLevelAnnotations(); }
[ "private", "function", "loadMethodLevelAnnotations", "(", "object", "$", "service", ")", ":", "AnnotationCollection", "{", "return", "$", "this", "->", "annotationReader", "->", "extract", "(", "\\", "get_class", "(", "$", "service", ")", ")", "->", "filter", ...
Load a list of annotations for message handlers. @param object $service @throws \ServiceBus\AnnotationsReader\Exceptions\ParseAnnotationFailed @return AnnotationCollection
[ "Load", "a", "list", "of", "annotations", "for", "message", "handlers", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/Configuration/AnnotationsBasedServiceHandlersLoader.php#L155-L171
php-service-bus/service-bus
src/Services/Configuration/AnnotationsBasedServiceHandlersLoader.php
AnnotationsBasedServiceHandlersLoader.extractMessageClass
private function extractMessageClass(array $parameters): string { if (0 === \count($parameters)) { throw InvalidHandlerArguments::emptyArguments(); } /** @var \ReflectionParameter $firstArgument */ $firstArgument = $parameters[0]; if (null !== $firstArgument->getType()) { /** @var \ReflectionType $type */ $type = $firstArgument->getType(); /** @psalm-var class-string $className */ $className = $type->getName(); /** @psalm-suppress RedundantConditionGivenDocblockType */ if (true === \class_exists($className)) { return $className; } } throw InvalidHandlerArguments::invalidFirstArgument(); }
php
private function extractMessageClass(array $parameters): string { if (0 === \count($parameters)) { throw InvalidHandlerArguments::emptyArguments(); } /** @var \ReflectionParameter $firstArgument */ $firstArgument = $parameters[0]; if (null !== $firstArgument->getType()) { /** @var \ReflectionType $type */ $type = $firstArgument->getType(); /** @psalm-var class-string $className */ $className = $type->getName(); /** @psalm-suppress RedundantConditionGivenDocblockType */ if (true === \class_exists($className)) { return $className; } } throw InvalidHandlerArguments::invalidFirstArgument(); }
[ "private", "function", "extractMessageClass", "(", "array", "$", "parameters", ")", ":", "string", "{", "if", "(", "0", "===", "\\", "count", "(", "$", "parameters", ")", ")", "{", "throw", "InvalidHandlerArguments", "::", "emptyArguments", "(", ")", ";", ...
@psalm-return class-string @param \ReflectionParameter[] $parameters @throws \ServiceBus\Services\Exceptions\InvalidHandlerArguments @return string
[ "@psalm", "-", "return", "class", "-", "string" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/Configuration/AnnotationsBasedServiceHandlersLoader.php#L182-L208
php-service-bus/service-bus
src/Services/Configuration/DefaultHandlerOptions.php
DefaultHandlerOptions.enableValidation
public function enableValidation(array $validationGroups = []): self { $defaultValidationFailedEvent = $this->defaultValidationFailedEvent; $defaultThrowableEvent = $this->defaultThrowableEvent; /** * @psalm-var class-string|null $defaultValidationFailedEvent * @psalm-var class-string|null $defaultThrowableEvent */ return new self( $this->isEventListener, $this->isCommandHandler, true, $validationGroups, $defaultValidationFailedEvent, $defaultThrowableEvent ); }
php
public function enableValidation(array $validationGroups = []): self { $defaultValidationFailedEvent = $this->defaultValidationFailedEvent; $defaultThrowableEvent = $this->defaultThrowableEvent; /** * @psalm-var class-string|null $defaultValidationFailedEvent * @psalm-var class-string|null $defaultThrowableEvent */ return new self( $this->isEventListener, $this->isCommandHandler, true, $validationGroups, $defaultValidationFailedEvent, $defaultThrowableEvent ); }
[ "public", "function", "enableValidation", "(", "array", "$", "validationGroups", "=", "[", "]", ")", ":", "self", "{", "$", "defaultValidationFailedEvent", "=", "$", "this", "->", "defaultValidationFailedEvent", ";", "$", "defaultThrowableEvent", "=", "$", "this",...
Enable validation. @psalm-param array<array-key, string> $validationGroups @param string[] $validationGroups @return self
[ "Enable", "validation", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/Configuration/DefaultHandlerOptions.php#L111-L129
php-service-bus/service-bus
src/Services/Configuration/DefaultHandlerOptions.php
DefaultHandlerOptions.withDefaultValidationFailedEvent
public function withDefaultValidationFailedEvent(string $eventClass): self { if (false === \is_a($eventClass, ValidationFailedEvent::class, true)) { throw new InvalidEventType( \sprintf( 'Event class "%s" must implement "%s" interface', $eventClass, ValidationFailedEvent::class ) ); } $defaultThrowableEvent = $this->defaultThrowableEvent; /** * @psalm-var class-string $eventClass * @psalm-var class-string|null $defaultThrowableEvent */ return new self( $this->isEventListener, $this->isCommandHandler, $this->validationEnabled, $this->validationGroups, $eventClass, $defaultThrowableEvent ); }
php
public function withDefaultValidationFailedEvent(string $eventClass): self { if (false === \is_a($eventClass, ValidationFailedEvent::class, true)) { throw new InvalidEventType( \sprintf( 'Event class "%s" must implement "%s" interface', $eventClass, ValidationFailedEvent::class ) ); } $defaultThrowableEvent = $this->defaultThrowableEvent; /** * @psalm-var class-string $eventClass * @psalm-var class-string|null $defaultThrowableEvent */ return new self( $this->isEventListener, $this->isCommandHandler, $this->validationEnabled, $this->validationGroups, $eventClass, $defaultThrowableEvent ); }
[ "public", "function", "withDefaultValidationFailedEvent", "(", "string", "$", "eventClass", ")", ":", "self", "{", "if", "(", "false", "===", "\\", "is_a", "(", "$", "eventClass", ",", "ValidationFailedEvent", "::", "class", ",", "true", ")", ")", "{", "thro...
@psalm-param class-string $eventClass @param string $eventClass @throws \ServiceBus\Services\Exceptions\InvalidEventType Event class must implement @see ExecutionFailedEvent @return self
[ "@psalm", "-", "param", "class", "-", "string", "$eventClass" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/Configuration/DefaultHandlerOptions.php#L140-L168
php-service-bus/service-bus
src/Services/Configuration/DefaultHandlerOptions.php
DefaultHandlerOptions.withDefaultThrowableEvent
public function withDefaultThrowableEvent(string $eventClass): self { if (false === \is_a($eventClass, ExecutionFailedEvent::class, true)) { throw new InvalidEventType( \sprintf( 'Event class "%s" must implement "%s" interface', $eventClass, ExecutionFailedEvent::class ) ); } $defaultValidationFailedEvent = $this->defaultValidationFailedEvent; /** * @psalm-var class-string $eventClass * @psalm-var class-string|null $defaultValidationFailedEvent */ return new self( $this->isEventListener, $this->isCommandHandler, $this->validationEnabled, $this->validationGroups, $defaultValidationFailedEvent, $eventClass ); }
php
public function withDefaultThrowableEvent(string $eventClass): self { if (false === \is_a($eventClass, ExecutionFailedEvent::class, true)) { throw new InvalidEventType( \sprintf( 'Event class "%s" must implement "%s" interface', $eventClass, ExecutionFailedEvent::class ) ); } $defaultValidationFailedEvent = $this->defaultValidationFailedEvent; /** * @psalm-var class-string $eventClass * @psalm-var class-string|null $defaultValidationFailedEvent */ return new self( $this->isEventListener, $this->isCommandHandler, $this->validationEnabled, $this->validationGroups, $defaultValidationFailedEvent, $eventClass ); }
[ "public", "function", "withDefaultThrowableEvent", "(", "string", "$", "eventClass", ")", ":", "self", "{", "if", "(", "false", "===", "\\", "is_a", "(", "$", "eventClass", ",", "ExecutionFailedEvent", "::", "class", ",", "true", ")", ")", "{", "throw", "n...
@psalm-param class-string $eventClass @param string $eventClass @throws \ServiceBus\Services\Exceptions\InvalidEventType Event class must implement @see ExecutionFailedEvent @return self
[ "@psalm", "-", "param", "class", "-", "string", "$eventClass" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/Configuration/DefaultHandlerOptions.php#L179-L207
php-service-bus/service-bus
src/EntryPoint/IncomingMessageDecoder.php
IncomingMessageDecoder.decode
public function decode(IncomingPackage $package): object { $encoderKey = $this->extractEncoderKey($package->headers()); return $this ->findDecoderByKey($encoderKey) ->decode($package->payload()); }
php
public function decode(IncomingPackage $package): object { $encoderKey = $this->extractEncoderKey($package->headers()); return $this ->findDecoderByKey($encoderKey) ->decode($package->payload()); }
[ "public", "function", "decode", "(", "IncomingPackage", "$", "package", ")", ":", "object", "{", "$", "encoderKey", "=", "$", "this", "->", "extractEncoderKey", "(", "$", "package", "->", "headers", "(", ")", ")", ";", "return", "$", "this", "->", "findD...
Decodes a packet using a handler defined in the headers (or uses a default decoder). @psalm-suppress MixedTypeCoercion Incorrect resolving the value of the promise @param IncomingPackage $package @throws \LogicException Could not find decoder in the service container @throws \ServiceBus\MessageSerializer\Exceptions\DecodeMessageFailed @return object
[ "Decodes", "a", "packet", "using", "a", "handler", "defined", "in", "the", "headers", "(", "or", "uses", "a", "default", "decoder", ")", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/EntryPoint/IncomingMessageDecoder.php#L65-L72
php-service-bus/service-bus
src/EntryPoint/IncomingMessageDecoder.php
IncomingMessageDecoder.findDecoderByKey
private function findDecoderByKey(string $encoderKey): MessageDecoder { /** @var string $encoderContainerId */ $encoderContainerId = true === !empty($this->decodersConfiguration[$encoderKey]) ? $this->decodersConfiguration[$encoderKey] : self::DEFAULT_DECODER; return $this->obtainDecoder($encoderContainerId); }
php
private function findDecoderByKey(string $encoderKey): MessageDecoder { /** @var string $encoderContainerId */ $encoderContainerId = true === !empty($this->decodersConfiguration[$encoderKey]) ? $this->decodersConfiguration[$encoderKey] : self::DEFAULT_DECODER; return $this->obtainDecoder($encoderContainerId); }
[ "private", "function", "findDecoderByKey", "(", "string", "$", "encoderKey", ")", ":", "MessageDecoder", "{", "/** @var string $encoderContainerId */", "$", "encoderContainerId", "=", "true", "===", "!", "empty", "(", "$", "this", "->", "decodersConfiguration", "[", ...
@param string $encoderKey @throws \LogicException Could not find decoder @return MessageDecoder
[ "@param", "string", "$encoderKey" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/EntryPoint/IncomingMessageDecoder.php#L81-L89
php-service-bus/service-bus
src/EntryPoint/IncomingMessageDecoder.php
IncomingMessageDecoder.obtainDecoder
private function obtainDecoder(string $decoderId): MessageDecoder { if (true === $this->decodersLocator->has($decoderId)) { /** @var MessageDecoder $decoder */ $decoder = $this->decodersLocator->get($decoderId); return $decoder; } throw new \LogicException( \sprintf('Could not find decoder "%s" in the service container', $decoderId) ); }
php
private function obtainDecoder(string $decoderId): MessageDecoder { if (true === $this->decodersLocator->has($decoderId)) { /** @var MessageDecoder $decoder */ $decoder = $this->decodersLocator->get($decoderId); return $decoder; } throw new \LogicException( \sprintf('Could not find decoder "%s" in the service container', $decoderId) ); }
[ "private", "function", "obtainDecoder", "(", "string", "$", "decoderId", ")", ":", "MessageDecoder", "{", "if", "(", "true", "===", "$", "this", "->", "decodersLocator", "->", "has", "(", "$", "decoderId", ")", ")", "{", "/** @var MessageDecoder $decoder */", ...
@param string $decoderId @throws \LogicException Could not find decoder @return MessageDecoder
[ "@param", "string", "$decoderId" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/EntryPoint/IncomingMessageDecoder.php#L98-L111
php-service-bus/service-bus
src/EntryPoint/IncomingMessageDecoder.php
IncomingMessageDecoder.extractEncoderKey
private function extractEncoderKey(array $headers): string { /** @var string $encoderKey */ $encoderKey = $headers[Transport::SERVICE_BUS_SERIALIZER_HEADER] ?? self::DEFAULT_DECODER; return $encoderKey; }
php
private function extractEncoderKey(array $headers): string { /** @var string $encoderKey */ $encoderKey = $headers[Transport::SERVICE_BUS_SERIALIZER_HEADER] ?? self::DEFAULT_DECODER; return $encoderKey; }
[ "private", "function", "extractEncoderKey", "(", "array", "$", "headers", ")", ":", "string", "{", "/** @var string $encoderKey */", "$", "encoderKey", "=", "$", "headers", "[", "Transport", "::", "SERVICE_BUS_SERIALIZER_HEADER", "]", "??", "self", "::", "DEFAULT_DE...
@param array $headers @return string
[ "@param", "array", "$headers" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/EntryPoint/IncomingMessageDecoder.php#L118-L124
php-service-bus/service-bus
src/MessageExecutor/DefaultMessageExecutorFactory.php
DefaultMessageExecutorFactory.create
public function create(MessageHandler $messageHandler): MessageExecutor { /** @var \ServiceBus\Services\Configuration\DefaultHandlerOptions $options */ $options = $messageHandler->options; $messageExecutor = new DefaultMessageExecutor( $messageHandler->closure, $messageHandler->arguments, $options, $this->argumentResolvers ); if (true === $options->validationEnabled) { $messageExecutor = new MessageValidationExecutor($messageExecutor, $options, $this->validator); } return $messageExecutor; }
php
public function create(MessageHandler $messageHandler): MessageExecutor { /** @var \ServiceBus\Services\Configuration\DefaultHandlerOptions $options */ $options = $messageHandler->options; $messageExecutor = new DefaultMessageExecutor( $messageHandler->closure, $messageHandler->arguments, $options, $this->argumentResolvers ); if (true === $options->validationEnabled) { $messageExecutor = new MessageValidationExecutor($messageExecutor, $options, $this->validator); } return $messageExecutor; }
[ "public", "function", "create", "(", "MessageHandler", "$", "messageHandler", ")", ":", "MessageExecutor", "{", "/** @var \\ServiceBus\\Services\\Configuration\\DefaultHandlerOptions $options */", "$", "options", "=", "$", "messageHandler", "->", "options", ";", "$", "messa...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/MessageExecutor/DefaultMessageExecutorFactory.php#L63-L81
php-service-bus/service-bus
src/Context/KernelContext.php
KernelContext.delivery
public function delivery(object $message, ?DeliveryOptions $deliveryOptions = null): Promise { $messageClass = \get_class($message); $endpoints = $this->endpointRouter->route($messageClass); $logger = $this->logger; $traceId = $this->incomingPackage->traceId(); $options = $deliveryOptions ?? DefaultDeliveryOptions::create(); if (null === $options->traceId()) { $options->withTraceId($traceId); } /** @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) */ return call( static function(object $message, DeliveryOptions $options) use ($endpoints, $logger, $traceId): void { foreach ($endpoints as $endpoint) { /** @var \ServiceBus\Endpoint\Endpoint $endpoint */ /** @noinspection DisconnectedForeachInstructionInspection */ $logger->debug( 'Send message "{messageClass}" to "{endpoint}"', [ 'traceId' => $traceId, 'messageClass' => \get_class($message), 'endpoint' => $endpoint->name(), ] ); $endpoint->delivery($message, $options)->onResolve( function(?\Throwable $throwable): void { if (null !== $throwable) { throw $throwable; } } ); } }, $message, $options ); }
php
public function delivery(object $message, ?DeliveryOptions $deliveryOptions = null): Promise { $messageClass = \get_class($message); $endpoints = $this->endpointRouter->route($messageClass); $logger = $this->logger; $traceId = $this->incomingPackage->traceId(); $options = $deliveryOptions ?? DefaultDeliveryOptions::create(); if (null === $options->traceId()) { $options->withTraceId($traceId); } /** @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) */ return call( static function(object $message, DeliveryOptions $options) use ($endpoints, $logger, $traceId): void { foreach ($endpoints as $endpoint) { /** @var \ServiceBus\Endpoint\Endpoint $endpoint */ /** @noinspection DisconnectedForeachInstructionInspection */ $logger->debug( 'Send message "{messageClass}" to "{endpoint}"', [ 'traceId' => $traceId, 'messageClass' => \get_class($message), 'endpoint' => $endpoint->name(), ] ); $endpoint->delivery($message, $options)->onResolve( function(?\Throwable $throwable): void { if (null !== $throwable) { throw $throwable; } } ); } }, $message, $options ); }
[ "public", "function", "delivery", "(", "object", "$", "message", ",", "?", "DeliveryOptions", "$", "deliveryOptions", "=", "null", ")", ":", "Promise", "{", "$", "messageClass", "=", "\\", "get_class", "(", "$", "message", ")", ";", "$", "endpoints", "=", ...
@psalm-suppress MixedInferredReturnType {@inheritdoc}
[ "@psalm", "-", "suppress", "MixedInferredReturnType" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Context/KernelContext.php#L116-L163
php-service-bus/service-bus
src/Context/KernelContext.php
KernelContext.logContextMessage
public function logContextMessage(string $logMessage, array $extra = [], string $level = LogLevel::INFO): void { $extra = \array_merge_recursive( $extra, [ 'traceId' => $this->incomingPackage->traceId(), 'packageId' => $this->incomingPackage->id(), ] ); $this->logger->log($level, $logMessage, $extra); }
php
public function logContextMessage(string $logMessage, array $extra = [], string $level = LogLevel::INFO): void { $extra = \array_merge_recursive( $extra, [ 'traceId' => $this->incomingPackage->traceId(), 'packageId' => $this->incomingPackage->id(), ] ); $this->logger->log($level, $logMessage, $extra); }
[ "public", "function", "logContextMessage", "(", "string", "$", "logMessage", ",", "array", "$", "extra", "=", "[", "]", ",", "string", "$", "level", "=", "LogLevel", "::", "INFO", ")", ":", "void", "{", "$", "extra", "=", "\\", "array_merge_recursive", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Context/KernelContext.php#L168-L179
php-service-bus/service-bus
src/Context/KernelContext.php
KernelContext.logContextThrowable
public function logContextThrowable(\Throwable $throwable, string $level = LogLevel::ERROR, array $extra = []): void { $extra = \array_merge_recursive( $extra, ['throwablePoint' => \sprintf('%s:%d', $throwable->getFile(), $throwable->getLine())] ); $this->logContextMessage($throwable->getMessage(), $extra, $level); }
php
public function logContextThrowable(\Throwable $throwable, string $level = LogLevel::ERROR, array $extra = []): void { $extra = \array_merge_recursive( $extra, ['throwablePoint' => \sprintf('%s:%d', $throwable->getFile(), $throwable->getLine())] ); $this->logContextMessage($throwable->getMessage(), $extra, $level); }
[ "public", "function", "logContextThrowable", "(", "\\", "Throwable", "$", "throwable", ",", "string", "$", "level", "=", "LogLevel", "::", "ERROR", ",", "array", "$", "extra", "=", "[", "]", ")", ":", "void", "{", "$", "extra", "=", "\\", "array_merge_re...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Context/KernelContext.php#L184-L192
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.addCompilerPasses
public function addCompilerPasses(CompilerPassInterface ...$compilerPasses): void { foreach ($compilerPasses as $compilerPass) { $this->compilerPasses->attach($compilerPass); } }
php
public function addCompilerPasses(CompilerPassInterface ...$compilerPasses): void { foreach ($compilerPasses as $compilerPass) { $this->compilerPasses->attach($compilerPass); } }
[ "public", "function", "addCompilerPasses", "(", "CompilerPassInterface", "...", "$", "compilerPasses", ")", ":", "void", "{", "foreach", "(", "$", "compilerPasses", "as", "$", "compilerPass", ")", "{", "$", "this", "->", "compilerPasses", "->", "attach", "(", ...
Add customer compiler pass. @noinspection PhpDocSignatureInspection @param CompilerPassInterface ...$compilerPasses @return void
[ "Add", "customer", "compiler", "pass", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L125-L131
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.addExtensions
public function addExtensions(Extension ...$extensions): void { foreach ($extensions as $extension) { $this->extensions->attach($extension); } }
php
public function addExtensions(Extension ...$extensions): void { foreach ($extensions as $extension) { $this->extensions->attach($extension); } }
[ "public", "function", "addExtensions", "(", "Extension", "...", "$", "extensions", ")", ":", "void", "{", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "$", "this", "->", "extensions", "->", "attach", "(", "$", "extension", ")", ";...
Add customer extension. @noinspection PhpDocSignatureInspection @param Extension ...$extensions @return void
[ "Add", "customer", "extension", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L142-L148
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.addModules
public function addModules(ServiceBusModule ...$serviceBusModules): void { foreach ($serviceBusModules as $serviceBusModule) { $this->modules->attach($serviceBusModule); } }
php
public function addModules(ServiceBusModule ...$serviceBusModules): void { foreach ($serviceBusModules as $serviceBusModule) { $this->modules->attach($serviceBusModule); } }
[ "public", "function", "addModules", "(", "ServiceBusModule", "...", "$", "serviceBusModules", ")", ":", "void", "{", "foreach", "(", "$", "serviceBusModules", "as", "$", "serviceBusModule", ")", "{", "$", "this", "->", "modules", "->", "attach", "(", "$", "s...
Add customer modules. @param ServiceBusModule ...$serviceBusModules @return void
[ "Add", "customer", "modules", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L157-L163
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.addParameters
public function addParameters(array $parameters): void { foreach ($parameters as $key => $value) { $this->parameters[$key] = $value; } }
php
public function addParameters(array $parameters): void { foreach ($parameters as $key => $value) { $this->parameters[$key] = $value; } }
[ "public", "function", "addParameters", "(", "array", "$", "parameters", ")", ":", "void", "{", "foreach", "(", "$", "parameters", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "parameters", "[", "$", "key", "]", "=", "$", "value"...
@psalm-param array<string, bool|string|int|float|array<mixed, mixed>|null> $parameters @param array $parameters @return void
[ "@psalm", "-", "param", "array<string", "bool|string|int|float|array<mixed", "mixed", ">", "|null", ">", "$parameters" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L172-L178
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.hasActualContainer
public function hasActualContainer(): bool { if (false === $this->environment->isDebug()) { return true === $this->configCache()->isFresh(); } return false; }
php
public function hasActualContainer(): bool { if (false === $this->environment->isDebug()) { return true === $this->configCache()->isFresh(); } return false; }
[ "public", "function", "hasActualContainer", "(", ")", ":", "bool", "{", "if", "(", "false", "===", "$", "this", "->", "environment", "->", "isDebug", "(", ")", ")", "{", "return", "true", "===", "$", "this", "->", "configCache", "(", ")", "->", "isFres...
Has compiled actual container. @return bool
[ "Has", "compiled", "actual", "container", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L197-L205
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.cachedContainer
public function cachedContainer(): ContainerInterface { /** * @noinspection PhpIncludeInspection Include generated file * @psalm-suppress UnresolvableInclude Include generated file */ include_once $this->getContainerClassPath(); /** @psalm-var class-string<\Symfony\Component\DependencyInjection\Container> $containerClassName */ $containerClassName = $this->getContainerClassName(); /** @var ContainerInterface $container */ $container = new $containerClassName(); return $container; }
php
public function cachedContainer(): ContainerInterface { /** * @noinspection PhpIncludeInspection Include generated file * @psalm-suppress UnresolvableInclude Include generated file */ include_once $this->getContainerClassPath(); /** @psalm-var class-string<\Symfony\Component\DependencyInjection\Container> $containerClassName */ $containerClassName = $this->getContainerClassName(); /** @var ContainerInterface $container */ $container = new $containerClassName(); return $container; }
[ "public", "function", "cachedContainer", "(", ")", ":", "ContainerInterface", "{", "/**\n * @noinspection PhpIncludeInspection Include generated file\n * @psalm-suppress UnresolvableInclude Include generated file\n */", "include_once", "$", "this", "->", "getConta...
Receive cached container. @return ContainerInterface
[ "Receive", "cached", "container", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L212-L227
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.build
public function build(): ContainerInterface { $this->parameters['service_bus.environment'] = (string) $this->environment; $this->parameters['service_bus.entry_point'] = $this->entryPointName; $containerBuilder = new SymfonyContainerBuilder(new ParameterBag($this->parameters)); /** @var Extension $extension */ foreach ($this->extensions as $extension) { $extension->load($this->parameters, $containerBuilder); } /** @var CompilerPassInterface $compilerPass */ foreach ($this->compilerPasses as $compilerPass) { $containerBuilder->addCompilerPass($compilerPass); } /** @var ServiceBusModule $module */ foreach ($this->modules as $module) { $module->boot($containerBuilder); } $containerBuilder->compile(); $this->dumpContainer($containerBuilder); return $this->cachedContainer(); }
php
public function build(): ContainerInterface { $this->parameters['service_bus.environment'] = (string) $this->environment; $this->parameters['service_bus.entry_point'] = $this->entryPointName; $containerBuilder = new SymfonyContainerBuilder(new ParameterBag($this->parameters)); /** @var Extension $extension */ foreach ($this->extensions as $extension) { $extension->load($this->parameters, $containerBuilder); } /** @var CompilerPassInterface $compilerPass */ foreach ($this->compilerPasses as $compilerPass) { $containerBuilder->addCompilerPass($compilerPass); } /** @var ServiceBusModule $module */ foreach ($this->modules as $module) { $module->boot($containerBuilder); } $containerBuilder->compile(); $this->dumpContainer($containerBuilder); return $this->cachedContainer(); }
[ "public", "function", "build", "(", ")", ":", "ContainerInterface", "{", "$", "this", "->", "parameters", "[", "'service_bus.environment'", "]", "=", "(", "string", ")", "$", "this", "->", "environment", ";", "$", "this", "->", "parameters", "[", "'service_b...
Build container. @throws \InvalidArgumentException When provided tag is not defined in this extension @throws \LogicException Cannot dump an uncompiled container @throws \RuntimeException When cache file can't be written @throws \Symfony\Component\DependencyInjection\Exception\EnvParameterException When an env var exists but has not been dumped @throws \Throwable Boot module failed @return ContainerInterface
[ "Build", "container", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L241-L271
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.dumpContainer
private function dumpContainer(SymfonyContainerBuilder $builder): void { $dumper = new PhpDumper($builder); $content = $dumper->dump( [ 'class' => $this->getContainerClassName(), 'base_class' => 'Container', 'file' => $this->configCache()->getPath(), ] ); if (true === \is_string($content)) { $this->configCache()->write($content, $builder->getResources()); } }
php
private function dumpContainer(SymfonyContainerBuilder $builder): void { $dumper = new PhpDumper($builder); $content = $dumper->dump( [ 'class' => $this->getContainerClassName(), 'base_class' => 'Container', 'file' => $this->configCache()->getPath(), ] ); if (true === \is_string($content)) { $this->configCache()->write($content, $builder->getResources()); } }
[ "private", "function", "dumpContainer", "(", "SymfonyContainerBuilder", "$", "builder", ")", ":", "void", "{", "$", "dumper", "=", "new", "PhpDumper", "(", "$", "builder", ")", ";", "$", "content", "=", "$", "dumper", "->", "dump", "(", "[", "'class'", "...
Save container. @param SymfonyContainerBuilder $builder @throws \LogicException Cannot dump an uncompiled container @throws \RuntimeException When cache file can't be written @throws \Symfony\Component\DependencyInjection\Exception\EnvParameterException When an env var exists but has not been dumped @return void
[ "Save", "container", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L284-L300
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.configCache
private function configCache(): ConfigCache { if (null === $this->configCache) { $this->configCache = new ConfigCache($this->getContainerClassPath(), $this->environment->isDebug()); } return $this->configCache; }
php
private function configCache(): ConfigCache { if (null === $this->configCache) { $this->configCache = new ConfigCache($this->getContainerClassPath(), $this->environment->isDebug()); } return $this->configCache; }
[ "private", "function", "configCache", "(", ")", ":", "ConfigCache", "{", "if", "(", "null", "===", "$", "this", "->", "configCache", ")", "{", "$", "this", "->", "configCache", "=", "new", "ConfigCache", "(", "$", "this", "->", "getContainerClassPath", "("...
Receive config cache. @return ConfigCache
[ "Receive", "config", "cache", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L307-L315
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.cacheDirectory
private function cacheDirectory(): string { $cacheDirectory = (string) $this->cacheDirectory; if ('' === $cacheDirectory && false === \is_writable($cacheDirectory)) { $cacheDirectory = \sys_get_temp_dir(); } return \rtrim($cacheDirectory, '/'); }
php
private function cacheDirectory(): string { $cacheDirectory = (string) $this->cacheDirectory; if ('' === $cacheDirectory && false === \is_writable($cacheDirectory)) { $cacheDirectory = \sys_get_temp_dir(); } return \rtrim($cacheDirectory, '/'); }
[ "private", "function", "cacheDirectory", "(", ")", ":", "string", "{", "$", "cacheDirectory", "=", "(", "string", ")", "$", "this", "->", "cacheDirectory", ";", "if", "(", "''", "===", "$", "cacheDirectory", "&&", "false", "===", "\\", "is_writable", "(", ...
Receive cache directory path. @return string
[ "Receive", "cache", "directory", "path", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L322-L332
php-service-bus/service-bus
src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php
ContainerBuilder.getContainerClassName
private function getContainerClassName(): string { return \sprintf( self::CONTAINER_NAME_TEMPLATE, \lcfirst($this->entryPointName), \ucfirst((string) $this->environment) ); }
php
private function getContainerClassName(): string { return \sprintf( self::CONTAINER_NAME_TEMPLATE, \lcfirst($this->entryPointName), \ucfirst((string) $this->environment) ); }
[ "private", "function", "getContainerClassName", "(", ")", ":", "string", "{", "return", "\\", "sprintf", "(", "self", "::", "CONTAINER_NAME_TEMPLATE", ",", "\\", "lcfirst", "(", "$", "this", "->", "entryPointName", ")", ",", "\\", "ucfirst", "(", "(", "strin...
Get container class name. @return string
[ "Get", "container", "class", "name", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/ContainerBuilder/ContainerBuilder.php#L349-L356
php-service-bus/service-bus
src/EntryPoint/EntryPoint.php
EntryPoint.listen
public function listen(Queue ...$queues): Promise { /** Hack for phpunit tests */ $isTestCall = 'phpunitTests' === (string) \getenv('SERVICE_BUS_TESTING'); /** * @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) * @psalm-suppress MixedArgument */ return call( function(array $queues) use ($isTestCall): \Generator { /** @psalm-suppress TooManyTemplateParams */ yield $this->transport->consume( function(IncomingPackage $package) use ($isTestCall): \Generator { $this->currentTasksInProgressCount++; /** Hack for phpUnit */ if (true === $isTestCall) { $this->currentTasksInProgressCount--; yield $this->processor->handle($package); yield $this->transport->stop(); Loop::stop(); } /** Handle incoming package */ $this->deferExecution($package); /** Limit the maximum number of concurrently running tasks */ while ($this->maxConcurrentTaskCount <= $this->currentTasksInProgressCount) { yield new Delayed($this->awaitDelay); } }, ...$queues ); }, $queues ); }
php
public function listen(Queue ...$queues): Promise { /** Hack for phpunit tests */ $isTestCall = 'phpunitTests' === (string) \getenv('SERVICE_BUS_TESTING'); /** * @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) * @psalm-suppress MixedArgument */ return call( function(array $queues) use ($isTestCall): \Generator { /** @psalm-suppress TooManyTemplateParams */ yield $this->transport->consume( function(IncomingPackage $package) use ($isTestCall): \Generator { $this->currentTasksInProgressCount++; /** Hack for phpUnit */ if (true === $isTestCall) { $this->currentTasksInProgressCount--; yield $this->processor->handle($package); yield $this->transport->stop(); Loop::stop(); } /** Handle incoming package */ $this->deferExecution($package); /** Limit the maximum number of concurrently running tasks */ while ($this->maxConcurrentTaskCount <= $this->currentTasksInProgressCount) { yield new Delayed($this->awaitDelay); } }, ...$queues ); }, $queues ); }
[ "public", "function", "listen", "(", "Queue", "...", "$", "queues", ")", ":", "Promise", "{", "/** Hack for phpunit tests */", "$", "isTestCall", "=", "'phpunitTests'", "===", "(", "string", ")", "\\", "getenv", "(", "'SERVICE_BUS_TESTING'", ")", ";", "/**\n ...
Start queues listen. @param Queue ...$queues @throws \ServiceBus\Transport\Common\Exceptions\ConnectionFail Connection refused @return Promise It does not return any result
[ "Start", "queues", "listen", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/EntryPoint/EntryPoint.php#L112-L155
php-service-bus/service-bus
src/EntryPoint/EntryPoint.php
EntryPoint.stop
public function stop(int $delay = 10): void { $delay = 0 >= $delay ? 1 : $delay; /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::defer( function() use ($delay): \Generator { yield $this->transport->stop(); $this->logger->info('Handler will stop after {duration} seconds', ['duration' => $delay]); /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::delay( $delay * 1000, function(): void { $this->logger->info('The event loop has been stopped'); Loop::stop(); } ); } ); }
php
public function stop(int $delay = 10): void { $delay = 0 >= $delay ? 1 : $delay; /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::defer( function() use ($delay): \Generator { yield $this->transport->stop(); $this->logger->info('Handler will stop after {duration} seconds', ['duration' => $delay]); /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::delay( $delay * 1000, function(): void { $this->logger->info('The event loop has been stopped'); Loop::stop(); } ); } ); }
[ "public", "function", "stop", "(", "int", "$", "delay", "=", "10", ")", ":", "void", "{", "$", "delay", "=", "0", ">=", "$", "delay", "?", "1", ":", "$", "delay", ";", "/** @psalm-suppress MixedTypeCoercion Incorrect amphp types */", "Loop", "::", "defer", ...
Unsubscribe all queues. Terminates the subscription and stops the daemon after the specified number of seconds. @param int $delay The delay before the completion (in seconds) @return void
[ "Unsubscribe", "all", "queues", ".", "Terminates", "the", "subscription", "and", "stops", "the", "daemon", "after", "the", "specified", "number", "of", "seconds", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/EntryPoint/EntryPoint.php#L165-L189
php-service-bus/service-bus
src/EntryPoint/EntryPoint.php
EntryPoint.deferExecution
private function deferExecution(IncomingPackage $package): void { /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::defer( function() use ($package): void { $this->processor->handle($package)->onResolve( function(?\Throwable $throwable) use ($package): void { $this->currentTasksInProgressCount--; if (null !== $throwable) { $this->logger->critical($throwable->getMessage(), [ 'packageId' => $package->id(), 'traceId' => $package->traceId(), 'throwablePoint' => \sprintf('%s:%d', $throwable->getFile(), $throwable->getLine()), ]); } } ); } ); }
php
private function deferExecution(IncomingPackage $package): void { /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::defer( function() use ($package): void { $this->processor->handle($package)->onResolve( function(?\Throwable $throwable) use ($package): void { $this->currentTasksInProgressCount--; if (null !== $throwable) { $this->logger->critical($throwable->getMessage(), [ 'packageId' => $package->id(), 'traceId' => $package->traceId(), 'throwablePoint' => \sprintf('%s:%d', $throwable->getFile(), $throwable->getLine()), ]); } } ); } ); }
[ "private", "function", "deferExecution", "(", "IncomingPackage", "$", "package", ")", ":", "void", "{", "/** @psalm-suppress MixedTypeCoercion Incorrect amphp types */", "Loop", "::", "defer", "(", "function", "(", ")", "use", "(", "$", "package", ")", ":", "void", ...
@param IncomingPackage $package @return void
[ "@param", "IncomingPackage", "$package" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/EntryPoint/EntryPoint.php#L196-L219
php-service-bus/service-bus
src/Application/ServiceBusKernel.php
ServiceBusKernel.createQueue
public function createQueue(Queue $queue, QueueBind ...$binds): Promise { return $this->transport->createQueue($queue, ...$binds); }
php
public function createQueue(Queue $queue, QueueBind ...$binds): Promise { return $this->transport->createQueue($queue, ...$binds); }
[ "public", "function", "createQueue", "(", "Queue", "$", "queue", ",", "QueueBind", "...", "$", "binds", ")", ":", "Promise", "{", "return", "$", "this", "->", "transport", "->", "createQueue", "(", "$", "queue", ",", "...", "$", "binds", ")", ";", "}" ...
Create queue and bind to topic(s) If the topic to which we binds does not exist, it will be created. @param Queue $queue @param QueueBind ...$binds @throws \ServiceBus\Transport\Common\Exceptions\ConnectionFail @throws \ServiceBus\Transport\Common\Exceptions\CreateQueueFailed @throws \ServiceBus\Transport\Common\Exceptions\BindFailed @return Promise
[ "Create", "queue", "and", "bind", "to", "topic", "(", "s", ")", "If", "the", "topic", "to", "which", "we", "binds", "does", "not", "exist", "it", "will", "be", "created", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/ServiceBusKernel.php#L105-L108
php-service-bus/service-bus
src/Application/ServiceBusKernel.php
ServiceBusKernel.createTopic
public function createTopic(Topic $topic, TopicBind ...$binds): Promise { return $this->transport->createTopic($topic, ...$binds); }
php
public function createTopic(Topic $topic, TopicBind ...$binds): Promise { return $this->transport->createTopic($topic, ...$binds); }
[ "public", "function", "createTopic", "(", "Topic", "$", "topic", ",", "TopicBind", "...", "$", "binds", ")", ":", "Promise", "{", "return", "$", "this", "->", "transport", "->", "createTopic", "(", "$", "topic", ",", "...", "$", "binds", ")", ";", "}" ...
Create topic and bind them If the topic to which we binds does not exist, it will be created. @param Topic $topic @param TopicBind ...$binds @throws \ServiceBus\Transport\Common\Exceptions\ConnectionFail @throws \ServiceBus\Transport\Common\Exceptions\CreateTopicFailed @throws \ServiceBus\Transport\Common\Exceptions\BindFailed @return Promise
[ "Create", "topic", "and", "bind", "them", "If", "the", "topic", "to", "which", "we", "binds", "does", "not", "exist", "it", "will", "be", "created", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/ServiceBusKernel.php#L123-L126
php-service-bus/service-bus
src/Application/ServiceBusKernel.php
ServiceBusKernel.useDefaultStopSignalHandler
public function useDefaultStopSignalHandler(int $stopDelay = 10, array $signals = [\SIGINT, \SIGTERM]): self { $stopDelay = 0 >= $stopDelay ? 1 : $stopDelay; /** * @noinspection PhpUnhandledExceptionInspection * * @var LoggerInterface $logger */ $logger = $this->getKernelContainerService('service_bus.logger'); $handler = function(string $watcherId, int $signalId) use ($stopDelay, $logger): void { $logger->info( 'A signal "{signalId}" was received', [ 'signalId' => $signalId, 'watcherId' => $watcherId, ] ); $this->entryPoint->stop($stopDelay); }; foreach ($signals as $signal) { /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::onSignal($signal, $handler); } return $this; }
php
public function useDefaultStopSignalHandler(int $stopDelay = 10, array $signals = [\SIGINT, \SIGTERM]): self { $stopDelay = 0 >= $stopDelay ? 1 : $stopDelay; /** * @noinspection PhpUnhandledExceptionInspection * * @var LoggerInterface $logger */ $logger = $this->getKernelContainerService('service_bus.logger'); $handler = function(string $watcherId, int $signalId) use ($stopDelay, $logger): void { $logger->info( 'A signal "{signalId}" was received', [ 'signalId' => $signalId, 'watcherId' => $watcherId, ] ); $this->entryPoint->stop($stopDelay); }; foreach ($signals as $signal) { /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::onSignal($signal, $handler); } return $this; }
[ "public", "function", "useDefaultStopSignalHandler", "(", "int", "$", "stopDelay", "=", "10", ",", "array", "$", "signals", "=", "[", "\\", "SIGINT", ",", "\\", "SIGTERM", "]", ")", ":", "self", "{", "$", "stopDelay", "=", "0", ">=", "$", "stopDelay", ...
Use default handler for signal "SIGINT" and "SIGTERM". @noinspection PhpDocMissingThrowsInspection @psalm-param array<mixed, int> $signals @param int $stopDelay The delay before the completion (in seconds) @param int[] $signals Processed signals @throws \Amp\Loop\UnsupportedFeatureException This might happen if ext-pcntl is missing and the loop driver doesn't support another way to dispatch signals @return $this
[ "Use", "default", "handler", "for", "signal", "SIGINT", "and", "SIGTERM", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/ServiceBusKernel.php#L198-L229
php-service-bus/service-bus
src/Application/ServiceBusKernel.php
ServiceBusKernel.stopAfter
public function stopAfter(int $seconds): self { $seconds = 0 >= $seconds ? 1 : $seconds; /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::delay( $seconds * 1000, function() use ($seconds): void { /** @var LoggerInterface $logger */ $logger = $this->getKernelContainerService('service_bus.logger'); $logger->info('The demon\'s lifetime has expired ({lifetime} seconds)', ['lifetime' => $seconds]); $this->entryPoint->stop(); } ); return $this; }
php
public function stopAfter(int $seconds): self { $seconds = 0 >= $seconds ? 1 : $seconds; /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::delay( $seconds * 1000, function() use ($seconds): void { /** @var LoggerInterface $logger */ $logger = $this->getKernelContainerService('service_bus.logger'); $logger->info('The demon\'s lifetime has expired ({lifetime} seconds)', ['lifetime' => $seconds]); $this->entryPoint->stop(); } ); return $this; }
[ "public", "function", "stopAfter", "(", "int", "$", "seconds", ")", ":", "self", "{", "$", "seconds", "=", "0", ">=", "$", "seconds", "?", "1", ":", "$", "seconds", ";", "/** @psalm-suppress MixedTypeCoercion Incorrect amphp types */", "Loop", "::", "delay", "...
Shut down after N seconds. @param int $seconds @return self
[ "Shut", "down", "after", "N", "seconds", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/ServiceBusKernel.php#L238-L257
php-service-bus/service-bus
src/Application/ServiceBusKernel.php
ServiceBusKernel.stopWhenFilesChange
public function stopWhenFilesChange(string $directoryPath, int $checkInterval = 30, int $stopDelay = 5): self { $checkInterval = 0 >= $checkInterval ? 1 : $checkInterval; $watcher = new FileChangesWatcher($directoryPath); /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::repeat( $checkInterval * 1000, function() use ($watcher, $stopDelay): \Generator { /** @var bool $changed */ $changed = yield $watcher->compare(); if (true === $changed) { /** @var LoggerInterface $logger */ $logger = $this->getKernelContainerService('service_bus.logger'); $logger->info( 'Application files have been changed. Shut down after {delay} seconds', ['delay' => $stopDelay] ); $this->entryPoint->stop($stopDelay); } } ); return $this; }
php
public function stopWhenFilesChange(string $directoryPath, int $checkInterval = 30, int $stopDelay = 5): self { $checkInterval = 0 >= $checkInterval ? 1 : $checkInterval; $watcher = new FileChangesWatcher($directoryPath); /** @psalm-suppress MixedTypeCoercion Incorrect amphp types */ Loop::repeat( $checkInterval * 1000, function() use ($watcher, $stopDelay): \Generator { /** @var bool $changed */ $changed = yield $watcher->compare(); if (true === $changed) { /** @var LoggerInterface $logger */ $logger = $this->getKernelContainerService('service_bus.logger'); $logger->info( 'Application files have been changed. Shut down after {delay} seconds', ['delay' => $stopDelay] ); $this->entryPoint->stop($stopDelay); } } ); return $this; }
[ "public", "function", "stopWhenFilesChange", "(", "string", "$", "directoryPath", ",", "int", "$", "checkInterval", "=", "30", ",", "int", "$", "stopDelay", "=", "5", ")", ":", "self", "{", "$", "checkInterval", "=", "0", ">=", "$", "checkInterval", "?", ...
Enable file change monitoring. If the application files have been modified, quit. @param string $directoryPath @param int $checkInterval Hash check interval (in seconds) @param int $stopDelay The delay before the completion (in seconds) @return self
[ "Enable", "file", "change", "monitoring", ".", "If", "the", "application", "files", "have", "been", "modified", "quit", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/ServiceBusKernel.php#L268-L297
php-service-bus/service-bus
src/Application/ServiceBusKernel.php
ServiceBusKernel.registerEndpointForMessages
public function registerEndpointForMessages(Endpoint $endpoint, string ...$messages): self { /** * @noinspection PhpUnhandledExceptionInspection * * @var EndpointRouter $entryPointRouter */ $entryPointRouter = $this->getKernelContainerService(EndpointRouter::class); /** @psalm-var class-string $messageClass */ foreach ($messages as $messageClass) { $entryPointRouter->registerRoute($messageClass, $endpoint); } return $this; }
php
public function registerEndpointForMessages(Endpoint $endpoint, string ...$messages): self { /** * @noinspection PhpUnhandledExceptionInspection * * @var EndpointRouter $entryPointRouter */ $entryPointRouter = $this->getKernelContainerService(EndpointRouter::class); /** @psalm-var class-string $messageClass */ foreach ($messages as $messageClass) { $entryPointRouter->registerRoute($messageClass, $endpoint); } return $this; }
[ "public", "function", "registerEndpointForMessages", "(", "Endpoint", "$", "endpoint", ",", "string", "...", "$", "messages", ")", ":", "self", "{", "/**\n * @noinspection PhpUnhandledExceptionInspection\n *\n * @var EndpointRouter $entryPointRouter\n ...
Apply specific route to deliver a messages By default, messages will be sent to the application transport. If a different option is specified for the message, it will be sent only to it. @noinspection PhpDocMissingThrowsInspection @param Endpoint $endpoint @param string ...$messages @return ServiceBusKernel
[ "Apply", "specific", "route", "to", "deliver", "a", "messages", "By", "default", "messages", "will", "be", "sent", "to", "the", "application", "transport", ".", "If", "a", "different", "option", "is", "specified", "for", "the", "message", "it", "will", "be",...
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/ServiceBusKernel.php#L311-L327
php-service-bus/service-bus
src/Application/ServiceBusKernel.php
ServiceBusKernel.registerDestinationForMessages
public function registerDestinationForMessages(DeliveryDestination $deliveryDestination, string ...$messages): self { /** * @noinspection PhpUnhandledExceptionInspection * * @var Endpoint $applicationEndpoint */ $applicationEndpoint = $this->getKernelContainerService(Endpoint::class); $newEndpoint = $applicationEndpoint->withNewDeliveryDestination($deliveryDestination); return $this->registerEndpointForMessages($newEndpoint, ...$messages); }
php
public function registerDestinationForMessages(DeliveryDestination $deliveryDestination, string ...$messages): self { /** * @noinspection PhpUnhandledExceptionInspection * * @var Endpoint $applicationEndpoint */ $applicationEndpoint = $this->getKernelContainerService(Endpoint::class); $newEndpoint = $applicationEndpoint->withNewDeliveryDestination($deliveryDestination); return $this->registerEndpointForMessages($newEndpoint, ...$messages); }
[ "public", "function", "registerDestinationForMessages", "(", "DeliveryDestination", "$", "deliveryDestination", ",", "string", "...", "$", "messages", ")", ":", "self", "{", "/**\n * @noinspection PhpUnhandledExceptionInspection\n *\n * @var Endpoint $applicat...
Like the registerEndpointForMessages method, it adds a custom message delivery route. The only difference is that the route is specified for the current application transport. @noinspection PhpDocMissingThrowsInspection @param DeliveryDestination $deliveryDestination @param string ...$messages @return ServiceBusKernel
[ "Like", "the", "registerEndpointForMessages", "method", "it", "adds", "a", "custom", "message", "delivery", "route", ".", "The", "only", "difference", "is", "that", "the", "route", "is", "specified", "for", "the", "current", "application", "transport", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/ServiceBusKernel.php#L340-L352
php-service-bus/service-bus
src/Application/ServiceBusKernel.php
ServiceBusKernel.getKernelContainerService
private function getKernelContainerService(string $service): object { /** @var \Symfony\Component\DependencyInjection\ServiceLocator $serviceLocator */ $serviceLocator = $this->container->get('service_bus.public_services_locator'); /** @var object $object */ $object = $serviceLocator->get($service); return $object; }
php
private function getKernelContainerService(string $service): object { /** @var \Symfony\Component\DependencyInjection\ServiceLocator $serviceLocator */ $serviceLocator = $this->container->get('service_bus.public_services_locator'); /** @var object $object */ $object = $serviceLocator->get($service); return $object; }
[ "private", "function", "getKernelContainerService", "(", "string", "$", "service", ")", ":", "object", "{", "/** @var \\Symfony\\Component\\DependencyInjection\\ServiceLocator $serviceLocator */", "$", "serviceLocator", "=", "$", "this", "->", "container", "->", "get", "(",...
@param string $service @throws \Throwable Unknown service @return object
[ "@param", "string", "$service" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/ServiceBusKernel.php#L361-L370
php-service-bus/service-bus
src/Application/Bootstrap.php
Bootstrap.enableAutoImportMessageHandlers
public function enableAutoImportMessageHandlers(array $directories, array $excludedFiles = []): self { $this->importParameters([ 'service_bus.auto_import.handlers_enabled' => true, 'service_bus.auto_import.handlers_directories' => $directories, 'service_bus.auto_import.handlers_excluded' => $excludedFiles, ]); $this->containerBuilder->addCompilerPasses(new ImportMessageHandlersCompilerPass()); return $this; }
php
public function enableAutoImportMessageHandlers(array $directories, array $excludedFiles = []): self { $this->importParameters([ 'service_bus.auto_import.handlers_enabled' => true, 'service_bus.auto_import.handlers_directories' => $directories, 'service_bus.auto_import.handlers_excluded' => $excludedFiles, ]); $this->containerBuilder->addCompilerPasses(new ImportMessageHandlersCompilerPass()); return $this; }
[ "public", "function", "enableAutoImportMessageHandlers", "(", "array", "$", "directories", ",", "array", "$", "excludedFiles", "=", "[", "]", ")", ":", "self", "{", "$", "this", "->", "importParameters", "(", "[", "'service_bus.auto_import.handlers_enabled'", "=>", ...
All message handlers from the specified directories will be registered automatically. Note: All files containing user-defined functions must be excluded Note: Increases start time because of the need to scan files @param array<int, string> $directories @param array<int, string> $excludedFiles @return self
[ "All", "message", "handlers", "from", "the", "specified", "directories", "will", "be", "registered", "automatically", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/Bootstrap.php#L98-L109
php-service-bus/service-bus
src/Application/Bootstrap.php
Bootstrap.boot
public function boot(): ContainerInterface { $this->containerBuilder->addCompilerPasses(new TaggedMessageHandlersCompilerPass(), new ServiceLocatorTagPass()); return $this->containerBuilder->build(); }
php
public function boot(): ContainerInterface { $this->containerBuilder->addCompilerPasses(new TaggedMessageHandlersCompilerPass(), new ServiceLocatorTagPass()); return $this->containerBuilder->build(); }
[ "public", "function", "boot", "(", ")", ":", "ContainerInterface", "{", "$", "this", "->", "containerBuilder", "->", "addCompilerPasses", "(", "new", "TaggedMessageHandlersCompilerPass", "(", ")", ",", "new", "ServiceLocatorTagPass", "(", ")", ")", ";", "return", ...
Compile container. @throws \InvalidArgumentException When provided tag is not defined in this extension @throws \LogicException Cannot dump an uncompiled container @throws \RuntimeException When cache file can't be written @throws \Symfony\Component\DependencyInjection\Exception\EnvParameterException When an env var exists but has not been dumped @throws \Throwable Boot module failed @return ContainerInterface
[ "Compile", "container", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/Bootstrap.php#L122-L127
php-service-bus/service-bus
src/Environment.php
Environment.create
public static function create(string $environment): self { $environment = \strtolower($environment); self::validateEnvironment($environment); return new self($environment); }
php
public static function create(string $environment): self { $environment = \strtolower($environment); self::validateEnvironment($environment); return new self($environment); }
[ "public", "static", "function", "create", "(", "string", "$", "environment", ")", ":", "self", "{", "$", "environment", "=", "\\", "strtolower", "(", "$", "environment", ")", ";", "self", "::", "validateEnvironment", "(", "$", "environment", ")", ";", "ret...
Creating the specified environment. @param string $environment @throws \LogicException The value of the environment is not specified, or is incorrect @return Environment
[ "Creating", "the", "specified", "environment", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Environment.php#L78-L85
php-service-bus/service-bus
src/Environment.php
Environment.validateEnvironment
private static function validateEnvironment(string $specifiedEnvironment): void { if ('' === $specifiedEnvironment || false === \in_array($specifiedEnvironment, self::LIST, true) ) { throw new \LogicException( \sprintf( 'Provided incorrect value of the environment: "%s". Allowable values: %s', $specifiedEnvironment, \implode(', ', \array_values(self::LIST)) ) ); } }
php
private static function validateEnvironment(string $specifiedEnvironment): void { if ('' === $specifiedEnvironment || false === \in_array($specifiedEnvironment, self::LIST, true) ) { throw new \LogicException( \sprintf( 'Provided incorrect value of the environment: "%s". Allowable values: %s', $specifiedEnvironment, \implode(', ', \array_values(self::LIST)) ) ); } }
[ "private", "static", "function", "validateEnvironment", "(", "string", "$", "specifiedEnvironment", ")", ":", "void", "{", "if", "(", "''", "===", "$", "specifiedEnvironment", "||", "false", "===", "\\", "in_array", "(", "$", "specifiedEnvironment", ",", "self",...
Validate the specified environment. @param string $specifiedEnvironment @throws \LogicException The value of the environment is not specified, or is incorrect @return void
[ "Validate", "the", "specified", "environment", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Environment.php#L159-L172
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php
ImportMessageHandlersCompilerPass.process
public function process(ContainerBuilder $container): void { if (true === self::enabled($container)) { $excludedFiles = canonicalizeFilesPath(self::getExcludedFiles($container)); $files = searchFiles(self::getDirectories($container), '/\.php/i'); $this->registerClasses($container, $files, $excludedFiles); } }
php
public function process(ContainerBuilder $container): void { if (true === self::enabled($container)) { $excludedFiles = canonicalizeFilesPath(self::getExcludedFiles($container)); $files = searchFiles(self::getDirectories($container), '/\.php/i'); $this->registerClasses($container, $files, $excludedFiles); } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "if", "(", "true", "===", "self", "::", "enabled", "(", "$", "container", ")", ")", "{", "$", "excludedFiles", "=", "canonicalizeFilesPath", "(", "self", "::...
{@inheritdoc} @param ContainerBuilder $container @throws \LogicException @throws \ServiceBus\Common\Exceptions\FileSystemException @return void
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php#L36-L46
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php
ImportMessageHandlersCompilerPass.registerClasses
private function registerClasses(ContainerBuilder $container, \Generator $generator, array $excludedFiles): void { /** @var \SplFileInfo $file */ foreach ($generator as $file) { $filePath = $file->getRealPath(); if (false === $filePath || true === \in_array($filePath, $excludedFiles, true)) { continue; } $class = extractNamespaceFromFile($filePath); if ( null !== $class && true === self::isMessageHandler($filePath) && false === $container->hasDefinition($class) ) { $container->register($class, $class)->addTag('service_bus.service'); } } }
php
private function registerClasses(ContainerBuilder $container, \Generator $generator, array $excludedFiles): void { /** @var \SplFileInfo $file */ foreach ($generator as $file) { $filePath = $file->getRealPath(); if (false === $filePath || true === \in_array($filePath, $excludedFiles, true)) { continue; } $class = extractNamespaceFromFile($filePath); if ( null !== $class && true === self::isMessageHandler($filePath) && false === $container->hasDefinition($class) ) { $container->register($class, $class)->addTag('service_bus.service'); } } }
[ "private", "function", "registerClasses", "(", "ContainerBuilder", "$", "container", ",", "\\", "Generator", "$", "generator", ",", "array", "$", "excludedFiles", ")", ":", "void", "{", "/** @var \\SplFileInfo $file */", "foreach", "(", "$", "generator", "as", "$"...
@psalm-param \Generator<\SplFileInfo> $generator @psalm-param array<int, string> $excludedFiles @param ContainerBuilder $container @param \Generator $generator @param string[] $excludedFiles @throws \LogicException @throws \ServiceBus\Common\Exceptions\FileSystemException @return void
[ "@psalm", "-", "param", "\\", "Generator<", "\\", "SplFileInfo", ">", "$generator", "@psalm", "-", "param", "array<int", "string", ">", "$excludedFiles" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php#L61-L83
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php
ImportMessageHandlersCompilerPass.enabled
private static function enabled(ContainerBuilder $container): bool { /** @noinspection PhpUnhandledExceptionInspection */ return true === $container->hasParameter('service_bus.auto_import.handlers_enabled') ? (bool) $container->getParameter('service_bus.auto_import.handlers_enabled') : false; }
php
private static function enabled(ContainerBuilder $container): bool { /** @noinspection PhpUnhandledExceptionInspection */ return true === $container->hasParameter('service_bus.auto_import.handlers_enabled') ? (bool) $container->getParameter('service_bus.auto_import.handlers_enabled') : false; }
[ "private", "static", "function", "enabled", "(", "ContainerBuilder", "$", "container", ")", ":", "bool", "{", "/** @noinspection PhpUnhandledExceptionInspection */", "return", "true", "===", "$", "container", "->", "hasParameter", "(", "'service_bus.auto_import.handlers_ena...
@noinspection PhpDocMissingThrowsInspection @param ContainerBuilder $container @return bool
[ "@noinspection", "PhpDocMissingThrowsInspection" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php#L92-L98
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php
ImportMessageHandlersCompilerPass.isMessageHandler
private static function isMessageHandler(string $filePath): bool { $fileContent = \file_get_contents($filePath); if (false !== $fileContent) { return false !== \strpos($fileContent, '@CommandHandler') || false !== \strpos($fileContent, '@EventListener'); } throw new \LogicException( \sprintf('Error loading "%s" file contents', $filePath) ); }
php
private static function isMessageHandler(string $filePath): bool { $fileContent = \file_get_contents($filePath); if (false !== $fileContent) { return false !== \strpos($fileContent, '@CommandHandler') || false !== \strpos($fileContent, '@EventListener'); } throw new \LogicException( \sprintf('Error loading "%s" file contents', $filePath) ); }
[ "private", "static", "function", "isMessageHandler", "(", "string", "$", "filePath", ")", ":", "bool", "{", "$", "fileContent", "=", "\\", "file_get_contents", "(", "$", "filePath", ")", ";", "if", "(", "false", "!==", "$", "fileContent", ")", "{", "return...
@param string $filePath @throws \LogicException Error loading file contents @return bool
[ "@param", "string", "$filePath" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php#L107-L120
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php
ImportMessageHandlersCompilerPass.getDirectories
private static function getDirectories(ContainerBuilder $container): array { /** * @noinspection PhpUnhandledExceptionInspection * @psalm-var array<int, string> $directories * * @var string[] $directories */ $directories = true === $container->hasParameter('service_bus.auto_import.handlers_directories') ? $container->getParameter('service_bus.auto_import.handlers_directories') : []; return $directories; }
php
private static function getDirectories(ContainerBuilder $container): array { /** * @noinspection PhpUnhandledExceptionInspection * @psalm-var array<int, string> $directories * * @var string[] $directories */ $directories = true === $container->hasParameter('service_bus.auto_import.handlers_directories') ? $container->getParameter('service_bus.auto_import.handlers_directories') : []; return $directories; }
[ "private", "static", "function", "getDirectories", "(", "ContainerBuilder", "$", "container", ")", ":", "array", "{", "/**\n * @noinspection PhpUnhandledExceptionInspection\n * @psalm-var array<int, string> $directories\n *\n * @var string[] $directories\n ...
@noinspection PhpDocMissingThrowsInspection @param ContainerBuilder $container @return string[]
[ "@noinspection", "PhpDocMissingThrowsInspection" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php#L129-L142
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php
ImportMessageHandlersCompilerPass.getExcludedFiles
private static function getExcludedFiles(ContainerBuilder $container): array { /** * @noinspection PhpUnhandledExceptionInspection * @psalm-var array<int, string> $excludedFiles * * @var string[] $excludedFiles */ $excludedFiles = true === $container->hasParameter('service_bus.auto_import.handlers_excluded') ? $container->getParameter('service_bus.auto_import.handlers_excluded') : []; return $excludedFiles; }
php
private static function getExcludedFiles(ContainerBuilder $container): array { /** * @noinspection PhpUnhandledExceptionInspection * @psalm-var array<int, string> $excludedFiles * * @var string[] $excludedFiles */ $excludedFiles = true === $container->hasParameter('service_bus.auto_import.handlers_excluded') ? $container->getParameter('service_bus.auto_import.handlers_excluded') : []; return $excludedFiles; }
[ "private", "static", "function", "getExcludedFiles", "(", "ContainerBuilder", "$", "container", ")", ":", "array", "{", "/**\n * @noinspection PhpUnhandledExceptionInspection\n * @psalm-var array<int, string> $excludedFiles\n *\n * @var string[] $excludedFi...
@noinspection PhpDocMissingThrowsInspection @psalm-return array<int, string> @param ContainerBuilder $container @return string[]
[ "@noinspection", "PhpDocMissingThrowsInspection" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/ImportMessageHandlersCompilerPass.php#L153-L166
php-service-bus/service-bus
src/Infrastructure/Logger/Handlers/StdOut/StdOutHandler.php
StdOutHandler.write
protected function write(array $record): void { try { $this->streamWriter->write((string) $record['formatted']); } // @codeCoverageIgnoreStart catch (\Throwable $throwable) { /** Not interest */ } // @codeCoverageIgnoreEnd }
php
protected function write(array $record): void { try { $this->streamWriter->write((string) $record['formatted']); } // @codeCoverageIgnoreStart catch (\Throwable $throwable) { /** Not interest */ } // @codeCoverageIgnoreEnd }
[ "protected", "function", "write", "(", "array", "$", "record", ")", ":", "void", "{", "try", "{", "$", "this", "->", "streamWriter", "->", "write", "(", "(", "string", ")", "$", "record", "[", "'formatted'", "]", ")", ";", "}", "// @codeCoverageIgnoreSta...
{@inheritdoc} @return void
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Infrastructure/Logger/Handlers/StdOut/StdOutHandler.php#L49-L61
php-service-bus/service-bus
src/Endpoint/EndpointRouter.php
EndpointRouter.registerRoutes
public function registerRoutes(array $messages, Endpoint $endpoint): void { foreach ($messages as $message) { $this->registerRoute($message, $endpoint); } }
php
public function registerRoutes(array $messages, Endpoint $endpoint): void { foreach ($messages as $message) { $this->registerRoute($message, $endpoint); } }
[ "public", "function", "registerRoutes", "(", "array", "$", "messages", ",", "Endpoint", "$", "endpoint", ")", ":", "void", "{", "foreach", "(", "$", "messages", "as", "$", "message", ")", "{", "$", "this", "->", "registerRoute", "(", "$", "message", ",",...
Add custom endpoint for multiple messages. @psalm-param array<array-key, class-string> $messages @param string[] $messages @param Endpoint $endpoint @return void
[ "Add", "custom", "endpoint", "for", "multiple", "messages", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Endpoint/EndpointRouter.php#L70-L76
php-service-bus/service-bus
src/Endpoint/EndpointRouter.php
EndpointRouter.registerRoute
public function registerRoute(string $messageClass, Endpoint $endpoint): void { $this->routes[$messageClass][] = $endpoint; }
php
public function registerRoute(string $messageClass, Endpoint $endpoint): void { $this->routes[$messageClass][] = $endpoint; }
[ "public", "function", "registerRoute", "(", "string", "$", "messageClass", ",", "Endpoint", "$", "endpoint", ")", ":", "void", "{", "$", "this", "->", "routes", "[", "$", "messageClass", "]", "[", "]", "=", "$", "endpoint", ";", "}" ]
Add custom endpoint to specified message. @psalm-param class-string $messageClass @param string $messageClass @param Endpoint $endpoint @return void
[ "Add", "custom", "endpoint", "to", "specified", "message", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Endpoint/EndpointRouter.php#L88-L91
php-service-bus/service-bus
src/Endpoint/EndpointRouter.php
EndpointRouter.route
public function route(string $messageClass): array { if (false === empty($this->routes[$messageClass])) { return $this->routes[$messageClass]; } return $this->globalEndpoints; }
php
public function route(string $messageClass): array { if (false === empty($this->routes[$messageClass])) { return $this->routes[$messageClass]; } return $this->globalEndpoints; }
[ "public", "function", "route", "(", "string", "$", "messageClass", ")", ":", "array", "{", "if", "(", "false", "===", "empty", "(", "$", "this", "->", "routes", "[", "$", "messageClass", "]", ")", ")", "{", "return", "$", "this", "->", "routes", "[",...
Receiving a message sending route If no specific route is registered, the default endpoint route will be returned. @psalm-return array<array-key, \ServiceBus\Endpoint\Endpoint> @param string $messageClass @return \ServiceBus\Endpoint\Endpoint[]
[ "Receiving", "a", "message", "sending", "route", "If", "no", "specific", "route", "is", "registered", "the", "default", "endpoint", "route", "will", "be", "returned", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Endpoint/EndpointRouter.php#L103-L111
php-service-bus/service-bus
src/EntryPoint/DefaultEntryPointProcessor.php
DefaultEntryPointProcessor.handle
public function handle(IncomingPackage $package): Promise { $messageDecoder = $this->messageDecoder; $messagesRouter = $this->messagesRouter; $logger = $this->logger; $endpointRouter = $this->endpointRouter; /** @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) */ return call( static function(IncomingPackage $package) use ($messageDecoder, $messagesRouter, $endpointRouter, $logger): \Generator { try { $message = $messageDecoder->decode($package); } catch (DecodeMessageFailed $exception) { $logger->error('Failed to denormalize the message', [ 'packageId' => $package->id(), 'traceId' => $package->traceId(), 'payload' => $package->payload(), 'throwableMessage' => $exception->getMessage(), ]); yield $package->ack(); return; } $logger->debug('Dispatch "{messageClass}" message', [ 'packageId' => $package->id(), 'traceId' => $package->traceId(), 'messageClass' => \get_class($message), ]); $executors = $messagesRouter->match($message); if (0 === \count($executors)) { $logger->debug( 'There are no handlers configured for the message "{messageClass}"', ['messageClass' => \get_class($message)] ); } /** @var \ServiceBus\Common\MessageExecutor\MessageExecutor $executor */ foreach ($executors as $executor) { $context = new KernelContext($package, $endpointRouter, $logger); try { yield $executor($message, $context); } catch (\Throwable $throwable) { $context->logContextThrowable($throwable); } } yield $package->ack(); }, $package ); }
php
public function handle(IncomingPackage $package): Promise { $messageDecoder = $this->messageDecoder; $messagesRouter = $this->messagesRouter; $logger = $this->logger; $endpointRouter = $this->endpointRouter; /** @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) */ return call( static function(IncomingPackage $package) use ($messageDecoder, $messagesRouter, $endpointRouter, $logger): \Generator { try { $message = $messageDecoder->decode($package); } catch (DecodeMessageFailed $exception) { $logger->error('Failed to denormalize the message', [ 'packageId' => $package->id(), 'traceId' => $package->traceId(), 'payload' => $package->payload(), 'throwableMessage' => $exception->getMessage(), ]); yield $package->ack(); return; } $logger->debug('Dispatch "{messageClass}" message', [ 'packageId' => $package->id(), 'traceId' => $package->traceId(), 'messageClass' => \get_class($message), ]); $executors = $messagesRouter->match($message); if (0 === \count($executors)) { $logger->debug( 'There are no handlers configured for the message "{messageClass}"', ['messageClass' => \get_class($message)] ); } /** @var \ServiceBus\Common\MessageExecutor\MessageExecutor $executor */ foreach ($executors as $executor) { $context = new KernelContext($package, $endpointRouter, $logger); try { yield $executor($message, $context); } catch (\Throwable $throwable) { $context->logContextThrowable($throwable); } } yield $package->ack(); }, $package ); }
[ "public", "function", "handle", "(", "IncomingPackage", "$", "package", ")", ":", "Promise", "{", "$", "messageDecoder", "=", "$", "this", "->", "messageDecoder", ";", "$", "messagesRouter", "=", "$", "this", "->", "messagesRouter", ";", "$", "logger", "=", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/EntryPoint/DefaultEntryPointProcessor.php#L77-L141
php-service-bus/service-bus
src/ArgumentResolvers/ContainerArgumentResolver.php
ContainerArgumentResolver.supports
public function supports(MessageHandlerArgument $argument): bool { return true === $argument->isObject && true === $this->serviceLocator->has((string) $argument->typeClass); }
php
public function supports(MessageHandlerArgument $argument): bool { return true === $argument->isObject && true === $this->serviceLocator->has((string) $argument->typeClass); }
[ "public", "function", "supports", "(", "MessageHandlerArgument", "$", "argument", ")", ":", "bool", "{", "return", "true", "===", "$", "argument", "->", "isObject", "&&", "true", "===", "$", "this", "->", "serviceLocator", "->", "has", "(", "(", "string", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/ArgumentResolvers/ContainerArgumentResolver.php#L40-L43
php-service-bus/service-bus
src/ArgumentResolvers/ContainerArgumentResolver.php
ContainerArgumentResolver.resolve
public function resolve(object $message, ServiceBusContext $context, MessageHandlerArgument $argument): object { /** @var object $object */ $object = $this->serviceLocator->get((string) $argument->typeClass); return $object; }
php
public function resolve(object $message, ServiceBusContext $context, MessageHandlerArgument $argument): object { /** @var object $object */ $object = $this->serviceLocator->get((string) $argument->typeClass); return $object; }
[ "public", "function", "resolve", "(", "object", "$", "message", ",", "ServiceBusContext", "$", "context", ",", "MessageHandlerArgument", "$", "argument", ")", ":", "object", "{", "/** @var object $object */", "$", "object", "=", "$", "this", "->", "serviceLocator"...
{@inheritdoc} @return object
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/ArgumentResolvers/ContainerArgumentResolver.php#L50-L56
php-service-bus/service-bus
src/Infrastructure/Logger/Handlers/Graylog/UdpHandler.php
UdpHandler.write
protected function write(array $record): void { try { $body = \json_encode($record); // @codeCoverageIgnoreStart if (false === \is_string($body)) { return; } // @codeCoverageIgnoreEnd if (true === $this->gzipMessage) { /** @noinspection UnnecessaryCastingInspection */ $body = (string) \gzcompress($body); } $this->outputStream()->write($body); } // @codeCoverageIgnoreStart catch (\Throwable $throwable) { /** Not interest */ } // @codeCoverageIgnoreEnd }
php
protected function write(array $record): void { try { $body = \json_encode($record); // @codeCoverageIgnoreStart if (false === \is_string($body)) { return; } // @codeCoverageIgnoreEnd if (true === $this->gzipMessage) { /** @noinspection UnnecessaryCastingInspection */ $body = (string) \gzcompress($body); } $this->outputStream()->write($body); } // @codeCoverageIgnoreStart catch (\Throwable $throwable) { /** Not interest */ } // @codeCoverageIgnoreEnd }
[ "protected", "function", "write", "(", "array", "$", "record", ")", ":", "void", "{", "try", "{", "$", "body", "=", "\\", "json_encode", "(", "$", "record", ")", ";", "// @codeCoverageIgnoreStart", "if", "(", "false", "===", "\\", "is_string", "(", "$", ...
{@inheritdoc} @return void
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Infrastructure/Logger/Handlers/Graylog/UdpHandler.php#L73-L100
php-service-bus/service-bus
src/Infrastructure/Logger/Handlers/Graylog/UdpHandler.php
UdpHandler.outputStream
private function outputStream(): ResourceOutputStream { if (null === $this->outputStream) { $this->outputStream = new ResourceOutputStream(self::createStream($this->host, $this->port), 65000); } return $this->outputStream; }
php
private function outputStream(): ResourceOutputStream { if (null === $this->outputStream) { $this->outputStream = new ResourceOutputStream(self::createStream($this->host, $this->port), 65000); } return $this->outputStream; }
[ "private", "function", "outputStream", "(", ")", ":", "ResourceOutputStream", "{", "if", "(", "null", "===", "$", "this", "->", "outputStream", ")", "{", "$", "this", "->", "outputStream", "=", "new", "ResourceOutputStream", "(", "self", "::", "createStream", ...
@throws \RuntimeException Could not connect @return ResourceOutputStream
[ "@throws", "\\", "RuntimeException", "Could", "not", "connect" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Infrastructure/Logger/Handlers/Graylog/UdpHandler.php#L115-L123
php-service-bus/service-bus
src/Infrastructure/Logger/Handlers/Graylog/UdpHandler.php
UdpHandler.createStream
private static function createStream(string $host, int $port) { $uri = \sprintf('udp://%s:%d', $host, $port); $stream = @\stream_socket_client($uri, $errno, $errstr, 0, \STREAM_CLIENT_CONNECT); if (false === $stream) { throw new \RuntimeException(\sprintf('Could not connect to %s', $uri)); } return $stream; }
php
private static function createStream(string $host, int $port) { $uri = \sprintf('udp://%s:%d', $host, $port); $stream = @\stream_socket_client($uri, $errno, $errstr, 0, \STREAM_CLIENT_CONNECT); if (false === $stream) { throw new \RuntimeException(\sprintf('Could not connect to %s', $uri)); } return $stream; }
[ "private", "static", "function", "createStream", "(", "string", "$", "host", ",", "int", "$", "port", ")", "{", "$", "uri", "=", "\\", "sprintf", "(", "'udp://%s:%d'", ",", "$", "host", ",", "$", "port", ")", ";", "$", "stream", "=", "@", "\\", "st...
@param string $host @param int $port @throws \RuntimeException Could not connect @return resource
[ "@param", "string", "$host", "@param", "int", "$port" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Infrastructure/Logger/Handlers/Graylog/UdpHandler.php#L133-L144
php-service-bus/service-bus
src/Infrastructure/Watchers/FileChangesWatcher.php
FileChangesWatcher.compare
public function compare(): Promise { /** @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) */ return call( function(): \Generator { /** @var string $bufferContent */ $bufferContent = yield from self::execute($this->directory); $hash = self::extractHash($bufferContent); /** A runtime error has occurred */ // @codeCoverageIgnoreStart if (null === $hash) { return false; } // @codeCoverageIgnoreEnd /** New hash is different from previously received */ if (null !== $this->previousHash && $this->previousHash !== $hash) { return true; } $this->previousHash = $hash; return false; } ); }
php
public function compare(): Promise { /** @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) */ return call( function(): \Generator { /** @var string $bufferContent */ $bufferContent = yield from self::execute($this->directory); $hash = self::extractHash($bufferContent); /** A runtime error has occurred */ // @codeCoverageIgnoreStart if (null === $hash) { return false; } // @codeCoverageIgnoreEnd /** New hash is different from previously received */ if (null !== $this->previousHash && $this->previousHash !== $hash) { return true; } $this->previousHash = $hash; return false; } ); }
[ "public", "function", "compare", "(", ")", ":", "Promise", "{", "/** @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args) */", "return", "call", "(", "function", "(", ")", ":", "\\", "Generator", "{", "/** @var string $bufferContent */", "$", "buffer...
Compare hashes If returned false, the files have not been changed. Otherwise, return true. @psalm-suppress MixedTypeCoercion Incorrect resolving the value of the promise @return Promise<bool>
[ "Compare", "hashes", "If", "returned", "false", "the", "files", "have", "not", "been", "changed", ".", "Otherwise", "return", "true", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Infrastructure/Watchers/FileChangesWatcher.php#L55-L85
php-service-bus/service-bus
src/Infrastructure/Watchers/FileChangesWatcher.php
FileChangesWatcher.execute
private static function execute(string $directory): \Generator { try { $process = new Process( \sprintf( 'find %s -name \'*.php\' \( -exec sha1sum "$PWD"/{} \; -o -print \) | sha1sum', $directory ) ); /** @psalm-suppress TooManyTemplateParams Wrong Promise template */ yield $process->start(); /** * @psalm-suppress TooManyTemplateParams Wrong Promise template * * @var string $bufferContent */ $bufferContent = yield buffer($process->getStdout()); return $bufferContent; } // @codeCoverageIgnoreStart catch (\Throwable $throwable) { return ''; } // @codeCoverageIgnoreEnd }
php
private static function execute(string $directory): \Generator { try { $process = new Process( \sprintf( 'find %s -name \'*.php\' \( -exec sha1sum "$PWD"/{} \; -o -print \) | sha1sum', $directory ) ); /** @psalm-suppress TooManyTemplateParams Wrong Promise template */ yield $process->start(); /** * @psalm-suppress TooManyTemplateParams Wrong Promise template * * @var string $bufferContent */ $bufferContent = yield buffer($process->getStdout()); return $bufferContent; } // @codeCoverageIgnoreStart catch (\Throwable $throwable) { return ''; } // @codeCoverageIgnoreEnd }
[ "private", "static", "function", "execute", "(", "string", "$", "directory", ")", ":", "\\", "Generator", "{", "try", "{", "$", "process", "=", "new", "Process", "(", "\\", "sprintf", "(", "'find %s -name \\'*.php\\' \\( -exec sha1sum \"$PWD\"/{} \\; -o -print \\) | s...
Execute calculate hashes. @psalm-suppress InvalidReturnType Incorrect resolving the value of the generator @param string $directory @return \Generator<string>
[ "Execute", "calculate", "hashes", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Infrastructure/Watchers/FileChangesWatcher.php#L96-L125
php-service-bus/service-bus
src/Infrastructure/Watchers/FileChangesWatcher.php
FileChangesWatcher.extractHash
private static function extractHash(string $response): ?string { $parts = \array_map('trim', \explode(' ', $response)); return $parts[0] ?? null; }
php
private static function extractHash(string $response): ?string { $parts = \array_map('trim', \explode(' ', $response)); return $parts[0] ?? null; }
[ "private", "static", "function", "extractHash", "(", "string", "$", "response", ")", ":", "?", "string", "{", "$", "parts", "=", "\\", "array_map", "(", "'trim'", ",", "\\", "explode", "(", "' '", ",", "$", "response", ")", ")", ";", "return", "$", "...
Get a hash from the stdOut. @param string $response @return string|null
[ "Get", "a", "hash", "from", "the", "stdOut", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Infrastructure/Watchers/FileChangesWatcher.php#L134-L139
php-service-bus/service-bus
src/Endpoint/MessageDeliveryEndpoint.php
MessageDeliveryEndpoint.withNewDeliveryDestination
public function withNewDeliveryDestination(DeliveryDestination $destination): Endpoint { return new self( $this->name, $this->transport, $destination, $this->encoder, $this->deliveryRetryHandler ); }
php
public function withNewDeliveryDestination(DeliveryDestination $destination): Endpoint { return new self( $this->name, $this->transport, $destination, $this->encoder, $this->deliveryRetryHandler ); }
[ "public", "function", "withNewDeliveryDestination", "(", "DeliveryDestination", "$", "destination", ")", ":", "Endpoint", "{", "return", "new", "self", "(", "$", "this", "->", "name", ",", "$", "this", "->", "transport", ",", "$", "destination", ",", "$", "t...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Endpoint/MessageDeliveryEndpoint.php#L96-L105
php-service-bus/service-bus
src/Endpoint/MessageDeliveryEndpoint.php
MessageDeliveryEndpoint.delivery
public function delivery(object $message, DeliveryOptions $options): Promise { $encoded = $this->encoder->handler->encode($message); $options->withHeader(Transport::SERVICE_BUS_SERIALIZER_HEADER, $this->encoder->tag); return $this->deferredDelivery( self::createPackage($encoded, $options, $this->destination) ); }
php
public function delivery(object $message, DeliveryOptions $options): Promise { $encoded = $this->encoder->handler->encode($message); $options->withHeader(Transport::SERVICE_BUS_SERIALIZER_HEADER, $this->encoder->tag); return $this->deferredDelivery( self::createPackage($encoded, $options, $this->destination) ); }
[ "public", "function", "delivery", "(", "object", "$", "message", ",", "DeliveryOptions", "$", "options", ")", ":", "Promise", "{", "$", "encoded", "=", "$", "this", "->", "encoder", "->", "handler", "->", "encode", "(", "$", "message", ")", ";", "$", "...
@psalm-suppress MixedInferredReturnType {@inheritdoc}
[ "@psalm", "-", "suppress", "MixedInferredReturnType" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Endpoint/MessageDeliveryEndpoint.php#L112-L121
php-service-bus/service-bus
src/Endpoint/MessageDeliveryEndpoint.php
MessageDeliveryEndpoint.createPackage
private static function createPackage( string $payload, DeliveryOptions $options, DeliveryDestination $destination ): OutboundPackage { return OutboundPackage::create( $payload, $options->headers(), $destination, $options->traceId(), $options->isPersistent(), // @todo: fixme false, false, $options->expirationAfter() ); }
php
private static function createPackage( string $payload, DeliveryOptions $options, DeliveryDestination $destination ): OutboundPackage { return OutboundPackage::create( $payload, $options->headers(), $destination, $options->traceId(), $options->isPersistent(), // @todo: fixme false, false, $options->expirationAfter() ); }
[ "private", "static", "function", "createPackage", "(", "string", "$", "payload", ",", "DeliveryOptions", "$", "options", ",", "DeliveryDestination", "$", "destination", ")", ":", "OutboundPackage", "{", "return", "OutboundPackage", "::", "create", "(", "$", "paylo...
Create outbound package with specified parameters. @param string $payload @param DeliveryOptions $options @param DeliveryDestination $destination @return OutboundPackage
[ "Create", "outbound", "package", "with", "specified", "parameters", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Endpoint/MessageDeliveryEndpoint.php#L132-L148
php-service-bus/service-bus
src/Endpoint/MessageDeliveryEndpoint.php
MessageDeliveryEndpoint.deferredDelivery
private function deferredDelivery(OutboundPackage $package): Promise { $deferred = new Deferred(); /** * @psalm-suppress MixedTypeCoercion Incorrect amphp types * @psalm-suppress InvalidArgument */ Loop::defer( function() use ($package, $deferred): \Generator { try { yield call( $this->deliveryRetryHandler, function() use ($package): \Generator { yield $this->transport->send($package); }, SendMessageFailed::class ); $deferred->resolve(); } catch (\Throwable $throwable) { $deferred->fail($throwable); } } ); return $deferred->promise(); }
php
private function deferredDelivery(OutboundPackage $package): Promise { $deferred = new Deferred(); /** * @psalm-suppress MixedTypeCoercion Incorrect amphp types * @psalm-suppress InvalidArgument */ Loop::defer( function() use ($package, $deferred): \Generator { try { yield call( $this->deliveryRetryHandler, function() use ($package): \Generator { yield $this->transport->send($package); }, SendMessageFailed::class ); $deferred->resolve(); } catch (\Throwable $throwable) { $deferred->fail($throwable); } } ); return $deferred->promise(); }
[ "private", "function", "deferredDelivery", "(", "OutboundPackage", "$", "package", ")", ":", "Promise", "{", "$", "deferred", "=", "new", "Deferred", "(", ")", ";", "/**\n * @psalm-suppress MixedTypeCoercion Incorrect amphp types\n * @psalm-suppress InvalidArgum...
@param OutboundPackage $package @return Promise
[ "@param", "OutboundPackage", "$package" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Endpoint/MessageDeliveryEndpoint.php#L155-L187
php-service-bus/service-bus
src/Services/MessagesRouterConfigurator.php
MessagesRouterConfigurator.configure
public function configure(Router $router): void { try { /** @var ServiceHandlersLoader $serviceConfigurationExtractor */ $serviceConfigurationExtractor = $this->routingServiceLocator->get(ServiceHandlersLoader::class); foreach ($this->servicesList as $serviceId) { /** @var object $serviceObject */ $serviceObject = $this->servicesServiceLocator->get(\sprintf('%s_service', $serviceId)); /** @var \ServiceBus\Services\Configuration\ServiceMessageHandler $handler */ foreach ($serviceConfigurationExtractor->load($serviceObject) as $handler) { self::assertMessageClassSpecifiedInArguments($serviceObject, $handler->messageHandler); $messageExecutor = $this->executorFactory->create($handler->messageHandler); $registerMethod = true === $handler->isCommandHandler() ? 'registerHandler' : 'registerListener'; $router->{$registerMethod}((string) $handler->messageHandler->messageClass, $messageExecutor); } } } catch (\Throwable $throwable) { throw new MessageRouterConfigurationFailed($throwable->getMessage(), (int) $throwable->getCode(), $throwable); } }
php
public function configure(Router $router): void { try { /** @var ServiceHandlersLoader $serviceConfigurationExtractor */ $serviceConfigurationExtractor = $this->routingServiceLocator->get(ServiceHandlersLoader::class); foreach ($this->servicesList as $serviceId) { /** @var object $serviceObject */ $serviceObject = $this->servicesServiceLocator->get(\sprintf('%s_service', $serviceId)); /** @var \ServiceBus\Services\Configuration\ServiceMessageHandler $handler */ foreach ($serviceConfigurationExtractor->load($serviceObject) as $handler) { self::assertMessageClassSpecifiedInArguments($serviceObject, $handler->messageHandler); $messageExecutor = $this->executorFactory->create($handler->messageHandler); $registerMethod = true === $handler->isCommandHandler() ? 'registerHandler' : 'registerListener'; $router->{$registerMethod}((string) $handler->messageHandler->messageClass, $messageExecutor); } } } catch (\Throwable $throwable) { throw new MessageRouterConfigurationFailed($throwable->getMessage(), (int) $throwable->getCode(), $throwable); } }
[ "public", "function", "configure", "(", "Router", "$", "router", ")", ":", "void", "{", "try", "{", "/** @var ServiceHandlersLoader $serviceConfigurationExtractor */", "$", "serviceConfigurationExtractor", "=", "$", "this", "->", "routingServiceLocator", "->", "get", "(...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/MessagesRouterConfigurator.php#L79-L110
php-service-bus/service-bus
src/Services/MessagesRouterConfigurator.php
MessagesRouterConfigurator.assertMessageClassSpecifiedInArguments
private static function assertMessageClassSpecifiedInArguments(object $service, MessageHandler $handler): void { if (null === $handler->messageClass || '' === (string) $handler->messageClass) { throw new \LogicException( \sprintf( 'The message argument was not found in the "%s:%s" method', \get_class($service), $handler->methodName ) ); } }
php
private static function assertMessageClassSpecifiedInArguments(object $service, MessageHandler $handler): void { if (null === $handler->messageClass || '' === (string) $handler->messageClass) { throw new \LogicException( \sprintf( 'The message argument was not found in the "%s:%s" method', \get_class($service), $handler->methodName ) ); } }
[ "private", "static", "function", "assertMessageClassSpecifiedInArguments", "(", "object", "$", "service", ",", "MessageHandler", "$", "handler", ")", ":", "void", "{", "if", "(", "null", "===", "$", "handler", "->", "messageClass", "||", "''", "===", "(", "str...
@param object $service @param MessageHandler $handler @throws \LogicException @return void
[ "@param", "object", "$service", "@param", "MessageHandler", "$handler" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Services/MessagesRouterConfigurator.php#L120-L132
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/TaggedMessageHandlersCompilerPass.php
TaggedMessageHandlersCompilerPass.process
public function process(ContainerBuilder $container): void { $servicesReference = []; $serviceIds = []; /** * @psalm-var array<string, array<mixed, string>> $taggedServices * * @var array $taggedServices */ $taggedServices = $container->findTaggedServiceIds('service_bus.service'); foreach ($taggedServices as $id => $tags) { /** @psalm-var class-string|null $serviceClass */ $serviceClass = $container->getDefinition($id)->getClass(); if (null !== $serviceClass) { $this->collectServiceDependencies($serviceClass, $container, $servicesReference); $serviceIds[] = $serviceClass; $servicesReference[\sprintf('%s_service', $serviceClass)] = new ServiceClosureArgument( new Reference($id) ); } } $container->setParameter('service_bus.services_map', $serviceIds); $container ->register('service_bus.services_locator', ServiceLocator::class) ->setPublic(true) ->setArguments([$servicesReference]); }
php
public function process(ContainerBuilder $container): void { $servicesReference = []; $serviceIds = []; /** * @psalm-var array<string, array<mixed, string>> $taggedServices * * @var array $taggedServices */ $taggedServices = $container->findTaggedServiceIds('service_bus.service'); foreach ($taggedServices as $id => $tags) { /** @psalm-var class-string|null $serviceClass */ $serviceClass = $container->getDefinition($id)->getClass(); if (null !== $serviceClass) { $this->collectServiceDependencies($serviceClass, $container, $servicesReference); $serviceIds[] = $serviceClass; $servicesReference[\sprintf('%s_service', $serviceClass)] = new ServiceClosureArgument( new Reference($id) ); } } $container->setParameter('service_bus.services_map', $serviceIds); $container ->register('service_bus.services_locator', ServiceLocator::class) ->setPublic(true) ->setArguments([$servicesReference]); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "servicesReference", "=", "[", "]", ";", "$", "serviceIds", "=", "[", "]", ";", "/**\n * @psalm-var array<string, array<mixed, string>> $taggedServices\n ...
{@inheritdoc} @throws \Exception
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/TaggedMessageHandlersCompilerPass.php#L32-L67
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/TaggedMessageHandlersCompilerPass.php
TaggedMessageHandlersCompilerPass.collectServiceDependencies
private function collectServiceDependencies(string $serviceClass, ContainerBuilder $container, array &$servicesReference): void { $reflectionClass = new \ReflectionClass($serviceClass); foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) { foreach ($reflectionMethod->getParameters() as $parameter) { if (false === $parameter->hasType()) { continue; } /** @var \ReflectionType $reflectionType */ $reflectionType = $parameter->getType(); $reflectionTypeName = $reflectionType->getName(); if (true === self::supportedType($parameter) && true === $container->has($reflectionTypeName)) { $servicesReference[$reflectionTypeName] = new ServiceClosureArgument(new Reference($reflectionTypeName)); } } } }
php
private function collectServiceDependencies(string $serviceClass, ContainerBuilder $container, array &$servicesReference): void { $reflectionClass = new \ReflectionClass($serviceClass); foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) { foreach ($reflectionMethod->getParameters() as $parameter) { if (false === $parameter->hasType()) { continue; } /** @var \ReflectionType $reflectionType */ $reflectionType = $parameter->getType(); $reflectionTypeName = $reflectionType->getName(); if (true === self::supportedType($parameter) && true === $container->has($reflectionTypeName)) { $servicesReference[$reflectionTypeName] = new ServiceClosureArgument(new Reference($reflectionTypeName)); } } } }
[ "private", "function", "collectServiceDependencies", "(", "string", "$", "serviceClass", ",", "ContainerBuilder", "$", "container", ",", "array", "&", "$", "servicesReference", ")", ":", "void", "{", "$", "reflectionClass", "=", "new", "\\", "ReflectionClass", "("...
@psalm-param class-string $serviceClass @param string $serviceClass @param ContainerBuilder $container @param array $servicesReference (passed by reference) @throws \ReflectionException @return void
[ "@psalm", "-", "param", "class", "-", "string", "$serviceClass" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/TaggedMessageHandlersCompilerPass.php#L80-L103
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/TaggedMessageHandlersCompilerPass.php
TaggedMessageHandlersCompilerPass.supportedType
private static function supportedType(\ReflectionParameter $parameter): bool { /** @var \ReflectionType $reflectionType */ $reflectionType = $parameter->getType(); $reflectionTypeName = $reflectionType->getName(); return (true === \class_exists($reflectionTypeName) || true === \interface_exists($reflectionTypeName)) && false === \is_a($reflectionTypeName, ServiceBusContext::class, true) && false === \is_a($reflectionTypeName, \Throwable::class, true); }
php
private static function supportedType(\ReflectionParameter $parameter): bool { /** @var \ReflectionType $reflectionType */ $reflectionType = $parameter->getType(); $reflectionTypeName = $reflectionType->getName(); return (true === \class_exists($reflectionTypeName) || true === \interface_exists($reflectionTypeName)) && false === \is_a($reflectionTypeName, ServiceBusContext::class, true) && false === \is_a($reflectionTypeName, \Throwable::class, true); }
[ "private", "static", "function", "supportedType", "(", "\\", "ReflectionParameter", "$", "parameter", ")", ":", "bool", "{", "/** @var \\ReflectionType $reflectionType */", "$", "reflectionType", "=", "$", "parameter", "->", "getType", "(", ")", ";", "$", "reflectio...
@param \ReflectionParameter $parameter @return bool
[ "@param", "\\", "ReflectionParameter", "$parameter" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/TaggedMessageHandlersCompilerPass.php#L110-L119
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/Logger/LoggerCompilerPass.php
LoggerCompilerPass.process
public function process(ContainerBuilder $container): void { $loggerDefinition = $container->getDefinition('service_bus.logger'); if (NullLogger::class === $loggerDefinition->getClass()) { $loggerDefinition->setClass(Logger::class); $loggerDefinition->setArguments(['%service_bus.entry_point%']); } $processors = [ PsrLogMessageProcessor::class, MemoryUsageProcessor::class, ProcessIdProcessor::class, ]; foreach ($processors as $processor) { $container->addDefinitions([$processor => new Definition($processor)]); $loggerDefinition->addMethodCall( 'pushProcessor', [new Reference($processor)] ); } }
php
public function process(ContainerBuilder $container): void { $loggerDefinition = $container->getDefinition('service_bus.logger'); if (NullLogger::class === $loggerDefinition->getClass()) { $loggerDefinition->setClass(Logger::class); $loggerDefinition->setArguments(['%service_bus.entry_point%']); } $processors = [ PsrLogMessageProcessor::class, MemoryUsageProcessor::class, ProcessIdProcessor::class, ]; foreach ($processors as $processor) { $container->addDefinitions([$processor => new Definition($processor)]); $loggerDefinition->addMethodCall( 'pushProcessor', [new Reference($processor)] ); } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "loggerDefinition", "=", "$", "container", "->", "getDefinition", "(", "'service_bus.logger'", ")", ";", "if", "(", "NullLogger", "::", "class", "===", "$",...
{@inheritdoc} @throws \Throwable
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/Logger/LoggerCompilerPass.php#L35-L59
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/Logger/GraylogLoggerCompilerPass.php
GraylogLoggerCompilerPass.process
public function process(ContainerBuilder $container): void { $this->injectParameters($container); $handlerDefinition = new Definition(UdpHandler::class, [ '%service_bus.logger.graylog.udp_host%', '%service_bus.logger.graylog.udp_port%', '%service_bus.logger.graylog.gzip%', '%service_bus.logger.graylog.log_level%', ]); $container->addDefinitions([UdpHandler::class => $handlerDefinition]); (new LoggerCompilerPass())->process($container); $loggerDefinition = $container->getDefinition('service_bus.logger'); $loggerDefinition->addMethodCall( 'pushHandler', [new Reference(UdpHandler::class)] ); }
php
public function process(ContainerBuilder $container): void { $this->injectParameters($container); $handlerDefinition = new Definition(UdpHandler::class, [ '%service_bus.logger.graylog.udp_host%', '%service_bus.logger.graylog.udp_port%', '%service_bus.logger.graylog.gzip%', '%service_bus.logger.graylog.log_level%', ]); $container->addDefinitions([UdpHandler::class => $handlerDefinition]); (new LoggerCompilerPass())->process($container); $loggerDefinition = $container->getDefinition('service_bus.logger'); $loggerDefinition->addMethodCall( 'pushHandler', [new Reference(UdpHandler::class)] ); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "this", "->", "injectParameters", "(", "$", "container", ")", ";", "$", "handlerDefinition", "=", "new", "Definition", "(", "UdpHandler", "::", "class", "...
{@inheritdoc} @throws \Throwable
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/Logger/GraylogLoggerCompilerPass.php#L68-L89
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/Logger/GraylogLoggerCompilerPass.php
GraylogLoggerCompilerPass.injectParameters
private function injectParameters(ContainerBuilder $containerBuilder): void { $parameters = [ 'service_bus.logger.graylog.udp_host' => $this->host, 'service_bus.logger.graylog.udp_port' => $this->port, 'service_bus.logger.graylog.gzip' => $this->gzipMessage, 'service_bus.logger.graylog.log_level' => $this->logLevel, ]; foreach ($parameters as $key => $value) { $containerBuilder->setParameter($key, $value); } }
php
private function injectParameters(ContainerBuilder $containerBuilder): void { $parameters = [ 'service_bus.logger.graylog.udp_host' => $this->host, 'service_bus.logger.graylog.udp_port' => $this->port, 'service_bus.logger.graylog.gzip' => $this->gzipMessage, 'service_bus.logger.graylog.log_level' => $this->logLevel, ]; foreach ($parameters as $key => $value) { $containerBuilder->setParameter($key, $value); } }
[ "private", "function", "injectParameters", "(", "ContainerBuilder", "$", "containerBuilder", ")", ":", "void", "{", "$", "parameters", "=", "[", "'service_bus.logger.graylog.udp_host'", "=>", "$", "this", "->", "host", ",", "'service_bus.logger.graylog.udp_port'", "=>",...
@param ContainerBuilder $containerBuilder @throws \Throwable
[ "@param", "ContainerBuilder", "$containerBuilder" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/Logger/GraylogLoggerCompilerPass.php#L96-L108
php-service-bus/service-bus
src/MessageExecutor/MessageValidationExecutor.php
MessageValidationExecutor.publishViolations
private static function publishViolations(string $eventClass, ServiceBusContext $context): Promise { /** * @noinspection VariableFunctionsUsageInspection * * @var \ServiceBus\Services\Contracts\ValidationFailedEvent $event */ $event = \forward_static_call_array([$eventClass, 'create'], [$context->traceId(), $context->violations()]); return $context->delivery($event); }
php
private static function publishViolations(string $eventClass, ServiceBusContext $context): Promise { /** * @noinspection VariableFunctionsUsageInspection * * @var \ServiceBus\Services\Contracts\ValidationFailedEvent $event */ $event = \forward_static_call_array([$eventClass, 'create'], [$context->traceId(), $context->violations()]); return $context->delivery($event); }
[ "private", "static", "function", "publishViolations", "(", "string", "$", "eventClass", ",", "ServiceBusContext", "$", "context", ")", ":", "Promise", "{", "/**\n * @noinspection VariableFunctionsUsageInspection\n *\n * @var \\ServiceBus\\Services\\Contracts\\...
Publish failed event. @param string $eventClass @param ServiceBusContext $context @return Promise
[ "Publish", "failed", "event", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/MessageExecutor/MessageValidationExecutor.php#L102-L112
php-service-bus/service-bus
src/MessageExecutor/MessageValidationExecutor.php
MessageValidationExecutor.bindViolations
private static function bindViolations(ConstraintViolationList $violations, ServiceBusContext $context): void { $errors = []; /** @var \Symfony\Component\Validator\ConstraintViolation $violation */ foreach ($violations as $violation) { $errors[$violation->getPropertyPath()][] = $violation->getMessage(); } try { invokeReflectionMethod($context, 'validationFailed', $errors); } // @codeCoverageIgnoreStart catch (\Throwable $throwable) { /** No exceptions can happen */ } // @codeCoverageIgnoreEnd }
php
private static function bindViolations(ConstraintViolationList $violations, ServiceBusContext $context): void { $errors = []; /** @var \Symfony\Component\Validator\ConstraintViolation $violation */ foreach ($violations as $violation) { $errors[$violation->getPropertyPath()][] = $violation->getMessage(); } try { invokeReflectionMethod($context, 'validationFailed', $errors); } // @codeCoverageIgnoreStart catch (\Throwable $throwable) { /** No exceptions can happen */ } // @codeCoverageIgnoreEnd }
[ "private", "static", "function", "bindViolations", "(", "ConstraintViolationList", "$", "violations", ",", "ServiceBusContext", "$", "context", ")", ":", "void", "{", "$", "errors", "=", "[", "]", ";", "/** @var \\Symfony\\Component\\Validator\\ConstraintViolation $violat...
Bind violations to context. @param ConstraintViolationList $violations @param ServiceBusContext $context @return void
[ "Bind", "violations", "to", "context", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/MessageExecutor/MessageValidationExecutor.php#L122-L142
php-service-bus/service-bus
src/Infrastructure/Watchers/LoopBlockWatcher.php
LoopBlockWatcher.createOnBlockHandler
private static function createOnBlockHandler(LoggerInterface $logger): callable { return static function(int $blockInterval) use ($logger): void { $trace = \debug_backtrace(); $traceData = ['info' => []]; /** skip first since it's always the current method */ \array_shift($trace); /** the call_user_func call is also skipped */ \array_shift($trace); $i = 0; while (isset($trace[$i]['class'])) { /** @noinspection SlowArrayOperationsInLoopInspection */ $traceData['info'] = \array_merge( $traceData['info'], [ 'file' => $trace[$i - 1]['file'] ?? null, 'line' => $trace[$i - 1]['line'] ?? null, 'class' => $trace[$i]['class'] ?? null, 'function' => $trace[$i]['function'] ?? null, ] ); $i++; } $traceData['lockTime'] = 0 !== $blockInterval ? $blockInterval / 1000 : 0; $logger->error('A lock event loop has been detected. Blocking time: {lockTime} seconds', $traceData); unset($traceData, $trace, $i); }; }
php
private static function createOnBlockHandler(LoggerInterface $logger): callable { return static function(int $blockInterval) use ($logger): void { $trace = \debug_backtrace(); $traceData = ['info' => []]; /** skip first since it's always the current method */ \array_shift($trace); /** the call_user_func call is also skipped */ \array_shift($trace); $i = 0; while (isset($trace[$i]['class'])) { /** @noinspection SlowArrayOperationsInLoopInspection */ $traceData['info'] = \array_merge( $traceData['info'], [ 'file' => $trace[$i - 1]['file'] ?? null, 'line' => $trace[$i - 1]['line'] ?? null, 'class' => $trace[$i]['class'] ?? null, 'function' => $trace[$i]['function'] ?? null, ] ); $i++; } $traceData['lockTime'] = 0 !== $blockInterval ? $blockInterval / 1000 : 0; $logger->error('A lock event loop has been detected. Blocking time: {lockTime} seconds', $traceData); unset($traceData, $trace, $i); }; }
[ "private", "static", "function", "createOnBlockHandler", "(", "LoggerInterface", "$", "logger", ")", ":", "callable", "{", "return", "static", "function", "(", "int", "$", "blockInterval", ")", "use", "(", "$", "logger", ")", ":", "void", "{", "$", "trace", ...
@param LoggerInterface $logger @return callable(int):void
[ "@param", "LoggerInterface", "$logger" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Infrastructure/Watchers/LoopBlockWatcher.php#L90-L126
php-service-bus/service-bus
src/Application/DependencyInjection/Extensions/ServiceBusExtension.php
ServiceBusExtension.load
public function load(array $configs, ContainerBuilder $container): void { $loader = new YamlFileLoader($container, new FileLocator()); $loader->load(__DIR__ . '/../service_bus.yaml'); /** * @var string $key * @var mixed $value * * @psalm-suppress MixedAssignment Cannot assign $value to a mixed type */ foreach ($configs as $key => $value) { $container->setParameter($key, $value); } }
php
public function load(array $configs, ContainerBuilder $container): void { $loader = new YamlFileLoader($container, new FileLocator()); $loader->load(__DIR__ . '/../service_bus.yaml'); /** * @var string $key * @var mixed $value * * @psalm-suppress MixedAssignment Cannot assign $value to a mixed type */ foreach ($configs as $key => $value) { $container->setParameter($key, $value); } }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "loader", "=", "new", "YamlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", ")", ")", ";", "$", "loader"...
{@inheritdoc} @psalm-suppress MoreSpecificImplementedParamType @psalm-param array<string, mixed> $configs @param array $configs @param ContainerBuilder $container @throws \Exception
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Extensions/ServiceBusExtension.php#L36-L51
php-service-bus/service-bus
src/MessageExecutor/DefaultMessageExecutor.php
DefaultMessageExecutor.publishThrowable
private static function publishThrowable(string $eventClass, string $errorMessage, KernelContext $context): \Generator { /** * @noinspection VariableFunctionsUsageInspection * * @var \ServiceBus\Services\Contracts\ExecutionFailedEvent $event */ $event = \forward_static_call_array([$eventClass, 'create'], [$context->traceId(), $errorMessage]); yield $context->delivery($event); }
php
private static function publishThrowable(string $eventClass, string $errorMessage, KernelContext $context): \Generator { /** * @noinspection VariableFunctionsUsageInspection * * @var \ServiceBus\Services\Contracts\ExecutionFailedEvent $event */ $event = \forward_static_call_array([$eventClass, 'create'], [$context->traceId(), $errorMessage]); yield $context->delivery($event); }
[ "private", "static", "function", "publishThrowable", "(", "string", "$", "eventClass", ",", "string", "$", "errorMessage", ",", "KernelContext", "$", "context", ")", ":", "\\", "Generator", "{", "/**\n * @noinspection VariableFunctionsUsageInspection\n *\n ...
Publish failed response event. @param string $eventClass @param string $errorMessage @param KernelContext $context @return \Generator
[ "Publish", "failed", "response", "event", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/MessageExecutor/DefaultMessageExecutor.php#L154-L164
php-service-bus/service-bus
src/MessageExecutor/DefaultMessageExecutor.php
DefaultMessageExecutor.collectArguments
private static function collectArguments( \SplObjectStorage $arguments, array $resolvers, object $message, KernelContext $context ): array { $preparedArguments = []; /** @var \ServiceBus\Common\MessageHandler\MessageHandlerArgument $argument */ foreach ($arguments as $argument) { foreach ($resolvers as $argumentResolver) { if (true === $argumentResolver->supports($argument)) { /** @psalm-suppress MixedAssignment Unknown data type */ $preparedArguments[] = $argumentResolver->resolve($message, $context, $argument); } } } /** @var array<int, mixed> $preparedArguments */ return $preparedArguments; }
php
private static function collectArguments( \SplObjectStorage $arguments, array $resolvers, object $message, KernelContext $context ): array { $preparedArguments = []; /** @var \ServiceBus\Common\MessageHandler\MessageHandlerArgument $argument */ foreach ($arguments as $argument) { foreach ($resolvers as $argumentResolver) { if (true === $argumentResolver->supports($argument)) { /** @psalm-suppress MixedAssignment Unknown data type */ $preparedArguments[] = $argumentResolver->resolve($message, $context, $argument); } } } /** @var array<int, mixed> $preparedArguments */ return $preparedArguments; }
[ "private", "static", "function", "collectArguments", "(", "\\", "SplObjectStorage", "$", "arguments", ",", "array", "$", "resolvers", ",", "object", "$", "message", ",", "KernelContext", "$", "context", ")", ":", "array", "{", "$", "preparedArguments", "=", "[...
Collect arguments list. @psalm-param \SplObjectStorage<\ServiceBus\Common\MessageHandler\MessageHandlerArgument, string> $arguments @psalm-param array<string, \ServiceBus\ArgumentResolvers\ArgumentResolver> $resolvers @psalm-return array<int, mixed> @param \SplObjectStorage $arguments @param \ServiceBus\ArgumentResolvers\ArgumentResolver[] $resolvers @param object $message @param KernelContext $context @return array
[ "Collect", "arguments", "list", "." ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/MessageExecutor/DefaultMessageExecutor.php#L180-L204
php-service-bus/service-bus
src/Application/DependencyInjection/Compiler/Logger/StdOutLoggerCompilerPass.php
StdOutLoggerCompilerPass.process
public function process(ContainerBuilder $container): void { $container->setParameter('service_bus.logger.echo.log_level', $this->logLevel); $container->addDefinitions( [ StdOutHandler::class => (new Definition(StdOutHandler::class))->setArguments(['%service_bus.logger.echo.log_level%']), ] ); (new LoggerCompilerPass())->process($container); $loggerDefinition = $container->getDefinition('service_bus.logger'); $loggerDefinition->addMethodCall( 'pushHandler', [new Reference(StdOutHandler::class)] ); }
php
public function process(ContainerBuilder $container): void { $container->setParameter('service_bus.logger.echo.log_level', $this->logLevel); $container->addDefinitions( [ StdOutHandler::class => (new Definition(StdOutHandler::class))->setArguments(['%service_bus.logger.echo.log_level%']), ] ); (new LoggerCompilerPass())->process($container); $loggerDefinition = $container->getDefinition('service_bus.logger'); $loggerDefinition->addMethodCall( 'pushHandler', [new Reference(StdOutHandler::class)] ); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "container", "->", "setParameter", "(", "'service_bus.logger.echo.log_level'", ",", "$", "this", "->", "logLevel", ")", ";", "$", "container", "->", "addDefin...
{@inheritdoc} @throws \Throwable
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-service-bus/service-bus/blob/42f5f21c902a52a4ae1b04864bbe014f762a7d3f/src/Application/DependencyInjection/Compiler/Logger/StdOutLoggerCompilerPass.php#L45-L63
tp5er/tp5-databackup
src/Backup.php
Backup.setTimeout
public function setTimeout($time=null) { if (!is_null($time)) { set_time_limit($time)||ini_set("max_execution_time", $time); } return $this; }
php
public function setTimeout($time=null) { if (!is_null($time)) { set_time_limit($time)||ini_set("max_execution_time", $time); } return $this; }
[ "public", "function", "setTimeout", "(", "$", "time", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "time", ")", ")", "{", "set_time_limit", "(", "$", "time", ")", "||", "ini_set", "(", "\"max_execution_time\"", ",", "$", "time", ")", "...
设置脚本运行超时时间 0表示不限制,支持连贯操作
[ "设置脚本运行超时时间", "0表示不限制,支持连贯操作" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L66-L72
tp5er/tp5-databackup
src/Backup.php
Backup.setDbConn
public function setDbConn($dbconfig = []) { if (empty($dbconfig)) { $this->dbconfig = config('database'); //$this->dbconfig = Config::get('database'); } else { $this->dbconfig = $dbconfig; } return $this; }
php
public function setDbConn($dbconfig = []) { if (empty($dbconfig)) { $this->dbconfig = config('database'); //$this->dbconfig = Config::get('database'); } else { $this->dbconfig = $dbconfig; } return $this; }
[ "public", "function", "setDbConn", "(", "$", "dbconfig", "=", "[", "]", ")", "{", "if", "(", "empty", "(", "$", "dbconfig", ")", ")", "{", "$", "this", "->", "dbconfig", "=", "config", "(", "'database'", ")", ";", "//$this->dbconfig = Config::get('database...
设置数据库连接必备参数 @param array $dbconfig 数据库连接配置信息 @return object
[ "设置数据库连接必备参数" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L78-L87
tp5er/tp5-databackup
src/Backup.php
Backup.setFile
public function setFile($file = null) { if (is_null($file)) { $this->file = ['name' => date('Ymd-His'), 'part' => 1]; } else { if (!array_key_exists("name", $file) && !array_key_exists("part", $file)) { $this->file = $file['1']; } else { $this->file = $file; } } return $this; }
php
public function setFile($file = null) { if (is_null($file)) { $this->file = ['name' => date('Ymd-His'), 'part' => 1]; } else { if (!array_key_exists("name", $file) && !array_key_exists("part", $file)) { $this->file = $file['1']; } else { $this->file = $file; } } return $this; }
[ "public", "function", "setFile", "(", "$", "file", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "file", ")", ")", "{", "$", "this", "->", "file", "=", "[", "'name'", "=>", "date", "(", "'Ymd-His'", ")", ",", "'part'", "=>", "1", "]", ...
设置备份文件名 @param Array $file 文件名字 @return object
[ "设置备份文件名" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L93-L105
tp5er/tp5-databackup
src/Backup.php
Backup.dataList
public function dataList($table = null,$type=1) { $db = self::connect(); if (is_null($table)) { $list = $db->query("SHOW TABLE STATUS"); } else { if ($type) { $list = $db->query("SHOW FULL COLUMNS FROM {$table}"); }else{ $list = $db->query("show columns from {$table}"); } } return array_map('array_change_key_case', $list); //$list; }
php
public function dataList($table = null,$type=1) { $db = self::connect(); if (is_null($table)) { $list = $db->query("SHOW TABLE STATUS"); } else { if ($type) { $list = $db->query("SHOW FULL COLUMNS FROM {$table}"); }else{ $list = $db->query("show columns from {$table}"); } } return array_map('array_change_key_case', $list); //$list; }
[ "public", "function", "dataList", "(", "$", "table", "=", "null", ",", "$", "type", "=", "1", ")", "{", "$", "db", "=", "self", "::", "connect", "(", ")", ";", "if", "(", "is_null", "(", "$", "table", ")", ")", "{", "$", "list", "=", "$", "db...
数据库表列表
[ "数据库表列表" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L112-L126
tp5er/tp5-databackup
src/Backup.php
Backup.fileList
public function fileList() { if (!is_dir($this->config['path'])) { mkdir($this->config['path'], 0755, true); } $path = realpath($this->config['path']); $flag = \FilesystemIterator::KEY_AS_FILENAME; $glob = new \FilesystemIterator($path, $flag); $list = array(); foreach ($glob as $name => $file) { if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) { $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d'); $date = "{$name[0]}-{$name[1]}-{$name[2]}"; $time = "{$name[3]}:{$name[4]}:{$name[5]}"; $part = $name[6]; if (isset($list["{$date} {$time}"])) { $info = $list["{$date} {$time}"]; $info['part'] = max($info['part'], $part); $info['size'] = $info['size'] + $file->getSize(); } else { $info['part'] = $part; $info['size'] = $file->getSize(); } $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION)); $info['compress'] = $extension === 'SQL' ? '-' : $extension; $info['time'] = strtotime("{$date} {$time}"); $list["{$date} {$time}"] = $info; } } return $list; }
php
public function fileList() { if (!is_dir($this->config['path'])) { mkdir($this->config['path'], 0755, true); } $path = realpath($this->config['path']); $flag = \FilesystemIterator::KEY_AS_FILENAME; $glob = new \FilesystemIterator($path, $flag); $list = array(); foreach ($glob as $name => $file) { if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) { $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d'); $date = "{$name[0]}-{$name[1]}-{$name[2]}"; $time = "{$name[3]}:{$name[4]}:{$name[5]}"; $part = $name[6]; if (isset($list["{$date} {$time}"])) { $info = $list["{$date} {$time}"]; $info['part'] = max($info['part'], $part); $info['size'] = $info['size'] + $file->getSize(); } else { $info['part'] = $part; $info['size'] = $file->getSize(); } $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION)); $info['compress'] = $extension === 'SQL' ? '-' : $extension; $info['time'] = strtotime("{$date} {$time}"); $list["{$date} {$time}"] = $info; } } return $list; }
[ "public", "function", "fileList", "(", ")", "{", "if", "(", "!", "is_dir", "(", "$", "this", "->", "config", "[", "'path'", "]", ")", ")", "{", "mkdir", "(", "$", "this", "->", "config", "[", "'path'", "]", ",", "0755", ",", "true", ")", ";", "...
数据库备份文件列表
[ "数据库备份文件列表" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L128-L158
tp5er/tp5-databackup
src/Backup.php
Backup.delFile
public function delFile($time) { if ($time) { $file = $this->getFile('time', $time); array_map("unlink", $this->getFile('time', $time)); if (count($this->getFile('time', $time))) { throw new \Exception("File {$path} deleted failed"); } else { return $time; } } else { throw new \Exception("{$time} Time parameter is incorrect"); } }
php
public function delFile($time) { if ($time) { $file = $this->getFile('time', $time); array_map("unlink", $this->getFile('time', $time)); if (count($this->getFile('time', $time))) { throw new \Exception("File {$path} deleted failed"); } else { return $time; } } else { throw new \Exception("{$time} Time parameter is incorrect"); } }
[ "public", "function", "delFile", "(", "$", "time", ")", "{", "if", "(", "$", "time", ")", "{", "$", "file", "=", "$", "this", "->", "getFile", "(", "'time'", ",", "$", "time", ")", ";", "array_map", "(", "\"unlink\"", ",", "$", "this", "->", "get...
删除备份文件
[ "删除备份文件" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L204-L217
tp5er/tp5-databackup
src/Backup.php
Backup.downloadFile
public function downloadFile($time, $part = 0) { $file = $this->getFile('time', $time); $fileName = $file[$part]; if (file_exists($fileName)) { ob_end_clean(); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Length: ' . filesize($fileName)); header('Content-Disposition: attachment; filename=' . basename($fileName)); readfile($fileName); } else { throw new \Exception("{$time} File is abnormal"); } }
php
public function downloadFile($time, $part = 0) { $file = $this->getFile('time', $time); $fileName = $file[$part]; if (file_exists($fileName)) { ob_end_clean(); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Length: ' . filesize($fileName)); header('Content-Disposition: attachment; filename=' . basename($fileName)); readfile($fileName); } else { throw new \Exception("{$time} File is abnormal"); } }
[ "public", "function", "downloadFile", "(", "$", "time", ",", "$", "part", "=", "0", ")", "{", "$", "file", "=", "$", "this", "->", "getFile", "(", "'time'", ",", "$", "time", ")", ";", "$", "fileName", "=", "$", "file", "[", "$", "part", "]", "...
下载备份 @Author: 浪哥 <939881475@qq.com> @param string $time @param integer $part @return array|mixed|string
[ "下载备份" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L225-L240
tp5er/tp5-databackup
src/Backup.php
Backup.Backup_Init
public function Backup_Init() { $sql = "-- -----------------------------\n"; $sql .= "-- Think MySQL Data Transfer \n"; $sql .= "-- \n"; $sql .= "-- Host : " . $this->dbconfig['hostname'] . "\n"; $sql .= "-- Port : " . $this->dbconfig['hostport'] . "\n"; $sql .= "-- Database : " . $this->dbconfig['database'] . "\n"; $sql .= "-- \n"; $sql .= "-- Part : #{$this->file['part']}\n"; $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n"; $sql .= "-- -----------------------------\n\n"; $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n"; return $this->write($sql); }
php
public function Backup_Init() { $sql = "-- -----------------------------\n"; $sql .= "-- Think MySQL Data Transfer \n"; $sql .= "-- \n"; $sql .= "-- Host : " . $this->dbconfig['hostname'] . "\n"; $sql .= "-- Port : " . $this->dbconfig['hostport'] . "\n"; $sql .= "-- Database : " . $this->dbconfig['database'] . "\n"; $sql .= "-- \n"; $sql .= "-- Part : #{$this->file['part']}\n"; $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n"; $sql .= "-- -----------------------------\n\n"; $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n"; return $this->write($sql); }
[ "public", "function", "Backup_Init", "(", ")", "{", "$", "sql", "=", "\"-- -----------------------------\\n\"", ";", "$", "sql", ".=", "\"-- Think MySQL Data Transfer \\n\"", ";", "$", "sql", ".=", "\"-- \\n\"", ";", "$", "sql", ".=", "\"-- Host : \"", ".", "$...
写入初始数据 @return boolean true - 写入成功,false - 写入失败
[ "写入初始数据" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L275-L289
tp5er/tp5-databackup
src/Backup.php
Backup.backup
public function backup($table, $start) { $db = self::connect(); // 备份表结构 if (0 == $start) { $result = $db->query("SHOW CREATE TABLE `{$table}`"); $sql = "\n"; $sql .= "-- -----------------------------\n"; $sql .= "-- Table structure for `{$table}`\n"; $sql .= "-- -----------------------------\n"; $sql .= "DROP TABLE IF EXISTS `{$table}`;\n"; $sql .= trim($result[0]['Create Table']) . ";\n\n"; if (false === $this->write($sql)) { return false; } } //数据总数 $result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`"); $count = $result['0']['count']; //备份表数据 if ($count) { //写入数据注释 if (0 == $start) { $sql = "-- -----------------------------\n"; $sql .= "-- Records of `{$table}`\n"; $sql .= "-- -----------------------------\n"; $this->write($sql); } //备份数据记录 $result = $db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000"); foreach ($result as $row) { $row = array_map('addslashes', $row); $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r", "\n"), array('\\r', '\\n'), implode("', '", $row)) . "');\n"; if (false === $this->write($sql)) { return false; } } //还有更多数据 if ($count > $start + 1000) { //return array($start + 1000, $count); return $this->backup($table, $start + 1000); } } //备份下一表 return 0; }
php
public function backup($table, $start) { $db = self::connect(); // 备份表结构 if (0 == $start) { $result = $db->query("SHOW CREATE TABLE `{$table}`"); $sql = "\n"; $sql .= "-- -----------------------------\n"; $sql .= "-- Table structure for `{$table}`\n"; $sql .= "-- -----------------------------\n"; $sql .= "DROP TABLE IF EXISTS `{$table}`;\n"; $sql .= trim($result[0]['Create Table']) . ";\n\n"; if (false === $this->write($sql)) { return false; } } //数据总数 $result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`"); $count = $result['0']['count']; //备份表数据 if ($count) { //写入数据注释 if (0 == $start) { $sql = "-- -----------------------------\n"; $sql .= "-- Records of `{$table}`\n"; $sql .= "-- -----------------------------\n"; $this->write($sql); } //备份数据记录 $result = $db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000"); foreach ($result as $row) { $row = array_map('addslashes', $row); $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r", "\n"), array('\\r', '\\n'), implode("', '", $row)) . "');\n"; if (false === $this->write($sql)) { return false; } } //还有更多数据 if ($count > $start + 1000) { //return array($start + 1000, $count); return $this->backup($table, $start + 1000); } } //备份下一表 return 0; }
[ "public", "function", "backup", "(", "$", "table", ",", "$", "start", ")", "{", "$", "db", "=", "self", "::", "connect", "(", ")", ";", "// 备份表结构", "if", "(", "0", "==", "$", "start", ")", "{", "$", "result", "=", "$", "db", "->", "query", "(",...
备份表结构 @param string $table 表名 @param integer $start 起始行数 @return boolean false - 备份失败
[ "备份表结构" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L296-L341
tp5er/tp5-databackup
src/Backup.php
Backup.optimize
public function optimize($tables = null) { if ($tables) { $db = self::connect(); if (is_array($tables)) { $tables = implode('`,`', $tables); $list = $db->query("OPTIMIZE TABLE `{$tables}`"); } else { $list = $db->query("OPTIMIZE TABLE `{$tables}`"); } if ($list) { return $tables; } else { throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!"); } } else { throw new \Exception("Please specify the table to be repaired!"); } }
php
public function optimize($tables = null) { if ($tables) { $db = self::connect(); if (is_array($tables)) { $tables = implode('`,`', $tables); $list = $db->query("OPTIMIZE TABLE `{$tables}`"); } else { $list = $db->query("OPTIMIZE TABLE `{$tables}`"); } if ($list) { return $tables; } else { throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!"); } } else { throw new \Exception("Please specify the table to be repaired!"); } }
[ "public", "function", "optimize", "(", "$", "tables", "=", "null", ")", "{", "if", "(", "$", "tables", ")", "{", "$", "db", "=", "self", "::", "connect", "(", ")", ";", "if", "(", "is_array", "(", "$", "tables", ")", ")", "{", "$", "tables", "=...
优化表 @param String $tables 表名 @return String $tables
[ "优化表" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L347-L365
tp5er/tp5-databackup
src/Backup.php
Backup.write
private function write($sql) { $size = strlen($sql); //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%, //一般情况压缩率都会高于50%; $size = $this->config['compress'] ? $size / 2 : $size; $this->open($size); return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql); }
php
private function write($sql) { $size = strlen($sql); //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%, //一般情况压缩率都会高于50%; $size = $this->config['compress'] ? $size / 2 : $size; $this->open($size); return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql); }
[ "private", "function", "write", "(", "$", "sql", ")", "{", "$", "size", "=", "strlen", "(", "$", "sql", ")", ";", "//由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,", "//一般情况压缩率都会高于50%;", "$", "size", "=", "$", "this", "->", "config", "[", "'compress'", "]", "?", "$", "...
写入SQL语句 @param string $sql 要写入的SQL语句 @return boolean true - 写入成功,false - 写入失败!
[ "写入SQL语句" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L395-L403
tp5er/tp5-databackup
src/Backup.php
Backup.open
private function open($size) { if ($this->fp) { $this->size += $size; if ($this->size > $this->config['part']) { $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp); $this->fp = null; $this->file['part']++; session('backup_file', $this->file); $this->Backup_Init(); } } else { $backuppath = $this->config['path']; $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql"; if ($this->config['compress']) { $filename = "{$filename}.gz"; $this->fp = @gzopen($filename, "a{$this->config['level']}"); } else { $this->fp = @fopen($filename, 'a'); } $this->size = filesize($filename) + $size; } }
php
private function open($size) { if ($this->fp) { $this->size += $size; if ($this->size > $this->config['part']) { $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp); $this->fp = null; $this->file['part']++; session('backup_file', $this->file); $this->Backup_Init(); } } else { $backuppath = $this->config['path']; $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql"; if ($this->config['compress']) { $filename = "{$filename}.gz"; $this->fp = @gzopen($filename, "a{$this->config['level']}"); } else { $this->fp = @fopen($filename, 'a'); } $this->size = filesize($filename) + $size; } }
[ "private", "function", "open", "(", "$", "size", ")", "{", "if", "(", "$", "this", "->", "fp", ")", "{", "$", "this", "->", "size", "+=", "$", "size", ";", "if", "(", "$", "this", "->", "size", ">", "$", "this", "->", "config", "[", "'part'", ...
打开一个卷,用于写入数据 @param integer $size 写入数据的大小
[ "打开一个卷,用于写入数据" ]
train
https://github.com/tp5er/tp5-databackup/blob/2a5832c4e75bf17164c277023c63d6cafab46812/src/Backup.php#L408-L430
yiisoft/yii2-swiftmailer
src/Mailer.php
Mailer.createTransport
protected function createTransport(array $config) { if (!isset($config['class'])) { $config['class'] = 'Swift_SendmailTransport'; } if (isset($config['plugins'])) { $plugins = $config['plugins']; unset($config['plugins']); } else { $plugins = []; } if ($this->enableSwiftMailerLogging) { $plugins[] = [ 'class' => 'Swift_Plugins_LoggerPlugin', 'constructArgs' => [ [ 'class' => 'yii\swiftmailer\Logger' ] ], ]; } /* @var $transport \Swift_Transport */ $transport = $this->createSwiftObject($config); if (!empty($plugins)) { foreach ($plugins as $plugin) { if (is_array($plugin) && isset($plugin['class'])) { $plugin = $this->createSwiftObject($plugin); } $transport->registerPlugin($plugin); } } return $transport; }
php
protected function createTransport(array $config) { if (!isset($config['class'])) { $config['class'] = 'Swift_SendmailTransport'; } if (isset($config['plugins'])) { $plugins = $config['plugins']; unset($config['plugins']); } else { $plugins = []; } if ($this->enableSwiftMailerLogging) { $plugins[] = [ 'class' => 'Swift_Plugins_LoggerPlugin', 'constructArgs' => [ [ 'class' => 'yii\swiftmailer\Logger' ] ], ]; } /* @var $transport \Swift_Transport */ $transport = $this->createSwiftObject($config); if (!empty($plugins)) { foreach ($plugins as $plugin) { if (is_array($plugin) && isset($plugin['class'])) { $plugin = $this->createSwiftObject($plugin); } $transport->registerPlugin($plugin); } } return $transport; }
[ "protected", "function", "createTransport", "(", "array", "$", "config", ")", "{", "if", "(", "!", "isset", "(", "$", "config", "[", "'class'", "]", ")", ")", "{", "$", "config", "[", "'class'", "]", "=", "'Swift_SendmailTransport'", ";", "}", "if", "(...
Creates email transport instance by its array configuration. @param array $config transport configuration. @throws \yii\base\InvalidConfigException on invalid transport configuration. @return \Swift_Transport transport instance.
[ "Creates", "email", "transport", "instance", "by", "its", "array", "configuration", "." ]
train
https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Mailer.php#L174-L209
yiisoft/yii2-swiftmailer
src/Mailer.php
Mailer.createSwiftObject
protected function createSwiftObject(array $config) { if (isset($config['class'])) { $className = $config['class']; unset($config['class']); } else { throw new InvalidConfigException('Object configuration must be an array containing a "class" element.'); } if (isset($config['constructArgs'])) { $args = []; foreach ($config['constructArgs'] as $arg) { if (is_array($arg) && isset($arg['class'])) { $args[] = $this->createSwiftObject($arg); } else { $args[] = $arg; } } unset($config['constructArgs']); $object = Yii::createObject($className, $args); } else { $object = Yii::createObject($className); } if (!empty($config)) { $reflection = new \ReflectionObject($object); foreach ($config as $name => $value) { if ($reflection->hasProperty($name) && $reflection->getProperty($name)->isPublic()) { $object->$name = $value; } else { $setter = 'set' . $name; if ($reflection->hasMethod($setter) || $reflection->hasMethod('__call')) { $object->$setter($value); } else { throw new InvalidConfigException('Setting unknown property: ' . $className . '::' . $name); } } } } return $object; }
php
protected function createSwiftObject(array $config) { if (isset($config['class'])) { $className = $config['class']; unset($config['class']); } else { throw new InvalidConfigException('Object configuration must be an array containing a "class" element.'); } if (isset($config['constructArgs'])) { $args = []; foreach ($config['constructArgs'] as $arg) { if (is_array($arg) && isset($arg['class'])) { $args[] = $this->createSwiftObject($arg); } else { $args[] = $arg; } } unset($config['constructArgs']); $object = Yii::createObject($className, $args); } else { $object = Yii::createObject($className); } if (!empty($config)) { $reflection = new \ReflectionObject($object); foreach ($config as $name => $value) { if ($reflection->hasProperty($name) && $reflection->getProperty($name)->isPublic()) { $object->$name = $value; } else { $setter = 'set' . $name; if ($reflection->hasMethod($setter) || $reflection->hasMethod('__call')) { $object->$setter($value); } else { throw new InvalidConfigException('Setting unknown property: ' . $className . '::' . $name); } } } } return $object; }
[ "protected", "function", "createSwiftObject", "(", "array", "$", "config", ")", "{", "if", "(", "isset", "(", "$", "config", "[", "'class'", "]", ")", ")", "{", "$", "className", "=", "$", "config", "[", "'class'", "]", ";", "unset", "(", "$", "confi...
Creates Swift library object, from given array configuration. @param array $config object configuration @return Object created object @throws \yii\base\InvalidConfigException on invalid configuration.
[ "Creates", "Swift", "library", "object", "from", "given", "array", "configuration", "." ]
train
https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Mailer.php#L217-L258
yiisoft/yii2-swiftmailer
src/Message.php
Message.setBody
protected function setBody($body, $contentType) { $message = $this->getSwiftMessage(); $oldBody = $message->getBody(); $charset = $message->getCharset(); if (empty($oldBody)) { $parts = $message->getChildren(); $partFound = false; foreach ($parts as $key => $part) { if (!($part instanceof \Swift_Mime_Attachment)) { /* @var $part \Swift_Mime_MimePart */ if ($part->getContentType() == $contentType) { $charset = $part->getCharset(); unset($parts[$key]); $partFound = true; break; } } } if ($partFound) { reset($parts); $message->setChildren($parts); $message->addPart($body, $contentType, $charset); } else { $message->setBody($body, $contentType); } } else { $oldContentType = $message->getContentType(); if ($oldContentType == $contentType) { $message->setBody($body, $contentType); } else { $message->setBody(null); $message->setContentType(null); $message->addPart($oldBody, $oldContentType, $charset); $message->addPart($body, $contentType, $charset); } } }
php
protected function setBody($body, $contentType) { $message = $this->getSwiftMessage(); $oldBody = $message->getBody(); $charset = $message->getCharset(); if (empty($oldBody)) { $parts = $message->getChildren(); $partFound = false; foreach ($parts as $key => $part) { if (!($part instanceof \Swift_Mime_Attachment)) { /* @var $part \Swift_Mime_MimePart */ if ($part->getContentType() == $contentType) { $charset = $part->getCharset(); unset($parts[$key]); $partFound = true; break; } } } if ($partFound) { reset($parts); $message->setChildren($parts); $message->addPart($body, $contentType, $charset); } else { $message->setBody($body, $contentType); } } else { $oldContentType = $message->getContentType(); if ($oldContentType == $contentType) { $message->setBody($body, $contentType); } else { $message->setBody(null); $message->setContentType(null); $message->addPart($oldBody, $oldContentType, $charset); $message->addPart($body, $contentType, $charset); } } }
[ "protected", "function", "setBody", "(", "$", "body", ",", "$", "contentType", ")", "{", "$", "message", "=", "$", "this", "->", "getSwiftMessage", "(", ")", ";", "$", "oldBody", "=", "$", "message", "->", "getBody", "(", ")", ";", "$", "charset", "=...
Sets the message body. If body is already set and its content type matches given one, it will be overridden, if content type miss match the multipart message will be composed. @param string $body body content. @param string $contentType body content type.
[ "Sets", "the", "message", "body", ".", "If", "body", "is", "already", "set", "and", "its", "content", "type", "matches", "given", "one", "it", "will", "be", "overridden", "if", "content", "type", "miss", "match", "the", "multipart", "message", "will", "be"...
train
https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Message.php#L225-L262
yiisoft/yii2-swiftmailer
src/Message.php
Message.setSignature
public function setSignature($signature) { if (!empty($this->signers)) { // clear previously set signers $swiftMessage = $this->getSwiftMessage(); foreach ($this->signers as $signer) { $swiftMessage->detachSigner($signer); } $this->signers = []; } return $this->addSignature($signature); }
php
public function setSignature($signature) { if (!empty($this->signers)) { // clear previously set signers $swiftMessage = $this->getSwiftMessage(); foreach ($this->signers as $signer) { $swiftMessage->detachSigner($signer); } $this->signers = []; } return $this->addSignature($signature); }
[ "public", "function", "setSignature", "(", "$", "signature", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "signers", ")", ")", "{", "// clear previously set signers", "$", "swiftMessage", "=", "$", "this", "->", "getSwiftMessage", "(", ")", "...
Sets message signature @param array|callable|\Swift_Signer $signature signature specification. See [[addSignature()]] for details on how it should be specified. @return $this self reference. @since 2.0.6
[ "Sets", "message", "signature" ]
train
https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Message.php#L340-L351
yiisoft/yii2-swiftmailer
src/Message.php
Message.addSignature
public function addSignature($signature) { if ($signature instanceof \Swift_Signer) { $signer = $signature; } elseif (is_callable($signature)) { $signer = call_user_func($signature); } elseif (is_array($signature)) { $signer = $this->createSwiftSigner($signature); } else { throw new InvalidConfigException('Signature should be instance of "Swift_Signer", callable or array configuration'); } $this->getSwiftMessage()->attachSigner($signer); $this->signers[] = $signer; return $this; }
php
public function addSignature($signature) { if ($signature instanceof \Swift_Signer) { $signer = $signature; } elseif (is_callable($signature)) { $signer = call_user_func($signature); } elseif (is_array($signature)) { $signer = $this->createSwiftSigner($signature); } else { throw new InvalidConfigException('Signature should be instance of "Swift_Signer", callable or array configuration'); } $this->getSwiftMessage()->attachSigner($signer); $this->signers[] = $signer; return $this; }
[ "public", "function", "addSignature", "(", "$", "signature", ")", "{", "if", "(", "$", "signature", "instanceof", "\\", "Swift_Signer", ")", "{", "$", "signer", "=", "$", "signature", ";", "}", "elseif", "(", "is_callable", "(", "$", "signature", ")", ")...
Adds message signature. @param array|callable|\Swift_Signer $signature signature specification, this can be: - [[\Swift_Signer]] instance - callable, which returns [[\Swift_Signer]] instance - configuration array for the signer creation @return $this self reference @throws InvalidConfigException on invalid signature configuration @since 2.0.6
[ "Adds", "message", "signature", ".", "@param", "array|callable|", "\\", "Swift_Signer", "$signature", "signature", "specification", "this", "can", "be", ":" ]
train
https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Message.php#L365-L381
yiisoft/yii2-swiftmailer
src/Message.php
Message.createSwiftSigner
protected function createSwiftSigner($signature) { if (!isset($signature['type'])) { throw new InvalidConfigException('Signature configuration should contain "type" key'); } switch (strtolower($signature['type'])) { case 'dkim' : $domain = ArrayHelper::getValue($signature, 'domain', null); $selector = ArrayHelper::getValue($signature, 'selector', null); if (isset($signature['key'])) { $privateKey = $signature['key']; } elseif (isset($signature['file'])) { $privateKey = file_get_contents(Yii::getAlias($signature['file'])); } else { throw new InvalidConfigException("Either 'key' or 'file' signature option should be specified"); } return new \Swift_Signers_DKIMSigner($privateKey, $domain, $selector); case 'opendkim' : $domain = ArrayHelper::getValue($signature, 'domain', null); $selector = ArrayHelper::getValue($signature, 'selector', null); if (isset($signature['key'])) { $privateKey = $signature['key']; } elseif (isset($signature['file'])) { $privateKey = file_get_contents(Yii::getAlias($signature['file'])); } else { throw new InvalidConfigException("Either 'key' or 'file' signature option should be specified"); } return new \Swift_Signers_OpenDKIMSigner($privateKey, $domain, $selector); default: throw new InvalidConfigException("Unrecognized signature type '{$signature['type']}'"); } }
php
protected function createSwiftSigner($signature) { if (!isset($signature['type'])) { throw new InvalidConfigException('Signature configuration should contain "type" key'); } switch (strtolower($signature['type'])) { case 'dkim' : $domain = ArrayHelper::getValue($signature, 'domain', null); $selector = ArrayHelper::getValue($signature, 'selector', null); if (isset($signature['key'])) { $privateKey = $signature['key']; } elseif (isset($signature['file'])) { $privateKey = file_get_contents(Yii::getAlias($signature['file'])); } else { throw new InvalidConfigException("Either 'key' or 'file' signature option should be specified"); } return new \Swift_Signers_DKIMSigner($privateKey, $domain, $selector); case 'opendkim' : $domain = ArrayHelper::getValue($signature, 'domain', null); $selector = ArrayHelper::getValue($signature, 'selector', null); if (isset($signature['key'])) { $privateKey = $signature['key']; } elseif (isset($signature['file'])) { $privateKey = file_get_contents(Yii::getAlias($signature['file'])); } else { throw new InvalidConfigException("Either 'key' or 'file' signature option should be specified"); } return new \Swift_Signers_OpenDKIMSigner($privateKey, $domain, $selector); default: throw new InvalidConfigException("Unrecognized signature type '{$signature['type']}'"); } }
[ "protected", "function", "createSwiftSigner", "(", "$", "signature", ")", "{", "if", "(", "!", "isset", "(", "$", "signature", "[", "'type'", "]", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "'Signature configuration should contain \"type\" key'", ...
Creates signer from its configuration @param array $signature signature configuration @return \Swift_Signer signer instance @throws InvalidConfigException on invalid configuration provided @since 2.0.6
[ "Creates", "signer", "from", "its", "configuration" ]
train
https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Message.php#L390-L421
yiisoft/yii2-swiftmailer
src/Message.php
Message.addHeader
public function addHeader($name, $value) { $this->getSwiftMessage()->getHeaders()->addTextHeader($name, $value); return $this; }
php
public function addHeader($name, $value) { $this->getSwiftMessage()->getHeaders()->addTextHeader($name, $value); return $this; }
[ "public", "function", "addHeader", "(", "$", "name", ",", "$", "value", ")", "{", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "getHeaders", "(", ")", "->", "addTextHeader", "(", "$", "name", ",", "$", "value", ")", ";", "return", "$", "this...
Adds custom header value to the message. Several invocations of this method with the same name will add multiple header values. @param string $name header name. @param string $value header value. @return $this self reference. @since 2.0.6
[ "Adds", "custom", "header", "value", "to", "the", "message", ".", "Several", "invocations", "of", "this", "method", "with", "the", "same", "name", "will", "add", "multiple", "header", "values", "." ]
train
https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Message.php#L450-L454
yiisoft/yii2-swiftmailer
src/Message.php
Message.setHeader
public function setHeader($name, $value) { $headerSet = $this->getSwiftMessage()->getHeaders(); if ($headerSet->has($name)) { $headerSet->remove($name); } foreach ((array)$value as $v) { $headerSet->addTextHeader($name, $v); } return $this; }
php
public function setHeader($name, $value) { $headerSet = $this->getSwiftMessage()->getHeaders(); if ($headerSet->has($name)) { $headerSet->remove($name); } foreach ((array)$value as $v) { $headerSet->addTextHeader($name, $v); } return $this; }
[ "public", "function", "setHeader", "(", "$", "name", ",", "$", "value", ")", "{", "$", "headerSet", "=", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "getHeaders", "(", ")", ";", "if", "(", "$", "headerSet", "->", "has", "(", "$", "name", ...
Sets custom header value to the message. @param string $name header name. @param string|array $value header value or values. @return $this self reference. @since 2.0.6
[ "Sets", "custom", "header", "value", "to", "the", "message", "." ]
train
https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Message.php#L463-L476