text
stringlengths 52
3.87M
|
---|
public function delete($_id = NULL)
{
if ($_id) {
$this->_id = $_id;
}
$parameters = [
"id" => $this->_id,
'client' => ['ignore' => $this->ignores]
];
if ($index = $this->getIndex()) {
$parameters["index"] = $index;
}
if ($type = $this->getType()) {
$parameters["type"] = $type;
}
return (object)$this->connection->delete($parameters);
} |
function exists()
{
$index = new Index($this->index);
$index->connection = $this->connection;
return $index->exists();
} |
function createIndex($name, $callback = false)
{
$index = new Index($name, $callback);
$index->connection = $this->connection;
return $index->create();
} |
function dropIndex($name)
{
$index = new Index($name);
$index->connection = $this->connection;
return $index->drop();
} |
function create($callback = false)
{
$index = new Index($this->index, $callback);
$index->connection = $this->connection;
return $index->create();
} |
function drop()
{
$index = new Index($this->index);
$index->connection = $this->connection;
return $index->drop();
} |
public function action($actionType, $data = [])
{
$this->body["body"][] = [
$actionType => [
'_index' => $this->getIndex(),
'_type' => $this->getType(),
'_id' => $this->_id
]
];
if (!empty($data)) {
if($actionType == "update"){
$this->body["body"][] = ["doc" => $data];
}else {
$this->body["body"][] = $data;
}
}
$this->operationCount++;
$this->reset();
if ($this->autocommitAfter > 0 && $this->operationCount >= $this->autocommitAfter) {
return $this->commit();
}
return true;
} |
public function commit()
{
if (empty($this->body)) {
return false;
}
$result = $this->query->connection->bulk($this->body);
$this->operationCount = 0;
$this->body = [];
return $result;
} |
public function links($view = "default", $data = [])
{
extract($data);
$paginator = $this;
$elements = $this->elements();
require dirname(__FILE__) . "/pagination/" . $view . ".php";
} |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('m6web_api_exception');
$rootNode
->children()
->booleanNode('stack_trace')->defaultValue(false)->end()
->booleanNode('match_all')->defaultValue(true)->end()
->arrayNode('default')
->addDefaultsIfNotSet()
->children()
->integerNode('code')->defaultValue(0)->end()
->integerNode('status')->defaultValue(500)->end()
->scalarNode('message')->defaultValue('Internal server error')->end()
->arrayNode('headers')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->defaultValue([])
->end()
->end()
->end()
->arrayNode('exceptions')
->useAttributeAsKey('name')
->prototype('array')
->children()
->integerNode('code')->end()
->integerNode('status')->end()
->scalarNode('message')->end()
->arrayNode('headers')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
} |
public function configure(ExceptionInterface $exception)
{
$exceptionName = get_class($exception);
$configException = $this->getConfigException($exceptionName);
$exception->setCode($configException['code']);
$exception->setMessage($configException['message']);
if ($exception instanceof HttpExceptionInterface) {
$exception->setStatusCode($configException['status']);
$exception->setHeaders($configException['headers']);
}
return $exception;
} |
protected function getConfigException($exceptionName)
{
$exceptionParentName = get_parent_class($exceptionName);
if (in_array(
'M6Web\Bundle\ApiExceptionBundle\Exception\Interfaces\ExceptionInterface',
class_implements($exceptionParentName)
)) {
$parentConfig = $this->getConfigException($exceptionParentName);
} else {
$parentConfig = $this->defaultConfig;
}
if (isset($this->exceptions[$exceptionName])) {
return array_merge($parentConfig, $this->exceptions[$exceptionName]);
}
return $parentConfig;
} |
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$this->loadExceptionManager($container, $config);
$this->loadExceptionListener($container, $config);
} |
protected function loadExceptionManager(ContainerBuilder $container, array $config)
{
$definition = new Definition(
'M6Web\Bundle\ApiExceptionBundle\Manager\ExceptionManager',
[
$config['default'],
$config['exceptions'],
]
);
$definition->setPublic(true);
$container->setDefinition($this->getAlias().'.manager.exception', $definition);
} |
protected function loadExceptionListener(ContainerBuilder $container, array $config)
{
$definition = new Definition(
'M6Web\Bundle\ApiExceptionBundle\EventListener\ExceptionListener',
[
new Reference('kernel'),
new Reference($this->getAlias().'.manager.exception'),
$config['match_all'],
$config['default'],
$config['stack_trace'],
]
);
$definition->setPublic(true);
$definition->addTag(
'kernel.event_listener',
[
'event' => 'kernel.exception',
'method' => 'onKernelException',
'priority' => '-100' // as the setResponse stop the exception propagation, this listener has to pass in last position
]
);
$container->setDefinition($this->getAlias().'.listener.exception', $definition);
} |
public function getMessageWithVariables()
{
$message = $this->message;
preg_match(self::VARIABLE_REGEX, $message, $variables);
foreach ($variables as $variable) {
$variableName = substr($variable, 1, -1);
if (!isset($this->$variableName)) {
throw new \Exception(sprintf(
'Variable "%s" for exception "%s" not found',
$variableName,
get_class($this)
), 500);
}
if (!is_string($this->$variableName)) {
throw new \Exception(sprintf(
'Variable "%s" for exception "%s" must be a string, %s found',
$variableName,
get_class($this),
gettype($this->$variableName)
), 500);
}
$message = str_replace($variable, $this->$variableName, $message);
}
return $message;
} |
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if (!($event->getRequest())
|| ($this->matchAll === false && !$this->isApiException($exception))
) {
return;
}
$data = [];
if ($this->isApiException($exception)) {
$exception = $this->exceptionManager->configure($exception);
}
$statusCode = $this->getStatusCode($exception);
$data['error']['status'] = $statusCode;
if ($code = $exception->getCode()) {
$data['error']['code'] = $code;
}
$data['error']['message'] = $this->getMessage($exception);
if ($this->isFlattenErrorException($exception)) {
$data['error']['errors'] = $exception->getFlattenErrors();
}
if ($this->stackTrace) {
$data['error']['stack_trace'] = $exception->getTrace();
// Clean stacktrace to avoid circular reference or invalid type
array_walk_recursive(
$data['error']['stack_trace'],
function(&$item) {
if (is_object($item)) {
$item = get_class($item);
} elseif (is_resource($item)) {
$item = get_resource_type($item);
}
}
);
}
$response = new JsonResponse($data, $statusCode, $this->getHeaders($exception));
$event->setResponse($response);
} |
private function getStatusCode(\Exception $exception)
{
$statusCode = $this->default['status'];
if ($exception instanceof SymfonyHttpExceptionInterface
|| $exception instanceof HttpExceptionInterface
) {
$statusCode = $exception->getStatusCode();
}
return $statusCode;
} |
private function getMessage(\Exception $exception)
{
$message = $exception->getMessage();
if ($this->isApiException($exception)) {
$message = $exception->getMessageWithVariables();
}
return $message;
} |
private function getHeaders(\Exception $exception)
{
$headers = $this->default['headers'];
if ($exception instanceof SymfonyHttpExceptionInterface
|| $exception instanceof HttpExceptionInterface
) {
$headers = $exception->getHeaders();
}
return $headers;
} |
public function getFlattenErrors(FormInterface $form = null, $subForm = false)
{
$form = $form ?: $this->form;
$flatten = [];
foreach ($form->getErrors() as $error) {
if ($subForm) {
$flatten[] = $error->getMessage();
} else {
$path = $error->getCause()->getPropertyPath();
if (!array_key_exists($path, $flatten)) {
$flatten[$path] = [$error->getMessage()];
continue;
}
$flatten[$path][] = $error->getMessage();
}
}
$subForm = true;
foreach ($form->all() as $key => $child) {
$childErrors = $this->getFlattenErrors($child, $subForm);
if (!empty($childErrors)) {
$flatten[$key] = $childErrors;
}
}
return $flatten;
} |
protected function processParts(array $parts)
{
$strValue = '';
$ret = [];
$filtered = $this->filterIgnoredSpaces($parts);
foreach ($filtered as $part) {
if ($part instanceof CommentPart) {
$ret[] = $part;
continue; // getValue() is empty anyway, but for clarity...
}
$strValue .= $part->getValue();
}
array_unshift($ret, $this->partFactory->newReceivedPart($this->getPartName(), $strValue));
return $ret;
} |
public function getAddress($index)
{
if (!isset($this->addresses[$index])) {
return null;
}
return $this->addresses[$index];
} |
protected function processParts(array $parts)
{
$comment = '';
foreach ($parts as $part) {
// order is important here - CommentPart extends LiteralPart
if ($part instanceof CommentPart) {
$comment .= '(' . $part->getComment() . ')';
} elseif ($part instanceof LiteralPart) {
$comment .= '"' . $part->getValue() . '"';
} else {
$comment .= $part->getValue();
}
}
return [$this->partFactory->newCommentPart($comment)];
} |
private function matchHostPart($value, &$hostname, &$address) {
$matches = [];
$pattern = '~^(?P<name>[a-z0-9\-]+\.[a-z0-9\-\.]+)?\s*(\[(IPv[64])?(?P<addr>[a-f\d\.\:]+)\])?$~i';
if (preg_match($pattern, $value, $matches)) {
if (!empty($matches['name'])) {
$hostname = $matches['name'];
}
if (!empty($matches['addr'])) {
$address = $matches['addr'];
}
return true;
}
return false;
} |
protected function processParts(array $parts)
{
$ehloName = null;
$hostname = null;
$address = null;
$commentPart = null;
$filtered = $this->filterIgnoredSpaces($parts);
foreach ($filtered as $part) {
if ($part instanceof CommentPart) {
$commentPart = $part;
continue;
}
$ehloName .= $part->getValue();
}
$strValue = $ehloName;
if ($commentPart !== null && $this->matchHostPart($commentPart->getComment(), $hostname, $address)) {
$strValue .= ' (' . $commentPart->getComment() . ')';
$commentPart = null;
}
$domainPart = $this->partFactory->newReceivedDomainPart(
$this->getPartName(),
$strValue,
$ehloName,
$hostname,
$address
);
return array_filter([ $domainPart, $commentPart ]);
} |
protected function extractMetaInformationAndValue($value, $index)
{
if (preg_match('~^([^\']*)\'([^\']*)\'(.*)$~', $value, $matches)) {
if ($index === 0) {
$this->charset = (!empty($matches[1])) ? $matches[1] : $this->charset;
$this->language = (!empty($matches[2])) ? $matches[2] : $this->language;
}
$value = $matches[3];
}
$this->encodedParts[$index] = $value;
} |
public function addPart($value, $isEncoded, $index)
{
if (empty($index)) {
$index = 0;
}
if ($isEncoded) {
$this->extractMetaInformationAndValue($value, $index);
} else {
$this->literalParts[$index] = $this->convertEncoding($value);
}
} |
private function getNextEncodedValue()
{
$cur = current($this->encodedParts);
$key = key($this->encodedParts);
$running = '';
while ($cur !== false) {
$running .= $cur;
$cur = next($this->encodedParts);
$nKey = key($this->encodedParts);
if ($nKey !== $key + 1) {
break;
}
$key = $nKey;
}
return $this->convertEncoding(
rawurldecode($running),
$this->charset,
true
);
} |
public function getValue()
{
$parts = $this->literalParts;
reset($this->encodedParts);
ksort($this->encodedParts);
while (current($this->encodedParts) !== false) {
$parts[key($this->encodedParts)] = $this->getNextEncodedValue();
}
ksort($parts);
return array_reduce(
$parts,
function ($carry, $item) {
return $carry . $item;
},
''
);
} |
private function validateArgument($name, $value, array $valid)
{
if (!in_array($value, $valid)) {
$last = array_pop($valid);
throw new InvalidArgumentException(
'$value parameter for ' . $name . ' must be one of '
. join(', ', $valid) . ' or ' . $last . ' - "' . $value
. '" provided'
);
}
} |
public function setHeaders(array $headers)
{
array_walk($headers, function ($v, $k) {
$this->validateArgument(
'headers',
$k,
[ static::FILTER_EXCLUDE, static::FILTER_INCLUDE ]
);
if (!is_array($v)) {
throw new InvalidArgumentException(
'$value must be an array with keys set to FILTER_EXCLUDE, '
. 'FILTER_INCLUDE and values set to an array of header '
. 'name => values'
);
}
});
$this->headers = $headers;
} |
private function failsHasContentFilter(MessagePart $part)
{
return ($this->hascontent === static::FILTER_EXCLUDE && $part->hasContent())
|| ($this->hascontent === static::FILTER_INCLUDE && !$part->hasContent());
} |
private function failsMultiPartFilter(MessagePart $part)
{
if (!($part instanceof MimePart)) {
return $this->multipart !== static::FILTER_EXCLUDE;
}
return ($this->multipart === static::FILTER_EXCLUDE && $part->isMultiPart())
|| ($this->multipart === static::FILTER_INCLUDE && !$part->isMultiPart());
} |
private function failsTextPartFilter(MessagePart $part)
{
return ($this->textpart === static::FILTER_EXCLUDE && $part->isTextPart())
|| ($this->textpart === static::FILTER_INCLUDE && !$part->isTextPart());
} |
private function failsSignedPartFilter(MessagePart $part)
{
if ($this->signedpart === static::FILTER_OFF) {
return false;
} elseif (!$part->isMime() || $part->getParent() === null) {
return ($this->signedpart === static::FILTER_INCLUDE);
}
$partMimeType = $part->getContentType();
$parentMimeType = $part->getParent()->getContentType();
$parentProtocol = $part->getParent()->getHeaderParameter('Content-Type', 'protocol');
if (strcasecmp($parentMimeType, 'multipart/signed') === 0 && strcasecmp($partMimeType, $parentProtocol) === 0) {
return ($this->signedpart === static::FILTER_EXCLUDE);
}
return ($this->signedpart === static::FILTER_INCLUDE);
} |
private function failsHeaderFor(MessagePart $part, $type, $name, $header)
{
$headerValue = null;
static $map = [
'content-type' => 'getContentType',
'content-disposition' => 'getContentDisposition',
'content-transfer-encoding' => 'getContentTransferEncoding',
'content-id' => 'getContentId'
];
$lower = strtolower($name);
if (isset($map[$lower])) {
$headerValue = call_user_func([$part, $map[$lower]]);
} elseif (!($part instanceof MimePart)) {
return ($type === static::FILTER_INCLUDE);
} else {
$headerValue = $part->getHeaderValue($name);
}
return (($type === static::FILTER_EXCLUDE && strcasecmp($headerValue, $header) === 0)
|| ($type === static::FILTER_INCLUDE && strcasecmp($headerValue, $header) !== 0));
} |
private function failsHeaderPartFilter(MessagePart $part)
{
foreach ($this->headers as $type => $values) {
foreach ($values as $name => $header) {
if ($this->failsHeaderFor($part, $type, $name, $header)) {
return true;
}
}
}
return false;
} |
public function filter(MessagePart $part)
{
return !($this->failsMultiPartFilter($part)
|| $this->failsTextPartFilter($part)
|| $this->failsSignedPartFilter($part)
|| $this->failsHeaderPartFilter($part));
} |
public function getUniqueBoundary($mimeType)
{
$type = ltrim(strtoupper(preg_replace('/^(multipart\/(.{3}).*|.*)$/i', '$2-', $mimeType)), '-');
return uniqid('----=MMP-' . $type . '.', true);
} |
public function setMessageAsMixed(Message $message)
{
if ($message->hasContent()) {
$part = $this->genericHelper->createNewContentPartFrom($message);
$message->addChild($part, 0);
}
$this->setMimeHeaderBoundaryOnPart($message, 'multipart/mixed');
$atts = $message->getAllAttachmentParts();
if (!empty($atts)) {
foreach ($atts as $att) {
$att->markAsChanged();
}
}
} |
public function setMessageAsAlternative(Message $message)
{
if ($message->hasContent()) {
$part = $this->genericHelper->createNewContentPartFrom($message);
$message->addChild($part, 0);
}
$this->setMimeHeaderBoundaryOnPart($message, 'multipart/alternative');
} |
public function getContentPartContainerFromAlternative($mimeType, ParentHeaderPart $alternativePart)
{
$part = $alternativePart->getPart(0, PartFilter::fromInlineContentType($mimeType));
$contPart = null;
do {
if ($part === null) {
return false;
}
$contPart = $part;
$part = $part->getParent();
} while ($part !== $alternativePart);
return $contPart;
} |
public function removeAllContentPartsFromAlternative(Message $message, $mimeType, ParentHeaderPart $alternativePart, $keepOtherContent)
{
$rmPart = $this->getContentPartContainerFromAlternative($mimeType, $alternativePart);
if ($rmPart === false) {
return false;
}
if ($keepOtherContent) {
$this->moveAllPartsAsAttachmentsExcept($message, $rmPart, $mimeType);
$alternativePart = $message->getPart(0, PartFilter::fromInlineContentType('multipart/alternative'));
} else {
$rmPart->removeAllParts();
}
$message->removePart($rmPart);
if ($alternativePart !== null) {
if ($alternativePart->getChildCount() === 1) {
$this->genericHelper->replacePart($message, $alternativePart, $alternativePart->getChild(0));
} elseif ($alternativePart->getChildCount() === 0) {
$message->removePart($alternativePart);
}
}
while ($message->getChildCount() === 1) {
$this->genericHelper->replacePart($message, $message, $message->getChild(0));
}
return true;
} |
public function createAlternativeContentPart(Message $message, MessagePart $contentPart)
{
$altPart = $this->partBuilderFactory->newPartBuilder($this->mimePartFactory)->createMessagePart();
$this->setMimeHeaderBoundaryOnPart($altPart, 'multipart/alternative');
$message->removePart($contentPart);
$message->addChild($altPart, 0);
$altPart->addChild($contentPart, 0);
return $altPart;
} |
public function moveAllPartsAsAttachmentsExcept(Message $message, ParentHeaderPart $from, $exceptMimeType)
{
$parts = $from->getAllParts(new PartFilter([
'multipart' => PartFilter::FILTER_EXCLUDE,
'headers' => [
PartFilter::FILTER_EXCLUDE => [
'Content-Type' => $exceptMimeType
]
]
]));
if (strcasecmp($message->getContentType(), 'multipart/mixed') !== 0) {
$this->setMessageAsMixed($message);
}
foreach ($parts as $part) {
$from->removePart($part);
$message->addChild($part);
}
} |
public function enforceMime(Message $message)
{
if (!$message->isMime()) {
if ($message->getAttachmentCount()) {
$this->setMessageAsMixed($message);
} else {
$message->setRawHeader('Content-Type', "text/plain;\r\n\tcharset=\"iso-8859-1\"");
}
$message->setRawHeader('Mime-Version', '1.0');
}
} |
public function createMultipartRelatedPartForInlineChildrenOf(ParentHeaderPart $parent)
{
$relatedPart = $this->partBuilderFactory->newPartBuilder($this->mimePartFactory)->createMessagePart();
$this->setMimeHeaderBoundaryOnPart($relatedPart, 'multipart/related');
foreach ($parent->getChildParts(PartFilter::fromDisposition('inline', PartFilter::FILTER_EXCLUDE)) as $part) {
$parent->removePart($part);
$relatedPart->addChild($part);
}
$parent->addChild($relatedPart, 0);
return $relatedPart;
} |
public function findOtherContentPartFor(Message $message, $mimeType)
{
$altPart = $message->getPart(
0,
PartFilter::fromInlineContentType(($mimeType === 'text/plain') ? 'text/html' : 'text/plain')
);
if ($altPart !== null && $altPart->getParent() !== null && $altPart->getParent()->isMultiPart()) {
$altPartParent = $altPart->getParent();
if ($altPartParent->getChildCount(PartFilter::fromDisposition('inline', PartFilter::FILTER_EXCLUDE)) !== 1) {
$altPart = $this->createMultipartRelatedPartForInlineChildrenOf($altPartParent);
}
}
return $altPart;
} |
public function createContentPartForMimeType(Message $message, $mimeType, $charset)
{
$builder = $this->partBuilderFactory->newPartBuilder($this->mimePartFactory);
$builder->addHeader('Content-Type', "$mimeType;\r\n\tcharset=\"$charset\"");
$builder->addHeader('Content-Transfer-Encoding', 'quoted-printable');
$this->enforceMime($message);
$mimePart = $builder->createMessagePart();
$altPart = $this->findOtherContentPartFor($message, $mimeType);
if ($altPart === $message) {
$this->setMessageAsAlternative($message);
$message->addChild($mimePart);
} elseif ($altPart !== null) {
$mimeAltPart = $this->createAlternativeContentPart($message, $altPart);
$mimeAltPart->addChild($mimePart, 1);
} else {
$message->addChild($mimePart, 0);
}
return $mimePart;
} |
public function createAndAddPartForAttachment(Message $message, $resource, $mimeType, $disposition, $filename = null)
{
if ($filename === null) {
$filename = 'file' . uniqid();
}
$safe = iconv('UTF-8', 'US-ASCII//translit//ignore', $filename);
if ($message->isMime()) {
$builder = $this->partBuilderFactory->newPartBuilder($this->mimePartFactory);
$builder->addHeader('Content-Transfer-Encoding', 'base64');
if (strcasecmp($message->getContentType(), 'multipart/mixed') !== 0) {
$this->setMessageAsMixed($message);
}
$builder->addHeader('Content-Type', "$mimeType;\r\n\tname=\"$safe\"");
$builder->addHeader('Content-Disposition', "$disposition;\r\n\tfilename=\"$safe\"");
} else {
$builder = $this->partBuilderFactory->newPartBuilder(
$this->uuEncodedPartFactory
);
$builder->setProperty('filename', $safe);
}
$part = $builder->createMessagePart();
$part->setContent($resource);
$message->addChild($part);
} |
public function removeAllContentPartsByMimeType(Message $message, $mimeType, $keepOtherContent = false)
{
$alt = $message->getPart(0, PartFilter::fromInlineContentType('multipart/alternative'));
if ($alt !== null) {
return $this->removeAllContentPartsFromAlternative($message, $mimeType, $alt, $keepOtherContent);
}
$message->removeAllParts(PartFilter::fromInlineContentType($mimeType));
return true;
} |
public function removePartByMimeType(Message $message, $mimeType, $index = 0)
{
$parts = $message->getAllParts(PartFilter::fromInlineContentType($mimeType));
$alt = $message->getPart(0, PartFilter::fromInlineContentType('multipart/alternative'));
if ($parts === null || !isset($parts[$index])) {
return false;
} elseif (count($parts) === 1) {
return $this->removeAllContentPartsByMimeType($message, $mimeType, true);
}
$part = $parts[$index];
$message->removePart($part);
if ($alt !== null && $alt->getChildCount() === 1) {
$this->genericHelper->replacePart($message, $alt, $alt->getChild(0));
}
return true;
} |