_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q10100 | Picture.resize | train | public function resize($width, $height = NULL, $resizeMode = NULL)
{
if(!$height)
{
$height = $width;
}
$this->effect[] = new Resize($width, $height, $resizeMode);
} | php | {
"resource": ""
} |
q10101 | Picture.setProgressive | train | public function setProgressive($progressive = TRUE)
{
if(is_bool($progressive))
{
$this->progressive = $progressive;
}
else
{
trigger_error('Picture progressive mode must be boolean', E_USER_WARNING);
}
} | php | {
"resource": ""
} |
q10102 | Picture.save | train | public function save($file = NULL)
{
if(is_null($file) && $this->storage)
{
$this->storage->save($this);
}
elseif(!is_null($file))
{
$this->savePicture($file);
}
else
{
trigger_error('Image file to save is not defined', E_USER_WARNING);
}
} | php | {
"resource": ""
} |
q10103 | Picture.output | train | public function output()
{
$imageFile = $this->storage->getPath($this);
if(file_exists($imageFile))
{
header('Content-Type: image');
header('Content-Length: ' . filesize($imageFile));
readfile($imageFile);
exit;
}
} | php | {
"resource": ""
} |
q10104 | Picture.getUrl | train | public function getUrl()
{
if($this->storage)
{
$this->save();
return $this->storage->getUrl($this);
}
return NULL;
} | php | {
"resource": ""
} |
q10105 | Picture.getDimensions | train | public function getDimensions()
{
$imageDimension = getimagesize($this->image);
$width = $imageDimension[0];
$height = $imageDimension[1];
foreach($this->effect as $effect)
{
if($effect instanceof PictureEffect)
{
$modified = $effect->getNewDimensions($width, $height);
$width = $modified['w'];
$height = $modified['h'];
}
}
return array(
'w' => $width,
'h' => $height,
);
} | php | {
"resource": ""
} |
q10106 | Transformation.perspective | train | public function perspective($dx1, $dy1, $dx2, $dy2, $dx3, $dy3, $dx4, $dy4, $sx1 = null, $sy1 = null, $sx2 = null, $sy2 = null, $sx3 = null, $sy3 = null, $sx4 = null, $sy4 = null)
{
if (!is_null($sx1) || !is_null($sy1) || !is_null($sx2) || !is_null($sy2) || !is_null($sx3) || !is_null($sy3) || !is_null($sx4) || !is_null($sy4)) {
$params = [$sx1, $sy1, $dx1, $dy1, $sx2, $sy2, $dx2, $dy2, $sx3, $sy3, $dx3, $dy3, $sx4, $sy4, $dx4, $dy4];
} else {
$params = [$dx1, $dy1, $dx2, $dy2, $dx3, $dy3, $dx4, $dy4];
}
return $this->addItem('e', 'perspective', implode(',', $params));
} | php | {
"resource": ""
} |
q10107 | Transformation.border | train | public function border($top, $right = null, $bottom = null, $left = null)
{
return $this->addItem('border', implode(',', func_get_args()));
} | php | {
"resource": ""
} |
q10108 | Transformation.round | train | public function round($topLeft, $topRight = null, $bottomRight = null, $bottomLeft = null)
{
return $this->addItem('ro', implode(',', func_get_args()));
} | php | {
"resource": ""
} |
q10109 | Transformation.jpegoptim | train | public function jpegoptim($quality = null)
{
return $quality === null ? $this->addItem('q', 'jpegoptim') : $this->addItem('q', 'jpegoptim', $quality);
} | php | {
"resource": ""
} |
q10110 | Transformation.addItem | train | private function addItem()
{
$args = func_get_args();
if (in_array($args[0], self::$appendableTransformations)) {
$i = $this->findLastTransformation($args[0]);
if ($i !== false) {
$this->items[$i]['rendered'] .= ','.implode(':', array_slice($args, 1));
return $this;
}
}
if ($args[0] != '/' && $this->itemCount && in_array($this->items[$this->itemCount - 1]['type'], self::$forcedLastTransformations)) {
$lastTransformation = array_pop($this->items);
}
$this->items[] = [
'type' => $args[0],
'rendered' => implode(':', $args),
];
++$this->itemCount;
if (isset($lastTransformation)) {
$this->items[] = $lastTransformation;
}
return $this;
} | php | {
"resource": ""
} |
q10111 | Transformation.render | train | private function render()
{
$transformation = implode('_', array_column($this->items, 'rendered'));
$transformation = preg_replace('#(_?/_?)+#isu', '/', $transformation);
$transformation = trim($transformation, '/_');
return $transformation;
} | php | {
"resource": ""
} |
q10112 | Socket.stopHeartbeat | train | private function stopHeartbeat()
{
if ($this->hTimer !== null)
{
$this->hTimer->cancel();
$this->hTimer = null;
}
} | php | {
"resource": ""
} |
q10113 | Socket.clearConnectionPool | train | private function clearConnectionPool()
{
$deleted = $this->connectionPool->removeInvalid();
foreach ($deleted as $deletedid)
{
$this->emit('disconnect', [ $deletedid ]);
}
} | php | {
"resource": ""
} |
q10114 | Socket.startTimeRegister | train | private function startTimeRegister()
{
if ($this->rTimer === null && $this->flags['enableHeartbeat'] === true && $this->flags['enableTimeRegister'] === true)
{
$proxy = $this;
$this->rTimer = $this->loop->addPeriodicTimer(($this->options['timeRegisterInterval']/1000), function() use($proxy) {
$now = round(microtime(true)*1000);
$proxy->connectionPool->setNow(function() use($now) {
return $now;
});
});
}
} | php | {
"resource": ""
} |
q10115 | Socket.stopTimeRegister | train | private function stopTimeRegister()
{
if ($this->rTimer !== null)
{
$this->rTimer->cancel();
$this->rTimer = null;
$this->connectionPool->resetNow();
}
} | php | {
"resource": ""
} |
q10116 | Enum.read | train | public function read(AbstractStream $stream)
{
$key = parent::read($stream);
$values = $this->getValues();
if (array_key_exists($key, $values)) {
$value = $values[$key];
} else {
$value = $this->getDefault();
}
if ($value === null) {
throw new InvalidKeyException(
"Value '{$key}' does not correspond to a valid enum key. Presented keys: '" .
implode("', '", array_keys($values)) . "'"
);
}
return $value;
} | php | {
"resource": ""
} |
q10117 | Shareable.all | train | public function all()
{
$defaultButtons = Config::get('shareable::default_buttons', array());
$buttons = array();
$output = '';
foreach ($defaultButtons as $button) {
$buttons[] = call_user_func(array($this, $button));
}
return $this->view->make('shareable::all', array('buttons' => $buttons));
} | php | {
"resource": ""
} |
q10118 | StrictPasswordBehavior.buildValidator | train | public function buildValidator(Event $event, Validator $validator, string $name): void
{
$this->validationStrictPassword($validator);
} | php | {
"resource": ""
} |
q10119 | StrictPasswordBehavior.validationStrictPassword | train | public function validationStrictPassword(Validator $validator): Validator
{
$validator
->add('password', [
'minLength' => [
'rule' => ['minLength', $this->getConfig('minPasswordLength')],
'last' => true,
'message' => __d('ck_tools', 'validation.user.password_min_length'),
],
])
->add('password', 'passwordFormat', [
'rule' => function ($value, $context) {
return $this->validFormat($value, $context);
},
'message' => __d('ck_tools', 'validation.user.password_invalid_format'),
])
->add('password', 'passwordNoUserName', [
'rule' => function ($value, $context) {
return $this->checkForUserName($value, $context);
},
'message' => __d('ck_tools', 'validation.user.password_user_name_not_allowed'),
])
->add('password', 'passwordUsedBefore', [
'rule' => function ($value, $context) {
return $this->checkLastPasswords($value, $context);
},
'message' => __d('ck_tools', 'validation.user.password_used_before'),
]);
return $validator;
} | php | {
"resource": ""
} |
q10120 | StrictPasswordBehavior.checkForUserName | train | public function checkForUserName(string $value, array $context): bool
{
// return true if config is not set
if (empty($this->getConfig('noUserName'))) {
return true;
}
// Get Config
$firstNameField = $this->getConfig('userNameFields.firstname');
$lastNameField = $this->getConfig('userNameFields.lastname');
// No Usernames in Context
if (empty($context['data'][$firstNameField]) || empty($context['data'][$lastNameField])) {
if (!empty($context['data']['id'])) {
$user = $this->_table->get($context['data']['id']);
$firstname = $user->$firstNameField;
$lastname = $user->$lastNameField;
} else {
// no name to check
return true;
}
} else {
$firstname = $context['data'][$firstNameField];
$lastname = $context['data'][$lastNameField];
}
// validate password
if (!empty($firstname) && strpos(strtolower($value), strtolower($firstname)) !== false) {
return false;
}
if (!empty($lastname) && strpos(strtolower($value), strtolower($lastname)) !== false) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q10121 | StrictPasswordBehavior.checkLastPasswords | train | public function checkLastPasswords(string $value, array $context): bool
{
// return true if config is not set
if (empty($this->getConfig('oldPasswordCount'))) {
return true;
}
// ignore on new user
if (empty($context['data']['id'])) {
return true;
}
$user = $this->_table->get($context['data']['id']);
if (is_array($user->last_passwords)) {
foreach ($user->last_passwords as $oldPasswordHash) {
if ((new DefaultPasswordHasher)->check($value, $oldPasswordHash)) {
return false;
}
}
}
return true;
} | php | {
"resource": ""
} |
q10122 | StrictPasswordBehavior.beforeSave | train | public function beforeSave(Event $event, EntityInterface $entity): bool
{
if (empty($this->getConfig('oldPasswordCount')) || !is_numeric($this->getConfig('oldPasswordCount'))) {
return true;
}
if (!is_array($entity->last_passwords)) {
$entity->last_passwords = [];
}
$lastPasswords = $entity->last_passwords;
if (count($lastPasswords) == $this->getConfig('oldPasswordCount')) {
array_shift($lastPasswords);
}
$lastPasswords[] = $entity->password;
$entity->setAccess('last_passwords', true);
$this->_table->patchEntity($entity, [
'last_passwords' => $lastPasswords,
]);
return true;
} | php | {
"resource": ""
} |
q10123 | RemoteProcessFactory.spawnProcess | train | protected static function spawnProcess(string $cmd, array $spec, ?array & $pipes, ?string $dir = null, ?array $env = null, bool $bypassShell = false)
{
return @\proc_open($cmd, $spec, $pipes, $dir, $env, $bypassShell ? [
'bypass_shell' => true
] : []);
} | php | {
"resource": ""
} |
q10124 | UserController.store | train | public function store(StoreUserRequest $request, Repository $config)
{
$this->dispatch(new RegisterUser($request->get('name'), $request->get('email'), $request->get('password')));
return redirect($config->get('authentication.registration.redirectUri'));
} | php | {
"resource": ""
} |
q10125 | DatatablesEnabledControllerTrait.listAction | train | public function listAction(Request $request)
{
$manager = $this->getEntityManager();
$total_count = $manager->getTotalCount($request);
$filtered_count = $manager->getFilteredCount($request);
$entities = $manager->getEntities($request);
return array_merge(
$this->getExtraTemplateParameters($request),
array(
'total_count' => $total_count,
'filtered_count' => $filtered_count,
'entities' => $entities,
)
);
} | php | {
"resource": ""
} |
q10126 | DatatablesEnabledControllerTrait.getFilter | train | protected function getFilter(Request $request)
{
if ($filter_type = $this->getEntityManager()->getFilterType($request)) {
return $this->createForm($filter_type);
}
} | php | {
"resource": ""
} |
q10127 | TypeAwareTrait.getTypeDescription | train | public static function getTypeDescription(?string $type): ?string
{
$descriptions = self::typeDescriptions();
if (isset($descriptions[$type])) {
return $descriptions[$type];
}
return $type;
} | php | {
"resource": ""
} |
q10128 | IterableResultHydrator.hydrate | train | public function hydrate($objectClass, array $data, $indexOfBy = false)
{
$this->objectClass = $objectClass;
if (0 == count($data)) {
yield $this->createObjectToHydrate($this->objectClass);
} elseif (! is_array(current($data))) {
yield $this->hydrateItem($this->objectClass, $data);
} elseif (false === $indexOfBy) {
foreach ($data as $item) {
yield $this->hydrateItem($this->objectClass, $item);
}
} else {
foreach ($this->hydrateBy($data, $indexOfBy) as $valueOfBy => $item) {
yield $valueOfBy => $item;
}
}
} | php | {
"resource": ""
} |
q10129 | Busy.done | train | public function done()
{
if ($this->watcher) {
if ($this->watcher->count > 0) {
$this->watcher->count--;
}
$this->watcher = null;
}
} | php | {
"resource": ""
} |
q10130 | DoctrineSectionManager.restoreFromHistory | train | public function restoreFromHistory(SectionInterface $sectionFromHistory): SectionInterface
{
/** @var SectionInterface $activeSection */
$activeSection = $this->readByHandle($sectionFromHistory->getHandle()); // 1
/** @var SectionInterface $newSectionHistory */
$newSectionHistory = $this->copySectionDataToSectionHistoryEntity($activeSection); // 2
$newSectionHistory->setVersioned(new \DateTime()); // 3
$version = $this->getHighestVersion($newSectionHistory->getHandle());
$newSectionHistory->setVersion(1 + $version->toInt());
$this->sectionHistoryManager->create($newSectionHistory); // 3
$updatedActiveSection = $this->copySectionHistoryDataToSectionEntity($sectionFromHistory, $activeSection); // 4
$updatedActiveSection->removeFields(); // 5
$this->entityManager->persist($updatedActiveSection);
$this->entityManager->flush();
$fields = $this->fieldManager->readByHandles($updatedActiveSection->getConfig()->getFields()); // 6
foreach ($fields as $field) {
$updatedActiveSection->addField($field);
} // 7
$this->entityManager->persist($updatedActiveSection);
$this->entityManager->flush();
return $updatedActiveSection;
} | php | {
"resource": ""
} |
q10131 | DoctrineSectionManager.updateByConfig | train | public function updateByConfig(
SectionConfig $sectionConfig,
SectionInterface $section,
bool $history = false
): SectionInterface {
if ($history) {
/** @var SectionInterface $sectionHistory */
$sectionHistory = $this->copySectionDataToSectionHistoryEntity($section); // 1
$sectionHistory->setVersioned(new \DateTime()); // 2
$this->sectionHistoryManager->create($sectionHistory); // 2
$version = $this->getHighestVersion($section->getHandle());
$section->setVersion(1 + $version->toInt()); // 3
}
$section->removeFields(); // 4
$fields = $this->fieldManager->readByHandles($sectionConfig->getFields()); // 5
foreach ($fields as $field) {
$section->addField($field);
} // 6
$section->setName((string) $sectionConfig->getName()); // 7
$section->setHandle((string) $sectionConfig->getHandle()); // 7
$section->setConfig($sectionConfig->toArray()); // 8
$this->entityManager->persist($section); // 9
$this->entityManager->flush(); // 9
return $section;
} | php | {
"resource": ""
} |
q10132 | Coanda.loadModules | train | public function loadModules()
{
$core_modules = [
'CoandaCMS\Coanda\Pages\PagesModuleProvider',
'CoandaCMS\Coanda\Media\MediaModuleProvider',
'CoandaCMS\Coanda\Users\UsersModuleProvider',
'CoandaCMS\Coanda\Layout\LayoutModuleProvider',
'CoandaCMS\Coanda\Urls\UrlModuleProvider',
'CoandaCMS\Coanda\History\HistoryModuleProvider'
];
$enabled_modules = $this->config->get('coanda::coanda.enabled_modules');
$modules = array_merge($core_modules, $enabled_modules);
foreach ($modules as $module)
{
if (class_exists($module))
{
$enabled_module = new $module($this);
$enabled_module->boot($this);
$this->modules[$enabled_module->name] = $enabled_module;
}
}
} | php | {
"resource": ""
} |
q10133 | Coanda.filters | train | public function filters()
{
Route::filter('admin_auth', function()
{
if (!App::make('coanda')->isLoggedIn())
{
Session::put('pre_auth_path', Request::path());
Session::put('pre_auth_query_string', Request::getQueryString());
return Redirect::to('/' . Config::get('coanda::coanda.admin_path') . '/login');
}
});
} | php | {
"resource": ""
} |
q10134 | Coanda.routes | train | public function routes()
{
Route::group(array('prefix' => $this->config->get('coanda::coanda.admin_path')), function()
{
// All module admin routes should be wrapper in the auth filter
Route::group(array('before' => 'admin_auth'), function()
{
foreach ($this->modules as $module)
{
$module->adminRoutes();
}
});
// We will put the main admin controller outside the group so it can handle its own filters
Route::controller('/', 'CoandaCMS\Coanda\Controllers\AdminController');
});
// Let the module output any front end 'user' routes
foreach ($this->modules as $module)
{
$module->userRoutes();
}
App::before( function () {
Route::match(['GET', 'POST'], 'search', function () {
// Pass this route to the search provider, it can do whatever it likes!
return Coanda::search()->handleSearch();
});
Route::match(['GET', 'POST'], '{slug}', function ($slug)
{
return Coanda::route($slug);
})->where('slug', '[\.\/_\-\_A-Za-z0-9]+');
Route::match(['GET', 'POST'], '/', function ()
{
return Coanda::routeHome();
});
});
} | php | {
"resource": ""
} |
q10135 | Coanda.bindings | train | public function bindings($app)
{
$app->bind('CoandaCMS\Coanda\Urls\Repositories\UrlRepositoryInterface', 'CoandaCMS\Coanda\Urls\Repositories\Eloquent\EloquentUrlRepository');
$search_provider = $this->config->get('coanda::coanda.search_provider');
if (class_exists($search_provider))
{
$app->bind('CoandaCMS\Coanda\Search\CoandaSearchProvider', $search_provider);
}
else
{
$app->bind('CoandaCMS\Coanda\Search\CoandaSearchProvider', 'CoandaCMS\Coanda\Search\Basic\CoandaBasicSearchProvider');
}
// Let the module output any bindings
foreach ($this->modules as $module)
{
$module->bindings($app);
}
} | php | {
"resource": ""
} |
q10136 | Lexer.updateOptions | train | public function updateOptions()
{
if ($onLex = $this->getOption('on_lex')) {
$this->attach(LexerEvent::LEX, $onLex);
}
if ($onLex = $this->getOption('on_lex_end')) {
$this->attach(LexerEvent::END_LEX, $onLex);
}
if ($onToken = $this->getOption('on_token')) {
$this->attach(LexerEvent::TOKEN, $onToken);
}
$this->addModules($this->getOption('lexer_modules'));
} | php | {
"resource": ""
} |
q10137 | Lexer.prependScanner | train | public function prependScanner($name, $scanner)
{
$this->filterScanner($scanner);
$scanners = [
$name => $scanner,
];
foreach ($this->getScanners() as $scannerName => $classNameOrInstance) {
if ($scannerName !== $name) {
$scanners[$scannerName] = $classNameOrInstance;
}
}
return $this->setOption('scanners', $scanners);
} | php | {
"resource": ""
} |
q10138 | Lexer.addScanner | train | public function addScanner($name, $scanner)
{
$this->filterScanner($scanner);
return $this->setOption(['scanners', $name], $scanner);
} | php | {
"resource": ""
} |
q10139 | Lexer.lex | train | public function lex($input, $path = null)
{
$stateClassName = $this->getOption('lexer_state_class_name');
$lexEvent = new LexEvent($input, $path, $stateClassName, [
'encoding' => $this->getOption('encoding'),
'indent_style' => $this->getOption('indent_style'),
'indent_width' => $this->getOption('indent_width'),
'allow_mixed_indent' => $this->getOption('allow_mixed_indent'),
'multiline_markup_enabled' => $this->getOption('multiline_markup_enabled'),
'level' => $this->getOption('level'),
]);
$this->trigger($lexEvent);
$input = $lexEvent->getInput();
$path = $lexEvent->getPath();
$stateClassName = $lexEvent->getStateClassName();
$stateOptions = $lexEvent->getStateOptions();
$stateOptions['path'] = $path;
$stateOptions['keyword_names'] = array_keys($this->getOption('keywords') ?: []);
if (!is_a($stateClassName, State::class, true)) {
throw new \InvalidArgumentException(
'lexer_state_class_name needs to be a valid '.State::class.' sub class, '.
$stateClassName.' given'
);
}
//Put together our initial state
$this->state = new $stateClassName($this, $input, $stateOptions);
$scanners = $this->getOption('scanners');
//We always scan for text at the very end.
$scanners['final_plain_text'] = TextScanner::class;
//Scan for tokens
//N> yield from $this->handleTokens($this->>state->loopScan($scanners));
$tokens = $this->state->loopScan($scanners);
foreach ($this->handleTokens($tokens) as $token) {
yield $token;
}
$this->trigger(new EndLexEvent($lexEvent));
//Free state
$this->state = null;
$this->lastToken = null;
} | php | {
"resource": ""
} |
q10140 | Message.addQuestion | train | public function addQuestion(string $host, int $type, int $class = self::CLASS_IN): void
{
$this->questions[] = [
'host' => $host,
'type' => $type,
'class' => $class
];
} | php | {
"resource": ""
} |
q10141 | Message.addAnswer | train | public function addAnswer(string $host, int $type, int $class, string $data, int $ttl): void
{
$this->answers[] = [
'host' => $host,
'type' => $type,
'class' => $class,
'data' => $data,
'ttl' => $ttl
];
} | php | {
"resource": ""
} |
q10142 | Message.encodeHeader | train | protected function encodeHeader(): string
{
return \pack('n*', ...[
$this->id,
$this->getFlags(),
\count($this->questions),
\count($this->answers),
$this->authorityCount,
$this->additionalCount
]);
} | php | {
"resource": ""
} |
q10143 | Message.encodeLabel | train | protected function encodeLabel(string $label): string
{
$encoded = '';
foreach (\explode('.', $label) as $part) {
$encoded .= \chr(\strlen($part)) . $part;
}
return $encoded . "\x00";
} | php | {
"resource": ""
} |
q10144 | Message.encodeQuestion | train | protected function encodeQuestion(array $question): string
{
$encoded = $this->encodeLabel($question['host']);
$encoded .= \pack('nn', $question['type'], $question['class']);
return $encoded;
} | php | {
"resource": ""
} |
q10145 | Message.encodeAnswer | train | protected function encodeAnswer(array $answer): string
{
$encoded = $this->encodeLabel($answer['host']);
switch ($answer['type']) {
case self::TYPE_A:
case self::TYPE_AAAA:
$data = \inet_pton($answer['data']);
break;
case self::TYPE_CNAME:
$data = $this->encodeLabel($answer['data']);
break;
default:
$data = $answer['data'];
}
$encoded .= \pack('nnNn', $answer['type'], self::CLASS_IN, $answer['ttl'], \strlen($data));
$encoded .= $data;
return $encoded;
} | php | {
"resource": ""
} |
q10146 | ShoppingCart.emptycart | train | public function emptycart()
{
ShoppingCartFactory::create()->delete();
$form = $this->CartForm();
$form->sessionMessage(_t(
"ShoppingCart.EmptiedCart",
"Shopping cart emptied"
));
return $this->redirectBack();
} | php | {
"resource": ""
} |
q10147 | ShoppingCart.checkout | train | public function checkout()
{
if (!class_exists($this->config()->checkout_class)) {
return $this->httpError(404);
}
$checkout = Injector::inst()
->get($this->config()->checkout_class);
$checkout->setEstimate($this->dataRecord);
$this->extend("onBeforeCheckout");
$this->redirect($checkout->Link());
} | php | {
"resource": ""
} |
q10148 | DateService.getFormat | train | public function getFormat(string $dateLength): string
{
// Oops, unknown length of date
if (false === (new DateLength())->isCorrectType($dateLength)) {
throw UnknownDateLengthException::createException($dateLength);
}
$format = '';
switch ($dateLength) {
case DateLength::DATE:
$format = $this->dateFormat;
break;
case DateLength::DATETIME:
$format = $this->dateTimeFormat;
break;
case DateLength::TIME:
$format = $this->timeFormat;
break;
}
return $format;
} | php | {
"resource": ""
} |
q10149 | DateService.formatDate | train | public function formatDate(\DateTimeInterface $dateTime, string $dateLength): string
{
$format = $this->getFormat($dateLength);
return $dateTime->format($format);
} | php | {
"resource": ""
} |
q10150 | Success.success | train | public function success(int $statusCode, string $message, $data = null): JsonResponse
{
$this->setStatusCode($statusCode);
$this->setMessage($message);
$this->setData($data);
$content['message'] = $this->getMessage();
if (null !== $this->getCode()) {
$content['code'] = $this->getCode();
}
$content['status_code'] = $this->getStatusCode();
if (null !== $this->getData() && $this->getErrors() !== $this->getData()) {
$content['data'] = $this->getData();
}
if (null !== $this->getErrors()) {
$content['errors'] = $this->getErrors();
}
$content += $this->Hypermedia;
return new JsonResponse($content, $this->getHttpStatusCode() ?: $this->getStatusCode());
} | php | {
"resource": ""
} |
q10151 | HierarchyBuilder.explodeChildren | train | private function explodeChildren($id, array $childrenMap)
{
if (! isset($childrenMap[$id])) {
return [];
}
// Indexing items by their value
$indexed = [];
foreach ($childrenMap[$id] as $childName) {
$indexed[$childName] = $childName;
}
return array_map(
function ($childId) use ($childrenMap) {
return $this->explodeChildren($childId, $childrenMap);
},
$indexed
);
} | php | {
"resource": ""
} |
q10152 | Hydrator.doHydrate | train | protected function doHydrate(array $data, $object)
{
$previousHydrationContext = $this->currentHydrationContext;
$this->currentHydrationContext = new CurrentHydrationContext($data, $object);
foreach ($this->metadata->getMappedFieldNames() as $mappedFieldName) {
$defaultValue = $this->metadata->getFieldDefaultValue($mappedFieldName);
if (null !== $defaultValue) {
$this->resolveValue($defaultValue, $object);
$this->memberAccessStrategy->setValue($defaultValue, $object, $mappedFieldName);
}
}
if (! $this->metadata->hasCustomHydrator()) {
$this->executeMethods($object, $this->metadata->getPreHydrateListeners());
foreach ($data as $originalFieldName => $value) {
$mappedFieldName = $this->metadata->getMappedFieldName($originalFieldName);
if (null === $mappedFieldName) {
//It's possible that a raw field name has no corresponding field name
//because a raw field can be a value object part.
continue;
}
if (! $this->metadata->hasSource($mappedFieldName)) {
//Classical hydration.
$this->walkHydration($mappedFieldName, $object, $value, $data);
}
}
} else {
list($customHydratorClass, $customHydrateMethod) = $this->metadata->getCustomHydratorInfo();
$this->executeMethod($object, new ClassMetadata\Model\Method($customHydratorClass, $customHydrateMethod, [$data, $object]));
}
//DataSources hydration.
foreach ($this->metadata->getFieldsWithDataSources() as $mappedFieldName) {
if ($this->metadata->hasDataSource($mappedFieldName)) {//<= Is this test usefull ?
$this->walkHydrationByDataSource($mappedFieldName, $object, false);
}
}
//Providers hydration.
foreach ($this->metadata->getFieldsWithProviders() as $mappedFieldName) {
if ($this->metadata->hasProvider($mappedFieldName)) {//<= Is this test usefull ?
$this->walkHydrationByProvider($mappedFieldName, $object, false);
}
}
//Value objects hydration.
foreach ($this->metadata->getFieldsWithValueObjects() as $mappedFieldName) {
$this->walkValueObjectHydration($mappedFieldName, $object, $data);
}
$this->executeMethods($object, $this->metadata->getPostHydrateListeners());
$this->currentHydrationContext = $previousHydrationContext;
return $object;
} | php | {
"resource": ""
} |
q10153 | Hydrator.getCurrentConfigVariableByName | train | public function getCurrentConfigVariableByName($variableKey)
{
if (! isset($this->currentConfigVariables[$variableKey])) {
throw new ObjectMappingException(
sprintf(
'The current config variables do not contains key "%s". Availables keys are "[%s]".',
$variableKey,
implode(',', array_keys($this->currentConfigVariables))
)
);
}
return $this->currentConfigVariables[$variableKey];
} | php | {
"resource": ""
} |
q10154 | PineAnnotationsServiceProvider.registerReader | train | protected function registerReader()
{
// Give a Cached Reader when our
// reader class needs
// a ReaderContract.
$this->app->when(AnnotationsReader::class)
->needs(Reader::class)
->give(function () {
return $this->createAndReturnCachedReader();
});
} | php | {
"resource": ""
} |
q10155 | PineAnnotationsServiceProvider.addAnnotationsToRegistry | train | protected function addAnnotationsToRegistry()
{
// Creates annotation Reader.
$reader = $this->app->make(AnnotationsReader::class);
// Register files autoload.
$reader->addFilesToRegistry(config('pine-annotations.autoload_files'));
// Register namespaces autoload.
$reader->addNamespacesToRegistry(config('pine-annotations.autoload_namespaces'));
} | php | {
"resource": ""
} |
q10156 | Compare.isDimensionsEqual | train | public function isDimensionsEqual()
{
if($this->image1->getImageWidth() !== $this->image2->getImageWidth()
|| $this->image1->getImageHeight() !== $this->image2->getImageHeight())
{
return FALSE;
}
return TRUE;
} | php | {
"resource": ""
} |
q10157 | Compare.isEqual | train | public function isEqual()
{
// CHECK IMAGES DIMENSIONS
if(!$this->isDimensionsEqual())
{
return FALSE;
}
$compare = $this->image1->compareImages($this->image2, Imagick::METRIC_MEANSQUAREERROR);
// IMAGE IS EXACTLY THE SAME
if($compare === TRUE)
{
return TRUE;
}
// IMAGE IS IN TOLERABLE RANGE
elseif($compare)
{
if($compare[1] < $this->tolerance)
{
return TRUE;
}
}
return FALSE;
} | php | {
"resource": ""
} |
q10158 | Paymill.createModel | train | public function createModel($class, $id)
{
$this->model = new $class();
if ($id) {
$this->model->setId($id);
}
return $this;
} | php | {
"resource": ""
} |
q10159 | UserController.index | train | public function index(Request $request, UserRepository $users)
{
return view('authentication::user.index')
->with('users', $users->query($request->get('q')));
} | php | {
"resource": ""
} |
q10160 | InstallDirectoryCommand.getAllYamls | train | private static function getAllYamls(string $directory): \Generator
{
/** @var \SplFileInfo $file */
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory)) as $file) {
if ($file->isFile() && $file->getExtension() === 'yml') {
$fileName = $file->getPathname();
yield $fileName => Yaml::parse(file_get_contents($fileName));
}
}
} | php | {
"resource": ""
} |
q10161 | ExpressionContext.addVariable | train | public function addVariable($key, $value)
{
if (is_null($key) || ! is_string($key)) {
throw new RuntimeException(sprintf('The key where to save your variable in the expression context is invalid. Got "%s".', $key));
}
$this->variables[$key] = $value;
} | php | {
"resource": ""
} |
q10162 | Server.serverResponse | train | public function serverResponse()
{
if(!empty($_GET['imageQuery']))
{
$picture = $this->loadPicture($_GET['imageQuery']);
$savePath = $this->getPath($picture);
$picture->save($savePath);
if($savePath !== $this->getPath($picture))
{
throw new Exception('Picture effect is changing its own arguments on effect apply');
}
$picture->output();
}
if(!empty($_POST['regenerate']))
{
$picture = $this->loadPicture($_POST['regenerate']);
$picture->save($this->getPath($picture));
}
} | php | {
"resource": ""
} |
q10163 | Server.requestWithoutWaiting | train | function requestWithoutWaiting($url, array $params = array())
{
$post = array();
foreach($params as $index => $val)
{
$post[] = $index . '=' . urlencode($val);
}
$post = implode('&', $post);
$request = parse_url($url);
// SUPPORT FOR RELATIVE GENERATOR URL
if(!isset($request['host']))
{
$request['host'] = $_SERVER['HTTP_HOST'];
}
if(!isset($request['port']))
{
$request['port'] = $_SERVER['SERVER_PORT'];
}
// SEND REQUEST WITHOUT WAITING
$protocol = isset($_SERVER['HTTPS']) ? 'ssl://' : '';
$safePort = isset($_SERVER['HTTPS']) ? 443 : 80;
// HTTPS WORKAROUND
if($request['port'] == 80 && $safePort == 443)
{
$request['port'] = $safePort;
}
$fp = fsockopen($protocol . $request['host'], $request['port'], $errNo, $errStr, 60);
$command = "POST " . $request['path'] . " HTTP/1.1\r\n";
$command .= "Host: " . $request['host'] . "\r\n";
$command .= "Content-Type: application/x-www-form-urlencoded\r\n";
$command .= "Content-Length: " . strlen($post) . "\r\n";
$command .= "Connection: Close\r\n\r\n";
if($post)
{
$command .= $post;
}
fwrite($fp, $command);
fclose($fp);
} | php | {
"resource": ""
} |
q10164 | DataSet.setValue | train | public function setValue($name, $value)
{
$child = & $this->data;
foreach ($this->currentPath as $part) {
if (isset($child[$part])) {
$child = & $child[$part];
} else {
$child[$part] = [];
$child = & $child[$part];
}
}
$child[$name] = $value;
} | php | {
"resource": ""
} |
q10165 | DataSet.getValue | train | public function getValue($name)
{
$child = & $this->data;
foreach ($this->currentPath as $part) {
if (isset($child[$part])) {
$child = & $child[$part];
} else {
return null;
}
}
return isset($child[$name]) ? $child[$name] : null;
} | php | {
"resource": ""
} |
q10166 | DataSet.getValueByPath | train | public function getValueByPath($path)
{
if (is_string($path)) {
$path = $this->parsePath($path);
}
$child = $this->data;
foreach ($path as $part) {
if (isset($child[$part])) {
$child = $child[$part];
} else {
return null;
}
}
return $child;
} | php | {
"resource": ""
} |
q10167 | DataSet.setValueByPath | train | public function setValueByPath($path, $value)
{
if (is_string($path)) {
$path = $this->parsePath($path);
}
$endPart = array_pop($path);
$child = & $this->data;
foreach ($path as $part) {
if (isset($child[$part])) {
$child = & $child[$part];
} else {
$child[$part] = [];
$child = & $child[$part];
}
}
$child[$endPart] = $value;
} | php | {
"resource": ""
} |
q10168 | DataSet.parsePath | train | public function parsePath($path)
{
$parts = explode('/', trim($path, '/'));
$pathArray = [];
if ($parts[0] == '.') {
$pathArray = $this->currentPath;
array_shift($parts);
}
foreach ($parts as $part) {
if ($part == '..') {
if (count($pathArray)) {
array_pop($pathArray);
} else {
throw new Field\ConfigurationException("Invalid path. To many '..', can't move higher root.");
}
} else {
$pathArray[] = $part;
}
}
return $pathArray;
} | php | {
"resource": ""
} |
q10169 | DataSet.resolvePath | train | public function resolvePath($value)
{
do {
$value = $this->getValueByPath($value);
} while (self::isPath($value));
return $value;
} | php | {
"resource": ""
} |
q10170 | SourceFactory.create | train | public function create(WP_Post $attachment, Size $size): Source
{
if (!wp_attachment_is_image($attachment)) {
throw new InvalidArgumentException('Attachment must be an image.');
}
$imageSource = (array)wp_get_attachment_image_src(
$attachment->ID,
[$size->width(), $size->height()]
);
$imageSource = array_filter($imageSource);
if (!$imageSource) {
throw new DomainException(
sprintf('Image with ID: %d, no longer exists', $attachment->ID)
);
}
return new Source(...$imageSource);
} | php | {
"resource": ""
} |
q10171 | Guzzle5ApiClient._doRequest | train | protected function _doRequest($method, $uri, $options)
{
// For Guzzle5 we cannot have any options that are not pre-defined,
// so instead we put it in the config array
if (isset($options[self::OPT_VIDEO_MANAGER_ID])) {
$options['config'][self::OPT_VIDEO_MANAGER_ID] = $options[self::OPT_VIDEO_MANAGER_ID];
unset($options[self::OPT_VIDEO_MANAGER_ID]);
}
$request = $this->httpClient->createRequest($method, $uri, $options);
return $this->httpClient->send($request);
} | php | {
"resource": ""
} |
q10172 | AlgoliaComponent.createManager | train | private function createManager()
{
$config = $this->generateConfig();
$algoliaManager = $this->algoliaFactory->make($config);
$algoliaManager->setEnv($this->env);
return $algoliaManager;
} | php | {
"resource": ""
} |
q10173 | AlgoliaComponent.generateConfig | train | private function generateConfig()
{
return new AlgoliaConfig(
$this->applicationId,
$this->apiKey,
$this->hostsArray,
$this->options
);
} | php | {
"resource": ""
} |
q10174 | URIHelper.hasExtension | train | public static function hasExtension(string $uri, string $extension): bool
{
$extension = '.' . ltrim($extension, '.');
$uriLength = mb_strlen($uri);
$extensionLength = mb_strlen($extension);
if ($extensionLength > $uriLength) {
return false;
}
return substr_compare($uri, $extension, $uriLength - $extensionLength, $extensionLength) === 0;
} | php | {
"resource": ""
} |
q10175 | URIHelper.containsExtension | train | public static function containsExtension(string $uri): string
{
$pathParts = explode('/', $uri);
$filename = array_pop($pathParts);
$filenameParts = explode('.', $filename);
if (count($filenameParts) > 1) {
return array_pop($filenameParts);
}
return '';
} | php | {
"resource": ""
} |
q10176 | RoutePermissionRepository.extractPermissionFrom | train | private function extractPermissionFrom(Route $route)
{
$parameters = $route->getAction();
if (isset($parameters['permission']))
{
return $parameters['permission'];
}
return null;
} | php | {
"resource": ""
} |
q10177 | RouteAnnotationListener.getUrlFromRoute | train | protected function getUrlFromRoute($name, Route $route)
{
$option = $route->getOption('sitemap');
if ($option === null) {
return null;
}
if (is_string($option)) {
$decoded = json_decode($option, true);
if (!json_last_error() && is_array($decoded)) {
$option = $decoded;
}
}
if (!is_array($option) && !is_bool($option)) {
$bool = filter_var($option, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if (null === $bool) {
throw new \InvalidArgumentException("The sitemap option for route $name must be boolean or array");
}
$option = $bool;
}
if (!$option) {
return null;
}
$url = $this->router->generate($name);
$urlObject = new Url(
$url,
(isset($option['lastMod']) ? $option['lastMod'] : null),
(isset($option['priority']) ? $option['priority'] : null),
(isset($option['changeFreq']) ? $option['changeFreq'] : null)
);
return $urlObject;
} | php | {
"resource": ""
} |
q10178 | PHPEngine.getRenderCallback | train | public function getRenderCallback(string $uri, array $context = []): callable
{
if (! is_readable($uri)) {
throw new FailedToLoadView(
sprintf(
_('The View URI "%1$s" is not accessible or readable.'),
$uri
)
);
}
$closure = function () use ($uri, $context) {
// Save current buffering level so we can backtrack in case of an error.
// This is needed because the view itself might also add an unknown number of output buffering levels.
$bufferLevel = ob_get_level();
ob_start();
try {
include $uri;
} catch (Exception $exception) {
// Remove whatever levels were added up until now.
while (ob_get_level() > $bufferLevel) {
ob_end_clean();
}
throw new FailedToLoadView(
sprintf(
_('Could not load the View URI "%1$s". Reason: "%2$s".'),
$uri,
$exception->getMessage()
),
$exception->getCode(),
$exception
);
}
return ob_get_clean();
};
return $closure;
} | php | {
"resource": ""
} |
q10179 | Text_Password.createMultiple | train | public static function createMultiple(
$number,
$length = 10,
$type = 'pronounceable',
$chars = ''
) {
$passwords = array();
while ($number > 0) {
while (true) {
$password = self::create($length, $type, $chars);
if (!in_array($password, $passwords)) {
$passwords[] = $password;
break;
}
}
$number--;
}
return $passwords;
} | php | {
"resource": ""
} |
q10180 | Text_Password.createMultipleFromLogin | train | public static function createMultipleFromLogin($login, $type, $key = 0)
{
$passwords = array();
$number = count($login);
$save = $number;
while ($number > 0) {
while (true) {
$password = self::createFromLogin($login[$save - $number], $type, $key);
if (!in_array($password, $passwords)) {
$passwords[] = $password;
break;
}
}
$number--;
}
return $passwords;
} | php | {
"resource": ""
} |
q10181 | Text_Password._shuffle | train | protected static function _shuffle($login)
{
$tmp = array();
for ($i = 0; $i < strlen($login); $i++) {
$tmp[] = $login[$i];
}
shuffle($tmp);
return implode($tmp, '');
} | php | {
"resource": ""
} |
q10182 | Text_Password._rand | train | protected static function _rand($min, $max)
{
if (version_compare(PHP_VERSION, '7.0.0', 'ge')) {
$value = random_int($min, $max);
} else {
$value = mt_rand($min, $max);
}
return $value;
} | php | {
"resource": ""
} |
q10183 | Errors.badRequest | train | public function badRequest($message = 'Bad Request', $errors = null): void
{
$this->setStatusCode(400);
$this->setMessage($message);
$this->setErrors($errors);
throw new ApiException($this);
} | php | {
"resource": ""
} |
q10184 | TWBTreeView.finalize | train | public function finalize()
{
\Ease\TWB\Part::twBootstrapize();
$this->includeJavascript('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js');
$this->includeCss('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css');
$this->addJavascript('$(\'#'.$this->getTagID().'\').treeview({'.\Ease\TWB\Part::partPropertiesToString($this->properties).'})',
null, true);
} | php | {
"resource": ""
} |
q10185 | DcxApiClient.stream | train | public function stream($url, array $query, callable $eventListener)
{
try {
$response = $this->guzzleClient->request
(
'GET',
$this->fullUrl($url),
$this->getRequestOptions
(
[
'stream' => true,
'query' => $this->mergeQuery($url, $query),
'headers' =>
[
'Accept' => 'text/event-stream'
]
]
)
);
} catch (RequestException $exception) {
if ($exception->hasResponse()) {
$response = $exception->getResponse();
} else {
return 500;
}
}
if (strpos($response->getHeader('Content-Type')[0], 'text/event-stream') !== false) {
$this->handleStreamBody($response->getBody(), $eventListener);
} elseif ($this->isJsonResponse($response)) {
$responseData = $this->decodeJson($response->getBody());
$eventListener(['type' => '', 'id' => '', 'data' => $responseData]);
}
return $response->getStatusCode();
} | php | {
"resource": ""
} |
q10186 | Service.sendRequest | train | protected function sendRequest($requiredParams, $params, $callback)
{
$response = $this->client->send($requiredParams, array_merge($params, [
'module' => static::getModule(),
'controller' => static::getController(),
'version' => $this->version,
]), function ($response) use ($callback) {
if (isset($response->error)) {
return $response;
}
return call_user_func($callback, $response);
});
if (isset($response->error)) {
$this->lastError = isset($response->error->message) ? $response->error->message : 'Unknown error!';
if ($this->client->softExceptionEnabled) {
if (isset($response->meta['statusCode']) ? $response->meta['statusCode'] : false) {
throw $response->error->exception;
}
throw new Exception('API error ' . (isset($response->error->code) ? $response->error->code : -1) . '!');
}
}
return $response;
} | php | {
"resource": ""
} |
q10187 | FileLoader.mergeEnvironments | train | public function mergeEnvironments(array $lines, string $file): array
{
if ($this->files->exists($file)) {
$lines = \array_replace_recursive($lines, $this->files->getRequire($file));
}
return $lines;
} | php | {
"resource": ""
} |
q10188 | FeatureType.getValue | train | public static function getValue($slug, $featureId, $locale = 'en_US')
{
return self::getValues([$slug], [$featureId], $locale)[$slug][$featureId];
} | php | {
"resource": ""
} |
q10189 | Guzzle6ApiClient._doRequest | train | protected function _doRequest($method, $uri, $options)
{
return $this->httpClient->request($method, $uri, $options);
} | php | {
"resource": ""
} |
q10190 | DoctrineIterator.loadPage | train | protected function loadPage($page)
{
$this->pageStart = $page * $this->pageSize;
$this->pageData = $this->query->setFirstResult($this->pageStart)->setMaxResults($this->pageSize)->getResult();
} | php | {
"resource": ""
} |
q10191 | FeatureType.initFeatureFeatureTypes | train | public function initFeatureFeatureTypes($overrideExisting = true)
{
if (null !== $this->collFeatureFeatureTypes && !$overrideExisting) {
return;
}
$this->collFeatureFeatureTypes = new ObjectCollection();
$this->collFeatureFeatureTypes->setModel('\FeatureType\Model\FeatureFeatureType');
} | php | {
"resource": ""
} |
q10192 | FeatureType.getFeatureFeatureTypes | train | public function getFeatureFeatureTypes($criteria = null, ConnectionInterface $con = null)
{
$partial = $this->collFeatureFeatureTypesPartial && !$this->isNew();
if (null === $this->collFeatureFeatureTypes || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collFeatureFeatureTypes) {
// return empty collection
$this->initFeatureFeatureTypes();
} else {
$collFeatureFeatureTypes = ChildFeatureFeatureTypeQuery::create(null, $criteria)
->filterByFeatureType($this)
->find($con);
if (null !== $criteria) {
if (false !== $this->collFeatureFeatureTypesPartial && count($collFeatureFeatureTypes)) {
$this->initFeatureFeatureTypes(false);
foreach ($collFeatureFeatureTypes as $obj) {
if (false == $this->collFeatureFeatureTypes->contains($obj)) {
$this->collFeatureFeatureTypes->append($obj);
}
}
$this->collFeatureFeatureTypesPartial = true;
}
reset($collFeatureFeatureTypes);
return $collFeatureFeatureTypes;
}
if ($partial && $this->collFeatureFeatureTypes) {
foreach ($this->collFeatureFeatureTypes as $obj) {
if ($obj->isNew()) {
$collFeatureFeatureTypes[] = $obj;
}
}
}
$this->collFeatureFeatureTypes = $collFeatureFeatureTypes;
$this->collFeatureFeatureTypesPartial = false;
}
}
return $this->collFeatureFeatureTypes;
} | php | {
"resource": ""
} |
q10193 | FeatureType.countFeatureFeatureTypes | train | public function countFeatureFeatureTypes(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collFeatureFeatureTypesPartial && !$this->isNew();
if (null === $this->collFeatureFeatureTypes || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collFeatureFeatureTypes) {
return 0;
}
if ($partial && !$criteria) {
return count($this->getFeatureFeatureTypes());
}
$query = ChildFeatureFeatureTypeQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterByFeatureType($this)
->count($con);
}
return count($this->collFeatureFeatureTypes);
} | php | {
"resource": ""
} |
q10194 | FeatureType.addFeatureFeatureType | train | public function addFeatureFeatureType(ChildFeatureFeatureType $l)
{
if ($this->collFeatureFeatureTypes === null) {
$this->initFeatureFeatureTypes();
$this->collFeatureFeatureTypesPartial = true;
}
if (!in_array($l, $this->collFeatureFeatureTypes->getArrayCopy(), true)) { // only add it if the **same** object is not already associated
$this->doAddFeatureFeatureType($l);
}
return $this;
} | php | {
"resource": ""
} |
q10195 | FeatureType.getFeatureFeatureTypesJoinFeature | train | public function getFeatureFeatureTypesJoinFeature($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN)
{
$query = ChildFeatureFeatureTypeQuery::create(null, $criteria);
$query->joinWith('Feature', $joinBehavior);
return $this->getFeatureFeatureTypes($query, $con);
} | php | {
"resource": ""
} |
q10196 | FeatureType.initFeatureTypeI18ns | train | public function initFeatureTypeI18ns($overrideExisting = true)
{
if (null !== $this->collFeatureTypeI18ns && !$overrideExisting) {
return;
}
$this->collFeatureTypeI18ns = new ObjectCollection();
$this->collFeatureTypeI18ns->setModel('\FeatureType\Model\FeatureTypeI18n');
} | php | {
"resource": ""
} |
q10197 | FeatureType.getFeatureTypeI18ns | train | public function getFeatureTypeI18ns($criteria = null, ConnectionInterface $con = null)
{
$partial = $this->collFeatureTypeI18nsPartial && !$this->isNew();
if (null === $this->collFeatureTypeI18ns || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collFeatureTypeI18ns) {
// return empty collection
$this->initFeatureTypeI18ns();
} else {
$collFeatureTypeI18ns = ChildFeatureTypeI18nQuery::create(null, $criteria)
->filterByFeatureType($this)
->find($con);
if (null !== $criteria) {
if (false !== $this->collFeatureTypeI18nsPartial && count($collFeatureTypeI18ns)) {
$this->initFeatureTypeI18ns(false);
foreach ($collFeatureTypeI18ns as $obj) {
if (false == $this->collFeatureTypeI18ns->contains($obj)) {
$this->collFeatureTypeI18ns->append($obj);
}
}
$this->collFeatureTypeI18nsPartial = true;
}
reset($collFeatureTypeI18ns);
return $collFeatureTypeI18ns;
}
if ($partial && $this->collFeatureTypeI18ns) {
foreach ($this->collFeatureTypeI18ns as $obj) {
if ($obj->isNew()) {
$collFeatureTypeI18ns[] = $obj;
}
}
}
$this->collFeatureTypeI18ns = $collFeatureTypeI18ns;
$this->collFeatureTypeI18nsPartial = false;
}
}
return $this->collFeatureTypeI18ns;
} | php | {
"resource": ""
} |
q10198 | FeatureType.countFeatureTypeI18ns | train | public function countFeatureTypeI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collFeatureTypeI18nsPartial && !$this->isNew();
if (null === $this->collFeatureTypeI18ns || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collFeatureTypeI18ns) {
return 0;
}
if ($partial && !$criteria) {
return count($this->getFeatureTypeI18ns());
}
$query = ChildFeatureTypeI18nQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterByFeatureType($this)
->count($con);
}
return count($this->collFeatureTypeI18ns);
} | php | {
"resource": ""
} |
q10199 | FeatureType.addFeatureTypeI18n | train | public function addFeatureTypeI18n(ChildFeatureTypeI18n $l)
{
if ($l && $locale = $l->getLocale()) {
$this->setLocale($locale);
$this->currentTranslations[$locale] = $l;
}
if ($this->collFeatureTypeI18ns === null) {
$this->initFeatureTypeI18ns();
$this->collFeatureTypeI18nsPartial = true;
}
if (!in_array($l, $this->collFeatureTypeI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated
$this->doAddFeatureTypeI18n($l);
}
return $this;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.