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
VincentChalnot/SidusEAVModelBundle
Registry/AttributeRegistry.php
AttributeRegistry.createAttribute
public function createAttribute($code, array $attributeConfiguration = []) { $attributeClass = $this->attributeClass; /** @var AttributeInterface $attribute */ $attribute = new $attributeClass( $code, $this->attributeTypeRegistry, $attributeConfiguration, $this->globalContextMask ); if (method_exists($attribute, 'setTranslator')) { $attribute->setTranslator($this->translator); } return $attribute; }
php
public function createAttribute($code, array $attributeConfiguration = []) { $attributeClass = $this->attributeClass; /** @var AttributeInterface $attribute */ $attribute = new $attributeClass( $code, $this->attributeTypeRegistry, $attributeConfiguration, $this->globalContextMask ); if (method_exists($attribute, 'setTranslator')) { $attribute->setTranslator($this->translator); } return $attribute; }
[ "public", "function", "createAttribute", "(", "$", "code", ",", "array", "$", "attributeConfiguration", "=", "[", "]", ")", "{", "$", "attributeClass", "=", "$", "this", "->", "attributeClass", ";", "/** @var AttributeInterface $attribute */", "$", "attribute", "=...
@param string $code @param array $attributeConfiguration @throws \UnexpectedValueException @return AttributeInterface
[ "@param", "string", "$code", "@param", "array", "$attributeConfiguration" ]
train
https://github.com/VincentChalnot/SidusEAVModelBundle/blob/6a0e184ac7ed2aead48b05e5f97badac7fe8000f/Registry/AttributeRegistry.php#L102-L117
VincentChalnot/SidusEAVModelBundle
Registry/AttributeRegistry.php
AttributeRegistry.addAttribute
protected function addAttribute(AttributeInterface $attribute) { if (\in_array($attribute->getCode(), static::$reservedCodes, true)) { throw new AttributeConfigurationException("Attribute code '{$attribute->getCode()}' is a reserved code"); } $this->attributes[$attribute->getCode()] = $attribute; }
php
protected function addAttribute(AttributeInterface $attribute) { if (\in_array($attribute->getCode(), static::$reservedCodes, true)) { throw new AttributeConfigurationException("Attribute code '{$attribute->getCode()}' is a reserved code"); } $this->attributes[$attribute->getCode()] = $attribute; }
[ "protected", "function", "addAttribute", "(", "AttributeInterface", "$", "attribute", ")", "{", "if", "(", "\\", "in_array", "(", "$", "attribute", "->", "getCode", "(", ")", ",", "static", "::", "$", "reservedCodes", ",", "true", ")", ")", "{", "throw", ...
@param AttributeInterface $attribute @throws \UnexpectedValueException
[ "@param", "AttributeInterface", "$attribute" ]
train
https://github.com/VincentChalnot/SidusEAVModelBundle/blob/6a0e184ac7ed2aead48b05e5f97badac7fe8000f/Registry/AttributeRegistry.php#L174-L180
VincentChalnot/SidusEAVModelBundle
Doctrine/Types/FamilyType.php
FamilyType.convertToPHPValue
public function convertToPHPValue($value, AbstractPlatform $platform) { if (null === $value) { return null; } $listeners = $platform->getEventManager()->getListeners('sidus_family_configuration'); /** @var FamilyRegistry $familyRegistry */ $familyRegistry = array_shift($listeners); return $familyRegistry->getFamily($value); }
php
public function convertToPHPValue($value, AbstractPlatform $platform) { if (null === $value) { return null; } $listeners = $platform->getEventManager()->getListeners('sidus_family_configuration'); /** @var FamilyRegistry $familyRegistry */ $familyRegistry = array_shift($listeners); return $familyRegistry->getFamily($value); }
[ "public", "function", "convertToPHPValue", "(", "$", "value", ",", "AbstractPlatform", "$", "platform", ")", "{", "if", "(", "null", "===", "$", "value", ")", "{", "return", "null", ";", "}", "$", "listeners", "=", "$", "platform", "->", "getEventManager",...
@param mixed $value @param AbstractPlatform $platform @throws MissingFamilyException @return null|FamilyInterface
[ "@param", "mixed", "$value", "@param", "AbstractPlatform", "$platform" ]
train
https://github.com/VincentChalnot/SidusEAVModelBundle/blob/6a0e184ac7ed2aead48b05e5f97badac7fe8000f/Doctrine/Types/FamilyType.php#L36-L47
VincentChalnot/SidusEAVModelBundle
Form/Type/FamilySelectorType.php
FamilySelectorType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addModelTransformer( new CallbackTransformer( function ($originalData) use ($options) { if (\is_array($originalData) && $options['multiple']) { foreach ($originalData as $key => $originalDatum) { if ($originalDatum instanceof FamilyInterface) { $originalData[$key] = $originalDatum->getCode(); } } return $originalData; } if ($originalData instanceof FamilyInterface) { $originalData = $originalData->getCode(); } return $originalData; }, function ($submittedData) use ($options) { if (null === $submittedData) { return $submittedData; } if ($submittedData instanceof FamilyInterface) { // Should actually never happen ? return $submittedData; } if (\is_array($submittedData) && $options['multiple']) { foreach ($submittedData as $key => $submittedDatum) { if ($submittedDatum instanceof FamilyInterface) { continue; } $submittedData[$key] = $this->familyRegistry->getFamily($submittedDatum); } return $submittedData; } /** @var string $submittedData */ return $this->familyRegistry->getFamily($submittedData); } ) ); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addModelTransformer( new CallbackTransformer( function ($originalData) use ($options) { if (\is_array($originalData) && $options['multiple']) { foreach ($originalData as $key => $originalDatum) { if ($originalDatum instanceof FamilyInterface) { $originalData[$key] = $originalDatum->getCode(); } } return $originalData; } if ($originalData instanceof FamilyInterface) { $originalData = $originalData->getCode(); } return $originalData; }, function ($submittedData) use ($options) { if (null === $submittedData) { return $submittedData; } if ($submittedData instanceof FamilyInterface) { // Should actually never happen ? return $submittedData; } if (\is_array($submittedData) && $options['multiple']) { foreach ($submittedData as $key => $submittedDatum) { if ($submittedDatum instanceof FamilyInterface) { continue; } $submittedData[$key] = $this->familyRegistry->getFamily($submittedDatum); } return $submittedData; } /** @var string $submittedData */ return $this->familyRegistry->getFamily($submittedData); } ) ); }
[ "public", "function", "buildForm", "(", "FormBuilderInterface", "$", "builder", ",", "array", "$", "options", ")", "{", "$", "builder", "->", "addModelTransformer", "(", "new", "CallbackTransformer", "(", "function", "(", "$", "originalData", ")", "use", "(", ...
@param FormBuilderInterface $builder @param array $options @throws MissingFamilyException
[ "@param", "FormBuilderInterface", "$builder", "@param", "array", "$options" ]
train
https://github.com/VincentChalnot/SidusEAVModelBundle/blob/6a0e184ac7ed2aead48b05e5f97badac7fe8000f/Form/Type/FamilySelectorType.php#L47-L93
VincentChalnot/SidusEAVModelBundle
Form/Type/FamilySelectorType.php
FamilySelectorType.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'choices' => null, 'families' => null, ] ); $resolver->setNormalizer( 'families', function (Options $options, $values) { if (null === $values) { $values = $this->familyRegistry->getFamilies(); } $families = []; foreach ($values as $value) { if (!$value instanceof FamilyInterface) { $value = $this->familyRegistry->getFamily($value); } if ($value->isInstantiable()) { $families[$value->getCode()] = $value; } } return $families; } ); $resolver->setNormalizer( 'choices', function (Options $options, $value) { if (null !== $value) { throw new \UnexpectedValueException( "'choices' options is not supported for family selector, please use 'families' option" ); } $choices = []; /** @var FamilyInterface[] $families */ $families = $options['families']; $duplicates = []; foreach ($families as $family) { if ($family->isInstantiable()) { $label = ucfirst($family); if (array_key_exists($label, $choices)) { // Storing duplicates $duplicates[] = $label; $label = "{$label} ({$family->getCode()})"; } $choices[$label] = $family->getCode(); } } // Recreating duplicates foreach ($duplicates as $duplicate) { $choices["{$duplicate} ({$choices[$duplicate]})"] = $choices[$duplicate]; unset($choices[$duplicate]); } ksort($choices); return $choices; } ); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'choices' => null, 'families' => null, ] ); $resolver->setNormalizer( 'families', function (Options $options, $values) { if (null === $values) { $values = $this->familyRegistry->getFamilies(); } $families = []; foreach ($values as $value) { if (!$value instanceof FamilyInterface) { $value = $this->familyRegistry->getFamily($value); } if ($value->isInstantiable()) { $families[$value->getCode()] = $value; } } return $families; } ); $resolver->setNormalizer( 'choices', function (Options $options, $value) { if (null !== $value) { throw new \UnexpectedValueException( "'choices' options is not supported for family selector, please use 'families' option" ); } $choices = []; /** @var FamilyInterface[] $families */ $families = $options['families']; $duplicates = []; foreach ($families as $family) { if ($family->isInstantiable()) { $label = ucfirst($family); if (array_key_exists($label, $choices)) { // Storing duplicates $duplicates[] = $label; $label = "{$label} ({$family->getCode()})"; } $choices[$label] = $family->getCode(); } } // Recreating duplicates foreach ($duplicates as $duplicate) { $choices["{$duplicate} ({$choices[$duplicate]})"] = $choices[$duplicate]; unset($choices[$duplicate]); } ksort($choices); return $choices; } ); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", "{", "$", "resolver", "->", "setDefaults", "(", "[", "'choices'", "=>", "null", ",", "'families'", "=>", "null", ",", "]", ")", ";", "$", "resolver", "->", "setNormalizer...
@param OptionsResolver $resolver @throws \Exception
[ "@param", "OptionsResolver", "$resolver" ]
train
https://github.com/VincentChalnot/SidusEAVModelBundle/blob/6a0e184ac7ed2aead48b05e5f97badac7fe8000f/Form/Type/FamilySelectorType.php#L100-L162
thephpleague/event
src/BufferedEmitter.php
BufferedEmitter.emitBufferedEvents
public function emitBufferedEvents() { $result = []; while ($event = array_shift($this->bufferedEvents)) { $result[] = parent::emit($event); } return $result; }
php
public function emitBufferedEvents() { $result = []; while ($event = array_shift($this->bufferedEvents)) { $result[] = parent::emit($event); } return $result; }
[ "public", "function", "emitBufferedEvents", "(", ")", "{", "$", "result", "=", "[", "]", ";", "while", "(", "$", "event", "=", "array_shift", "(", "$", "this", "->", "bufferedEvents", ")", ")", "{", "$", "result", "[", "]", "=", "parent", "::", "emit...
Emit the buffered events. @return array
[ "Emit", "the", "buffered", "events", "." ]
train
https://github.com/thephpleague/event/blob/d2cc124cf9a3fab2bb4ff963307f60361ce4d119/src/BufferedEmitter.php#L39-L48
thephpleague/event
src/Emitter.php
Emitter.getSortedListeners
protected function getSortedListeners($event) { if (! $this->hasListeners($event)) { return []; } $listeners = $this->listeners[$event]; krsort($listeners); return call_user_func_array('array_merge', $listeners); }
php
protected function getSortedListeners($event) { if (! $this->hasListeners($event)) { return []; } $listeners = $this->listeners[$event]; krsort($listeners); return call_user_func_array('array_merge', $listeners); }
[ "protected", "function", "getSortedListeners", "(", "$", "event", ")", "{", "if", "(", "!", "$", "this", "->", "hasListeners", "(", "$", "event", ")", ")", "{", "return", "[", "]", ";", "}", "$", "listeners", "=", "$", "this", "->", "listeners", "[",...
Get the listeners sorted by priority for a given event. @param string $event @return ListenerInterface[]
[ "Get", "the", "listeners", "sorted", "by", "priority", "for", "a", "given", "event", "." ]
train
https://github.com/thephpleague/event/blob/d2cc124cf9a3fab2bb4ff963307f60361ce4d119/src/Emitter.php#L150-L160
thephpleague/event
src/Emitter.php
Emitter.invokeListeners
protected function invokeListeners($name, EventInterface $event, array $arguments) { $listeners = $this->getListeners($name); foreach ($listeners as $listener) { if ($event->isPropagationStopped()) { break; } call_user_func_array([$listener, 'handle'], $arguments); } }
php
protected function invokeListeners($name, EventInterface $event, array $arguments) { $listeners = $this->getListeners($name); foreach ($listeners as $listener) { if ($event->isPropagationStopped()) { break; } call_user_func_array([$listener, 'handle'], $arguments); } }
[ "protected", "function", "invokeListeners", "(", "$", "name", ",", "EventInterface", "$", "event", ",", "array", "$", "arguments", ")", "{", "$", "listeners", "=", "$", "this", "->", "getListeners", "(", "$", "name", ")", ";", "foreach", "(", "$", "liste...
Invoke the listeners for an event. @param string $name @param EventInterface $event @param array $arguments @return void
[ "Invoke", "the", "listeners", "for", "an", "event", "." ]
train
https://github.com/thephpleague/event/blob/d2cc124cf9a3fab2bb4ff963307f60361ce4d119/src/Emitter.php#L208-L219
thephpleague/event
src/Emitter.php
Emitter.prepareEvent
protected function prepareEvent($event) { $event = $this->ensureEvent($event); $name = $event->getName(); $event->setEmitter($this); return [$name, $event]; }
php
protected function prepareEvent($event) { $event = $this->ensureEvent($event); $name = $event->getName(); $event->setEmitter($this); return [$name, $event]; }
[ "protected", "function", "prepareEvent", "(", "$", "event", ")", "{", "$", "event", "=", "$", "this", "->", "ensureEvent", "(", "$", "event", ")", ";", "$", "name", "=", "$", "event", "->", "getName", "(", ")", ";", "$", "event", "->", "setEmitter", ...
Prepare an event for emitting. @param string|EventInterface $event @return array
[ "Prepare", "an", "event", "for", "emitting", "." ]
train
https://github.com/thephpleague/event/blob/d2cc124cf9a3fab2bb4ff963307f60361ce4d119/src/Emitter.php#L228-L235
thephpleague/event
src/Emitter.php
Emitter.ensureEvent
protected function ensureEvent($event) { if (is_string($event)) { return Event::named($event); } if (! $event instanceof EventInterface) { throw new InvalidArgumentException('Events should be provides as Event instances or string, received type: '.gettype($event)); } return $event; }
php
protected function ensureEvent($event) { if (is_string($event)) { return Event::named($event); } if (! $event instanceof EventInterface) { throw new InvalidArgumentException('Events should be provides as Event instances or string, received type: '.gettype($event)); } return $event; }
[ "protected", "function", "ensureEvent", "(", "$", "event", ")", "{", "if", "(", "is_string", "(", "$", "event", ")", ")", "{", "return", "Event", "::", "named", "(", "$", "event", ")", ";", "}", "if", "(", "!", "$", "event", "instanceof", "EventInter...
Ensure event input is of type EventInterface or convert it. @param string|EventInterface $event @throws InvalidArgumentException @return EventInterface
[ "Ensure", "event", "input", "is", "of", "type", "EventInterface", "or", "convert", "it", "." ]
train
https://github.com/thephpleague/event/blob/d2cc124cf9a3fab2bb4ff963307f60361ce4d119/src/Emitter.php#L246-L257
thephpleague/event
src/EmitterTrait.php
EmitterTrait.addListener
public function addListener($event, $listener, $priority = ListenerAcceptorInterface::P_NORMAL) { $this->getEmitter()->addListener($event, $listener, $priority); return $this; }
php
public function addListener($event, $listener, $priority = ListenerAcceptorInterface::P_NORMAL) { $this->getEmitter()->addListener($event, $listener, $priority); return $this; }
[ "public", "function", "addListener", "(", "$", "event", ",", "$", "listener", ",", "$", "priority", "=", "ListenerAcceptorInterface", "::", "P_NORMAL", ")", "{", "$", "this", "->", "getEmitter", "(", ")", "->", "addListener", "(", "$", "event", ",", "$", ...
Add a listener for an event. The first parameter should be the event name, and the second should be the event listener. It may implement the League\Event\ListenerInterface or simply be "callable". @param string $event @param ListenerInterface|callable $listener @param int $priority @return $this
[ "Add", "a", "listener", "for", "an", "event", "." ]
train
https://github.com/thephpleague/event/blob/d2cc124cf9a3fab2bb4ff963307f60361ce4d119/src/EmitterTrait.php#L22-L27
thephpleague/event
src/EmitterTrait.php
EmitterTrait.addOneTimeListener
public function addOneTimeListener($event, $listener, $priority = ListenerAcceptorInterface::P_NORMAL) { $this->getEmitter()->addOneTimeListener($event, $listener, $priority); return $this; }
php
public function addOneTimeListener($event, $listener, $priority = ListenerAcceptorInterface::P_NORMAL) { $this->getEmitter()->addOneTimeListener($event, $listener, $priority); return $this; }
[ "public", "function", "addOneTimeListener", "(", "$", "event", ",", "$", "listener", ",", "$", "priority", "=", "ListenerAcceptorInterface", "::", "P_NORMAL", ")", "{", "$", "this", "->", "getEmitter", "(", ")", "->", "addOneTimeListener", "(", "$", "event", ...
Add a one time listener for an event. The first parameter should be the event name, and the second should be the event listener. It may implement the League\Event\ListenerInterface or simply be "callable". @param string $event @param ListenerInterface|callable $listener @param int $priority @return $this
[ "Add", "a", "one", "time", "listener", "for", "an", "event", "." ]
train
https://github.com/thephpleague/event/blob/d2cc124cf9a3fab2bb4ff963307f60361ce4d119/src/EmitterTrait.php#L42-L47
thephpleague/event
src/EmitterTrait.php
EmitterTrait.emit
public function emit($event) { $emitter = $this->getEmitter(); $arguments = [$event] + func_get_args(); return call_user_func_array([$emitter, 'emit'], $arguments); }
php
public function emit($event) { $emitter = $this->getEmitter(); $arguments = [$event] + func_get_args(); return call_user_func_array([$emitter, 'emit'], $arguments); }
[ "public", "function", "emit", "(", "$", "event", ")", "{", "$", "emitter", "=", "$", "this", "->", "getEmitter", "(", ")", ";", "$", "arguments", "=", "[", "$", "event", "]", "+", "func_get_args", "(", ")", ";", "return", "call_user_func_array", "(", ...
Emit an event. @param string|EventInterface $event @return EventInterface
[ "Emit", "an", "event", "." ]
train
https://github.com/thephpleague/event/blob/d2cc124cf9a3fab2bb4ff963307f60361ce4d119/src/EmitterTrait.php#L106-L112
schmittjoh/metadata
src/Driver/AbstractFileDriver.php
AbstractFileDriver.getAllClassNames
public function getAllClassNames(): array { if (!$this->locator instanceof AdvancedFileLocatorInterface) { throw new \RuntimeException(sprintf('Locator "%s" must be an instance of "AdvancedFileLocatorInterface".', get_class($this->locator))); } return $this->locator->findAllClasses($this->getExtension()); }
php
public function getAllClassNames(): array { if (!$this->locator instanceof AdvancedFileLocatorInterface) { throw new \RuntimeException(sprintf('Locator "%s" must be an instance of "AdvancedFileLocatorInterface".', get_class($this->locator))); } return $this->locator->findAllClasses($this->getExtension()); }
[ "public", "function", "getAllClassNames", "(", ")", ":", "array", "{", "if", "(", "!", "$", "this", "->", "locator", "instanceof", "AdvancedFileLocatorInterface", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Locator \"%s\" must be an ...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Driver/AbstractFileDriver.php#L38-L45
schmittjoh/metadata
src/Driver/DriverChain.php
DriverChain.getAllClassNames
public function getAllClassNames(): array { $classes = []; foreach ($this->drivers as $driver) { if (!$driver instanceof AdvancedDriverInterface) { throw new \RuntimeException( sprintf( 'Driver "%s" must be an instance of "AdvancedDriverInterface" to use ' . '"DriverChain::getAllClassNames()".', get_class($driver) ) ); } $driverClasses = $driver->getAllClassNames(); if (!empty($driverClasses)) { $classes = array_merge($classes, $driverClasses); } } return $classes; }
php
public function getAllClassNames(): array { $classes = []; foreach ($this->drivers as $driver) { if (!$driver instanceof AdvancedDriverInterface) { throw new \RuntimeException( sprintf( 'Driver "%s" must be an instance of "AdvancedDriverInterface" to use ' . '"DriverChain::getAllClassNames()".', get_class($driver) ) ); } $driverClasses = $driver->getAllClassNames(); if (!empty($driverClasses)) { $classes = array_merge($classes, $driverClasses); } } return $classes; }
[ "public", "function", "getAllClassNames", "(", ")", ":", "array", "{", "$", "classes", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "drivers", "as", "$", "driver", ")", "{", "if", "(", "!", "$", "driver", "instanceof", "AdvancedDriverInterface"...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Driver/DriverChain.php#L43-L63
schmittjoh/metadata
src/Cache/PsrCacheAdapter.php
PsrCacheAdapter.load
public function load(string $class): ?ClassMetadata { $this->lastItem = $this->pool->getItem(strtr($this->prefix . $class, '\\', '.')); return $this->lastItem->get(); }
php
public function load(string $class): ?ClassMetadata { $this->lastItem = $this->pool->getItem(strtr($this->prefix . $class, '\\', '.')); return $this->lastItem->get(); }
[ "public", "function", "load", "(", "string", "$", "class", ")", ":", "?", "ClassMetadata", "{", "$", "this", "->", "lastItem", "=", "$", "this", "->", "pool", "->", "getItem", "(", "strtr", "(", "$", "this", "->", "prefix", ".", "$", "class", ",", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Cache/PsrCacheAdapter.php#L36-L41
schmittjoh/metadata
src/Cache/PsrCacheAdapter.php
PsrCacheAdapter.put
public function put(ClassMetadata $metadata): void { $key = strtr($this->prefix . $metadata->name, '\\', '.'); if (null === $this->lastItem || $this->lastItem->getKey() !== $key) { $this->lastItem = $this->pool->getItem($key); } $this->pool->save($this->lastItem->set($metadata)); }
php
public function put(ClassMetadata $metadata): void { $key = strtr($this->prefix . $metadata->name, '\\', '.'); if (null === $this->lastItem || $this->lastItem->getKey() !== $key) { $this->lastItem = $this->pool->getItem($key); } $this->pool->save($this->lastItem->set($metadata)); }
[ "public", "function", "put", "(", "ClassMetadata", "$", "metadata", ")", ":", "void", "{", "$", "key", "=", "strtr", "(", "$", "this", "->", "prefix", ".", "$", "metadata", "->", "name", ",", "'\\\\'", ",", "'.'", ")", ";", "if", "(", "null", "==="...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Cache/PsrCacheAdapter.php#L46-L55
schmittjoh/metadata
src/Cache/DoctrineCacheAdapter.php
DoctrineCacheAdapter.load
public function load(string $class): ?ClassMetadata { $cache = $this->cache->fetch($this->prefix . $class); return false === $cache ? null : $cache; }
php
public function load(string $class): ?ClassMetadata { $cache = $this->cache->fetch($this->prefix . $class); return false === $cache ? null : $cache; }
[ "public", "function", "load", "(", "string", "$", "class", ")", ":", "?", "ClassMetadata", "{", "$", "cache", "=", "$", "this", "->", "cache", "->", "fetch", "(", "$", "this", "->", "prefix", ".", "$", "class", ")", ";", "return", "false", "===", "...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Cache/DoctrineCacheAdapter.php#L33-L37
schmittjoh/metadata
src/Cache/DoctrineCacheAdapter.php
DoctrineCacheAdapter.put
public function put(ClassMetadata $metadata): void { $this->cache->save($this->prefix . $metadata->name, $metadata); }
php
public function put(ClassMetadata $metadata): void { $this->cache->save($this->prefix . $metadata->name, $metadata); }
[ "public", "function", "put", "(", "ClassMetadata", "$", "metadata", ")", ":", "void", "{", "$", "this", "->", "cache", "->", "save", "(", "$", "this", "->", "prefix", ".", "$", "metadata", "->", "name", ",", "$", "metadata", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Cache/DoctrineCacheAdapter.php#L42-L45
schmittjoh/metadata
src/ClassMetadata.php
ClassMetadata.serialize
public function serialize() { return serialize([ $this->name, $this->methodMetadata, $this->propertyMetadata, $this->fileResources, $this->createdAt, ]); }
php
public function serialize() { return serialize([ $this->name, $this->methodMetadata, $this->propertyMetadata, $this->fileResources, $this->createdAt, ]); }
[ "public", "function", "serialize", "(", ")", "{", "return", "serialize", "(", "[", "$", "this", "->", "name", ",", "$", "this", "->", "methodMetadata", ",", "$", "this", "->", "propertyMetadata", ",", "$", "this", "->", "fileResources", ",", "$", "this",...
@phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.UselessReturnAnnotation @return string
[ "@phpcsSuppress", "SlevomatCodingStandard", ".", "TypeHints", ".", "TypeHintDeclaration", ".", "MissingParameterTypeHint", "@phpcsSuppress", "SlevomatCodingStandard", ".", "TypeHints", ".", "TypeHintDeclaration", ".", "MissingReturnTypeHint", "@phpcsSuppress", "SlevomatCodingStanda...
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/ClassMetadata.php#L84-L93
schmittjoh/metadata
src/ClassMetadata.php
ClassMetadata.unserialize
public function unserialize($str) { list( $this->name, $this->methodMetadata, $this->propertyMetadata, $this->fileResources, $this->createdAt ) = unserialize($str); }
php
public function unserialize($str) { list( $this->name, $this->methodMetadata, $this->propertyMetadata, $this->fileResources, $this->createdAt ) = unserialize($str); }
[ "public", "function", "unserialize", "(", "$", "str", ")", "{", "list", "(", "$", "this", "->", "name", ",", "$", "this", "->", "methodMetadata", ",", "$", "this", "->", "propertyMetadata", ",", "$", "this", "->", "fileResources", ",", "$", "this", "->...
@phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.UselessReturnAnnotation @param string $str @return void
[ "@phpcsSuppress", "SlevomatCodingStandard", ".", "TypeHints", ".", "TypeHintDeclaration", ".", "MissingParameterTypeHint", "@phpcsSuppress", "SlevomatCodingStandard", ".", "TypeHints", ".", "TypeHintDeclaration", ".", "MissingReturnTypeHint", "@phpcsSuppress", "SlevomatCodingStanda...
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/ClassMetadata.php#L103-L112
schmittjoh/metadata
src/Cache/FileCache.php
FileCache.load
public function load(string $class): ?ClassMetadata { $path = $this->dir . '/' . strtr($class, '\\', '-') . '.cache.php'; if (!file_exists($path)) { return null; } return include $path; }
php
public function load(string $class): ?ClassMetadata { $path = $this->dir . '/' . strtr($class, '\\', '-') . '.cache.php'; if (!file_exists($path)) { return null; } return include $path; }
[ "public", "function", "load", "(", "string", "$", "class", ")", ":", "?", "ClassMetadata", "{", "$", "path", "=", "$", "this", "->", "dir", ".", "'/'", ".", "strtr", "(", "$", "class", ",", "'\\\\'", ",", "'-'", ")", ".", "'.cache.php'", ";", "if",...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Cache/FileCache.php#L28-L36
schmittjoh/metadata
src/Cache/FileCache.php
FileCache.put
public function put(ClassMetadata $metadata): void { if (!is_writable($this->dir)) { throw new \InvalidArgumentException(sprintf('The directory "%s" is not writable.', $this->dir)); } $path = $this->dir . '/' . strtr($metadata->name, '\\', '-') . '.cache.php'; $tmpFile = tempnam($this->dir, 'metadata-cache'); file_put_contents($tmpFile, '<?php return unserialize(' . var_export(serialize($metadata), true) . ');'); // Let's not break filesystems which do not support chmod. @chmod($tmpFile, 0666 & ~umask()); $this->renameFile($tmpFile, $path); }
php
public function put(ClassMetadata $metadata): void { if (!is_writable($this->dir)) { throw new \InvalidArgumentException(sprintf('The directory "%s" is not writable.', $this->dir)); } $path = $this->dir . '/' . strtr($metadata->name, '\\', '-') . '.cache.php'; $tmpFile = tempnam($this->dir, 'metadata-cache'); file_put_contents($tmpFile, '<?php return unserialize(' . var_export(serialize($metadata), true) . ');'); // Let's not break filesystems which do not support chmod. @chmod($tmpFile, 0666 & ~umask()); $this->renameFile($tmpFile, $path); }
[ "public", "function", "put", "(", "ClassMetadata", "$", "metadata", ")", ":", "void", "{", "if", "(", "!", "is_writable", "(", "$", "this", "->", "dir", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'The directory \...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Cache/FileCache.php#L41-L56
schmittjoh/metadata
src/Cache/FileCache.php
FileCache.evict
public function evict(string $class): void { $path = $this->dir . '/' . strtr($class, '\\', '-') . '.cache.php'; if (file_exists($path)) { unlink($path); } }
php
public function evict(string $class): void { $path = $this->dir . '/' . strtr($class, '\\', '-') . '.cache.php'; if (file_exists($path)) { unlink($path); } }
[ "public", "function", "evict", "(", "string", "$", "class", ")", ":", "void", "{", "$", "path", "=", "$", "this", "->", "dir", ".", "'/'", ".", "strtr", "(", "$", "class", ",", "'\\\\'", ",", "'-'", ")", ".", "'.cache.php'", ";", "if", "(", "file...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/Cache/FileCache.php#L81-L87
schmittjoh/metadata
src/MetadataFactory.php
MetadataFactory.getMetadataForClass
public function getMetadataForClass(string $className) { if (isset($this->loadedMetadata[$className])) { return $this->filterNullMetadata($this->loadedMetadata[$className]); } $metadata = null; foreach ($this->getClassHierarchy($className) as $class) { if (isset($this->loadedClassMetadata[$name = $class->getName()])) { if (null !== $classMetadata = $this->filterNullMetadata($this->loadedClassMetadata[$name])) { $this->addClassMetadata($metadata, $classMetadata); } continue; } // check the cache if (null !== $this->cache) { if (($classMetadata = $this->cache->load($class->getName())) instanceof NullMetadata) { $this->loadedClassMetadata[$name] = $classMetadata; continue; } if (null !== $classMetadata) { if (!$classMetadata instanceof ClassMetadata) { throw new \LogicException(sprintf('The cache must return instances of ClassMetadata, but got %s.', var_export($classMetadata, true))); } if ($this->debug && !$classMetadata->isFresh()) { $this->cache->evict($classMetadata->name); } else { $this->loadedClassMetadata[$name] = $classMetadata; $this->addClassMetadata($metadata, $classMetadata); continue; } } } // load from source if (null !== $classMetadata = $this->driver->loadMetadataForClass($class)) { $this->loadedClassMetadata[$name] = $classMetadata; $this->addClassMetadata($metadata, $classMetadata); if (null !== $this->cache) { $this->cache->put($classMetadata); } continue; } if (null !== $this->cache && !$this->debug) { $this->cache->put(new NullMetadata($class->getName())); } } if (null === $metadata) { $metadata = new NullMetadata($className); } return $this->filterNullMetadata($this->loadedMetadata[$className] = $metadata); }
php
public function getMetadataForClass(string $className) { if (isset($this->loadedMetadata[$className])) { return $this->filterNullMetadata($this->loadedMetadata[$className]); } $metadata = null; foreach ($this->getClassHierarchy($className) as $class) { if (isset($this->loadedClassMetadata[$name = $class->getName()])) { if (null !== $classMetadata = $this->filterNullMetadata($this->loadedClassMetadata[$name])) { $this->addClassMetadata($metadata, $classMetadata); } continue; } // check the cache if (null !== $this->cache) { if (($classMetadata = $this->cache->load($class->getName())) instanceof NullMetadata) { $this->loadedClassMetadata[$name] = $classMetadata; continue; } if (null !== $classMetadata) { if (!$classMetadata instanceof ClassMetadata) { throw new \LogicException(sprintf('The cache must return instances of ClassMetadata, but got %s.', var_export($classMetadata, true))); } if ($this->debug && !$classMetadata->isFresh()) { $this->cache->evict($classMetadata->name); } else { $this->loadedClassMetadata[$name] = $classMetadata; $this->addClassMetadata($metadata, $classMetadata); continue; } } } // load from source if (null !== $classMetadata = $this->driver->loadMetadataForClass($class)) { $this->loadedClassMetadata[$name] = $classMetadata; $this->addClassMetadata($metadata, $classMetadata); if (null !== $this->cache) { $this->cache->put($classMetadata); } continue; } if (null !== $this->cache && !$this->debug) { $this->cache->put(new NullMetadata($class->getName())); } } if (null === $metadata) { $metadata = new NullMetadata($className); } return $this->filterNullMetadata($this->loadedMetadata[$className] = $metadata); }
[ "public", "function", "getMetadataForClass", "(", "string", "$", "className", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "loadedMetadata", "[", "$", "className", "]", ")", ")", "{", "return", "$", "this", "->", "filterNullMetadata", "(", "$", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/MetadataFactory.php#L69-L128
schmittjoh/metadata
src/MetadataFactory.php
MetadataFactory.getAllClassNames
public function getAllClassNames(): array { if (!$this->driver instanceof AdvancedDriverInterface) { throw new \RuntimeException( sprintf('Driver "%s" must be an instance of "AdvancedDriverInterface".', get_class($this->driver)) ); } return $this->driver->getAllClassNames(); }
php
public function getAllClassNames(): array { if (!$this->driver instanceof AdvancedDriverInterface) { throw new \RuntimeException( sprintf('Driver "%s" must be an instance of "AdvancedDriverInterface".', get_class($this->driver)) ); } return $this->driver->getAllClassNames(); }
[ "public", "function", "getAllClassNames", "(", ")", ":", "array", "{", "if", "(", "!", "$", "this", "->", "driver", "instanceof", "AdvancedDriverInterface", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Driver \"%s\" must be an instanc...
{@inheritDoc}
[ "{" ]
train
https://github.com/schmittjoh/metadata/blob/d2ef520eb331e00bddd1b9306eecca9302c57f16/src/MetadataFactory.php#L133-L142
Seldaek/jsonlint
src/Seld/JsonLint/JsonParser.php
JsonParser.performAction
private function performAction(stdClass $yyval, $yytext, $yyleng, $yylineno, $yystate, &$tokens) { // $0 = $len $len = count($tokens) - 1; switch ($yystate) { case 1: $yytext = preg_replace_callback('{(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4})}', array($this, 'stringInterpolation'), $yytext); $yyval->token = $yytext; break; case 2: if (strpos($yytext, 'e') !== false || strpos($yytext, 'E') !== false) { $yyval->token = floatval($yytext); } else { $yyval->token = strpos($yytext, '.') === false ? intval($yytext) : floatval($yytext); } break; case 3: $yyval->token = null; break; case 4: $yyval->token = true; break; case 5: $yyval->token = false; break; case 6: return $yyval->token = $tokens[$len-1]; case 13: if ($this->flags & self::PARSE_TO_ASSOC) { $yyval->token = array(); } else { $yyval->token = new stdClass; } break; case 14: $yyval->token = $tokens[$len-1]; break; case 15: $yyval->token = array($tokens[$len-2], $tokens[$len]); break; case 16: if (PHP_VERSION_ID < 70100) { $property = $tokens[$len][0] === '' ? '_empty_' : $tokens[$len][0]; } else { $property = $tokens[$len][0]; } if ($this->flags & self::PARSE_TO_ASSOC) { $yyval->token = array(); $yyval->token[$property] = $tokens[$len][1]; } else { $yyval->token = new stdClass; $yyval->token->$property = $tokens[$len][1]; } break; case 17: if ($this->flags & self::PARSE_TO_ASSOC) { $yyval->token =& $tokens[$len-2]; $key = $tokens[$len][0]; if (($this->flags & self::DETECT_KEY_CONFLICTS) && isset($tokens[$len-2][$key])) { $errStr = 'Parse error on line ' . ($yylineno+1) . ":\n"; $errStr .= $this->lexer->showPosition() . "\n"; $errStr .= "Duplicate key: ".$tokens[$len][0]; throw new DuplicateKeyException($errStr, $tokens[$len][0], array('line' => $yylineno+1)); } elseif (($this->flags & self::ALLOW_DUPLICATE_KEYS) && isset($tokens[$len-2][$key])) { $duplicateCount = 1; do { $duplicateKey = $key . '.' . $duplicateCount++; } while (isset($tokens[$len-2][$duplicateKey])); $key = $duplicateKey; } $tokens[$len-2][$key] = $tokens[$len][1]; } else { $yyval->token = $tokens[$len-2]; if (PHP_VERSION_ID < 70100) { $key = $tokens[$len][0] === '' ? '_empty_' : $tokens[$len][0]; } else { $key = $tokens[$len][0]; } if (($this->flags & self::DETECT_KEY_CONFLICTS) && isset($tokens[$len-2]->{$key})) { $errStr = 'Parse error on line ' . ($yylineno+1) . ":\n"; $errStr .= $this->lexer->showPosition() . "\n"; $errStr .= "Duplicate key: ".$tokens[$len][0]; throw new DuplicateKeyException($errStr, $tokens[$len][0], array('line' => $yylineno+1)); } elseif (($this->flags & self::ALLOW_DUPLICATE_KEYS) && isset($tokens[$len-2]->{$key})) { $duplicateCount = 1; do { $duplicateKey = $key . '.' . $duplicateCount++; } while (isset($tokens[$len-2]->$duplicateKey)); $key = $duplicateKey; } $tokens[$len-2]->$key = $tokens[$len][1]; } break; case 18: $yyval->token = array(); break; case 19: $yyval->token = $tokens[$len-1]; break; case 20: $yyval->token = array($tokens[$len]); break; case 21: $tokens[$len-2][] = $tokens[$len]; $yyval->token = $tokens[$len-2]; break; } return new Undefined(); }
php
private function performAction(stdClass $yyval, $yytext, $yyleng, $yylineno, $yystate, &$tokens) { // $0 = $len $len = count($tokens) - 1; switch ($yystate) { case 1: $yytext = preg_replace_callback('{(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4})}', array($this, 'stringInterpolation'), $yytext); $yyval->token = $yytext; break; case 2: if (strpos($yytext, 'e') !== false || strpos($yytext, 'E') !== false) { $yyval->token = floatval($yytext); } else { $yyval->token = strpos($yytext, '.') === false ? intval($yytext) : floatval($yytext); } break; case 3: $yyval->token = null; break; case 4: $yyval->token = true; break; case 5: $yyval->token = false; break; case 6: return $yyval->token = $tokens[$len-1]; case 13: if ($this->flags & self::PARSE_TO_ASSOC) { $yyval->token = array(); } else { $yyval->token = new stdClass; } break; case 14: $yyval->token = $tokens[$len-1]; break; case 15: $yyval->token = array($tokens[$len-2], $tokens[$len]); break; case 16: if (PHP_VERSION_ID < 70100) { $property = $tokens[$len][0] === '' ? '_empty_' : $tokens[$len][0]; } else { $property = $tokens[$len][0]; } if ($this->flags & self::PARSE_TO_ASSOC) { $yyval->token = array(); $yyval->token[$property] = $tokens[$len][1]; } else { $yyval->token = new stdClass; $yyval->token->$property = $tokens[$len][1]; } break; case 17: if ($this->flags & self::PARSE_TO_ASSOC) { $yyval->token =& $tokens[$len-2]; $key = $tokens[$len][0]; if (($this->flags & self::DETECT_KEY_CONFLICTS) && isset($tokens[$len-2][$key])) { $errStr = 'Parse error on line ' . ($yylineno+1) . ":\n"; $errStr .= $this->lexer->showPosition() . "\n"; $errStr .= "Duplicate key: ".$tokens[$len][0]; throw new DuplicateKeyException($errStr, $tokens[$len][0], array('line' => $yylineno+1)); } elseif (($this->flags & self::ALLOW_DUPLICATE_KEYS) && isset($tokens[$len-2][$key])) { $duplicateCount = 1; do { $duplicateKey = $key . '.' . $duplicateCount++; } while (isset($tokens[$len-2][$duplicateKey])); $key = $duplicateKey; } $tokens[$len-2][$key] = $tokens[$len][1]; } else { $yyval->token = $tokens[$len-2]; if (PHP_VERSION_ID < 70100) { $key = $tokens[$len][0] === '' ? '_empty_' : $tokens[$len][0]; } else { $key = $tokens[$len][0]; } if (($this->flags & self::DETECT_KEY_CONFLICTS) && isset($tokens[$len-2]->{$key})) { $errStr = 'Parse error on line ' . ($yylineno+1) . ":\n"; $errStr .= $this->lexer->showPosition() . "\n"; $errStr .= "Duplicate key: ".$tokens[$len][0]; throw new DuplicateKeyException($errStr, $tokens[$len][0], array('line' => $yylineno+1)); } elseif (($this->flags & self::ALLOW_DUPLICATE_KEYS) && isset($tokens[$len-2]->{$key})) { $duplicateCount = 1; do { $duplicateKey = $key . '.' . $duplicateCount++; } while (isset($tokens[$len-2]->$duplicateKey)); $key = $duplicateKey; } $tokens[$len-2]->$key = $tokens[$len][1]; } break; case 18: $yyval->token = array(); break; case 19: $yyval->token = $tokens[$len-1]; break; case 20: $yyval->token = array($tokens[$len]); break; case 21: $tokens[$len-2][] = $tokens[$len]; $yyval->token = $tokens[$len-2]; break; } return new Undefined(); }
[ "private", "function", "performAction", "(", "stdClass", "$", "yyval", ",", "$", "yytext", ",", "$", "yyleng", ",", "$", "yylineno", ",", "$", "yystate", ",", "&", "$", "tokens", ")", "{", "// $0 = $len", "$", "len", "=", "count", "(", "$", "tokens", ...
_$ removed, useless?
[ "_$", "removed", "useless?" ]
train
https://github.com/Seldaek/jsonlint/blob/6a4aec51a0d1d79f2060d429800bc5312663b4d7/src/Seld/JsonLint/JsonParser.php#L340-L449
php-http/curl-client
src/CurlPromise.php
CurlPromise.then
public function then(callable $onFulfilled = null, callable $onRejected = null) { if ($onFulfilled) { $this->core->addOnFulfilled($onFulfilled); } if ($onRejected) { $this->core->addOnRejected($onRejected); } return new self($this->core, $this->runner); }
php
public function then(callable $onFulfilled = null, callable $onRejected = null) { if ($onFulfilled) { $this->core->addOnFulfilled($onFulfilled); } if ($onRejected) { $this->core->addOnRejected($onRejected); } return new self($this->core, $this->runner); }
[ "public", "function", "then", "(", "callable", "$", "onFulfilled", "=", "null", ",", "callable", "$", "onRejected", "=", "null", ")", "{", "if", "(", "$", "onFulfilled", ")", "{", "$", "this", "->", "core", "->", "addOnFulfilled", "(", "$", "onFulfilled"...
Add behavior for when the promise is resolved or rejected. If you do not care about one of the cases, you can set the corresponding callable to null The callback will be called when the response or exception arrived and never more than once. @param callable $onFulfilled Called when a response will be available @param callable $onRejected Called when an error happens. You must always return the Response in the interface or throw an Exception @return Promise Always returns a new promise which is resolved with value of the executed callback (onFulfilled / onRejected)
[ "Add", "behavior", "for", "when", "the", "promise", "is", "resolved", "or", "rejected", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/CurlPromise.php#L62-L72
php-http/curl-client
src/CurlPromise.php
CurlPromise.wait
public function wait($unwrap = true) { $this->runner->wait($this->core); if ($unwrap) { if ($this->core->getState() === self::REJECTED) { throw $this->core->getException(); } return $this->core->getResponse(); } return null; }
php
public function wait($unwrap = true) { $this->runner->wait($this->core); if ($unwrap) { if ($this->core->getState() === self::REJECTED) { throw $this->core->getException(); } return $this->core->getResponse(); } return null; }
[ "public", "function", "wait", "(", "$", "unwrap", "=", "true", ")", "{", "$", "this", "->", "runner", "->", "wait", "(", "$", "this", "->", "core", ")", ";", "if", "(", "$", "unwrap", ")", "{", "if", "(", "$", "this", "->", "core", "->", "getSt...
Wait for the promise to be fulfilled or rejected. When this method returns, the request has been resolved and the appropriate callable has terminated. When called with the unwrap option @param bool $unwrap Whether to return resolved value / throw reason or not @return \Psr\Http\Message\ResponseInterface|null Resolved value, null if $unwrap is set to false @throws \Http\Client\Exception The rejection reason
[ "Wait", "for", "the", "promise", "to", "be", "fulfilled", "or", "rejected", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/CurlPromise.php#L97-L110
php-http/curl-client
src/Client.php
Client.sendRequest
public function sendRequest(RequestInterface $request): ResponseInterface { $responseBuilder = $this->createResponseBuilder(); $requestOptions = $this->prepareRequestOptions($request, $responseBuilder); if (is_resource($this->handle)) { curl_reset($this->handle); } else { $this->handle = curl_init(); } curl_setopt_array($this->handle, $requestOptions); curl_exec($this->handle); $errno = curl_errno($this->handle); switch ($errno) { case CURLE_OK: // All OK, no actions needed. break; case CURLE_COULDNT_RESOLVE_PROXY: case CURLE_COULDNT_RESOLVE_HOST: case CURLE_COULDNT_CONNECT: case CURLE_OPERATION_TIMEOUTED: case CURLE_SSL_CONNECT_ERROR: throw new Exception\NetworkException(curl_error($this->handle), $request); default: throw new Exception\RequestException(curl_error($this->handle), $request); } $response = $responseBuilder->getResponse(); $response->getBody()->seek(0); return $response; }
php
public function sendRequest(RequestInterface $request): ResponseInterface { $responseBuilder = $this->createResponseBuilder(); $requestOptions = $this->prepareRequestOptions($request, $responseBuilder); if (is_resource($this->handle)) { curl_reset($this->handle); } else { $this->handle = curl_init(); } curl_setopt_array($this->handle, $requestOptions); curl_exec($this->handle); $errno = curl_errno($this->handle); switch ($errno) { case CURLE_OK: // All OK, no actions needed. break; case CURLE_COULDNT_RESOLVE_PROXY: case CURLE_COULDNT_RESOLVE_HOST: case CURLE_COULDNT_CONNECT: case CURLE_OPERATION_TIMEOUTED: case CURLE_SSL_CONNECT_ERROR: throw new Exception\NetworkException(curl_error($this->handle), $request); default: throw new Exception\RequestException(curl_error($this->handle), $request); } $response = $responseBuilder->getResponse(); $response->getBody()->seek(0); return $response; }
[ "public", "function", "sendRequest", "(", "RequestInterface", "$", "request", ")", ":", "ResponseInterface", "{", "$", "responseBuilder", "=", "$", "this", "->", "createResponseBuilder", "(", ")", ";", "$", "requestOptions", "=", "$", "this", "->", "prepareReque...
Sends a PSR-7 request and returns a PSR-7 response. @param RequestInterface $request @return ResponseInterface @throws \InvalidArgumentException For invalid header names or values. @throws \RuntimeException If creating the body stream fails. @throws Exception\NetworkException In case of network problems. @throws Exception\RequestException On invalid request. @since 1.6 \UnexpectedValueException replaced with RequestException @since 1.6 Throw NetworkException on network errors @since 1.0
[ "Sends", "a", "PSR", "-", "7", "request", "and", "returns", "a", "PSR", "-", "7", "response", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/Client.php#L140-L173
php-http/curl-client
src/Client.php
Client.createResponseBuilder
private function createResponseBuilder(): ResponseBuilder { $body = $this->streamFactory->createStreamFromFile('php://temp', 'w+b'); $response = $this->responseFactory ->createResponse(200) ->withBody($body); return new ResponseBuilder($response); }
php
private function createResponseBuilder(): ResponseBuilder { $body = $this->streamFactory->createStreamFromFile('php://temp', 'w+b'); $response = $this->responseFactory ->createResponse(200) ->withBody($body); return new ResponseBuilder($response); }
[ "private", "function", "createResponseBuilder", "(", ")", ":", "ResponseBuilder", "{", "$", "body", "=", "$", "this", "->", "streamFactory", "->", "createStreamFromFile", "(", "'php://temp'", ",", "'w+b'", ")", ";", "$", "response", "=", "$", "this", "->", "...
Create builder to use for building response object. @return ResponseBuilder
[ "Create", "builder", "to", "use", "for", "building", "response", "object", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/Client.php#L180-L189
php-http/curl-client
src/Client.php
Client.prepareRequestOptions
private function prepareRequestOptions( RequestInterface $request, ResponseBuilder $responseBuilder ): array { $curlOptions = $this->curlOptions; try { $curlOptions[CURLOPT_HTTP_VERSION] = $this->getProtocolVersion($request->getProtocolVersion()); } catch (\UnexpectedValueException $e) { throw new Exception\RequestException($e->getMessage(), $request); } $curlOptions[CURLOPT_URL] = (string)$request->getUri(); $curlOptions = $this->addRequestBodyOptions($request, $curlOptions); $curlOptions[CURLOPT_HTTPHEADER] = $this->createHeaders($request, $curlOptions); if ($request->getUri()->getUserInfo()) { $curlOptions[CURLOPT_USERPWD] = $request->getUri()->getUserInfo(); } $curlOptions[CURLOPT_HEADERFUNCTION] = function ($ch, $data) use ($responseBuilder) { $str = trim($data); if ('' !== $str) { if (stripos($str, 'http/') === 0) { $responseBuilder->setStatus($str)->getResponse(); } else { $responseBuilder->addHeader($str); } } return strlen($data); }; $curlOptions[CURLOPT_WRITEFUNCTION] = function ($ch, $data) use ($responseBuilder) { return $responseBuilder->getResponse()->getBody()->write($data); }; return $curlOptions; }
php
private function prepareRequestOptions( RequestInterface $request, ResponseBuilder $responseBuilder ): array { $curlOptions = $this->curlOptions; try { $curlOptions[CURLOPT_HTTP_VERSION] = $this->getProtocolVersion($request->getProtocolVersion()); } catch (\UnexpectedValueException $e) { throw new Exception\RequestException($e->getMessage(), $request); } $curlOptions[CURLOPT_URL] = (string)$request->getUri(); $curlOptions = $this->addRequestBodyOptions($request, $curlOptions); $curlOptions[CURLOPT_HTTPHEADER] = $this->createHeaders($request, $curlOptions); if ($request->getUri()->getUserInfo()) { $curlOptions[CURLOPT_USERPWD] = $request->getUri()->getUserInfo(); } $curlOptions[CURLOPT_HEADERFUNCTION] = function ($ch, $data) use ($responseBuilder) { $str = trim($data); if ('' !== $str) { if (stripos($str, 'http/') === 0) { $responseBuilder->setStatus($str)->getResponse(); } else { $responseBuilder->addHeader($str); } } return strlen($data); }; $curlOptions[CURLOPT_WRITEFUNCTION] = function ($ch, $data) use ($responseBuilder) { return $responseBuilder->getResponse()->getBody()->write($data); }; return $curlOptions; }
[ "private", "function", "prepareRequestOptions", "(", "RequestInterface", "$", "request", ",", "ResponseBuilder", "$", "responseBuilder", ")", ":", "array", "{", "$", "curlOptions", "=", "$", "this", "->", "curlOptions", ";", "try", "{", "$", "curlOptions", "[", ...
Update cURL options for given request and hook in the response builder. @param RequestInterface $request Request on which to create options. @param ResponseBuilder $responseBuilder Builder to use for building response. @return array cURL options based on request. @throws \InvalidArgumentException For invalid header names or values. @throws \RuntimeException If can not read body. @throws Exception\RequestException On invalid request.
[ "Update", "cURL", "options", "for", "given", "request", "and", "hook", "in", "the", "response", "builder", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/Client.php#L203-L243
php-http/curl-client
src/Client.php
Client.getProtocolVersion
private function getProtocolVersion(string $requestVersion): int { switch ($requestVersion) { case '1.0': return CURL_HTTP_VERSION_1_0; case '1.1': return CURL_HTTP_VERSION_1_1; case '2.0': if (defined('CURL_HTTP_VERSION_2_0')) { return CURL_HTTP_VERSION_2_0; } throw new \UnexpectedValueException('libcurl 7.33 needed for HTTP 2.0 support'); } return CURL_HTTP_VERSION_NONE; }
php
private function getProtocolVersion(string $requestVersion): int { switch ($requestVersion) { case '1.0': return CURL_HTTP_VERSION_1_0; case '1.1': return CURL_HTTP_VERSION_1_1; case '2.0': if (defined('CURL_HTTP_VERSION_2_0')) { return CURL_HTTP_VERSION_2_0; } throw new \UnexpectedValueException('libcurl 7.33 needed for HTTP 2.0 support'); } return CURL_HTTP_VERSION_NONE; }
[ "private", "function", "getProtocolVersion", "(", "string", "$", "requestVersion", ")", ":", "int", "{", "switch", "(", "$", "requestVersion", ")", "{", "case", "'1.0'", ":", "return", "CURL_HTTP_VERSION_1_0", ";", "case", "'1.1'", ":", "return", "CURL_HTTP_VERS...
Return cURL constant for specified HTTP version. @param string $requestVersion HTTP version ("1.0", "1.1" or "2.0"). @return int Respective CURL_HTTP_VERSION_x_x constant. @throws \UnexpectedValueException If unsupported version requested.
[ "Return", "cURL", "constant", "for", "specified", "HTTP", "version", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/Client.php#L254-L269
php-http/curl-client
src/Client.php
Client.addRequestBodyOptions
private function addRequestBodyOptions(RequestInterface $request, array $curlOptions): array { /* * Some HTTP methods cannot have payload: * * - GET — cURL will automatically change method to PUT or POST if we set CURLOPT_UPLOAD or * CURLOPT_POSTFIELDS. * - HEAD — cURL treats HEAD as GET request with a same restrictions. * - TRACE — According to RFC7231: a client MUST NOT send a message body in a TRACE request. */ if (!in_array($request->getMethod(), ['GET', 'HEAD', 'TRACE'], true)) { $body = $request->getBody(); $bodySize = $body->getSize(); if ($bodySize !== 0) { if ($body->isSeekable()) { $body->rewind(); } // Message has non empty body. if (null === $bodySize || $bodySize > 1024 * 1024) { // Avoid full loading large or unknown size body into memory $curlOptions[CURLOPT_UPLOAD] = true; if (null !== $bodySize) { $curlOptions[CURLOPT_INFILESIZE] = $bodySize; } $curlOptions[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) { return $body->read($length); }; } else { // Small body can be loaded into memory $curlOptions[CURLOPT_POSTFIELDS] = (string)$body; } } } if ($request->getMethod() === 'HEAD') { // This will set HTTP method to "HEAD". $curlOptions[CURLOPT_NOBODY] = true; } elseif ($request->getMethod() !== 'GET') { // GET is a default method. Other methods should be specified explicitly. $curlOptions[CURLOPT_CUSTOMREQUEST] = $request->getMethod(); } return $curlOptions; }
php
private function addRequestBodyOptions(RequestInterface $request, array $curlOptions): array { /* * Some HTTP methods cannot have payload: * * - GET — cURL will automatically change method to PUT or POST if we set CURLOPT_UPLOAD or * CURLOPT_POSTFIELDS. * - HEAD — cURL treats HEAD as GET request with a same restrictions. * - TRACE — According to RFC7231: a client MUST NOT send a message body in a TRACE request. */ if (!in_array($request->getMethod(), ['GET', 'HEAD', 'TRACE'], true)) { $body = $request->getBody(); $bodySize = $body->getSize(); if ($bodySize !== 0) { if ($body->isSeekable()) { $body->rewind(); } // Message has non empty body. if (null === $bodySize || $bodySize > 1024 * 1024) { // Avoid full loading large or unknown size body into memory $curlOptions[CURLOPT_UPLOAD] = true; if (null !== $bodySize) { $curlOptions[CURLOPT_INFILESIZE] = $bodySize; } $curlOptions[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) { return $body->read($length); }; } else { // Small body can be loaded into memory $curlOptions[CURLOPT_POSTFIELDS] = (string)$body; } } } if ($request->getMethod() === 'HEAD') { // This will set HTTP method to "HEAD". $curlOptions[CURLOPT_NOBODY] = true; } elseif ($request->getMethod() !== 'GET') { // GET is a default method. Other methods should be specified explicitly. $curlOptions[CURLOPT_CUSTOMREQUEST] = $request->getMethod(); } return $curlOptions; }
[ "private", "function", "addRequestBodyOptions", "(", "RequestInterface", "$", "request", ",", "array", "$", "curlOptions", ")", ":", "array", "{", "/*\n * Some HTTP methods cannot have payload:\n *\n * - GET — cURL will automatically change method to PUT or POST...
Add request body related cURL options. @param RequestInterface $request Request on which to create options. @param array $curlOptions Options created by prepareRequestOptions(). @return array cURL options based on request.
[ "Add", "request", "body", "related", "cURL", "options", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/Client.php#L279-L323
php-http/curl-client
src/Client.php
Client.createHeaders
private function createHeaders(RequestInterface $request, array $curlOptions): array { $curlHeaders = []; $headers = $request->getHeaders(); foreach ($headers as $name => $values) { $header = strtolower($name); if ('expect' === $header) { // curl-client does not support "Expect-Continue", so dropping "expect" headers continue; } if ('content-length' === $header) { if (array_key_exists(CURLOPT_POSTFIELDS, $curlOptions)) { // Small body content length can be calculated here. $values = [strlen($curlOptions[CURLOPT_POSTFIELDS])]; } elseif (!array_key_exists(CURLOPT_READFUNCTION, $curlOptions)) { // Else if there is no body, forcing "Content-length" to 0 $values = [0]; } } foreach ($values as $value) { $curlHeaders[] = $name . ': ' . $value; } } /* * curl-client does not support "Expect-Continue", but cURL adds "Expect" header by default. * We can not suppress it, but we can set it to empty. */ $curlHeaders[] = 'Expect:'; return $curlHeaders; }
php
private function createHeaders(RequestInterface $request, array $curlOptions): array { $curlHeaders = []; $headers = $request->getHeaders(); foreach ($headers as $name => $values) { $header = strtolower($name); if ('expect' === $header) { // curl-client does not support "Expect-Continue", so dropping "expect" headers continue; } if ('content-length' === $header) { if (array_key_exists(CURLOPT_POSTFIELDS, $curlOptions)) { // Small body content length can be calculated here. $values = [strlen($curlOptions[CURLOPT_POSTFIELDS])]; } elseif (!array_key_exists(CURLOPT_READFUNCTION, $curlOptions)) { // Else if there is no body, forcing "Content-length" to 0 $values = [0]; } } foreach ($values as $value) { $curlHeaders[] = $name . ': ' . $value; } } /* * curl-client does not support "Expect-Continue", but cURL adds "Expect" header by default. * We can not suppress it, but we can set it to empty. */ $curlHeaders[] = 'Expect:'; return $curlHeaders; }
[ "private", "function", "createHeaders", "(", "RequestInterface", "$", "request", ",", "array", "$", "curlOptions", ")", ":", "array", "{", "$", "curlHeaders", "=", "[", "]", ";", "$", "headers", "=", "$", "request", "->", "getHeaders", "(", ")", ";", "fo...
Create headers array for CURLOPT_HTTPHEADER. @param RequestInterface $request Request on which to create headers. @param array $curlOptions Options created by prepareRequestOptions(). @return string[]
[ "Create", "headers", "array", "for", "CURLOPT_HTTPHEADER", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/Client.php#L333-L363
php-http/curl-client
src/Client.php
Client.sendAsyncRequest
public function sendAsyncRequest(RequestInterface $request) { if (!$this->multiRunner instanceof MultiRunner) { $this->multiRunner = new MultiRunner(); } $handle = curl_init(); $responseBuilder = $this->createResponseBuilder(); $requestOptions = $this->prepareRequestOptions($request, $responseBuilder); curl_setopt_array($handle, $requestOptions); $core = new PromiseCore($request, $handle, $responseBuilder); $promise = new CurlPromise($core, $this->multiRunner); $this->multiRunner->add($core); return $promise; }
php
public function sendAsyncRequest(RequestInterface $request) { if (!$this->multiRunner instanceof MultiRunner) { $this->multiRunner = new MultiRunner(); } $handle = curl_init(); $responseBuilder = $this->createResponseBuilder(); $requestOptions = $this->prepareRequestOptions($request, $responseBuilder); curl_setopt_array($handle, $requestOptions); $core = new PromiseCore($request, $handle, $responseBuilder); $promise = new CurlPromise($core, $this->multiRunner); $this->multiRunner->add($core); return $promise; }
[ "public", "function", "sendAsyncRequest", "(", "RequestInterface", "$", "request", ")", "{", "if", "(", "!", "$", "this", "->", "multiRunner", "instanceof", "MultiRunner", ")", "{", "$", "this", "->", "multiRunner", "=", "new", "MultiRunner", "(", ")", ";", ...
Sends a PSR-7 request in an asynchronous way. Exceptions related to processing the request are available from the returned Promise. @param RequestInterface $request @return Promise Resolves a PSR-7 Response or fails with an Http\Client\Exception. @throws \InvalidArgumentException For invalid header names or values. @throws \RuntimeException If creating the body stream fails. @throws Exception\RequestException On invalid request. @since 1.6 \UnexpectedValueException replaced with RequestException @since 1.0
[ "Sends", "a", "PSR", "-", "7", "request", "in", "an", "asynchronous", "way", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/Client.php#L381-L397
php-http/curl-client
src/MultiRunner.php
MultiRunner.add
public function add(PromiseCore $core): void { foreach ($this->cores as $existed) { if ($existed === $core) { return; } } $this->cores[] = $core; if (null === $this->multiHandle) { $this->multiHandle = curl_multi_init(); } curl_multi_add_handle($this->multiHandle, $core->getHandle()); }
php
public function add(PromiseCore $core): void { foreach ($this->cores as $existed) { if ($existed === $core) { return; } } $this->cores[] = $core; if (null === $this->multiHandle) { $this->multiHandle = curl_multi_init(); } curl_multi_add_handle($this->multiHandle, $core->getHandle()); }
[ "public", "function", "add", "(", "PromiseCore", "$", "core", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "cores", "as", "$", "existed", ")", "{", "if", "(", "$", "existed", "===", "$", "core", ")", "{", "return", ";", "}", "}", "$"...
Add promise to runner. @param PromiseCore $core
[ "Add", "promise", "to", "runner", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/MultiRunner.php#L46-L60
php-http/curl-client
src/MultiRunner.php
MultiRunner.remove
public function remove(PromiseCore $core): void { foreach ($this->cores as $index => $existed) { if ($existed === $core) { curl_multi_remove_handle($this->multiHandle, $core->getHandle()); unset($this->cores[$index]); return; } } }
php
public function remove(PromiseCore $core): void { foreach ($this->cores as $index => $existed) { if ($existed === $core) { curl_multi_remove_handle($this->multiHandle, $core->getHandle()); unset($this->cores[$index]); return; } } }
[ "public", "function", "remove", "(", "PromiseCore", "$", "core", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "cores", "as", "$", "index", "=>", "$", "existed", ")", "{", "if", "(", "$", "existed", "===", "$", "core", ")", "{", "curl_m...
Remove promise from runner. @param PromiseCore $core
[ "Remove", "promise", "from", "runner", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/MultiRunner.php#L67-L77
php-http/curl-client
src/MultiRunner.php
MultiRunner.wait
public function wait(PromiseCore $targetCore = null): void { do { $status = curl_multi_exec($this->multiHandle, $active); $info = curl_multi_info_read($this->multiHandle); if (false !== $info) { $core = $this->findCoreByHandle($info['handle']); if (null === $core) { // We have no promise for this handle. Drop it. curl_multi_remove_handle($this->multiHandle, $info['handle']); continue; } if (CURLE_OK === $info['result']) { $core->fulfill(); } else { $error = curl_error($core->getHandle()); $core->reject(new RequestException($error, $core->getRequest())); } $this->remove($core); // This is a promise we are waited for. So exiting wait(). if ($core === $targetCore) { return; } } } while ($status === CURLM_CALL_MULTI_PERFORM || $active); }
php
public function wait(PromiseCore $targetCore = null): void { do { $status = curl_multi_exec($this->multiHandle, $active); $info = curl_multi_info_read($this->multiHandle); if (false !== $info) { $core = $this->findCoreByHandle($info['handle']); if (null === $core) { // We have no promise for this handle. Drop it. curl_multi_remove_handle($this->multiHandle, $info['handle']); continue; } if (CURLE_OK === $info['result']) { $core->fulfill(); } else { $error = curl_error($core->getHandle()); $core->reject(new RequestException($error, $core->getRequest())); } $this->remove($core); // This is a promise we are waited for. So exiting wait(). if ($core === $targetCore) { return; } } } while ($status === CURLM_CALL_MULTI_PERFORM || $active); }
[ "public", "function", "wait", "(", "PromiseCore", "$", "targetCore", "=", "null", ")", ":", "void", "{", "do", "{", "$", "status", "=", "curl_multi_exec", "(", "$", "this", "->", "multiHandle", ",", "$", "active", ")", ";", "$", "info", "=", "curl_mult...
Wait for request(s) to be completed. @param PromiseCore|null $targetCore
[ "Wait", "for", "request", "(", "s", ")", "to", "be", "completed", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/MultiRunner.php#L84-L112
php-http/curl-client
src/MultiRunner.php
MultiRunner.findCoreByHandle
private function findCoreByHandle($handle): ?PromiseCore { foreach ($this->cores as $core) { if ($core->getHandle() === $handle) { return $core; } } return null; }
php
private function findCoreByHandle($handle): ?PromiseCore { foreach ($this->cores as $core) { if ($core->getHandle() === $handle) { return $core; } } return null; }
[ "private", "function", "findCoreByHandle", "(", "$", "handle", ")", ":", "?", "PromiseCore", "{", "foreach", "(", "$", "this", "->", "cores", "as", "$", "core", ")", "{", "if", "(", "$", "core", "->", "getHandle", "(", ")", "===", "$", "handle", ")",...
Find core by handle. @param resource $handle @return PromiseCore|null
[ "Find", "core", "by", "handle", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/MultiRunner.php#L121-L130
php-http/curl-client
src/PromiseCore.php
PromiseCore.addOnFulfilled
public function addOnFulfilled(callable $callback): void { if ($this->getState() === Promise::PENDING) { $this->onFulfilled[] = $callback; } elseif ($this->getState() === Promise::FULFILLED) { $response = call_user_func($callback, $this->responseBuilder->getResponse()); if ($response instanceof ResponseInterface) { $this->responseBuilder->setResponse($response); } } }
php
public function addOnFulfilled(callable $callback): void { if ($this->getState() === Promise::PENDING) { $this->onFulfilled[] = $callback; } elseif ($this->getState() === Promise::FULFILLED) { $response = call_user_func($callback, $this->responseBuilder->getResponse()); if ($response instanceof ResponseInterface) { $this->responseBuilder->setResponse($response); } } }
[ "public", "function", "addOnFulfilled", "(", "callable", "$", "callback", ")", ":", "void", "{", "if", "(", "$", "this", "->", "getState", "(", ")", "===", "Promise", "::", "PENDING", ")", "{", "$", "this", "->", "onFulfilled", "[", "]", "=", "$", "c...
Add on fulfilled callback. @param callable $callback
[ "Add", "on", "fulfilled", "callback", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/PromiseCore.php#L112-L122
php-http/curl-client
src/PromiseCore.php
PromiseCore.addOnRejected
public function addOnRejected(callable $callback): void { if ($this->getState() === Promise::PENDING) { $this->onRejected[] = $callback; } elseif ($this->getState() === Promise::REJECTED) { $this->exception = call_user_func($callback, $this->exception); } }
php
public function addOnRejected(callable $callback): void { if ($this->getState() === Promise::PENDING) { $this->onRejected[] = $callback; } elseif ($this->getState() === Promise::REJECTED) { $this->exception = call_user_func($callback, $this->exception); } }
[ "public", "function", "addOnRejected", "(", "callable", "$", "callback", ")", ":", "void", "{", "if", "(", "$", "this", "->", "getState", "(", ")", "===", "Promise", "::", "PENDING", ")", "{", "$", "this", "->", "onRejected", "[", "]", "=", "$", "cal...
Add on rejected callback. @param callable $callback
[ "Add", "on", "rejected", "callback", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/PromiseCore.php#L129-L136
php-http/curl-client
src/PromiseCore.php
PromiseCore.fulfill
public function fulfill(): void { $this->state = Promise::FULFILLED; $response = $this->responseBuilder->getResponse(); try { $response->getBody()->seek(0); } catch (\RuntimeException $e) { $exception = new Exception\TransferException($e->getMessage(), $e->getCode(), $e); $this->reject($exception); return; } while (count($this->onFulfilled) > 0) { $callback = array_shift($this->onFulfilled); $response = call_user_func($callback, $response); } if ($response instanceof ResponseInterface) { $this->responseBuilder->setResponse($response); } }
php
public function fulfill(): void { $this->state = Promise::FULFILLED; $response = $this->responseBuilder->getResponse(); try { $response->getBody()->seek(0); } catch (\RuntimeException $e) { $exception = new Exception\TransferException($e->getMessage(), $e->getCode(), $e); $this->reject($exception); return; } while (count($this->onFulfilled) > 0) { $callback = array_shift($this->onFulfilled); $response = call_user_func($callback, $response); } if ($response instanceof ResponseInterface) { $this->responseBuilder->setResponse($response); } }
[ "public", "function", "fulfill", "(", ")", ":", "void", "{", "$", "this", "->", "state", "=", "Promise", "::", "FULFILLED", ";", "$", "response", "=", "$", "this", "->", "responseBuilder", "->", "getResponse", "(", ")", ";", "try", "{", "$", "response"...
Fulfill promise.
[ "Fulfill", "promise", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/PromiseCore.php#L200-L221
php-http/curl-client
src/PromiseCore.php
PromiseCore.reject
public function reject(Exception $exception): void { $this->exception = $exception; $this->state = Promise::REJECTED; while (count($this->onRejected) > 0) { $callback = array_shift($this->onRejected); try { $exception = call_user_func($callback, $this->exception); $this->exception = $exception; } catch (Exception $exception) { $this->exception = $exception; } } }
php
public function reject(Exception $exception): void { $this->exception = $exception; $this->state = Promise::REJECTED; while (count($this->onRejected) > 0) { $callback = array_shift($this->onRejected); try { $exception = call_user_func($callback, $this->exception); $this->exception = $exception; } catch (Exception $exception) { $this->exception = $exception; } } }
[ "public", "function", "reject", "(", "Exception", "$", "exception", ")", ":", "void", "{", "$", "this", "->", "exception", "=", "$", "exception", ";", "$", "this", "->", "state", "=", "Promise", "::", "REJECTED", ";", "while", "(", "count", "(", "$", ...
Reject promise. @param Exception $exception Reject reason
[ "Reject", "promise", "." ]
train
https://github.com/php-http/curl-client/blob/d02343021dacbaf54cecd4e9a9181dbf6d9927f1/src/PromiseCore.php#L228-L242
guzzle/RingPHP
src/Client/StreamHandler.php
StreamHandler.drain
private function drain($stream, $dest) { if (is_resource($stream)) { if (!is_resource($dest)) { $stream = Stream::factory($stream); } else { stream_copy_to_stream($stream, $dest); fclose($stream); rewind($dest); return $dest; } } // Stream the response into the destination stream $dest = is_string($dest) ? new Stream(Utils::open($dest, 'r+')) : Stream::factory($dest); Utils::copyToStream($stream, $dest); $dest->seek(0); $stream->close(); return $dest; }
php
private function drain($stream, $dest) { if (is_resource($stream)) { if (!is_resource($dest)) { $stream = Stream::factory($stream); } else { stream_copy_to_stream($stream, $dest); fclose($stream); rewind($dest); return $dest; } } // Stream the response into the destination stream $dest = is_string($dest) ? new Stream(Utils::open($dest, 'r+')) : Stream::factory($dest); Utils::copyToStream($stream, $dest); $dest->seek(0); $stream->close(); return $dest; }
[ "private", "function", "drain", "(", "$", "stream", ",", "$", "dest", ")", "{", "if", "(", "is_resource", "(", "$", "stream", ")", ")", "{", "if", "(", "!", "is_resource", "(", "$", "dest", ")", ")", "{", "$", "stream", "=", "Stream", "::", "fact...
Drains the stream into the "save_to" client option. @param resource $stream @param string|resource|StreamInterface $dest @return Stream @throws \RuntimeException when the save_to option is invalid.
[ "Drains", "the", "stream", "into", "the", "save_to", "client", "option", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/StreamHandler.php#L93-L116
guzzle/RingPHP
src/Client/StreamHandler.php
StreamHandler.createErrorResponse
private function createErrorResponse($url, RingException $e) { // Determine if the error was a networking error. $message = $e->getMessage(); // This list can probably get more comprehensive. if (strpos($message, 'getaddrinfo') // DNS lookup failed || strpos($message, 'Connection refused') ) { $e = new ConnectException($e->getMessage(), 0, $e); } return new CompletedFutureArray([ 'status' => null, 'body' => null, 'headers' => [], 'effective_url' => $url, 'error' => $e ]); }
php
private function createErrorResponse($url, RingException $e) { // Determine if the error was a networking error. $message = $e->getMessage(); // This list can probably get more comprehensive. if (strpos($message, 'getaddrinfo') // DNS lookup failed || strpos($message, 'Connection refused') ) { $e = new ConnectException($e->getMessage(), 0, $e); } return new CompletedFutureArray([ 'status' => null, 'body' => null, 'headers' => [], 'effective_url' => $url, 'error' => $e ]); }
[ "private", "function", "createErrorResponse", "(", "$", "url", ",", "RingException", "$", "e", ")", "{", "// Determine if the error was a networking error.", "$", "message", "=", "$", "e", "->", "getMessage", "(", ")", ";", "// This list can probably get more comprehens...
Creates an error response for the given stream. @param string $url @param RingException $e @return array
[ "Creates", "an", "error", "response", "for", "the", "given", "stream", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/StreamHandler.php#L126-L145
guzzle/RingPHP
src/Client/CurlFactory.php
CurlFactory.createResponse
public static function createResponse( callable $handler, array $request, array $response, array $headers, $body ) { if (isset($response['transfer_stats']['url'])) { $response['effective_url'] = $response['transfer_stats']['url']; } if (!empty($headers)) { $startLine = explode(' ', array_shift($headers), 3); $headerList = Core::headersFromLines($headers); $response['headers'] = $headerList; $response['version'] = isset($startLine[0]) ? substr($startLine[0], 5) : null; $response['status'] = isset($startLine[1]) ? (int) $startLine[1] : null; $response['reason'] = isset($startLine[2]) ? $startLine[2] : null; $response['body'] = $body; Core::rewindBody($response); } return !empty($response['curl']['errno']) || !isset($response['status']) ? self::createErrorResponse($handler, $request, $response) : $response; }
php
public static function createResponse( callable $handler, array $request, array $response, array $headers, $body ) { if (isset($response['transfer_stats']['url'])) { $response['effective_url'] = $response['transfer_stats']['url']; } if (!empty($headers)) { $startLine = explode(' ', array_shift($headers), 3); $headerList = Core::headersFromLines($headers); $response['headers'] = $headerList; $response['version'] = isset($startLine[0]) ? substr($startLine[0], 5) : null; $response['status'] = isset($startLine[1]) ? (int) $startLine[1] : null; $response['reason'] = isset($startLine[2]) ? $startLine[2] : null; $response['body'] = $body; Core::rewindBody($response); } return !empty($response['curl']['errno']) || !isset($response['status']) ? self::createErrorResponse($handler, $request, $response) : $response; }
[ "public", "static", "function", "createResponse", "(", "callable", "$", "handler", ",", "array", "$", "request", ",", "array", "$", "response", ",", "array", "$", "headers", ",", "$", "body", ")", "{", "if", "(", "isset", "(", "$", "response", "[", "'t...
Creates a response hash from a cURL result. @param callable $handler Handler that was used. @param array $request Request that sent. @param array $response Response hash to update. @param array $headers Headers received during transfer. @param resource $body Body fopen response. @return array
[ "Creates", "a", "response", "hash", "from", "a", "cURL", "result", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/CurlFactory.php#L68-L93
guzzle/RingPHP
src/Client/CurlFactory.php
CurlFactory.applyCustomCurlOptions
private function applyCustomCurlOptions(array $config, array $options) { $curlOptions = []; foreach ($config as $key => $value) { if (is_int($key)) { $curlOptions[$key] = $value; } } return $curlOptions + $options; }
php
private function applyCustomCurlOptions(array $config, array $options) { $curlOptions = []; foreach ($config as $key => $value) { if (is_int($key)) { $curlOptions[$key] = $value; } } return $curlOptions + $options; }
[ "private", "function", "applyCustomCurlOptions", "(", "array", "$", "config", ",", "array", "$", "options", ")", "{", "$", "curlOptions", "=", "[", "]", ";", "foreach", "(", "$", "config", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "i...
Takes an array of curl options specified in the 'curl' option of a request's configuration array and maps them to CURLOPT_* options. This method is only called when a request has a 'curl' config setting. @param array $config Configuration array of custom curl option @param array $options Array of existing curl options @return array Returns a new array of curl options
[ "Takes", "an", "array", "of", "curl", "options", "specified", "in", "the", "curl", "option", "of", "a", "request", "s", "configuration", "array", "and", "maps", "them", "to", "CURLOPT_", "*", "options", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/CurlFactory.php#L318-L328
guzzle/RingPHP
src/Client/CurlFactory.php
CurlFactory.applyHandlerOptions
private function applyHandlerOptions(array $request, array &$options) { foreach ($request['client'] as $key => $value) { switch ($key) { // Violating PSR-4 to provide more room. case 'verify': if ($value === false) { unset($options[CURLOPT_CAINFO]); $options[CURLOPT_SSL_VERIFYHOST] = 0; $options[CURLOPT_SSL_VERIFYPEER] = false; continue 2; } $options[CURLOPT_SSL_VERIFYHOST] = 2; $options[CURLOPT_SSL_VERIFYPEER] = true; if (is_string($value)) { $options[CURLOPT_CAINFO] = $value; if (!file_exists($value)) { throw new \InvalidArgumentException( "SSL CA bundle not found: $value" ); } } break; case 'decode_content': if ($value === false) { continue 2; } $accept = Core::firstHeader($request, 'Accept-Encoding'); if ($accept) { $options[CURLOPT_ENCODING] = $accept; } else { $options[CURLOPT_ENCODING] = ''; // Don't let curl send the header over the wire $options[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; } break; case 'save_to': if (is_string($value)) { if (!is_dir(dirname($value))) { throw new \RuntimeException(sprintf( 'Directory %s does not exist for save_to value of %s', dirname($value), $value )); } $value = new LazyOpenStream($value, 'w+'); } if ($value instanceof StreamInterface) { $options[CURLOPT_WRITEFUNCTION] = function ($ch, $write) use ($value) { return $value->write($write); }; } elseif (is_resource($value)) { $options[CURLOPT_FILE] = $value; } else { throw new \InvalidArgumentException('save_to must be a ' . 'GuzzleHttp\Stream\StreamInterface or resource'); } break; case 'timeout': if (defined('CURLOPT_TIMEOUT_MS')) { $options[CURLOPT_TIMEOUT_MS] = $value * 1000; } else { $options[CURLOPT_TIMEOUT] = $value; } break; case 'connect_timeout': if (defined('CURLOPT_CONNECTTIMEOUT_MS')) { $options[CURLOPT_CONNECTTIMEOUT_MS] = $value * 1000; } else { $options[CURLOPT_CONNECTTIMEOUT] = $value; } break; case 'proxy': if (!is_array($value)) { $options[CURLOPT_PROXY] = $value; } elseif (isset($request['scheme'])) { $scheme = $request['scheme']; if (isset($value[$scheme])) { $options[CURLOPT_PROXY] = $value[$scheme]; } } break; case 'cert': if (is_array($value)) { $options[CURLOPT_SSLCERTPASSWD] = $value[1]; $value = $value[0]; } if (!file_exists($value)) { throw new \InvalidArgumentException( "SSL certificate not found: {$value}" ); } $options[CURLOPT_SSLCERT] = $value; break; case 'ssl_key': if (is_array($value)) { $options[CURLOPT_SSLKEYPASSWD] = $value[1]; $value = $value[0]; } if (!file_exists($value)) { throw new \InvalidArgumentException( "SSL private key not found: {$value}" ); } $options[CURLOPT_SSLKEY] = $value; break; case 'progress': if (!is_callable($value)) { throw new \InvalidArgumentException( 'progress client option must be callable' ); } $options[CURLOPT_NOPROGRESS] = false; $options[CURLOPT_PROGRESSFUNCTION] = function () use ($value) { $args = func_get_args(); // PHP 5.5 pushed the handle onto the start of the args if (is_resource($args[0])) { array_shift($args); } call_user_func_array($value, $args); }; break; case 'debug': if ($value) { $options[CURLOPT_STDERR] = Core::getDebugResource($value); $options[CURLOPT_VERBOSE] = true; } break; } } }
php
private function applyHandlerOptions(array $request, array &$options) { foreach ($request['client'] as $key => $value) { switch ($key) { // Violating PSR-4 to provide more room. case 'verify': if ($value === false) { unset($options[CURLOPT_CAINFO]); $options[CURLOPT_SSL_VERIFYHOST] = 0; $options[CURLOPT_SSL_VERIFYPEER] = false; continue 2; } $options[CURLOPT_SSL_VERIFYHOST] = 2; $options[CURLOPT_SSL_VERIFYPEER] = true; if (is_string($value)) { $options[CURLOPT_CAINFO] = $value; if (!file_exists($value)) { throw new \InvalidArgumentException( "SSL CA bundle not found: $value" ); } } break; case 'decode_content': if ($value === false) { continue 2; } $accept = Core::firstHeader($request, 'Accept-Encoding'); if ($accept) { $options[CURLOPT_ENCODING] = $accept; } else { $options[CURLOPT_ENCODING] = ''; // Don't let curl send the header over the wire $options[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; } break; case 'save_to': if (is_string($value)) { if (!is_dir(dirname($value))) { throw new \RuntimeException(sprintf( 'Directory %s does not exist for save_to value of %s', dirname($value), $value )); } $value = new LazyOpenStream($value, 'w+'); } if ($value instanceof StreamInterface) { $options[CURLOPT_WRITEFUNCTION] = function ($ch, $write) use ($value) { return $value->write($write); }; } elseif (is_resource($value)) { $options[CURLOPT_FILE] = $value; } else { throw new \InvalidArgumentException('save_to must be a ' . 'GuzzleHttp\Stream\StreamInterface or resource'); } break; case 'timeout': if (defined('CURLOPT_TIMEOUT_MS')) { $options[CURLOPT_TIMEOUT_MS] = $value * 1000; } else { $options[CURLOPT_TIMEOUT] = $value; } break; case 'connect_timeout': if (defined('CURLOPT_CONNECTTIMEOUT_MS')) { $options[CURLOPT_CONNECTTIMEOUT_MS] = $value * 1000; } else { $options[CURLOPT_CONNECTTIMEOUT] = $value; } break; case 'proxy': if (!is_array($value)) { $options[CURLOPT_PROXY] = $value; } elseif (isset($request['scheme'])) { $scheme = $request['scheme']; if (isset($value[$scheme])) { $options[CURLOPT_PROXY] = $value[$scheme]; } } break; case 'cert': if (is_array($value)) { $options[CURLOPT_SSLCERTPASSWD] = $value[1]; $value = $value[0]; } if (!file_exists($value)) { throw new \InvalidArgumentException( "SSL certificate not found: {$value}" ); } $options[CURLOPT_SSLCERT] = $value; break; case 'ssl_key': if (is_array($value)) { $options[CURLOPT_SSLKEYPASSWD] = $value[1]; $value = $value[0]; } if (!file_exists($value)) { throw new \InvalidArgumentException( "SSL private key not found: {$value}" ); } $options[CURLOPT_SSLKEY] = $value; break; case 'progress': if (!is_callable($value)) { throw new \InvalidArgumentException( 'progress client option must be callable' ); } $options[CURLOPT_NOPROGRESS] = false; $options[CURLOPT_PROGRESSFUNCTION] = function () use ($value) { $args = func_get_args(); // PHP 5.5 pushed the handle onto the start of the args if (is_resource($args[0])) { array_shift($args); } call_user_func_array($value, $args); }; break; case 'debug': if ($value) { $options[CURLOPT_STDERR] = Core::getDebugResource($value); $options[CURLOPT_VERBOSE] = true; } break; } } }
[ "private", "function", "applyHandlerOptions", "(", "array", "$", "request", ",", "array", "&", "$", "options", ")", "{", "foreach", "(", "$", "request", "[", "'client'", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "switch", "(", "$", "key", ...
Applies an array of request client options to a the options array. This method uses a large switch rather than double-dispatch to save on high overhead of calling functions in PHP.
[ "Applies", "an", "array", "of", "request", "client", "options", "to", "a", "the", "options", "array", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/CurlFactory.php#L352-L512
guzzle/RingPHP
src/Client/CurlFactory.php
CurlFactory.retryFailedRewind
private static function retryFailedRewind( callable $handler, array $request, array $response ) { // If there is no body, then there is some other kind of issue. This // is weird and should probably never happen. if (!isset($request['body'])) { $response['err_message'] = 'No response was received for a request ' . 'with no body. This could mean that you are saturating your ' . 'network.'; return self::createErrorResponse($handler, $request, $response); } if (!Core::rewindBody($request)) { $response['err_message'] = 'The connection unexpectedly failed ' . 'without providing an error. The request would have been ' . 'retried, but attempting to rewind the request body failed.'; return self::createErrorResponse($handler, $request, $response); } // Retry no more than 3 times before giving up. if (!isset($request['curl']['retries'])) { $request['curl']['retries'] = 1; } elseif ($request['curl']['retries'] == 2) { $response['err_message'] = 'The cURL request was retried 3 times ' . 'and did no succeed. cURL was unable to rewind the body of ' . 'the request and subsequent retries resulted in the same ' . 'error. Turn on the debug option to see what went wrong. ' . 'See https://bugs.php.net/bug.php?id=47204 for more information.'; return self::createErrorResponse($handler, $request, $response); } else { $request['curl']['retries']++; } return $handler($request); }
php
private static function retryFailedRewind( callable $handler, array $request, array $response ) { // If there is no body, then there is some other kind of issue. This // is weird and should probably never happen. if (!isset($request['body'])) { $response['err_message'] = 'No response was received for a request ' . 'with no body. This could mean that you are saturating your ' . 'network.'; return self::createErrorResponse($handler, $request, $response); } if (!Core::rewindBody($request)) { $response['err_message'] = 'The connection unexpectedly failed ' . 'without providing an error. The request would have been ' . 'retried, but attempting to rewind the request body failed.'; return self::createErrorResponse($handler, $request, $response); } // Retry no more than 3 times before giving up. if (!isset($request['curl']['retries'])) { $request['curl']['retries'] = 1; } elseif ($request['curl']['retries'] == 2) { $response['err_message'] = 'The cURL request was retried 3 times ' . 'and did no succeed. cURL was unable to rewind the body of ' . 'the request and subsequent retries resulted in the same ' . 'error. Turn on the debug option to see what went wrong. ' . 'See https://bugs.php.net/bug.php?id=47204 for more information.'; return self::createErrorResponse($handler, $request, $response); } else { $request['curl']['retries']++; } return $handler($request); }
[ "private", "static", "function", "retryFailedRewind", "(", "callable", "$", "handler", ",", "array", "$", "request", ",", "array", "$", "response", ")", "{", "// If there is no body, then there is some other kind of issue. This", "// is weird and should probably never happen.",...
This function ensures that a response was set on a transaction. If one was not set, then the request is retried if possible. This error typically means you are sending a payload, curl encountered a "Connection died, retrying a fresh connect" error, tried to rewind the stream, and then encountered a "necessary data rewind wasn't possible" error, causing the request to be sent through curl_multi_info_read() without an error status.
[ "This", "function", "ensures", "that", "a", "response", "was", "set", "on", "a", "transaction", ".", "If", "one", "was", "not", "set", "then", "the", "request", "is", "retried", "if", "possible", ".", "This", "error", "typically", "means", "you", "are", ...
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/CurlFactory.php#L523-L559
guzzle/RingPHP
src/Client/ClientUtils.php
ClientUtils.getDefaultCaBundle
public static function getDefaultCaBundle() { static $cached = null; static $cafiles = [ // Red Hat, CentOS, Fedora (provided by the ca-certificates package) '/etc/pki/tls/certs/ca-bundle.crt', // Ubuntu, Debian (provided by the ca-certificates package) '/etc/ssl/certs/ca-certificates.crt', // FreeBSD (provided by the ca_root_nss package) '/usr/local/share/certs/ca-root-nss.crt', // OS X provided by homebrew (using the default path) '/usr/local/etc/openssl/cert.pem', // Windows? 'C:\\windows\\system32\\curl-ca-bundle.crt', 'C:\\windows\\curl-ca-bundle.crt', ]; if ($cached) { return $cached; } if ($ca = ini_get('openssl.cafile')) { return $cached = $ca; } if ($ca = ini_get('curl.cainfo')) { return $cached = $ca; } foreach ($cafiles as $filename) { if (file_exists($filename)) { return $cached = $filename; } } throw new \RuntimeException(self::CA_ERR); }
php
public static function getDefaultCaBundle() { static $cached = null; static $cafiles = [ // Red Hat, CentOS, Fedora (provided by the ca-certificates package) '/etc/pki/tls/certs/ca-bundle.crt', // Ubuntu, Debian (provided by the ca-certificates package) '/etc/ssl/certs/ca-certificates.crt', // FreeBSD (provided by the ca_root_nss package) '/usr/local/share/certs/ca-root-nss.crt', // OS X provided by homebrew (using the default path) '/usr/local/etc/openssl/cert.pem', // Windows? 'C:\\windows\\system32\\curl-ca-bundle.crt', 'C:\\windows\\curl-ca-bundle.crt', ]; if ($cached) { return $cached; } if ($ca = ini_get('openssl.cafile')) { return $cached = $ca; } if ($ca = ini_get('curl.cainfo')) { return $cached = $ca; } foreach ($cafiles as $filename) { if (file_exists($filename)) { return $cached = $filename; } } throw new \RuntimeException(self::CA_ERR); }
[ "public", "static", "function", "getDefaultCaBundle", "(", ")", "{", "static", "$", "cached", "=", "null", ";", "static", "$", "cafiles", "=", "[", "// Red Hat, CentOS, Fedora (provided by the ca-certificates package)", "'/etc/pki/tls/certs/ca-bundle.crt'", ",", "// Ubuntu,...
Returns the default cacert bundle for the current system. First, the openssl.cafile and curl.cainfo php.ini settings are checked. If those settings are not configured, then the common locations for bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X and Windows are checked. If any of these file locations are found on disk, they will be utilized. Note: the result of this function is cached for subsequent calls. @return string @throws \RuntimeException if no bundle can be found.
[ "Returns", "the", "default", "cacert", "bundle", "for", "the", "current", "system", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/ClientUtils.php#L23-L59
guzzle/RingPHP
src/Client/CurlHandler.php
CurlHandler._invokeAsArray
public function _invokeAsArray(array $request) { $factory = $this->factory; // Ensure headers are by reference. They're updated elsewhere. $result = $factory($request, $this->checkoutEasyHandle()); $h = $result[0]; $hd =& $result[1]; $bd = $result[2]; Core::doSleep($request); curl_exec($h); $response = ['transfer_stats' => curl_getinfo($h)]; $response['curl']['error'] = curl_error($h); $response['curl']['errno'] = curl_errno($h); $response['transfer_stats'] = array_merge($response['transfer_stats'], $response['curl']); $this->releaseEasyHandle($h); return CurlFactory::createResponse([$this, '_invokeAsArray'], $request, $response, $hd, $bd); }
php
public function _invokeAsArray(array $request) { $factory = $this->factory; // Ensure headers are by reference. They're updated elsewhere. $result = $factory($request, $this->checkoutEasyHandle()); $h = $result[0]; $hd =& $result[1]; $bd = $result[2]; Core::doSleep($request); curl_exec($h); $response = ['transfer_stats' => curl_getinfo($h)]; $response['curl']['error'] = curl_error($h); $response['curl']['errno'] = curl_errno($h); $response['transfer_stats'] = array_merge($response['transfer_stats'], $response['curl']); $this->releaseEasyHandle($h); return CurlFactory::createResponse([$this, '_invokeAsArray'], $request, $response, $hd, $bd); }
[ "public", "function", "_invokeAsArray", "(", "array", "$", "request", ")", "{", "$", "factory", "=", "$", "this", "->", "factory", ";", "// Ensure headers are by reference. They're updated elsewhere.", "$", "result", "=", "$", "factory", "(", "$", "request", ",", ...
@internal @param array $request @return array
[ "@internal" ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/CurlHandler.php#L79-L97
guzzle/RingPHP
src/Core.php
Core.headerLines
public static function headerLines($message, $header) { $result = []; if (!empty($message['headers'])) { foreach ($message['headers'] as $name => $value) { if (!strcasecmp($name, $header)) { $result = array_merge($result, $value); } } } return $result; }
php
public static function headerLines($message, $header) { $result = []; if (!empty($message['headers'])) { foreach ($message['headers'] as $name => $value) { if (!strcasecmp($name, $header)) { $result = array_merge($result, $value); } } } return $result; }
[ "public", "static", "function", "headerLines", "(", "$", "message", ",", "$", "header", ")", "{", "$", "result", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "message", "[", "'headers'", "]", ")", ")", "{", "foreach", "(", "$", "message",...
Gets an array of header line values from a message for a specific header This method searches through the "headers" key of a message for a header using a case-insensitive search. @param array $message Request or response hash. @param string $header Header to retrieve @return array
[ "Gets", "an", "array", "of", "header", "line", "values", "from", "a", "message", "for", "a", "specific", "header" ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L42-L55
guzzle/RingPHP
src/Core.php
Core.header
public static function header($message, $header) { $match = self::headerLines($message, $header); return $match ? implode(', ', $match) : null; }
php
public static function header($message, $header) { $match = self::headerLines($message, $header); return $match ? implode(', ', $match) : null; }
[ "public", "static", "function", "header", "(", "$", "message", ",", "$", "header", ")", "{", "$", "match", "=", "self", "::", "headerLines", "(", "$", "message", ",", "$", "header", ")", ";", "return", "$", "match", "?", "implode", "(", "', '", ",", ...
Gets a header value from a message as a string or null This method searches through the "headers" key of a message for a header using a case-insensitive search. The lines of the header are imploded using commas into a single string return value. @param array $message Request or response hash. @param string $header Header to retrieve @return string|null Returns the header string if found, or null if not.
[ "Gets", "a", "header", "value", "from", "a", "message", "as", "a", "string", "or", "null" ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L69-L73
guzzle/RingPHP
src/Core.php
Core.firstHeader
public static function firstHeader($message, $header) { if (!empty($message['headers'])) { foreach ($message['headers'] as $name => $value) { if (!strcasecmp($name, $header)) { // Return the match itself if it is a single value. $pos = strpos($value[0], ','); return $pos ? substr($value[0], 0, $pos) : $value[0]; } } } return null; }
php
public static function firstHeader($message, $header) { if (!empty($message['headers'])) { foreach ($message['headers'] as $name => $value) { if (!strcasecmp($name, $header)) { // Return the match itself if it is a single value. $pos = strpos($value[0], ','); return $pos ? substr($value[0], 0, $pos) : $value[0]; } } } return null; }
[ "public", "static", "function", "firstHeader", "(", "$", "message", ",", "$", "header", ")", "{", "if", "(", "!", "empty", "(", "$", "message", "[", "'headers'", "]", ")", ")", "{", "foreach", "(", "$", "message", "[", "'headers'", "]", "as", "$", ...
Returns the first header value from a message as a string or null. If a header line contains multiple values separated by a comma, then this function will return the first value in the list. @param array $message Request or response hash. @param string $header Header to retrieve @return string|null Returns the value as a string if found.
[ "Returns", "the", "first", "header", "value", "from", "a", "message", "as", "a", "string", "or", "null", ".", "If", "a", "header", "line", "contains", "multiple", "values", "separated", "by", "a", "comma", "then", "this", "function", "will", "return", "the...
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L85-L98
guzzle/RingPHP
src/Core.php
Core.hasHeader
public static function hasHeader($message, $header) { if (!empty($message['headers'])) { foreach ($message['headers'] as $name => $value) { if (!strcasecmp($name, $header)) { return true; } } } return false; }
php
public static function hasHeader($message, $header) { if (!empty($message['headers'])) { foreach ($message['headers'] as $name => $value) { if (!strcasecmp($name, $header)) { return true; } } } return false; }
[ "public", "static", "function", "hasHeader", "(", "$", "message", ",", "$", "header", ")", "{", "if", "(", "!", "empty", "(", "$", "message", "[", "'headers'", "]", ")", ")", "{", "foreach", "(", "$", "message", "[", "'headers'", "]", "as", "$", "n...
Returns true if a message has the provided case-insensitive header. @param array $message Request or response hash. @param string $header Header to check @return bool
[ "Returns", "true", "if", "a", "message", "has", "the", "provided", "case", "-", "insensitive", "header", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L108-L119
guzzle/RingPHP
src/Core.php
Core.headersFromLines
public static function headersFromLines($lines) { $headers = []; foreach ($lines as $line) { $parts = explode(':', $line, 2); $headers[trim($parts[0])][] = isset($parts[1]) ? trim($parts[1]) : null; } return $headers; }
php
public static function headersFromLines($lines) { $headers = []; foreach ($lines as $line) { $parts = explode(':', $line, 2); $headers[trim($parts[0])][] = isset($parts[1]) ? trim($parts[1]) : null; } return $headers; }
[ "public", "static", "function", "headersFromLines", "(", "$", "lines", ")", "{", "$", "headers", "=", "[", "]", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "$", "parts", "=", "explode", "(", "':'", ",", "$", "line", ",", "2", ...
Parses an array of header lines into an associative array of headers. @param array $lines Header lines array of strings in the following format: "Name: Value" @return array
[ "Parses", "an", "array", "of", "header", "lines", "into", "an", "associative", "array", "of", "headers", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L128-L140
guzzle/RingPHP
src/Core.php
Core.removeHeader
public static function removeHeader(array $message, $header) { if (isset($message['headers'])) { foreach (array_keys($message['headers']) as $key) { if (!strcasecmp($header, $key)) { unset($message['headers'][$key]); } } } return $message; }
php
public static function removeHeader(array $message, $header) { if (isset($message['headers'])) { foreach (array_keys($message['headers']) as $key) { if (!strcasecmp($header, $key)) { unset($message['headers'][$key]); } } } return $message; }
[ "public", "static", "function", "removeHeader", "(", "array", "$", "message", ",", "$", "header", ")", "{", "if", "(", "isset", "(", "$", "message", "[", "'headers'", "]", ")", ")", "{", "foreach", "(", "array_keys", "(", "$", "message", "[", "'headers...
Removes a header from a message using a case-insensitive comparison. @param array $message Message that contains 'headers' @param string $header Header to remove @return array
[ "Removes", "a", "header", "from", "a", "message", "using", "a", "case", "-", "insensitive", "comparison", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L150-L161
guzzle/RingPHP
src/Core.php
Core.setHeader
public static function setHeader(array $message, $header, array $value) { $message = self::removeHeader($message, $header); $message['headers'][$header] = $value; return $message; }
php
public static function setHeader(array $message, $header, array $value) { $message = self::removeHeader($message, $header); $message['headers'][$header] = $value; return $message; }
[ "public", "static", "function", "setHeader", "(", "array", "$", "message", ",", "$", "header", ",", "array", "$", "value", ")", "{", "$", "message", "=", "self", "::", "removeHeader", "(", "$", "message", ",", "$", "header", ")", ";", "$", "message", ...
Replaces any existing case insensitive headers with the given value. @param array $message Message that contains 'headers' @param string $header Header to set. @param array $value Value to set. @return array
[ "Replaces", "any", "existing", "case", "insensitive", "headers", "with", "the", "given", "value", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L172-L178
guzzle/RingPHP
src/Core.php
Core.url
public static function url(array $request) { if (isset($request['url'])) { return $request['url']; } $uri = (isset($request['scheme']) ? $request['scheme'] : 'http') . '://'; if ($host = self::header($request, 'host')) { $uri .= $host; } else { throw new \InvalidArgumentException('No Host header was provided'); } if (isset($request['uri'])) { $uri .= $request['uri']; } if (isset($request['query_string'])) { $uri .= '?' . $request['query_string']; } return $uri; }
php
public static function url(array $request) { if (isset($request['url'])) { return $request['url']; } $uri = (isset($request['scheme']) ? $request['scheme'] : 'http') . '://'; if ($host = self::header($request, 'host')) { $uri .= $host; } else { throw new \InvalidArgumentException('No Host header was provided'); } if (isset($request['uri'])) { $uri .= $request['uri']; } if (isset($request['query_string'])) { $uri .= '?' . $request['query_string']; } return $uri; }
[ "public", "static", "function", "url", "(", "array", "$", "request", ")", "{", "if", "(", "isset", "(", "$", "request", "[", "'url'", "]", ")", ")", "{", "return", "$", "request", "[", "'url'", "]", ";", "}", "$", "uri", "=", "(", "isset", "(", ...
Creates a URL string from a request. If the "url" key is present on the request, it is returned, otherwise the url is built up based on the scheme, host, uri, and query_string request values. @param array $request Request to get the URL from @return string Returns the request URL as a string. @throws \InvalidArgumentException if no Host header is present.
[ "Creates", "a", "URL", "string", "from", "a", "request", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L192-L216
guzzle/RingPHP
src/Core.php
Core.body
public static function body($message) { if (!isset($message['body'])) { return null; } if ($message['body'] instanceof StreamInterface) { return (string) $message['body']; } switch (gettype($message['body'])) { case 'string': return $message['body']; case 'resource': return stream_get_contents($message['body']); case 'object': if ($message['body'] instanceof \Iterator) { return implode('', iterator_to_array($message['body'])); } elseif (method_exists($message['body'], '__toString')) { return (string) $message['body']; } default: throw new \InvalidArgumentException('Invalid request body: ' . self::describeType($message['body'])); } }
php
public static function body($message) { if (!isset($message['body'])) { return null; } if ($message['body'] instanceof StreamInterface) { return (string) $message['body']; } switch (gettype($message['body'])) { case 'string': return $message['body']; case 'resource': return stream_get_contents($message['body']); case 'object': if ($message['body'] instanceof \Iterator) { return implode('', iterator_to_array($message['body'])); } elseif (method_exists($message['body'], '__toString')) { return (string) $message['body']; } default: throw new \InvalidArgumentException('Invalid request body: ' . self::describeType($message['body'])); } }
[ "public", "static", "function", "body", "(", "$", "message", ")", "{", "if", "(", "!", "isset", "(", "$", "message", "[", "'body'", "]", ")", ")", "{", "return", "null", ";", "}", "if", "(", "$", "message", "[", "'body'", "]", "instanceof", "Stream...
Reads the body of a message into a string. @param array|FutureArrayInterface $message Array containing a "body" key @return null|string Returns the body as a string or null if not set. @throws \InvalidArgumentException if a request body is invalid.
[ "Reads", "the", "body", "of", "a", "message", "into", "a", "string", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L226-L251
guzzle/RingPHP
src/Core.php
Core.rewindBody
public static function rewindBody($message) { if ($message['body'] instanceof StreamInterface) { return $message['body']->seek(0); } if ($message['body'] instanceof \Generator) { return false; } if ($message['body'] instanceof \Iterator) { $message['body']->rewind(); return true; } if (is_resource($message['body'])) { return rewind($message['body']); } return is_string($message['body']) || (is_object($message['body']) && method_exists($message['body'], '__toString')); }
php
public static function rewindBody($message) { if ($message['body'] instanceof StreamInterface) { return $message['body']->seek(0); } if ($message['body'] instanceof \Generator) { return false; } if ($message['body'] instanceof \Iterator) { $message['body']->rewind(); return true; } if (is_resource($message['body'])) { return rewind($message['body']); } return is_string($message['body']) || (is_object($message['body']) && method_exists($message['body'], '__toString')); }
[ "public", "static", "function", "rewindBody", "(", "$", "message", ")", "{", "if", "(", "$", "message", "[", "'body'", "]", "instanceof", "StreamInterface", ")", "{", "return", "$", "message", "[", "'body'", "]", "->", "seek", "(", "0", ")", ";", "}", ...
Rewind the body of the provided message if possible. @param array $message Message that contains a 'body' field. @return bool Returns true on success, false on failure
[ "Rewind", "the", "body", "of", "the", "provided", "message", "if", "possible", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L260-L282
guzzle/RingPHP
src/Core.php
Core.describeType
public static function describeType($input) { switch (gettype($input)) { case 'object': return 'object(' . get_class($input) . ')'; case 'array': return 'array(' . count($input) . ')'; default: ob_start(); var_dump($input); // normalize float vs double return str_replace('double(', 'float(', rtrim(ob_get_clean())); } }
php
public static function describeType($input) { switch (gettype($input)) { case 'object': return 'object(' . get_class($input) . ')'; case 'array': return 'array(' . count($input) . ')'; default: ob_start(); var_dump($input); // normalize float vs double return str_replace('double(', 'float(', rtrim(ob_get_clean())); } }
[ "public", "static", "function", "describeType", "(", "$", "input", ")", "{", "switch", "(", "gettype", "(", "$", "input", ")", ")", "{", "case", "'object'", ":", "return", "'object('", ".", "get_class", "(", "$", "input", ")", ".", "')'", ";", "case", ...
Debug function used to describe the provided value type and class. @param mixed $input @return string Returns a string containing the type of the variable and if a class is provided, the class name.
[ "Debug", "function", "used", "to", "describe", "the", "provided", "value", "type", "and", "class", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L292-L305
guzzle/RingPHP
src/Core.php
Core.proxy
public static function proxy( FutureArrayInterface $future, callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null ) { return new FutureArray( $future->then($onFulfilled, $onRejected, $onProgress), [$future, 'wait'], [$future, 'cancel'] ); }
php
public static function proxy( FutureArrayInterface $future, callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null ) { return new FutureArray( $future->then($onFulfilled, $onRejected, $onProgress), [$future, 'wait'], [$future, 'cancel'] ); }
[ "public", "static", "function", "proxy", "(", "FutureArrayInterface", "$", "future", ",", "callable", "$", "onFulfilled", "=", "null", ",", "callable", "$", "onRejected", "=", "null", ",", "callable", "$", "onProgress", "=", "null", ")", "{", "return", "new"...
Returns a proxied future that modifies the dereferenced value of another future using a promise. @param FutureArrayInterface $future Future to wrap with a new future @param callable $onFulfilled Invoked when the future fulfilled @param callable $onRejected Invoked when the future rejected @param callable $onProgress Invoked when the future progresses @return FutureArray
[ "Returns", "a", "proxied", "future", "that", "modifies", "the", "dereferenced", "value", "of", "another", "future", "using", "a", "promise", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Core.php#L334-L345
guzzle/RingPHP
src/Client/CurlMultiHandler.php
CurlMultiHandler.execute
public function execute() { do { if ($this->active && curl_multi_select($this->_mh, $this->selectTimeout) === -1 ) { // Perform a usleep if a select returns -1. // See: https://bugs.php.net/bug.php?id=61141 usleep(250); } // Add any delayed futures if needed. if ($this->delays) { $this->addDelays(); } do { $mrc = curl_multi_exec($this->_mh, $this->active); } while ($mrc === CURLM_CALL_MULTI_PERFORM); $this->processMessages(); // If there are delays but no transfers, then sleep for a bit. if (!$this->active && $this->delays) { usleep(500); } } while ($this->active || $this->handles); }
php
public function execute() { do { if ($this->active && curl_multi_select($this->_mh, $this->selectTimeout) === -1 ) { // Perform a usleep if a select returns -1. // See: https://bugs.php.net/bug.php?id=61141 usleep(250); } // Add any delayed futures if needed. if ($this->delays) { $this->addDelays(); } do { $mrc = curl_multi_exec($this->_mh, $this->active); } while ($mrc === CURLM_CALL_MULTI_PERFORM); $this->processMessages(); // If there are delays but no transfers, then sleep for a bit. if (!$this->active && $this->delays) { usleep(500); } } while ($this->active || $this->handles); }
[ "public", "function", "execute", "(", ")", "{", "do", "{", "if", "(", "$", "this", "->", "active", "&&", "curl_multi_select", "(", "$", "this", "->", "_mh", ",", "$", "this", "->", "selectTimeout", ")", "===", "-", "1", ")", "{", "// Perform a usleep i...
Runs until all outstanding connections have completed.
[ "Runs", "until", "all", "outstanding", "connections", "have", "completed", "." ]
train
https://github.com/guzzle/RingPHP/blob/5e2a174052995663dd68e6b5ad838afd47dd615b/src/Client/CurlMultiHandler.php#L115-L144
php-http/promise
src/FulfilledPromise.php
FulfilledPromise.then
public function then(callable $onFulfilled = null, callable $onRejected = null) { if (null === $onFulfilled) { return $this; } try { return new self($onFulfilled($this->result)); } catch (\Exception $e) { return new RejectedPromise($e); } }
php
public function then(callable $onFulfilled = null, callable $onRejected = null) { if (null === $onFulfilled) { return $this; } try { return new self($onFulfilled($this->result)); } catch (\Exception $e) { return new RejectedPromise($e); } }
[ "public", "function", "then", "(", "callable", "$", "onFulfilled", "=", "null", ",", "callable", "$", "onRejected", "=", "null", ")", "{", "if", "(", "null", "===", "$", "onFulfilled", ")", "{", "return", "$", "this", ";", "}", "try", "{", "return", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-http/promise/blob/1cc44dc01402d407fc6da922591deebe4659826f/src/FulfilledPromise.php#L28-L39
cakephp/chronos
src/ChronosInterval.php
ChronosInterval.weeksAndDays
public function weeksAndDays($weeks, $days) { $this->dayz = ($weeks * ChronosInterface::DAYS_PER_WEEK) + $days; return $this; }
php
public function weeksAndDays($weeks, $days) { $this->dayz = ($weeks * ChronosInterface::DAYS_PER_WEEK) + $days; return $this; }
[ "public", "function", "weeksAndDays", "(", "$", "weeks", ",", "$", "days", ")", "{", "$", "this", "->", "dayz", "=", "(", "$", "weeks", "*", "ChronosInterface", "::", "DAYS_PER_WEEK", ")", "+", "$", "days", ";", "return", "$", "this", ";", "}" ]
Allow setting of weeks and days to be cumulative. @param int $weeks Number of weeks to set @param int $days Number of days to set @return static
[ "Allow", "setting", "of", "weeks", "and", "days", "to", "be", "cumulative", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/ChronosInterval.php#L345-L350
cakephp/chronos
src/Translator.php
Translator.plural
public function plural($key, $count, array $vars = []) { if ($count === 1) { return $this->singular($key, $vars); } return $this->singular($key . '_plural', ['count' => $count] + $vars); }
php
public function plural($key, $count, array $vars = []) { if ($count === 1) { return $this->singular($key, $vars); } return $this->singular($key . '_plural', ['count' => $count] + $vars); }
[ "public", "function", "plural", "(", "$", "key", ",", "$", "count", ",", "array", "$", "vars", "=", "[", "]", ")", "{", "if", "(", "$", "count", "===", "1", ")", "{", "return", "$", "this", "->", "singular", "(", "$", "key", ",", "$", "vars", ...
Get a plural message. @param string $key The key to use. @param int $count The number of items in the translation. @param array $vars Additional context variables. @return string The translated message or ''.
[ "Get", "a", "plural", "message", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Translator.php#L64-L71
cakephp/chronos
src/Translator.php
Translator.singular
public function singular($key, array $vars = []) { if (isset(static::$strings[$key])) { $varKeys = array_keys($vars); foreach ($varKeys as $i => $k) { $varKeys[$i] = '{' . $k . '}'; } return str_replace($varKeys, $vars, static::$strings[$key]); } return ''; }
php
public function singular($key, array $vars = []) { if (isset(static::$strings[$key])) { $varKeys = array_keys($vars); foreach ($varKeys as $i => $k) { $varKeys[$i] = '{' . $k . '}'; } return str_replace($varKeys, $vars, static::$strings[$key]); } return ''; }
[ "public", "function", "singular", "(", "$", "key", ",", "array", "$", "vars", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "static", "::", "$", "strings", "[", "$", "key", "]", ")", ")", "{", "$", "varKeys", "=", "array_keys", "(", "$", "v...
Get a singular message. @param string $key The key to use. @param array $vars Additional context variables. @return string The translated message or ''.
[ "Get", "a", "singular", "message", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Translator.php#L80-L92
cakephp/chronos
src/Traits/ComparisonTrait.php
ComparisonTrait.between
public function between(ChronosInterface $dt1, ChronosInterface $dt2, $equal = true) { if ($dt1->gt($dt2)) { $temp = $dt1; $dt1 = $dt2; $dt2 = $temp; } if ($equal) { return $this->gte($dt1) && $this->lte($dt2); } return $this->gt($dt1) && $this->lt($dt2); }
php
public function between(ChronosInterface $dt1, ChronosInterface $dt2, $equal = true) { if ($dt1->gt($dt2)) { $temp = $dt1; $dt1 = $dt2; $dt2 = $temp; } if ($equal) { return $this->gte($dt1) && $this->lte($dt2); } return $this->gt($dt1) && $this->lt($dt2); }
[ "public", "function", "between", "(", "ChronosInterface", "$", "dt1", ",", "ChronosInterface", "$", "dt2", ",", "$", "equal", "=", "true", ")", "{", "if", "(", "$", "dt1", "->", "gt", "(", "$", "dt2", ")", ")", "{", "$", "temp", "=", "$", "dt1", ...
Determines if the instance is between two others @param \Cake\Chronos\ChronosInterface $dt1 The instance to compare with. @param \Cake\Chronos\ChronosInterface $dt2 The instance to compare with. @param bool $equal Indicates if a > and < comparison should be used or <= or >= @return bool
[ "Determines", "if", "the", "instance", "is", "between", "two", "others" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ComparisonTrait.php#L127-L140
cakephp/chronos
src/Traits/ComparisonTrait.php
ComparisonTrait.closest
public function closest(ChronosInterface $dt1, ChronosInterface $dt2) { return $this->diffInSeconds($dt1) < $this->diffInSeconds($dt2) ? $dt1 : $dt2; }
php
public function closest(ChronosInterface $dt1, ChronosInterface $dt2) { return $this->diffInSeconds($dt1) < $this->diffInSeconds($dt2) ? $dt1 : $dt2; }
[ "public", "function", "closest", "(", "ChronosInterface", "$", "dt1", ",", "ChronosInterface", "$", "dt2", ")", "{", "return", "$", "this", "->", "diffInSeconds", "(", "$", "dt1", ")", "<", "$", "this", "->", "diffInSeconds", "(", "$", "dt2", ")", "?", ...
Get the closest date from the instance. @param \Cake\Chronos\ChronosInterface $dt1 The instance to compare with. @param \Cake\Chronos\ChronosInterface $dt2 The instance to compare with. @return \Cake\Chronos\ChronosInterface
[ "Get", "the", "closest", "date", "from", "the", "instance", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ComparisonTrait.php#L149-L152
cakephp/chronos
src/Traits/ComparisonTrait.php
ComparisonTrait.farthest
public function farthest(ChronosInterface $dt1, ChronosInterface $dt2) { return $this->diffInSeconds($dt1) > $this->diffInSeconds($dt2) ? $dt1 : $dt2; }
php
public function farthest(ChronosInterface $dt1, ChronosInterface $dt2) { return $this->diffInSeconds($dt1) > $this->diffInSeconds($dt2) ? $dt1 : $dt2; }
[ "public", "function", "farthest", "(", "ChronosInterface", "$", "dt1", ",", "ChronosInterface", "$", "dt2", ")", "{", "return", "$", "this", "->", "diffInSeconds", "(", "$", "dt1", ")", ">", "$", "this", "->", "diffInSeconds", "(", "$", "dt2", ")", "?", ...
Get the farthest date from the instance. @param \Cake\Chronos\ChronosInterface $dt1 The instance to compare with. @param \Cake\Chronos\ChronosInterface $dt2 The instance to compare with. @return \Cake\Chronos\ChronosInterface
[ "Get", "the", "farthest", "date", "from", "the", "instance", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ComparisonTrait.php#L161-L164
cakephp/chronos
src/Traits/ComparisonTrait.php
ComparisonTrait.min
public function min(ChronosInterface $dt = null) { $dt = ($dt === null) ? static::now($this->tz) : $dt; return $this->lt($dt) ? $this : $dt; }
php
public function min(ChronosInterface $dt = null) { $dt = ($dt === null) ? static::now($this->tz) : $dt; return $this->lt($dt) ? $this : $dt; }
[ "public", "function", "min", "(", "ChronosInterface", "$", "dt", "=", "null", ")", "{", "$", "dt", "=", "(", "$", "dt", "===", "null", ")", "?", "static", "::", "now", "(", "$", "this", "->", "tz", ")", ":", "$", "dt", ";", "return", "$", "this...
Get the minimum instance between a given instance (default now) and the current instance. @param \Cake\Chronos\ChronosInterface|null $dt The instance to compare with. @return static
[ "Get", "the", "minimum", "instance", "between", "a", "given", "instance", "(", "default", "now", ")", "and", "the", "current", "instance", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ComparisonTrait.php#L172-L177
cakephp/chronos
src/Traits/ComparisonTrait.php
ComparisonTrait.max
public function max(ChronosInterface $dt = null) { $dt = ($dt === null) ? static::now($this->tz) : $dt; return $this->gt($dt) ? $this : $dt; }
php
public function max(ChronosInterface $dt = null) { $dt = ($dt === null) ? static::now($this->tz) : $dt; return $this->gt($dt) ? $this : $dt; }
[ "public", "function", "max", "(", "ChronosInterface", "$", "dt", "=", "null", ")", "{", "$", "dt", "=", "(", "$", "dt", "===", "null", ")", "?", "static", "::", "now", "(", "$", "this", "->", "tz", ")", ":", "$", "dt", ";", "return", "$", "this...
Get the maximum instance between a given instance (default now) and the current instance. @param \Cake\Chronos\ChronosInterface|null $dt The instance to compare with. @return static
[ "Get", "the", "maximum", "instance", "between", "a", "given", "instance", "(", "default", "now", ")", "and", "the", "current", "instance", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ComparisonTrait.php#L185-L190
cakephp/chronos
src/Traits/ComparisonTrait.php
ComparisonTrait.isBirthday
public function isBirthday(ChronosInterface $dt = null) { if ($dt === null) { $dt = static::now($this->tz); } return $this->format('md') === $dt->format('md'); }
php
public function isBirthday(ChronosInterface $dt = null) { if ($dt === null) { $dt = static::now($this->tz); } return $this->format('md') === $dt->format('md'); }
[ "public", "function", "isBirthday", "(", "ChronosInterface", "$", "dt", "=", "null", ")", "{", "if", "(", "$", "dt", "===", "null", ")", "{", "$", "dt", "=", "static", "::", "now", "(", "$", "this", "->", "tz", ")", ";", "}", "return", "$", "this...
Check if its the birthday. Compares the date/month values of the two dates. @param \Cake\Chronos\ChronosInterface|null $dt The instance to compare with or null to use current day. @return static
[ "Check", "if", "its", "the", "birthday", ".", "Compares", "the", "date", "/", "month", "values", "of", "the", "two", "dates", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ComparisonTrait.php#L449-L456
cakephp/chronos
src/Traits/ComparisonTrait.php
ComparisonTrait.wasWithinLast
public function wasWithinLast($timeInterval) { $now = new static(); $interval = $now->copy()->modify('-' . $timeInterval); $thisTime = $this->format('U'); return $thisTime >= $interval->format('U') && $thisTime <= $now->format('U'); }
php
public function wasWithinLast($timeInterval) { $now = new static(); $interval = $now->copy()->modify('-' . $timeInterval); $thisTime = $this->format('U'); return $thisTime >= $interval->format('U') && $thisTime <= $now->format('U'); }
[ "public", "function", "wasWithinLast", "(", "$", "timeInterval", ")", "{", "$", "now", "=", "new", "static", "(", ")", ";", "$", "interval", "=", "$", "now", "->", "copy", "(", ")", "->", "modify", "(", "'-'", ".", "$", "timeInterval", ")", ";", "$...
Returns true this instance happened within the specified interval @param string|int $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute. @return bool
[ "Returns", "true", "this", "instance", "happened", "within", "the", "specified", "interval" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ComparisonTrait.php#L465-L472
cakephp/chronos
src/Traits/FormattingTrait.php
FormattingTrait.toQuarter
public function toQuarter($range = false) { $quarter = ceil($this->format('m') / 3); if ($range === false) { return $quarter; } $year = $this->format('Y'); switch ($quarter) { case 1: return [$year . '-01-01', $year . '-03-31']; case 2: return [$year . '-04-01', $year . '-06-30']; case 3: return [$year . '-07-01', $year . '-09-30']; case 4: return [$year . '-10-01', $year . '-12-31']; } }
php
public function toQuarter($range = false) { $quarter = ceil($this->format('m') / 3); if ($range === false) { return $quarter; } $year = $this->format('Y'); switch ($quarter) { case 1: return [$year . '-01-01', $year . '-03-31']; case 2: return [$year . '-04-01', $year . '-06-30']; case 3: return [$year . '-07-01', $year . '-09-30']; case 4: return [$year . '-10-01', $year . '-12-31']; } }
[ "public", "function", "toQuarter", "(", "$", "range", "=", "false", ")", "{", "$", "quarter", "=", "ceil", "(", "$", "this", "->", "format", "(", "'m'", ")", "/", "3", ")", ";", "if", "(", "$", "range", "===", "false", ")", "{", "return", "$", ...
Returns the quarter @param bool $range Range. @return int|array 1, 2, 3, or 4 quarter of year or array if $range true
[ "Returns", "the", "quarter" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/FormattingTrait.php#L232-L250
cakephp/chronos
src/Traits/DifferenceTrait.php
DifferenceTrait.diffInDaysFiltered
public function diffInDaysFiltered(callable $callback, ChronosInterface $dt = null, $abs = true) { return $this->diffFiltered(ChronosInterval::day(), $callback, $dt, $abs); }
php
public function diffInDaysFiltered(callable $callback, ChronosInterface $dt = null, $abs = true) { return $this->diffFiltered(ChronosInterval::day(), $callback, $dt, $abs); }
[ "public", "function", "diffInDaysFiltered", "(", "callable", "$", "callback", ",", "ChronosInterface", "$", "dt", "=", "null", ",", "$", "abs", "=", "true", ")", "{", "return", "$", "this", "->", "diffFiltered", "(", "ChronosInterval", "::", "day", "(", ")...
Get the difference in days using a filter callable @param callable $callback The callback to use for filtering. @param \Cake\Chronos\ChronosInterface|null $dt The instance to difference from. @param bool $abs Get the absolute of the difference @return int
[ "Get", "the", "difference", "in", "days", "using", "a", "filter", "callable" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/DifferenceTrait.php#L102-L105
cakephp/chronos
src/Traits/DifferenceTrait.php
DifferenceTrait.diffInHoursFiltered
public function diffInHoursFiltered(callable $callback, ChronosInterface $dt = null, $abs = true) { return $this->diffFiltered(ChronosInterval::hour(), $callback, $dt, $abs); }
php
public function diffInHoursFiltered(callable $callback, ChronosInterface $dt = null, $abs = true) { return $this->diffFiltered(ChronosInterval::hour(), $callback, $dt, $abs); }
[ "public", "function", "diffInHoursFiltered", "(", "callable", "$", "callback", ",", "ChronosInterface", "$", "dt", "=", "null", ",", "$", "abs", "=", "true", ")", "{", "return", "$", "this", "->", "diffFiltered", "(", "ChronosInterval", "::", "hour", "(", ...
Get the difference in hours using a filter callable @param callable $callback The callback to use for filtering. @param \Cake\Chronos\ChronosInterface|null $dt The instance to difference from. @param bool $abs Get the absolute of the difference @return int
[ "Get", "the", "difference", "in", "hours", "using", "a", "filter", "callable" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/DifferenceTrait.php#L115-L118
cakephp/chronos
src/Traits/DifferenceTrait.php
DifferenceTrait.diffFiltered
public function diffFiltered(ChronosInterval $ci, callable $callback, ChronosInterface $dt = null, $abs = true) { $start = $this; $end = $dt === null ? static::now($this->tz) : $dt; $inverse = false; if (defined('HHVM_VERSION')) { $start = new DateTimeImmutable($this->toIso8601String()); $end = new DateTimeImmutable($end->toIso8601String()); } if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $period = new DatePeriod($start, $ci, $end); $vals = array_filter(iterator_to_array($period), function (DateTimeInterface $date) use ($callback) { return $callback(static::instance($date)); }); $diff = count($vals); return $inverse && !$abs ? -$diff : $diff; }
php
public function diffFiltered(ChronosInterval $ci, callable $callback, ChronosInterface $dt = null, $abs = true) { $start = $this; $end = $dt === null ? static::now($this->tz) : $dt; $inverse = false; if (defined('HHVM_VERSION')) { $start = new DateTimeImmutable($this->toIso8601String()); $end = new DateTimeImmutable($end->toIso8601String()); } if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $period = new DatePeriod($start, $ci, $end); $vals = array_filter(iterator_to_array($period), function (DateTimeInterface $date) use ($callback) { return $callback(static::instance($date)); }); $diff = count($vals); return $inverse && !$abs ? -$diff : $diff; }
[ "public", "function", "diffFiltered", "(", "ChronosInterval", "$", "ci", ",", "callable", "$", "callback", ",", "ChronosInterface", "$", "dt", "=", "null", ",", "$", "abs", "=", "true", ")", "{", "$", "start", "=", "$", "this", ";", "$", "end", "=", ...
Get the difference by the given interval using a filter callable @param \Cake\Chronos\ChronosInterval $ci An interval to traverse by @param callable $callback The callback to use for filtering. @param \Cake\Chronos\ChronosInterface|null $dt The instance to difference from. @param bool $abs Get the absolute of the difference @return int
[ "Get", "the", "difference", "by", "the", "given", "interval", "using", "a", "filter", "callable" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/DifferenceTrait.php#L129-L154
cakephp/chronos
src/Traits/DifferenceTrait.php
DifferenceTrait.diffForHumans
public function diffForHumans(ChronosInterface $other = null, $absolute = false) { return static::diffFormatter()->diffForHumans($this, $other, $absolute); }
php
public function diffForHumans(ChronosInterface $other = null, $absolute = false) { return static::diffFormatter()->diffForHumans($this, $other, $absolute); }
[ "public", "function", "diffForHumans", "(", "ChronosInterface", "$", "other", "=", "null", ",", "$", "absolute", "=", "false", ")", "{", "return", "static", "::", "diffFormatter", "(", ")", "->", "diffForHumans", "(", "$", "this", ",", "$", "other", ",", ...
Get the difference in a human readable format. When comparing a value in the past to default now: 1 hour ago 5 months ago When comparing a value in the future to default now: 1 hour from now 5 months from now When comparing a value in the past to another value: 1 hour before 5 months before When comparing a value in the future to another value: 1 hour after 5 months after @param \Cake\Chronos\ChronosInterface|null $other The datetime to compare with. @param bool $absolute removes time difference modifiers ago, after, etc @return string
[ "Get", "the", "difference", "in", "a", "human", "readable", "format", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/DifferenceTrait.php#L279-L282
cakephp/chronos
src/Traits/DifferenceTrait.php
DifferenceTrait.diffFormatter
public static function diffFormatter($formatter = null) { if ($formatter === null) { if (static::$diffFormatter === null) { static::$diffFormatter = new DifferenceFormatter(); } return static::$diffFormatter; } return static::$diffFormatter = $formatter; }
php
public static function diffFormatter($formatter = null) { if ($formatter === null) { if (static::$diffFormatter === null) { static::$diffFormatter = new DifferenceFormatter(); } return static::$diffFormatter; } return static::$diffFormatter = $formatter; }
[ "public", "static", "function", "diffFormatter", "(", "$", "formatter", "=", "null", ")", "{", "if", "(", "$", "formatter", "===", "null", ")", "{", "if", "(", "static", "::", "$", "diffFormatter", "===", "null", ")", "{", "static", "::", "$", "diffFor...
Get the difference formatter instance or overwrite the current one. @param \Cake\Chronos\DifferenceFormatter|null $formatter The formatter instance when setting. @return \Cake\Chronos\DifferenceFormatter The formatter instance.
[ "Get", "the", "difference", "formatter", "instance", "or", "overwrite", "the", "current", "one", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/DifferenceTrait.php#L290-L301
cakephp/chronos
src/Traits/FactoryTrait.php
FactoryTrait.createFromTime
public static function createFromTime($hour = null, $minute = null, $second = null, $tz = null) { return static::create(null, null, null, $hour, $minute, $second, $tz); }
php
public static function createFromTime($hour = null, $minute = null, $second = null, $tz = null) { return static::create(null, null, null, $hour, $minute, $second, $tz); }
[ "public", "static", "function", "createFromTime", "(", "$", "hour", "=", "null", ",", "$", "minute", "=", "null", ",", "$", "second", "=", "null", ",", "$", "tz", "=", "null", ")", "{", "return", "static", "::", "create", "(", "null", ",", "null", ...
Create a ChronosInterface instance from just a time. The date portion is set to today. @param int|null $hour The hour to create an instance with. @param int|null $minute The minute to create an instance with. @param int|null $second The second to create an instance with. @param \DateTimeZone|string|null $tz The DateTimeZone object or timezone name the new instance should use. @return static
[ "Create", "a", "ChronosInterface", "instance", "from", "just", "a", "time", ".", "The", "date", "portion", "is", "set", "to", "today", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/FactoryTrait.php#L190-L193
cakephp/chronos
src/Traits/FactoryTrait.php
FactoryTrait.safeCreateDateTimeZone
protected static function safeCreateDateTimeZone($object) { if ($object === null) { return new DateTimeZone(date_default_timezone_get()); } if ($object instanceof DateTimeZone) { return $object; } return new DateTimeZone($object); }
php
protected static function safeCreateDateTimeZone($object) { if ($object === null) { return new DateTimeZone(date_default_timezone_get()); } if ($object instanceof DateTimeZone) { return $object; } return new DateTimeZone($object); }
[ "protected", "static", "function", "safeCreateDateTimeZone", "(", "$", "object", ")", "{", "if", "(", "$", "object", "===", "null", ")", "{", "return", "new", "DateTimeZone", "(", "date_default_timezone_get", "(", ")", ")", ";", "}", "if", "(", "$", "objec...
Creates a DateTimeZone from a string or a DateTimeZone @param \DateTimeZone|string|null $object The value to convert. @return \DateTimeZone @throws \InvalidArgumentException
[ "Creates", "a", "DateTimeZone", "from", "a", "string", "or", "a", "DateTimeZone" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/FactoryTrait.php#L253-L264
cakephp/chronos
src/DifferenceFormatter.php
DifferenceFormatter.diffForHumans
public function diffForHumans(ChronosInterface $date, ChronosInterface $other = null, $absolute = false) { $isNow = $other === null; if ($isNow) { $other = $date->now($date->tz); } $diffInterval = $date->diff($other); switch (true) { case ($diffInterval->y > 0): $unit = 'year'; $count = $diffInterval->y; break; case ($diffInterval->m > 0): $unit = 'month'; $count = $diffInterval->m; break; case ($diffInterval->d > 0): $unit = 'day'; $count = $diffInterval->d; if ($count >= ChronosInterface::DAYS_PER_WEEK) { $unit = 'week'; $count = (int)($count / ChronosInterface::DAYS_PER_WEEK); } break; case ($diffInterval->h > 0): $unit = 'hour'; $count = $diffInterval->h; break; case ($diffInterval->i > 0): $unit = 'minute'; $count = $diffInterval->i; break; default: $count = $diffInterval->s; $unit = 'second'; break; } $time = $this->translate->plural($unit, $count, ['count' => $count]); if ($absolute) { return $time; } $isFuture = $diffInterval->invert === 1; $transId = $isNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); // Some langs have special pluralization for past and future tense. $tryKeyExists = $unit . '_' . $transId; if ($this->translate->exists($tryKeyExists)) { $time = $this->translate->plural($tryKeyExists, $count, ['count' => $count]); } return $this->translate->singular($transId, ['time' => $time]); }
php
public function diffForHumans(ChronosInterface $date, ChronosInterface $other = null, $absolute = false) { $isNow = $other === null; if ($isNow) { $other = $date->now($date->tz); } $diffInterval = $date->diff($other); switch (true) { case ($diffInterval->y > 0): $unit = 'year'; $count = $diffInterval->y; break; case ($diffInterval->m > 0): $unit = 'month'; $count = $diffInterval->m; break; case ($diffInterval->d > 0): $unit = 'day'; $count = $diffInterval->d; if ($count >= ChronosInterface::DAYS_PER_WEEK) { $unit = 'week'; $count = (int)($count / ChronosInterface::DAYS_PER_WEEK); } break; case ($diffInterval->h > 0): $unit = 'hour'; $count = $diffInterval->h; break; case ($diffInterval->i > 0): $unit = 'minute'; $count = $diffInterval->i; break; default: $count = $diffInterval->s; $unit = 'second'; break; } $time = $this->translate->plural($unit, $count, ['count' => $count]); if ($absolute) { return $time; } $isFuture = $diffInterval->invert === 1; $transId = $isNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); // Some langs have special pluralization for past and future tense. $tryKeyExists = $unit . '_' . $transId; if ($this->translate->exists($tryKeyExists)) { $time = $this->translate->plural($tryKeyExists, $count, ['count' => $count]); } return $this->translate->singular($transId, ['time' => $time]); }
[ "public", "function", "diffForHumans", "(", "ChronosInterface", "$", "date", ",", "ChronosInterface", "$", "other", "=", "null", ",", "$", "absolute", "=", "false", ")", "{", "$", "isNow", "=", "$", "other", "===", "null", ";", "if", "(", "$", "isNow", ...
Get the difference in a human readable format. @param \Cake\Chronos\ChronosInterface $date The datetime to start with. @param \Cake\Chronos\ChronosInterface|null $other The datetime to compare against. @param bool $absolute removes time difference modifiers ago, after, etc @return string The difference between the two days in a human readable format @see \Cake\Chronos\ChronosInterface::diffForHumans
[ "Get", "the", "difference", "in", "a", "human", "readable", "format", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/DifferenceFormatter.php#L50-L102
cakephp/chronos
src/Traits/FrozenTimeTrait.php
FrozenTimeTrait.stripTime
protected function stripTime($time) { if (is_int($time) || ctype_digit($time)) { return gmdate('Y-m-d 00:00:00', $time); } if ($time instanceof DateTimeInterface) { $time = $time->format('Y-m-d 00:00:00'); } if (substr($time, 0, 1) === '@') { return gmdate('Y-m-d 00:00:00', substr($time, 1)); } if ($time === null || $time === 'now' || $time === '') { return date('Y-m-d 00:00:00'); } if ($this->hasRelativeKeywords($time)) { return date('Y-m-d 00:00:00', strtotime($time)); } return preg_replace('/\d{1,2}:\d{1,2}:\d{1,2}(?:\.\d+)?/', '00:00:00', $time); }
php
protected function stripTime($time) { if (is_int($time) || ctype_digit($time)) { return gmdate('Y-m-d 00:00:00', $time); } if ($time instanceof DateTimeInterface) { $time = $time->format('Y-m-d 00:00:00'); } if (substr($time, 0, 1) === '@') { return gmdate('Y-m-d 00:00:00', substr($time, 1)); } if ($time === null || $time === 'now' || $time === '') { return date('Y-m-d 00:00:00'); } if ($this->hasRelativeKeywords($time)) { return date('Y-m-d 00:00:00', strtotime($time)); } return preg_replace('/\d{1,2}:\d{1,2}:\d{1,2}(?:\.\d+)?/', '00:00:00', $time); }
[ "protected", "function", "stripTime", "(", "$", "time", ")", "{", "if", "(", "is_int", "(", "$", "time", ")", "||", "ctype_digit", "(", "$", "time", ")", ")", "{", "return", "gmdate", "(", "'Y-m-d 00:00:00'", ",", "$", "time", ")", ";", "}", "if", ...
Removes the time components from an input string. Used to ensure constructed objects always lack time. @param string|int $time The input time. Integer values will be assumed to be in UTC. The 'now' and '' values will use the current local time. @return string The date component of $time.
[ "Removes", "the", "time", "components", "from", "an", "input", "string", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/FrozenTimeTrait.php#L34-L53
cakephp/chronos
src/Traits/FrozenTimeTrait.php
FrozenTimeTrait.setTime
public function setTime($hours, $minutes, $seconds = null, $microseconds = null) { if (CHRONOS_SUPPORTS_MICROSECONDS) { return parent::setTime(0, 0, 0, 0); } return parent::setTime(0, 0, 0); }
php
public function setTime($hours, $minutes, $seconds = null, $microseconds = null) { if (CHRONOS_SUPPORTS_MICROSECONDS) { return parent::setTime(0, 0, 0, 0); } return parent::setTime(0, 0, 0); }
[ "public", "function", "setTime", "(", "$", "hours", ",", "$", "minutes", ",", "$", "seconds", "=", "null", ",", "$", "microseconds", "=", "null", ")", "{", "if", "(", "CHRONOS_SUPPORTS_MICROSECONDS", ")", "{", "return", "parent", "::", "setTime", "(", "0...
Modify the time on the Date. This method ignores all inputs and forces all inputs to 0. @param int $hours The hours to set (ignored) @param int $minutes The minutes to set (ignored) @param int $seconds The seconds to set (ignored) @param int $microseconds The microseconds to set (ignored) @return static A modified Date instance.
[ "Modify", "the", "time", "on", "the", "Date", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/FrozenTimeTrait.php#L77-L84
cakephp/chronos
src/Traits/FrozenTimeTrait.php
FrozenTimeTrait.modify
public function modify($relative) { if (preg_match('/hour|minute|second/', $relative)) { return $this; } $new = parent::modify($relative); if ($new->format('H:i:s') !== '00:00:00') { return $new->setTime(0, 0, 0); } return $new; }
php
public function modify($relative) { if (preg_match('/hour|minute|second/', $relative)) { return $this; } $new = parent::modify($relative); if ($new->format('H:i:s') !== '00:00:00') { return $new->setTime(0, 0, 0); } return $new; }
[ "public", "function", "modify", "(", "$", "relative", ")", "{", "if", "(", "preg_match", "(", "'/hour|minute|second/'", ",", "$", "relative", ")", ")", "{", "return", "$", "this", ";", "}", "$", "new", "=", "parent", "::", "modify", "(", "$", "relative...
Overloaded to ignore time changes. Changing any aspect of the time will be ignored, and the resulting object will have its time frozen to 00:00:00. @param string $relative The relative change to make. @return static A new date with the applied date changes.
[ "Overloaded", "to", "ignore", "time", "changes", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/FrozenTimeTrait.php#L174-L185
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.setDate
public function setDate($year, $month, $day) { return $this->modify('+0 day')->setDateParent($year, $month, $day); }
php
public function setDate($year, $month, $day) { return $this->modify('+0 day')->setDateParent($year, $month, $day); }
[ "public", "function", "setDate", "(", "$", "year", ",", "$", "month", ",", "$", "day", ")", "{", "return", "$", "this", "->", "modify", "(", "'+0 day'", ")", "->", "setDateParent", "(", "$", "year", ",", "$", "month", ",", "$", "day", ")", ";", "...
Set the date to a different date. Workaround for a PHP bug related to the first day of a month @param int $year The year to set. @param int $month The month to set. @param int $day The day to set. @return static @see https://bugs.php.net/bug.php?id=63863
[ "Set", "the", "date", "to", "a", "different", "date", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L114-L117
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.addMonths
public function addMonths($value) { $day = $this->day; $date = $this->modify((int)$value . ' month'); if ($date->day !== $day) { return $date->modify('last day of previous month'); } return $date; }
php
public function addMonths($value) { $day = $this->day; $date = $this->modify((int)$value . ' month'); if ($date->day !== $day) { return $date->modify('last day of previous month'); } return $date; }
[ "public", "function", "addMonths", "(", "$", "value", ")", "{", "$", "day", "=", "$", "this", "->", "day", ";", "$", "date", "=", "$", "this", "->", "modify", "(", "(", "int", ")", "$", "value", ".", "' month'", ")", ";", "if", "(", "$", "date"...
Add months to the instance. Positive $value travels forward while negative $value travels into the past. When adding or subtracting months, if the resulting time is a date that does not exist, the result of this operation will always be the last day of the intended month. ### Example: ``` (new Chronos('2015-01-03'))->addMonths(1); // Results in 2015-02-03 (new Chronos('2015-01-31'))->addMonths(1); // Results in 2015-02-28 ``` @param int $value The number of months to add. @return static
[ "Add", "months", "to", "the", "instance", ".", "Positive", "$value", "travels", "forward", "while", "negative", "$value", "travels", "into", "the", "past", "." ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L306-L316
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.startOfDecade
public function startOfDecade() { $year = $this->year - $this->year % ChronosInterface::YEARS_PER_DECADE; return $this->modify("first day of january $year, midnight"); }
php
public function startOfDecade() { $year = $this->year - $this->year % ChronosInterface::YEARS_PER_DECADE; return $this->modify("first day of january $year, midnight"); }
[ "public", "function", "startOfDecade", "(", ")", "{", "$", "year", "=", "$", "this", "->", "year", "-", "$", "this", "->", "year", "%", "ChronosInterface", "::", "YEARS_PER_DECADE", ";", "return", "$", "this", "->", "modify", "(", "\"first day of january $ye...
Resets the date to the first day of the decade and the time to 00:00:00 @return static
[ "Resets", "the", "date", "to", "the", "first", "day", "of", "the", "decade", "and", "the", "time", "to", "00", ":", "00", ":", "00" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L809-L814
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.endOfDecade
public function endOfDecade() { $year = $this->year - $this->year % ChronosInterface::YEARS_PER_DECADE + ChronosInterface::YEARS_PER_DECADE - 1; return $this->modify("last day of december $year, 23:59:59"); }
php
public function endOfDecade() { $year = $this->year - $this->year % ChronosInterface::YEARS_PER_DECADE + ChronosInterface::YEARS_PER_DECADE - 1; return $this->modify("last day of december $year, 23:59:59"); }
[ "public", "function", "endOfDecade", "(", ")", "{", "$", "year", "=", "$", "this", "->", "year", "-", "$", "this", "->", "year", "%", "ChronosInterface", "::", "YEARS_PER_DECADE", "+", "ChronosInterface", "::", "YEARS_PER_DECADE", "-", "1", ";", "return", ...
Resets the date to end of the decade and time to 23:59:59 @return static
[ "Resets", "the", "date", "to", "end", "of", "the", "decade", "and", "time", "to", "23", ":", "59", ":", "59" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L821-L826
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.startOfCentury
public function startOfCentury() { $year = $this->startOfYear()->year(($this->year - 1) - ($this->year - 1) % ChronosInterface::YEARS_PER_CENTURY + 1)->year; return $this->modify("first day of january $year, midnight"); }
php
public function startOfCentury() { $year = $this->startOfYear()->year(($this->year - 1) - ($this->year - 1) % ChronosInterface::YEARS_PER_CENTURY + 1)->year; return $this->modify("first day of january $year, midnight"); }
[ "public", "function", "startOfCentury", "(", ")", "{", "$", "year", "=", "$", "this", "->", "startOfYear", "(", ")", "->", "year", "(", "(", "$", "this", "->", "year", "-", "1", ")", "-", "(", "$", "this", "->", "year", "-", "1", ")", "%", "Chr...
Resets the date to the first day of the century and the time to 00:00:00 @return static
[ "Resets", "the", "date", "to", "the", "first", "day", "of", "the", "century", "and", "the", "time", "to", "00", ":", "00", ":", "00" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L833-L838
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.endOfCentury
public function endOfCentury() { $year = $this->endOfYear()->year(($this->year - 1) - ($this->year - 1) % ChronosInterface::YEARS_PER_CENTURY + ChronosInterface::YEARS_PER_CENTURY)->year; return $this->modify("last day of december $year, 23:59:59"); }
php
public function endOfCentury() { $year = $this->endOfYear()->year(($this->year - 1) - ($this->year - 1) % ChronosInterface::YEARS_PER_CENTURY + ChronosInterface::YEARS_PER_CENTURY)->year; return $this->modify("last day of december $year, 23:59:59"); }
[ "public", "function", "endOfCentury", "(", ")", "{", "$", "year", "=", "$", "this", "->", "endOfYear", "(", ")", "->", "year", "(", "(", "$", "this", "->", "year", "-", "1", ")", "-", "(", "$", "this", "->", "year", "-", "1", ")", "%", "Chronos...
Resets the date to end of the century and time to 23:59:59 @return static
[ "Resets", "the", "date", "to", "end", "of", "the", "century", "and", "time", "to", "23", ":", "59", ":", "59" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L845-L850
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.startOfWeek
public function startOfWeek() { $dt = $this; if ($dt->dayOfWeek !== static::$weekStartsAt) { $dt = $dt->previous(static::$weekStartsAt); } return $dt->startOfDay(); }
php
public function startOfWeek() { $dt = $this; if ($dt->dayOfWeek !== static::$weekStartsAt) { $dt = $dt->previous(static::$weekStartsAt); } return $dt->startOfDay(); }
[ "public", "function", "startOfWeek", "(", ")", "{", "$", "dt", "=", "$", "this", ";", "if", "(", "$", "dt", "->", "dayOfWeek", "!==", "static", "::", "$", "weekStartsAt", ")", "{", "$", "dt", "=", "$", "dt", "->", "previous", "(", "static", "::", ...
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00 @return static
[ "Resets", "the", "date", "to", "the", "first", "day", "of", "week", "(", "defined", "in", "$weekStartsAt", ")", "and", "the", "time", "to", "00", ":", "00", ":", "00" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L857-L865
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.endOfWeek
public function endOfWeek() { $dt = $this; if ($dt->dayOfWeek !== static::$weekEndsAt) { $dt = $dt->next(static::$weekEndsAt); } return $dt->endOfDay(); }
php
public function endOfWeek() { $dt = $this; if ($dt->dayOfWeek !== static::$weekEndsAt) { $dt = $dt->next(static::$weekEndsAt); } return $dt->endOfDay(); }
[ "public", "function", "endOfWeek", "(", ")", "{", "$", "dt", "=", "$", "this", ";", "if", "(", "$", "dt", "->", "dayOfWeek", "!==", "static", "::", "$", "weekEndsAt", ")", "{", "$", "dt", "=", "$", "dt", "->", "next", "(", "static", "::", "$", ...
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59 @return static
[ "Resets", "the", "date", "to", "end", "of", "week", "(", "defined", "in", "$weekEndsAt", ")", "and", "time", "to", "23", ":", "59", ":", "59" ]
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L872-L880
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.next
public function next($dayOfWeek = null) { if ($dayOfWeek === null) { $dayOfWeek = $this->dayOfWeek; } $day = static::$days[$dayOfWeek]; return $this->modify("next $day, midnight"); }
php
public function next($dayOfWeek = null) { if ($dayOfWeek === null) { $dayOfWeek = $this->dayOfWeek; } $day = static::$days[$dayOfWeek]; return $this->modify("next $day, midnight"); }
[ "public", "function", "next", "(", "$", "dayOfWeek", "=", "null", ")", "{", "if", "(", "$", "dayOfWeek", "===", "null", ")", "{", "$", "dayOfWeek", "=", "$", "this", "->", "dayOfWeek", ";", "}", "$", "day", "=", "static", "::", "$", "days", "[", ...
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int|null $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "next", "occurrence", "of", "a", "given", "day", "of", "the", "week", ".", "If", "no", "dayOfWeek", "is", "provided", "modify", "to", "the", "next", "occurrence", "of", "the", "current", "day", "of", "the", "week", ".", "Use", "t...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L891-L900
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.previous
public function previous($dayOfWeek = null) { if ($dayOfWeek === null) { $dayOfWeek = $this->dayOfWeek; } $day = static::$days[$dayOfWeek]; return $this->modify("last $day, midnight"); }
php
public function previous($dayOfWeek = null) { if ($dayOfWeek === null) { $dayOfWeek = $this->dayOfWeek; } $day = static::$days[$dayOfWeek]; return $this->modify("last $day, midnight"); }
[ "public", "function", "previous", "(", "$", "dayOfWeek", "=", "null", ")", "{", "if", "(", "$", "dayOfWeek", "===", "null", ")", "{", "$", "dayOfWeek", "=", "$", "this", "->", "dayOfWeek", ";", "}", "$", "day", "=", "static", "::", "$", "days", "["...
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int|null $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "previous", "occurrence", "of", "a", "given", "day", "of", "the", "week", ".", "If", "no", "dayOfWeek", "is", "provided", "modify", "to", "the", "previous", "occurrence", "of", "the", "current", "day", "of", "the", "week", ".", "Us...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L911-L920
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.firstOfMonth
public function firstOfMonth($dayOfWeek = null) { $day = $dayOfWeek === null ? 'day' : static::$days[$dayOfWeek]; return $this->modify("first $day of this month, midnight"); }
php
public function firstOfMonth($dayOfWeek = null) { $day = $dayOfWeek === null ? 'day' : static::$days[$dayOfWeek]; return $this->modify("first $day of this month, midnight"); }
[ "public", "function", "firstOfMonth", "(", "$", "dayOfWeek", "=", "null", ")", "{", "$", "day", "=", "$", "dayOfWeek", "===", "null", "?", "'day'", ":", "static", "::", "$", "days", "[", "$", "dayOfWeek", "]", ";", "return", "$", "this", "->", "modif...
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int|null $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "first", "occurrence", "of", "a", "given", "day", "of", "the", "week", "in", "the", "current", "month", ".", "If", "no", "dayOfWeek", "is", "provided", "modify", "to", "the", "first", "day", "of", "the", "current", "month", ".", ...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L931-L936
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.lastOfMonth
public function lastOfMonth($dayOfWeek = null) { $day = $dayOfWeek === null ? 'day' : static::$days[$dayOfWeek]; return $this->modify("last $day of this month, midnight"); }
php
public function lastOfMonth($dayOfWeek = null) { $day = $dayOfWeek === null ? 'day' : static::$days[$dayOfWeek]; return $this->modify("last $day of this month, midnight"); }
[ "public", "function", "lastOfMonth", "(", "$", "dayOfWeek", "=", "null", ")", "{", "$", "day", "=", "$", "dayOfWeek", "===", "null", "?", "'day'", ":", "static", "::", "$", "days", "[", "$", "dayOfWeek", "]", ";", "return", "$", "this", "->", "modify...
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int|null $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "last", "occurrence", "of", "a", "given", "day", "of", "the", "week", "in", "the", "current", "month", ".", "If", "no", "dayOfWeek", "is", "provided", "modify", "to", "the", "last", "day", "of", "the", "current", "month", ".", "U...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L947-L952