sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function visitArray($data, TypeMetadataInterface $type, ContextInterface $context)
{
return parent::visitArray($data === '[]' ? [] : $data, $type, $context);
} | {@inheritdoc} | entailment |
protected function decode($data)
{
$result = $first = [];
$headers = null;
$resource = fopen('php://temp', 'r+');
fwrite($resource, $data);
rewind($resource);
while (($fields = fgetcsv($resource, 0, $this->delimiter, $this->enclosure, $this->escapeChar)) !== false) {
if ($fields === [null]) {
continue;
}
$fieldsCount = count($fields);
if ($headers === null) {
$first = $fields;
$headersCount = $fieldsCount;
$headers = array_map(function ($value) {
return explode($this->keySeparator, $value);
}, $fields);
continue;
}
if ($fieldsCount !== $headersCount) {
throw new \InvalidArgumentException(sprintf(
'The input dimension is not equals for all entries (Expected: %d, got %d).',
$headersCount,
$fieldsCount
));
}
foreach ($fields as $key => $value) {
$this->expand($headers[$key], $value, $result);
}
}
fclose($resource);
if (!empty($result)) {
return $result;
}
if (empty($first)) {
return;
}
if (count($first) === 1) {
return reset($first);
}
return $first;
} | {@inheritdoc} | entailment |
public function convert($data, TypeMetadataInterface $type, ContextInterface $context)
{
$class = $this->classMetadataFactory->getClassMetadata($type->getName());
if ($class === null) {
throw new \RuntimeException(sprintf('The class metadata "%s" does not exit.', $type->getName()));
}
$visitor = $context->getVisitor();
if (!$visitor->startVisitingObject($data, $class, $context)) {
return $visitor->visitNull(null, $type, $context);
}
foreach ($class->getProperties() as $property) {
$visitor->visitObjectProperty($data, $property, $context);
}
return $visitor->finishVisitingObject($data, $class, $context);
} | {@inheritdoc} | entailment |
public function convert($exception, TypeMetadataInterface $type, ContextInterface $context)
{
if ($context->getDirection() === Direction::DESERIALIZATION) {
throw new \RuntimeException(sprintf('De-serializing an "Exception" is not supported.'));
}
$result = [
'code' => 500,
'message' => 'Internal Server Error',
];
if ($this->debug) {
$result['exception'] = $this->serializeException($exception);
}
return $context->getVisitor()->visitArray($result, $type, $context);
} | {@inheritdoc} | entailment |
private function serializeException(\Exception $exception)
{
$result = [
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTraceAsString(),
];
if ($exception->getPrevious() !== null) {
$result['previous'] = $this->serializeException($exception->getPrevious());
}
return $result;
} | @param \Exception $exception
@return mixed[] | entailment |
public function merge(PropertyMetadataInterface $propertyMetadata)
{
if ($propertyMetadata->hasAlias()) {
$this->setAlias($propertyMetadata->getAlias());
}
if ($propertyMetadata->hasType()) {
$this->setType($propertyMetadata->getType());
}
if ($propertyMetadata->hasReadable()) {
$this->setReadable($propertyMetadata->isReadable());
}
if ($propertyMetadata->hasWritable()) {
$this->setWritable($propertyMetadata->isWritable());
}
if ($propertyMetadata->hasAccessor()) {
$this->setAccessor($propertyMetadata->getAccessor());
}
if ($propertyMetadata->hasMutator()) {
$this->setMutator($propertyMetadata->getMutator());
}
if ($propertyMetadata->hasSinceVersion()) {
$this->setSinceVersion($propertyMetadata->getSinceVersion());
}
if ($propertyMetadata->hasUntilVersion()) {
$this->setUntilVersion($propertyMetadata->getUntilVersion());
}
if ($propertyMetadata->hasMaxDepth()) {
$this->setMaxDepth($propertyMetadata->getMaxDepth());
}
foreach ($propertyMetadata->getGroups() as $group) {
$this->addGroup($group);
}
if ($propertyMetadata->hasXmlAttribute()) {
$this->setXmlAttribute($propertyMetadata->isXmlAttribute());
}
if ($propertyMetadata->hasXmlValue()) {
$this->setXmlValue($propertyMetadata->isXmlValue());
}
if ($propertyMetadata->hasXmlInline()) {
$this->setXmlInline($propertyMetadata->isXmlInline());
}
if ($propertyMetadata->hasXmlEntry()) {
$this->setXmlEntry($propertyMetadata->getXmlEntry());
}
if ($propertyMetadata->hasXmlEntryAttribute()) {
$this->setXmlEntryAttribute($propertyMetadata->getXmlEntryAttribute());
}
if ($propertyMetadata->hasXmlKeyAsAttribute()) {
$this->setXmlKeyAsAttribute($propertyMetadata->useXmlKeyAsAttribute());
}
if ($propertyMetadata->hasXmlKeyAsNode()) {
$this->setXmlKeyAsNode($propertyMetadata->useXmlKeyAsNode());
}
} | {@inheritdoc} | entailment |
public function unserialize($serialized)
{
list(
$this->name,
$this->class,
$this->alias,
$this->type,
$this->readable,
$this->writable,
$this->accessor,
$this->mutator,
$this->since,
$this->until,
$this->maxDepth,
$this->groups,
$this->xmlAttribute,
$this->xmlValue,
$this->xmlInline,
$this->xmlEntry,
$this->xmlEntryAttribute,
$this->xmlKeyAsAttribute,
$this->xmlKeyAsNode
) = unserialize($serialized);
} | {@inheritdoc} | entailment |
public function getClassMetadata($class)
{
$classMetadata = $this->factory->getClassMetadata($class);
if ($classMetadata === null) {
$this->dispatcher->dispatch(
SerializerEvents::CLASS_METADATA_NOT_FOUND,
$event = new ClassMetadataNotFoundEvent($class)
);
} else {
$this->dispatcher->dispatch(
SerializerEvents::CLASS_METADATA_LOAD,
$event = new ClassMetadataLoadEvent($classMetadata)
);
}
return $event->getClassMetadata();
} | {@inheritdoc} | entailment |
public static function create(
array $visitors = [],
InstantiatorInterface $instantiator = null,
AccessorInterface $accessor = null,
MutatorInterface $mutator = null
) {
$instantiator = $instantiator ?: new DoctrineInstantiator();
$accessor = $accessor ?: new ReflectionAccessor();
$mutator = $mutator ?: new ReflectionMutator();
return new static(array_replace_recursive([
Direction::SERIALIZATION => [
Format::CSV => new CsvSerializationVisitor($accessor),
Format::JSON => new JsonSerializationVisitor($accessor),
Format::XML => new XmlSerializationVisitor($accessor),
Format::YAML => new YamlSerializationVisitor($accessor),
],
Direction::DESERIALIZATION => [
Format::CSV => new CsvDeserializationVisitor($instantiator, $mutator),
Format::JSON => new JsonDeserializationVisitor($instantiator, $mutator),
Format::XML => new XmlDeserializationVisitor($instantiator, $mutator),
Format::YAML => new YamlDeserializationVisitor($instantiator, $mutator),
],
], $visitors));
} | @param VisitorInterface[][] $visitors
@param InstantiatorInterface|null $instantiator
@param AccessorInterface|null $accessor
@param MutatorInterface|null $mutator
@return VisitorRegistryInterface | entailment |
public function registerVisitor($direction, $format, VisitorInterface $visitor)
{
if (!isset($this->visitors[$direction])) {
$this->visitors[$direction] = [];
}
$this->visitors[$direction][$format] = $visitor;
} | {@inheritdoc} | entailment |
public function getVisitor($direction, $format)
{
if (!isset($this->visitors[$direction]) || !isset($this->visitors[$direction][$format])) {
throw new \InvalidArgumentException(sprintf(
'The visitor for direction "%s" and format "%s" does not exist.',
$direction === Direction::SERIALIZATION ? 'serialization' : 'deserialization',
$format
));
}
return $this->visitors[$direction][$format];
} | {@inheritdoc} | entailment |
public function getConfigTreeBuilder()
{
if (\method_exists(TreeBuilder::class, 'getRootNode')) {
$treeBuilder = new TreeBuilder('accord_mandrill_swift_mailer');
$rootNode = $treeBuilder->getRootNode();
} else {
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('accord_mandrill_swift_mailer');
}
$rootNode
->children()
->scalarNode('api_key')->isRequired()->end()
->end()
->children()
->scalarNode('async')->defaultFalse()->info('Background sending mode that is optimized for bulk sending')->example(false)->end()
->end()
->children()
->scalarNode('subaccount')->defaultNull()->end()
->end()
;
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
} | {@inheritDoc} | entailment |
public function log(string $name, string $message, array $data = []): void
{
$filename = $this->dir . '/' . $name . '-' . date('Y-m-d') . '.log';
try {
$microtime = microtime(true);
$microtimeParts = explode('.', $microtime);
$logData = date('H:i:s', $microtime) . ':' . (isset($microtimeParts[1]) ? $microtimeParts[1] : '0') . "\n" . trim($message) . (empty($data) ? '' : "\n" . trim(print_r($data, true))) . "\n\n";
$fileHandler = fopen($filename, 'ab');
fwrite($fileHandler, $logData);
fclose($fileHandler);
} catch (\Exception $e) {
throw new \Exception('Cannot write log file (' . $filename . ')');
}
} | Logs the data specified.
@param string $name The name of the log context.
@param string $message The message that will be logged.
@param array $data Additional information to log.
@return void No value is returned. | entailment |
protected function loadData($class)
{
$reflection = new \ReflectionClass($class);
$result = $this->loadClass($reflection);
$properties = [];
foreach ($reflection->getMethods() as $method) {
if ($method->class !== $class) {
continue;
}
if (($methodName = $this->validateMethod($method->name)) === null) {
continue;
}
$data = $this->loadMethod($method);
if (is_array($data)) {
$properties[$methodName] = $data;
}
}
foreach ($reflection->getProperties() as $property) {
if ($property->class !== $class) {
continue;
}
$data = $this->loadProperty($property);
if (is_array($data)) {
$name = $property->getName();
$properties[$name] = isset($properties[$name])
? array_merge_recursive($properties[$name], $data)
: $data;
}
}
if (!empty($properties)) {
$result['properties'] = $properties;
}
if (!empty($result)) {
return $result;
}
} | {@inheritdoc} | entailment |
private function validateMethod($method)
{
$prefix = substr($method, 0, 3);
if ($prefix === 'get' || $prefix === 'set' || $prefix === 'has') {
return lcfirst(substr($method, 3));
}
$prefix = substr($prefix, 0, 2);
if ($prefix === 'is') {
return lcfirst(substr($method, 2));
}
} | @param string $method
@return string|null | entailment |
public function matchesRequest()
{
$noAttachments = Collection::make($this->event->get('attachments'))->isEmpty();
return $noAttachments && (! is_null($this->event->get('recipient')) && ! is_null($this->event->get('serviceUrl')));
} | Determine if the request is for this driver.
@return bool | entailment |
public function getMessages()
{
// replace bot's name for group chats and special characters that might be sent from Web Skype
$pattern = '/<at id=(.*?)at>[^(\x20-\x7F)\x0A]*\s*/';
$message = preg_replace($pattern, '', $this->event->get('text'));
if (empty($this->messages)) {
$this->messages = [
new IncomingMessage($message, $this->event->get('from')['id'], $this->event->get('conversation')['id'],
$this->payload),
];
}
return $this->messages;
} | Retrieve the chat message.
@return array | entailment |
private function convertQuestion(Question $question)
{
$replies = Collection::make($question->getButtons())->map(function ($button) {
return array_merge([
'type' => 'imBack',
'title' => $button['text'],
'value' => $button['text'].'<botman value="'.$button['value'].'" />',
], $button['additional']);
});
return $replies->toArray();
} | Convert a Question object into a valid Facebook
quick reply response object.
@param Question $question
@return array | entailment |
public function sendRequest($endpoint, array $parameters, IncomingMessage $matchingMessage)
{
$headers = [
'Content-Type:application/json',
'Authorization:Bearer '.$this->getAccessToken(),
];
$apiURL = Collection::make($matchingMessage->getPayload())->get('serviceUrl',
Collection::make($parameters)->get('serviceUrl'));
return $this->http->post($apiURL.'/v3/'.$endpoint, [], $parameters, $headers, true);
} | Low-level method to perform driver specific API requests.
@param string $endpoint
@param array $parameters
@param IncomingMessage $matchingMessage
@return Response | entailment |
public function until($function, $message = '')
{
$end = microtime(true) + $this->timeout;
$last_exception = null;
while ($end > microtime(true)) {
try {
$ret_val = call_user_func($function, $this->mailtrap);
if ($ret_val) {
return $ret_val;
}
} catch (\Exception $e) {
$last_exception = $e;
}
usleep($this->interval * 1000);
}
if ($last_exception) {
throw $last_exception;
}
throw new \Exception($message);
} | Calls the function provided with the driver as an argument until the return value is not falsey.
@param callable $function
@param string $message
@throws \Exception
@return mixed The return value of $function | entailment |
public function addEventListener(string $name, callable $listener): self
{
if (!isset($this->internalEventListenersData[$name])) {
$this->internalEventListenersData[$name] = [];
}
$this->internalEventListenersData[$name][] = $listener;
return $this;
} | Registers a new event listener.
@param string $name The name of the event.
@param callable $listener A listener callback.
@return self Returns a reference to itself. | entailment |
public function removeEventListener(string $name, callable $listener): self
{
if (isset($this->internalEventListenersData[$name])) {
foreach ($this->internalEventListenersData[$name] as $i => $value) {
if ($value === $listener) {
unset($this->internalEventListenersData[$name][$i]);
if (empty($this->internalEventListenersData[$name])) {
unset($this->internalEventListenersData[$name]);
}
break;
}
}
}
return $this;
} | Removes a registered event listener.
@param string $name The name of the event.
@param callable $listener A listener callback.
@return self Returns a reference to itself. | entailment |
public function dispatchEvent(string $name, $details = null): self
{
if (isset($this->internalEventListenersData[$name])) {
foreach ($this->internalEventListenersData[$name] as $listener) {
call_user_func($listener, $details);
}
}
return $this;
} | Calls the registered listeners (in order) for the event name specified.
@param string $name The name of the event.
@param mixed $details Additional event data.
@return self Returns a reference to itself. | entailment |
public function convert($name)
{
return isset($this->names[$name])
? $this->names[$name]
: $this->names[$name] = $this->doConvert($name);
} | {@inheritdoc} | entailment |
public function make(string $name = null, string $value = null): \BearFramework\App\Request\QueryItem
{
if ($this->newQueryItemCache === null) {
$this->newQueryItemCache = new \BearFramework\App\Request\QueryItem();
}
$object = clone($this->newQueryItemCache);
if ($name !== null) {
$object->name = $name;
}
if ($value !== null) {
$object->value = $value;
}
return $object;
} | Constructs a new query item and returns it.
@param string|null $name The name of the query item.
@param string|null $value The value of the query item.
@return \BearFramework\App\Request\QueryItem Returns a new query item. | entailment |
public function set(\BearFramework\App\Request\QueryItem $queryItem): self
{
$this->data[$queryItem->name] = $queryItem;
return $this;
} | Sets a query item.
@param \BearFramework\App\Request\QueryItem $query item The query item to set.
@return self Returns a reference to itself. | entailment |
public function getList()
{
$list = new \BearFramework\DataList();
foreach ($this->data as $queryItem) {
$list[] = clone($queryItem);
}
return $list;
} | Returns a list of all query items.
@return \BearFramework\DataList|\BearFramework\App\Request\QueryItem[] An array containing all query items. | entailment |
public function toString()
{
$temp = [];
foreach ($this->data as $queryItem) {
$temp[$queryItem->name] = $queryItem->value;
}
return http_build_query($temp);
} | Returns the query items as string.
@return string Returns the query items as string. | entailment |
public function add(string $class, string $filename): self
{
$this->appClasses->add($class, $this->dir . '/' . $filename);
return $this;
} | Registers a class for autoloading in the current context.
@param string $class The class name or class name pattern (format: Namespace\*).
@param string $filename The filename that contains the class or path pattern (format: path/to/file/*.php).
@return self Returns a reference to itself. | entailment |
public function getMessageData($key)
{
if ($this->{$key}) {
return $this->{$key};
}
$data_key = str_replace(['text_body', 'html_body'], ['txt_path', 'html_path'], $key);
$data = $this->retrieveMessageData($data_key);
if (!$data) {
return '';
}
$this->{$key} = $data;
return $data;
} | Get the body data for a message
@param $key
@return bool|mixed|null|string | entailment |
protected function retrieveMessageData($key)
{
$data = $this->client->get($this->data[$key])->getBody();
if ($data instanceof Stream) {
return $data->getContents();
}
return false;
} | Retrieve the body data from the MailTrap API
@param $key
@return bool|string | entailment |
public function prepare($data, ContextInterface $context)
{
$this->document = null;
$this->node = null;
$this->stack = [];
return parent::prepare($data, $context);
} | {@inheritdoc} | entailment |
public function visitFloat($data, TypeMetadataInterface $type, ContextInterface $context)
{
$data = (string) $data;
if (strpos($data, '.') === false) {
$data .= '.0';
}
return $this->visitText($data);
} | {@inheritdoc} | entailment |
public function visitString($data, TypeMetadataInterface $type, ContextInterface $context)
{
$document = $this->getDocument();
$data = (string) $data;
$node = strpos($data, '<') !== false || strpos($data, '>') !== false || strpos($data, '&') !== false
? $document->createCDATASection($data)
: $document->createTextNode($data);
return $this->visitNode($node);
} | {@inheritdoc} | entailment |
public function startVisitingObject($data, ClassMetadataInterface $class, ContextInterface $context)
{
$result = parent::startVisitingObject($data, $class, $context);
if ($result && $class->hasXmlRoot()) {
$this->getDocument($class->getXmlRoot());
}
return $result;
} | {@inheritdoc} | entailment |
public function getResult()
{
$document = $this->getDocument();
if ($document->formatOutput) {
$document->loadXML($document->saveXML());
}
return $document->saveXML();
} | {@inheritdoc} | entailment |
protected function doVisitObjectProperty(
$data,
$name,
PropertyMetadataInterface $property,
ContextInterface $context
) {
if (!$property->isReadable()) {
return false;
}
$value = $this->accessor->getValue(
$data,
$property->hasAccessor() ? $property->getAccessor() : $property->getName()
);
if ($value === null && $context->isNullIgnored()) {
return false;
}
$node = $this->createNode($name);
$this->enterNodeScope($node);
$this->navigator->navigate($value, $context, $property->getType());
$this->leaveNodeScope();
if ($property->isXmlAttribute()) {
$this->node->setAttribute($name, $node->nodeValue);
} elseif ($property->isXmlValue()) {
$this->visitNode($node->firstChild);
} elseif ($property->isXmlInline()) {
$children = $node->childNodes;
$count = $children->length;
for ($index = 0; $index < $count; ++$index) {
$this->visitNode($children->item(0));
}
} else {
$this->visitNode($node);
}
return true;
} | {@inheritdoc} | entailment |
protected function doVisitArray($data, TypeMetadataInterface $type, ContextInterface $context)
{
$entry = $this->entry;
$entryAttribute = $this->entryAttribute;
$keyAsAttribute = false;
$keyAsNode = true;
$metadataStack = $context->getMetadataStack();
$metadataIndex = count($metadataStack) - 2;
$metadata = isset($metadataStack[$metadataIndex]) ? $metadataStack[$metadataIndex] : null;
if ($metadata instanceof PropertyMetadataInterface) {
if ($metadata->hasXmlEntry()) {
$entry = $metadata->getXmlEntry();
}
if ($metadata->hasXmlEntryAttribute()) {
$entryAttribute = $metadata->getXmlEntryAttribute();
}
if ($metadata->hasXmlKeyAsAttribute()) {
$keyAsAttribute = $metadata->useXmlKeyAsAttribute();
}
if ($metadata->hasXmlKeyAsNode()) {
$keyAsNode = $metadata->useXmlKeyAsNode();
}
}
$valueType = $type->getOption('value');
$ignoreNull = $context->isNullIgnored();
$this->getDocument();
foreach ($data as $key => $value) {
if ($value === null && $ignoreNull) {
continue;
}
$node = $this->createNode($keyAsNode ? $key : $entry, $entry, $entryAttribute);
if ($keyAsAttribute) {
$node->setAttribute($entryAttribute, $key);
}
$this->enterNodeScope($node);
$this->navigator->navigate($value, $context, $valueType);
$this->leaveNodeScope();
$this->visitNode($node);
}
} | {@inheritdoc} | entailment |
private function visitNode(\DOMNode $node)
{
if ($this->node !== $node) {
$this->node->appendChild($node);
}
return $node;
} | @param \DOMNode $node
@return \DOMNode | entailment |
private function getDocument($root = null)
{
return $this->document !== null ? $this->document : $this->document = $this->createDocument($root);
} | @param string|null $root
@return \DOMDocument | entailment |
private function createNode($name, $entry = null, $entryAttribute = null)
{
$document = $this->getDocument();
try {
$node = $document->createElement($name);
} catch (\DOMException $e) {
$node = $document->createElement($entry ?: $this->entry);
if (is_string($name)) {
$node->setAttribute($entryAttribute ?: $this->entryAttribute, $name);
}
}
return $node;
} | @param string $name
@param string|null $entry
@param string|null $entryAttribute
@return \DOMElement | entailment |
private function createDocument($root = null)
{
$document = new \DOMDocument($this->version, $this->encoding);
$document->formatOutput = $this->formatOutput;
$this->node = $document->createElement($root ?: $this->root);
$document->appendChild($this->node);
return $document;
} | @param string|null $root
@return \DOMDocument | entailment |
protected function getHostChunks(Request $request)
{
$host = parse_url($request->getHostInfo(), PHP_URL_HOST);
return explode(self::SEPARATOR_HOST, $host);
} | Returns the "Host" header value splitted by the separator.
@see \cetver\LanguageUrlManager\UrlManager::SEPARATOR_HOST
@param Request $request the Request component instance.
@return array | entailment |
protected function setQueryParam(Request $request, $value)
{
$queryParams = $request->getQueryParams();
$queryParams[$this->queryParam] = $value;
$request->setQueryParams($queryParams);
} | Sets the query parameter that contains a language.
@param Request $request the Request component instance.
@param string $value a language value. | entailment |
protected function isBlacklisted($pathInfo)
{
$pathInfo = ltrim($pathInfo, self::SEPARATOR_PATH);
foreach ($this->blacklist as $pattern) {
if (preg_match($pattern, $pathInfo)) {
return true;
}
}
return false;
} | Returns whether the path info is blacklisted.
@see $blacklist
@param string $pathInfo the path info of the currently requested URL.
@return bool | entailment |
protected function getHtmlClasses()
{
$classes = '';
if( ! empty($this->css_classes) )
{
// open attribute
$classes.= " class=\"";
foreach($this->css_classes as $class)
{
$classes.="{$class} ";
}
// close attribute
$classes.= "\"";
}
return $classes;
} | Return the custom classes as html attribute
@return String | entailment |
protected function decode($data)
{
$internalErrors = libxml_use_internal_errors();
$disableEntityLoader = libxml_disable_entity_loader();
$this->setLibXmlState(true, true);
$document = simplexml_load_string($data);
if ($document === false) {
$errors = [];
foreach (libxml_get_errors() as $error) {
$errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
$error->level === LIBXML_ERR_WARNING ? 'WARNING' : 'ERROR',
$error->code,
trim($error->message),
$error->file ?: 'n/a',
$error->line,
$error->column
);
}
$this->setLibXmlState($internalErrors, $disableEntityLoader);
throw new \InvalidArgumentException(implode(PHP_EOL, $errors));
}
$this->setLibXmlState($internalErrors, $disableEntityLoader);
return $document;
} | {@inheritdoc} | entailment |
protected function doVisitArray($data, TypeMetadataInterface $type, ContextInterface $context)
{
$this->result = [];
$entry = $this->entry;
$entryAttribute = $this->entryAttribute;
$keyAsAttribute = false;
$inline = false;
$metadataStack = $context->getMetadataStack();
$metadataIndex = count($metadataStack) - 2;
$metadata = isset($metadataStack[$metadataIndex]) ? $metadataStack[$metadataIndex] : null;
if ($metadata instanceof PropertyMetadataInterface) {
$inline = $metadata->isXmlInline();
if ($metadata->hasXmlEntry()) {
$entry = $metadata->getXmlEntry();
}
if ($metadata->hasXmlEntryAttribute()) {
$entryAttribute = $metadata->getXmlEntryAttribute();
}
if ($metadata->hasXmlKeyAsAttribute()) {
$keyAsAttribute = $metadata->useXmlKeyAsAttribute();
}
}
$keyType = $type->getOption('key');
$valueType = $type->getOption('value');
if ($data instanceof \SimpleXMLElement && !$inline) {
$data = $data->children();
}
foreach ($data as $key => $value) {
$result = $value;
$isElement = $value instanceof \SimpleXMLElement;
if ($isElement && $valueType === null) {
$result = $this->visitNode($value, $entry);
}
$result = $this->navigator->navigate($result, $context, $valueType);
if ($result === null && $context->isNullIgnored()) {
continue;
}
if ($key === $entry) {
$key = null;
}
if ($isElement && ($keyAsAttribute || $key === null)) {
$attributes = $value->attributes();
$key = isset($attributes[$entryAttribute]) ? $this->visitNode($attributes[$entryAttribute]) : null;
}
$key = $this->navigator->navigate($key, $context, $keyType);
if ($key === null) {
$this->result[] = $result;
} else {
$this->result[$key] = $result;
}
}
return $this->result;
} | {@inheritdoc} | entailment |
protected function doVisitObjectProperty(
$data,
$name,
PropertyMetadataInterface $property,
ContextInterface $context
) {
if ($property->isXmlInline() && $property->useXmlKeyAsNode()) {
return false;
}
if ($property->isXmlAttribute()) {
return parent::doVisitObjectProperty($data->attributes(), $name, $property, $context);
}
if ($property->isXmlValue()) {
return parent::doVisitObjectProperty([$name => $data], $name, $property, $context);
}
$key = $name;
if ($property->isXmlInline()) {
$key = $property->hasXmlEntry() ? $property->getXmlEntry() : $this->entry;
}
if (!isset($data->$key)) {
return false;
}
$data = $data->$key;
if ($data->count() === 1 && (string) $data === '') {
return false;
}
return parent::doVisitObjectProperty([$name => $data], $name, $property, $context);
} | {@inheritdoc} | entailment |
private function visitNode(\SimpleXMLElement $data, $entry = null)
{
if ($data->count() === 0) {
$data = (string) $data;
return $data !== '' ? $data : null;
}
$result = [];
$entry = $entry ?: $this->entry;
foreach ($data as $value) {
$key = $value->getName();
if ($key === $entry) {
$result[] = $value;
} elseif (isset($result[$key])) {
if (!is_array($result[$key])) {
$result[$key] = [$result[$key]];
}
$result[$key][] = $value;
} else {
$result[$key] = $value;
}
}
return $result;
} | @param \SimpleXMLElement $data
@param string|null $entry
@return mixed | entailment |
public function getImpersonatingUser()
{
if ($this->isGranted('ROLE_PREVIOUS_ADMIN')) {
foreach ($this->tokenStorage->getToken()->getRoles() as $role) {
if ($role instanceof SwitchUserRole) {
return $role->getSource()->getUser();
}
}
}
} | When impersonating a user, it returns the original user who started
the impersonation.
@return mixed | entailment |
public function hasRole($role, $user = null)
{
$roleName = $role instanceof Role ? $role->getRole() : $role;
$user = $user ?: $this->getUser();
if (!($user instanceof UserInterface)) {
return false;
}
if (null === $this->roleHierarchy) {
return in_array($roleName, $user->getRoles(), true);
}
$userRoles = $this->roleHierarchy->getReachableRoles($this->getUserRolesAsObjects($user));
foreach ($userRoles as $userRole) {
if ($roleName === $userRole->getRole()) {
return true;
}
}
return false;
} | Returns true if the current application user (or the optionally given user)
has the given role. It takes into account the full role hierarchy.
@param $role
@param null $user
@return bool | entailment |
public function isRemembered($user = null)
{
$user = $user ?: $this->getUser();
if ($this->isFullyAuthenticated($user)) {
return false;
}
return $this->isGranted('IS_AUTHENTICATED_REMEMBERED', $user);
} | Returns true if the current application user (or the optionally given user)
is remembered. This behaves differently than Symfony built-in methods and
it returns true only when the user is really remembered and they haven't
introduced their credentials (username and password).
@param null $user
@return bool | entailment |
public function isFullyAuthenticated($user = null)
{
$user = $user ?: $this->getUser();
return $this->isGranted('IS_AUTHENTICATED_FULLY', $user);
} | Returns true if the current application user (or the optionally given user)
is authenticated because they have introduced their credentials (username
and password).
@param null $user
@return bool | entailment |
public function isAuthenticated($user = null)
{
$user = $user ?: $this->getUser();
return $this->isGranted('IS_AUTHENTICATED_FULLY', $user) || $this->isGranted('IS_AUTHENTICATED_REMEMBERED', $user);
} | Returns true if the current application user (or the optionally given user)
is authenticated in any way (because they have introduced their credentials
(username and password) or they have been remembered).
@param null $user
@return bool | entailment |
public function login(UserInterface $user, $firewallName = 'main')
{
$token = new UsernamePasswordToken($user, $user->getPassword(), $firewallName, $user->getRoles());
$this->tokenStorage->setToken($token);
return $user;
} | It logs in the given user in the 'main' application firewall (or the
optionally given firewall name).
@param UserInterface $user
@param string $firewallName
@return UserInterface | entailment |
public function encodePassword($plainPassword, $user = null)
{
$user = $user ?: $this->getUser();
return $this->passwordEncoder->encodePassword($user, $plainPassword);
} | Returns the given plain password encoded/hashed using the encoder of the
current application user or the optionally given user.
@param string $plainPassword
@param null $user
@return string | entailment |
public function isPasswordValid($plainPassword, $user = null)
{
$user = $user ?: $this->getUser();
return $this->passwordEncoder->isPasswordValid($user, $plainPassword);
} | Returns true if the given plain password is valid for the current
application user or the optionally given user.
@param string $plainPassword
@param null $user
@return bool | entailment |
private function getUserRolesAsObjects(UserInterface $user)
{
$userRoles = array();
foreach ($user->getRoles() as $userRole) {
$userRoles[] = $userRole instanceof Role ? $userRole : new Role($userRole);
}
return $userRoles;
} | Returns an array with the roles of the given user turned into Role objects,
which are needed by methods such as getReachableRoles().
@param UserInterface $user
@return RoleInterface[] | entailment |
public function convert($data, TypeMetadataInterface $type, ContextInterface $context)
{
$visitor = $context->getVisitor();
if ($context->getDirection() === Direction::SERIALIZATION) {
return $visitor->visitArray((array) $data, $type, $context);
}
return (object) $visitor->visitArray($data, $type, $context);
} | {@inheritdoc} | entailment |
public function guess($data)
{
return new TypeMetadata(is_object($data) ? get_class($data) : strtolower(gettype($data)));
} | {@inheritdoc} | entailment |
public function getSegment($index): ?string
{
$path = trim($this->path, '/');
if (isset($path{0})) {
$parts = explode('/', $path);
if (array_key_exists($index, $parts)) {
return $parts[$index];
}
}
return null;
} | Returns the value of the path segment for the index specified or null if not found.
@param int $index the index of the path segment.
@return string|null The value of the path segment for the index specified or null if not found. | entailment |
public function match($pattern): bool
{
$requestPath = $this->path;
$patterns = is_array($pattern) ? $pattern : [$pattern];
foreach ($patterns as $pattern) {
if (preg_match('/^' . str_replace(['/', '?', '*'], ['\/', '[^\/]+?', '.+?'], $pattern) . '$/u', $requestPath) === 1) {
return true;
}
}
return false;
} | Checks if the current path matches the pattern/patterns specified.
@param string|string[] $pattern Path pattern or array of patterns. Can contain "?" (path segment) and "*" (matches everything).
@return bool Returns TRUE if the current path matches the pattern provided/ | entailment |
public function visitArray($data, TypeMetadataInterface $type, ContextInterface $context)
{
$context->enterScope($data, $type);
if ($context->getExclusionStrategy()->skipType($type, $context)) {
$data = [];
}
$result = $this->doVisitArray($data, $type, $context);
$context->leaveScope();
return $result;
} | {@inheritdoc} | entailment |
public function visitBoolean($data, TypeMetadataInterface $type, ContextInterface $context)
{
return $this->visitData((bool) $data, $type, $context);
} | {@inheritdoc} | entailment |
public function visitFloat($data, TypeMetadataInterface $type, ContextInterface $context)
{
return $this->visitData((float) $data, $type, $context);
} | {@inheritdoc} | entailment |
public function visitInteger($data, TypeMetadataInterface $type, ContextInterface $context)
{
return $this->visitData((int) $data, $type, $context);
} | {@inheritdoc} | entailment |
public function visitNull($data, TypeMetadataInterface $type, ContextInterface $context)
{
return $this->visitData(null, $type, $context);
} | {@inheritdoc} | entailment |
public function visitString($data, TypeMetadataInterface $type, ContextInterface $context)
{
return $this->visitData((string) $data, $type, $context);
} | {@inheritdoc} | entailment |
public function startVisitingObject($data, ClassMetadataInterface $class, ContextInterface $context)
{
$context->enterScope($data, $class);
if ($context->getExclusionStrategy()->skipClass($class, $context)) {
$context->leaveScope();
return false;
}
return true;
} | {@inheritdoc} | entailment |
public function visitObjectProperty($data, PropertyMetadataInterface $property, ContextInterface $context)
{
$visited = false;
if (!$context->getExclusionStrategy()->skipProperty($property, $context)) {
$context->enterScope($data, $property);
$name = $property->hasAlias()
? $property->getAlias()
: $context->getNamingStrategy()->convert($property->getName());
$visited = $this->doVisitObjectProperty($data, $name, $property, $context);
$context->leaveScope();
}
return $visited;
} | {@inheritdoc} | entailment |
public function set(DataItem $item): void
{
$command = [
'command' => 'set',
'key' => $item->key,
'body' => $item->value,
'metadata.*' => ''
];
$metadataAsArray = $item->metadata->toArray();
foreach ($metadataAsArray as $name => $value) {
$command['metadata.' . $name] = $value;
}
$this->execute([$command]);
} | Stores a data item.
@param \BearFramework\App\DataItem $item The data item to store.
@return void No value is returned.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function setValue(string $key, string $value): void
{
$this->execute([
[
'command' => 'set',
'key' => $key,
'body' => $value
]
]);
} | Sets a new value of the item specified or creates a new item with the key and value specified.
@param string $key The key of the data item.
@param string $value The value of the data item.
@return void No value is returned.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function get(string $key): ?\BearFramework\App\DataItem
{
$result = $this->execute([
[
'command' => 'get',
'key' => $key,
'result' => ['key', 'body', 'metadata']
]
]);
if (isset($result[0]['key'])) {
return $this->makeDataItemFromRawData($result[0]);
}
return null;
} | Returns a stored data item or null if not found.
@param string $key The key of the stored data item.
@return \BearFramework\App\DataItem|null A data item or null if not found.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function getValue(string $key): ?string
{
$result = $this->execute([
[
'command' => 'get',
'key' => $key,
'result' => ['body']
]
]);
if (isset($result[0]['body'])) {
return $result[0]['body'];
}
return null;
} | Returns the value of a stored data item or null if not found.
@param string $key The key of the stored data item.
@return string|null The value of a stored data item or null if not found.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function exists(string $key): bool
{
$result = $this->execute([
[
'command' => 'get',
'key' => $key,
'result' => ['key']
]
]);
return isset($result[0]['key']);
} | Returns TRUE if the data item exists. FALSE otherwise.
@param string $key The key of the stored data item.
@return bool TRUE if the data item exists. FALSE otherwise.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function append(string $key, string $content): void
{
$this->execute([
[
'command' => 'append',
'key' => $key,
'body' => $content
]
]);
} | Appends data to the data item's value specified. If the data item does not exist, it will be created.
@param string $key The key of the data item.
@param string $content The content to append.
@return void No value is returned.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function duplicate(string $sourceKey, string $destinationKey): void
{
$this->execute([
[
'command' => 'duplicate',
'sourceKey' => $sourceKey,
'targetKey' => $destinationKey
]
]);
} | Creates a copy of the data item specified.
@param string $sourceKey The key of the source data item.
@param string $destinationKey The key of the destination data item.
@return void No value is returned.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function rename(string $sourceKey, string $destinationKey): void
{
$this->execute([
[
'command' => 'rename',
'sourceKey' => $sourceKey,
'targetKey' => $destinationKey
]
]);
} | Changes the key of the data item specified.
@param string $sourceKey The current key of the data item.
@param string $destinationKey The new key of the data item.
@return void No value is returned.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function setMetadata(string $key, string $name, string $value): void
{
$this->execute([
[
'command' => 'set',
'key' => $key,
'metadata.' . $name => $value
]
]);
} | Stores metadata for the data item specified.
@param string $key The key of the data item.
@param string $name The metadata name.
@param string $value The metadata value.
@return void No value is returned.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function getMetadata(string $key, string $name): ?string
{
$result = $this->execute([
[
'command' => 'get',
'key' => $key,
'result' => ['metadata.' . $name]
]
]
);
return isset($result[0]['metadata.' . $name]) ? $result[0]['metadata.' . $name] : null;
} | Retrieves metadata for the data item specified.
@param string $key The data item key.
@param string $name The metadata name.
@return string|null The value of the data item metadata.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function deleteMetadata(string $key, string $name): void
{
$this->execute([
[
'command' => 'set',
'key' => $key,
'metadata.' . $name => ''
]
]);
} | Deletes metadata for the data item key specified.
@param string $key The data item key.
@param string $name The metadata name.
@return void No value is returned.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function getList(\BearFramework\DataList\Context $context = null): \BearFramework\DataList
{
$whereOptions = [];
$resultKeys = [];
if ($context !== null) {
$limit = null;
foreach ($context->actions as $action) {
if ($action instanceof \BearFramework\DataList\FilterByAction) {
$whereOptions[] = [$action->property, $action->value, $action->operator];
} elseif ($action instanceof \BearFramework\DataList\SlicePropertiesAction) {
foreach ($action->properties as $requestedProperty) {
if ($requestedProperty === 'key') {
$resultKeys[] = 'key';
} elseif ($requestedProperty === 'value') {
$resultKeys[] = 'body';
} elseif ($requestedProperty === 'metadata') {
$resultKeys[] = 'metadata';
}
}
} elseif ($action instanceof \BearFramework\DataList\SliceAction) {
$limit = $action->offset + $action->limit;
}
}
}
$resultKeys = empty($resultKeys) ? ['key', 'body', 'metadata'] : array_unique(array_merge(['key'], $resultKeys));
$executeArgs = [
'command' => 'search',
'where' => $whereOptions,
'result' => $resultKeys
];
if ($limit !== null) {
$executeArgs['limit'] = $limit;
}
$result = $this->execute([$executeArgs]);
$list = new \BearFramework\DataList();
foreach ($result[0] as $rawData) {
$list[] = $this->makeDataItemFromRawData($rawData);
}
return $list;
} | Returns a list of all items in the data storage.
@param \BearFramework\DataList\Context|null $context
@return \BearFramework\DataList|\BearFramework\App\DataItem[] A list of all items in the data storage.
@throws \Exception
@throws \BearFramework\App\Data\DataLockedException | entailment |
public function getDataItemStreamWrapper(string $key): \BearFramework\App\IDataItemStreamWrapper
{
return new \BearFramework\App\FileDataItemStreamWrapper($key, $this->dir);
} | Returns a DataItemStreamWrapper for the key specified.
@param string $key The data item key.
@return \BearFramework\App\IDataItemStreamWrapper | entailment |
protected function checkLimits($numerator, $denominator)
{
if (($max = max(abs($numerator), abs($denominator))) < PHP_INT_MAX) {
return [$numerator, $denominator];
}
$divisor = min(
abs($this->getDivisor($max)),
abs($numerator),
abs($denominator)
);
return [
intval($numerator / $divisor),
intval($denominator / $divisor),
];
} | Check limits
@param mixed $numerator
@param mixed $denominator
@return array | entailment |
private function simplify()
{
$gcd = $this->getGreatestCommonDivisor();
$this->numerator /= $gcd;
$this->denominator /= $gcd;
} | Simplify
e.g. transform 2/4 into 1/2
@author Tom Haskins-Vaughan <[email protected]>
@since 0.1.0
@return integer | entailment |
public function multiply(Fraction $fraction)
{
$numerator = $this->getNumerator() * $fraction->getNumerator();
$denominator = $this->getDenominator() * $fraction->getDenominator();
return new static($numerator, $denominator);
} | Multiply this fraction by a given fraction
@author Tom Haskins-Vaughan <[email protected]>
@since 0.1.0
@param Fraction $fraction
@return Fraction | entailment |
public function divide(Fraction $fraction)
{
$numerator = $this->getNumerator() * $fraction->getDenominator();
$denominator = $this->getDenominator() * $fraction->getNumerator();
if ($denominator < 0) {
$numerator *= -1;
}
return new static($numerator, abs($denominator));
} | Divide this fraction by a given fraction
@author Tom Haskins-Vaughan <[email protected]>
@since 0.1.0
@param Fraction $fraction
@return Fraction | entailment |
public function add(Fraction $fraction)
{
$numerator = ($this->getNumerator() * $fraction->getDenominator())
+ ($fraction->getNumerator() * $this->getDenominator());
$denominator = $this->getDenominator()
* $fraction->getDenominator();
return new static($numerator, $denominator);
} | Add this fraction to a given fraction
@author Tom Haskins-Vaughan <[email protected]>
@since 0.1.0
@param Fraction $fraction
@return Fraction | entailment |
public function subtract(Fraction $fraction)
{
$numerator = ($this->getNumerator() * $fraction->getDenominator())
- ($fraction->getNumerator() * $this->getDenominator());
$denominator = $this->getDenominator()
* $fraction->getDenominator();
return new static($numerator, $denominator);
} | Subtract a given fraction from this fraction
@author Tom Haskins-Vaughan <[email protected]>
@since 0.1.0
@param Fraction $fraction
@return Fraction | entailment |
public static function fromFloat($float)
{
if (is_int($float)) {
return new self($float);
}
if (!is_numeric($float)) {
throw new InvalidArgumentException(
'Argument passed is not a numeric value.'
);
}
// Make sure the float is a float not scientific notation.
// Limit a max of 8 chars to prevent float errors
$float = rtrim(sprintf('%.8F', $float), '0');
// Find and grab the decimal space and everything after it
$denominator = strstr($float, '.');
// Pad a one with zeros for the length of the decimal places
// ie 0.1 = 10; 0.02 = 100; 0.01234 = 100000;
$denominator = (int) str_pad('1', strlen($denominator), '0');
// Multiply to get rid of the decimal places.
$numerator = (int) ($float*$denominator);
return new self($numerator, $denominator);
} | Create from float
@author Christopher Tatro <[email protected]>
@since 0.2.0
@param float $float
return Fraction | entailment |
public static function fromString($string)
{
if (preg_match(self::PATTERN_FROM_STRING, trim($string), $matches)) {
if (2 === count($matches)) {
// whole number
return new self((int) $matches[1]);
} else {
// either x y/z or x/y
if ($matches[2]) {
// x y/z
$whole = new self((int) $matches[1]);
return $whole->add(new self(
(int) $matches[2],
(int) $matches[3]
));
}
// x/y
return new self((int) $matches[1], (int) $matches[3]);
}
}
throw new InvalidArgumentException(sprintf(
'Cannot parse "%s"',
$string
));
} | Create from string, e.g.
* 1/3
* 1/20
* 40
* 3 4/5
* 20 34/67
@author Tom Haskins-Vaughan <[email protected]>
@since 0.4.0
@param string $string
return Fraction | entailment |
public function isSameValueAs(Fraction $fraction)
{
if ($this->getNumerator() != $fraction->getNumerator()) {
return false;
}
if ($this->getDenominator() != $fraction->getDenominator()) {
return false;
}
return true;
} | isSameValueAs
ValueObject comparison
@author Christopher Tatro <[email protected]>
@since 1.1.0
@param Fraction $fraction
@return bool | entailment |
public function getValue($object, $property)
{
if (property_exists($object, $property)) {
return $this->getReflectionProperty($object, $property)->getValue($object);
}
return $this->getMethodValue($object, $property);
} | {@inheritdoc} | entailment |
private function getMethodValue($object, $property)
{
$methods = [$property];
if (method_exists($object, $property)) {
return $this->getReflectionMethod($object, $property)->invoke($object);
}
$methodSuffix = ucfirst($property);
foreach (['get', 'has', 'is'] as $methodPrefix) {
$methods[] = $method = $methodPrefix.$methodSuffix;
if (method_exists($object, $method)) {
return $this->getReflectionMethod($object, $method)->invoke($object);
}
}
throw new \InvalidArgumentException(sprintf(
'The property "%s" or methods %s don\'t exist on class "%s".',
$property,
'"'.implode('", "', $methods).'"',
get_class($object)
));
} | @param object $object
@param string $property
@return mixed | entailment |
public function convert($data, TypeMetadataInterface $type, ContextInterface $context)
{
return $context->getVisitor()->visitNull($data, $type, $context);
} | {@inheritdoc} | entailment |
public function convert($data, TypeMetadataInterface $type, ContextInterface $context)
{
$result = $context->getDirection() === Direction::SERIALIZATION
? $this->serialize($data, $type, $context)
: $this->deserialize($data, $type, $context);
return $context->getVisitor()->visitData($result, $type, $context);
} | {@inheritdoc} | entailment |
private function serialize($data, TypeMetadataInterface $type, ContextInterface $context)
{
$class = $type->getName();
if (!$data instanceof $class) {
throw new \InvalidArgumentException(sprintf(
'Expected a "%s", got "%s".',
$class,
is_object($data) ? get_class($data) : gettype($data)
));
}
$result = $data->format($format = $type->getOption('format', $this->format));
if ($result === false) {
throw new \InvalidArgumentException(sprintf('The date format "%s" is not valid.', $format));
}
return $result;
} | @param \DateTimeInterface $data
@param TypeMetadataInterface $type
@param ContextInterface $context
@return string | entailment |
private function deserialize($data, TypeMetadataInterface $type, ContextInterface $context)
{
$class = $type->getName();
if (!method_exists($class, 'createFromFormat')) {
throw new \InvalidArgumentException(sprintf(
'The method "%s" does not exist on "%s".',
'createFromFormat',
$class
));
}
if (!method_exists($class, 'getLastErrors')) {
throw new \InvalidArgumentException(sprintf(
'The method "%s" does not exist on "%s".',
'getLastErrors',
$class
));
}
$result = $class::createFromFormat(
$format = $type->getOption('format', $this->format),
(string) $data,
$timezone = new \DateTimeZone($type->getOption('timezone', $this->timeZone))
);
$errors = $class::getLastErrors();
if (!empty($errors['warnings']) || !empty($errors['errors'])) {
throw new \InvalidArgumentException(sprintf(
'The date "%s" with format "%s" and timezone "%s" is not valid.',
$data,
$format,
$timezone->getName()
));
}
return $result;
} | @param mixed $data
@param TypeMetadataInterface $type
@param ContextInterface $context
@return \DateTimeInterface | entailment |
public function addDir(string $pathname): self
{
$this->dirs[] = $pathname;
$this->optimizedDirs = null;
return $this;
} | Registers a directory that will be publicly accessible.
@param string $pathname The directory name.
@return self Returns a reference to itself.
@see BearFramework\App
@see BearFramework\App\DataRepository::validate
@see BearFramework\App\DataRepository::set()
@example Routes.php description | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.