_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9200 | ElasticaService.index | train | public function index($record, $stage = 'Stage') {
if (!$this->enabled) {
return;
}
$document = $record->getElasticaDocument($stage);
$type = $record->getElasticaType();
$this->indexDocument($document, $type);
} | php | {
"resource": ""
} |
q9201 | ElasticaService.endBulkIndex | train | public function endBulkIndex() {
if (!$this->connected) {
return;
}
$index = $this->getIndex();
try {
foreach ($this->buffer as $type => $documents) {
$index->getType($type)->addDocuments($documents);
$index->refresh();
}
} catch (HttpException $ex) {
$this->connected = false;
// TODO LOG THIS ERROR
\SS_Log::log($ex, \SS_Log::ERR);
} catch (\Elastica\Exception\BulkException $be) {
\SS_Log::log($be, \SS_Log::ERR);
throw $be;
}
$this->buffered = false;
$this->buffer = array();
} | php | {
"resource": ""
} |
q9202 | ElasticaService.remove | train | public function remove($record, $stage = 'Stage') {
$index = $this->getIndex();
$type = $index->getType($record->getElasticaType());
try {
$type->deleteDocument($record->getElasticaDocument($stage));
} catch (\Exception $ex) {
\SS_Log::log($ex, \SS_Log::WARN);
return false;
}
return true;
} | php | {
"resource": ""
} |
q9203 | ElasticaService.define | train | public function define() {
$index = $this->getIndex();
if (!$index->exists()) {
$index->create();
}
try {
$this->createMappings($index);
} catch (\Elastica\Exception\ResponseException $ex) {
\SS_Log::log($ex, \SS_Log::WARN);
}
} | php | {
"resource": ""
} |
q9204 | ElasticaService.createMappings | train | protected function createMappings(\Elastica\Index $index) {
foreach ($this->getIndexedClasses() as $class) {
/** @var $sng Searchable */
$sng = singleton($class);
$type = $sng->getElasticaType();
if (isset($this->mappings[$type])) {
// captured later
continue;
}
$mapping = $sng->getElasticaMapping();
$mapping->setType($index->getType($type));
$mapping->send();
}
if ($this->mappings) {
foreach ($this->mappings as $type => $fields) {
$mapping = new Mapping();
$mapping->setProperties($fields);
$mapping->setParam('date_detection', false);
$mapping->setType($index->getType($type));
$mapping->send();
}
}
} | php | {
"resource": ""
} |
q9205 | ElasticaService.refresh | train | public function refresh($logFunc = null) {
$index = $this->getIndex();
if (!$logFunc) {
$logFunc = function ($msg) {
};
}
foreach ($this->getIndexedClasses() as $class) {
$logFunc("Indexing items of type $class");
$this->startBulkIndex();
foreach ($class::get() as $record) {
$logFunc("Indexing " . $record->Title);
$this->index($record);
}
if (\Object::has_extension($class, 'Versioned')) {
$live = \Versioned::get_by_stage($class, 'Live');
foreach ($live as $liveRecord) {
$logFunc("Indexing Live record " . $liveRecord->Title);
$this->index($liveRecord, 'Live');
}
}
$this->endBulkIndex();
}
} | php | {
"resource": ""
} |
q9206 | DateHelper.formatOrNull | train | public static function formatOrNull($dateTime, $format = 'Y-m-d H:i:s', $null = null)
{
if ($dateTime instanceof \DateTime) {
return $dateTime->format($format);
} elseif (ValueHelper::isDateTime($dateTime)) {
return static::stringToDateTime($dateTime)->format($format);
} else {
return $null;
}
} | php | {
"resource": ""
} |
q9207 | Domain.getDomainInfo | train | public function getDomainInfo($domain)
{
try {
$result = $this->getDomainLookupQuery($domain)->getSingleResult();
} catch (NoResultException $e) {
$result = null;
}
return $result;
} | php | {
"resource": ""
} |
q9208 | Domain.getDomainLookupQuery | train | private function getDomainLookupQuery($domain = null)
{
/** @var \Doctrine\ORM\QueryBuilder $queryBuilder */
$queryBuilder = $this->_em->createQueryBuilder();
$queryBuilder->select(
'domain.domain,
primary.domain primaryDomain,
language.iso639_2b languageId,
site.siteId,
country.iso3 countryId'
)
->from(\Rcm\Entity\Domain::class, 'domain', 'domain.domain')
->leftJoin('domain.primaryDomain', 'primary')
->leftJoin('domain.defaultLanguage', 'language')
->leftJoin(
\Rcm\Entity\Site::class,
'site',
Join::WITH,
'site.domain = domain.domainId'
)
->leftJoin('site.country', 'country');
if (!empty($domain)) {
$queryBuilder->andWhere('domain.domain = :domain')
->setParameter('domain', $domain);
}
return $queryBuilder->getQuery();
} | php | {
"resource": ""
} |
q9209 | Domain.searchForDomain | train | public function searchForDomain($domainSearchParam)
{
$domainsQueryBuilder = $this->createQueryBuilder('domain');
$domainsQueryBuilder->where('domain.domain LIKE :domainSearchParam');
$query = $domainsQueryBuilder->getQuery();
$query->setParameter('domainSearchParam', $domainSearchParam);
return $query->getResult();
} | php | {
"resource": ""
} |
q9210 | Redirect.getRedirectList | train | public function getRedirectList($siteId)
{
try {
$result = $this->getQuery($siteId)->getResult();
} catch (NoResultException $e) {
$result = [];
}
return $result;
} | php | {
"resource": ""
} |
q9211 | Redirect.getQuery | train | private function getQuery($siteId, $url = null)
{
if (empty($siteId) || !is_numeric($siteId)) {
throw new InvalidArgumentException('Invalid Site Id To Search By');
}
/** @var \Doctrine\ORM\QueryBuilder $queryBuilder */
$queryBuilder = $this->_em->createQueryBuilder();
$queryBuilder
->select('r')
->from(\Rcm\Entity\Redirect::class, 'r', 'r.requestUrl')
->leftJoin('r.site', 'site')
->where('r.site = :siteId')
->orWhere('r.site is null')
->orderBy('site.siteId', 'DESC')//Makes site-specific rules take priority
->setMaxResults(1)//Improves speed when no match found
->setParameter('siteId', $siteId);
if (!empty($url)) {
$queryBuilder->andWhere('r.requestUrl = :requestUrl');
$queryBuilder->setParameter('requestUrl', $url);
}
return $queryBuilder->getQuery();
} | php | {
"resource": ""
} |
q9212 | Client.query | train | public function query($name, $parameters = [])
{
if (!isset($parameters['APPID'])) {
$parameters['APPID'] = $this->apiKey;
}
if (!isset($parameters['units'])) {
$parameters['units'] = $this->units;
}
if (!isset($parameters['lang'])) {
$parameters['lang'] = $this->lang;
}
$baseUrl = $this->apiUrl.$name;
$requestQueryParts = [];
foreach ($parameters as $key => $value) {
$requestQueryParts[] = $key.'='.rawurlencode($value);
}
$baseUrl .= '?'.implode('&', $requestQueryParts);
$response = $this->guzzleClient->get($baseUrl);
$response = json_decode($response->getBody()->getContents());
return $response;
} | php | {
"resource": ""
} |
q9213 | Client.getForecast | train | public function getForecast($city, $days = null, $parameters = [])
{
if ($days) {
if (!empty($parameters)) {
$parameters['cnt'] = $days;
} else {
$parameters = ['cnt' => $days];
}
}
return $this->doGenericQuery('forecast/daily', $city, $parameters);
} | php | {
"resource": ""
} |
q9214 | Router.post | train | public function post($uri, $callback, $acceptedFormats = null)
{
parent::addRoute('POST', $uri, $callback, $acceptedFormats);
} | php | {
"resource": ""
} |
q9215 | IconFactory.parseFontAwesomeIcon | train | public static function parseFontAwesomeIcon(array $args) {
$icon = static::newFontAwesomeIcon();
$icon->setName(ArrayHelper::get($args, "name", "home"));
$icon->setStyle(ArrayHelper::get($args, "style"));
$icon->setAnimation(ArrayHelper::get($args, "animation"));
$icon->setBordered(ArrayHelper::get($args, "bordered", false));
$icon->setFixedWidth(ArrayHelper::get($args, "fixedWidth", false));
$icon->setFont(ArrayHelper::get($args, "font"));
$icon->setPull(ArrayHelper::get($args, "pull"));
$icon->setSize(ArrayHelper::get($args, "size"));
return $icon;
} | php | {
"resource": ""
} |
q9216 | IconFactory.parseMaterialDesignIconicFontIcon | train | public static function parseMaterialDesignIconicFontIcon(array $args) {
$icon = static::newMaterialDesignIconicFontIcon();
$icon->setName(ArrayHelper::get($args, "name", "home"));
$icon->setStyle(ArrayHelper::get($args, "style"));
$icon->setBorder(ArrayHelper::get($args, "border", false));
$icon->setFixedWidth(ArrayHelper::get($args, "fixedWidth", false));
$icon->setFlip(ArrayHelper::get($args, "flip"));
$icon->setPull(ArrayHelper::get($args, "pull"));
$icon->setRotate(ArrayHelper::get($args, "rotate"));
$icon->setSize(ArrayHelper::get($args, "size"));
$icon->setSpin(ArrayHelper::get($args, "spin"));
return $icon;
} | php | {
"resource": ""
} |
q9217 | BaseController.renderInstance | train | public function renderInstance($instanceId, $instanceConfig)
{
$view = new ViewModel(
[
'instanceId' => $instanceId,
'instanceConfig' => $instanceConfig,
'config' => $this->config,
]
);
$view->setTemplate($this->template);
return $view;
} | php | {
"resource": ""
} |
q9218 | BaseController.postIsForThisPlugin | train | public function postIsForThisPlugin()
{
if (!$this->getRequest()->isPost()) {
return false;
}
return
$this->getRequest()->getPost('rcmPluginName') == $this->pluginName;
} | php | {
"resource": ""
} |
q9219 | UserRepository.findUserByForgetPasswordToken | train | public function findUserByForgetPasswordToken($token)
{
try {
$builder = $this->createQueryBuilder('u');
return $builder->where($builder->expr()->eq('u.forgetPasswordToken', ':token'))
->andWhere($builder->expr()->isNotNull('u.forgetPasswordExpired'))
->andWhere('u.forgetPasswordExpired >= :today')
->setParameter('token', $token)
->setParameter('today', new \DateTime(), Type::DATETIME)
->getQuery()
->getSingleResult();
} catch (NoResultException $ex) {
// This means that nothing was found this thrown by the getSingleResult method
return null;
} catch (NonUniqueResultException $ex) {
// this means that there was more then one result found and we have duplicate tokens in our database.
// Look up the code for the error message in the logs
throw new ProgrammerException('Duplicate Forget Password Token was found.', ProgrammerException::FORGET_PASSWORD_TOKEN_DUPLICATE_EXCEPTION_CODE);
}
} | php | {
"resource": ""
} |
q9220 | UserRepository.searchUsers | train | public function searchUsers($searchString = null, $page, $limit)
{
return $this->buildUserSearchQuery($searchString)
->getQuery()
->setMaxResults($limit)
->setFirstResult($limit * ($page - 1))
->getResult();
} | php | {
"resource": ""
} |
q9221 | UserRepository.countNumberOfUserInSearch | train | public function countNumberOfUserInSearch($searchString = null)
{
$builder = $this->buildUserSearchQuery($searchString);
return $builder->select($builder->expr()->count('u.id'))
->getQuery()
->getSingleScalarResult();
} | php | {
"resource": ""
} |
q9222 | UserRepository.findUserByValidRefreshToken | train | public function findUserByValidRefreshToken($token)
{
/** @var BaseUser $user */
$user = $this->findOneBy(['refreshToken' => $token]);
if (!empty($user) && $user->isRefreshTokenValid()) {
return $user;
}
return null;
} | php | {
"resource": ""
} |
q9223 | ModelSaving.save | train | public function save()
{
event(new BeforeSave($this));
$this->beforeSave();
$this->doSave();
$this->afterSave();
event(new AfterSave($this));
} | php | {
"resource": ""
} |
q9224 | ModelSaving.afterSave | train | protected function afterSave()
{
$this->brokenAfterSave = false;
foreach (\Request::except('_token') as $key => $value) {
// Could swap this out for model -> getAttribute, then check if we have an attribute or a relation... getRelationValue() is helpful
if (method_exists($this->model, $key) && is_a(call_user_func_array([$this->model, $key], []), 'Illuminate\Database\Eloquent\Relations\Relation')) {
$this->saveRelation('afterSave', $key, $value);
}
}
} | php | {
"resource": ""
} |
q9225 | ModelSaving.saveRelation | train | private function saveRelation($action, $key, $value)
{
// Could swap this out for model -> getAttribute, then check if we have an attribute or a relation... getRelationValue() is helpful
if (method_exists($this->model, $key) && is_a(call_user_func_array([$this->model, $key], []), 'Illuminate\Database\Eloquent\Relations\Relation')) {
foreach ($this->{$action.'Relations'} as $relationship => $method) {
if (is_a(call_user_func_array([$this->model, $key], []), 'Illuminate\Database\Eloquent\Relations\\'.$relationship)) {
$this->model->$key()->$method($value);
return;
}
}
}
} | php | {
"resource": ""
} |
q9226 | EventManager.storeCallback | train | protected function storeCallback(\Closure $callback)
{
$key = md5(microtime());
$this->callbacks[$key] = $callback;
return $key;
} | php | {
"resource": ""
} |
q9227 | EventManager.pushToQueue | train | protected function pushToQueue($event, $key, $priority)
{
$end = substr($event, -2);
if (isset($this->queues[$event])) {
if ($end == self::WILDCARD) {
$this->wildcardSearching = true;
$this->queues[$event][] = ['key' => $key, 'priority' => $priority];
} else {
$this->queues[$event]->insert($key, $priority);
}
} else {
if ($end == self::WILDCARD) {
$this->wildcardSearching = true;
$this->queues[$event][] = ['key' => $key, 'priority' => $priority];
} else {
$this->queues[$event] = new PriorityQueue;
$this->queues[$event]->insert($key, $priority);
}
}
} | php | {
"resource": ""
} |
q9228 | EventManager.remove | train | public function remove($name)
{
if (isset($this->queues[$name])) {
unset($this->queues[$name]);
}
return $this;
} | php | {
"resource": ""
} |
q9229 | EventManager.getListeners | train | public function getListeners($name)
{
$listenerMatched = false;
/**
* Do we have an exact match?
*/
if (isset($this->queues[$name])) {
$listenerMatched = true;
}
/**
* Optionally search for wildcard matches.
*/
if ($this->wildcardSearching) {
if ($this->populateQueueFromWildSearch($name)) {
$listenerMatched = true;
}
}
$listeners = [];
if ($listenerMatched) {
foreach ($this->queues[$name] as $key) {
$listeners[] = $this->callbacks[$key];
}
}
return $listeners;
} | php | {
"resource": ""
} |
q9230 | EventManager.attach | train | public function attach($name, \Closure $callback, $priority = 0)
{
$key = $this->storeCallback($callback);
if (is_array($name)) {
foreach ($name as $event) {
$this->pushToQueue($event, $key, $priority);
}
} else {
$this->pushToQueue($name, $key, $priority);
}
return $this;
} | php | {
"resource": ""
} |
q9231 | JsonBodyParserMiddleware.process | train | public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
$contentType = $request->getHeaderLine('Content-Type');
if (!$this->match($contentType)) {
return $delegate->process($request);
}
$rawBody = (string)$request->getBody();
$parsedBody = json_decode($rawBody, true);
if (!empty($rawBody) && json_last_error() !== JSON_ERROR_NONE) {
$statusCode = 400;
$apiMessage = new HttpStatusCodeApiMessage($statusCode);
$apiMessage->setCode('invalid-json');
$apiMessage->setValue('Invalid JSON');
$apiResponse = $this->newPsrResponseWithTranslatedMessages->__invoke(
null,
$statusCode,
$apiMessage
);
return $apiResponse;
}
$request = $request
->withAttribute('rawBody', $rawBody)
->withParsedBody($parsedBody);
return $delegate->process($request);
} | php | {
"resource": ""
} |
q9232 | ContainerRenderer.renderContainer | train | public function renderContainer(
PhpRenderer $view,
$name,
$revisionId = null
) {
$site = $this->getSite($view);
$container = $site->getContainer($name);
$pluginHtml = '';
if (!empty($container)) {
if (empty($revisionId)) {
$revision = $container->getPublishedRevision();
} else {
$revision = $container->getRevisionById($revisionId);
}
$pluginWrapperRows = $revision->getPluginWrappersByRow();
if (!empty($pluginWrapperRows)) {
$pluginHtml = $this->getPluginRowsHtml($view, $pluginWrapperRows);
}
$revisionId = $revision->getRevisionId();
} else {
$revisionId = -1;
}
// The front end demands rows in empty containers
if (empty($pluginHtml)) {
$pluginHtml .= '<div class="row"></div>';
}
return $this->getContainerWrapperHtml(
$revisionId,
$name,
$pluginHtml,
false
);
} | php | {
"resource": ""
} |
q9233 | ContainerRenderer.isDuplicateCss | train | protected function isDuplicateCss(
PhpRenderer $view,
$container
) {
/** @var \Zend\View\Helper\HeadLink $headLink */
$headLink = $view->headLink();
$containers = $headLink->getContainer();
foreach ($containers as &$item) {
if (($item->rel == 'stylesheet')
&& ($item->href == $container->href)
) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q9234 | ContainerRenderer.isDuplicateScript | train | protected function isDuplicateScript(
PhpRenderer $view,
$container
) {
/** @var \Zend\View\Helper\HeadScript $headScript */
$headScript = $view->headScript();
$container = $headScript->getContainer();
foreach ($container as &$item) {
if (($item->source === null)
&& !empty($item->attributes['src'])
&& !empty($container->attributes['src'])
&& ($container->attributes['src'] == $item->attributes['src'])
) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q9235 | ErrorHandler.registerError | train | public function registerError($level, callable $callback)
{
$reflection = new \ReflectionFunction($callback);
$parameters = $reflection->getParameters();
if (count($parameters) > 4) {
throw new \Exception("Specified callback cannot have more than 4 arguments (message, file, line, context)");
}
$this->registeredErrorCallbacks[$level] = $callback;
} | php | {
"resource": ""
} |
q9236 | ErrorHandler.exceptionHandler | train | public function exceptionHandler(\Throwable $error)
{
$reflection = new \ReflectionClass($error);
$registeredException = $this->findRegisteredExceptions($reflection);
if (!is_null($registeredException)) {
$registeredException($error);
}
} | php | {
"resource": ""
} |
q9237 | ErrorHandler.errorHandler | train | public function errorHandler($type, ...$args)
{
if (!(error_reporting() & $type)) {
// This error code is not included in error_reporting
return true;
}
if (array_key_exists($type, $this->registeredErrorCallbacks)) {
$callback = $this->registeredErrorCallbacks[$type];
$reflection = new \ReflectionFunction($callback);
$reflection->invokeArgs($args);
return true;
}
return false;
} | php | {
"resource": ""
} |
q9238 | ContextAwareParamConverterTrait.initialize | train | protected function initialize(Request $request, ParamConverter $configuration): void
{
$this->request = $request;
$this->configuration = $configuration;
$this->options = new ParameterBag($configuration->getOptions());
} | php | {
"resource": ""
} |
q9239 | DatabaseStatement.next | train | public function next($fetchStyle = \PDO::FETCH_BOTH)
{
$row = $this->statement->fetch($fetchStyle);
$this->sanitizeOutput($row);
return $row;
} | php | {
"resource": ""
} |
q9240 | FacebookProvider.loadUserByUsername | train | public function loadUserByUsername($username)
{
try {
// If you want to request the user's picture you can picture
// You can also specify the picture height using picture.height(500).width(500)
// Be sure request the scope param in the js
$response = $this->facebookClient->get('/me?fields=email', $username);
$facebookUser = $response->getGraphUser();
$email = $facebookUser->getEmail();
$facebookUserId = $facebookUser->getId();
$user = $this->userService->findByFacebookUserId($facebookUserId);
// We always check their facebook user id first because they could have change their email address
if (!empty($user)) {
return $user;
}
$user = $this->userService->findUserByEmail($email);
// This means that user already register and we need to associate their facebook account to their user entity
if (!empty($user)) {
$this->updateUserWithFacebookId($user, $facebookUserId);
return $user;
}
// This means no user was found and we need to register user with their facebook user id
return $this->registerUser($email, $facebookUserId);
} catch (FacebookResponseException $ex) {
throw new UsernameNotFoundException("Facebook AuthToken Did Not validate, ERROR MESSAGE " . $ex->getMessage(), ProgrammerException::FACEBOOK_RESPONSE_EXCEPTION_CODE);
} catch (FacebookSDKException $ex) {
throw new UsernameNotFoundException("Facebook SDK failed, ERROR MESSAGE " . $ex->getMessage(), ProgrammerException::FACEBOOK_SDK_EXCEPTION_CODE);
} catch (\Exception $ex) {
throw new UsernameNotFoundException("Something unknown went wrong, ERROR MESSAGE " . $ex->getMessage(), ProgrammerException::FACEBOOK_PROVIDER_EXCEPTION);
}
} | php | {
"resource": ""
} |
q9241 | FacebookProvider.updateUserWithFacebookId | train | protected function updateUserWithFacebookId(BaseUser $user, $facebookUserId)
{
$user->setFacebookUserId($facebookUserId);
$this->userService->save($user);
} | php | {
"resource": ""
} |
q9242 | FacebookProvider.registerUser | train | protected function registerUser($email, $facebookUserId)
{
$className = $this->userService->getUserClass();
/** @var BaseUser $user */
$user = (new $className());
$user->setEmail($email)
->setFacebookUserId($facebookUserId)
->setPlainPassword(base64_encode(random_bytes(20)));
$this->userService->registerUser($user, UserService::SOURCE_TYPE_FACEBOOK);
return $user;
} | php | {
"resource": ""
} |
q9243 | Tag.reIndex | train | public function reIndex()
{
$tags = $this->select(['tags.id', 'taggables.tag_id as pivot_tag_id'])
->join('taggables', 'tags.id', '=', 'taggables.tag_id')
->get()->keyBy('id')->all();
$this->whereNotIn('id', array_keys($tags))->delete();
// dd($this->has($model->getMorphClass(), '=', 0)->toSql());
//
// The commentable relation on the Comment model will return either a
// Post or Video instance, depending on which type of model owns the comment.
// $commentable = $comment->commentable;
} | php | {
"resource": ""
} |
q9244 | Select2Helper.toResults | train | public static function toResults(array $items) {
$output = [];
foreach ($items as $current) {
if (false === ($current instanceof Select2ItemInterface)) {
throw new InvalidArgumentException("The item must implements Select2ItemInterface");
}
$output[] = [
"id" => $current->getSelect2ItemId(),
"text" => $current->getSelect2ItemText(),
];
}
return $output;
} | php | {
"resource": ""
} |
q9245 | BalancedThread.SomeUndefinedLongRunningWork | train | public function SomeUndefinedLongRunningWork($timeToWorkOnSomething, callable $onComplete = null)
{
if ($this->isExternal()) {
$timeToWorkOnSomething *= 100;
echo "Start work $timeToWorkOnSomething msec on thread: " . posix_getpid() . PHP_EOL;
//just a simulation on different time running process
usleep($timeToWorkOnSomething);
//not required but return everything you like
//lets return a message to display on parent
echo "Completed work $timeToWorkOnSomething msec on thread: " . posix_getpid();
return "Completed work $timeToWorkOnSomething msec on thread: " . posix_getpid();
} else {
return $this->asyncCallOnChild(__FUNCTION__, array($timeToWorkOnSomething), $onComplete, function (AsyncMessage $messga) {
var_dump($messga->GetResult()->getMessage());
});
}
} | php | {
"resource": ""
} |
q9246 | NewPageForm.isValid | train | public function isValid()
{
if ($this->get('page-template')->getValue() == 'blank') {
$this->setValidationGroup(
[
'url',
'title',
'main-layout',
]
);
} else {
$this->setValidationGroup(
[
'url',
'title',
'page-template',
]
);
}
return parent::isValid();
} | php | {
"resource": ""
} |
q9247 | Broker.selectSingle | train | protected function selectSingle(string $query, array $parameters = [], string $allowedTags = "")
{
$statement = $this->query($query, $parameters);
$statement->setAllowedHtmlTags($allowedTags);
$result = $statement->next($this->fetchStyle);
return ($result) ? $result : null;
} | php | {
"resource": ""
} |
q9248 | Broker.select | train | protected function select(string $query, array $parameters = [], string $allowedTags = ""): array
{
if (!is_null($this->pager)) {
$query .= $this->pager->getSqlLimit();
}
$statement = $this->query($query, $parameters);
$statement->setAllowedHtmlTags($allowedTags);
$results = [];
while ($row = $statement->next($this->fetchStyle)) {
$results[] = $row;
}
return $results;
} | php | {
"resource": ""
} |
q9249 | Broker.transaction | train | protected function transaction(callable $callback)
{
try {
$this->database->beginTransaction();
$reflect = new \ReflectionFunction($callback);
if ($reflect->getNumberOfParameters() == 1) {
$result = $callback($this->database);
} elseif ($reflect->getNumberOfParameters() == 0) {
$result = $callback();
} else {
throw new \InvalidArgumentException("Specified callback must have 0 or 1 argument");
}
$this->database->commit();
return $result;
} catch (\Exception $e) {
$this->database->rollback();
throw new DatabaseException($e->getMessage());
}
} | php | {
"resource": ""
} |
q9250 | AbstractController.hasRolesOrRedirect | train | protected function hasRolesOrRedirect(array $roles, $or, $redirectUrl, $originUrl = "") {
$user = $this->getKernelEventListener()->getUser();
if (false === UserHelper::hasRoles($user, $roles, $or)) {
// Throw a bad user role exception with an anonymous user if user is null.
$user = null !== $user ? $user : new User("anonymous", "");
throw new BadUserRoleException($user, $roles, $redirectUrl, $originUrl);
}
return true;
} | php | {
"resource": ""
} |
q9251 | RequestFactory.captureHttpRequest | train | private static function captureHttpRequest()
{
$server = $_SERVER;
$uri = self::getCompleteRequestUri($server);
$method = strtoupper($server['REQUEST_METHOD']);
$parameters = self::getParametersFromContentType($server['CONTENT_TYPE'] ?? ContentType::PLAIN);
if (isset($parameters['__method'])) {
$method = strtoupper($parameters['__method']);
}
self::$httpRequest = new Request($uri, $method, [
'parameters' => $parameters,
'cookies' => $_COOKIE,
'files' => $_FILES,
'server' => $server
]);
} | php | {
"resource": ""
} |
q9252 | RequestFactory.getParametersFromContentType | train | private static function getParametersFromContentType(string $contentType): array
{
$parameters = array_merge(
self::getParametersFromGlobal($_GET),
self::getParametersFromGlobal($_POST),
self::getParametersFromGlobal($_FILES));
$paramsSource = [];
$rawInput = file_get_contents('php://input');
switch ($contentType) {
case ContentType::JSON:
$paramsSource = (array) json_decode($rawInput);
break;
case ContentType::XML:
case ContentType::XML_APP:
$xml = new \SimpleXMLElement($rawInput);
$paramsSource = (array) $xml;
break;
default:
parse_str($rawInput, $paramsSource);
}
return array_merge($parameters, self::getParametersFromGlobal($paramsSource));
} | php | {
"resource": ""
} |
q9253 | Block.setBody | train | public function setBody($text)
{
if (is_string($text)) {
$this->lines = explode("\n", $text);
} elseif (is_array($text)) {
$this->lines = $text;
} else {
throw new InvalidArgumentTypeException('Invalid body type', $text, array('string', 'array'));
}
} | php | {
"resource": ""
} |
q9254 | VersionRepository.findPublishedVersionByLocator | train | public function findPublishedVersionByLocator(LocatorInterface $locator)
{
$entity = $this->findActiveVersionByLocator($locator);
if ($entity !== null && $entity->getStatus() === VersionStatuses::PUBLISHED) {
return $entity;
}
return null;
} | php | {
"resource": ""
} |
q9255 | VersionRepository.findActiveVersionByLocator | train | protected function findActiveVersionByLocator(LocatorInterface $locator)
{
$criteria = new Criteria();
$criteria->where(
$criteria->expr()->in(
'status',
[VersionStatuses::PUBLISHED, VersionStatuses::DEPUBLISHED]
)
);
foreach ($locator->toArray() as $column => $value) {
$criteria->andWhere($criteria->expr()->eq($column, $value));
}
$criteria->orderBy(['id' => Criteria::DESC]);
$criteria->setMaxResults(1);
$entities = $this->entityManger->getRepository($this->entityClassName)->matching($criteria)->toArray();
if (isset($entities[0])) {
return $entities[0];
}
return null;
} | php | {
"resource": ""
} |
q9256 | XeroHelperTrait.addCondition | train | public function addCondition($field, $value = '', $operator = '==')
{
if (!in_array($operator, self::$conditionOperators)) {
throw new \InvalidArgumentException('Invalid operator');
}
// Transform a boolean value to its string representation.
if (is_bool($value)) {
$value = $value ? 'true' : 'false';
}
// Construct condition statement based on operator.
if (in_array($operator, ['==', '!='])) {
$this->conditions[] = $field . $operator . '"' . $value . '"';
} elseif ($operator === 'guid') {
$this->conditions[] = $field . '= Guid("'. $value . '")';
} else {
$this->conditions[] = $field . '.' . $operator . '("' . $value . '")';
}
return $this;
} | php | {
"resource": ""
} |
q9257 | XeroHelperTrait.compileConditions | train | public function compileConditions()
{
$ret = [];
if (!empty($this->conditions)) {
$ret['where'] = implode(' ', $this->conditions);
}
return $ret;
} | php | {
"resource": ""
} |
q9258 | XeroHelperTrait.getRequestParameters | train | public function getRequestParameters($request_parameters)
{
$ret = [];
$parts = explode('&', $request_parameters);
foreach ($parts as $part) {
list($key, $value) = explode('=', $part);
$key_decoded = urldecode($key);
$value_decoded = urldecode($value);
$ret[$key_decoded] = $value_decoded;
}
return $ret;
} | php | {
"resource": ""
} |
q9259 | Dispatcher.handle | train | public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
while ($route = $this->router->route($request)) {
$module = $route->getPayload()['module'];
$controller = $route->getPayload()['controller'];
$action = $route->getPayload()['action'];
$class = str_replace(
['{:module}', '{:controller}'],
[$module, $controller],
$this->mapping
);
try {
return $this->assetManager->resolve($class, ['invoke' => $action]);
} catch (\LogicException $e) {
$this->failures[] = ['route' => $route, 'exception' => $e];
}
}
} | php | {
"resource": ""
} |
q9260 | WidgetAbstract.cacheKey | train | public function cacheKey()
{
$this->cacheKey = $this->cacheKey ??
$this->generateCacheKey(
auth()->guest() ? 'guest' : auth()->user()->role
);
return $this->cacheKey;
} | php | {
"resource": ""
} |
q9261 | WidgetAbstract.cacheKeys | train | public function cacheKeys()
{
$keys = [];
$roles = array_merge(cache('roles'), ['guest']);
foreach ($roles as $role) {
$keys[] = $this->generateCacheKey($role);
}
return implode('|', $keys);
} | php | {
"resource": ""
} |
q9262 | WidgetAbstract.generateCacheKey | train | protected function generateCacheKey(string $role)
{
return md5(serialize(array_merge($this->params, [
'widget' => get_class($this),
'app_theme' => app_theme(),
'app_locale' => app_locale(),
'role' => $role,
])));
} | php | {
"resource": ""
} |
q9263 | WidgetAbstract.validator | train | public function validator()
{
return Validator::make(
$this->params, $this->rules(),
$this->messages(), $this->attributes()
);
} | php | {
"resource": ""
} |
q9264 | WidgetAbstract.castParam | train | protected function castParam($key, $value)
{
if (is_null($value) or ! $this->hasCast($key)) {
return $value;
}
switch ($this->getCastType($key)) {
case 'int':
case 'integer':
return (int) $value;
case 'real':
case 'float':
case 'double':
return (float) $value;
case 'string':
return (string) $value;
case 'bool':
case 'boolean':
return (bool) $value;
case 'array':
return (array) $value;
case 'collection':
return collect((array) $value);
default:
return $value;
}
} | php | {
"resource": ""
} |
q9265 | DownloaderThread.download | train | public function download($url, callable $onComplete = null)
{
//first check if the function is called external
if($this->isExternal())
{
$data = file_get_contents($url);
//hold the process to simulate more to do ;-)
sleep(3);
echo "Downloaded: ".strlen($data).' bytes from url: '.$url.PHP_EOL;
//return the data
//parent thread can handle this if needed
return $data;
}
else
{
//we are in the parent context
//just redirect to the thread
//we use async as we dont want to wait for the result
//return the handle allow the caller to check result
return $this->asyncCallOnChild(__FUNCTION__, array($url), $onComplete);
}
} | php | {
"resource": ""
} |
q9266 | CompatibilityServiceProvider.registerServiceProviders | train | protected function registerServiceProviders()
{
foreach ($this->serviceProviders[$this->flare->compatibility()] as $class) {
$this->app->register($class);
}
} | php | {
"resource": ""
} |
q9267 | EncryptedSessionHandler.open | train | public function open($savePath, $sessionName)
{
parent::open($savePath, $sessionName);
$this->cookieKeyName = "key_$sessionName";
if (empty($_COOKIE[$this->cookieKeyName]) || strpos($_COOKIE[$this->cookieKeyName], ':') === false) {
$this->createEncryptionCookie();
return true;
}
list($this->cryptKey, $this->cryptAuth) = explode(':', $_COOKIE[$this->cookieKeyName]);
$this->cryptKey = base64_decode($this->cryptKey);
$this->cryptAuth = base64_decode($this->cryptAuth);
return true;
} | php | {
"resource": ""
} |
q9268 | EncryptedSessionHandler.destroy | train | public function destroy($sessionId)
{
parent::destroy($sessionId);
if (isset($_COOKIE[$this->cookieKeyName])) {
setcookie($this->cookieKeyName, '', 1);
unset($_COOKIE[$this->cookieKeyName]);
}
return true;
} | php | {
"resource": ""
} |
q9269 | EncryptedSessionHandler.encrypt | train | private function encrypt(string $data): string
{
$cipher = Cryptography::encrypt($data, $this->cryptKey);
list($initializationVector, $cipher) = explode(':', $cipher);
$initializationVector = base64_decode($initializationVector);
$cipher = base64_decode($cipher);
$content = $initializationVector . Cryptography::getEncryptionAlgorithm() . $cipher;
$hmac = hash_hmac('sha256', $content, $this->cryptAuth);
return $hmac . ':' . base64_encode($initializationVector) . ':' . base64_encode($cipher);
} | php | {
"resource": ""
} |
q9270 | EncryptedSessionHandler.decrypt | train | private function decrypt(string $data): string
{
list($hmac, $initializationVector, $cipher) = explode(':', $data);
$ivReal = base64_decode($initializationVector);
$cipherReal = base64_decode($cipher);
$validHash = $ivReal . Cryptography::getEncryptionAlgorithm() . $cipherReal;
$newHmac = hash_hmac('sha256', $validHash, $this->cryptAuth);
if ($hmac !== $newHmac) {
throw new \RuntimeException("Invalid decryption key");
}
$decrypt = Cryptography::decrypt($initializationVector . ':' . $cipher, $this->cryptKey);
return $decrypt;
} | php | {
"resource": ""
} |
q9271 | ThreadBase.handleMessage | train | public function handleMessage(ThreadCommunicator $communicator, $messagePayload)
{
$action = $messagePayload['action'];
$parameters = $messagePayload['parameters'];
if (method_exists($this, $action)) {
return call_user_func_array(array($this, $action), $parameters);
}
return false;
} | php | {
"resource": ""
} |
q9272 | ThreadBase.stop | train | public function stop()
{
if ($this->isExternal())
{
$this->communicator->getLoop()->stop();
}
else
{
$this->asyncCallOnChild(__FUNCTION__, func_get_args());
}
} | php | {
"resource": ""
} |
q9273 | ThreadBase.join | train | public function join()
{
if ($this->isExternal()) {
$this->communicator->getLoop()->stop();
} else {
$this->callOnChild(__FUNCTION__, func_get_args());
}
} | php | {
"resource": ""
} |
q9274 | ThreadBase.asyncCallOnChild | train | protected function asyncCallOnChild($action, array $parameters = array(), callable $onResult = null, callable $onError = null)
{
if($this->isExternal())
{
throw new \RuntimeException("Calling ClientThread::CallOnChild from Child context. Did you mean ClientThread::CallOnParent?");
}
else
{
return $this->communicator->SendMessageAsync($this->encode($action, $parameters), $onResult, $onError);
}
} | php | {
"resource": ""
} |
q9275 | Injector.registerMappings | train | public function registerMappings(ConfigInterface $config)
{
$configKeys = [
static::STANDARD_ALIASES => 'mapAliases',
static::SHARED_ALIASES => 'shareAliases',
static::ARGUMENT_DEFINITIONS => 'defineArguments',
static::ARGUMENT_PROVIDERS => 'defineArgumentProviders',
static::DELEGATIONS => 'defineDelegations',
static::PREPARATIONS => 'definePreparations',
];
try {
foreach ($configKeys as $key => $method) {
$$key = $config->hasKey($key)
? $config->getKey($key) : [];
}
$standardAliases = array_merge(
$sharedAliases,
$standardAliases
);
} catch (Exception $exception) {
throw new InvalidMappingsException(
sprintf(
_('Failed to read needed keys from config. Reason: "%1$s".'),
$exception->getMessage()
)
);
}
try {
foreach ($configKeys as $key => $method) {
array_walk($$key, [$this, $method]);
}
} catch (Exception $exception) {
throw new InvalidMappingsException(
sprintf(
_('Failed to set up dependency injector. Reason: "%1$s".'),
$exception->getMessage()
)
);
}
} | php | {
"resource": ""
} |
q9276 | Injector.defineArguments | train | protected function defineArguments($argumentSetup, $alias)
{
foreach ($argumentSetup as $key => $value) {
$this->addArgumentDefinition($value, $alias, [$key, null]);
}
} | php | {
"resource": ""
} |
q9277 | Injector.defineArgumentProviders | train | protected function defineArgumentProviders($argumentSetup, $argument)
{
if (! array_key_exists('mappings', $argumentSetup)) {
throw new InvalidMappingsException(
sprintf(
_('Failed to define argument providers for argument "%1$s". '
. 'Reason: The key "mappings" was not found.'),
$argument
)
);
}
array_walk(
$argumentSetup['mappings'],
[$this, 'addArgumentDefinition'],
[$argument, $argumentSetup['interface'] ?: null]
);
} | php | {
"resource": ""
} |
q9278 | Injector.addArgumentDefinition | train | protected function addArgumentDefinition($callable, $alias, $args)
{
list($argument, $interface) = $args;
$value = is_callable($callable)
? $this->getArgumentProxy($alias, $interface, $callable)
: $callable;
$argumentDefinition = array_key_exists($alias, $this->argumentDefinitions)
? $this->argumentDefinitions[$alias]
: [];
if ($value instanceof Injection) {
$argumentDefinition[$argument] = $value->getAlias();
} else {
$argumentDefinition[":${argument}"] = $value;
}
$this->argumentDefinitions[$alias] = $argumentDefinition;
$this->define($alias, $this->argumentDefinitions[$alias]);
} | php | {
"resource": ""
} |
q9279 | Injector.getArgumentProxy | train | protected function getArgumentProxy($alias, $interface, $callable)
{
if (null === $interface) {
$interface = 'stdClass';
}
$factory = new LazyLoadingValueHolderFactory();
$initializer = function (
& $wrappedObject,
LazyLoadingInterface $proxy,
$method,
array $parameters,
& $initializer
) use (
$alias,
$interface,
$callable
) {
$initializer = null;
$wrappedObject = $callable($alias, $interface);
return true;
};
return $factory->createProxy($interface, $initializer);
} | php | {
"resource": ""
} |
q9280 | Injector.alias | train | public function alias($original, $alias)
{
if (empty($original) || ! is_string($original)) {
throw new ConfigException(
InjectorException::M_NON_EMPTY_STRING_ALIAS,
InjectorException::E_NON_EMPTY_STRING_ALIAS
);
}
if (empty($alias) || ! is_string($alias)) {
throw new ConfigException(
InjectorException::M_NON_EMPTY_STRING_ALIAS,
InjectorException::E_NON_EMPTY_STRING_ALIAS
);
}
$originalNormalized = $this->normalizeName($original);
if (isset($this->shares[$originalNormalized])) {
throw new ConfigException(
sprintf(
InjectorException::M_SHARED_CANNOT_ALIAS,
$this->normalizeName(get_class($this->shares[$originalNormalized])),
$alias
),
InjectorException::E_SHARED_CANNOT_ALIAS
);
}
if (array_key_exists($originalNormalized, $this->shares)) {
$aliasNormalized = $this->normalizeName($alias);
$this->shares[$aliasNormalized] = null;
unset($this->shares[$originalNormalized]);
}
$this->aliases[$originalNormalized] = $alias;
return $this;
} | php | {
"resource": ""
} |
q9281 | Injector.inspect | train | public function inspect($nameFilter = null, $typeFilter = null)
{
$result = [];
$name = $nameFilter ? $this->normalizeName($nameFilter) : null;
if (empty($typeFilter)) {
$typeFilter = static::I_ALL;
}
$types = [
static::I_BINDINGS => 'classDefinitions',
static::I_DELEGATES => 'delegates',
static::I_PREPARES => 'prepares',
static::I_ALIASES => 'aliases',
static::I_SHARES => 'shares',
];
foreach ($types as $type => $source) {
if ($typeFilter & $type) {
$result[$type] = $this->filter($this->{$source}, $name);
}
}
return $result;
} | php | {
"resource": ""
} |
q9282 | Theme.getTemplates | train | public static function getTemplates($path = null, $regex = null)
{
$dirs = [];
$files = [];
$path = $path ?? theme_path('views');
$regex = $regex ?? '/\.(tpl|ini|css|js|blade\.php)/';
if (! $path instanceof \DirectoryIterator) {
$path = new \DirectoryIterator((string) $path);
}
foreach ($path as $node) {
if ($node->isDir() and ! $node->isDot()) {
if (count($tree = self::getTemplates($node->getPathname(), $regex))) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
if (is_null($regex) or preg_match($regex, $name = $node->getFilename())) {
$data_path = str_replace(theme_path('views'), '', $node->getPathname());
$files[$data_path] = $name;
}
}
}
// asort($dirs); sort($files);
return array_merge($dirs, $files);
} | php | {
"resource": ""
} |
q9283 | DepartureBoard.generateUrlOptions | train | protected function generateUrlOptions(array $options): array
{
$urlOptions = [];
if (isset($options['date'])) {
$urlOptions['date'] = $options['date']->format('d.m.y');
$urlOptions['time'] = $options['date']->format('H:i');
unset($options['date']);
}
return array_merge($urlOptions, $options);
} | php | {
"resource": ""
} |
q9284 | CsrfGuard.generateHiddenFields | train | public function generateHiddenFields()
{
$name = $this->generateFormName();
$token = $this->generateToken($name);
$html = '<input type="hidden" name="' . self::REQUEST_TOKEN_NAME . '" value="' . $name . '" />';
$html .= '<input type="hidden" name="' . self::REQUEST_TOKEN_VALUE . '" value="' . $token . '" />';
return $html;
} | php | {
"resource": ""
} |
q9285 | CsrfGuard.guard | train | public function guard()
{
if ($this->isHttpMethodFiltered($this->request->getMethod())) {
$formName = $this->getProvidedFormName();
$providedToken = $this->getProvidedCsrfToken();
if (is_null($formName) || is_null($providedToken)) {
throw new InvalidCsrfException();
}
if (!$this->validateToken($formName, $providedToken)) {
throw new InvalidCsrfException();
}
}
} | php | {
"resource": ""
} |
q9286 | CsrfGuard.injectForms | train | public function injectForms($html)
{
preg_match_all("/<form(.*?)>(.*?)<\\/form>/is", $html, $matches, PREG_SET_ORDER);
if (is_array($matches)) {
foreach ($matches as $match) {
if (strpos($match[1], "nocsrf") !== false) {
continue;
}
$hiddenFields = self::generateHiddenFields();
$html = str_replace($match[0], "<form{$match[1]}>{$hiddenFields}{$match[2]}</form>", $html);
}
}
return $html;
} | php | {
"resource": ""
} |
q9287 | CsrfGuard.generateToken | train | private function generateToken(string $formName): string
{
$token = Cryptography::randomString(self::TOKEN_LENGTH);
$csrfData = Session::getInstance()->read('__CSRF_TOKEN', []);
$csrfData[$formName] = $token;
Session::getInstance()->set('__CSRF_TOKEN', $csrfData);
return $token;
} | php | {
"resource": ""
} |
q9288 | CsrfGuard.validateToken | train | private function validateToken(string $formName, string $token): bool
{
$sortedCsrf = $this->getStoredCsrfToken($formName);
if (!is_null($sortedCsrf)) {
$csrfData = Session::getInstance()->read('__CSRF_TOKEN', []);
if (is_null($this->request->getHeader('CSRF_KEEP_ALIVE'))
&& is_null($this->request->getParameter('CSRF_KEEP_ALIVE'))) {
$csrfData[$formName] = '';
Session::getInstance()->set('__CSRF_TOKEN', $csrfData);
}
return hash_equals($sortedCsrf, $token);
}
return false;
} | php | {
"resource": ""
} |
q9289 | CsrfGuard.getStoredCsrfToken | train | private function getStoredCsrfToken(string $formName): ?string
{
$csrfData = Session::getInstance()->read('__CSRF_TOKEN');
if (is_null($csrfData)) {
return null;
}
return isset($csrfData[$formName]) ? $csrfData[$formName] : null;
} | php | {
"resource": ""
} |
q9290 | CsrfGuard.isHttpMethodFiltered | train | private function isHttpMethodFiltered($method): bool
{
$method = strtoupper($method);
if ($this->getSecured && $method == "GET") {
return true;
} elseif ($this->postSecured && $method == "POST") {
return true;
} elseif ($this->putSecured && $method == "PUT") {
return true;
} elseif ($this->deleteSecured && $method == "DELETE") {
return true;
}
return false;
} | php | {
"resource": ""
} |
q9291 | UtilityTwigExtension.calcAge | train | public function calcAge(DateTime $birthDate, DateTime $refDate = null) {
return DateTimeRenderer::renderAge($birthDate, $refDate);
} | php | {
"resource": ""
} |
q9292 | UtilityTwigExtension.formatString | train | public function formatString($string, $format) {
$fmt = str_replace("_", "%s", $format);
$str = str_split($string);
return vsprintf($fmt, $str);
} | php | {
"resource": ""
} |
q9293 | ModuleAdmin.getView | train | public function getView()
{
if (view()->exists($this->view)) {
return $this->view;
}
if (view()->exists('admin.'.$this->urlPrefix().'.index')) {
return 'admin.'.$this->urlPrefix().'.index';
}
if (view()->exists('admin.'.$this->urlPrefix())) {
return 'admin.'.$this->urlPrefix();
}
if (view()->exists('flare::'.$this->view)) {
return 'flare::'.$this->view;
}
return parent::getView();
} | php | {
"resource": ""
} |
q9294 | EntityResource.getStringId | train | public static function getStringId(ResourceEntityInterface $entity = NULL)
{
return is_null($entity)
? NULL
: (string) $entity->getId();
} | php | {
"resource": ""
} |
q9295 | ContainerAbstract.newInstance | train | public function newInstance(
string $createdByUserId,
string $createdReason = Tracking::UNKNOWN_REASON
) {
/** @var ContainerInterface|ContainerAbstract $new */
$new = parent::newInstance(
$createdByUserId,
$createdReason
);
$new->lastPublished = new \DateTime();
$new->revisions = new ArrayCollection();
if (!empty($new->publishedRevision)) {
$revision = $new->publishedRevision->newInstance(
$createdByUserId,
$createdReason
);
$new->removePublishedRevision();
$new->revisions->add($revision);
$new->setStagedRevision($revision);
} elseif (!empty($new->stagedRevision)) {
$revision = $new->stagedRevision->newInstance(
$createdByUserId,
$createdReason
);
$new->setStagedRevision($revision);
$new->revisions->add($revision);
}
return $new;
} | php | {
"resource": ""
} |
q9296 | ContainerAbstract.newInstanceIfHasRevision | train | public function newInstanceIfHasRevision(
string $createdByUserId,
string $createdReason = Tracking::UNKNOWN_REASON
) {
/** @var ContainerInterface|ContainerAbstract $new */
$new = parent::newInstance(
$createdByUserId,
$createdReason
);
$publishedRevision = $new->getPublishedRevision();
if (empty($publishedRevision)) {
return null;
}
$new->lastPublished = new \DateTime();
$new->revisions = new ArrayCollection();
$new->stagedRevision = null;
$new->stagedRevisionId = null;
$new->setPublishedRevision(
$publishedRevision->newInstance(
$createdByUserId,
$createdReason
)
);
return $new;
} | php | {
"resource": ""
} |
q9297 | ContainerAbstract.setPublishedRevision | train | public function setPublishedRevision(Revision $revision)
{
if (!empty($this->stagedRevision)) {
$this->removeStagedRevision();
}
$revision->publishRevision();
$this->publishedRevision = $revision;
$this->publishedRevisionId = $revision->getRevisionId();
$this->setLastPublished(new \DateTime());
} | php | {
"resource": ""
} |
q9298 | ContainerAbstract.setStagedRevision | train | public function setStagedRevision(Revision $revision)
{
if (!empty($this->publishedRevision)
&& $this->publishedRevision->getRevisionId() == $revision->getRevisionId()
) {
$this->removePublishedRevision();
}
$this->stagedRevision = $revision;
$this->stagedRevisionId = $revision->getRevisionId();
} | php | {
"resource": ""
} |
q9299 | ContainerAbstract.setSite | train | public function setSite(Site $site)
{
$this->site = $site;
$this->siteId = $site->getSiteId();
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.