_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q244400 | QtiRunnerService.storeVariables | validation | public function storeVariables(
QtiRunnerServiceContext $context,
$itemUri,
$metaVariables,
$itemId = null
) {
$sessionId = $context->getTestSession()->getSessionId();
/** @var DeliveryServerService $deliveryServerService */
$deliveryServerService = $this->getServiceManager()->get(DeliveryServerService::SERVICE_ID);
$resultStore = $deliveryServerService->getResultStoreWrapper($sessionId);
$testUri = $context->getTestDefinitionUri();
if (!is_null($itemUri)) {
$resultStore->storeItemVariables($testUri, $itemUri, $metaVariables, $this->getTransmissionId($context, $itemId));
} else {
$resultStore->storeTestVariables($testUri, $metaVariables, $sessionId);
}
return true;
} | php | {
"resource": ""
} |
q244401 | QtiRunnerService.storeVariable | validation | protected function storeVariable(
QtiRunnerServiceContext $context,
$itemUri,
\taoResultServer_models_classes_Variable $metaVariable,
$itemId = null
) {
$sessionId = $context->getTestSession()->getSessionId();
$testUri = $context->getTestDefinitionUri();
/** @var DeliveryServerService $deliveryServerService */
$deliveryServerService = $this->getServiceManager()->get(DeliveryServerService::SERVICE_ID);
$resultStore = $deliveryServerService->getResultStoreWrapper($sessionId);
if (!is_null($itemUri)) {
$resultStore->storeItemVariable($testUri, $itemUri, $metaVariable, $this->getTransmissionId($context, $itemId));
} else {
$resultStore->storeTestVariable($testUri, $metaVariable, $sessionId);
}
return true;
} | php | {
"resource": ""
} |
q244402 | QtiRunnerService.getTransmissionId | validation | protected function getTransmissionId(QtiRunnerServiceContext $context, $itemId = null)
{
if (is_null($itemId)) {
$itemId = $context->getCurrentAssessmentItemRef();
} elseif ($itemId != $context->getCurrentAssessmentItemRef()) {
throw new \common_exception_NotImplemented('Item variables can be stored only for the current item');
}
$sessionId = $context->getTestSession()->getSessionId();
$currentOccurrence = $context->getTestSession()->getCurrentAssessmentItemRefOccurence();
return $sessionId . '.' . $itemId . '.' . $currentOccurrence;
} | php | {
"resource": ""
} |
q244403 | QtiRunnerService.assertQtiRunnerServiceContext | validation | public function assertQtiRunnerServiceContext(RunnerServiceContext $context)
{
if (!$context instanceof QtiRunnerServiceContext) {
throw new \common_exception_InvalidArgumentType(
__CLASS__,
__FUNCTION__,
0,
QtiRunnerServiceContext::class,
$context
);
}
} | php | {
"resource": ""
} |
q244404 | QtiRunnerService.startTimer | validation | public function startTimer(RunnerServiceContext $context, $timestamp = null)
{
if ($context instanceof QtiRunnerServiceContext) {
/* @var TestSession $session */
$session = $context->getTestSession();
if($session->getState() === AssessmentTestSessionState::INTERACTING) {
$session->startItemTimer($timestamp);
}
} else {
throw new \common_exception_InvalidArgumentType(
'QtiRunnerService',
'startTimer',
0,
'oat\taoQtiTest\models\runner\QtiRunnerServiceContext',
$context
);
}
return true;
} | php | {
"resource": ""
} |
q244405 | QtiRunnerService.endTimer | validation | public function endTimer(RunnerServiceContext $context, $duration = null, $timestamp = null)
{
if ($context instanceof QtiRunnerServiceContext) {
/* @var TestSession $session */
$session = $context->getTestSession();
$session->endItemTimer($duration, $timestamp);
} else {
throw new \common_exception_InvalidArgumentType(
'QtiRunnerService',
'endTimer',
0,
'oat\taoQtiTest\models\runner\QtiRunnerServiceContext',
$context
);
}
return true;
} | php | {
"resource": ""
} |
q244406 | QtiRunnerService.switchClientStoreId | validation | public function switchClientStoreId(RunnerServiceContext $context, $receivedStoreId)
{
if ($context instanceof QtiRunnerServiceContext){
/* @var TestSession $session */
$session = $context->getTestSession();
$sessionId = $session->getSessionId();
$stateService = $this->getServiceManager()->get(ExtendedStateService::SERVICE_ID);
$lastStoreId = $stateService->getStoreId($sessionId);
if($lastStoreId == false || $lastStoreId != $receivedStoreId){
$stateService->setStoreId($sessionId, $receivedStoreId);
}
return $lastStoreId;
} else {
throw new \common_exception_InvalidArgumentType(
'QtiRunnerService',
'switchClientStoreId',
0,
'oat\taoQtiTest\models\runner\QtiRunnerServiceContext',
$context
);
}
} | php | {
"resource": ""
} |
q244407 | QtiRunnerService.getCurrentAssessmentSession | validation | public function getCurrentAssessmentSession(RunnerServiceContext $context)
{
if ($context->isAdaptive()) {
return new AssessmentItemSession($context->getCurrentAssessmentItemRef(), new SessionManager());
} else {
return $context->getTestSession();
}
} | php | {
"resource": ""
} |
q244408 | QtiRunnerService.isThemeSwitcherEnabled | validation | private function isThemeSwitcherEnabled()
{
/** @var \common_ext_ExtensionsManager $extensionsManager */
$extensionsManager = $this->getServiceLocator()->get(\common_ext_ExtensionsManager::SERVICE_ID);
$config = $extensionsManager->getExtensionById("taoTests")->getConfig("test_runner_plugin_registry");
return array_key_exists(self::TOOL_ITEM_THEME_SWITCHER_KEY, $config)
&& $config[self::TOOL_ITEM_THEME_SWITCHER_KEY]["active"] === true;
} | php | {
"resource": ""
} |
q244409 | QtiRunnerService.getCurrentThemeId | validation | private function getCurrentThemeId()
{
/** @var ThemeService $themeService */
$themeService = $this->getServiceLocator()->get(ThemeService::SERVICE_ID);
return $themeService->getTheme()->getId();
} | php | {
"resource": ""
} |
q244410 | QtiRunnerMap.getItemHrefIndexFile | validation | protected function getItemHrefIndexFile(QtiRunnerServiceContext $context, $itemIdentifier)
{
$compilationDirectory = $context->getCompilationDirectory()['private'];
return $compilationDirectory->getFile(\taoQtiTest_models_classes_QtiTestCompiler::buildHrefIndexPath($itemIdentifier));
} | php | {
"resource": ""
} |
q244411 | QtiRunnerMap.hasItemHrefIndexFile | validation | protected function hasItemHrefIndexFile(QtiRunnerServiceContext $context, $itemIdentifier)
{
// In case the context is adaptive, it means that the delivery was compiled in a version
// we are 100% sure it produced Item Href Index Files.
if ($context->isAdaptive()) {
return true;
} else {
$indexFile = $this->getItemHrefIndexFile($context, $itemIdentifier);
return $indexFile->exists();
}
} | php | {
"resource": ""
} |
q244412 | QtiRunnerMap.getMap | validation | public function getMap(RunnerServiceContext $context, RunnerConfig $config)
{
return $this->getScopedMap($context, $config, RunnerMap::SCOPE_TEST);
} | php | {
"resource": ""
} |
q244413 | QtiRunnerMap.updateStats | validation | protected function updateStats(&$target, $itemInfos)
{
if (!isset($target['stats'])) {
$target['stats'] = [
'questions' => 0,
'answered' => 0,
'flagged' => 0,
'viewed' => 0,
'total' => 0,
'questionsViewed' => 0,
];
}
if (empty($itemInfos['informational'])) {
$target['stats']['questions'] ++;
if (!empty($itemInfos['answered'])) {
$target['stats']['answered'] ++;
}
if (!empty($itemInfos['viewed'])) {
$target['stats']['questionsViewed'] ++;
}
}
if (!empty($itemInfos['flagged'])) {
$target['stats']['flagged'] ++;
}
if (!empty($itemInfos['viewed'])) {
$target['stats']['viewed'] ++;
}
$target['stats']['total'] ++;
} | php | {
"resource": ""
} |
q244414 | QtiRunnerMap.getRouteItemAssessmentItemRefs | validation | protected function getRouteItemAssessmentItemRefs(RunnerServiceContext $context, RouteItem $routeItem, &$catSession)
{
/* @var CatService */
$catService = $this->getServiceManager()->get(CatService::SERVICE_ID);
$compilationDirectory = $context->getCompilationDirectory()['private'];
$itemRefs = [];
$catSession = false;
if ($context->isAdaptive($routeItem->getAssessmentItemRef())) {
$catSession = $context->getCatSession($routeItem);
$itemRefs = $catService->getAssessmentItemRefByIdentifiers(
$compilationDirectory,
$context->getShadowTest($routeItem)
);
} else {
$itemRefs[] = $routeItem->getAssessmentItemRef();
}
return $itemRefs;
} | php | {
"resource": ""
} |
q244415 | QtiRunnerMap.getTimeConstraint | validation | private function getTimeConstraint(TestSession $session, QtiComponent $source, $navigationMode)
{
$constraint = new QtiTimeConstraint(
$source,
$session->getTimerDuration($source->getIdentifier()),
$navigationMode,
true,
true,
$session->getTimerTarget()
);
$constraint->setTimer($session->getTimer());
return $constraint;
} | php | {
"resource": ""
} |
q244416 | QtiRunnerMap.getItemLabel | validation | private function getItemLabel(RunnerServiceContext $context, $itemUri, $useTitle = false)
{
$label = '';
if ($useTitle) {
$label = $context->getItemIndexValue($itemUri, 'title');
}
if (!$label) {
$label = $context->getItemIndexValue($itemUri, 'label');
}
if (!$label) {
$item = new \core_kernel_classes_Resource($itemUri);
$label = $item->getLabel();
}
return $label;
} | php | {
"resource": ""
} |
q244417 | QtiRunnerNavigation.getNavigator | validation | public static function getNavigator($direction, $scope)
{
$className = __NAMESPACE__ . '\QtiRunnerNavigation' . ucfirst($direction) . ucfirst($scope);
if (class_exists($className)) {
$navigator = new $className();
if ($navigator instanceof RunnerNavigation) {
return $navigator;
} else {
throw new \common_exception_InconsistentData('Navigator must be an instance of RunnerNavigation');
}
} else {
throw new \common_exception_NotImplemented('The action is invalid!');
}
} | php | {
"resource": ""
} |
q244418 | QtiRunnerNavigation.checkTimedSectionExit | validation | public static function checkTimedSectionExit(RunnerServiceContext $context, $nextPosition)
{
$timerConfig = $context->getTestConfig()->getConfigValue('timer');
if (empty($timerConfig['keepUpToTimeout'])) {
/* @var AssessmentTestSession $session */
$session = $context->getTestSession();
$route = $session->getRoute();
$section = $session->getCurrentAssessmentSection();
$limits = $section->getTimeLimits();
// As we have only one identifier for the whole adaptive section it will consider a jump of section on the first item
if(!($context instanceof QtiRunnerServiceContext) || !$context->isAdaptive() ){
$isJumpOutOfSection = false;
if (($nextPosition >= 0) && ($nextPosition < $route->count())) {
$nextSection = $route->getRouteItemAt($nextPosition);
$isJumpOutOfSection = ($section->getIdentifier() !== $nextSection->getAssessmentSection()->getIdentifier());
}
if ($isJumpOutOfSection && $limits != null && $limits->hasMaxTime()) {
$assessmentItemRefs = $section->getComponentsByClassName('assessmentItemRef');
foreach ($assessmentItemRefs as $assessmentItemRef) {
$itemSessions = $session->getAssessmentItemSessions($assessmentItemRef->getIdentifier());
if($itemSessions !== false){
foreach ($itemSessions as $itemSession) {
$itemSession->endItemSession();
}
}
}
}
}
}
} | php | {
"resource": ""
} |
q244419 | CreatorItems.getItemClasses | validation | public function getItemClasses()
{
$itemClass = $this->getClass(self::ITEM_ROOT_CLASS_URI);
return $this->getResourceService()->getAllClasses($itemClass);
} | php | {
"resource": ""
} |
q244420 | CreatorItems.getQtiItems | validation | public function getQtiItems(\core_kernel_classes_Class $itemClass, $format = 'list', $search = '', $offset = 0, $limit = 30)
{
$propertyFilters = [];
if($this->hasOption(self::ITEM_MODEL_SEARCH_OPTION) && $this->getOption(self::ITEM_MODEL_SEARCH_OPTION) !== false){
$propertyFilters[self::PROPERTY_ITEM_MODEL_URI] = $this->getOption(self::ITEM_MODEL_SEARCH_OPTION);
}
if($this->hasOption(self::ITEM_CONTENT_SEARCH_OPTION) && $this->getOption(self::ITEM_MODEL_SEARCH_OPTION) !== false){
$propertyFilters[self::PROPERTY_ITEM_CONTENT_URI] = '*';
}
if(is_string($search) && strlen(trim($search)) > 0){
$propertyFilters[self::LABEL_URI] = $search;
}
if(is_array($search)){
foreach($search as $uri => $value){
if( is_string($uri) &&
(is_string($value) && strlen(trim($value)) > 0) ||
(is_array($value) && count($value) > 0) ) {
$propertyFilters[$uri] = $value;
}
}
}
$result = [];
//whitelisting's mandatory to prevent hijacking the dependency injection
if(in_array($format, self::$formats)){
//load the lookup dynamically using the format
$itemLookup = $this->getServiceLocator()->get(self::SERVICE_ID . '/' . $format);
if(!is_null($itemLookup) && $itemLookup instanceof ItemLookup){
$result = $itemLookup->getItems($itemClass, $propertyFilters, $offset, $limit);
}
}
return $result;
} | php | {
"resource": ""
} |
q244421 | CompilationService.useClientContainer | validation | public function useClientContainer()
{
if ($this->hasOption(self::OPTION_CLIENT_TESTRUNNER)) {
return $this->getOption(self::OPTION_CLIENT_TESTRUNNER);
} else {
// fallback to taoQtiItem config
$itemModel = $this->getServiceLocator()->get(ItemModel::SERVICE_ID);
return $itemModel->getCompilerClass() == QtiJsonItemCompiler::class;
}
} | php | {
"resource": ""
} |
q244422 | QtiTimeConstraint.getMaximumRemainingTime | validation | public function getMaximumRemainingTime()
{
if (($timeLimits = $this->getSource()->getTimeLimits()) !== null && ($maxTime = $timeLimits->getMaxTime()) !== null) {
return $this->getRemainingTimeFrom($maxTime);
}
return false;
} | php | {
"resource": ""
} |
q244423 | QtiTimeConstraint.getMinimumRemainingTime | validation | public function getMinimumRemainingTime()
{
if (($timeLimits = $this->getSource()->getTimeLimits()) !== null && ($minTime = $timeLimits->getMinTime()) !== null) {
return $this->getRemainingTimeFrom($minTime);
}
return false;
} | php | {
"resource": ""
} |
q244424 | QtiTimeConstraint.durationToMs | validation | private function durationToMs($duration)
{
if(!is_null($duration) && $duration instanceof QtiDuration){
return TestRunnerUtils::getDurationWithMicroseconds($duration);
}
return false;
} | php | {
"resource": ""
} |
q244425 | QtiTimeConstraint.jsonSerialize | validation | public function jsonSerialize()
{
$source = $this->getSource();
$timeLimits = $source->getTimeLimits();
if(!is_null($timeLimits)){
$identifier = $source->getIdentifier();
$maxTime = $timeLimits->getMaxTime();
$minTime = $timeLimits->getMinTime();
$maxTimeRemaining = $this->getMaximumRemainingTime();
$minTimeRemaining = $this->getMinimumRemainingTime();
if ($maxTimeRemaining !== false || $minTimeRemaining !== false) {
$label = method_exists($source, 'getTitle') ? $source->getTitle() : $identifier;
$extraTime = [];
if (!is_null($this->getTimer()) && $source->getTimeLimits()->hasMaxTime()) {
$timer = $this->getTimer();
$maxTimeSeconds = $source->getTimeLimits()->getMaxTime()->getSeconds(true);
$extraTime = [
'total' => $timer->getExtraTime($maxTimeSeconds),
'consumed' => $timer->getConsumedExtraTime($identifier, $maxTimeSeconds, $this->timerTarget),
'remaining' => $timer->getRemainingExtraTime($identifier, $maxTimeSeconds, $this->timerTarget),
];
}
/** @var TimerLabelFormatterService $labelFormatter */
$labelFormatter = ServiceManager::getServiceManager()->get(TimerLabelFormatterService::SERVICE_ID);
return [
'label' => $labelFormatter->format($label),
'source' => $identifier,
'qtiClassName' => $source->getQtiClassName(),
'extraTime' => $extraTime,
'allowLateSubmission' => $this->allowLateSubmission(),
'minTime' => $this->durationToMs($minTime),
'minTimeRemaining' => $this->durationToMs($minTimeRemaining),
'maxTime' => $this->durationToMs($maxTime),
'maxTimeRemaining' => $this->durationToMs($maxTimeRemaining),
];
}
}
return null;
} | php | {
"resource": ""
} |
q244426 | Skip.process | validation | public function process()
{
$this->validate();
$ref = $this->getRequestParameter('ref') ?: null;
$itemDuration = null;
$scope = $this->getRequestParameter('scope');
$start = $this->getRequestParameter('start') !== false;
try {
$serviceContext = $this->getServiceContext();
$this->saveToolStates();
$this->getRunnerService()->endTimer($serviceContext, $itemDuration, $this->getTime());
if ($this->getRequestParameter('offline') === true) {
$this->setOffline();
}
$result = $this->getRunnerService()->skip($serviceContext, $scope, $ref);
$response = [
'success' => $result,
];
if ($result) {
$response['testContext'] = $this->getRunnerService()->getTestContext($serviceContext);
if ($serviceContext->containsAdaptive()) {
// Force map update.
$response['testMap'] = $this->getRunnerService()->getTestMap($serviceContext, true);
}
}
if ($start == true) {
// start the timer only when move starts the item session
// and after context build to avoid timing error
$this->getRunnerService()->startTimer($serviceContext, $this->getTime());
}
} catch (Exception $e) {
$response = $this->getErrorResponse($e);
}
return $response;
} | php | {
"resource": ""
} |
q244427 | QtiTimer.start | validation | public function start($tags, $timestamp)
{
// check the provided arguments
if (!is_numeric($timestamp) || $timestamp < 0) {
throw new InvalidDataException('start() needs a valid timestamp!');
}
// extract the TimePoint identification from the provided item, and find existing range
$range = $this->getRange($tags);
// validate the data consistence
if ($this->isRangeOpen($range)) {
// unclosed range found, auto closing
// auto generate the timestamp for the missing END point, one microsecond earlier
\common_Logger::t('Missing END TimePoint in QtiTimer, auto add an arbitrary value');
$point = new TimePoint($tags, $timestamp - (1 / TimePoint::PRECISION), TimePoint::TYPE_END, TimePoint::TARGET_SERVER);
$this->timeLine->add($point);
$range[] = $point;
}
$this->checkTimestampCoherence($range, $timestamp);
// append the new START TimePoint
$point = new TimePoint($tags, $timestamp, TimePoint::TYPE_START, TimePoint::TARGET_SERVER);
$this->timeLine->add($point);
return $this;
} | php | {
"resource": ""
} |
q244428 | QtiTimer.end | validation | public function end($tags, $timestamp)
{
// check the provided arguments
if (!is_numeric($timestamp) || $timestamp < 0) {
throw new InvalidDataException('end() needs a valid timestamp!');
}
// extract the TimePoint identification from the provided item, and find existing range
$range = $this->getRange($tags);
// validate the data consistence
if ($this->isRangeOpen($range)) {
$this->checkTimestampCoherence($range, $timestamp);
// append the new END TimePoint
$point = new TimePoint($tags, $timestamp, TimePoint::TYPE_END, TimePoint::TARGET_SERVER);
$this->timeLine->add($point);
} else {
// already closed range found, just log the info
\common_Logger::t('Range already closed, or missing START TimePoint in QtiTimer, continue anyway');
}
return $this;
} | php | {
"resource": ""
} |
q244429 | QtiTimer.getFirstTimestamp | validation | public function getFirstTimestamp($tags)
{
// extract the TimePoint identification from the provided item, and find existing range
$range = $this->getRange($tags);
$last = false;
if (count($range)) {
$last = $range[0]->getTimestamp();
}
return $last;
} | php | {
"resource": ""
} |
q244430 | QtiTimer.getLastTimestamp | validation | public function getLastTimestamp($tags)
{
// extract the TimePoint identification from the provided item, and find existing range
$range = $this->getRange($tags);
$length = count($range);
$last = false;
if ($length) {
$last = $range[$length - 1]->getTimestamp();
}
return $last;
} | php | {
"resource": ""
} |
q244431 | QtiTimer.getLastRegisteredTimestamp | validation | public function getLastRegisteredTimestamp()
{
$points = $this->timeLine->getPoints();
$length = count($points);
$last = false;
if ($length) {
$last = end($points)->getTimestamp();
}
return $last;
} | php | {
"resource": ""
} |
q244432 | QtiTimer.timeout | validation | public function timeout($timeLimit, $tags, $target)
{
$duration = $this->compute($tags, $target);
return $duration >= $timeLimit;
} | php | {
"resource": ""
} |
q244433 | QtiTimer.save | validation | public function save()
{
if (!$this->storage) {
throw new InvalidStorageException('A storage must be defined in order to store the data!');
}
$this->storage->store($this->toArray());
return $this;
} | php | {
"resource": ""
} |
q244434 | QtiTimer.load | validation | public function load()
{
if (!$this->storage) {
throw new InvalidStorageException('A storage must be defined in order to store the data!');
}
$data = $this->storage->load();
if (isset($data)) {
if (!is_array($data)) {
$data = [
self::STORAGE_KEY_TIME_LINE => $data,
];
}
if (isset($data[self::STORAGE_KEY_TIME_LINE])) {
$this->timeLine = $this->unserializeTimeLine($data[self::STORAGE_KEY_TIME_LINE]);
} else {
$this->timeLine = new QtiTimeLine();
}
if (isset($data[self::STORAGE_KEY_EXTRA_TIME])) {
$this->extraTime = $data[self::STORAGE_KEY_EXTRA_TIME];
} else {
$this->extraTime = 0;
}
if (isset($data[self::STORAGE_KEY_EXTENDED_TIME])) {
$this->extendedTime = $data[self::STORAGE_KEY_EXTENDED_TIME];
} else {
$this->extendedTime = 0;
}
if (isset($data[self::STORAGE_KEY_CONSUMED_EXTRA_TIME])) {
$this->consumedExtraTime = $data[self::STORAGE_KEY_CONSUMED_EXTRA_TIME];
} else {
$this->consumedExtraTime = 0;
}
if (!$this->timeLine instanceof TimeLine) {
throw new InvalidDataException('The storage did not provide acceptable data when loading!');
}
}
return $this;
} | php | {
"resource": ""
} |
q244435 | QtiTimer.getExtraTime | validation | public function getExtraTime($maxTime = 0)
{
if ($maxTime && $this->getExtendedTime()) {
$secondsNew = $maxTime * $this->getExtendedTime();
$extraTime = $secondsNew - $maxTime;
$this->setExtraTime($extraTime);
return $extraTime;
}
return $this->extraTime;
} | php | {
"resource": ""
} |
q244436 | QtiTimer.setConsumedExtraTime | validation | public function setConsumedExtraTime($time)
{
$this->consumedExtraTime = max($this->consumedExtraTime, floatval($time));
return $this;
} | php | {
"resource": ""
} |
q244437 | QtiTimer.getConsumedExtraTime | validation | public function getConsumedExtraTime($tags = null, $maxTime = 0, $target = TimePoint::TARGET_SERVER)
{
if ($maxTime) {
$totalConsumed = $this->compute($tags, $target);
$consumedExtraTime = $totalConsumed - $maxTime < 0 ? 0 : $totalConsumed - $maxTime;
$this->setConsumedExtraTime($consumedExtraTime)->save();
}
return $this->consumedExtraTime;
} | php | {
"resource": ""
} |
q244438 | QtiTimer.getRemainingExtraTime | validation | public function getRemainingExtraTime($tags = null, $maxTime = 0, $target = TimePoint::TARGET_SERVER)
{
return max(0, $this->getExtraTime($maxTime) - $this->getConsumedExtraTime($tags, $maxTime, $target));
} | php | {
"resource": ""
} |
q244439 | QtiTimer.checkTimestampCoherence | validation | protected function checkTimestampCoherence($points, $timestamp)
{
foreach($points as $point) {
if ($point->getTimestamp() > $timestamp) {
throw new InconsistentRangeException('A new TimePoint cannot be set before an existing one!');
}
}
} | php | {
"resource": ""
} |
q244440 | QtiTimer.getRange | validation | protected function getRange($tags)
{
$range = $this->timeLine->find($tags, TimePoint::TARGET_SERVER);
TimePoint::sort($range);
return $range;
} | php | {
"resource": ""
} |
q244441 | QtiTimer.binaryPopCount | validation | protected function binaryPopCount($value)
{
$value -= (($value >> 1) & 0x55555555);
$value = ((($value >> 2) & 0x33333333) + ($value & 0x33333333));
$value = ((($value >> 4) + $value) & 0x0f0f0f0f);
$value += ($value >> 8);
$value += ($value >> 16);
return $value & 0x0000003f;
} | php | {
"resource": ""
} |
q244442 | ListItemLookup.getItems | validation | public function getItems(\core_kernel_classes_Class $itemClass, array $propertyFilters = [], $offset = 0, $limit = 30)
{
$result = $this->getListResourceLookupService()->getResources($itemClass, [], $propertyFilters, $offset, $limit);
array_map(function($item){
return array_merge($item, [
'categories' => $this->getCategoryService()->getItemCategories($this->getResource($item['uri']))
]);
}, $result['nodes']);
return $result;
} | php | {
"resource": ""
} |
q244443 | AdminBarRemovalSniff.process_css_style | validation | protected function process_css_style( $stackPtr ) {
if ( ! isset( $this->target_css_properties[ $this->tokens[ $stackPtr ]['content'] ] ) ) {
// Not one of the CSS properties we're interested in.
return;
}
$css_property = $this->target_css_properties[ $this->tokens[ $stackPtr ]['content'] ];
// Check if the CSS selector matches.
$opener = $this->phpcsFile->findPrevious( \T_OPEN_CURLY_BRACKET, $stackPtr );
if ( false !== $opener ) {
for ( $i = ( $opener - 1 ); $i >= 0; $i-- ) {
if ( isset( Tokens::$commentTokens[ $this->tokens[ $i ]['code'] ] )
|| \T_CLOSE_CURLY_BRACKET === $this->tokens[ $i ]['code']
) {
break;
}
}
$start = ( $i + 1 );
$selector = trim( $this->phpcsFile->getTokensAsString( $start, ( $opener - $start ) ) );
unset( $i );
foreach ( $this->target_css_selectors as $target_selector ) {
if ( false !== strpos( $selector, $target_selector ) ) {
$error = true;
if ( true === $this->remove_only ) {
// Check the value of the CSS property.
$valuePtr = $this->phpcsFile->findNext( array( \T_COLON, \T_WHITESPACE ), ( $stackPtr + 1 ), null, true );
$value = $this->tokens[ $valuePtr ]['content'];
$valid = $this->validate_css_property_value( $value, $css_property['type'], $css_property['value'] );
if ( true === $valid ) {
$error = false;
}
}
if ( true === $error ) {
$this->phpcsFile->addError( 'Hiding of the admin bar is not allowed.', $stackPtr, 'HidingDetected' );
}
}
}
}
} | php | {
"resource": ""
} |
q244444 | AdminBarRemovalSniff.validate_css_property_value | validation | protected function validate_css_property_value( $value, $compare_type, $compare_value ) {
switch ( $compare_type ) {
case '!=':
return $value !== $compare_value;
case '>':
return $value > $compare_value;
default:
return false;
}
} | php | {
"resource": ""
} |
q244445 | CorrectTGMPAVersionSniff.detect_manual_editing | validation | protected function detect_manual_editing( $version ) {
// Skip this check for TGMPA versions which didn't have the `tgmpa()` function or
// didn't have the `function_exists()` wrapper.
if ( false === $version || true === version_compare( $version, '2.2.0', '<' ) ) {
return;
}
$checkTokens = array(
// This is what we're looking for.
T_FUNCTION => true,
// These are just here to be able to skip as much as we can.
T_CLASS => true,
T_ARRAY => true,
T_OPEN_SHORT_ARRAY => true,
);
for ( $ptr = 0; $ptr < $this->phpcsFile->numTokens; $ptr++ ) {
if ( ! isset( $checkTokens[ $this->tokens[ $ptr ]['code'] ] ) ) {
continue;
}
// Skip as much as we can.
if ( T_CLASS === $this->tokens[ $ptr ]['code'] && isset( $this->tokens[ $ptr ]['scope_closer'] ) ) {
$ptr = $this->tokens[ $ptr ]['scope_closer'];
continue;
} elseif ( T_OPEN_SHORT_ARRAY === $this->tokens[ $ptr ]['code'] && isset( $this->tokens[ $ptr ]['bracket_closer'] ) ) {
$ptr = $this->tokens[ $ptr ]['bracket_closer'];
continue;
} elseif ( T_ARRAY === $this->tokens[ $ptr ]['code'] && isset( $this->tokens[ $ptr ]['parenthesis_closer'] ) ) {
$ptr = $this->tokens[ $ptr ]['parenthesis_closer'];
continue;
}
// Detect whether this is the `tgmpa()` function declaration.
if ( T_FUNCTION === $this->tokens[ $ptr ]['code'] ) {
$function_name = $this->phpcsFile->getDeclarationName( $ptr );
if ( 'tgmpa' !== $function_name ) {
if ( isset( $this->tokens[ $ptr ]['scope_closer'] ) ) {
// Skip the rest of the function.
$ptr = $this->tokens[ $ptr ]['scope_closer'];
}
continue;
}
// Ok, found the tgmpa function declaration. Now let's check for the typical
// manual text-domain replacement error.
$function_exists = $this->phpcsFile->findPrevious( T_STRING, ( $ptr - 1 ), null, false, 'function_exists' );
$param = false;
if ( false !== $function_exists ) {
$param = $this->get_function_call_parameter( $function_exists, 1 );
$param = $this->strip_quotes( $param['raw'] );
}
if ( false === $function_exists || 'tgmpa' !== $param ) {
$this->phpcsFile->recordMetric( 0, 'Manual editing detected', 'yes' );
$this->phpcsFile->addError(
'Manual editing of the TGM Plugin Activation file detected. Your edit will cause fatal errors for end-users. Download an official copy using the Custom TGMPA Generator. http://tgmpluginactivation.com/download/',
0,
'ManualEditDetected',
array(),
9
);
} else {
$this->phpcsFile->recordMetric( 0, 'Manual editing detected', 'no' );
}
break;
}
}
} | php | {
"resource": ""
} |
q244446 | CorrectTGMPAVersionSniff.get_docblock_tags | validation | protected function get_docblock_tags( $comment_opener ) {
$tags = array();
$opener = $this->tokens[ $comment_opener ];
if ( ! isset( $opener['comment_tags'] ) ) {
return $tags;
}
$closer = null;
if ( isset( $opener['comment_closer'] ) ) {
$closer = $opener['comment_closer'];
}
$tag_count = count( $opener['comment_tags'] );
for ( $i = 0; $i < $tag_count; $i++ ) {
$tag_token = $opener['comment_tags'][ $i ];
$tag = trim( $this->tokens[ $tag_token ]['content'], '@' );
$search_end = $closer;
if ( ( $i + 1 ) < $tag_count ) {
$search_end = $opener['comment_tags'][ ( $i + 1 ) ];
}
$value_token = $this->phpcsFile->findNext( T_DOC_COMMENT_STRING, ( $tag_token + 1 ), $search_end );
$tags[ $tag ] = trim( $this->tokens[ $value_token ]['content'] );
unset( $tag_token, $tag, $search_end, $value );
}
return $tags;
} | php | {
"resource": ""
} |
q244447 | CorrectTGMPAVersionSniff.parse_response_headers | validation | private function parse_response_headers( $headers ) {
$head = array();
foreach ( $headers as $key => $value ) {
$tag = explode( ':', $value, 2 );
if ( isset( $tag[1] ) ) {
$head[ trim( $tag[0] ) ] = trim( $tag[1] );
} else {
$head[] = $value;
if ( preg_match( '`HTTP/[0-9\.]+\s+([0-9]+)`', $value, $out ) ) {
$head['response_code'] = intval( $out[1] );
}
}
}
return $head;
} | php | {
"resource": ""
} |
q244448 | Base32.chunk | validation | private static function chunk($binaryString, $bits)
{
$binaryString = chunk_split($binaryString, $bits, ' ');
if (substr($binaryString, (strlen($binaryString)) - 1) == ' ') {
$binaryString = substr($binaryString, 0, strlen($binaryString)-1);
}
return explode(' ', $binaryString);
} | php | {
"resource": ""
} |
q244449 | Base32.encode | validation | public static function encode($string)
{
if (strlen($string) == 0) {
// Gives an empty string
return '';
}
// Convert string to binary
$binaryString = '';
foreach (str_split($string) as $s) {
// Return each character as an 8-bit binary string
$binaryString .= sprintf('%08b', ord($s));
}
// Break into 5-bit chunks, then break that into an array
$binaryArray = self::chunk($binaryString, 5);
// Pad array to be divisible by 8
while (count($binaryArray) % 8 !== 0) {
$binaryArray[] = null;
}
$base32String = '';
// Encode in base32
foreach ($binaryArray as $bin) {
$char = 32;
if (!is_null($bin)) {
// Pad the binary strings
$bin = str_pad($bin, 5, 0, STR_PAD_RIGHT);
$char = bindec($bin);
}
// Base32 character
$base32String .= self::$alphabet[$char];
}
return $base32String;
} | php | {
"resource": ""
} |
q244450 | OAuth1Upgrader.createOAuth2AccessToken | validation | function createOAuth2AccessToken($oauth1AccessToken)
{
OAuth1AccessToken::checkArg("oauth1AccessToken", $oauth1AccessToken);
$response = self::doPost($oauth1AccessToken, "1/oauth2/token_from_oauth1");
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
$parts = RequestUtil::parseResponseJson($response->body);
if (!array_key_exists('token_type', $parts) || !is_string($parts['token_type'])) {
throw new Exception_BadResponse("Missing \"token_type\" field.");
}
$tokenType = $parts['token_type'];
if (!array_key_exists('access_token', $parts) || !is_string($parts['access_token'])) {
throw new Exception_BadResponse("Missing \"access_token\" field.");
}
$accessToken = $parts['access_token'];
if ($tokenType !== "Bearer" && $tokenType !== "bearer") {
throw new Exception_BadResponse("Unknown \"token_type\"; expecting \"Bearer\", got "
. Util::q($tokenType));
}
return $accessToken;
} | php | {
"resource": ""
} |
q244451 | OAuth1Upgrader.disableOAuth1AccessToken | validation | function disableOAuth1AccessToken($oauth1AccessToken)
{
OAuth1AccessToken::checkArg("oauth1AccessToken", $oauth1AccessToken);
$response = self::doPost($oauth1AccessToken, "1/disable_access_token");
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
} | php | {
"resource": ""
} |
q244452 | OAuth1AccessToken.checkArg | validation | static function checkArg($argName, $argValue)
{
if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__);
} | php | {
"resource": ""
} |
q244453 | AppInfo.loadFromJsonFileWithRaw | validation | static function loadFromJsonFileWithRaw($path)
{
if (!file_exists($path)) {
throw new AppInfoLoadException("File doesn't exist: \"$path\"");
}
$str = Util::stripUtf8Bom(file_get_contents($path));
$jsonArr = json_decode($str, true, 10);
if (is_null($jsonArr)) {
throw new AppInfoLoadException("JSON parse error: \"$path\"");
}
$appInfo = self::loadFromJson($jsonArr);
return array($jsonArr, $appInfo);
} | php | {
"resource": ""
} |
q244454 | AppInfo.checkArgOrNull | validation | static function checkArgOrNull($argName, $argValue)
{
if ($argValue === null) return;
if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__);
} | php | {
"resource": ""
} |
q244455 | Client.disableAccessToken | validation | function disableAccessToken()
{
$response = $this->doPost($this->apiHost, "1/disable_access_token");
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
} | php | {
"resource": ""
} |
q244456 | Client.getAccountInfo | validation | function getAccountInfo()
{
$response = $this->doGet($this->apiHost, "1/account/info");
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
return RequestUtil::parseResponseJson($response->body);
} | php | {
"resource": ""
} |
q244457 | Client.chunkedUploadStart | validation | function chunkedUploadStart($data)
{
Checker::argString("data", $data);
$response = $this->_chunkedUpload(array(), $data);
if ($response->statusCode === 404) {
throw new Exception_BadResponse("Got a 404, but we didn't send up an 'upload_id'");
}
$correction = self::_chunkedUploadCheckForOffsetCorrection($response);
if ($correction !== null) throw new Exception_BadResponse(
"Got an offset-correcting 400 response, but we didn't send an offset");
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
list($uploadId, $byteOffset) = self::_chunkedUploadParse200Response($response->body);
$len = strlen($data);
if ($byteOffset !== $len) throw new Exception_BadResponse(
"We sent $len bytes, but server returned an offset of $byteOffset");
return $uploadId;
} | php | {
"resource": ""
} |
q244458 | Client.chunkedUploadContinue | validation | function chunkedUploadContinue($uploadId, $byteOffset, $data)
{
Checker::argStringNonEmpty("uploadId", $uploadId);
Checker::argNat("byteOffset", $byteOffset);
Checker::argString("data", $data);
$response = $this->_chunkedUpload(
array("upload_id" => $uploadId, "offset" => $byteOffset), $data);
if ($response->statusCode === 404) {
// The server doesn't know our upload ID. Maybe it expired?
return false;
}
$correction = self::_chunkedUploadCheckForOffsetCorrection($response);
if ($correction !== null) {
list($correctedUploadId, $correctedByteOffset) = $correction;
if ($correctedUploadId !== $uploadId) throw new Exception_BadResponse(
"Corrective 400 upload_id mismatch: us=".
Util::q($uploadId)." server=".Util::q($correctedUploadId));
if ($correctedByteOffset === $byteOffset) throw new Exception_BadResponse(
"Corrective 400 offset is the same as ours: $byteOffset");
return $correctedByteOffset;
}
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
list($retUploadId, $retByteOffset) = self::_chunkedUploadParse200Response($response->body);
$nextByteOffset = $byteOffset + strlen($data);
if ($uploadId !== $retUploadId) throw new Exception_BadResponse(
"upload_id mismatch: us=".Util::q($uploadId) .", server=".Util::q($uploadId));
if ($nextByteOffset !== $retByteOffset) throw new Exception_BadResponse(
"next-offset mismatch: us=$nextByteOffset, server=$retByteOffset");
return true;
} | php | {
"resource": ""
} |
q244459 | Client.chunkedUploadFinish | validation | function chunkedUploadFinish($uploadId, $path, $writeMode)
{
Checker::argStringNonEmpty("uploadId", $uploadId);
Path::checkArgNonRoot("path", $path);
WriteMode::checkArg("writeMode", $writeMode);
$params = array_merge(array("upload_id" => $uploadId), $writeMode->getExtraParams());
$response = $this->doPost(
$this->contentHost,
$this->appendFilePath("1/commit_chunked_upload", $path),
$params);
if ($response->statusCode === 404) return null;
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
return RequestUtil::parseResponseJson($response->body);
} | php | {
"resource": ""
} |
q244460 | Client.getDelta | validation | function getDelta($cursor = null, $pathPrefix = null)
{
Checker::argStringNonEmptyOrNull("cursor", $cursor);
Path::checkArgOrNull("pathPrefix", $pathPrefix);
$response = $this->doPost($this->apiHost, "1/delta", array(
"cursor" => $cursor,
"path_prefix" => $pathPrefix));
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
return RequestUtil::parseResponseJson($response->body);
} | php | {
"resource": ""
} |
q244461 | Client.restoreFile | validation | function restoreFile($path, $rev)
{
Path::checkArgNonRoot("path", $path);
Checker::argStringNonEmpty("rev", $rev);
$response = $this->doPost(
$this->apiHost,
$this->appendFilePath("1/restore", $path),
array("rev" => $rev));
if ($response->statusCode === 404) return null;
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
return RequestUtil::parseResponseJson($response->body);
} | php | {
"resource": ""
} |
q244462 | Client.searchFileNames | validation | function searchFileNames($basePath, $query, $limit = null, $includeDeleted = false)
{
Path::checkArg("basePath", $basePath);
Checker::argStringNonEmpty("query", $query);
Checker::argNatOrNull("limit", $limit);
Checker::argBool("includeDeleted", $includeDeleted);
$response = $this->doPost(
$this->apiHost,
$this->appendFilePath("1/search", $basePath),
array(
"query" => $query,
"file_limit" => $limit,
"include_deleted" => $includeDeleted,
));
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
return RequestUtil::parseResponseJson($response->body);
} | php | {
"resource": ""
} |
q244463 | Client.createShareableLink | validation | function createShareableLink($path)
{
Path::checkArg("path", $path);
$response = $this->doPost(
$this->apiHost,
$this->appendFilePath("1/shares", $path),
array(
"short_url" => "false",
));
if ($response->statusCode === 404) return null;
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
$j = RequestUtil::parseResponseJson($response->body);
return self::getField($j, "url");
} | php | {
"resource": ""
} |
q244464 | Client.createTemporaryDirectLink | validation | function createTemporaryDirectLink($path)
{
Path::checkArgNonRoot("path", $path);
$response = $this->doPost(
$this->apiHost,
$this->appendFilePath("1/media", $path));
if ($response->statusCode === 404) return null;
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
$j = RequestUtil::parseResponseJson($response->body);
$url = self::getField($j, "url");
$expires = self::parseDateTime(self::getField($j, "expires"));
return array($url, $expires);
} | php | {
"resource": ""
} |
q244465 | Client.getThumbnail | validation | function getThumbnail($path, $format, $size)
{
Path::checkArgNonRoot("path", $path);
Checker::argString("format", $format);
Checker::argString("size", $size);
if (!in_array($format, array("jpeg", "png"))) {
throw new \InvalidArgumentException("Invalid 'format': ".Util::q($format));
}
if (!in_array($size, array("xs", "s", "m", "l", "xl"))) {
throw new \InvalidArgumentException("Invalid 'size': ".Util::q($size));
}
$url = $this->buildUrlForGetOrPut(
$this->contentHost,
$this->appendFilePath("1/thumbnails", $path),
array("size" => $size, "format" => $format));
$curl = $this->mkCurl($url);
$metadataCatcher = new DropboxMetadataHeaderCatcher($curl->handle);
$curl->set(CURLOPT_RETURNTRANSFER, true);
$response = $curl->exec();
if ($response->statusCode === 404) return null;
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
$metadata = $metadataCatcher->getMetadata();
return array($metadata, $response->body);
} | php | {
"resource": ""
} |
q244466 | Client.createFolder | validation | function createFolder($path)
{
Path::checkArgNonRoot("path", $path);
$response = $this->doPost(
$this->apiHost,
"1/fileops/create_folder",
array(
"root" => "auto",
"path" => $path,
));
if ($response->statusCode === 403) return null;
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
return RequestUtil::parseResponseJson($response->body);
} | php | {
"resource": ""
} |
q244467 | Client.move | validation | function move($fromPath, $toPath)
{
Path::checkArgNonRoot("fromPath", $fromPath);
Path::checkArgNonRoot("toPath", $toPath);
$response = $this->doPost(
$this->apiHost,
"1/fileops/move",
array(
"root" => "auto",
"from_path" => $fromPath,
"to_path" => $toPath,
));
if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response);
return RequestUtil::parseResponseJson($response->body);
} | php | {
"resource": ""
} |
q244468 | Client.buildUrlForGetOrPut | validation | function buildUrlForGetOrPut($host, $path, $params = null)
{
return RequestUtil::buildUrlForGetOrPut($this->userLocale, $host, $path, $params);
} | php | {
"resource": ""
} |
q244469 | Client.doGet | validation | function doGet($host, $path, $params = null)
{
Checker::argString("host", $host);
Checker::argString("path", $path);
return RequestUtil::doGet($this->clientIdentifier, $this->accessToken, $this->userLocale,
$host, $path, $params);
} | php | {
"resource": ""
} |
q244470 | Util.q | validation | public static function q($string)
{
# HACK: "self::SPECIAL_ESCAPE_OUT[...]" is not valid syntax in PHP 5.3, so put
# it in a local variable first.
$special_escape_out = self::SPECIAL_ESCAPE_OUT;
$r = "\"";
$len = \strlen($string);
for ($i = 0; $i < $len; $i++) {
$c = $string[$i];
$escape_i = \strpos(self::SPECIAL_ESCAPE_IN, $c);
if ($escape_i !== false) {
// Characters with a special escape code.
$r .= "\\";
$r .= $special_escape_out[$escape_i];
}
else if ($c >= "\x20" and $c <= "\x7e") {
// Printable characters.
$r .= $c;
}
else {
// Generic hex escape code.
$r .= "\\x";
$r .= \bin2hex($c);
}
}
$r .= "\"";
return $r;
} | php | {
"resource": ""
} |
q244471 | Host.loadFromJson | validation | static function loadFromJson($jsonObj)
{
// Check for the optional 'auth_host' and 'host_suffix' fields.
$authHost = null;
if (array_key_exists('auth_host', $jsonObj)) {
$authHost = $jsonObj["auth_host"];
if (!is_string($authHost)) {
throw new HostLoadException("Optional field \"auth_host\" must be a string");
}
}
$hostSuffix = null;
if (array_key_exists('host_suffix', $jsonObj)) {
$hostSuffix = $jsonObj["host_suffix"];
if (!is_string($hostSuffix)) {
throw new HostLoadException("Optional field \"host_suffix\" must be a string");
}
}
if ($authHost === null && $hostSuffix === null) return null;
if ($authHost === null) {
throw new HostLoadException("Can't provide \"host_suffix\" without providing \"auth_host\".");
}
if ($hostSuffix === null) {
throw new HostLoadException("Can't provide \"auth_host\" without providing \"host_suffix\".");
}
$api = "api".$hostSuffix;
$content = "content".$hostSuffix;
$web = $authHost;
return new Host($api, $content, $web);
} | php | {
"resource": ""
} |
q244472 | AuthInfo.loadFromJsonFile | validation | static function loadFromJsonFile($path)
{
if (!file_exists($path)) {
throw new AuthInfoLoadException("File doesn't exist: \"$path\"");
}
$str = Util::stripUtf8Bom(file_get_contents($path));
$jsonArr = json_decode($str, true, 10);
if (is_null($jsonArr)) {
throw new AuthInfoLoadException("JSON parse error: \"$path\"");
}
return self::loadFromJson($jsonArr);
} | php | {
"resource": ""
} |
q244473 | Path.findError | validation | static function findError($path)
{
Checker::argStringNonEmpty("path", $path);
$matchResult = preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBD] # excluding overlongs, FFFE, and FFFF
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
)*$%xs', $path);
if ($matchResult !== 1) {
return "must be valid UTF-8; BMP only, no surrogates, no U+FFFE or U+FFFF";
}
if ($path[0] !== "/") return "must start with \"/\"";
$l = strlen($path);
if ($l === 1) return null; // Special case for "/"
if ($path[$l-1] === "/") return "must not end with \"/\"";
// TODO: More checks.
return null;
} | php | {
"resource": ""
} |
q244474 | RootCertificates.useExternalPaths | validation | static function useExternalPaths()
{
if (!self::$useExternalFile and self::$paths !== null) {
throw new \Exception("You called \"useExternalFile\" too late. The SDK already used the root ".
"certificate file (probably to make an API call).");
}
self::$useExternalFile = true;
} | php | {
"resource": ""
} |
q244475 | Security.stringEquals | validation | static function stringEquals($a, $b)
{
// Be strict with arguments. PHP's liberal types could get us pwned.
if (func_num_args() !== 2) {
throw new \InvalidArgumentException("Expecting 2 args, got ".func_num_args().".");
}
Checker::argString("a", $a);
Checker::argString("b", $b);
$len = strlen($a);
if (strlen($b) !== $len) return false;
$result = 0;
for ($i = 0; $i < $len; $i++) {
$result |= ord($a[$i]) ^ ord($b[$i]);
}
return $result === 0;
} | php | {
"resource": ""
} |
q244476 | ShopCalculationsTrait.getCountAttribute | validation | public function getCountAttribute()
{
if (empty($this->shopCalculations)) $this->runCalculations();
return round($this->shopCalculations->itemCount, 2);
} | php | {
"resource": ""
} |
q244477 | ShopCalculationsTrait.getTotalPriceAttribute | validation | public function getTotalPriceAttribute()
{
if (empty($this->shopCalculations)) $this->runCalculations();
return round($this->shopCalculations->totalPrice, 2);
} | php | {
"resource": ""
} |
q244478 | ShopCalculationsTrait.getTotalAttribute | validation | public function getTotalAttribute()
{
if (empty($this->shopCalculations)) $this->runCalculations();
return $this->totalPrice + $this->totalTax + $this->totalShipping;
} | php | {
"resource": ""
} |
q244479 | ShopCalculationsTrait.runCalculations | validation | private function runCalculations()
{
if (!empty($this->shopCalculations)) return $this->shopCalculations;
$cacheKey = $this->calculationsCacheKey;
if (Config::get('shop.cache_calculations')
&& Cache::has($cacheKey)
) {
$this->shopCalculations = Cache::get($cacheKey);
return $this->shopCalculations;
}
$this->shopCalculations = DB::table($this->table)
->select([
DB::raw('sum(' . Config::get('shop.item_table') . '.quantity) as itemCount'),
DB::raw('sum(' . Config::get('shop.item_table') . '.price * ' . Config::get('shop.item_table') . '.quantity) as totalPrice'),
DB::raw('sum(' . Config::get('shop.item_table') . '.tax * ' . Config::get('shop.item_table') . '.quantity) as totalTax'),
DB::raw('sum(' . Config::get('shop.item_table') . '.shipping * ' . Config::get('shop.item_table') . '.quantity) as totalShipping')
])
->join(
Config::get('shop.item_table'),
Config::get('shop.item_table') . '.' . ($this->table == Config::get('shop.order_table') ? 'order_id' : $this->table . '_id'),
'=',
$this->table . '.id'
)
->where($this->table . '.id', $this->attributes['id'])
->first();
if (Config::get('shop.cache_calculations')) {
Cache::put(
$cacheKey,
$this->shopCalculations,
Config::get('shop.cache_calculations_minutes')
);
}
return $this->shopCalculations;
} | php | {
"resource": ""
} |
q244480 | ShopCalculationsTrait.resetCalculations | validation | private function resetCalculations ()
{
$this->shopCalculations = null;
if (Config::get('shop.cache_calculations')) {
Cache::forget($this->calculationsCacheKey);
}
} | php | {
"resource": ""
} |
q244481 | PaymentGateway.setCallbacks | validation | public function setCallbacks($order)
{
$this->callbackSuccess = route(config('shop.callback_route'), [
'status' => 'success',
'id' => $order->id,
'token' => $this->token,
]);
$this->callbackFail = route(config('shop.callback_route'), [
'status' => 'fail',
'id' => $order->id,
'token' => $this->token,
]);
} | php | {
"resource": ""
} |
q244482 | MigrationCommand.createSeeder | validation | protected function createSeeder($data)
{
$seederFile = base_path('/database/seeds') . '/LaravelShopSeeder.php';
$output = $this->laravel->view->make('laravel-shop::generators.seeder')->with($data)->render();
if (!file_exists($seederFile) && $fs = fopen($seederFile, 'x')) {
fwrite($fs, $output);
fclose($fs);
return true;
}
return false;
} | php | {
"resource": ""
} |
q244483 | ShopItemTrait.getDisplayNameAttribute | validation | public function getDisplayNameAttribute()
{
if ($this->hasObject) return $this->object->displayName;
return isset($this->itemName)
? $this->attributes[$this->itemName]
: (array_key_exists('name', $this->attributes)
? $this->attributes['name']
: ''
);
} | php | {
"resource": ""
} |
q244484 | ShopItemTrait.getShopUrlAttribute | validation | public function getShopUrlAttribute()
{
if ($this->hasObject) return $this->object->shopUrl;
if (!property_exists($this, 'itemRouteName') && !property_exists($this, 'itemRouteParams')) return '#';
$params = [];
foreach (array_keys($this->attributes) as $attribute) {
if (in_array($attribute, $this->itemRouteParams)) $params[$attribute] = $this->attributes[$attribute];
}
return empty($this->itemRouteName) ? '#' : \route($this->itemRouteName, $params);
} | php | {
"resource": ""
} |
q244485 | ShopItemTrait.getWasPurchasedAttribute | validation | public function getWasPurchasedAttribute()
{
if (Auth::guest()) return false;
return Auth::user()
->orders()
->whereSKU($this->attributes['sku'])
->whereStatusIn(config('shop.order_status_purchase'))
->count() > 0;
} | php | {
"resource": ""
} |
q244486 | GatewayCallback.onCharge | validation | public function onCharge($order)
{
$this->statusCode = 'pending';
$this->detail = 'pending response, token:' . $this->token;
return parent::onCharge($order);
} | php | {
"resource": ""
} |
q244487 | GatewayCallback.onCallbackFail | validation | public function onCallbackFail($order, $data = null)
{
$this->statusCode = 'failed';
$this->detail = 'failed callback';
$this->didCallback = true;
} | php | {
"resource": ""
} |
q244488 | ShopCartTrait.add | validation | public function add($item, $quantity = 1, $quantityReset = false)
{
if (!is_array($item) && !$item->isShoppable) return;
// Get item
$cartItem = $this->getItem(is_array($item) ? $item['sku'] : $item->sku);
// Add new or sum quantity
if (empty($cartItem)) {
$reflection = null;
if (is_object($item)) {
$reflection = new \ReflectionClass($item);
}
$cartItem = call_user_func( Config::get('shop.item') . '::create', [
'user_id' => $this->user->shopId,
'cart_id' => $this->attributes['id'],
'sku' => is_array($item) ? $item['sku'] : $item->sku,
'price' => is_array($item) ? $item['price'] : $item->price,
'tax' => is_array($item)
? (array_key_exists('tax', $item)
? $item['tax']
: 0
)
: (isset($item->tax) && !empty($item->tax)
? $item->tax
: 0
),
'shipping' => is_array($item)
? (array_key_exists('shipping', $item)
? $item['shipping']
: 0
)
: (isset($item->shipping) && !empty($item->shipping)
? $item->shipping
: 0
),
'currency' => Config::get('shop.currency'),
'quantity' => $quantity,
'class' => is_array($item) ? null : $reflection->getName(),
'reference_id' => is_array($item) ? null : $item->shopId,
]);
} else {
$cartItem->quantity = $quantityReset
? $quantity
: $cartItem->quantity + $quantity;
$cartItem->save();
}
$this->resetCalculations();
return $this;
} | php | {
"resource": ""
} |
q244489 | ShopCartTrait.remove | validation | public function remove($item, $quantity = 0)
{
// Get item
$cartItem = $this->getItem(is_array($item) ? $item['sku'] : $item->sku);
// Remove or decrease quantity
if (!empty($cartItem)) {
if (!empty($quantity)) {
$cartItem->quantity -= $quantity;
$cartItem->save();
if ($cartItem->quantity > 0) return true;
}
$cartItem->delete();
}
$this->resetCalculations();
return $this;
} | php | {
"resource": ""
} |
q244490 | ShopCartTrait.hasItem | validation | public function hasItem($sku, $requireAll = false)
{
if (is_array($sku)) {
foreach ($sku as $skuSingle) {
$hasItem = $this->hasItem($skuSingle);
if ($hasItem && !$requireAll) {
return true;
} elseif (!$hasItem && $requireAll) {
return false;
}
}
// If we've made it this far and $requireAll is FALSE, then NONE of the roles were found
// If we've made it this far and $requireAll is TRUE, then ALL of the roles were found.
// Return the value of $requireAll;
return $requireAll;
} else {
foreach ($this->items as $item) {
if ($item->sku == $sku) {
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q244491 | ShopCartTrait.scopeWhereCurrent | validation | public function scopeWhereCurrent($query)
{
if (Auth::guest()) return $query;
return $query->whereUser(Auth::user()->shopId);
} | php | {
"resource": ""
} |
q244492 | ShopCartTrait.scopeFindByUser | validation | public function scopeFindByUser($query, $userId)
{
if (empty($userId)) return;
$cart = $query->whereUser($userId)->first();
if (empty($cart)) {
$cart = call_user_func( Config::get('shop.cart') . '::create', [
'user_id' => $userId
]);
}
return $cart;
} | php | {
"resource": ""
} |
q244493 | ShopCartTrait.placeOrder | validation | public function placeOrder($statusCode = null)
{
if (empty($statusCode)) $statusCode = Config::get('shop.order_status_placement');
// Create order
$order = call_user_func( Config::get('shop.order') . '::create', [
'user_id' => $this->user_id,
'statusCode' => $statusCode
]);
// Map cart items into order
for ($i = count($this->items) - 1; $i >= 0; --$i) {
// Attach to order
$this->items[$i]->order_id = $order->id;
// Remove from cart
$this->items[$i]->cart_id = null;
// Update
$this->items[$i]->save();
}
$this->resetCalculations();
return $order;
} | php | {
"resource": ""
} |
q244494 | ShopCartTrait.clear | validation | public function clear()
{
DB::table(Config::get('shop.item_table'))
->where('cart_id', $this->attributes['id'])
->delete();
$this->resetCalculations();
return $this;
} | php | {
"resource": ""
} |
q244495 | ShopCartTrait.getItem | validation | private function getItem($sku)
{
$className = Config::get('shop.item');
$item = new $className();
return $item->where('sku', $sku)
->where('cart_id', $this->attributes['id'])
->first();
} | php | {
"resource": ""
} |
q244496 | ShopTransactionTrait.scopeWhereUser | validation | public function scopeWhereUser($query, $userId)
{
return $query->join(
Config::get('shop.order_table'),
Config::get('shop.order_table') . '.id',
'=',
Config::get('shop.transaction_table') . '.order_id'
)
->where(Config::get('shop.order_table') . '.user_id', $userId);
} | php | {
"resource": ""
} |
q244497 | LaravelShopProvider.map | validation | public function map(Router $router)
{
$router->group(['namespace' => 'Amsgames\LaravelShop\Http\Controllers'], function($router) {
$router->group(['prefix' => 'shop'], function ($router) {
$router->get('callback/payment/{status}/{id}/{shoptoken}', ['as' => 'shop.callback', 'uses' => 'Shop\CallbackController@process']);
$router->post('callback/payment/{status}/{id}/{shoptoken}', ['as' => 'shop.callback', 'uses' => 'Shop\CallbackController@process']);
});
});
} | php | {
"resource": ""
} |
q244498 | ShopOrderTrait.scopeWhereSKU | validation | public function scopeWhereSKU($query, $sku) {
return $query->join(
config('shop.item_table'),
config('shop.item_table') . '.order_id',
'=',
$this->table . '.id'
)
->where(config('shop.item_table') . '.sku', $sku);
} | php | {
"resource": ""
} |
q244499 | ShopOrderTrait.scopeFindByUser | validation | public function scopeFindByUser($query, $userId, $statusCode = null) {
if (!empty($status)) {
$query = $query->whereStatus($status);
}
return $query->whereUser($userId)->get();
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.