_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q246400 | FactoryGallery.createGallery | validation | private static function createGallery(String $body, int $order, String $photo, String $source, string $lead): \One\Model\Gallery
{
return new Gallery(
$body,
$order,
$photo,
$source,
$lead
);
} | php | {
"resource": ""
} |
q246401 | Article.getAttachmentByField | validation | public function getAttachmentByField(string $field): array
{
if (isset($this->attachment[$field])) {
return $this->attachment[$field];
}
return [];
} | php | {
"resource": ""
} |
q246402 | Article.attach | validation | public function attach(string $field, Model $item): self
{
$this->attachment[$field][] = $item;
return $this;
} | php | {
"resource": ""
} |
q246403 | Article.attachGallery | validation | public function attachGallery(Gallery $gallery): self
{
return $this->attach(
self::ATTACHMENT_FIELD_GALLERY,
$this->ensureOrder(
$gallery,
self::ATTACHMENT_FIELD_GALLERY
)
);
} | php | {
"resource": ""
} |
q246404 | EmailSenderSerializer.serialize | validation | public function serialize(EntityContract $entity, Collection $select = null)
{
$bag = parent::serialize($entity, $select);
// ...
return $bag;
} | php | {
"resource": ""
} |
q246405 | EmailSenderManager.send | validation | public function send(EmailSender $email, array $data = [])
{
$result = (new DataBuilderManager())->validateRaw($email->data_builder, $data);
dispatch(new SendEmail($email, $data, $this->getAgent()));
return $result;
} | php | {
"resource": ""
} |
q246406 | EmailSenderManager.render | validation | public function render(DataBuilder $data_builder, $parameters, array $data = [])
{
$parameters = $this->castParameters($parameters);
$tm = new TemplateManager();
$result = new Result();
try {
$bag = new Bag($parameters);
$bag->set('body', $tm->renderRaw('text/html', strval($bag->get('body')), $data));
$attachments = [];
foreach ((array) Yaml::parse(strval($bag->get('attachments'))) as $key => $attachment) {
$attachment = (object) $attachment;
$attachments[$key]['as'] = strval($tm->renderRaw('text/plain', $attachment->as, $data));
$attachments[$key]['source'] = strval($tm->renderRaw('text/plain', $attachment->source, $data));
}
$bag->set('attachments', $attachments);
$bag->set('recipients', explode(',', $tm->renderRaw('text/plain', strval($bag->get('recipients')), $data)));
$bag->set('subject', $tm->renderRaw('text/plain', strval($bag->get('subject')), $data));
$bag->set('sender', $tm->renderRaw('text/plain', strval($bag->get('sender')), $data));
$result->setResources(new Collection([$bag->toArray()]));
} catch (\Twig_Error $e) {
$e = new Exceptions\EmailSenderRenderException($e->getRawMessage().' on line '.$e->getTemplateLine());
$result->addErrors(new Collection([$e]));
}
return $result;
} | php | {
"resource": ""
} |
q246407 | Model.filterUriInstance | validation | protected function filterUriInstance($uri): string
{
if ($uri instanceof UriInterface) {
return (string) $uri;
}
if (is_string($uri)) {
return (string) \One\createUriFromString($uri);
}
return '';
} | php | {
"resource": ""
} |
q246408 | Model.filterDateInstance | validation | protected function filterDateInstance($date): string
{
if (empty($date)) {
$date = new \DateTime('now', new \DateTimeZone('Asia/Jakarta'));
}
if (is_string($date) || is_int($date)) {
$date = new \DateTime($date, new \DateTimeZone('Asia/Jakarta'));
}
return $this->formatDate($date);
} | php | {
"resource": ""
} |
q246409 | Model.convertNonAscii | validation | private function convertNonAscii(string $string): string
{
$search = $replace = [];
// Replace Single Curly Quotes
$search[] = chr(226) . chr(128) . chr(152);
$replace[] = "'";
$search[] = chr(226) . chr(128) . chr(153);
$replace[] = "'";
// Replace Smart Double Curly Quotes
$search[] = chr(226) . chr(128) . chr(156);
$replace[] = '"';
$search[] = chr(226) . chr(128) . chr(157);
$replace[] = '"';
// Replace En Dash
$search[] = chr(226) . chr(128) . chr(147);
$replace[] = '--';
// Replace Em Dash
$search[] = chr(226) . chr(128) . chr(148);
$replace[] = '---';
// Replace Bullet
$search[] = chr(226) . chr(128) . chr(162);
$replace[] = '*';
// Replace Middle Dot
$search[] = chr(194) . chr(183);
$replace[] = '*';
// Replace Ellipsis with three consecutive dots
$search[] = chr(226) . chr(128) . chr(166);
$replace[] = '...';
// Apply Replacements
$string = str_replace($search, $replace, $string);
// Remove any non-ASCII Characters
return preg_replace("/[^\x01-\x7F]/", '', $string);
} | php | {
"resource": ""
} |
q246410 | Types.getTypeByValue | validation | public static function getTypeByValue($value)
{
if (is_int($value)) {
return self::TYPE_INT;
} elseif (is_string($value)) {
return self::TYPE_QSTRING;
} elseif (is_bool($value)) {
return self::TYPE_BOOL;
} elseif (self::isList($value)) {
return self::TYPE_QVARIANT_LIST;
} elseif (self::isMap($value)) {
return self::TYPE_QVARIANT_MAP;
} elseif ($value instanceof \DateTime) {
return self::TYPE_QDATETIME;
} else {
throw new \InvalidArgumentException('Can not guess variant type for type "' . gettype($value) . '"');
}
} | php | {
"resource": ""
} |
q246411 | Types.getNameByType | validation | public static function getNameByType($type)
{
static $map = array(
self::TYPE_BOOL => 'Bool',
self::TYPE_INT => 'Int',
self::TYPE_UINT => 'UInt',
self::TYPE_QCHAR => 'QChar',
self::TYPE_QVARIANT_MAP => 'QVariantMap',
self::TYPE_QVARIANT_LIST => 'QVariantList',
self::TYPE_QSTRING => 'QString',
self::TYPE_QSTRING_LIST => 'QStringList',
self::TYPE_QBYTE_ARRAY => 'QByteArray',
self::TYPE_QTIME => 'QTime',
self::TYPE_QDATETIME => 'QDateTime',
self::TYPE_QUSER_TYPE => 'QUserType',
self::TYPE_SHORT => 'Short',
self::TYPE_CHAR => 'Char',
self::TYPE_USHORT => 'UShort',
self::TYPE_UCHAR => 'UChar',
);
if (!isset($map[$type])) {
throw new \InvalidArgumentException('Invalid/unknown variant type (' . $type . ')');
}
return $map[$type];
} | php | {
"resource": ""
} |
q246412 | Photo.getAvailableRatios | validation | private function getAvailableRatios(): array
{
return [
self::RATIO_SQUARE,
self::RATIO_RECTANGLE,
self::RATIO_HEADLINE,
self::RATIO_VERTICAL,
self::RATIO_COVER,
];
} | php | {
"resource": ""
} |
q246413 | Yaml.setEncoder | validation | public function setEncoder(callable $encoder): Yaml
{
if (!is_callable($encoder)) {
throw new \InvalidArgumentException('The provided encoder must be callable.');
}
$this->encoder = $encoder;
return $this;
} | php | {
"resource": ""
} |
q246414 | FactoryArticle.createArticle | validation | public static function createArticle(String $title, string $body, string $source, string $uniqueId, int $typeId, int $categoryId, string $reporter, string $lead, string $tags, string $publishedAt, int $identifier): Article
{
return new Article(
$title,
$body,
$source,
$uniqueId,
$typeId,
$categoryId,
$reporter,
$lead,
$tags,
$publishedAt,
$identifier
);
} | php | {
"resource": ""
} |
q246415 | Collection.get | validation | public function get(string $key)
{
return isset($this->props[$key]) ? $this->props[$key] : null;
} | php | {
"resource": ""
} |
q246416 | Collection.set | validation | public function set(string $key, $value): self
{
if (! isset($this->props[$key])) {
throw new \Exception('Cannot add new property from set. Use add()');
}
$this->props[$key] = $value;
return $this;
} | php | {
"resource": ""
} |
q246417 | Collection.add | validation | public function add(string $key, $value): self
{
if (! array_key_exists($key, $this->props)) {
return $this->addNew($key, $value);
}
if (is_array($this->props[$key])) {
return $this->addArray($key, $value);
}
return $this->appendToArray($key, $value);
} | php | {
"resource": ""
} |
q246418 | Collection.map | validation | public function map(\Closure $callback, $context = []): self
{
$collection = new static();
foreach ($this->props as $key => $value) {
$collection->add($key, $callback($value, $key, $context));
}
return $collection;
} | php | {
"resource": ""
} |
q246419 | Collection.filter | validation | public function filter(\Closure $callback): self
{
$collection = new static();
foreach ($this->props as $key => $value) {
if ($callback($value, $key)) {
$collection->add($key, $value);
}
}
return $collection;
} | php | {
"resource": ""
} |
q246420 | Collection.addNew | validation | private function addNew(string $key, $value): self
{
$this->props[$key] = $value;
return $this;
} | php | {
"resource": ""
} |
q246421 | Collection.addArray | validation | private function addArray(string $key, $value): self
{
$this->props[$key][] = $value;
return $this;
} | php | {
"resource": ""
} |
q246422 | Collection.appendToArray | validation | private function appendToArray(string $key, $value): self
{
$this->props[$key] = [$this->props[$key], $value];
return $this;
} | php | {
"resource": ""
} |
q246423 | Gallery.fillSource | validation | private function fillSource($source, $photo): string
{
if (! empty($source)) {
return $this->filterUriInstance($source);
}
return (string) $photo;
} | php | {
"resource": ""
} |
q246424 | FormatMapping.article | validation | public function article(string $singleJsonArticle): Article
{
if (json_decode($singleJsonArticle, true)) {
$dataArticle = json_decode($singleJsonArticle, true)['data'];
$article = new Article(
$this->filterString(
$this->getValue('title', $dataArticle)
),
$this->filterString(
$this->getValue('body', $dataArticle)
),
$this->filterString(
$this->getValue('source', $dataArticle)
),
$this->getValue('unique_id', $dataArticle),
$this->filterInteger(
$this->getValue(
'type_id',
$dataArticle['type']
)
),
$this->filterInteger(
$this->getValue(
'category_id',
$dataArticle['category']
)
),
$this->getValue('reporter', $dataArticle),
$this->filterString(
$this->getValue('lead', $dataArticle)
),
$this->getValue('tag_name', $dataArticle['tags']),
$this->filterString(
$this->getValue('published_at', $dataArticle)
),
(string) $this->filterInteger(
$this->getValue('id', $dataArticle)
)
);
$attachmentConstants = [
Article::ATTACHMENT_FIELD_PHOTO,
Article::ATTACHMENT_FIELD_PAGE,
Article::ATTACHMENT_FIELD_GALLERY,
Article::ATTACHMENT_FIELD_VIDEO,
];
$attachmentTypes = [
self::JSON_PHOTO_FIELD, self::JSON_PAGE_FIELD,
self::JSON_GALLERY_FIELD, self::JSON_VIDEO_FIELD,
];
$attachmentAttributes = $this->lookUp($attachmentConstants);
return $this->generalAttachment(
$article,
$attachmentConstants,
$attachmentTypes,
$attachmentAttributes,
$dataArticle
);
}
throw new \Exception('Empty or invalid JSON Response', 1);
} | php | {
"resource": ""
} |
q246425 | FormatMapping.lookUp | validation | private function lookUp(array $articleConstant): array
{
$copyListAttributes = $this->listAttributes;
return array_map(function ($singleConst) use ($copyListAttributes) {
$res = $copyListAttributes[$singleConst];
return array_map(function ($str) use ($singleConst) {
return $singleConst . $str;
}, $res);
}, $articleConstant);
} | php | {
"resource": ""
} |
q246426 | FormatMapping.generalAttachment | validation | private function generalAttachment(
Article $article,
array $attachmentConst,
array $attachmentype,
array $attributes,
array $dataArticle
): Article {
$numOfAttachments = count($attachmentConst);
for ($i = 0; $i < $numOfAttachments; $i++) {
$attachments = $this->attachment($attachmentype[$i], $attributes[$i], $dataArticle);
for ($j = 0; $j < $attachments['numberOfItems']; $j++) {
$attachment = $attachments['attachments'][$j];
$article->attach($attachmentConst[$i], $attachment);
}
}
return $article;
} | php | {
"resource": ""
} |
q246427 | FormatMapping.makeAttachmentObject | validation | private function makeAttachmentObject(string $attachmentType, array $attrReferences, array $item)
{
$attrValues = [];
foreach ($attrReferences as $attrReference) {
$attrValues[$attrReference] = $this->getValue($attrReference, $item);
}
switch ($attachmentType) {
case self::JSON_PHOTO_FIELD:
return $this->createPhoto(
$attrValues['photo_url'],
$attrValues['photo_ratio'],
'',
''
);
case self::JSON_PAGE_FIELD:
return $this->createPage(
$attrValues['page_title'],
$attrValues['page_body'],
$attrValues['page_source'],
$attrValues['page_order'],
$attrValues['page_cover'],
$attrValues['page_lead']
);
case self::JSON_GALLERY_FIELD:
return $this->createGallery(
$attrValues['gallery_body'],
$attrValues['gallery_order'],
$attrValues['gallery_photo'],
$attrValues['gallery_source'],
$attrValues['gallery_lead']
);
case self::JSON_VIDEO_FIELD:
return $this->createVideo(
$attrValues['video_body'],
$attrValues['video_source'],
$attrValues['video_order'],
$attrValues['video_cover'],
$attrValues['video_lead']
);
default:
return null;
}
} | php | {
"resource": ""
} |
q246428 | FormatMapping.createPhoto | validation | private function createPhoto(string $url, string $ratio, string $desc, string $info): \One\Model\Photo
{
return new Photo(
$url,
$ratio,
$this->handleString($desc),
$this->handleString($info)
);
} | php | {
"resource": ""
} |
q246429 | FormatMapping.createPage | validation | private function createPage(string $title, string $body, string $source, int $order, string $cover, string $lead): \One\Model\Page
{
return new Page(
$title,
$body,
$source,
$order,
$cover,
$lead
);
} | php | {
"resource": ""
} |
q246430 | FormatMapping.createVideo | validation | private function createVideo(string $body, string $source, int $order, string $cover, string $lead): \One\Model\Video
{
return new Video(
$body,
$source,
$order,
$cover,
$lead
);
} | php | {
"resource": ""
} |
q246431 | FormatMapping.filterString | validation | private function filterString($str): string
{
if (is_string($str) && strlen($str) > 0 && $str !== null) {
return $str;
}
throw new \Exception('String required', 1);
} | php | {
"resource": ""
} |
q246432 | FormatMapping.handleString | validation | private function handleString($str): string
{
return is_string($str) &&
strlen($str) > 0
&& $str !== null ? $str : '';
} | php | {
"resource": ""
} |
q246433 | Router.map | validation | public function map(array $methods, string $path, RequestHandlerInterface $handler): Route
{
return $this->routes[] = new Route($methods, $path, $handler);
} | php | {
"resource": ""
} |
q246434 | Router.dispatch | validation | public function dispatch(ServerRequestInterface $request): ServerRequestInterface
{
$dispatcher = simpleDispatcher([$this, 'addRoutes']);
$routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getUri()->getPath());
if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
throw new MethodNotAllowedException($request->getMethod(), $routeInfo[1]);
}
if ($routeInfo[0] === Dispatcher::NOT_FOUND) {
throw new NotFoundHttpException(sprintf("Route '%s' not found.", $request->getUri()->getPath()));
}
foreach ($routeInfo[2] as $key => $value) {
$request = $request->withAttribute($key, $value);
}
return $request->withAttribute('route', $this->routes[$routeInfo[1]]);
} | php | {
"resource": ""
} |
q246435 | Router.addRoutes | validation | public function addRoutes(RouteCollector $routeCollector): void
{
foreach ($this->routes as $index => $route) {
$routeCollector->addRoute($route->getMethods(), $route->getPath(), $index);
}
} | php | {
"resource": ""
} |
q246436 | Client.getMethodResult | validation | protected function getMethodResult($method, array $arguments)
{
if (!is_callable(['Elasticsearch\Client', $method])) {
trigger_error(
sprintf('Call to undefined or protected/private method %s::%s()', get_called_class(), $method),
E_USER_ERROR
);
}
if (empty($this->results[$method])) {
throw new \Exception(
sprintf("ElasticsearchMock results is empty for %s", $method)
);
}
$this->calls[$method][] = $arguments;
return array_shift($this->results[$method]);
} | php | {
"resource": ""
} |
q246437 | Client.addSearchResult | validation | public function addSearchResult($index, $type, array $documents)
{
$result = [
'took' => 5,
'timed_out' => false,
'_shards' => [ 'total' => 5, 'successful' => 5, 'failed' => 0 ],
'hits' => [
'total' => count($documents),
'max_score' => 1,
'hits' => []
]
];
foreach ($documents as $document) {
$result['hits']['hits'][] = [
'_index' => $index,
'_type' => $type,
'_id' => $document['id'],
'_score' => 1,
'_source' => $document
];
}
return $this->addResult('search', $result);
} | php | {
"resource": ""
} |
q246438 | LumenServiceProvider.version | validation | protected function version()
{
$version = explode('(', $this->app->version());
if (isset($version[1])) {
return substr($version[1], 0, 3);
}
return null;
} | php | {
"resource": ""
} |
q246439 | Message.save | validation | public function save()
{
try
{
$connection = new Connection($this->buildConnectionOptions());
$connection->open();
$msg = new AMQPMessage($this->message, array('content_type' => $this->content_type, 'delivery_mode' => 2));
$connection->channel->basic_publish($msg, $this->exchange, $this->queue_name);
$connection->close();
}
catch (Exception $e)
{
$connection->close();
throw new Exception($e);
}
} | php | {
"resource": ""
} |
q246440 | BaseOptions.validateOptions | validation | public function validateOptions(array $options)
{
foreach ($options as $option => $value)
{
if (!in_array($option, $this->allowedOptions))
throw new InvalidOptionException("Option [$option] is not valid");
}
return $this;
} | php | {
"resource": ""
} |
q246441 | BaseOptions.setOptions | validation | public function setOptions(array $options)
{
//Validate options
$this->validateOptions($options);
//Set options
foreach ($options as $option => $value)
$this->$option = $value;
return $this;
} | php | {
"resource": ""
} |
q246442 | BaseOptions.buildConnectionOptions | validation | public function buildConnectionOptions()
{
//Default connection
$connection_name = $this->config->get("tail-settings.default");
//Check if set for this connection
if ($this->connection_name)
$connection_name = $this->connection_name;
$connectionOptions = $this->config->get("tail-settings.connections.$connection_name");
//Adding default values to exchange_type and content_type to avoid breaking change
if (!isset($connectionOptions['exchange_type']))
$connectionOptions['exchange_type'] = 'direct';
if (!isset($connectionOptions['content_type']))
$connectionOptions['content_type'] = 'text/plain';
//Set current instance properties values
if ($this->vhost)
$connectionOptions['vhost'] = $this->vhost;
if ($this->exchange)
$connectionOptions['exchange'] = $this->exchange;
if ($this->exchange_type)
$connectionOptions['exchange_type'] = $this->exchange_type;
if ($this->content_type)
$connectionOptions['content_type'] = $this->content_type;
//Queue specific options
$connectionOptions['queue_name'] = $this->queue_name;
return $connectionOptions;
} | php | {
"resource": ""
} |
q246443 | Connection.open | validation | public function open()
{
try
{
$additionalConnectionOptions = array();
foreach (array('connection_timeout', 'read_write_timeout', 'keepalive', 'heartbeat') as $option) {
if (isset($this->$option)) {
$additionalConnectionOptions[$option] = $this->$option;
}
}
$this->AMQPConnection = new AMQPSSLConnection(
$this->host,
$this->port,
$this->username,
$this->password,
$this->vhost,
$this->ssl_context_options,
$additionalConnectionOptions
);
$this->channel = $this->AMQPConnection->channel();
$this->channel->queue_declare($this->queue_name, false, false, false, false);
$this->channel->exchange_declare($this->exchange, $this->exchange_type, false, true, false);
$this->channel->queue_bind($this->queue_name, $this->exchange);
}
catch (Exception $e)
{
throw new Exception($e);
}
} | php | {
"resource": ""
} |
q246444 | Connection.close | validation | public function close()
{
if (isset($this->channel))
$this->channel->close();
if (isset($this->AMQPConnection))
$this->AMQPConnection->close();
} | php | {
"resource": ""
} |
q246445 | Ekko.isActiveURL | validation | public function isActiveURL($url, $output = "active")
{
if ($this->url->current() == $this->url->to($url)) {
return $output;
}
return null;
} | php | {
"resource": ""
} |
q246446 | Ekko.isActiveMatch | validation | public function isActiveMatch($string, $output = "active")
{
if (strpos($this->url->current(), $string) !== false) {
return $output;
}
return null;
} | php | {
"resource": ""
} |
q246447 | Ekko.areActiveRoutes | validation | public function areActiveRoutes(array $routeNames, $output = "active")
{
foreach ($routeNames as $routeName) {
if ($this->isActiveRoute($routeName, true)) {
return $output;
}
}
return null;
} | php | {
"resource": ""
} |
q246448 | Ekko.areActiveURLs | validation | public function areActiveURLs(array $urls, $output = "active")
{
foreach ($urls as $url) {
if ($this->isActiveURL($url, true)) {
return $output;
}
}
return null;
} | php | {
"resource": ""
} |
q246449 | Dispatcher.p | validation | public function p()
{
$args = func_get_args();
$node = $args[0];
if (null === $node) {
return;
}
$this->logger->trace('p'.$node->getType(), $node, $this->getMetadata()->getFullQualifiedNameClass());
$class = $this->getClass('p'.$node->getType());
return call_user_func_array(array($class, "convert"), $args);
} | php | {
"resource": ""
} |
q246450 | Dispatcher.convert | validation | public function convert(array $stmts, ClassMetadata $metadata, ClassCollector $classCollector, Logger $logger)
{
$this->metadata = $metadata;
$this->classCollector = $classCollector;
$this->logger = $logger;
return ltrim(str_replace("\n".self::noIndentToken, "\n", $this->pStmts($stmts, false)));
} | php | {
"resource": ""
} |
q246451 | CliFactory.getInstance | validation | public static function getInstance(OutputInterface $output)
{
$questionHelper = new QuestionHelper();
$application = new Application('PHP to Zephir Command Line Interface', 'Beta 0.2.1');
$application->getHelperSet()->set(new FormatterHelper(), 'formatter');
$application->getHelperSet()->set($questionHelper, 'question');
$application->add(ConvertFactory::getInstance($output));
return $application;
} | php | {
"resource": ""
} |
q246452 | PrecPrinter.convert | validation | public function convert(Node $node, $parentPrecedence, $parentAssociativity, $childPosition)
{
$type = $node->getType();
if ($this->dispatcher->issetPrecedenceMap($type) === true) {
$childPrecedences = $this->dispatcher->getPrecedenceMap($type);
$childPrecedence = $childPrecedences[0];
if ($childPrecedence > $parentPrecedence
|| ($parentPrecedence == $childPrecedence && $parentAssociativity != $childPosition)
) {
return '('.$this->dispatcher->{'p'.$type}($node).')';
}
}
return $this->dispatcher->{'p'.$type}($node);
} | php | {
"resource": ""
} |
q246453 | Injector.getConstant | validation | public function getConstant($name)
{
return $this->getBinding(ConstantBinding::TYPE, $name)
->getInstance($this, $name);
} | php | {
"resource": ""
} |
q246454 | Injector.getBinding | validation | private function getBinding($type, $name = null)
{
$binding = $this->findBinding($type, $name);
if (null === $binding) {
throw new BindingException('No binding for ' . $type . ' defined');
}
return $binding;
} | php | {
"resource": ""
} |
q246455 | Injector.findBinding | validation | private function findBinding($type, $name)
{
$bindingName = $this->bindingName($name);
if (null !== $bindingName && isset($this->index[$type . '#' . $bindingName])) {
return $this->index[$type . '#' . $bindingName];
}
if (isset($this->index[$type])) {
return $this->index[$type];
}
if (!in_array($type, [PropertyBinding::TYPE, ConstantBinding::TYPE, ListBinding::TYPE, MapBinding::TYPE])) {
$this->index[$type] = $this->getAnnotatedBinding(new \ReflectionClass($type));
return $this->index[$type];
}
return null;
} | php | {
"resource": ""
} |
q246456 | Injector.getAnnotatedBinding | validation | private function getAnnotatedBinding(\ReflectionClass $class)
{
$annotations = annotationsOf($class);
if ($class->isInterface() && $annotations->contain('ImplementedBy')) {
return $this->bind($class->getName())
->to($this->findImplementation($annotations, $class->getName()));
} elseif ($annotations->contain('ProvidedBy')) {
return $this->bind($class->getName())
->toProviderClass(
$annotations->firstNamed('ProvidedBy')
->getProviderClass()
);
}
return $this->getImplicitBinding($class);
} | php | {
"resource": ""
} |
q246457 | App.createInstance | validation | public static function createInstance($className, $projectPath)
{
Runtime::reset();
self::$projectPath = $projectPath;
$binder = new Binder();
foreach (static::getBindingsForApp($className) as $bindingModule) {
if (is_string($bindingModule)) {
$bindingModule = new $bindingModule();
}
if ($bindingModule instanceof BindingModule) {
$bindingModule->configure($binder, $projectPath);
} elseif ($bindingModule instanceof \Closure) {
$bindingModule($binder, $projectPath);
} else {
throw new \InvalidArgumentException(
'Given module class ' . get_class($bindingModule)
. ' is not an instance of stubbles\ioc\module\BindingModule'
);
}
}
return $binder->getInjector()->getInstance($className);
} | php | {
"resource": ""
} |
q246458 | App.getBindingsForApp | validation | protected static function getBindingsForApp($className)
{
$bindings = method_exists($className, '__bindings') ? $className::__bindings() : [];
if (!Runtime::initialized()) {
$bindings[] = static::runtime();
}
return $bindings;
} | php | {
"resource": ""
} |
q246459 | App.hostname | validation | protected static function hostname()
{
return function(Binder $binder)
{
if (DIRECTORY_SEPARATOR === '\\') {
$fq = php_uname('n');
if (isset($_SERVER['USERDNSDOMAIN'])) {
$fq .= '.' . $_SERVER['USERDNSDOMAIN'];
}
} else {
$fq = exec('hostname -f');
}
$binder->bindConstant('stubbles.hostname.nq')
->to(php_uname('n'));
$binder->bindConstant('stubbles.hostname.fq')
->to($fq);
};
} | php | {
"resource": ""
} |
q246460 | Predicate.castFrom | validation | public static function castFrom($predicate)
{
if ($predicate instanceof self) {
return $predicate;
} elseif (is_callable($predicate)) {
return new CallablePredicate($predicate);
}
throw new \InvalidArgumentException(
'Given predicate is neither a callable nor an instance of ' . __CLASS__
);
} | php | {
"resource": ""
} |
q246461 | Rootpath.contains | validation | public function contains($path)
{
$realpath = realpath($path);
if (false === $realpath) {
return false;
}
return substr($realpath, 0, strlen($this->rootpath)) === $this->rootpath;
} | php | {
"resource": ""
} |
q246462 | Rootpath.sourcePathes | validation | public function sourcePathes()
{
$vendorPathes = [];
foreach (array_merge($this->loadPsr0Pathes(), $this->loadPsr4Pathes()) as $pathes) {
if (is_array($pathes)) {
$vendorPathes = array_merge($vendorPathes, $pathes);
} else {
$vendorPathes[] = $pathes;
}
}
return $vendorPathes;
} | php | {
"resource": ""
} |
q246463 | PropertyBinding.hasProperty | validation | public function hasProperty($name)
{
if ($this->properties->containValue($this->environment, $name)) {
return true;
}
return $this->properties->containValue('config', $name);
} | php | {
"resource": ""
} |
q246464 | MultiBinding.getValueCreator | validation | protected function getValueCreator($value)
{
if (is_string($value) && class_exists($value)) {
return function($injector) use($value) { return $injector->getInstance($value); };
}
return function() use($value) { return $value; };
} | php | {
"resource": ""
} |
q246465 | MultiBinding.getProviderCreator | validation | protected function getProviderCreator($provider)
{
if (is_string($provider)) {
return function($injector, $name, $key) use($provider)
{
$providerInstance = $injector->getInstance($provider);
if (!($providerInstance instanceof InjectionProvider)) {
throw new BindingException('Configured provider class ' . $provider . ' for ' . $name . '[' . $key . '] is not an instance of stubbles\ioc\InjectionProvider.');
}
return $providerInstance->get();
};
} elseif ($provider instanceof InjectionProvider) {
return function() use($provider) { return $provider->get(); };
}
throw new \InvalidArgumentException(
'Given provider must either be a instance of'
. ' stubbles\ioc\InjectionProvider or a class name representing'
. ' such a provider instance.'
);
} | php | {
"resource": ""
} |
q246466 | MultiBinding.resolve | validation | private function resolve(Injector $injector, $type)
{
$resolved = [];
foreach ($this->getBindings() as $key => $bindingValue) {
$value = $bindingValue($injector, $this->name, $key);
if ($this->isTypeMismatch($type, $value)) {
$valueType = ((is_object($value)) ? (get_class($value)) : (gettype($value)));
throw new BindingException('Value of type ' . $valueType . ' for ' . ((is_int($key)) ? ('list') : ('map')) . ' named ' . $this->name . ' at position ' . $key . ' is not of type ' . $type->getName());
}
$resolved[$key] = $value;
}
return $resolved;
} | php | {
"resource": ""
} |
q246467 | MultiBinding.isTypeMismatch | validation | private function isTypeMismatch($type, $value)
{
if (!($type instanceof \ReflectionClass)) {
return false;
}
if (!is_object($value)) {
return true;
}
return !$type->isInstance($value);
} | php | {
"resource": ""
} |
q246468 | Binder.bindList | validation | public function bindList($name)
{
if (!isset($this->listBindings[$name])) {
$this->listBindings[$name] = $this->addBinding(new ListBinding($name));
}
return $this->listBindings[$name];
} | php | {
"resource": ""
} |
q246469 | Binder.createInjector | validation | public static function createInjector(callable ...$applyBindings)
{
$self = new self();
foreach ($applyBindings as $applyBinding) {
$applyBinding($self);
}
return $self->getInjector();
} | php | {
"resource": ""
} |
q246470 | Enum.forName | validation | public static function forName($name)
{
$enum = new \ReflectionClass(get_called_class());
try {
return $enum->getStaticPropertyValue($name);
} catch (\ReflectionException $re) {
throw new \InvalidArgumentException($re->getMessage());
}
} | php | {
"resource": ""
} |
q246471 | Enum.forValue | validation | public static function forValue($value)
{
$enumClass = new \ReflectionClass(get_called_class());
foreach ($enumClass->getStaticProperties() as $instance) {
if ($instance->value() === $value) {
return $instance;
}
}
throw new \InvalidArgumentException(
'Enum ' . $enumClass->getName() . ' for value ' . $value
. ' does not exist.'
);
} | php | {
"resource": ""
} |
q246472 | Enum.valuesOf | validation | public static function valuesOf()
{
$enum = new \ReflectionClass(get_called_class());
$values = [];
foreach ($enum->getStaticProperties() as $name => $instance) {
$values[$name] = $instance->value;
}
return $values;
} | php | {
"resource": ""
} |
q246473 | Enum.equals | validation | public function equals($compare)
{
if ($compare instanceof self) {
return (get_class($compare) === get_class($this) && $compare->name() === $this->name);
}
return false;
} | php | {
"resource": ""
} |
q246474 | AbstractExceptionHandler.handleException | validation | public function handleException(\Exception $exception)
{
if ($this->loggingEnabled) {
$this->exceptionLogger->log($exception);
}
if ('cgi' === $this->sapi) {
$this->header('Status: 500 Internal Server Error');
} else {
$this->header('HTTP/1.1 500 Internal Server Error');
}
$this->writeBody($this->createResponseBody($exception));
} | php | {
"resource": ""
} |
q246475 | MapBinding.withEntry | validation | public function withEntry($key, $value)
{
$this->bindings[$key] = $this->getValueCreator($value);
return $this;
} | php | {
"resource": ""
} |
q246476 | MapBinding.withEntryFromProvider | validation | public function withEntryFromProvider($key, $provider)
{
$this->bindings[$key] = $this->getProviderCreator($provider);
return $this;
} | php | {
"resource": ""
} |
q246477 | DefaultInjectionProvider.get | validation | public function get($name = null)
{
$constructor = $this->class->getConstructor();
if (null === $constructor || $this->class->isInternal()) {
return $this->class->newInstance();
}
$params = $this->injectionValuesForMethod($constructor);
if (count($params) === 0) {
return $this->class->newInstance();
}
return $this->class->newInstanceArgs($params);
} | php | {
"resource": ""
} |
q246478 | DefaultInjectionProvider.injectionValuesForMethod | validation | private function injectionValuesForMethod(\ReflectionMethod $method)
{
$paramValues = [];
$defaultName = $this->methodBindingName($method);
foreach ($method->getParameters() as $param) {
$type = $this->paramType($method, $param);
$name = $this->detectBindingName($param, $defaultName);
$hasExplicitBinding = $this->injector->hasExplicitBinding($type, $name);
if (!$hasExplicitBinding && $param->isDefaultValueAvailable()) {
$paramValues[] = $param->getDefaultValue();
continue;
}
if (!$this->injector->hasBinding($type, $name)) {
$typeMsg = $this->createTypeMessage($type, $name);
throw new BindingException(
'Can not inject into '
. $this->class->getName() . '::' . $method->getName()
. '(' . $this->createParamString($param, $type)
. '). No binding for type ' . $typeMsg
. ' specified. Injection stack: ' . "\n"
. join("\n", $this->injector->stack())
);
}
$paramValues[] = $this->injector->getInstance($type, $name);
}
return $paramValues;
} | php | {
"resource": ""
} |
q246479 | DefaultInjectionProvider.methodBindingName | validation | private function methodBindingName(\ReflectionMethod $method)
{
$annotations = annotationsOf($method);
if ($annotations->contain('List')) {
return $annotations->firstNamed('List')->getValue();
}
if ($annotations->contain('Map')) {
return $annotations->firstNamed('Map')->getValue();
}
if ($annotations->contain('Named')) {
return $annotations->firstNamed('Named')->getName();
}
if ($annotations->contain('Property')) {
return $annotations->firstNamed('Property')->getValue();
}
return null;
} | php | {
"resource": ""
} |
q246480 | DefaultInjectionProvider.paramType | validation | private function paramType(\ReflectionMethod $method, \ReflectionParameter $param)
{
$methodAnnotations = annotationsOf($method);
$paramAnnotations = annotationsOf($param);
$paramClass = $param->getClass();
if (null !== $paramClass) {
if ($methodAnnotations->contain('Property') || $paramAnnotations->contain('Property')) {
return PropertyBinding::TYPE;
}
return $paramClass->getName();
}
if ($methodAnnotations->contain('List') || $paramAnnotations->contain('List')) {
return ListBinding::TYPE;
}
if ($methodAnnotations->contain('Map') || $paramAnnotations->contain('Map')) {
return MapBinding::TYPE;
}
if ($methodAnnotations->contain('Property') || $paramAnnotations->contain('Property')) {
return PropertyBinding::TYPE;
}
return ConstantBinding::TYPE;
} | php | {
"resource": ""
} |
q246481 | ExceptionLogger.log | validation | public function log(\Exception $exception)
{
$logData = date('Y-m-d H:i:s');
$logData .= $this->exceptionFields($exception);
$logData .= $this->fieldsForPrevious($exception->getPrevious());
error_log(
$logData . "\n",
3,
$this->getLogDir() . DIRECTORY_SEPARATOR . 'exceptions-' . date('Y-m-d') . '.log'
);
} | php | {
"resource": ""
} |
q246482 | ExceptionLogger.exceptionFields | validation | private function exceptionFields(\Exception $exception)
{
return '|' . get_class($exception)
. '|' . $exception->getMessage()
. '|' . $exception->getFile()
. '|' . $exception->getLine();
} | php | {
"resource": ""
} |
q246483 | Imposter.getAutoloads | validation | public function getAutoloads(): array
{
if (empty($this->autoloads)) {
$this->autoloads = $this->configCollection->getAutoloads();
}
return $this->autoloads;
} | php | {
"resource": ""
} |
q246484 | Transformer.transform | validation | public function transform(string $target)
{
if ($this->filesystem->isFile($target)) {
$this->doTransform($target);
return;
}
$files = $this->filesystem->allFiles($target);
array_walk($files, function (SplFileInfo $file) {
$this->doTransform($file->getRealPath());
});
} | php | {
"resource": ""
} |
q246485 | Transformer.prefixNamespace | validation | private function prefixNamespace(string $targetFile)
{
$pattern = sprintf(
'/%1$s\\s+(?!(%2$s)|(Composer(\\\\|;)))/',
'namespace',
$this->namespacePrefix
);
$replacement = sprintf('%1$s %2$s', 'namespace', $this->namespacePrefix);
$this->replace($pattern, $replacement, $targetFile);
} | php | {
"resource": ""
} |
q246486 | Transformer.replace | validation | private function replace(string $pattern, string $replacement, string $targetFile)
{
$this->filesystem->put(
$targetFile,
preg_replace(
$pattern,
$replacement,
$this->filesystem->get($targetFile)
)
);
} | php | {
"resource": ""
} |
q246487 | Filesystem.get | validation | public function get(string $path): string
{
if (! $this->isFile($path)) {
throw new RuntimeException('File does not exist at path ' . $path);
}
return file_get_contents($path);
} | php | {
"resource": ""
} |
q246488 | HasManyRelationship.get | validation | public function get()
{
$child = $this->childClassName;
$query = new QueryBuilder();
$query->filter(new ParentFilter($this->parent->getId()));
$collection = $child::search($query);
$collection->each(function (ElasticsearchModel $model) {
$model->setParent($this->parent);
});
return $collection;
} | php | {
"resource": ""
} |
q246489 | HasManyRelationship.find | validation | public function find($id)
{
$child = $this->childClassName;
$model = $child::findWithParentId($id, $this->parent->getId());
if ($model) {
$model->setParent($this->parent);
}
return $model;
} | php | {
"resource": ""
} |
q246490 | HasManyRelationship.save | validation | public function save($child)
{
/** @var ElasticsearchModel[] $children */
$children = !is_array($child) ? [$child] : $child;
// @TODO: use bulk if count($children) > 1
foreach ($children as $child) {
$child->setParent($this->parent);
$child->save();
}
} | php | {
"resource": ""
} |
q246491 | Model.save | validation | public function save($columns = ['*'])
{
$columns = $columns ? (array)$columns : ['*'];
if ($this->saving() === false) {
return false;
}
$this->fillTimestamp();
$this->_dal->put($columns);
$this->_exist = true;
// self::cache()->put($id, $this);
if ($this->saved() === false) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q246492 | Model.delete | validation | public function delete()
{
if ($this->deleting() === false) {
return false;
}
$this->_dal->delete();
$this->_exist = false;
$cache = self::cache();
$cache->forget($this->getId());
if ($this->deleted() === false) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q246493 | Model.findOrNew | validation | public static function findOrNew($id)
{
$model = static::find($id);
if (is_null($model)) {
$model = static::createInstance();
$model->setId($id);
}
return $model;
} | php | {
"resource": ""
} |
q246494 | Model.findOrFail | validation | public static function findOrFail($id, array $columns = ['*'], $parent = null)
{
$model = static::find($id, $columns, ['parent' => $parent]);
if (is_null($model)) {
throw new ModelNotFoundException(get_called_class(), $id);
}
return $model;
} | php | {
"resource": ""
} |
q246495 | Model.destroy | validation | public static function destroy($id)
{
$ids = is_array($id) ? $id : [$id];
foreach ($ids as $id) {
$model = static::find($id);
if (!is_null($model)) {
$model->delete();
}
}
} | php | {
"resource": ""
} |
q246496 | Paginationable.makePagination | validation | public function makePagination(QueryBuilder $query = null)
{
if (is_null($this->_position)) {
throw new Exception('To use Paginationable trait you must fill _position property in your model');
}
/** @var ElasticsearchModel $model */
$model = static::createInstance();
$query = $query ?: new QueryBuilder();
$prevDoc = null;
$nextDoc = null;
$query->fields();
$prevPos = $this->_position - 1;
if ($prevPos >= 0) {
$items = $model->search($query->from($prevPos)->size(3));
$prevDoc = $items->first();
$items = array_values($items->toArray());
if (array_key_exists(2, $items)) {
$nextDoc = $items[2];
}
} else {
$items = $model->search($query->from($this->_position)->size(2));
$total = $items->getTotal();
$nextDoc = $items->last();
$last = $total - 1;
$items = $model->search($query->from($last)->size(1));
$prevDoc = $items->first();
}
if (!$nextDoc) {
$items = $model->search($query->from(0)->size(1));
$nextDoc = $items->first();
}
$this->_previous = $prevDoc;
$this->_next = $nextDoc;
} | php | {
"resource": ""
} |
q246497 | Relationshipable.setParent | validation | public function setParent(ElasticsearchModel $parent)
{
$this->_parent = $parent;
$this->setParentId($parent->getId());
} | php | {
"resource": ""
} |
q246498 | ElasticsearchModel.search | validation | public static function search($query = [])
{
if ($query instanceof QueryBuilder) {
$query = $query->build();
}
$model = static::createInstance();
return $model->_dal->search($query);
} | php | {
"resource": ""
} |
q246499 | ElasticsearchModel.map | validation | public static function map($query = [], callable $callback = null, $limit = -1)
{
if ($query instanceof QueryBuilder) {
$query = $query->build();
}
$query['from'] = Arr::get($query, 'from', 0);
$query['size'] = Arr::get($query, 'size', 50);
$i = 0;
$models = static::search($query);
$total = $models->getTotal();
while ($models) {
foreach ($models as $model) {
if ($callback) {
$callback($model);
}
$i++;
}
$query['from'] += $query['size'];
if ($i >= $total || ($limit > 0 && $i >= $limit)) {
break;
}
$models = static::search($query);
}
return $total;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.