_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q10300 | Resolver.createRequest | train | protected function createRequest(string $host, int $type): Request
{
$request = new Request();
$request->addQuestion($host, $type);
$request->setRecursionDesired(true);
return $request;
} | php | {
"resource": ""
} |
q10301 | Element.parseAttribute | train | private function parseAttribute(string $html) : string
{
$remainingHtml = ltrim($html);
try {
// Will match the first entire name/value attribute pair.
preg_match(
"/((([a-z0-9\-_]+:)?[a-z0-9\-_]+)(\s*=\s*)?)/i",
$remainingHtml,
$attributeMatches
);
$attributeName = $attributeMatches[2];
$remainingHtml = mb_substr(mb_strstr($remainingHtml, $attributeName), mb_strlen($attributeName));
if ($this->isAttributeValueless($remainingHtml)) {
$this->attributes[trim($attributeName)] = true;
return $remainingHtml;
}
return $this->parseAttributeValue($html, $remainingHtml, $attributeName);
} catch (ParseException $e) {
if ($this->getThrowOnError()) {
throw $e;
}
}
return '';
} | php | {
"resource": ""
} |
q10302 | Retry.run | train | public function run()
{
$count = 0;
$start = microtime(true);
while (true) {
try {
return call_user_func($this->callable);
} catch (\Throwable $e) {
// Check exception
if (!$e instanceof $this->exceptionType) {
throw $e;
}
// Check timeout
if ($this->timeout > -1 && microtime(true) - $start > ($this->timeout / self::SECONDS)) {
throw $e;
}
// Check count
if ($this->count > -1 && ++$count >= $this->count) {
throw $e;
}
// Before pause hook
if (array_key_exists(self::BEFORE_PAUSE_HOOK, $this->hooks)) {
call_user_func($this->hooks[self::BEFORE_PAUSE_HOOK], $e);
}
usleep($this->pause);
// After pause hook
if (array_key_exists(self::AFTER_PAUSE_HOOK, $this->hooks)) {
call_user_func($this->hooks[self::AFTER_PAUSE_HOOK], $e);
}
}
}
} | php | {
"resource": ""
} |
q10303 | Retry.setHook | train | public function setHook(string $hook, callable $callable): self
{
$availableHooks = [self::BEFORE_PAUSE_HOOK, self::AFTER_PAUSE_HOOK];
if (!in_array($hook, $availableHooks)) {
throw new \InvalidArgumentException('Invalid hook. Available hooks: ' . join(', ', $availableHooks));
}
$this->hooks[$hook] = $callable;
return $this;
} | php | {
"resource": ""
} |
q10304 | Retry.setExceptionType | train | public function setExceptionType(string $exceptionType): self
{
try {
$ref = new \ReflectionClass($exceptionType);
if (!$ref->implementsInterface(\Throwable::class)) {
throw new \InvalidArgumentException('Exception class must implement Throwable interface');
}
} catch (\ReflectionException $e) {
throw new \InvalidArgumentException('Exception class not found');
}
$this->exceptionType = $exceptionType;
return $this;
} | php | {
"resource": ""
} |
q10305 | CloudService.update | train | public function update($params, $optParams = [])
{
if (!$params instanceof Cloud) {
throw new InvalidParamException(Cloud::class . ' is required!');
}
return $this->sendRequest([], [
'restAction' => 'update',
'restId' => $params->id,
'postParams' => $params->toArray(),
'getParams' => $optParams,
], function ($response) {
return isset($response->data) ? new Cloud($response->data) : $response;
});
} | php | {
"resource": ""
} |
q10306 | CloudService.delete | train | public function delete($params, $optParams = [])
{
if ($params instanceof Cloud) {
$params = $params->id;
}
return $this->sendRequest([], [
'restAction' => 'delete',
'restId' => $params,
'getParams' => $optParams,
], function ($response) {
return $response->success;
});
} | php | {
"resource": ""
} |
q10307 | HtmlTokenizer.parse | train | public function parse(string $html) : TokenCollection
{
self::$allHtml = $html;
$tokens = new TokenCollection();
$remainingHtml = trim($html);
while (mb_strlen($remainingHtml) > 0) {
$token = TokenFactory::buildFromHtml(
$remainingHtml,
null,
$this->throwOnError
);
if (!$token instanceof Token) {
// Error has occurred, so we stop.
break;
}
$remainingHtml = $token->parse($remainingHtml);
$tokens[] = $token;
}
return $tokens;
} | php | {
"resource": ""
} |
q10308 | Arr.parse | train | public function parse(AbstractStream $stream)
{
try {
return parent::parse($stream);
} catch (\OutOfBoundsException $e) {
if ($this->isUntilEof()) {
return $this->dataSet->getData();
}
throw $e;
}
} | php | {
"resource": ""
} |
q10309 | Compiler.generateText | train | protected function generateText($node)
{
$buffer = '';
$value = explode("\n", $node['value']);
$last = count($value) - 1;
foreach ($value as $i => $line) {
$line = str_replace("'", '\\\'', $line);
if ($i === $last) {
$buffer .= $this->prettyPrint(sprintf(self::BLOCK_TEXT_LAST, $line));
continue;
}
$buffer .= $this->prettyPrint(sprintf(self::BLOCK_TEXT_LINE, $line));
}
return $buffer;
} | php | {
"resource": ""
} |
q10310 | Compiler.generatePartials | train | protected function generatePartials()
{
$partials = $this->handlebars->getPartials();
foreach ($partials as $name => $partial) {
$partials[$name] = sprintf(
self::BLOCK_OPTIONS_HASH_KEY_VALUE,
$name,
"'" . str_replace("'", '\\\'', $partial) . "'"
);
}
return $this->prettyPrint(self::BLOCK_OPTIONS_OPEN)
. $this->prettyPrint('\r\t')
. implode($this->prettyPrint(',\r\t'), $partials)
. $this->prettyPrint(self::BLOCK_OPTIONS_CLOSE);
} | php | {
"resource": ""
} |
q10311 | Compiler.parseArguments | train | protected function parseArguments($string)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$args = array();
$hash = array();
$regex = array(
'([a-zA-Z0-9]+\="[^"]*")', // cat="meow"
'([a-zA-Z0-9]+\=\'[^\']*\')', // mouse='squeak squeak'
'([a-zA-Z0-9]+\=[a-zA-Z0-9]+)', // dog=false
'("[^"]*")', // "some\'thi ' ng"
'(\'[^\']*\')', // 'some"thi " ng'
'([^\s]+)' // <any group with no spaces>
);
preg_match_all('#'.implode('|', $regex).'#is', $string, $matches);
$stringArgs = $matches[0];
$name = array_shift($stringArgs);
$hashRegex = array(
'([a-zA-Z0-9]+\="[^"]*")', // cat="meow"
'([a-zA-Z0-9]+\=\'[^\']*\')', // mouse='squeak squeak'
'([a-zA-Z0-9]+\=[a-zA-Z0-9]+)', // dog=false
);
foreach ($stringArgs as $arg) {
//if it's an attribute
if (!(substr($arg, 0, 1) === "'" && substr($arg, -1) === "'")
&& !(substr($arg, 0, 1) === '"' && substr($arg, -1) === '"')
&& preg_match('#'.implode('|', $hashRegex).'#is', $arg)
) {
list($hashKey, $hashValue) = explode('=', $arg, 2);
$hash[$hashKey] = $this->parseArgument($hashValue);
continue;
}
$args[] = $this->parseArgument($arg);
}
return array($name, $args, $hash);
} | php | {
"resource": ""
} |
q10312 | Compiler.parseArgument | train | protected function parseArgument($arg)
{
//if it's a literal string value
if (strpos($arg, '"') === 0
|| strpos($arg, "'") === 0
) {
return "'" . str_replace("'", '\\\'', substr($arg, 1, -1)) . "'";
}
//if it's null
if (strtolower($arg) === 'null'
|| strtolower($arg) === 'true'
|| strtolower($arg) === 'false'
|| is_numeric($arg)
) {
return $arg;
}
$arg = str_replace(array('[', ']', '(', ')'), '', $arg);
$arg = str_replace("'", '\\\'', $arg);
return sprintf(self::BLOCK_ARGUMENT_VALUE, $arg);
} | php | {
"resource": ""
} |
q10313 | LoggerAwareTrait.getLogger | train | protected function getLogger()
{
if (!isset($this->logger)) {
// When no logger is injected, create a new one
// that doesn't do anything
$this->logger = new Logger('api-client');
$this->logger->setHandlers([
new NullHandler(),
]);
}
return $this->logger;
} | php | {
"resource": ""
} |
q10314 | Ratings.addRating | train | public function addRating($videoId, $rating)
{
$this->validateRating($rating);
$customMetaData = $this->getVideo($videoId)->getCustomMetadata();
$average = $this->getRatingAverage($videoId);
$count = $this->getRatingCount($videoId);
$newCount = $count + 1;
$customMetaData[$this->metadataFieldCount] = $newCount;
$customMetaData[$this->metadataFieldAverage] = (($average * $count) + $rating) / $newCount;
$this->storeCustomMetaData($customMetaData, $videoId);
} | php | {
"resource": ""
} |
q10315 | Ratings.getCustomMetaDataField | train | private function getCustomMetaDataField($videoId, $customMetaDataField)
{
$customMetaData = $this->getVideo($videoId)->getCustomMetadata();
return array_key_exists($customMetaDataField, $customMetaData)
? (float) $customMetaData[$customMetaDataField]
: 0;
} | php | {
"resource": ""
} |
q10316 | Ratings.storeCustomMetaData | train | private function storeCustomMetaData($customMetaData, $videoId)
{
// only update custom meta data fields related to rating
$this->client->setCustomMetaData(
$this->vmId,
$videoId,
$this->filterCustomMetaData($customMetaData)
);
// also store custom meta data fields locally, if video is fetched again by function $this->getVideo($videoId)
$this->getVideo($videoId)->setCustomMetadata($customMetaData);
} | php | {
"resource": ""
} |
q10317 | Ratings.getVideo | train | private function getVideo($videoId)
{
if (!array_key_exists($videoId, $this->videos)) {
$options = new VideoRequestParameters();
$options->setIncludeCustomMetadata(true);
$this->videos[$videoId] = $this->client->getVideo($this->vmId, $videoId, $options);
}
return $this->videos[$videoId];
} | php | {
"resource": ""
} |
q10318 | Ratings.filterCustomMetaData | train | private function filterCustomMetaData($customMetaData)
{
foreach ($customMetaData as $key => $data) {
if (!in_array($key, [$this->metadataFieldCount, $this->metadataFieldAverage])) {
unset($customMetaData[$key]);
}
}
return $customMetaData;
} | php | {
"resource": ""
} |
q10319 | Sequence.push | train | public function push($value, int $repeat = null): self
{
if ($repeat !== null && $repeat <= 0) {
throw new InvalidArgumentException(sprintf(static::MSG_NEGATIVE_ARGUMENT_NOT_ALLOWED, 2, 1));
}
for ($i = 0; $i < ($repeat ?? 1); $i++) {
$this->values[] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q10320 | Sequence.pushAll | train | public function pushAll(array $values): self
{
foreach ($values as $value) {
$this->push($value);
}
return $this;
} | php | {
"resource": ""
} |
q10321 | AccessTokenService.update | train | public function update($params, $optParams = [])
{
if (!$params instanceof AccessToken) {
throw new InvalidParamException(AccessToken::class . ' is required!');
}
$class = get_class($params);
return $this->sendRequest([], [
'restAction' => 'update',
'restId' => $params->id,
'postParams' => $params->toArray(),
'getParams' => $optParams,
], function ($response) use ($class) {
return isset($response->data) ? new $class($response->data) : $response;
});
} | php | {
"resource": ""
} |
q10322 | AccessTokenService.view | train | public function view($params, $optParams = [])
{
if (!$params instanceof AccessToken) {
throw new InvalidParamException(AccessToken::class . ' is required!');
}
$class = get_class($params);
return $this->sendRequest([], [
'restAction' => 'view',
'restId' => $params->id,
'getParams' => $optParams,
], function ($response) use ($class) {
return isset($response->data) ? new $class($response->data) : $response;
});
} | php | {
"resource": ""
} |
q10323 | AnnotationParser.extractContent | train | private function extractContent($docComment, $annotationClass)
{
$isRecording = false;
$content = '';
// remove doc comment stars at line start
$docComment = preg_replace('/^[ \t]*(\*\/? ?|\/\*\*)/m', '', $docComment);
$search = '(' .
preg_quote($annotationClass, '/')
. '|'
. substr($annotationClass, strrpos($annotationClass, '\\') + 1)
. ')';
$lines = preg_split('/\n|\r\n/', $docComment);
foreach ($lines as $line) {
if ($isRecording === false && preg_match('/^@' . $search . '(\s|\(|$)/', $line)) {
$isRecording = true;
} elseif ($isRecording) {
if (preg_match('/^@/', $line)) {
break;
}
$content .= $line . PHP_EOL;
}
}
return trim($content);
} | php | {
"resource": ""
} |
q10324 | StringSupport.parametrize | train | public static function parametrize($str, $params)
{
$keys = array_keys($params);
$vals = array_values($params);
array_walk($keys, function(&$key) {
$key = '%' . $key . '%';
});
return str_replace($keys, $vals, $str);
} | php | {
"resource": ""
} |
q10325 | StringSupport.findOne | train | public static function findOne($pattern, $entries)
{
$found = [];
foreach ($entries as $entry)
{
if (static::match($pattern, $entry))
{
$found[] = $entry;
}
}
return $found;
} | php | {
"resource": ""
} |
q10326 | DumpAction.run | train | public function run($type = 'default')
{
$this->stdout("dump {$type}:\n", Console::FG_GREEN);
switch ($type) {
case 'default':
foreach ($this->ipv4->getQueries() as $name => $query) {
$this->dumpDefault($query, $name);
}
break;
case 'division':
foreach ($this->ipv4->getQueries() as $name => $query) {
$this->dumpDivision($query, $name);
}
break;
case 'division_id':
foreach ($this->ipv4->getQueries() as $name => $query) {
if (FileQuery::is_a($query)) {
$this->dumpDivisionWithId($query, $name);
}
}
break;
default:
$this->stderr("Unknown type \"{$type}\".\n", Console::FG_GREY, Console::BG_RED);
break;
}
} | php | {
"resource": ""
} |
q10327 | AssetFormHelper.typeField | train | public static function typeField($type = '', $locale = null, $name = 'type'): string
{
$result = '<input type="hidden" value="'.$type.'" name="';
if (! $locale) {
return $result.$name.'">';
}
return $result.'trans['.$locale.'][files][]">';
} | php | {
"resource": ""
} |
q10328 | MenuHelper.setPageTitle | train | public function setPageTitle(array $config): void
{
foreach ($config as $item) {
if (isset($item['active']) && $item['active']) {
$this->_View->assign('title', $item['title']);
break;
}
}
} | php | {
"resource": ""
} |
q10329 | MenuHelper._hasAllowedChildren | train | protected function _hasAllowedChildren(array $children): bool
{
foreach ($children as $child) {
if ($this->Auth->urlAllowed($child['url'])) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q10330 | MenuHelper._isItemActive | train | protected function _isItemActive(array $item): bool
{
if (empty($item['url'])) {
return false;
}
$current = $this->_currentUrl;
if (!empty($item['url']['plugin']) && $item['url']['plugin'] != $current['plugin']) {
return false;
}
if ($item['url']['controller'] == $current['controller'] && $item['url']['action'] == $current['action']) {
$this->_controllerActive = $current['controller'];
$this->_actionActive = $item['url']['action'];
return true;
}
if (!empty($this->_actionActive) && $item['url']['controller'] == $current['controller']) {
$this->_controllerActive = $current['controller'];
return true;
}
return false;
} | php | {
"resource": ""
} |
q10331 | FeatureTypeAvMeta.setFeatureAv | train | public function setFeatureAv(ChildFeatureAv $v = null)
{
if ($v === null) {
$this->setFeatureAvId(NULL);
} else {
$this->setFeatureAvId($v->getId());
}
$this->aFeatureAv = $v;
// Add binding for other direction of this n:n relationship.
// If this object has already been added to the ChildFeatureAv object, it will not be re-added.
if ($v !== null) {
$v->addFeatureTypeAvMeta($this);
}
return $this;
} | php | {
"resource": ""
} |
q10332 | FeatureTypeAvMeta.getFeatureAv | train | public function getFeatureAv(ConnectionInterface $con = null)
{
if ($this->aFeatureAv === null && ($this->feature_av_id !== null)) {
$this->aFeatureAv = FeatureAvQuery::create()->findPk($this->feature_av_id, $con);
/* The following can be used additionally to
guarantee the related object contains a reference
to this object. This level of coupling may, however, be
undesirable since it could result in an only partially populated collection
in the referenced object.
$this->aFeatureAv->addFeatureTypeAvMetas($this);
*/
}
return $this->aFeatureAv;
} | php | {
"resource": ""
} |
q10333 | FeatureTypeAvMeta.setFeatureFeatureType | train | public function setFeatureFeatureType(ChildFeatureFeatureType $v = null)
{
if ($v === null) {
$this->setFeatureFeatureTypeId(NULL);
} else {
$this->setFeatureFeatureTypeId($v->getId());
}
$this->aFeatureFeatureType = $v;
// Add binding for other direction of this n:n relationship.
// If this object has already been added to the ChildFeatureFeatureType object, it will not be re-added.
if ($v !== null) {
$v->addFeatureTypeAvMeta($this);
}
return $this;
} | php | {
"resource": ""
} |
q10334 | FeatureTypeAvMeta.getFeatureFeatureType | train | public function getFeatureFeatureType(ConnectionInterface $con = null)
{
if ($this->aFeatureFeatureType === null && ($this->feature_feature_type_id !== null)) {
$this->aFeatureFeatureType = ChildFeatureFeatureTypeQuery::create()->findPk($this->feature_feature_type_id, $con);
/* The following can be used additionally to
guarantee the related object contains a reference
to this object. This level of coupling may, however, be
undesirable since it could result in an only partially populated collection
in the referenced object.
$this->aFeatureFeatureType->addFeatureTypeAvMetas($this);
*/
}
return $this->aFeatureFeatureType;
} | php | {
"resource": ""
} |
q10335 | HealthBuilder.status | train | public function status($status)
{
if (!($status instanceof Status)) {
$status = new Status($status);
}
$this->status = $status;
return $this;
} | php | {
"resource": ""
} |
q10336 | HealthBuilder.withDetail | train | public function withDetail($key, $message)
{
assert(!is_null($key), 'Key must not be null');
assert(!is_null($message), 'Message must not be null');
$this->details[strval($key)] = $message;
return $this;
} | php | {
"resource": ""
} |
q10337 | DefaultDoctrineUserRepository.createUser | train | protected function createUser(array $credentials)
{
$entity = static::ENTITY_CLASSNAME;
if (count(array_only($credentials, ['email', 'password', 'username'])) < 3)
{
throw new \InvalidArgumentException("Missing arguments.");
}
/** @var User $user */
$user = new $entity(
$credentials['email'],
$credentials['password'],
$credentials['username']
);
$rest = array_except($credentials, ['email', 'username', 'password']);
if (! empty($rest))
{
$user->update($rest);
}
return $user;
} | php | {
"resource": ""
} |
q10338 | SortableControllerTrait.sort | train | public function sort(): ServiceResponse
{
$this->request->allowMethod('post');
if (!empty($this->sortModelName) && !empty($this->request->getData('foreignKey'))) {
$table = TableRegistry::getTableLocator()->get($this->sortModelName);
$entity = $table->get($this->request->getData('foreignKey'));
$entity->sort = $this->request->getData('sort');
if ($table->save($entity)) {
return new ServiceResponse(ApiReturnCode::SUCCESS, [
$entity->id,
$this->request->getData('sort'),
]);
}
return new ServiceResponse(ApiReturnCode::INTERNAL_ERROR, []);
}
throw new NotFoundException();
} | php | {
"resource": ""
} |
q10339 | IndentStyleTrait.setIndentStyle | train | public function setIndentStyle($indentStyle)
{
if (!in_array($indentStyle, [null, Lexer::INDENT_TAB, Lexer::INDENT_SPACE])) {
throw new \InvalidArgumentException(
'indentStyle needs to be null or one of the INDENT_* constants of the lexer'
);
}
$this->indentStyle = $indentStyle;
return $this;
} | php | {
"resource": ""
} |
q10340 | IndentStyleTrait.setIndentWidth | train | public function setIndentWidth($indentWidth)
{
if (!is_null($indentWidth) &&
(!is_int($indentWidth) || $indentWidth < 1)
) {
throw new \InvalidArgumentException(
'indentWidth needs to be null or an integer above 0'
);
}
$this->indentWidth = $indentWidth;
return $this;
} | php | {
"resource": ""
} |
q10341 | ObjectManager.getHydratorFor | train | public function getHydratorFor($objectClass)
{
if (! isset($this->hydratorInstances[$objectClass])) {
$this->hydratorInstances[$objectClass] = $this->createHydratorFor($objectClass);
}
return $this->hydratorInstances[$objectClass];
} | php | {
"resource": ""
} |
q10342 | ObjectManager.createHydratorFor | train | public function createHydratorFor($objectClass)
{
$metadata = $this->getMetadata($objectClass);
$propertyAccessStrategy = $metadata->isPropertyAccessStrategyEnabled();
$hydrator = new Hydrator\Hydrator($this, $propertyAccessStrategy);
if ($this->classResolver) {
$hydrator->setClassResolver($this->classResolver);
}
$fieldsWithHydrationStrategy = $metadata->computeFieldsWithHydrationStrategy();
$mappedFieldNames = $metadata->getMappedFieldNames();
foreach ($mappedFieldNames as $mappedFieldName) {
$strategy = null;
if ($metadata->isMappedFieldWithStrategy($mappedFieldName)) {
$fieldStrategy = $fieldsWithHydrationStrategy[$mappedFieldName];
$strategy = new ClosureHydrationStrategy(
$fieldStrategy[$metadata::INDEX_EXTRACTION_STRATEGY],
$fieldStrategy[$metadata::INDEX_HYDRATION_STRATEGY]
);
}
if ($metadata->isMappedDateField($mappedFieldName)) {
$readDateConverter = $metadata->getReadDateFormatByMappedField($mappedFieldName, null);
$writeDateConverter = $metadata->getWriteDateFormatByMappedField($mappedFieldName, null);
if (! is_null($readDateConverter) && ! is_null($writeDateConverter)) {
$strategy = new DateHydrationStrategy($readDateConverter, $writeDateConverter, $strategy);
} else {
throw new ObjectMappingException(
sprintf(
'The date field "%s" should provide "readDateConverter" and "writeDateConverter" metadata.',
$mappedFieldName
)
);
}
}
if (! is_null($strategy)) {
$hydrator->addStrategy($mappedFieldName, $strategy);
}
}
//------------------------------------------------------------------------------------------
if ($metadata->eventsExist()) {
$hydrator = new Hydrator\EventHydrator($hydrator, $this);
}
return $hydrator;
} | php | {
"resource": ""
} |
q10343 | ObjectManager.getMetadata | train | public function getMetadata($objectClass)
{
if (! $objectClass instanceof ObjectKey) {
$objectClass = new ObjectKey($objectClass);
}
$key = $objectClass->getKey();
return $this->classMetadataFactory->loadMetadata(
$objectClass,
LoadingCriteria::createFromConfiguration($this->configuration, $objectClass),
$this->configuration
);
} | php | {
"resource": ""
} |
q10344 | DataMapperBuilder.instance | train | public function instance()
{
$settings = $this->getValidatedSettings();
$objectManager = $this->createObjectManager($settings);
$logger = isset($settings['logger']) ? isset($settings['logger']) : null;
$this->initializeRegistry($objectManager, $logger);
return new DataMapper($objectManager);
} | php | {
"resource": ""
} |
q10345 | DataMapperBuilder.getValidatedSettings | train | private function getValidatedSettings()
{
$processor = new Processor();
$settingsValidator = new SettingsValidator();
$validatedSettings = $processor->processConfiguration(
$settingsValidator,
$this->pSettings
);
return $validatedSettings;
} | php | {
"resource": ""
} |
q10346 | DefaultCache.getItemKey | train | private function getItemKey(
string $sectionHandle,
array $requestedFields = null,
string $context = null,
string $id = null
): string {
return sha1($sectionHandle) .
$this->getFieldKey($requestedFields) .
$this->getContextKey($context) .
$this->getIdKey($id);
} | php | {
"resource": ""
} |
q10347 | DefaultCache.getFieldKey | train | private function getFieldKey(array $requestedFields = null): string
{
if (is_null($requestedFields)) {
return 'no-field-key';
}
return $fieldKey = '.' . sha1(implode(',', $requestedFields));
} | php | {
"resource": ""
} |
q10348 | DefaultCache.getRelationships | train | private function getRelationships(FullyQualifiedClassName $fullyQualifiedClassName): array
{
$fields = (string)$fullyQualifiedClassName;
if (!is_subclass_of($fields, CommonSectionInterface::class)) {
throw new NotASexyFieldEntityException;
}
/** @var CommonSectionInterface $fields */
$relationships = [];
foreach ($fields::fieldInfo() as $field) {
if (!is_null($field['relationship'])) {
$relationships[] = $field['relationship']['class'];
}
}
return $relationships;
} | php | {
"resource": ""
} |
q10349 | Searchable.getIndices | train | public function getIndices()
{
$indices = $this->indices();
if (empty($indices)) {
$className = (new \ReflectionClass($this))->getShortName();
return [$className];
}
return $indices;
} | php | {
"resource": ""
} |
q10350 | DoctrineReminderRepository.exists | train | public function exists(UserInterface $user, $code = null)
{
return $this->findIncomplete($user, $code) !== null;
} | php | {
"resource": ""
} |
q10351 | DoctrineReminderRepository.complete | train | public function complete(UserInterface $user, $code, $password)
{
$reminder = $this->findIncomplete($user, $code);
if ($reminder === null)
{
return false;
}
$credentials = ['password' => $password];
if (! $this->users->validForUpdate($user, $credentials))
{
return false;
}
$entityManager = $this->getEntityManager();
$entityManager->beginTransaction();
try
{
$this->users->update($user, $credentials);
$reminder->complete();
$this->save($reminder);
$entityManager->commit();
return true;
}
catch (\Exception $e)
{
$entityManager->rollback();
return false;
}
} | php | {
"resource": ""
} |
q10352 | AlgoliaFactory.make | train | public function make(AlgoliaConfig $config)
{
return new AlgoliaManager(
new Client(
$config->getApplicationId(),
$config->getApiKey(),
$config->getHostsArray(),
$config->getOptions()
),
new ActiveRecordFactory(),
new ActiveQueryChunker()
);
} | php | {
"resource": ""
} |
q10353 | Middleware.sendRequestThroughRouter | train | protected function sendRequestThroughRouter(Request $request)
{
return (new Pipeline($this->app))->send($request)->then(function ($request) {
/**
* @var Response $response
*/
$response = $this->router->dispatch($request);
if (property_exists($response, 'exception') && $response->exception instanceof Exception) {
throw $response->exception;
}
return $response;
});
} | php | {
"resource": ""
} |
q10354 | AbstractCoreApiClient.generateCacheKey | train | private function generateCacheKey($method, $uri, array $options = [])
{
return sha1(sprintf('%s.%s.%s.%s', get_class($this), $method, $uri, json_encode($options)));
} | php | {
"resource": ""
} |
q10355 | AbstractCoreApiClient.isCacheable | train | private function isCacheable($method, $uri, array $options, $response)
{
/** @var ResponseInterface $statusCode */
$statusCode = $response->getStatusCode();
//cache only 2** responses
if ($statusCode < 200 || $statusCode >= 300) {
return false;
}
//GET is always safe to cache
if ('GET' === $method) {
return true;
}
//POST may be cached for certain endpoints only (forgive us Roy Fielding)
if ('POST' === $method) {
return in_array($uri, self::CACHEABLE_POST_ENDPOINTS);
}
//assume not cacheable in all other cases
return false;
} | php | {
"resource": ""
} |
q10356 | UserRepository.query | train | public function query($q = null)
{
return User::where(function ($query) use ($q) {
$query->where('email', 'like', "%{$q}")
->orWhere('name', 'like', "%{$q}");
})->orderBy('email')->paginate();
} | php | {
"resource": ""
} |
q10357 | Generator.shouldIgnore | train | protected function shouldIgnore(FieldInterface $field): bool
{
$fieldType = $this->container->get(
(string) $field->getFieldType()->getFullyQualifiedClassName()
);
// The field type generator config refers to how the field type itself is defined
// as a service. You can see that in the services.yml
$fieldTypeGeneratorConfig = $fieldType->getFieldTypeGeneratorConfig()->toArray();
if (!key_exists(static::GENERATE_FOR, $fieldTypeGeneratorConfig)) {
return true;
}
// See if this field is to be ignored by this generator because it's explicitly
// set to ignore === true
try {
// The field generator config refers to how the field instructs the generator
// You see that in the field configuration yml
$fieldGeneratorConfig = $field->getConfig()->getGeneratorConfig()->toArray();
if (!empty($fieldGeneratorConfig[static::GENERATE_FOR]['ignore']) &&
$fieldGeneratorConfig[static::GENERATE_FOR]['ignore']
) {
return true;
}
} catch (\Exception $exception) {}
return false;
} | php | {
"resource": ""
} |
q10358 | Generator.getFieldTypeTemplateDirectory | train | protected function getFieldTypeTemplateDirectory(
FieldInterface $field,
string $supportingDirectory
) {
/** @var FieldTypeInterface $fieldType */
$fieldType = $this->container->get((string) $field->getFieldType()->getFullyQualifiedClassName());
$fieldTypeDirectory = explode('/', $fieldType->directory());
foreach ($fieldTypeDirectory as $key => $segment) {
if ($segment === 'vendor') {
$selector = $key + 2;
$fieldTypeDirectory[$selector] = $supportingDirectory;
break;
}
}
return implode('/', $fieldTypeDirectory);
} | php | {
"resource": ""
} |
q10359 | Watermark.applyWatermarkImagick | train | private function applyWatermarkImagick(Imagick $image)
{
$pictureWidth = $image->getImageWidth();
$pictureHeight = $image->getImageHeight();
$watermarkPicture = new Picture($this->watermark, NULL, Picture::WORKER_IMAGICK);
$opacity = new Opacity($this->opacity);
$opacity->apply($watermarkPicture);
if($this->size)
{
$resize = new Resize(
$pictureWidth / 100 * $this->size,
$pictureHeight / 100 * $this->size,
Resize::MODE_FIT
);
$resize->apply($watermarkPicture);
}
$watermark = $watermarkPicture->getResource(Picture::WORKER_IMAGICK);
$watermarkWidth = $watermark->getImageWidth();
$watermarkHeight = $watermark->getImageHeight();
switch($this->position)
{
case 'repeat':
for($w = 0; $w < $pictureWidth; $w += $watermarkWidth + $this->space)
{
for($h = 0; $h < $pictureHeight; $h += $watermarkHeight + $this->space)
{
$image->compositeImage($watermark, $watermark->getImageCompose(), $w, $h);
}
}
return;
case 'center':
$positionX = ($image->getImageWidth() - $watermark->getImageWidth()) / 2 - $this->offsetX;
$positionY = ($image->getImageHeight() - $watermark->getImageHeight()) / 2 - $this->offsetY;
break;
case 'topRight':
$positionX = $image->getImageWidth() - $watermark->getImageWidth() - $this->offsetX;
$positionY = $this->offsetY;
break;
case 'bottomRight':
$positionX = $image->getImageWidth() - $watermark->getImageWidth() - $this->offsetX;
$positionY = $image->getImageHeight() - $watermark->getImageHeight() - $this->offsetY;
break;
case 'bottomLeft':
$positionX = $this->offsetX;
$positionY = $image->getImageHeight() - $watermark->getImageHeight() - $this->offsetY;
break;
default:
$positionX = $this->offsetX;
$positionY = $this->offsetY;
break;
}
$image->compositeImage($watermark, $watermark->getImageCompose(), $positionX, $positionY);
} | php | {
"resource": ""
} |
q10360 | Watermark.applyWatermarkGD | train | protected function applyWatermarkGD($resource, Picture $picture) {
// SOURCE IMAGE DIMENSIONS
$pictureWidth = imagesx($resource);
$pictureHeight = imagesy($resource);
// WATERMARK DIMENSIONS
$watermarkPicture = new Picture($this->watermark, NULL, Picture::WORKER_GD);
$opacity = new Opacity($this->opacity);
$opacity->apply($watermarkPicture);
if($this->size)
{
$resize = new Resize(
$pictureWidth / 100 * $this->size,
$pictureHeight / 100 * $this->size,
Resize::MODE_FIT
);
$resize->apply($watermarkPicture);
}
$watermark = $watermarkPicture->getResource($watermarkPicture::WORKER_GD);
imagealphablending($watermark, TRUE);
$watermarkWidth = imagesx($watermark);
$watermarkHeight = imagesx($watermark);
// CALCULATE WATERMARK POSITION
switch($this->position)
{
case 'repeat':
for($w = 0; $w < $pictureWidth; $w += $watermarkWidth + $this->space)
{
for($h = 0; $h < $pictureHeight; $h += $watermarkHeight + $this->space)
{
imagecopy($resource, $watermark, $w, $h, 0, 0, $watermarkWidth, $watermarkHeight);
}
}
return $resource;
case 'center':
$positionX = ($pictureWidth - $watermarkWidth) / 2 - $this->offsetX;
$positionY = ($pictureHeight - $watermarkHeight) / 2 - $this->offsetY;
break;
case 'topRight':
$positionX = $pictureWidth - $watermarkWidth - $this->offsetX;
$positionY = $this->offsetY;
break;
case 'bottomRight':
$positionX = $pictureWidth - $watermarkWidth - $this->offsetX;
$positionY = $pictureHeight - $watermarkHeight - $this->offsetY;
break;
case 'bottomLeft':
$positionX = $this->offsetX;
$positionY = $pictureHeight - $watermarkHeight - $this->offsetY;
break;
default:
$positionX = $this->offsetX;
$positionY = $this->offsetY;
break;
}
imagecopy($resource, $watermark, $positionX, $positionY, 0, 0, $watermarkWidth, $watermarkHeight);
return $resource;
} | php | {
"resource": ""
} |
q10361 | Application.run | train | public function run(Request $request = null)
{
\ini_set('display_errors', $this->config['debug'] ? 1 : 0);
\ini_set('display_startup_errors', $this->config['debug'] ? 1 : 0);
\date_default_timezone_set($this->config['timezone']);
// map all routes
foreach ($this->routes as $r => &$x) {
if (isset($x['controller'])) {
$this->router->map($x['method'], $r, $x['action'], $x['controller']);
} else foreach ($x as &$xx) {
$this->router->map($xx['method'], $r, $xx['action'], $xx['controller']);
}
}
// dispatch
try {
try {
$this->router->dispatch(
$request === null ? Request::createFromGlobals() : $request,
new class(
(new MultiControllerFactory(...$this->controller_factories))->close(),
$this->endobox,
$this->logger,
$this->config['app-namespace']) extends ControllerFactoryDecorator {
private $endobox;
private $logger;
private $namespace;
public function __construct(
ControllerFactory $factory,
BoxFactory $endobox,
Logger $logger,
string $namespace) {
parent::__construct($factory);
$this->endobox = $endobox;
$this->logger = $logger;
$this->namespace = $namespace;
}
public function create(string $type) : ?Controller {
return parent::create('\\' . $this->namespace . '\\controllers\\' . $type)
->setBoxFactory($this->endobox)
->setLogger($this->logger);
}
});
} catch (\Klein\Exceptions\UnhandledException $e) {
// TODO fix this mess with the stack trace being part of the message
throw new \RuntimeException(\sprintf("%s: %s\n<pre>%s</pre>",
\get_class($e), $e->getMessage(), $e->getTraceAsString()), $e->getCode(), $e);
}
} catch (\Exception $e) {
if ($this->config['catch-exceptions'] === false) {
throw $e;
}
if ($this->config['debug'] === true) {
die(self::formatException($e));
}
die();
}
return $this;
} | php | {
"resource": ""
} |
q10362 | Money.make | train | public static function make(string $country = null)
{
if (empty($country)) {
$country = config('default');
}
return (new static() )->setCurrency($country);
} | php | {
"resource": ""
} |
q10363 | Money.setCurrency | train | public function setCurrency($country = null)
{
if (is_null($country)) {
$country = config('currency.default');
}
$config = config('currency.' . $country);
if (empty($config)) {
throw new CurrencyNotAvaialbleException($country . ' currency not avaialble.');
}
$this->currency = $config;
return $this;
} | php | {
"resource": ""
} |
q10364 | Money.getCurrency | train | public function getCurrency()
{
if (! empty($this->currency)) {
return $this->currency;
}
return $this->setCurrency(config('currency.default'))->getCurrency();
} | php | {
"resource": ""
} |
q10365 | Money.toCommon | train | public function toCommon(int $amount, bool $format = true): string
{
$money = $this->castMoney($amount, $this->getCurrencySwiftCode());
$moneyFormatter = new DecimalMoneyFormatter(new ISOCurrencies());
return ($format) ?
number_format($moneyFormatter->format($money), 2, '.', ',') :
$moneyFormatter->format($money);
} | php | {
"resource": ""
} |
q10366 | Money.toMachine | train | public function toMachine(string $amount, string $swift_code = ''): int
{
$swift_code = empty($swift_code) ? config('currency.default_swift_code') : $swift_code;
return (new DecimalMoneyParser(
new ISOCurrencies()
))->parse(
preg_replace('/[^0-9.-]/im', '', $amount),
(new Currency($swift_code))
)->getAmount();
} | php | {
"resource": ""
} |
q10367 | Money.convertFixedRate | train | public function convertFixedRate(array $fixedExchange, int $amount, string $swift_code): MoneyPHP
{
return (new Converter(
new ISOCurrencies(),
(new ReversedCurrenciesExchange(new FixedExchange($fixedExchange)))
))->convert($this->castMoney($amount), new Currency($swift_code));
} | php | {
"resource": ""
} |
q10368 | AbstractReadableStream.handleCancel | train | protected function handleCancel(CancellationException $e): ?string
{
throw $this->closed ? ($e->getPrevious() ?? $e) : $e;
} | php | {
"resource": ""
} |
q10369 | XmlException.createUsingErrors | train | public static function createUsingErrors(array $errors)
{
$message = "An error was encountered reading an XML document:\n";
foreach ($errors as $error) {
switch ($error->level) {
case LIBXML_ERR_ERROR:
$message .= '[Error] ';
break;
case LIBXML_ERR_FATAL:
$message .= '[Fatal] ';
break;
case LIBXML_ERR_WARNING:
$message .= '[Warning] ';
break;
}
$message .= sprintf(
"[line %d] [column %d] %s in \"%s\".\n",
$error->line,
$error->column,
trim($error->message),
$error->file
);
}
return new self($message);
} | php | {
"resource": ""
} |
q10370 | SwaggerUIServiceProvider.boot | train | public function boot(Application $app)
{
// Reference to $this, it's used for closure in anonymous function (PHP 5.3.x)
$self = &$this;
$app->get($app['swaggerui.path'], function(Request $request) use ($app) {
return str_replace(
array('{{swaggerui-root}}', '{{swagger-docs}}'),
array($request->getBasePath() . $app['swaggerui.path'], $request->getBasePath() . $app['swaggerui.apiDocPath']),
file_get_contents(__DIR__ . '/../../../../public/index.html')
);
});
$app->get($app['swaggerui.path'] . '/{resource}', function($resource) use ($app) {
$file = __DIR__ . '/../../../../public/' . $resource;
if (is_file($file)) {
return file_get_contents($file);
}
return '';
});
$app->get($app['swaggerui.path'] . '/lib/{resource}', function($resource) use ($app, $self) {
return $self->getFile(
__DIR__ . '/../../../../public/lib/' . $resource,
'text/javascript'
);
});
$app->get($app['swaggerui.path'] . '/css/{resource}', function($resource) use ($app, $self) {
return $self->getFile(
__DIR__ . '/../../../../public/css/' . $resource,
'text/css'
);
});
$app->get($app['swaggerui.path'] . '/images/{resource}', function($resource) use ($app, $self) {
return $self->getFile(
__DIR__ . '/../../../../public/images/' . $resource,
'image/png'
);
});
} | php | {
"resource": ""
} |
q10371 | SwaggerUIServiceProvider.getFile | train | public function getFile($path, $contentType) {
if (is_file($path)) {
$response = new Response(file_get_contents($path));
$response->headers->set('Content-Type', $contentType);
$response->setCharset('UTF-8');
return $response;
}
return new Response('', 404);
} | php | {
"resource": ""
} |
q10372 | Option.addMultiItem | train | private function addMultiItem()
{
$args = func_get_args();
$optionKey = array_shift($args);
$this->items[] = sprintf("%s:%s", $optionKey, implode(',', $args));
return $this;
} | php | {
"resource": ""
} |
q10373 | PdfGenerator._getView | train | protected function _getView(): View
{
if (!$this->getConfig('view')) {
$view = new View();
foreach ($this->getConfig('helpers') as $helper) {
$view->loadHelper($helper);
}
$this->setConfig('view', $view);
}
return $this->getConfig('view');
} | php | {
"resource": ""
} |
q10374 | PdfGenerator._preparePdf | train | protected function _preparePdf($viewFile, $viewVars): Mpdf
{
$mpdf = new Mpdf($this->_config['mpdfSettings']);
if (is_callable($this->_config['mpdfConfigurationCallback'])) {
$this->_config['mpdfConfigurationCallback']($mpdf);
}
$styles = '';
if ($this->_config['cssFile']) {
$styles = file_get_contents($this->_config['cssFile']);
}
if ($this->_config['cssStyles']) {
$styles .= $this->_config['cssStyles'];
}
if (!empty($styles)) {
$mpdf->WriteHTML($styles, 1);
}
if ($this->_config['pdfSourceFile']) {
$mpdf->SetImportUse();
$pagecount = $mpdf->SetSourceFile($this->_config['pdfSourceFile']);
if ($pagecount > 1) {
for ($i = 0; $i <= $pagecount; ++$i) {
// Import next page from the pdfSourceFile
$pageNumber = $i + 1;
if ($pageNumber <= $pagecount) {
$importPage = $mpdf->ImportPage($pageNumber);
$mpdf->UseTemplate($importPage);
if (is_array($viewFile) && isset($viewFile[$i])) {
$mpdf->WriteHTML($this->_getView()->element($viewFile[$i], $viewVars));
}
}
if ($pageNumber < $pagecount) {
$mpdf->AddPage();
}
}
} else {
$tplId = $mpdf->ImportPage($pagecount);
$mpdf->SetPageTemplate($tplId);
}
}
return $mpdf;
} | php | {
"resource": ""
} |
q10375 | PdfGenerator.render | train | public function render($viewFile, array $options = [])
{
$options = Hash::merge([
'target' => self::TARGET_RETURN,
'filename' => 'pdf.pdf',
], $options);
$mpdf = $this->_preparePdf($viewFile, $options['viewVars']);
$options['viewVars']['mpdf'] = $mpdf;
if (!is_array($viewFile)) {
$wholeString = $this->_getView()->element($viewFile, $options['viewVars']);
// use 10% less than pcre.backtrack_limit to account for multibyte characters
$splitLength = ini_get('pcre.backtrack_limit') - (ini_get('pcre.backtrack_limit') / 10);
$splitString = str_split($wholeString, $splitLength);
foreach ($splitString as $string) {
$mpdf->WriteHTML($string);
}
}
switch ($options['target']) {
case self::TARGET_RETURN:
return $mpdf;
break;
case self::TARGET_DOWNLOAD:
$mpdf->Output($options['filename'], 'D');
break;
case self::TARGET_BROWSER:
$mpdf->Output($options['filename'], 'I');
break;
case self::TARGET_FILE:
$mpdf->Output($options['filename'], 'F');
break;
case self::TARGET_BINARY:
return $mpdf->Output('', 'S');
break;
default:
throw new \InvalidArgumentException("{$options['target']} is not a valid target");
break;
}
} | php | {
"resource": ""
} |
q10376 | LazyPermissionsTrait.hasAccess | train | public function hasAccess($permissions)
{
if ($this->permissions->isEmpty())
{
$this->mergePermissions($this->userPermissions, $this->rolePermissions);
}
if (func_num_args() > 1)
{
$permissions = func_get_args();
}
foreach ((array) $permissions as $permissionName)
{
if (! $this->allows($permissionName))
{
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q10377 | LazyPermissionsTrait.add | train | protected function add(Permission $permission, $override = true)
{
if ($override || ! $this->permissions->containsKey($permission->getName()))
{
$this->permissions->set($permission->getName(), $permission);
}
} | php | {
"resource": ""
} |
q10378 | LazyPermissionsTrait.allows | train | protected function allows($permissionName)
{
foreach ($this->getMatchingPermissions($permissionName) as $key)
{
/** @var Permission $permission */
$permission = $this->permissions->get($key);
if ($permission->isAllowed())
{
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q10379 | Scalar.setSize | train | public function setSize($size)
{
if (is_string($size) && $parsed = $this->parseSizeWord($size)) {
$this->size = $parsed;
} else {
$this->size = $size;
}
return $this;
} | php | {
"resource": ""
} |
q10380 | Scalar.parse | train | public function parse(AbstractStream $stream)
{
$value = $this->format($this->read($stream));
$this->validate($value);
return $value;
} | php | {
"resource": ""
} |
q10381 | Scalar.format | train | private function format($value)
{
if (is_callable($this->formatter)) {
$value = call_user_func($this->formatter, $value, $this->dataSet);
}
return $value;
} | php | {
"resource": ""
} |
q10382 | Scalar.parseSizeWord | train | private function parseSizeWord($word)
{
$sizeWord = strtoupper(preg_replace('/([a-z])([A-Z])/', '$1_$2', $word));
if (array_key_exists($sizeWord, $this->sizes)) {
$size = $this->sizes[$sizeWord];
} else {
$size = 0;
}
return $size;
} | php | {
"resource": ""
} |
q10383 | Request.send | train | protected function send($url, array $headers = [], $body = []): ResponseContract
{
$endpoint = $url instanceof EndpointContract ? $url : static::to($url);
return $this->responseWith(
$this->client->send('POST', $endpoint, $headers, $body)
);
} | php | {
"resource": ""
} |
q10384 | OrderedHealthAggregator.statusComparator | train | private function statusComparator($s1, $s2)
{
if (array_search($s1->getCode(), $this->statusOrder) === array_search($s2->getCode(), $this->statusOrder)) {
return 0;
}
return (array_search($s1->getCode(), $this->statusOrder)
< array_search($s2->getCode(), $this->statusOrder)) ? -1 : 1;
} | php | {
"resource": ""
} |
q10385 | DefaultDoctrineReminderRepository.create | train | public function create(UserInterface $user)
{
$entity = static::ENTITY_CLASSNAME;
$reminder = new $entity($user);
$this->save($reminder);
return $reminder;
} | php | {
"resource": ""
} |
q10386 | SerializableValueStub.makeSerializable | train | private function makeSerializable($value)
{
if (null === $value) {
return $value;
}
if ($value instanceof Traversable || is_array($value)) {
$value = ArrayUtils::iteratorToArray($value);
foreach ($value as $key => $val) {
$value[$key] = $this->makeSerializable($val);
}
return $value;
}
if (is_scalar($value)) {
return $value;
}
if (is_resource($value)) {
return 'resource';
}
return new ObjectStub($value);
} | php | {
"resource": ""
} |
q10387 | SerializableValueStub.makeReal | train | private function makeReal($value)
{
if (is_array($value)) {
foreach ($value as $key => $val) {
$value[$key] = $this->makeReal($val);
}
}
if ($value instanceof ObjectStub) {
return $value->getObject();
}
return $value;
} | php | {
"resource": ""
} |
q10388 | ViewBuilder.getView | train | public function getView(string $uri, Engine $engine, $type = null): View
{
if (null === $type) {
$view = $this->getViewFinder()->find([$uri], $engine);
return $view->setBuilder( $this );
}
return $this->resolveType($type, $uri, $engine);
} | php | {
"resource": ""
} |
q10389 | ViewBuilder.addLocation | train | public function addLocation(Location $location)
{
$this->locations->add($location);
unset( $this->viewPathCache );
$this->viewPathCache = [];
return $this;
} | php | {
"resource": ""
} |
q10390 | ViewBuilder.scanLocations | train | public function scanLocations(array $criteria)
{
$uris = $this->locations->map(function ($location) use ($criteria) {
/** @var Location $location */
return $location->getURI($criteria);
})->filter(function ($uri) {
return false !== $uri;
});
// Fall back for absolute paths on current filesystem.
if ($uris->isEmpty()) {
foreach ($criteria as $criterion) {
if (file_exists($criterion)) {
return $criterion;
}
}
}
return $uris->isEmpty() ? false : $uris->first();
} | php | {
"resource": ""
} |
q10391 | ViewBuilder.getFinder | train | protected function getFinder($key)
{
$finderClass = $this->config->getKey($key, 'ClassName');
return new $finderClass($this->config->getSubConfig($key));
} | php | {
"resource": ""
} |
q10392 | ViewBuilder.resolveType | train | protected function resolveType($type, string $uri, Engine $engine = null): View
{
$configKey = [static::VIEW_FINDER_KEY, 'Views', $type];
if (is_string($type) && $this->config->hasKey($configKey)) {
$className = $this->config->getKey($configKey);
$type = new $className($uri, $engine, $this);
}
if (is_string($type)) {
$type = new $type($uri, $engine, $this);
}
if (is_callable($type)) {
$type = $type($uri, $engine, $this);
}
if (! $type instanceof View) {
throw new FailedToInstantiateView(
sprintf(
_('Could not instantiate view "%s".'),
serialize($type)
)
);
}
return $type;
} | php | {
"resource": ""
} |
q10393 | ViewBuilder.getConfig | train | protected function getConfig($config = []): ConfigInterface
{
$defaults = ConfigFactory::create(dirname(__DIR__, 2) . '/config/defaults.php', $config);
$config = $config
? ConfigFactory::createFromArray(array_merge_recursive($defaults->getArrayCopy(), $config->getArrayCopy()))
: $defaults;
return $config->getSubConfig('BrightNucleus\View');
} | php | {
"resource": ""
} |
q10394 | Asset.attachToModel | train | public function attachToModel(Model $model, $type = '', $locale = null): Model
{
if ($model->assets()->get()->contains($this)) {
throw AssetUploadException::create();
}
$model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
$locale = $locale ?? config('app.locale');
$model->assets()->attach($this, ['type' => $type, 'locale' => $locale, 'order' => $this->order]);
return $model->load('assets');
} | php | {
"resource": ""
} |
q10395 | Asset.getImageUrl | train | public function getImageUrl($type = ''): string
{
if ($this->getMedia()->isEmpty()) {
return asset('assets/back/img/other.png');
}
$extension = $this->getExtensionType();
if ($extension === 'image') {
return $this->getFileUrl($type);
} elseif ($extension) {
return asset('assets/back/img/'.$extension.'.png');
}
return asset('assets/back/img/other.png');
} | php | {
"resource": ""
} |
q10396 | Asset.removeByIds | train | public static function removeByIds($imageIds)
{
if (is_array($imageIds)) {
foreach ($imageIds as $id) {
if (! $id) {
continue;
}
self::remove($id);
}
} else {
if (! $imageIds) {
return;
}
self::remove($imageIds);
}
} | php | {
"resource": ""
} |
q10397 | Asset.remove | train | public static function remove($id)
{
$asset = self::find($id)->first();
$media = $asset->media;
foreach ($media as $file) {
if (! is_file(public_path($file->getUrl())) || ! is_writable(public_path($file->getUrl()))) {
return;
}
}
$asset->delete();
} | php | {
"resource": ""
} |
q10398 | Asset.registerMediaConversions | train | public function registerMediaConversions(Media $media = null)
{
$conversions = config('assetlibrary.conversions');
foreach ($conversions as $key => $value) {
$conversionName = $key;
$this->addMediaConversion($conversionName)
->width($value['width'])
->height($value['height'])
->keepOriginalImageFormat()
->optimize();
}
if (config('assetlibrary.allowCropping')) {
$this->addMediaConversion('cropped')
->keepOriginalImageFormat()
->optimize();
}
} | php | {
"resource": ""
} |
q10399 | AccessorTrait.checkArguments | train | protected function checkArguments(array $args, $min, $max, $methodName)
{
$argc = count($args);
if ($argc < $min || $argc > $max) {
throw new \BadMethodCallException("Method $methodName is not exist");
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.