_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q8200
Helpers.&
train
protected function & setCoreClass ($newCoreClassName, $coreClassVar, $coreClassInterface) { if (call_user_func( [$this->toolClass, 'CheckClassInterface'], $newCoreClassName, $coreClassInterface, TRUE, TRUE // check static methods and throw an exception if false )) $this->$coreClassVar = $newCoreClassName; /** @var $this \MvcCore\Application */ return $this; }
php
{ "resource": "" }
q8201
Helpers.&
train
protected function & setHandler (array & $handlers, callable $handler, $priorityIndex = NULL) { // there is possible to call any `callable` as closure function in variable // except forms like `'ClassName::methodName'` and `['childClassName', 'parent::methodName']` // and `[$childInstance, 'parent::methodName']`. $closureCalling = ( (is_string($handler) && strpos($handler, '::') !== FALSE) || (is_array($handler) && strpos($handler[1], '::') !== FALSE) ) ? FALSE : TRUE; if ($priorityIndex === NULL) { $handlers[] = [$closureCalling, $handler]; } else { if (isset($handlers[$priorityIndex])) { array_splice($handlers, $priorityIndex, 0, [$closureCalling, $handler]); } else { $handlers[$priorityIndex] = [$closureCalling, $handler]; } } /** @var $this \MvcCore\Application */ return $this; }
php
{ "resource": "" }
q8202
CreatePropertyConditionListener.onCreatePropertyCondition
train
public function onCreatePropertyCondition(CreatePropertyConditionEvent $event) { if (!$this->scopeMatcher->currentScopeIsFrontend()) { return; } $meta = $event->getData(); if ('conditionpropertyvalueis' !== $meta['type']) { return; } $metaModel = $event->getMetaModel(); $attribute = $metaModel->getAttributeById($meta['attr_id']); if (!($attribute instanceof Checkbox)) { return; } if ((bool) $meta['value']) { $event->setInstance(new PropertyTrueCondition($attribute->getColName())); return; } $event->setInstance(new PropertyFalseCondition($attribute->getColName())); }
php
{ "resource": "" }
q8203
MigratorUtil.getClassNameFromFile
train
public static function getClassNameFromFile($file) { $fp = fopen($file, 'r'); $class = $namespace = $buffer = ''; $i = 0; while (!$class) { if (feof($fp)) { break; } // Read entire lines to prevent keyword truncation for ($line = 0; $line <= 20; $line++) { $buffer .= fgets($fp); } $tokens = @token_get_all($buffer); if (strpos($buffer, '{') === false) { continue; } for (;$i < count($tokens);$i++) { if ($tokens[$i][0] === T_NAMESPACE) { for ($j = $i + 1;$j < count($tokens); $j++) { if ($tokens[$j][0] === T_STRING) { $namespace .= '\\' . $tokens[$j][1]; } elseif ($tokens[$j] === '{' || $tokens[$j] === ';') { break; } } } if ($tokens[$i][0] === T_CLASS) { for ($j = $i + 1;$j < count($tokens);$j++) { if ($tokens[$j] === '{') { $class = $tokens[$i + 2][1]; } } } } }; if (!$class) { return; } return $namespace . '\\' . $class; }
php
{ "resource": "" }
q8204
ConfirmExtension.configureTwigBundle
train
private function configureTwigBundle(ContainerBuilder $container) { // Get the twig configurations. $name = 'twig'; $configs = $container->getExtensionConfig($name); // Find any existing configurations and add to it them so when the // configs are merged they do not overwrite each other. foreach ($configs as $config) { if (isset($config['form_themes'])) { $formConfig = ['form_themes' => $config['form_themes']]; } } // Update or create the configuration. if (!empty($formConfig)) { $formConfig['form_themes'][] = $this->formTemplate; } else { $formConfig = [ 'form_themes' => [$this->formTemplate], ]; } // Prepend our configuration. $container->prependExtensionConfig($name, $formConfig); }
php
{ "resource": "" }
q8205
NamespaceMethods.&
train
public static function & GetNamespace ( $name = \MvcCore\ISession::DEFAULT_NAMESPACE_NAME ) { if (!static::GetStarted()) static::Start(); if (!isset(static::$instances[$name])) { static::$instances[$name] = new static($name); } /** @var $result \MvcCore\Session */ $result = & static::$instances[$name]; return $result; }
php
{ "resource": "" }
q8206
Builder.buildAsProduction
train
public function buildAsProduction(Collection $collection, $group) { // Get the assets of the given group from the collection. The collection is also responsible // for handling any ordering of the assets so that we just need to build them. $assets = $collection->getAssetsWithoutRaw($group); $entry = $this->manifest->make($identifier = $collection->getIdentifier()); // Build the assets and transform the array into a newline separated string. We'll use this // as a basis for the collections fingerprint and it will decide as to whether the // collection needs to be rebuilt. $build = array_to_newlines($assets->map(function($asset) { return $asset->build(true); })->all()); // If the build is empty then we'll reset the fingerprint on the manifest entry and throw the // exception as there's no point going any further. if (empty($build)) { $entry->resetProductionFingerprint($group); throw new BuildNotRequiredException; } $fingerprint = $identifier.'-'.md5($build).'.'.$collection->getExtension($group); $path = $this->buildPath.'/'.$fingerprint; // If the collection has already been built and we're not forcing the build then we'll throw // the exception here as we don't need to rebuild the collection. if ($fingerprint == $entry->getProductionFingerprint($group) and ! $this->force and $this->files->exists($path)) { throw new BuildNotRequiredException; } else { $this->files->put($path, $this->gzip($build)); $entry->setProductionFingerprint($group, $fingerprint); } }
php
{ "resource": "" }
q8207
Builder.buildAsDevelopment
train
public function buildAsDevelopment(Collection $collection, $group) { // Get the assets of the given group from the collection. The collection is also responsible // for handling any ordering of the assets so that we just need to build them. $assets = $collection->getAssetsWithoutRaw($group); $entry = $this->manifest->make($identifier = $collection->getIdentifier()); // If the collection definition has changed when compared to the manifest entry or if the // collection is being forcefully rebuilt then we'll reset the development assets. if ($this->collectionDefinitionHasChanged($assets, $entry, $group) or $this->force) { $entry->resetDevelopmentAssets($group); } // Otherwise we'll look at each of the assets and see if the entry has the asset or if // the assets build path differs from that of the manifest entry. else { $assets = $assets->filter(function($asset) use ($entry) { return ! $entry->hasDevelopmentAsset($asset) or $asset->getBuildPath() != $entry->getDevelopmentAsset($asset); }); } if ( ! $assets->isEmpty()) { foreach ($assets as $asset) { $path = "{$this->buildPath}/{$identifier}/{$asset->getBuildPath()}"; // If the build directory does not exist we'll attempt to recursively create it so we can // build the asset to the directory. ! $this->files->exists($directory = dirname($path)) and $this->files->makeDirectory($directory, 0777, true); $this->files->put($path, $this->gzip($asset->build())); // Add the development asset to the manifest entry so that we can save the built asset // to the manifest. $entry->addDevelopmentAsset($asset); } } else { throw new BuildNotRequiredException; } }
php
{ "resource": "" }
q8208
Builder.collectionDefinitionHasChanged
train
protected function collectionDefinitionHasChanged($assets, $entry, $group) { // If the manifest entry doesn't even have the group registered then it's obvious that the // collection has changed and needs to be rebuilt. if ( ! $entry->hasDevelopmentAssets($group)) { return true; } // Get the development assets from the manifest entry and flatten the keys so that we have // an array of relative paths that we can compare from. $manifest = $entry->getDevelopmentAssets($group); $manifest = array_flatten(array_keys($manifest)); // Compute the difference between the collections assets and the manifests assets. If we get // an array of values then the collection has changed since the last build and everything // should be rebuilt. $difference = array_diff_assoc($manifest, $assets->map(function($asset) { return $asset->getRelativePath(); })->flatten()->toArray()); return ! empty($difference); }
php
{ "resource": "" }
q8209
Builder.makeBuildPath
train
protected function makeBuildPath() { if ( ! $this->files->exists($this->buildPath)) { $this->files->makeDirectory($this->buildPath); } }
php
{ "resource": "" }
q8210
Component.initDefaultProperties
train
public function initDefaultProperties() { if (!empty($this->schema->properties)) { foreach ($this->schema->properties as $property_name => $property) { if ($this->setPropertyDefaultValue($property)) { $this->property_values->$property_name = $this->getFactory()->create($property, $this->schema_path); } } } }
php
{ "resource": "" }
q8211
Component.get
train
public function get($property_name = null) { if (!isset($property_name)) { return $this->property_values; } // @todo: This probably needs a refactor. // If this is a component itself just return the component. if (isset($this->property_values->$property_name) && is_object($this->property_values->$property_name) && get_class($this) == get_class($this->property_values->$property_name)) { return $this->property_values->$property_name; } // If this property is a component itself, just return it's get() method. if (isset($this->property_values->$property_name) && is_object($this->property_values->$property_name) && $this->property_values->$property_name instanceof PropertyInterface) { return $this->property_values->$property_name->get(); } elseif (isset($this->property_values->$property_name)) { return $this->property_values->$property_name; } return; }
php
{ "resource": "" }
q8212
Component.validate
train
public function validate($notify = false) { $validator = $this->getValidator(); if ($validator) { // Expand the schema. // TODO: recurse & $value->validate() instead? $schema = clone $this->schema; $this->resolver->resolve($schema, $this->schema_path); // Set to current values. $values = $this->flatValue(); if (isset($values)) { $validator->check($values, $schema); if (!$validator->isValid()) { $errors = $validator->getErrors(); if (empty($errors)) { // Create a top level schema error since something is wrong. $errors = array(array( 'property' => $this->schema_path, 'message' => 'The JSON schema failed validation.', 'constraint' => null, )); } // Log errors. if ($notify) { foreach ($errors as $error) { $error_keys = array( '%name' => $this->schema_name, '%message' => $error['message'], '%property' => isset($error['property']) ? $error['property'] : 'property', '%constraint' => isset($error['constraint']) ? $error['constraint'] : 'unknown', ); $this->logger->notice('Schema Validation: "%message" in schema "%name", property "%property" for constraint %constraint', $error_keys); } } return $errors; } } } return true; }
php
{ "resource": "" }
q8213
Component.render
train
public function render() { $template_variables = $this->prepareRender(); if ($this->configuration->developerMode()) { $this->validate(true); } // Decode/encode turns the full array/object into an array. // Just typecasting to an array does not recursively apply it. $template_array = json_decode(json_encode($template_variables), true); if (!empty($template_variables->template)) { return $this->twig->render($template_variables->template, $template_array); } else { $log_vars = array('%schema' => ''); if (isset($this->schema_name)) { $log_vars['%schema'] = $this->schema_name; } elseif (isset($this->schema_path)) { $log_vars['%schema'] = $this->schema_path; } $this->logger->notice('Cannot render: Missing template property in schema %schema.', $log_vars); } }
php
{ "resource": "" }
q8214
Component.prepareTemplateVariables
train
public function prepareTemplateVariables($variables) { if (!isset($variables)) { $variables = new \stdClass(); } // Set name property if the schema does not define it. if (!isset($variables->name) && !empty($this->schema_name)) { $variables->name = $this->schema_name; } // Set template property if the schema does not define it. if (!isset($variables->template) && ($theme = $this->getTheme())) { $variables->template = $theme; } }
php
{ "resource": "" }
q8215
TranslationToDatabase.getValue
train
private function getValue(array $values, $languages, $group, $parent = NULL) { foreach($values as $key => $value){ foreach($languages as $language){ $entry = Translation::firstOrCreate([ 'key' => $key, 'language' => $language, 'translation_group' => $group->id, 'parent' => $parent ]); if(is_array($value)){ $this->getValue($value, $languages, $group, $entry->id); } else { if($entry->value === NULL){ $entry->value = $value; $entry->save(); } } } } }
php
{ "resource": "" }
q8216
TranslationToDatabase.updateTranslationGroups
train
private function updateTranslationGroups($groupname) { $group = TranslationGroup::firstOrCreate(['name' => $groupname]); array_push($this->translation_groups, $group); }
php
{ "resource": "" }
q8217
Posterize.setLevel
train
public function setLevel($level) { if ($level < 0 || $level > 100) { throw new \InvalidArgumentException(sprintf( 'Invalid Postrize Level "%s"', (string) $level )); } $this->level = (int) $level; return $this; }
php
{ "resource": "" }
q8218
Instancing.&
train
public static function & GetInstance (array $routes = [], $autoInitialize = TRUE) { if (!self::$instance) { /** @var $app \MvcCore\Application */ $app = & \MvcCore\Application::GetInstance(); self::$routeClass = $app->GetRouteClass(); self::$routerClass = $app->GetRouterClass(); self::$toolClass = $app->GetToolClass(); $routerClass = $app->GetRouterClass(); $instance = new $routerClass($routes, $autoInitialize); $instance->application = & $app; self::$instance = & $instance; } return self::$instance; }
php
{ "resource": "" }
q8219
Models.all
train
public static function all() { $command = 'grep --include="*.php" --files-with-matches -r "class" '.app_path(); exec($command, $files); return collect($files)->map(function($file) { return self::convertFileToClass($file); })->filter(function($class) { return class_exists($class) && is_subclass_of($class, Model::class); }); }
php
{ "resource": "" }
q8220
Models.convertFileToClass
train
private static function convertFileToClass(string $file) { $fh = fopen($file, 'r'); $namespace = ''; while(($line = fgets($fh, 5000)) !== false) { if (str_contains($line, 'namespace')) { $namespace = trim(str_replace(['namespace', ';'], '', $line)); break; } } fclose($fh); $class = basename(str_replace('.php', '', $file)); return $namespace.'\\'.$class; }
php
{ "resource": "" }
q8221
Models.utf8EncodeModel
train
public static function utf8EncodeModel(Model $model) { foreach($model->toArray() as $key => $value) { if (is_numeric($value) || !is_string($value)) { continue; } $model->$key = utf8_encode($value); } return $model; }
php
{ "resource": "" }
q8222
Models.getNextId
train
public static function getNextId(Model $model) { $statement = DB::select('show table status like \''.$model->getTable().'\''); if (!isset($statement[0]) || !isset($statement[0]->Auto_increment)) { throw new \Exception('Unable to retrieve next auto-increment id for this model.'); } return (int) $statement[0]->Auto_increment; }
php
{ "resource": "" }
q8223
Models.areRelated
train
public static function areRelated(...$relations) { try { $max_key = count($relations) - 1; foreach ($relations as $key => $current) { if (!is_array($current)) { $previous = null; if ($key > 0) { $previous = $relations[ $key - 1 ]; $previous = is_array($previous) ? $previous[ 0 ] : $previous; } $basename = strtolower(class_basename($current)); $method = Str::plural($basename); if (!is_null($previous)) { if (!method_exists($previous, $method)) { $method = Str::singular($basename); } if (!method_exists($previous, $method)) { throw new \Exception('UNABLE_TO_FIND_RELATIONSHIP'); } } $relations[ $key ] = [ $current, $method ]; } if (!($relations[ $key ][ 0 ] instanceof Model)) { throw new \InvalidArgumentException('INVALID_MODEL'); } } foreach ($relations as $key => $current) { if ($key !== $max_key) { $model = $current[ 0 ]; $relation = $relations[ $key + 1 ]; $model->{$relation[ 1 ]}()->findOrFail($relation[ 0 ]->id); } } return true; } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return false; } }
php
{ "resource": "" }
q8224
Content.IsXmlOutput
train
public function IsXmlOutput () { if (isset($this->headers['Content-Type'])) { $value = $this->headers['Content-Type']; return strpos($value, 'xml') !== FALSE; } return FALSE; }
php
{ "resource": "" }
q8225
Content.Send
train
public function Send () { if ($this->IsSent()) return; $httpVersion = $this->GetHttpVersion(); $code = $this->GetCode(); $status = $this->codeMessage !== NULL ? ' '.$this->codeMessage : (isset(static::$codeMessages[$code]) ? ' '.static::$codeMessages[$code] : ''); if (!isset($this->headers['Content-Encoding'])) { if (!$this->encoding) $this->encoding = 'utf-8'; $this->headers['Content-Encoding'] = $this->encoding; } $this->UpdateHeaders(); header($httpVersion . ' ' . $code . $status); header('Host: ' . $this->request->GetHost()); foreach ($this->headers as $name => $value) { if ($name == 'Content-Type') { $charsetMatched = FALSE; $charsetPos = strpos($value, 'charset'); if ($charsetPos !== FALSE) { $equalPos = strpos($value, '=', $charsetPos); if ($equalPos !== FALSE) $charsetMatched = TRUE; } if (!$charsetMatched) $value .= ';charset=' . $this->encoding; } if (isset($this->disabledHeaders[$name])) { header_remove($name); } else { header($name . ": " . $value); } } foreach ($this->disabledHeaders as $name => $b) header_remove($name); $this->addTimeAndMemoryHeader(); echo $this->body; if (ob_get_level()) echo ob_get_clean(); flush(); $this->sent = TRUE; }
php
{ "resource": "" }
q8226
MelisSiteTable.getSites
train
public function getSites($env = '', $includeSite404Table = false) { $select = $this->tableGateway->getSql()->select(); $select->columns(array('*')); if($includeSite404Table) { $select->join('melis_cms_site_domain', 'melis_cms_site_domain.sdom_site_id = melis_cms_site.site_id', array('*'), $select::JOIN_LEFT) ->join('melis_cms_site_404', 'melis_cms_site_404.s404_site_id = melis_cms_site.site_id', array('*'), $select::JOIN_LEFT); } else { $select->join('melis_cms_site_domain', 'melis_cms_site_domain.sdom_site_id = melis_cms_site.site_id', array('*'), $select::JOIN_LEFT); } if ($env != '') $select->where("sdom_env = '$env'"); $resultSet = $this->tableGateway->selectWith($select); return $resultSet; }
php
{ "resource": "" }
q8227
MelisSiteTable.getSiteById
train
public function getSiteById($idSite, $env, $includeSite404Table = false) { // Retrieve cache version if front mode to avoid multiple calls $cacheKey = get_class($this) . '_getSiteById_' . $idSite . '_' . $env . '_' . $includeSite404Table; $cacheConfig = 'engine_page_services'; $melisEngineCacheSystem = $this->getServiceLocator()->get('MelisEngineCacheSystem'); $results = $melisEngineCacheSystem->getCacheByKey($cacheKey, $cacheConfig); if (!empty($results)) return $results; $select = $this->tableGateway->getSql()->select(); $select->columns(array('*')); $siteDomainjoin = new Expression('melis_cms_site_domain.sdom_site_id = melis_cms_site.site_id AND sdom_env =\''.$env.'\''); if($includeSite404Table) { $site404join = new Expression('melis_cms_site_domain.sdom_site_id = melis_cms_site.site_id'); $select->join('melis_cms_site_domain', $siteDomainjoin, array('*'), $select::JOIN_LEFT) ->join('melis_cms_site_404', $site404join, array('*'), $select::JOIN_LEFT); } else { $select->join('melis_cms_site_domain', $siteDomainjoin, array('*'), $select::JOIN_LEFT); } $select->where('site_id ='.$idSite); $resultSet = $this->tableGateway->selectWith($select); $melisEngineCacheSystem->setCacheByKey($cacheKey, $cacheConfig, $resultSet); return $resultSet; }
php
{ "resource": "" }
q8228
Png.setFilter
train
public function setFilter($filter) { $validFilters = self::NO_FILTER | self::FILTER_NONE | self::FILTER_SUB | self::FILTER_UP | self::FILTER_AVG | self::FILTER_PAETH | self::ALL_FILTERS; $filter = $filter & $validFilters; $this->filter = (integer) $filter; return $this; }
php
{ "resource": "" }
q8229
Png.isPngFile
train
public static function isPngFile($filename) { try { $image = new ImageFile($filename); if (strtolower($image->getMime()) !== @image_type_to_mime_type(IMAGETYPE_PNG)) { return false; } return true; } catch (\RuntimeException $ex) { return false; } }
php
{ "resource": "" }
q8230
Png.saveAlpha
train
protected function saveAlpha(Png $png, $flag) { if ($flag) { $png->alphaBlending(false); if (false == @imagesavealpha($png->getHandler(), $flag)) { throw new CanvasException(sprintf( 'Faild Saving The Alpha Channel Information To The Png Canvas "%s"' , (string) $this )); } } return $this; }
php
{ "resource": "" }
q8231
Image.getResizedFilename
train
protected function getResizedFilename( $filepath, $width, $height, $crop ) { $filename = basename( $filepath ); // match filename extension with dot // only the last extension will match when there are multiple ones $extension_pattern = '/(\.[^\.]+)$/'; // add width, height and crop to filename $replacement = '-' . $width . 'x' . $height . ( $crop ? '-cropped' : '' ) . '$1'; return preg_replace( $extension_pattern, $replacement, $filename ); }
php
{ "resource": "" }
q8232
Image.store
train
protected function store( $source, $destination, $width, $height, $crop ) { if ( file_exists( $destination ) ) { return $destination; } $editor = wp_get_image_editor( $source ); if ( is_wp_error( $editor ) ) { return ''; } $editor->resize( $width, $height, $crop ); $editor->save( $destination ); return $destination; }
php
{ "resource": "" }
q8233
DirectoryMethods.GetCurrentViewFullPath
train
public function GetCurrentViewFullPath () { $result = NULL; $renderedFullPaths = & $this->__protected['renderedFullPaths']; $count = count($renderedFullPaths); if ($count > 0) $result = $renderedFullPaths[$count - 1]; return $result; }
php
{ "resource": "" }
q8234
DirectoryMethods.GetCurrentViewDirectory
train
public function GetCurrentViewDirectory () { $result = $this->GetCurrentViewFullPath(); $lastSlashPos = mb_strrpos($result, '/'); if ($lastSlashPos !== FALSE) { $result = mb_substr($result, 0, $lastSlashPos); } return $result; }
php
{ "resource": "" }
q8235
AttributeBag.withAttribute
train
public function withAttribute(string $offset, $value) : self { if ($this->restricted) { if (!in_array($offset, array_keys($this->attributes))) { $message = sprintf('%s it not an allowed attribute on this object. The only allowed attributes are %s', $offset, implode(',', array_keys($this->attributes))); throw new \InvalidArgumentException($message); } } $that = clone($this); $that->attributes[$offset] = $value; return $that; }
php
{ "resource": "" }
q8236
TranslatorBuilder.build
train
public function build() { $fixer = new VendorDirectoryFixer(); // Set up the Translation component $translator = new Translator($this->locale); $pos = strpos($this->locale, '_'); $file = 'validators.' . ($pos ? substr($this->locale, 0, $pos) : $this->locale) . '.xlf'; $translator->addLoader('xlf', new XliffFileLoader()); $translator->addResource( 'xlf', $fixer->getLocation('form', self::FORM_TRANSLATIONS_DIR . $file), $this->locale, self::TRANSLATION_DOMAIN ); $translator->addResource( 'xlf', $fixer->getLocation('validator', self::VALIDATOR_TRANSLATIONS_DIR . $file), $this->locale, self::TRANSLATION_DOMAIN ); return $translator; }
php
{ "resource": "" }
q8237
MelisSite404Table.getDataBySiteIdAndPageId
train
public function getDataBySiteIdAndPageId($siteId, $pageId) { $select = $this->tableGateway->getSql()->select(); $select->columns(array('*')); $select->where(array("s404_site_id" => $siteId, 's404_page_id' => $pageId)); $resultSet = $this->tableGateway->selectWith($select); return $resultSet; }
php
{ "resource": "" }
q8238
APIRequest.has
train
public function has($key) { if ($this->needParser()) { $this->treatPutRequest(); return array_key_exists($key, $_REQUEST); } return parent::has($key); }
php
{ "resource": "" }
q8239
AbstractCanvas.isValidFile
train
protected function isValidFile($file) { if (!is_file($file) || !is_readable($file)) { throw new \InvalidArgumentException(sprintf( 'File "%s" Is Not Readable', (string) $file )); } }
php
{ "resource": "" }
q8240
AbstractCanvas.preserveAlpha
train
protected function preserveAlpha($dest, $src) { $transparent = @imagecolortransparent($src); if (-1 != $transparent) { $color = @imagecolorsforindex($src, $transparent); $allocated = @imagecolorallocatealpha( $dest , $color['red'] , $color['green'] , $color['blue'] , $color['alpha'] ); @imagecolortransparent($dest, $allocated); @imagefill($dest, 0, 0, $allocated); } }
php
{ "resource": "" }
q8241
Profiler.extend
train
public function extend(Contracts\Listener $listener): self { $listener->handle($this->getLogger()); return $this; }
php
{ "resource": "" }
q8242
ZmqSocket.handleEvent
train
public function handleEvent() { while ($this->socket !== null) { $events = $this->socket->getSockOpt(ZMQ::SOCKOPT_EVENTS); $hasEvents = ($events & ZMQ::POLL_IN) || ($events & ZMQ::POLL_OUT && $this->buffer->listening); if (!$hasEvents) { break; } if ($events & ZMQ::POLL_IN) { $this->handleReadEvent(); } if ($events & ZMQ::POLL_OUT && $this->buffer->listening) { $this->buffer->handleWriteEvent(); } } }
php
{ "resource": "" }
q8243
ZmqSocket.handleReadEvent
train
public function handleReadEvent() { $messages = $this->socket->recvmulti(ZMQ::MODE_DONTWAIT); if (false !== $messages) { $this->emit('messages', [ $messages ]); } }
php
{ "resource": "" }
q8244
ZmqSocket.close
train
public function close() { if ($this->closed) { return; } $this->emit('end', [ $this ]); $this->loop->removeStream($this->fd); $this->buffer->flushListeners(); $this->flushListeners(); unset($this->socket); $this->closed = true; }
php
{ "resource": "" }
q8245
EdgeDetection.setType
train
public function setType($type, $divisor = 1.0, $offset = 0.0) { if (!array_key_exists($type, self::$SUPPORTED_TYPES)) { throw new \InvalidArgumentException('Invalid Edge Type'); } $this->type = $type; $this->divisor = $divisor; $this->offset = $offset; return $this; }
php
{ "resource": "" }
q8246
CssoFilter.filterLoad
train
public function filterLoad(AssetInterface $asset) { $inputFile = tempnam(sys_get_temp_dir(), 'csso'); file_put_contents($inputFile, $asset->getContent()); // Before we create our process builder we'll create the arguments to be given to the builder. // If we have a node bin supplied then we'll shift that to the beginning of the array. $builderArguments = array($this->cssoBin); if ( ! is_null($this->nodeBin)) { array_unshift($builderArguments, $this->nodeBin); } $builder = $this->createProcessBuilder($builderArguments); $builder->add($inputFile); // Get the process from the builder and run the process. $process = $builder->getProcess(); $code = $process->run(); unlink($inputFile); if ($code !== 0) { throw FilterException::fromProcess($process)->setInput($asset->getContent()); } $asset->setContent($process->getOutput()); }
php
{ "resource": "" }
q8247
FileCacheClassLoader.saveCacheFile
train
public function saveCacheFile() { if ($this->store !== null) { file_put_contents($this->cacheFile, $this->createCache($this->store), LOCK_EX); $this->store = null; } }
php
{ "resource": "" }
q8248
FileCacheClassLoader.storeCache
train
public function storeCache(array $cache) { if ($this->store === null) { register_shutdown_function([$this, 'saveCacheFile']); } $this->store = $cache; }
php
{ "resource": "" }
q8249
FileCacheClassLoader.createCache
train
private function createCache(array $cache) { ksort($cache); $format = "\t%s => %s," . PHP_EOL; $rows = []; foreach ($cache as $key => $value) { $rows[] = sprintf($format, var_export($key, true), var_export($value, true)); } return sprintf('<?php return [%s];' . PHP_EOL, PHP_EOL . implode('', $rows)); }
php
{ "resource": "" }
q8250
Filterable.apply
train
public function apply($filter, Closure $callback = null) { // If the supplied filter is an array then we'll treat it as an array of filters that are // to be applied to the resource. if (is_array($filter)) { return $this->applyFromArray($filter); } $filter = $this->factory->get('filter')->make($filter)->setResource($this); is_callable($callback) and call_user_func($callback, $filter); return $this->filters[$filter->getFilter()] = $filter; }
php
{ "resource": "" }
q8251
Filterable.applyFromArray
train
public function applyFromArray($filters) { foreach ($filters as $key => $value) { $filter = $this->factory->get('filter')->make(is_callable($value) ? $key : $value)->setResource($this); is_callable($value) and call_user_func($value, $filter); $this->filters[$filter->getFilter()] = $filter; } return $this; }
php
{ "resource": "" }
q8252
MelisSearchService.createIndex
train
public function createIndex($moduleName, $pageId, $exclude = array(), $_defaultPath = self::FOLDER_PATH) { $this->tmpLogs = ''; $pageContent = ''; $folderPath = $_defaultPath . $moduleName; $lucenePath = $folderPath. '/' .self::FOLDER_NAME; // check if the module exists if(file_exists($folderPath)) { // check if the path exists if(!file_exists($lucenePath)) { $this->createDir($lucenePath); $this->tmpLogs = $this->createIndexForPages($lucenePath, $pageId, $exclude); } else { $this->changePermission($lucenePath); $this->tmpLogs = $this->createIndexForPages($lucenePath, $pageId, $exclude); } } return $this->tmpLogs; }
php
{ "resource": "" }
q8253
MelisSearchService.clearIndex
train
public function clearIndex($dir) { $success = 0; if (!file_exists($dir)) { $success = 1; } if (!is_dir($dir)) { return @unlink($dir); } foreach (scandir($dir) as $item) { if ($item == '.' || $item == '..') { continue; } if (!$this->clearIndex($dir . DIRECTORY_SEPARATOR . $item)) { $success = 0; } } $sucess = @rmdir($dir); return $sucess; }
php
{ "resource": "" }
q8254
MelisSearchService.optimizeIndex
train
public function optimizeIndex($moduleName) { $translator = $this->getServiceLocator()->get('translator'); $status = $translator->translate('tr_melis_engine_search_optimize'); $lucenePath = self::FOLDER_PATH.$moduleName.'/'.self::FOLDER_NAME . '/indexes'; if(file_exists($lucenePath) && is_readable($lucenePath)) { $index = Lucene::open($lucenePath); $index->optimize(); } return $status; }
php
{ "resource": "" }
q8255
MelisSearchService.setSearchResultsAsXml
train
protected function setSearchResultsAsXml($searchValue, $searchResults) { $pagePublishTable = $this->getServiceLocator()->get('MelisEngineTablePagePublished'); $pageLangTbl = $this->getServiceLocator()->get('MelisEngineTablePageLang'); $cmsLangTbl = $this->getServiceLocator()->get('MelisEngineTableCmsLang'); $pageTreeSvc = $this->getServiceLocator()->get('MelisEngineTree'); $xmlContent = '<?xml version="1.0" encoding="UTF-8"?>'; $xmlContent.= '<document type="MelisSearchResults" author="MelisTechnology" version="2.0">'; $xmlContent.= '<searchQuery>'.$searchValue.'</searchQuery>'; $lastEditedDate = null; $pageStatus = null; $totalResults = 0; foreach($searchResults as $result) { $pageData = $pagePublishTable->getEntryById($result->page_id)->current(); $pageLangId = $pageLangTbl->getEntryByField('plang_page_id',(int) $result->page_id )->current(); $pageUrl = $pageTreeSvc->getPageLink($result->page_id,true); $pageLangId = $pageLangId->plang_lang_id; $pageLangLocale = $cmsLangTbl->getEntryById($pageLangId)->current(); $pageLangLocale = $pageLangLocale->lang_cms_locale; if($pageData) { $lastEditedDate = $pageData->page_edit_date; $pageStatus = $pageData->page_status; } $description = $this->limitedText($result->description); $xmlContent .= '<result>'; $xmlContent .= ' <score>' . round($result->score, 2, PHP_ROUND_HALF_EVEN) . '</score>'; $xmlContent .= ' <pageStatus>' . $pageStatus .'</pageStatus>'; $xmlContent .= ' <url>' . $pageUrl .'</url>'; $xmlContent .= ' <pageId>' . $result->page_id .'</pageId>'; $xmlContent .= ' <pageName>' . $result->page_name .'</pageName>'; $xmlContent .= ' <pageLangId>' . $pageLangId .'</pageLangId>'; $xmlContent .= ' <pageLangLocale>' . $pageLangLocale .'</pageLangLocale>'; $xmlContent .= ' <lastPageEdit>' . $lastEditedDate .'</lastPageEdit>'; $xmlContent .= ' <description>' . $description .'</description>'; $xmlContent .= '</result>'; $totalResults++; } $xmlContent.= '<totalResults>'.$totalResults.'</totalResults>'; $xmlContent.= '</document>'; return $xmlContent; }
php
{ "resource": "" }
q8256
MelisSearchService.createDocument
train
protected function createDocument($data = array()) { $enginePage = $this->getServiceLocator()->get('MelisEngineTree'); $translator = $this->getServiceLocator()->get('translator'); $pageSvc = $this->getServiceLocator()->get('MelisEnginePage'); $doc = new Document(); if(is_array($data)) { $uri = $enginePage->getPageLink($data['page_id'], true); $pattern = '/(http|https)\:\/\/(www\.)?[a-zA-Z0-9-_.]+(\.([a-z.])?)*/'; $domain = $this->getCurrentDomain(); if($domain === '/'){ echo getenv('MELIS_PLATFORM') . " configuration is incorrect or does not exists in db"; die; } if(!preg_match($pattern, $uri)) { $uri = $domain . $uri; } #$pageContent = $this->getUrlContent($uri) -- old ; $pageId = $data['page_id'] ?? null; $pageData = $pageSvc->getDatasPage($pageId); $melisPageTree = $pageData->getMelisPageTree(); $pageContent = $melisPageTree->page_content; if($pageContent) { $doc->addField(Document\Field::Text('description', $enginePage->cleanString($this->getHtmlDescription($pageContent)))); $doc->addField(Document\Field::Keyword('url', $uri)); $doc->addField(Document\Field::Keyword('page_id', $data['page_id'])); $doc->addField(Document\Field::Keyword('page_name', $data['page_name'])); $doc->addField(Document\Field::UnStored('contents', $pageContent)); $this->tmpLogs .= 'OK ' . sprintf($translator->translate('tr_melis_engine_search_create_index'), $data['page_id']) . sprintf($translator->translate('tr_melis_engine_search_create_index_success'), $uri) . PHP_EOL . '<br/>'; } else { $this->tmpLogs .= 'KO ' . sprintf($translator->translate('tr_melis_engine_search_create_index'), $data['page_id']) . $translator->translate('tr_melis_engine_search_create_index_fail_unreachable') . ', ' . $uri . PHP_EOL . '<br/>'; $this->unreachableCount++; } } return $doc; }
php
{ "resource": "" }
q8257
MelisSearchService.getHtmlDescription
train
protected function getHtmlDescription($html) { $content = ''; $doc = new \DOMDocument; @$doc->loadHTML($html); $xpath = new \DOMXPath($doc); $query = '//p[preceding-sibling::p]'; foreach ($xpath->query($query) as $node) { $content .= trim($node->textContent, PHP_EOL); } return $content; }
php
{ "resource": "" }
q8258
MelisSearchService.getUrlContent
train
protected function getUrlContent($url) { $contents = ''; $time = (int) self::MAX_TIMEOUT_MINS * 60; $timeout = stream_context_create(array( 'http' => array( 'timeout' => $time, ), )); set_time_limit($time); ini_set('max_execution_time', $time); // check if the URL is valid if($this->isValidUrl($url)) { // make sure we are not getting 404 when accessing the page if( (int) $this->getUrlStatus($url) != self::HTTP_NOT_OK ) { // ge the contents of the page $contents = @file_get_contents($url, false, $timeout); // if the contents has results if($contents === true) { // convert encodings $contents = mb_convert_encoding($contents, 'HTML-ENTITIES', self::ENCODING); } } } return $contents; }
php
{ "resource": "" }
q8259
MelisSearchService.getUrlStatus
train
protected function getUrlStatus($url) { if($this->isValidUrl($url)) { ini_set('allow_url_fopen', 1); $url = @get_headers($url, 1); if($url) { $status = explode(' ',$url[0]); return (int) $status[1]; } } else { return 404; } }
php
{ "resource": "" }
q8260
MelisSearchService.createDir
train
protected function createDir($path) { $status = false; if(!file_exists($path)) { $oldmask = umask(0); mkdir($path, 0755); umask($oldmask); // check if the directory is readable and writable $status = $this->changePermission($path); } else { $status = $this->changePermission($path); } return $status; }
php
{ "resource": "" }
q8261
MelisSearchService.changePermission
train
protected function changePermission($path, $octal = 0755) { $status = false; if(!is_writable($path)) chmod($path, $octal); if(!is_readable($path)) chmod($path, $octal); if(is_readable($path) && is_writable($path)) $status = true; return $status; }
php
{ "resource": "" }
q8262
MelisSearchService.limitedText
train
protected function limitedText($text, $limit = 200) { $postString = '...'; $strCount = strlen(trim($text)); $sLimitedText = $text; if($strCount > $limit) { $sLimitedText = substr($text, 0, $limit) . $postString; } return $sLimitedText; }
php
{ "resource": "" }
q8263
MelisSearchService.isValidUrl
train
protected function isValidUrl($url) { $valid = false; $parseUrl = parse_url($url); if(isset($parseUrl['host']) || !empty($parseUrl['host'])) { $uri = new \Zend\Validator\Uri(); if ($uri->isValid($url)) { $valid = true; } else { $valid = false; } } return $valid; }
php
{ "resource": "" }
q8264
Common.expandNumber
train
public function expandNumber($number) { switch (strtoupper(substr($number, -1))) { case 'B': $multiplier = 1000000000; break; case 'M': $multiplier = 1000000; break; case 'K': $multiplier = 1000; break; default: $multiplier = 1; } return (int) intval($number) * $multiplier; }
php
{ "resource": "" }
q8265
Common.shortenNumber
train
public function shortenNumber($number) { $abbr = [9 => 'B', 6 => 'M', 3 => 'K']; foreach ($abbr as $exponent => $suffix) { if ($number >= pow(10, $exponent)) { return intval($number / pow(10, $exponent)) . $suffix; } } return $number; }
php
{ "resource": "" }
q8266
Common.xpTolevel
train
public function xpTolevel($xp) { $modifier = 0; for ($i = 1; $i <= 126; $i++) { $modifier += floor($i + 300 * pow(2, ($i / 7))); $level = floor($modifier / 4); if ($xp < $level) { return $i; } } // Return the maximum possible level return 126; }
php
{ "resource": "" }
q8267
Common.levelToXp
train
public function levelToXp($level) { $xp = 0; for ($i = 1; $i < $level; $i++) { $xp += floor($i + 300 * pow(2, ($i / 7))); } $xp = floor($xp / 4); // Check if our value is above 200m, if so return 200m, otherwise our value return ($xp > 200000000 ? 200000000 : $xp); }
php
{ "resource": "" }
q8268
Handlers.Dump
train
public static function Dump ($value, $return = FALSE, $exit = FALSE) { if (static::$originalDebugClass) { $options = ['bar' => FALSE, 'backtraceIndex' => 1]; if ($exit) $options['lastDump'] = TRUE; $dumpedValue = static::dumpHandler($value, NULL, $options); } else { $dumpedValue = @call_user_func(static::$handlers['dump'], $value, $return); } if ($return) return $dumpedValue; if (static::$debugging) { echo $dumpedValue; } else { static::storeLogRecord($dumpedValue, \MvcCore\IDebug::DEBUG); } return $value; }
php
{ "resource": "" }
q8269
Handlers.BarDump
train
public static function BarDump ($value, $title = NULL, $options = []) { if (static::$originalDebugClass) { if (!isset($options['backtraceIndex'])) $options['backtraceIndex'] = 1; $options['bar'] = static::$debugging; $dumpedValue = static::dumpHandler($value, $title, $options); } else { $dumpedValue = @call_user_func_array(static::$handlers['barDump'], func_get_args()); } if (!static::$debugging) static::storeLogRecord($dumpedValue, \MvcCore\IDebug::DEBUG); return $value; }
php
{ "resource": "" }
q8270
Handlers.Exception
train
public static function Exception ($exception, $exit = TRUE) { if (static::$originalDebugClass) { $dumpedValue = static::dumpHandler( $exception, NULL, ['bar' => !$exit, 'backtraceIndex' => 1] ); if (static::$debugging) { echo $dumpedValue; } else { static::storeLogRecord($dumpedValue, \MvcCore\IDebug::EXCEPTION); } } else { @call_user_func_array(static::$handlers['exceptionHandler'], func_get_args()); } }
php
{ "resource": "" }
q8271
Handlers.storeLogRecord
train
protected static function storeLogRecord ($value, $priority) { $content = date('[Y-m-d H-i-s]') . "\n" . $value; $content = preg_replace("#\n(\s)#", "\n\t$1", $content) . "\n"; if (!static::$logDirectoryInitialized) static::initLogDirectory(); $fullPath = static::$LogDirectory . '/' . $priority . '.log'; file_put_contents($fullPath, $content, FILE_APPEND); return $fullPath; }
php
{ "resource": "" }
q8272
Handlers.formatDebugDumps
train
protected static function formatDebugDumps () { $dumps = ''; $lastDump = FALSE; $app = static::$app ?: (static::$app = & \MvcCore\Application::GetInstance()); $appRoot = $app->GetRequest()->GetAppRoot(); foreach (self::$dumps as $values) { list($dumpResult, $lastDumpLocal) = self::formatDebugDump($values, $appRoot); $dumps .= $dumpResult; if ($lastDumpLocal) $lastDump = $lastDumpLocal; } return [$dumps, $lastDump]; }
php
{ "resource": "" }
q8273
Handlers.formatDebugDump
train
protected static function formatDebugDump ($dumpRecord, $appRoot = NULL) { $result = ''; $lastDump = FALSE; if ($appRoot === NULL) { $app = static::$app ?: (static::$app = & \MvcCore\Application::GetInstance()); $appRoot = $app->GetRequest()->GetAppRoot(); } $options = $dumpRecord[2]; $result .= '<div class="item">'; if ($dumpRecord[1] !== NULL) $result .= '<pre class="title">'.$dumpRecord[1].'</pre>'; $file = $options['file']; $line = $options['line']; $displayedFile = str_replace('\\', '/', $file); if (strpos($displayedFile, $appRoot) === 0) { $displayedFile = substr($displayedFile, strlen($appRoot)); } $link = '<a class="editor" href="editor://open/?file=' .rawurlencode($file).'&amp;line='.$line.'">' .$displayedFile.':'.$line .'</a>'; // make array dumps shorter $dump = & $dumpRecord[0]; $dump = preg_replace("#\n(\s+)\<b\>array\</b\>\s([^\n]+)\n(\s+)(\<i\>\<font )([^\>]+)(\>empty)#m", "<b>array</b> $2 $4$5$6", $dump); $dump = preg_replace("#\n(\s+)\<b\>array\</b\>\s([^\n]+)\n(\s+)\.\.\.#m", "<b>array</b> $2 ...", $dump); $dump = preg_replace("#\n(\s+)\<b\>array\</b\>\s([^\n]+)\n#m", "<b>array</b> $2\n", $dump); // make object dumps shorter $dump = preg_replace("#(\<font color='\#)([^']+)'\>\=&gt;\</font\>\s\n\s+([^\n]+)\n\s+\.\.\.#m", "<font color='#$2'>=&gt;</font> $3 ...", $dump); $dump = preg_replace("#\n\s+(.*)\<b\>object\</b\>([^\n]+)\n#m", "$1<b>object</b> $2\n", $dump); $result .= '<div class="value">' .preg_replace("#\[([^\]]*)\]=>([^\n]*)\n(\s*)#", "[$1] => ", str_replace("<required>","&lt;required&gt;",$link.$dump) ) .'</div></div>'; if (isset($dumpRecord[2]['lastDump']) && $dumpRecord[2]['lastDump']) $lastDump = TRUE; return [$result, $lastDump]; }
php
{ "resource": "" }
q8274
Handlers.sendDumpInAjaxHeader
train
protected static function sendDumpInAjaxHeader ($value, $title, $options) { static $ajaxHeadersIndex = 0; $app = static::$app ?: (static::$app = & \MvcCore\Application::GetInstance()); $response = & $app->GetResponse(); list ($dumpStr,) = self::formatDebugDump( [$value, $title, $options], $app->GetRequest()->GetAppRoot() ); $dumpStr64Arr = str_split(base64_encode($dumpStr), 5000); foreach ($dumpStr64Arr as $key => $base64Item) $response->SetHeader( 'X-MvcCore-Debug-' . $ajaxHeadersIndex . '-' . $key, $base64Item ); $ajaxHeadersIndex += 1; $response->SetHeader('X-MvcCore-Debug', $ajaxHeadersIndex); }
php
{ "resource": "" }
q8275
Handlers.isHtmlResponse
train
protected static function isHtmlResponse () { $app = static::$app ?: (static::$app = & \MvcCore\Application::GetInstance()); $request = & $app->GetRequest(); if ($request->IsInternalRequest()) return FALSE; $response = & $app->GetResponse(); return $response->HasHeader('Content-Type') && $response->IsHtmlOutput(); }
php
{ "resource": "" }
q8276
HtmlPage.withAttributeHelper
train
private function withAttributeHelper(string $collection, string $key, string $value) { $newAttributes = $this->$collection->withAttribute($key, $value); $that = clone($this); $that->$collection = $newAttributes; return $that; }
php
{ "resource": "" }
q8277
HttpClient.appendQuery
train
protected static function appendQuery(string $uri, array $query = []): string { if (!empty($query)) { $qs = http_build_query($query); $uri .= (strpos($uri, '?') === false ? '?' : '&').$qs; } return $uri; }
php
{ "resource": "" }
q8278
HttpClient.delete
train
public function delete(string $uri, array $query = [], array $headers = [], array $options = []) { $uri = static::appendQuery($uri, $query); return $this->request(HttpRequest::METHOD_DELETE, $uri, '', $headers, $options); }
php
{ "resource": "" }
q8279
HttpClient.get
train
public function get(string $uri, array $query = [], array $headers = [], $options = []) { $uri = static::appendQuery($uri, $query); return $this->request(HttpRequest::METHOD_GET, $uri, '', $headers, $options); }
php
{ "resource": "" }
q8280
HttpClient.handleErrorResponse
train
public function handleErrorResponse(HttpResponse $response, $options = []) { if ($options['throw'] ?? $this->throwExceptions) { $body = $response->getBody(); if (is_array($body)) { $message = $body['message'] ?? $response->getReasonPhrase(); } else { $message = $response->getReasonPhrase(); } throw new HttpResponseException($response, $message); } }
php
{ "resource": "" }
q8281
HttpClient.head
train
public function head(string $uri, array $query = [], array $headers = [], $options = []) { $uri = static::appendQuery($uri, $query); return $this->request(HttpRequest::METHOD_HEAD, $uri, '', $headers, $options); }
php
{ "resource": "" }
q8282
HttpClient.options
train
public function options(string $uri, array $query = [], array $headers = [], $options = []) { $uri = static::appendQuery($uri, $query); return $this->request(HttpRequest::METHOD_OPTIONS, $uri, '', $headers, $options); }
php
{ "resource": "" }
q8283
HttpClient.patch
train
public function patch(string $uri, $body = [], array $headers = [], $options = []) { return $this->request(HttpRequest::METHOD_PATCH, $uri, $body, $headers, $options); }
php
{ "resource": "" }
q8284
HttpClient.post
train
public function post(string $uri, $body = [], array $headers = [], $options = []) { return $this->request(HttpRequest::METHOD_POST, $uri, $body, $headers, $options); }
php
{ "resource": "" }
q8285
HttpClient.put
train
public function put(string $uri, $body = [], array $headers = [], $options = []) { return $this->request(HttpRequest::METHOD_PUT, $uri, $body, $headers, $options); }
php
{ "resource": "" }
q8286
HttpClient.request
train
public function request(string $method, string $uri, $body, array $headers = [], array $options = []) { $request = $this->createRequest($method, $uri, $body, $headers, $options); // Call the chain of middleware on the request. $response = call_user_func($this->middleware, $request); if (!$response->isResponseClass('2xx')) { $this->handleErrorResponse($response, $options); } return $response; }
php
{ "resource": "" }
q8287
HttpClient.setDefaultHeader
train
public function setDefaultHeader(string $name, string $value) { $this->defaultHeaders[$name] = $value; return $this; }
php
{ "resource": "" }
q8288
HttpClient.addMiddleware
train
public function addMiddleware(callable $middleware) { $next = $this->middleware; $this->middleware = function (HttpRequest $request) use ($middleware, $next): HttpResponse { return $middleware($request, $next); }; return $this; }
php
{ "resource": "" }
q8289
MelisEngineCacheSystemService.isCacheConfActive
train
public function isCacheConfActive($confCache) { $active = true; $config = $this->getServiceLocator()->get('config'); if (!empty($config['caches']) && !empty($config['caches'][$confCache])) { $conf = $config['caches'][$confCache]; if (isset($conf['active'])) $active = $conf['active']; } return $active; }
php
{ "resource": "" }
q8290
MelisEngineCacheSystemService.getTtlByKey
train
public function getTtlByKey($confCache, $cacheKey) { $ttl = 0; $config = $this->getServiceLocator()->get('config'); if (!empty($config['caches']) && !empty($config['caches'][$confCache])) { $conf = $config['caches'][$confCache]; // Get default ttl from adapater config if (!empty($conf['adapter']['options']['ttl'])) $ttl = $conf['adapter']['options']['ttl']; foreach ($conf['ttls'] as $nameKey => $tll) { preg_match("/$nameKey/", $cacheKey, $matches, PREG_OFFSET_CAPTURE, 3); if (count($matches) > 0) { $ttl = $conf['ttls'][$nameKey]; break; } } } return $ttl; }
php
{ "resource": "" }
q8291
VerifierPresenterTrait.tryCall
train
protected function tryCall($method, array $parameters): bool { $called = parent::tryCall($method, $parameters); if (!$called && substr($method, 0, 6) === 'action') { $class = get_class($this); throw new BadRequestException("Action '$class::$method' does not exist."); } return $called; }
php
{ "resource": "" }
q8292
VerifierPresenterTrait.createRequest
train
public function createRequest($component, $destination, array $parameters, $mode) { return parent::createRequest($component, $destination, $parameters, $mode); }
php
{ "resource": "" }
q8293
ButtonDropdownSorter.renderSortButtonDropdown
train
protected function renderSortButtonDropdown() { $attributes = empty($this->attributes) ? array_keys($this->sort->attributes) : $this->attributes; $links = []; foreach ($attributes as $name) { $links[] = Html::tag('li', $this->sort->link($name, [ 'tabindex' => '-1' ])); } if (empty($this->label)) $this->label = 'Sort'; return \yii\bootstrap\ButtonDropdown::widget([ 'label' => $this->label, 'dropdown' => [ 'items' => $links ] ]); }
php
{ "resource": "" }
q8294
Line.setLocation
train
public function setLocation(Coordinate $start, Coordinate $end) { return $this->setStart($start)->setEnd($end); }
php
{ "resource": "" }
q8295
Manifest.get
train
public function get($collection) { $collection = $this->getCollectionNameFromInstance($collection); return isset($this->entries[$collection]) ? $this->entries[$collection] : null; }
php
{ "resource": "" }
q8296
Manifest.make
train
public function make($collection) { $collection = $this->getCollectionNameFromInstance($collection); $this->dirty = true; return $this->get($collection) ?: $this->entries[$collection] = new Entry; }
php
{ "resource": "" }
q8297
Manifest.forget
train
public function forget($collection) { $collection = $this->getCollectionNameFromInstance($collection); if ($this->has($collection)) { $this->dirty = true; unset($this->entries[$collection]); } }
php
{ "resource": "" }
q8298
Manifest.load
train
public function load() { $path = $this->manifestPath.'/collections.json'; if ($this->files->exists($path) and is_array($manifest = json_decode($this->files->get($path), true))) { foreach ($manifest as $key => $entry) { $entry = new Entry($entry['fingerprints'], $entry['development']); $this->entries->put($key, $entry); } } }
php
{ "resource": "" }
q8299
Manifest.save
train
public function save() { if ($this->dirty) { $path = $this->manifestPath.'/collections.json'; $this->dirty = false; return (bool) $this->files->put($path, $this->entries->toJson()); } return false; }
php
{ "resource": "" }