_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q263900
I18nTranslationController.findModel
test
protected function findModel($message_id, $language) { if (($model = I18nTranslation::findOne(['message_id' => $message_id, 'language' => $language])) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
php
{ "resource": "" }
q263901
NoshiCommandController.listPagesCommand
test
public function listPagesCommand() { $pageRepository = new PageRepository(); $pages = $pageRepository->findAll(); $tableData = []; /** @var Page $page */ foreach ($pages as $page) { $tableData[] = [ 'identifier' => $page->getIdentifier(), 'title' => $page->getTitle(), 'is directory' => $page->getIsDirectory(), 'is virtual' => $page->getIsVirtual(), 'sorting' => $page->getSorting(), ]; } $this->outputTable($tableData); }
php
{ "resource": "" }
q263902
Page.getContent
test
public function getContent() { if (!$this->parsedContent) { $this->parsedContent = MarkdownFactory::getMarkdownRenderer()->transform($this->getRawContent()); } return $this->parsedContent; }
php
{ "resource": "" }
q263903
Page.getSorting
test
public function getSorting() { if (!$this->sorting) { $sorting = ObjectUtility::valueForKeyPathOfObject('meta.sorting', $this); if (!$sorting) { $sorting = self::DEFAULT_SORTING; } $this->sorting = $sorting; } return $this->sorting; }
php
{ "resource": "" }
q263904
Page.getUri
test
public function getUri() { if (!$this->uri) { if (($url = $this->_getUrlFromMeta())) { $this->uri = $url; } else { if ($this->getIsVirtual()) { $this->uri = '#'; } else { $uriParts = explode(DIRECTORY_SEPARATOR, $this->getIdentifier()); array_walk( $uriParts, function (&$uriPart) { $uriPart = urlencode($uriPart); } ); $this->uri = DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $uriParts) . DIRECTORY_SEPARATOR; } } } return $this->uri; }
php
{ "resource": "" }
q263905
Page._getUrlFromMeta
test
protected function _getUrlFromMeta() { $url = ObjectUtility::valueForKeyPathOfObject('meta.url', $this); if (!$url) { return null; } if (substr($url, 0, 11) === '/Resources/') { return $url; } if (substr($url, 0, 10) === 'Resources/') { return $url; } if (strpos($url, '://') === false) { $url = 'http://' . $url; } return $url; }
php
{ "resource": "" }
q263906
Page.getTitle
test
public function getTitle() { $title = ObjectUtility::valueForKeyPathOfObject('meta.title', $this); if (!$title) { $title = $this->getIdentifier(); $slashPosition = strpos($title, DIRECTORY_SEPARATOR); if ($slashPosition !== false) { $title = substr($title, $slashPosition + 1); } $title = str_replace(self::URI_WHITESPACE_REPLACE, ' ', $title); } return $title; }
php
{ "resource": "" }
q263907
Client.get
test
public function get($apiMethod, $parameters = []) { $requestUrl = $this->buildUrl($apiMethod, $parameters); $requestUrl = urldecode($requestUrl); $response = $this->getHttpClient()->get($requestUrl); return $this->handleResponse($response); }
php
{ "resource": "" }
q263908
Client.buildUrl
test
private function buildUrl($apiMethod, $parameters) { switch ($this->getApiType()) { case 'Brand': $url = sprintf($this->apiUrlBrand, $this->getNetworkId(), $this->getApiNamespace(), $apiMethod, $this->getApiKey()); break; case 'Affiliate': $url = sprintf($this->apiUrlAffiliate, $this->getNetworkId(), $this->getApiType(), $this->getApiNamespace(), $apiMethod, $this->getApiKey()); break; } return $url.'&'.http_build_query($parameters); }
php
{ "resource": "" }
q263909
Client.handleResponse
test
private function handleResponse($response) { $statusCode = $response->getStatusCode(); $body = json_decode($response->getBody()); if ($statusCode >= 200 && $statusCode < 300) { return $body; } throw new \Exception($response->getBody(), $statusCode); }
php
{ "resource": "" }
q263910
ConfigurationManager.initializeConfiguration
test
static public function initializeConfiguration($basePath) { // Read the configurations file $configuration = []; $configurationFile = $basePath . 'Configurations/Configuration.json'; if (file_exists($configurationFile) && is_readable($configurationFile)) { $configuration = json_decode(file_get_contents($configurationFile), true); } self::$sharedConfiguration = new Configuration($configuration); self::$sharedConfiguration->set('basePath', $basePath); return self::$sharedConfiguration; }
php
{ "resource": "" }
q263911
Profiler.profile
test
static public function profile($message = null) { static $fileHandle = null; // Make sure the start time is defined if (!static::$startTime) { static::$startTime = microtime(true); } // Make sure the file handle exists if (!$fileHandle) { $fileHandle = fopen(static::$streamUri, 'w'); } $output = sprintf('Profiler: %.4f', microtime(true) - static::$startTime); if ($message) { $output .= ' - ' . $message; } $output .= PHP_EOL; fwrite($fileHandle, $output); }
php
{ "resource": "" }
q263912
View.getTemplate
test
public function getTemplate() { if (file_exists($this->templatePath)) { return file_get_contents($this->templatePath); } return '<!-- Template file ' . $this->templatePath . ' not found -->' . PHP_EOL . '{content}'; }
php
{ "resource": "" }
q263913
ObjectUtility.valueForKeyPathOfObject
test
static public function valueForKeyPathOfObject($keyPath, $object, $default = null) { $i = 0; $keyPathParts = explode('.', $keyPath); $keyPathPartsLength = count($keyPathParts); $currentValue = $object; if (!is_string($keyPath)) { throw new \LogicException( 'Given key path is not of type string (maybe arguments are ordered incorrect)', 1395484136 ); } for ($i = 0; $i < $keyPathPartsLength; $i++) { $key = $keyPathParts[$i]; $accessorMethod = 'get' . ucfirst($key); switch (true) { // Current value is an array case is_array($currentValue) && isset($currentValue[$key]): $currentValue = $currentValue[$key]; break; // Current value is an object case is_object($currentValue): if (method_exists($currentValue, $accessorMethod)) { // Getter method $currentValue = $currentValue->$accessorMethod(); } else { if (method_exists($currentValue, 'get')) { // General "get" method $currentValue = $currentValue->get($key); } else { if (in_array($key, get_object_vars($currentValue))) { // Direct access $currentValue = $currentValue->$key; } else { $currentValue = null; } } } break; default: $currentValue = null; } if ($currentValue === null) { break; } } if ($i !== $keyPathPartsLength && func_num_args() > 2) { if (is_object($default) && ($default instanceof \Closure)) { $currentValue = $default(); } else { $currentValue = $default; } } return $currentValue; }
php
{ "resource": "" }
q263914
ClassFinder.setRootDirectory
test
public function setRootDirectory($directory) { if (!is_dir($directory)) { throw new \DomainException(sprintf( 'The value "%s" defined as the root directory does not exist.', $directory )); } $this->directory = $directory; return $this; }
php
{ "resource": "" }
q263915
ClassFinder.findClassReflections
test
public function findClassReflections($subDir = null, $suffix = null, $parent = null, $allowedParameters = 0) { $classes = []; $subDir = trim(preg_replace('#//{2,}#', '/', strtr($subDir, '\\', '/')), '/'); $namespace = trim($this->namespace, '\\') . '\\' . strtr($subDir, '/', '\\') . '\\'; $finder = $this->directory !== null && is_dir($directory = $this->directory . DIRECTORY_SEPARATOR . strtr($subDir, '/', DIRECTORY_SEPARATOR)) ? (new Finder)->files()->name(sprintf('*%s', $this->extension))->in($directory) : []; foreach ($finder as $file) { try { $class = $this->getClassReflection($file, $namespace, $suffix, $parent, $allowedParameters); $classes[] = $class; } catch (\Exception $exception) { continue; } } return $classes; }
php
{ "resource": "" }
q263916
ClassFinder.getClassReflection
test
protected function getClassReflection(SplFileInfo $file, $namespace, $suffix, $parent, $allowedParameters) { // Determine the fully-qualified class name of the found file. $class = preg_replace('#\\\\{2,}#', '\\', sprintf( '%s\\%s\\%s', $namespace, strtr($file->getRelativePath(), '/', '\\'), $file->getBasename($this->extension) )); // Make sure that the class name has the correct suffix. if (!empty($suffix) && substr($class, 0 - strlen($suffix)) !== $suffix) { throw new \LogicException(sprintf( 'The file found at "%s" does not end with the required suffix of "%s".', $file->getRealPath(), $suffix )); } // We have to perform a few checks on the class before we can return it. // - It must be an actual class; not interface, abstract or trait types. // - For this to work the constructor must not have more than the expected number of required parameters. // - And finally make sure that the class loaded was actually loaded from the directory we found it in. // TODO: Make sure that the final (file path) check doesn't cause problems with proxy classes or // bootstraped/compiled class caches. $reflect = new ReflectionClass($class, $file->getRelativePath()); if ((is_object($construct = $reflect->getConstructor()) && $construct->getNumberOfRequiredParameters() > $allowedParameters ) || $reflect->isAbstract() || $reflect->isInterface() || $reflect->isTrait() || (is_string($parent) && !empty($parent) && !$reflect->isSubclassOf($parent)) || $reflect->getFileName() !== $file->getRealPath() ) { throw new \LogicException(sprintf('The class definition for "%s" is invalid.', $class)); } return $reflect; }
php
{ "resource": "" }
q263917
Media.mediaUpload
test
public function mediaUpload($fileName = 'file', $useFile = false) { $file = UploadedFile::getInstanceByName($fileName); if ($useFile !== false) { $file = $file[0]; } if (is_null($file)) { throw new BadRequestHttpException('No file specified to upload.'); } return $this->insertMedia($file); }
php
{ "resource": "" }
q263918
Media.insertMedia
test
private function insertMedia($file) { /** * @var \yii\web\UploadedFile $file */ $result = ['success' => false, 'message' => 'File could not be saved.']; if ($file->size > Yii::$app->params['maxUploadSize']) { $result['message'] = 'Max upload size limit reached'; } $uploadTime = date("Y-m-W"); $media = new MediaModel(); $media->filename = KatoBase::sanitizeFile($file->baseName) . '-' . KatoBase::genRandomString(4) . '.' . $file->extension; $media->mimeType = $file->type; $media->byteSize = $file->size; $media->extension = $file->extension; $media->source = basename(\Yii::$app->params['uploadPath']) . '/' . $uploadTime . '/' . $media->filename; if (!is_file($media->source)) { //If saved upload the file $uploadPath = \Yii::$app->params['uploadPath'] . $uploadTime; if (!is_dir($uploadPath)) mkdir($uploadPath, 0777, true); if ($file->saveAs($uploadPath . '/' . $media->filename)) { //Save to media table if ($media->save(false)) { $result['success'] = true; $result['message'] = 'Upload Success'; $result['data'] = $media; } else { $result['message'] = "Database record could not be saved."; } } else { $result['message'] = "File could not be saved."; } } else { $result['message'] = "File already exists."; } return $result; }
php
{ "resource": "" }
q263919
ExampleCalculator.hours
test
public function hours($downTo=15, $decimalPlaces=2) { if (! $this->has(['start','end'])) return 0; $diff = $this->start->diffInMinutes($this->end); $minutes = $diff - ($downTo / 2); $hours = $minutes / 60; $periodsPerHour = 60 / $downTo; $roundedHours = round( round($hours * $periodsPerHour) / $periodsPerHour, $decimalPlaces ); $whole = floor($roundedHours); $fraction = round($roundedHours - $whole,2); $periodLength = round(1.0 / $periodsPerHour,2); if ($fraction == $periodLength && $diff % $downTo === 0) return ($roundedHours - $periodLength); return $roundedHours; }
php
{ "resource": "" }
q263920
UnitOfWork.getDirtyData
test
public function getDirtyData( array $newSerializedModel, array $oldSerializedModel, ClassMetadata $classMetadata ): array { return $this->getDirtyFields( $newSerializedModel, $oldSerializedModel, $classMetadata ); }
php
{ "resource": "" }
q263921
UnitOfWork.registerClean
test
public function registerClean(string $id, object $entity): self { $entityStored = clone $entity; $this->storage[$id] = $entityStored; return $this; }
php
{ "resource": "" }
q263922
UnitOfWork.getDirtyFields
test
private function getDirtyFields( array $newSerializedModel, array $oldSerializedModel, ClassMetadata $classMetadata ): array { $dirtyFields = []; foreach ($newSerializedModel as $key => $value) { if (!array_key_exists($key, $oldSerializedModel)) { // a new key has been found, add it to the dirtyFields $dirtyFields[$key] = $value; continue; } $oldValue = $oldSerializedModel[$key]; $currentRelation = $classMetadata->getRelation($key); if (!$currentRelation) { if ( is_array($value) && !ArrayHelper::arraySame($value, $oldValue ?: []) || $value !== $oldValue ) { $dirtyFields[$key] = $value; } continue; } $currentClassMetadata = $this->mapping->getClassMetadata( $currentRelation->getTargetEntity() ); $idSerializedKey = $currentClassMetadata->getIdSerializeKey(); if (Relation::MANY_TO_ONE === $currentRelation->getType()) { if ($value !== $oldValue) { if (is_string($value) || is_string($oldValue)) { $dirtyFields[$key] = $value; } else { $recursiveDiff = $this->getDirtyFields( $value, $oldValue, $currentClassMetadata ); if (!empty($recursiveDiff)) { $recursiveDiff[ $idSerializedKey ] = self::getEntityId($value, $idSerializedKey); $dirtyFields[$key] = $recursiveDiff; } } } continue; } // ONE_TO_MANY relation if (count($value ?? []) !== count($oldValue ?? [])) { // get all objects ids of new array $dirtyFields[$key] = $this->addIdentifiers( $value, [], $idSerializedKey ); } if (!empty($value)) { foreach ($value as $relationKey => $relationValue) { $oldRelationValue = $this->findOldRelation( $relationValue, $oldValue, $currentClassMetadata ); if ($relationValue !== $oldRelationValue) { if ( is_string($relationValue) || is_string($oldRelationValue) ) { $dirtyFields[$key][$relationKey] = $relationValue; } else { $recursiveDiff = $this->getDirtyFields( $relationValue, $oldRelationValue, $currentClassMetadata ); if (!empty($recursiveDiff)) { $idSerializedKey = $currentClassMetadata->getIdSerializeKey(); $entityId = self::getEntityId( $relationValue, $idSerializedKey ); if (null !== $entityId) { $recursiveDiff[ $idSerializedKey ] = $entityId; } $dirtyFields[$key][ $relationKey ] = $recursiveDiff; } } } } } } return $dirtyFields; }
php
{ "resource": "" }
q263923
UnitOfWork.addIdentifiers
test
private function addIdentifiers( $newSerializedModel, array $dirtyFields, $idSerializedKey = null ): array { foreach ($newSerializedModel as $key => $value) { if ($idSerializedKey && isset($value[$idSerializedKey])) { $dirtyFields[$key][$idSerializedKey] = $value[$idSerializedKey]; } elseif (is_string($value) && is_int($key)) { $dirtyFields[$key] = $value; } } return $dirtyFields; }
php
{ "resource": "" }
q263924
UnitOfWork.getEntityId
test
private static function getEntityId( $stringOrEntity, string $idSerializedKey ) { if (!is_array($stringOrEntity)) { return $stringOrEntity; } return $stringOrEntity[$idSerializedKey] ?? null; }
php
{ "resource": "" }
q263925
Tags.getTags
test
private function getTags() { $allTags = $this->getAllTags()->all(); $tags = ''; $total=0; foreach ($allTags as $tag) { $total += $tag->frequency; } foreach($allTags as $tag) { $weight = 8 + (int)(16*$tag->frequency/($total+10)); $this->options['style'] = "font-size:{$weight}pt"; if (isset($_GET[$this->get_real_class($this->model)]['tags']) && $_GET[$this->get_real_class($this->model)]['tags'] === $tag->name) { $this->options['class'] = 'tag active'; } else { $this->options['class'] = 'tag'; } $tags .= Html::tag('li', Html::a($tag->name, ['/blog/index', $this->get_real_class($this->model) . '[tags]' => $tag->name]), $this->options); } $tags .= Html::tag('li', '', ['class' => 'clearfix']); return $tags; }
php
{ "resource": "" }
q263926
Tags.get_real_class
test
private function get_real_class($obj) { $classname = get_class($obj); if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) { $classname = $matches[1]; } return $classname; }
php
{ "resource": "" }
q263927
ContaoBootstrapTabExtension.configureTabElementFactory
test
private function configureTabElementFactory(ContainerBuilder $container): void { $definition = $container->findDefinition(TabElementFactory::class); if (!$definition) { return; } $bundles = $container->getParameter('kernel.bundles'); if (!isset($bundles['ContaoBootstrapGridBundle'])) { return; } $definition->setArgument(5, new Reference('contao_bootstrap.grid.grid_provider')); }
php
{ "resource": "" }
q263928
Media.beforeDelete
test
public function beforeDelete() { if (parent::beforeDelete()) { //Remove file from system if (file_exists($this->baseSource)) { unlink($this->baseSource); } //Delete from relation table if ($contentMedia = ContentMedia::find()->where(['media_id' => $this->id])->all()) { foreach ($contentMedia as $data) { $data->delete(); } } return true; } return false; }
php
{ "resource": "" }
q263929
Media.createTitle
test
private function createTitle() { $title_parts = pathinfo($this->filename); $this->title = $title_parts['filename']; $this->title = \kato\helpers\KatoBase::sanitizeFile($this->title); $this->title = str_replace('_', ' ', str_replace('-', ' ', $this->title)); $this->title = ucwords($this->title); }
php
{ "resource": "" }
q263930
Media.renderPdf
test
public function renderPdf($data = []) { if (isset($data['imgTag'])) { $pdfPreview = Yii::$app->request->baseUrl . '/theme-assets/img/pdf-preview.jpg'; $options = []; if (isset($data['width'])) $options['width'] = $data['width']; if (isset($data['height'])) $options['height'] = $data['height']; return Html::img($pdfPreview, $options); } return '/' . $this->source; }
php
{ "resource": "" }
q263931
Media.renderImage
test
public function renderImage($data = []) { ini_set('memory_limit', '512M'); $cacheFile = Yii::getAlias('@cachePath/' . $this->filename); $baseSource = $this->baseSource; if (!isset($data['width']) && !isset($data['height'])) { if (!file_exists(Yii::getAlias('@root') . Yii::getAlias('@cacheDir/' . $this->filename))) { //only cache if not available try { $image = Image::getImagine(); $newImage = $image->open($baseSource); $newImage->save($cacheFile); } catch (\Exception $e) { //seems like image is corrupt! } } return Yii::getAlias('@cacheDir/' . $this->filename); } else { $path_parts = pathinfo($cacheFile); $newFileName = $path_parts['filename'] . '-' . $data['width'] . '-' . $data['height'] . '.' . $path_parts['extension']; //http://imagine.readthedocs.org/en/latest/ if (!file_exists(Yii::getAlias('@root') . Yii::getAlias('@cacheDir/' . $newFileName))) { //only cache if not available try { Image::thumbnail($baseSource, $data['width'], $data['height']) ->save(Yii::getAlias('@cachePath/' . $newFileName)); } catch (\Exception $e) { //seems like image is corrupt! } } if (isset($data['imgTag'])) { return Html::img(Yii::getAlias('@cacheDir/' . $newFileName)); } else { return Yii::getAlias('@cacheDir/' . $newFileName); } } }
php
{ "resource": "" }
q263932
ModelHydrator.hydrate
test
public function hydrate(?array $data, string $modelName): ?object { $mapping = $this->sdk->getMapping(); $key = $mapping->getKeyFromModel($modelName); $modelName = $mapping->getModelName($key); return $this->deserialize($data, $modelName); }
php
{ "resource": "" }
q263933
ModelHydrator.hydrateList
test
public function hydrateList(?array $data, string $modelName): Collection { $collectionKey = $this->sdk->getMapping()->getConfig()['collectionKey']; if (is_array($data) && ArrayHelper::arrayHas($data, $collectionKey)) { return $this->deserializeAll($data, $modelName); } return new Collection(); }
php
{ "resource": "" }
q263934
ModelHydrator.deserializeAll
test
private function deserializeAll(array $data, string $modelName): Collection { $collectionKey = $this->sdk->getMapping()->getConfig()['collectionKey']; $itemList = array_map(function ($member) use ($modelName) { return $this->deserialize($member, $modelName); }, ArrayHelper::arrayGet($data, $collectionKey)); $extraProperties = array_filter( $data, function ($key) use ($collectionKey) { return $key !== $collectionKey; }, ARRAY_FILTER_USE_KEY ); $collectionClassName = $this->guessCollectionClassname($data); return new $collectionClassName($itemList, $extraProperties); }
php
{ "resource": "" }
q263935
ModelHydrator.deserialize
test
private function deserialize(?array $data, string $modelName): ?object { if (null === $data) { return null; } return $this->sdk->getSerializer()->deserialize($data, $modelName); }
php
{ "resource": "" }
q263936
ModelHydrator.guessCollectionClassname
test
private function guessCollectionClassname(array $data): string { switch (true) { case !empty($data['@type']) && 'hydra:PagedCollection' === $data['@type']: return HydraPaginatedCollection::class; case array_key_exists('_embedded', $data): return HalCollection::class; default: return Collection::class; } }
php
{ "resource": "" }
q263937
Sitemap.buildSitemap
test
public function buildSitemap($returnAsArray = false) { $urls = $this->urls; foreach ($this->models as $modelName) { /** @var \kato\modules\sitemap\behaviors\SitemapBehavior $model */ if (is_array($modelName)) { $model = new $modelName['class']; if (isset($modelName['behaviors'])) { $model->attachBehaviors($modelName['behaviors']); } } else { $model = new $modelName; } $urls = array_merge($urls, $model->generateSiteMap()); } if ($returnAsArray === true) { return $urls; } $sitemapData = $this->createControllerByID('default')->renderPartial('index', [ 'urls' => $urls ]); $this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire); return $sitemapData; }
php
{ "resource": "" }
q263938
TabRegistry.getNavigation
test
public function getNavigation(string $elementId): Navigation { if (!isset($this->navigations[$elementId])) { $element = ContentModel::findByPk($elementId); Assertion::isInstanceOf($element, ContentModel::class); Assertion::eq($element->type, 'bs_tab_start'); $this->navigations[$elementId] = Navigation::fromSerialized((string) $element->bs_tabs, $elementId); } return $this->navigations[$elementId]; }
php
{ "resource": "" }
q263939
TabRegistry.getIterator
test
public function getIterator(string $elementId): NavigationIterator { if (!isset($this->iterators[$elementId])) { $this->iterators[$elementId] = new NavigationIterator($this->getNavigation($elementId)); } return $this->iterators[$elementId]; }
php
{ "resource": "" }
q263940
NormalizeTags.normalize
test
public function normalize() { if (!empty($this->owner->{$this->attribute})) { $this->owner->{$this->attribute} = $this->array2string(array_unique($this->string2array($this->owner->{$this->attribute}))); } }
php
{ "resource": "" }
q263941
Collection.getExtraProperty
test
public function getExtraProperty(string $key) { if (isset($this->extraProperties[$key])) { return $this->extraProperties[$key]; } }
php
{ "resource": "" }
q263942
KatoBase.genRandomString
test
public static function genRandomString($length=8) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $size = strlen( $chars ); $str=''; for( $i = 0; $i < $length; $i++ ) { $str .= $chars[ rand( 0, $size - 1 ) ]; } return $str; }
php
{ "resource": "" }
q263943
KatoBase.limit_words
test
public static function limit_words($string, $word_limit) { $words = explode(' ',$string); return trim(implode(' ', array_splice($words, 0, $word_limit))) .'...'; }
php
{ "resource": "" }
q263944
KatoBase.get_files
test
public static function get_files($directory, $ext = '') { $array_items = array(); if($handle = opendir($directory)){ while(false !== ($file = readdir($handle))){ if($file != "." && $file != ".."){ if(is_dir($directory. "/" . $file)){ $array_items = array_merge($array_items, self::get_files($directory. "/" . $file, $ext)); } else { $file = $directory . "/" . $file; if(!$ext || strstr($file, $ext)) $array_items[] = preg_replace("/\/\//si", "/", $file); } } } closedir($handle); } return $array_items; }
php
{ "resource": "" }
q263945
KatoBase.genShortDesc
test
public static function genShortDesc($content, $tag = 'p' , $wordLimit = 20) { if (preg_match('%(<' . $tag . '[^>]*>.*?</' . $tag . '>)%i', $content, $regs)) { $result = $regs[1]; } else { $result = ""; } return self::limit_words(strip_tags($result), $wordLimit); }
php
{ "resource": "" }
q263946
TimeOverlapCalculator.isOverlap
test
public function isOverlap(TimeSlotInterface $baseTimeSlot, TimeSlotInterface $overlappingTimeSlot) { return $baseTimeSlot->getStart() < $overlappingTimeSlot->getEnd() && $overlappingTimeSlot->getStart() < $baseTimeSlot->getEnd(); }
php
{ "resource": "" }
q263947
TimeOverlapCalculator.getNonOverlappedTimeSlots
test
public function getNonOverlappedTimeSlots( TimeSlotInterface $baseTimeSlot, array $overlappingTimeSlots, TimeSlotGeneratorInterface $timeSlotGenerator ) { $baseTimeSlots = [ $timeSlotGenerator->createTimeSlot($baseTimeSlot->getStart(), $baseTimeSlot->getEnd()), ]; foreach ($overlappingTimeSlots as $overlappingTimeSlot) { $freeTimeSlots = []; foreach ($baseTimeSlots as $timeSlot) { $freeTimeSlots = array_merge( $freeTimeSlots, $this->fetchNonOverlappedTimeSlots($timeSlot, $overlappingTimeSlot, $timeSlotGenerator) ); } $baseTimeSlots = $freeTimeSlots; } return $baseTimeSlots; }
php
{ "resource": "" }
q263948
TimeOverlapCalculator.mergeOverlappedTimeSlots
test
public function mergeOverlappedTimeSlots(TimeSlotGeneratorInterface $timeSlotGenerator, array $timeSlots) { if (empty($timeSlots)) { return []; } $timeSlots = $this->sortTimeSlotsByStartTime($timeSlots); $mergedTimeSlots = [ $timeSlotGenerator->createTimeSlot($timeSlots[0]->getStart(), $timeSlots[0]->getEnd()), ]; $headIndex = 0; foreach ($timeSlots as $timeSlot) { $headTimeSlot = $mergedTimeSlots[$headIndex]; if ($timeSlot->getStart() > $headTimeSlot->getEnd()) { $mergedTimeSlots[] = $timeSlotGenerator->createTimeSlot( $timeSlot->getStart(), $timeSlot->getEnd() ); $headIndex ++; } elseif ($headTimeSlot->getEnd() < $timeSlot->getEnd()) { $mergedTimeSlots[$headIndex] = $timeSlotGenerator->createTimeSlot( $headTimeSlot->getStart(), $timeSlot->getEnd() ); } } return $mergedTimeSlots; }
php
{ "resource": "" }
q263949
RestClient.get
test
public function get(string $path, array $parameters = []) { $requestUrl = $this->baseUrl . $path; try { return $this->executeRequest('GET', $requestUrl, $parameters); } catch (ClientException $e) { $response = $e->getResponse(); if (null !== $response && 404 === $response->getStatusCode()) { return null; } throw new RestClientException( 'Error while getting resource', $path, [], 7, $e ); } catch (TransferException $e) { throw new RestException( 'Error while getting resource', $path, [], 1, $e ); } }
php
{ "resource": "" }
q263950
RestClient.mergeDefaultParameters
test
protected function mergeDefaultParameters(array $parameters): array { $request = $this->getCurrentRequest(); $defaultParameters = ['version' => '1.0']; $defaultParameters['headers'] = ['Referer' => $request->getUri()]; return array_replace_recursive($defaultParameters, $parameters); }
php
{ "resource": "" }
q263951
RestClient.executeRequest
test
private function executeRequest( string $method, string $url, array $parameters = [] ) { $parameters = $this->mergeDefaultParameters($parameters); $startTime = null; if ($this->isHistoryLogged()) { $startTime = microtime(true); } try { $response = $this->httpClient->request($method, $url, $parameters); $this->logRequest( $startTime, $method, $url, $parameters, $response ); } catch (RequestException $e) { $this->logRequest( $startTime, $method, $url, $parameters, $e->getResponse() ); throw $e; } catch (TransferException $e) { $this->logRequest($startTime, $method, $url, $parameters); throw $e; } $headers = $response->getHeaders(); $jsonContentTypeList = ['application/ld+json', 'application/json']; $requestIsJson = false; if (isset($headers['Content-Type'])) { foreach ($jsonContentTypeList as $contentType) { if ( false !== mb_stripos($headers['Content-Type'][0], $contentType) ) { $requestIsJson = true; break; } } } if ($requestIsJson) { return json_decode((string) $response->getBody(), true); } else { return $response; } }
php
{ "resource": "" }
q263952
AbstractTabElement.renderBackendView
test
protected function renderBackendView($start, NavigationIterator $iterator = null): string { $parent = $this->getParent(); return $this->render( new ToolkitTemplateReference( 'be_bs_tab', 'html5', ToolkitTemplateReference::SCOPE_BACKEND ), [ 'name' => $parent ? $parent->bs_tab_name : null, 'color' => $start ? $this->rotateColor('ce:' . $start->id) : null, 'error' => $start ? null : $this->translator->trans('ERR.bsTabParentMissing', [], 'contao_default'), 'title' => $iterator ? $iterator->currentTitle() : null, ] ); }
php
{ "resource": "" }
q263953
AbstractTabElement.getIterator
test
protected function getIterator(): ?NavigationIterator { $parent = $this->getParent(); if (!$parent) { return null; } try { return $this->getTabRegistry()->getIterator((string) $parent->id); } catch (AssertionFailedException $e) { return null; } }
php
{ "resource": "" }
q263954
AbstractTabElement.getGridIterator
test
protected function getGridIterator(): ?GridIterator { $parent = $this->getParent(); if (!$parent || !$this->gridProvider || !$parent->bs_grid) { return null; } try { $gridIterator = $this->gridProvider->getIterator('ce:' . $parent->id, (int) $parent->bs_grid); return $gridIterator; } catch (\RuntimeException $e) { return null; } }
php
{ "resource": "" }
q263955
BBCodeBehavior.beforeSave
test
public function beforeSave($event) { $content = $this->owner->{$this->attribute}; if ($this->enableHtmlPurifierBefore) { $content = HtmlPurifier::process($content, $this->configHtmlPurifierBefore); } $content = $this->process($content); if ($this->enableHtmlPurifierAfter) { $content = HtmlPurifier::process($content, $this->configHtmlPurifierAfter); } $this->owner->{$this->saveAttribute} = $content; }
php
{ "resource": "" }
q263956
BBCodeBehavior.process
test
protected function process($content) { $parser = new Parser(); $parser->addCodeDefinitionSet(new $this->defaultCodeDefinitionSet()); // add definitions builder foreach ($this->codeDefinitionBuilder as $item) { if (is_string($item)) { $builder = new $item; if ($builder instanceof CodeDefinitionBuilder) { $parser->addCodeDefinition($builder->build()); } } elseif ($item instanceof CodeDefinitionBuilder) { $parser->addCodeDefinition($item->build()); } elseif (is_callable($item)) { $parser->addCodeDefinition(call_user_func_array($item, [new CodeDefinitionBuilder('', '')])); } elseif (isset($item[0]) && isset($item[1])) { $builder = new CodeDefinitionBuilder($item[0], $item[1]); $parser->addCodeDefinition($builder->build()); } } //added definitions set foreach ($this->codeDefinitionSet as $item) { if (is_string($item)) { $set = new $item; if ($set instanceof CodeDefinitionSet) { $parser->addCodeDefinitionSet($set); } } elseif ($item instanceof CodeDefinitionSet) { $parser->addCodeDefinitionSet($item); } } //added definitions foreach ($this->codeDefinition as $item) { if (is_string($item)) { $set = new $item; if ($set instanceof CodeDefinition) { $parser->addCodeDefinition($set); } } elseif ($item instanceof CodeDefinition) { $parser->addCodeDefinition($item); } } $parser->parse($content); if ($this->asHtml) { return $parser->getAsHtml(); } return $parser->getAsBBCode(); }
php
{ "resource": "" }
q263957
DefaultController.actionUpdate
test
public function actionUpdate($id) { $module = MediaModule::getInstance(); if (!is_null($module->adminLayout)) { $this->layout = $module->adminLayout; } $model = $this->findModel($id); $model->title = $model->id; $controllerName = $this->getUniqueId(); $meta['title'] = $this->pageTitle; $meta['description'] = 'Update media'; $meta['pageIcon'] = $this->pageIcon; if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->session->setFlash('success', 'Media has been updated'); return $this->redirect(Url::previous()); } else { return $this->render('update', [ 'model' => $model, 'meta' => $meta, 'controllerName' => $controllerName, ]); } }
php
{ "resource": "" }
q263958
DefaultController.doMediaJoin
test
private function doMediaJoin($result) { if (isset($_GET['content_id']) && isset($_GET['content_type'])) { $media = $result['data']; if (!is_null($media)) { //Do join here $contentMedia = new ContentMedia(); $contentMedia->content_id = $_GET['content_id']; $contentMedia->content_type = $_GET['content_type']; $contentMedia->media_id = $media['id']; if ($contentMedia->save(false)) { //success return true; } else { return false; } } } return true; }
php
{ "resource": "" }
q263959
DefaultController.actionUpload
test
public function actionUpload() { /** * @var \kato\modules\media\Media $module */ $module = \Yii::$app->controller->module; $result = $module->mediaUpload(); $response = new Response(); $response->format = Response::FORMAT_JSON; $response->setStatusCode(500); if ($result['success'] === true) { if ($this->doMediaJoin($result)) { //success $response->setStatusCode(200); $response->data = $result['data']; $response->send(); Yii::$app->end(); } else { $response->statusText = 'Unable to do join of media with content.'; $response->send(); Yii::$app->end(); } } else { $response->statusText = $result['message']; $response->send(); Yii::$app->end(); } }
php
{ "resource": "" }
q263960
DefaultController.actionUpdateData
test
public function actionUpdateData($id) { if ($post = Yii::$app->request->post()) { $model = $this->findModel($id); $model->$post['name'] = $post['value']; if ($model->save(false)) { echo 'true'; exit; } } echo 'false'; }
php
{ "resource": "" }
q263961
DefaultController.actionListMedia
test
public function actionListMedia() { $result = array(); if (isset($_GET['content_id']) && isset($_GET['content_type'])) { //get for modal $media = Media::find() ->leftJoin('kato_content_media', 'kato_content_media.media_id = kato_media.id') ->where(['kato_content_media.content_id' => $_GET['content_id'], 'kato_content_media.content_type' => $_GET['content_type']]) ->all(); } else { //return all media $media = Media::find()->all(); } if ($media) { foreach ($media as $data) { $result[] = array( 'thumb' => '/' . $data->source, 'image' => '/' . $data->source, 'title' => '/' . $data->filename, //'filelink' => '/' . $data->source, ); } } echo Json::encode($result); }
php
{ "resource": "" }
q263962
DefaultController.actionRenderRow
test
public function actionRenderRow($id) { $this->layout = false; if ($media = $this->findModel($id)) { return $this->render('mediaRow', [ 'media' => $media, 'isNew' => true, ]); } return ''; }
php
{ "resource": "" }
q263963
DefaultController.actionDelete
test
public function actionDelete($id) { $this->findModel($id)->delete(); if (Yii::$app->request->isAjax) { echo 'true'; exit; } Yii::$app->session->setFlash('success', 'Media has been deleted'); return $this->redirect(Url::previous()); }
php
{ "resource": "" }
q263964
ClassMetadata.setAttributeList
test
public function setAttributeList($attributeList): self { $this->attributeList = []; foreach ($attributeList as $attribute) { $this->attributeList[$attribute->getSerializedKey()] = $attribute; if ($attribute->isIdentifier()) { if ($this->identifierAttribute) { throw new MoreThanOneIdentifierException( sprintf( 'Class metadata for model "%s" already has an identifier named "%s". Only one identifier is allowed.', $this->modelName, $this->identifierAttribute->getSerializedKey() ) ); } $this->identifierAttribute = $attribute; } } return $this; }
php
{ "resource": "" }
q263965
ClassMetadata.getDefaultSerializedModel
test
public function getDefaultSerializedModel(): array { $out = []; $attributeList = $this->getAttributeList(); if ($attributeList) { foreach ($attributeList as $attribute) { $out[$attribute->getSerializedKey()] = null; } } $relationList = $this->getRelationList(); if ($relationList) { foreach ($relationList as $relation) { if ($relation->isOneToMany()) { $out[$relation->getSerializedKey()] = []; } } } return $out; }
php
{ "resource": "" }
q263966
AdminThemeCommand.createDirectories
test
protected function createDirectories() { if (! is_dir(base_path('resources/views/layouts'))) { mkdir(base_path('resources/views/layouts'), 0755, true); } if (! is_dir(base_path('resources/views/emails'))) { mkdir(base_path('resources/views/emails'), 0755, true); } if (! is_dir(base_path('resources/views/errors'))) { mkdir(base_path('resources/views/errors'), 0755, true); } if (! is_dir(base_path('resources/views/partials'))) { mkdir(base_path('resources/views/partials'), 0755, true); } if (! is_dir(base_path('resources/views/profile'))) { mkdir(base_path('resources/views/profile'), 0755, true); } if (! is_dir(base_path('resources/views/profile/partials'))) { mkdir(base_path('resources/views/profile/partials'), 0755, true); } if (! is_dir(base_path('resources/views/users'))) { mkdir(base_path('resources/views/users'), 0755, true); } if (! is_dir(base_path('resources/views/auth/passwords'))) { mkdir(base_path('resources/views/auth/passwords'), 0755, true); } if (! is_dir(public_path('plugins'))) { mkdir(public_path('plugins'), 0755, true); } if (! is_dir(base_path('resources/assets/less'))) { mkdir(base_path('resources/assets/less'), 0755, true); } if (! is_dir(base_path('resources/assets/js'))) { mkdir(base_path('resources/assets/js'), 0755, true); } }
php
{ "resource": "" }
q263967
AdminThemeCommand.exportViews
test
protected function exportViews() { foreach ($this->views as $key => $value) { $path = base_path('resources/views/'.$value); $this->line('<info>View:</info> '.$path); try { copy(__DIR__ . '/../stubs/views/' . $key, $path); } catch (ErrorException $e) { $this->error(__DIR__ . '/../stubs/views/' . $key); $this->error($path); } } }
php
{ "resource": "" }
q263968
AdminThemeCommand.exportControllers
test
protected function exportControllers() { foreach ($this->controllers as $key => $value) { $path = app_path('Http/Controllers/'.$value); $this->line('<info>Controller:</info> '.$path); file_put_contents( app_path('Http/Controllers/'.$value), $this->compileControllerStub($key) ); } }
php
{ "resource": "" }
q263969
AdminThemeCommand.exportRoutes
test
protected function exportRoutes() { if ($this->version < 5.3) { $routeFile = app_path('Http/routes.php'); $stubFile = __DIR__.'/../stubs/routes.stub'; } else { $routeFile = base_path('routes/web.php'); $stubFile = __DIR__.'/../stubs/routes/web.stub'; } $routeContent = file_get_contents($routeFile); preg_match('/ProfileController@view/', $routeContent, $matches); if (! count($matches)) { $this->info('Updated Routes File.'); file_put_contents( $routeFile, file_get_contents($stubFile), FILE_APPEND ); } }
php
{ "resource": "" }
q263970
AdminThemeCommand.checkPackages
test
protected function checkPackages() { if (! is_dir(base_path('vendor/twbs'))) { $this->line(''); $this->line('<error> Error </error> Missing <comment>Bootstrap</comment> package!'); $this->line('Run: <comment>composer require twbs/bootstrap</comment>'."\n"); return false; } if (! is_dir(base_path('vendor/almasaeed2010'))) { $this->line(''); $this->line('<error> Error </error> Missing <comment>AdminLTE</comment> package!'); $this->line('Run: <comment>composer require almasaeed2010/adminlte</comment>'."\n"); return false; } if (! is_dir(base_path('node_modules/jquery'))) { $this->line(''); $this->line('<error> Error </error> Missing <comment>jQuery</comment> package!'); $this->line('Run: <comment>npm install</comment> or <comment>npm install jquery</comment>'."\n"); return false; } if (! is_dir(base_path('node_modules/font-awesome'))) { $this->line(''); $this->line('<error> Error </error> Missing <comment>Font Awesome</comment> package!'); $this->line('Run: <comment>npm install</comment> or <comment>npm install font-awesome</comment>'."\n"); return false; } if (! is_dir(base_path('node_modules/ionicons'))) { $this->line(''); $this->line('<error> Error </error> Missing <comment>IonIcons</comment> package!'); $this->line('Run: <comment>npm install</comment> or <comment>npm install ionicons</comment>'."\n"); return false; } return true; }
php
{ "resource": "" }
q263971
AdminThemeCommand.copyPlugins
test
protected function copyPlugins() { $destination = public_path('plugins'); $this->line('<info>Plugin:</info> ' . $destination); File::copyDirectory(base_path('vendor/almasaeed2010/adminlte/plugins'), $destination); }
php
{ "resource": "" }
q263972
AdminThemeCommand.copyAssetFiles
test
protected function copyAssetFiles() { foreach ($this->assets as $destination => $source) { $this->line('<info>Asset:</info> ' . base_path($destination)); file_put_contents( base_path($destination), file_get_contents($source) ); } }
php
{ "resource": "" }
q263973
AdminThemeCommand.copyLessFolders
test
protected function copyLessFolders() { foreach ($this->lessSources as $source => $destination) { $this->line('<info>LESS:</info> ' . base_path($destination)); File::copyDirectory( base_path($source), base_path($destination) ); } }
php
{ "resource": "" }
q263974
Setting.getByCategories
test
public function getByCategories() { $data = [ 'categories' => $this->getCategories(), 'settings' => [], ]; foreach ($data['categories'] as $key => $category) { $model = self::find() ->where(['category' => $category]) ->indexBy('id') ->all(); $data['settings'][$category] = $model; } return $data; }
php
{ "resource": "" }
q263975
Navigation.fromSerialized
test
public static function fromSerialized(string $definition, string $tabId): self { $navigation = new Navigation(); $current = $navigation; $definition = StringUtil::deserialize($definition, true); $cssIds = []; foreach ($definition as $index => $tab) { if (!$tab['cssId']) { $tab['cssId'] = StringUtil::standardize($tab['title']); $tab['cssId'] .= '-' . $tabId; if (in_array($tab['cssId'], $cssIds)) { $tab['cssId'] .= '-' . $index; } } if ($tab['type'] === 'dropdown') { $item = Dropdown::fromArray($tab); $current = $item; $navigation->addItem($item); } else { if ($tab['type'] !== 'child') { $current = $navigation; } $item = NavItem::fromArray($tab); $current->addItem($item); } } return $navigation; }
php
{ "resource": "" }
q263976
NavItem.fromArray
test
public static function fromArray(array $definition): NavItem { return new static( $definition['title'], (bool) $definition['active'], $definition['cssId'] ?? null, $definition['navCssId'] ?? null ); }
php
{ "resource": "" }
q263977
View.loadBlock
test
public function loadBlock($name, $isGlobal = false) { if (is_null($name)) { throw new BadRequestHttpException('Block name not specified.'); } $find = [ 'title' => $name, ]; if ($isGlobal === false) { //if not global if (isset($this->params['block']['id'])) { $find['parent'] = $this->params['block']['id']; } if (isset($this->params['block']['layout'])) { $find['parent_layout'] = $this->params['block']['layout']; } if (isset($this->params['block']['slug'])) { //get parent page id /** * @var $page \backend\models\Page */ if ($page = Page::findOne([ 'slug' => $this->params['block']['slug'], ])) { $find['parent'] = $page->id; } } } /** * @var $block \backend\models\Block */ if ($block = Block::findOne($find)) { //if block found return $block->render(); } return false; }
php
{ "resource": "" }
q263978
SitemapWidget.getModule
test
public function getModule($m) { $mod = Yii::$app->controller->module; return $mod && $mod->getModule($m) ? $mod->getModule($m) : Yii::$app->getModule($m); }
php
{ "resource": "" }
q263979
Serializer.serialize
test
public function serialize( object $entity, string $modelName, array $context = [] ): array { $out = $this->recursiveSerialize($entity, $modelName, 0, $context); if (is_string($out)) { throw new \RuntimeException( 'recursiveSerialize should return an array for level 0 of serialization. This should not happen.' ); } return $out; }
php
{ "resource": "" }
q263980
Mapping.getModelName
test
public function getModelName(string $key): string { $this->checkMappingExistence($key, true); /** @var ClassMetadata */ $classMetadata = $this->getClassMetadataByKey($key); return $classMetadata->getModelName(); }
php
{ "resource": "" }
q263981
Mapping.getClassMetadata
test
public function getClassMetadata(string $modelName): ClassMetadata { foreach ($this->classMetadataList as $classMetadata) { if ($modelName === $classMetadata->getModelName()) { return $classMetadata; } } throw new MappingException($modelName . ' model is not mapped'); }
php
{ "resource": "" }
q263982
Mapping.tryGetClassMetadataById
test
public function tryGetClassMetadataById(string $id): ?ClassMetadata { $key = $this->parseKeyFromId($id); foreach ($this->classMetadataList as $classMetadata) { if ($key === $classMetadata->getKey()) { return $classMetadata; } } return null; }
php
{ "resource": "" }
q263983
PageTreeWidget.renderTree
test
private function renderTree($parentId = 0) { $query = Page::find(); $query->andWhere(['deleted' => 0, 'revision_to' => 0, 'parent_id' => $parentId]); $query->orderBy('title ASC'); if (($pages = $query->all()) == null) { //empty array if no data found return []; } $tree = $this->getBranch($pages, true); return $tree; }
php
{ "resource": "" }
q263984
PageTreeWidget.getBranch
test
protected function getBranch($pages) { $result = []; foreach ($pages as $page) { $result[] = array('model' => $page, 'children' => $this->renderTree($page->id)); } return $result; }
php
{ "resource": "" }
q263985
EntityRepository.removeFromCache
test
protected function removeFromCache(string $key): bool { $key = $this->normalizeCacheKey($key); $cacheItemPool = $this->sdk->getCacheItemPool(); if ($cacheItemPool) { $cacheKey = $this->sdk->getCachePrefix() . $key; if ($cacheItemPool->hasItem($cacheKey)) { return $cacheItemPool->deleteItem($cacheKey); } } return true; }
php
{ "resource": "" }
q263986
Tag.listTags
test
public static function listTags($tagType = null, $limit = 30) { $model = self::find() ->select('name') ->orderBy('frequency DESC, Name') ->limit($limit); if (!is_null($tagType)) { $data = $model->where('tag_type = :type', [':type' => $tagType])->all(); } else { $data = $model->all(); } $return = ['']; if (!empty($data)) { foreach ($data as $tag) { $return[] = $tag->name; } } return $return; }
php
{ "resource": "" }
q263987
Tag.findTagWeights
test
public function findTagWeights($limit = 20) { $models = self::find() ->orderBy('frequency DESC') ->limit($limit) -all(); $total=0; foreach ($models as $model) { $total+=$model->frequency; } $tags=[]; if ($total > 0) { foreach ($models as $model) { $tags[$model->name] = 8 + (int)(16*$model->frequency/($total+10)); } ksort($tags); } return $tags; }
php
{ "resource": "" }
q263988
Tag.addTags
test
public static function addTags($tags, $tagType) { foreach ($tags as $name) { $tag = self::find() ->where(['name' => $name]) ->andWhere(['tag_type' => $tagType]) ->one(); //if tag does not exists, insert it if (is_null($tag)) { $tag = new self(); $tag->name = $name; $tag->tag_type = $tagType; $tag->frequency = self::DEFAULT_FREQUENCY; $tag->save(false); } else { //Update count of tags already exists $tag->updateCounters(['frequency' => self::DEFAULT_FREQUENCY]); } } }
php
{ "resource": "" }
q263989
Tag.removeTags
test
public static function removeTags($tags, $tagType) { if (empty($tags)) { return; } foreach ($tags as $name) { $tag = self::find() ->where(['name' => $name]) ->andWhere(['tag_type' => $tagType]) ->one(); if (!is_null($tag)) { $tag->updateCounters(['frequency' => '-' . self::DEFAULT_FREQUENCY]); if ($tag->frequency <= 0) { $tag->delete(); } } } }
php
{ "resource": "" }
q263990
ContentListener.getTabParentOptions
test
public function getTabParentOptions(): array { $columns[] = 'tl_content.type = ?'; $columns[] = 'tl_content.pid = ?'; $columns[] = 'tl_content.ptable = ?'; $values[] = 'bs_tab_start'; $values[] = CURRENT_ID; $values[] = $GLOBALS['TL_DCA']['tl_content']['config']['ptable']; $collection = $this->repository->findBy($columns, $values); $options = []; if ($collection) { foreach ($collection as $model) { $options[$model->id] = sprintf( '%s [%s]', $model->bs_tab_name, $model->id ); } } return $options; }
php
{ "resource": "" }
q263991
ContentListener.generateColumns
test
public function generateColumns($dataContainer) { if (!$dataContainer->activeRecord || $dataContainer->activeRecord->type !== 'bs_tab_start') { return; } /** @var ContentModel|Result $current */ $current = $dataContainer->activeRecord; $stopElement = $this->getStopElement($current); $count = $this->countRequiredSeparators($dataContainer->activeRecord->bs_tabs, $current); $nextElements = $this->getNextElements($stopElement); if ($count > 0) { $sorting = (int) $stopElement->sorting; $sorting = $this->createSeparators((int) $count, $current, $sorting); array_unshift($nextElements, $stopElement); $this->updateSortings($nextElements, $sorting); } }
php
{ "resource": "" }
q263992
ContentListener.countRequiredSeparators
test
private function countRequiredSeparators($definition, $current): int { $definition = StringUtil::deserialize($definition, true); $count = -1; foreach ($definition as $item) { if ($item['type'] !== 'dropdown') { $count++; } } $count -= $this->repository->countBy( [ 'tl_content.ptable=?', 'tl_content.pid=?', '(tl_content.type = ? AND tl_content.bs_tab_parent = ?)', ], [$current->ptable, $current->pid, 'bs_tab_separator', $current->id], ['order' => 'tl_content.sorting ASC'] ); return $count; }
php
{ "resource": "" }
q263993
ContentListener.createSeparators
test
protected function createSeparators(int $value, $current, int $sorting): int { for ($count = 1; $count <= $value; $count++) { $sorting = ($sorting + 8); $this->createTabElement($current, 'bs_tab_separator', $sorting); } return $sorting; }
php
{ "resource": "" }
q263994
ContentListener.createStopElement
test
protected function createStopElement($current, int $sorting): Model { $sorting = ($sorting + 8); return $this->createTabElement($current, 'bs_tab_end', $sorting); }
php
{ "resource": "" }
q263995
ContentListener.createTabElement
test
protected function createTabElement($current, string $type, int &$sorting): Model { $model = new ContentModel(); $model->tstamp = time(); $model->pid = $current->pid; $model->ptable = $current->ptable; $model->sorting = $sorting; $model->type = $type; $model->bs_tab_parent = $current->id; $model->save(); return $model; }
php
{ "resource": "" }
q263996
ContentListener.getStopElement
test
protected function getStopElement($current): Model { $stopElement = $this->repository->findOneBy( ['tl_content.type=?', 'tl_content.bs_tab_parent=?'], ['bs_tab_end', $current->id] ); if ($stopElement) { return $stopElement; } $nextElements = $this->getNextElements($current); $stopElement = $this->createStopElement($current, (int) $current->sorting); $this->updateSortings($nextElements, (int) $stopElement->sorting); return $stopElement; }
php
{ "resource": "" }
q263997
DcaMemberOnlineIcon.addIcon
test
public function addIcon($row, $label, \DataContainer $dc, $args) { $image = 'member'; $time = \Date::floorToMinute(); $disabled = $row['start'] !== '' && $row['start'] > $time || $row['stop'] !== '' && $row['stop'] < $time; if ($row['disable'] || $disabled) { $image .= '_'; } $objUsers = \Database::getInstance() ->prepare("SELECT tlm.id FROM tl_member tlm, tl_beuseronline_session tls WHERE tlm.id = tls.pid AND tlm.id = ? AND tls.tstamp > ? AND tls.name = ?") ->execute($row['id'], time()-300, 'FE_USER_AUTH'); if ($objUsers->numRows < 1) { //offline $status = sprintf('<img src="%ssystem/themes/%s/icons/invisible.svg" width="16" height="16" alt="Offline" style="padding-left: 18px;">', TL_ASSETS_URL, \Backend::getTheme()); } else { //online $status = sprintf('<img src="%ssystem/themes/%s/icons/visible.svg" width="16" height="16" alt="Online" style="padding-left: 18px;">', TL_ASSETS_URL, \Backend::getTheme()); } $args[0] = sprintf('<div class="list_icon_new" style="background-image:url(\'%ssystem/themes/%s/icons/%s.svg\'); width: 34px;" data-icon="%s.svg" data-icon-disabled="%s.svg">%s</div>', TL_ASSETS_URL, \Backend::getTheme(), $image, $disabled ? $image : rtrim($image, '_'), rtrim($image, '_') . '_', $status); return $args; }
php
{ "resource": "" }
q263998
ActiveRecord.getSelectOptions
test
public static function getSelectOptions($key = 'id', $value = 'title', $where = []) { $parents = self::find(); if (!empty($where)) { $parents->where($where); } return \yii\helpers\ArrayHelper::map($parents->all(), $key, $value); }
php
{ "resource": "" }
q263999
ActiveRecord.listStatus
test
public function listStatus() { $data = []; // create a reflection class to get constants $refl = new ReflectionClass(get_called_class()); $constants = $refl->getConstants(); // check for status constants (e.g., STATUS_ACTIVE) foreach ($constants as $constantName => $constantValue) { // add prettified name to dropdown if (strpos($constantName, "STATUS_") === 0) { $prettyName = str_replace("STATUS_", "", $constantName); $prettyName = Inflector::humanize(strtolower($prettyName)); $data[$constantValue] = $prettyName; } } return $data; }
php
{ "resource": "" }