_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2300 | Install.checkPermission | train | protected function checkPermission(OutputInterface $output)
{
$output->writeln(array(
"Checking some permissions"
));
/** @var Translator $translator */
$translator = $this->getContainer()->get('thelia.translator');
$permissions = new CheckPermission(false, $translator);
$isValid = $permissions->exec();
foreach ($permissions->getValidationMessages() as $item => $data) {
if ($data['status']) {
$output->writeln(
array(
sprintf(
"<info>%s ...</info> %s",
$data['text'],
"<info>Ok</info>"
)
)
);
} else {
$output->writeln(array(
sprintf(
"<error>%s </error>%s",
$data['text'],
sprintf("<error>%s</error>", $data["hint"])
)
));
}
}
if (false === $isValid) {
throw new \RuntimeException('Please put correct permissions and reload install process');
}
} | php | {
"resource": ""
} |
q2301 | Install.createConfigFile | train | protected function createConfigFile($connectionInfo)
{
$fs = new Filesystem();
$sampleConfigFile = THELIA_CONF_DIR . "database.yml.sample";
$configFile = THELIA_CONF_DIR . "database.yml";
$fs->copy($sampleConfigFile, $configFile, true);
$configContent = file_get_contents($configFile);
$configContent = str_replace("%DRIVER%", "mysql", $configContent);
$configContent = str_replace("%USERNAME%", $connectionInfo["username"], $configContent);
$configContent = str_replace("%PASSWORD%", $connectionInfo["password"], $configContent);
$configContent = str_replace(
"%DSN%",
sprintf("mysql:host=%s;dbname=%s;port=%s", $connectionInfo["host"], $connectionInfo["dbName"], $connectionInfo['port']),
$configContent
);
file_put_contents($configFile, $configContent);
$fs->remove($this->getContainer()->getParameter("kernel.cache_dir"));
} | php | {
"resource": ""
} |
q2302 | Install.tryConnection | train | protected function tryConnection($connectionInfo, OutputInterface $output)
{
if (\is_null($connectionInfo["dbName"])) {
return false;
}
$dsn = "mysql:host=%s;port=%s";
try {
$connection = new \PDO(
sprintf($dsn, $connectionInfo["host"], $connectionInfo["port"]),
$connectionInfo["username"],
$connectionInfo["password"]
);
$connection->query('SET NAMES \'UTF8\'');
} catch (\PDOException $e) {
$output->writeln(array(
"<error>Wrong connection information</error>"
));
return false;
}
return $connection;
} | php | {
"resource": ""
} |
q2303 | Version.setVersion | train | public function setVersion() {
$wp_filesystem = self::getWpFilesystem();
// Get installed composer package data.
$installedFile = wp_normalize_path( realpath( __DIR__ . '/../../../../' ) ) . '/composer/installed.json';
if ( 'direct' === get_filesystem_method() ) {
$file = $wp_filesystem->get_contents( $installedFile );
} else {
$installedUrl = str_replace( ABSPATH, get_site_url() . '/', $installedFile );
$file = wp_remote_retrieve_body( wp_remote_get( $installedUrl ) );
}
$installed = json_decode( $file, true );
// Check for dep's installed version.
$version = null;
if ( $installed ) {
foreach( $installed as $key => $value ) {
if ( $value['name'] === $this->getDependency() ) {
$version = $value['version_normalized'];
break;
}
}
}
return $version;
} | php | {
"resource": ""
} |
q2304 | ClassFactory.create | train | public static function create(string $configType, ClassType $classType, array $options = [])
{
$classType = (string)$classType;
$classMapVersion = empty($options['classMapVersion']) ? Configure::read('ModuleConfig.classMapVersion') : (string)$options['classMapVersion'];
$classMap = empty($options['classMap'][$classMapVersion]) ? Configure::read('ModuleConfig.classMap.' . $classMapVersion) : (array)$options['classMap'][$classMapVersion];
if (empty($classMap[$configType][$classType])) {
throw new InvalidArgumentException("No [$classType] found for configuration type [$configType] in class map version [$classMapVersion]");
}
$className = $classMap[$configType][$classType];
$params = $options['classArgs'] ?? [];
$result = static::getInstance($className, $params);
return $result;
} | php | {
"resource": ""
} |
q2305 | ClassFactory.getInstance | train | public static function getInstance(string $class, array $params = [])
{
if (!class_exists($class)) {
throw new InvalidArgumentException("Class [$class] does not exist");
}
if (empty($params)) {
return new $class;
}
$reflection = new ReflectionClass($class);
return $reflection->newInstanceArgs($params);
} | php | {
"resource": ""
} |
q2306 | JavaScriptAssetHandlerConnector.includeLanguageJavaScriptFiles | train | public function includeLanguageJavaScriptFiles()
{
$filePath = $this->assetHandlerConnectorManager->getFormzGeneratedFilePath('locale-' . ContextService::get()->getLanguageKey()) . '.js';
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$filePath,
function () {
return $this->getFormzLocalizationJavaScriptAssetHandler()
->injectTranslationsForFormFieldsValidation()
->getJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($filePath));
return $this;
} | php | {
"resource": ""
} |
q2307 | JavaScriptAssetHandlerConnector.generateAndIncludeFormzConfigurationJavaScript | train | public function generateAndIncludeFormzConfigurationJavaScript()
{
$formzConfigurationJavaScriptAssetHandler = $this->getFormzConfigurationJavaScriptAssetHandler();
$fileName = $formzConfigurationJavaScriptAssetHandler->getJavaScriptFileName();
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$fileName,
function () use ($formzConfigurationJavaScriptAssetHandler) {
return $formzConfigurationJavaScriptAssetHandler->getJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($fileName));
return $this;
} | php | {
"resource": ""
} |
q2308 | JavaScriptAssetHandlerConnector.generateAndIncludeJavaScript | train | public function generateAndIncludeJavaScript()
{
$filePath = $this->assetHandlerConnectorManager->getFormzGeneratedFilePath() . '.js';
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$filePath,
function () {
return
// Form initialization code.
$this->getFormInitializationJavaScriptAssetHandler()
->getFormInitializationJavaScriptCode() .
LF .
// Fields validation code.
$this->getFieldsValidationJavaScriptAssetHandler()
->getJavaScriptCode() .
LF .
// Fields activation conditions code.
$this->getFieldsActivationJavaScriptAssetHandler()
->getFieldsActivationJavaScriptCode() .
LF .
// Fields validation activation conditions code.
$this->getFieldsValidationActivationJavaScriptAssetHandler()
->getFieldsValidationActivationJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($filePath));
return $this;
} | php | {
"resource": ""
} |
q2309 | JavaScriptAssetHandlerConnector.generateAndIncludeInlineJavaScript | train | public function generateAndIncludeInlineJavaScript()
{
$formName = $this->assetHandlerFactory->getFormObject()->getName();
$javaScriptCode = $this->getFormRequestDataJavaScriptAssetHandler()
->getFormRequestDataJavaScriptCode();
if (ExtensionService::get()->isInDebugMode()) {
$javaScriptCode .= LF . $this->getDebugActivationCode();
}
$uri = $this->getAjaxUrl();
$javaScriptCode .= LF;
$javaScriptCode .= <<<JS
Fz.setAjaxUrl('$uri');
JS;
$this->addInlineJs('FormZ - Initialization ' . $formName, $javaScriptCode);
return $this;
} | php | {
"resource": ""
} |
q2310 | JavaScriptAssetHandlerConnector.includeJavaScriptValidationAndConditionFiles | train | public function includeJavaScriptValidationAndConditionFiles()
{
$javaScriptValidationFiles = $this->getJavaScriptFiles();
$assetHandlerConnectorStates = $this->assetHandlerConnectorManager
->getAssetHandlerConnectorStates();
foreach ($javaScriptValidationFiles as $file) {
if (false === in_array($file, $assetHandlerConnectorStates->getAlreadyIncludedValidationJavaScriptFiles())) {
$assetHandlerConnectorStates->registerIncludedValidationJavaScriptFiles($file);
$this->includeJsFile(StringService::get()->getResourceRelativePath($file));
}
}
return $this;
} | php | {
"resource": ""
} |
q2311 | JavaScriptAssetHandlerConnector.getJavaScriptFiles | train | protected function getJavaScriptFiles()
{
$formObject = $this->assetHandlerFactory->getFormObject();
$javaScriptFiles = $this->getFieldsValidationJavaScriptAssetHandler()
->getJavaScriptValidationFiles();
$conditionProcessor = $this->getConditionProcessor($formObject);
$javaScriptFiles = array_merge($javaScriptFiles, $conditionProcessor->getJavaScriptFiles());
return $javaScriptFiles;
} | php | {
"resource": ""
} |
q2312 | JavaScriptAssetHandlerConnector.includeJsFile | train | protected function includeJsFile($path)
{
$pageRenderer = $this->assetHandlerConnectorManager->getPageRenderer();
if ($this->environmentService->isEnvironmentInFrontendMode()) {
$pageRenderer->addJsFooterFile($path);
} else {
$pageRenderer->addJsFile($path);
}
} | php | {
"resource": ""
} |
q2313 | Utility.validatePath | train | public static function validatePath(string $path = null): void
{
if (empty($path)) {
throw new InvalidArgumentException("Cannot validate empty path");
}
if (!file_exists($path)) {
throw new InvalidArgumentException("Path does not exist [$path]");
}
if (!is_readable($path)) {
throw new InvalidArgumentException("Path is not readable [$path]");
}
} | php | {
"resource": ""
} |
q2314 | Utility.getControllers | train | public static function getControllers(bool $includePlugins = true): array
{
// get application controllers
$result = static::getDirControllers(APP . 'Controller' . DS);
if ($includePlugins === false) {
return $result;
}
$plugins = Plugin::loaded();
if (!is_array($plugins)) {
return $result;
}
// get plugins controllers
foreach ($plugins as $plugin) {
$path = Plugin::path($plugin) . 'src' . DS . 'Controller' . DS;
$result = array_merge($result, static::getDirControllers($path, $plugin));
}
return $result;
} | php | {
"resource": ""
} |
q2315 | Utility.getApiVersions | train | public static function getApiVersions(string $path = ''): array
{
$apis = [];
$apiPath = (!empty($path)) ? $path : App::path('Controller/Api')[0];
$dir = new Folder();
// get folders in Controller/Api directory
$tree = $dir->tree($apiPath, false, 'dir');
foreach ($tree as $treePath) {
if ($treePath === $apiPath) {
continue;
}
$path = str_replace($apiPath, '', $treePath);
preg_match('/V(\d+)\/V(\d+)/', $path, $matches);
if (empty($matches)) {
continue;
}
unset($matches[0]);
$number = implode('.', $matches);
$apis[] = [
'number' => $number,
'prefix' => self::getApiRoutePrefix($matches),
'path' => self::getApiRoutePath($number),
];
}
if (!empty($apis)) {
$apis = self::sortApiVersions($apis);
}
return $apis;
} | php | {
"resource": ""
} |
q2316 | Utility.getDirControllers | train | public static function getDirControllers(string $path, string $plugin = null, bool $fqcn = true): array
{
$result = [];
try {
static::validatePath($path);
$dir = new DirectoryIterator($path);
} catch (InvalidArgumentException $e) {
return $result;
} catch (UnexpectedValueException $e) {
return $result;
}
foreach ($dir as $fileinfo) {
// skip directories
if (!$fileinfo->isFile()) {
continue;
}
$className = $fileinfo->getBasename('.php');
// skip AppController
if ('AppController' === $className) {
continue;
}
if (!empty($plugin)) {
$className = $plugin . '.' . $className;
}
if ($fqcn) {
$className = App::className($className, 'Controller');
}
if ($className) {
$result[] = $className;
}
}
return $result;
} | php | {
"resource": ""
} |
q2317 | Utility.getModels | train | public static function getModels(string $connectionManager = 'default', bool $excludePhinxlog = true): array
{
$result = [];
$tables = ConnectionManager::get($connectionManager)->getSchemaCollection()->listTables();
if (empty($tables)) {
return $result;
}
foreach ($tables as $table) {
if ($excludePhinxlog && preg_match('/phinxlog/', $table)) {
continue;
}
$result[$table] = Inflector::humanize($table);
}
return $result;
} | php | {
"resource": ""
} |
q2318 | Utility.getModelColumns | train | public static function getModelColumns(string $model = '', string $connectionManager = 'default'): array
{
$result = $columns = [];
if (empty($model)) {
return $result;
}
// making sure that model is in table naming conventions.
$model = Inflector::tableize($model);
try {
$connection = ConnectionManager::get($connectionManager);
$schema = $connection->getSchemaCollection();
$table = $schema->describe($model);
$columns = $table->columns();
} catch (MissingDatasourceConfigException $e) {
return $result;
} catch (Exception $e) {
return $result;
}
// A table with no columns?
if (empty($columns)) {
return $result;
}
foreach ($columns as $column) {
$result[$column] = $column;
}
return $result;
} | php | {
"resource": ""
} |
q2319 | Utility.getColors | train | public static function getColors(array $config = [], bool $pretty = true): array
{
$result = [];
$config = empty($config) ? Configure::read('Colors') : $config;
if (!$pretty) {
return $config;
}
if (!$config) {
return $result;
}
foreach ($config as $k => $v) {
$result[$k] = '<div><div style="width:20px;height:20px;margin:0;border:1px solid #eee;float:left;background:' . $k . ';"></div> ' . $v . '</div><div style="clear:all"></div>';
}
return $result;
} | php | {
"resource": ""
} |
q2320 | Utility.sortApiVersions | train | protected static function sortApiVersions(array $versions = []): array
{
usort($versions, function ($first, $second) {
$firstVersion = (float)$first['number'];
$secondVersion = (float)$second['number'];
if ($firstVersion == $secondVersion) {
return 0;
}
return ($firstVersion > $secondVersion) ? 1 : -1;
});
return $versions;
} | php | {
"resource": ""
} |
q2321 | Core.undefined_function | train | public static function undefined_function( $function_name ) {
if ( \function_exists( $function_name ) ) {
return new \Twig_Function(
$function_name,
function () use ( $function_name ) {
ob_start();
$return = \call_user_func_array( $function_name, \func_get_args() );
$echo = ob_get_clean();
return empty( $echo ) ? $return : $echo;
},
array( 'is_safe' => array( 'all' ) )
);
}
return false;
} | php | {
"resource": ""
} |
q2322 | ConfigurationFactory.getFormzConfiguration | train | public function getFormzConfiguration()
{
$cacheIdentifier = $this->getCacheIdentifier();
if (false === array_key_exists($cacheIdentifier, $this->instances)) {
$this->instances[$cacheIdentifier] = $this->getFormzConfigurationFromCache($cacheIdentifier);
}
return $this->instances[$cacheIdentifier];
} | php | {
"resource": ""
} |
q2323 | ConfigurationFactory.getFormzConfigurationFromCache | train | protected function getFormzConfigurationFromCache($cacheIdentifier)
{
$cacheInstance = CacheService::get()->getCacheInstance();
if ($cacheInstance->has($cacheIdentifier)) {
$instance = $cacheInstance->get($cacheIdentifier);
} else {
$instance = $this->buildFormzConfiguration();
if (false === $instance->getValidationResult()->hasErrors()) {
$cacheInstance->set($cacheIdentifier, $instance);
}
}
return $instance;
} | php | {
"resource": ""
} |
q2324 | FormzException.getNewExceptionInstance | train | final protected static function getNewExceptionInstance($message, $code, array $arguments = [])
{
$exceptionClassName = get_called_class();
return new $exceptionClassName(
vsprintf($message, $arguments),
$code
);
} | php | {
"resource": ""
} |
q2325 | LoggingContentHandler.shouldLog | train | private function shouldLog($event)
{
$level = isset($this->configuration[$event]) ? $this->configuration[$event] : '';
$level = strtolower($level);
if (!$level) {
return '';
}
if (!isset(self::$levels[$level])) {
return '';
}
return $level;
} | php | {
"resource": ""
} |
q2326 | SlotContextEntry.addSlot | train | public function addSlot($name, Closure $closure, array $arguments)
{
$this->closures[$name] = $closure;
$this->arguments[$name] = $arguments;
} | php | {
"resource": ""
} |
q2327 | SlotContextEntry.addTemplateVariables | train | public function addTemplateVariables($slotName, array $arguments)
{
$templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
$savedArguments = [];
ArrayUtility::mergeRecursiveWithOverrule(
$arguments,
$this->getSlotArguments($slotName)
);
foreach ($arguments as $key => $value) {
if ($templateVariableContainer->exists($key)) {
$savedArguments[$key] = $templateVariableContainer->get($key);
$templateVariableContainer->remove($key);
}
$templateVariableContainer->add($key, $value);
}
$this->injectedVariables[$slotName] = $arguments;
$this->savedVariables[$slotName] = $savedArguments;
} | php | {
"resource": ""
} |
q2328 | SlotContextEntry.restoreTemplateVariables | train | public function restoreTemplateVariables($slotName)
{
$templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
$mergedArguments = (isset($this->injectedVariables[$slotName])) ? $this->injectedVariables[$slotName] : [];
$savedArguments = (isset($this->savedVariables[$slotName])) ? $this->savedVariables[$slotName] : [];
foreach (array_keys($mergedArguments) as $key) {
$templateVariableContainer->remove($key);
}
foreach ($savedArguments as $key => $value) {
$templateVariableContainer->add($key, $value);
}
} | php | {
"resource": ""
} |
q2329 | Polyglot.stripLanguage | train | public function stripLanguage($path, $language = null)
{
$strip = '/' . ( isset($language) ? $language : $this->getLanguage() );
if ( strlen($strip) > 1 && strpos($path, $strip) === 0 ) {
$path = substr($path, strlen($strip));
}
return $path;
} | php | {
"resource": ""
} |
q2330 | Polyglot.prependLanguage | train | public function prependLanguage($path, $language = null)
{
$prepend = ( isset($language) ? $language : $this->getLanguage() );
if ( strlen($prepend) > 1 ) {
return $prepend . (strpos($path, '/') === 0 ? $path : '/' . $path);
}
return $path;
} | php | {
"resource": ""
} |
q2331 | Polyglot.replaceLanguage | train | public function replaceLanguage($path, $language, $replacement = null)
{
$path = $this->stripLanguage($path, $language);
$path = $this->prependLanguage($path, $replacement);
return $path;
} | php | {
"resource": ""
} |
q2332 | Polyglot.getFromHeader | train | protected function getFromHeader(ServerRequestInterface $request)
{
$accept = $request->getHeaderLine('Accept-Language');
if ( empty($accept) || empty($this->languages) ) {
return;
}
$language = (new Negotiator())->getBest($accept, $this->languages);
if ( $language ) {
return $language->getValue();
}
} | php | {
"resource": ""
} |
q2333 | Polyglot.getFromPath | train | protected function getFromPath(ServerRequestInterface $request)
{
$uri = $request->getUri();
$regex = '~^\/?' . $this->getRegEx() . '\b~';
$path = rtrim( $uri->getPath(), '/\\' ) . '/';
if ( preg_match($regex, $path, $matches) ) {
if (isset($matches['language'])) {
return $matches['language'];
} else {
throw new RuntimeException('The regular expression pattern is missing a named subpattern "language".');
}
}
} | php | {
"resource": ""
} |
q2334 | Polyglot.getFromQuery | train | protected function getFromQuery(ServerRequestInterface $request)
{
$params = array_intersect_key($request->getQueryParams(), array_flip($this->getQueryKeys()));
$regex = '~^\/?' . $this->getRegEx() . '\b~';
foreach ($params as $key => $value) {
if ( preg_match($regex, $value, $matches) ) {
if (isset($matches['language'])) {
return $matches['language'];
} else {
throw new RuntimeException('The regular expression pattern is missing a named subpattern "language".');
}
}
}
} | php | {
"resource": ""
} |
q2335 | Polyglot.setSupportedLanguages | train | public function setSupportedLanguages(array $languages)
{
$this->languages = $languages;
$this->fallbackLanguage = reset($languages);
return $this;
} | php | {
"resource": ""
} |
q2336 | Polyglot.setFallbackLanguage | train | public function setFallbackLanguage($language)
{
if ( $this->isSupported($language) ) {
$this->fallbackLanguage = $language;
}
else {
throw new RuntimeException('Variable must be one of the supported languages.');
}
return $this;
} | php | {
"resource": ""
} |
q2337 | Polyglot.getUserLanguage | train | public function getUserLanguage(ServerRequestInterface $request = null)
{
if (
$this->saveInSession &&
isset($_SESSION['language']) &&
$this->isSupported($_SESSION['language'])
) {
return $_SESSION['language'];
}
if ( empty($language) && $request instanceof ServerRequestInterface ) {
return $this->getFromHeader($request);
}
return null;
} | php | {
"resource": ""
} |
q2338 | Polyglot.setCallbacks | train | public function setCallbacks(array $callables)
{
$this->callbacks = [];
foreach ($callables as $callable) {
if (is_callable($callable)) {
$this->addCallback($callable);
}
}
return $this;
} | php | {
"resource": ""
} |
q2339 | Polyglot.setQueryKeys | train | public function setQueryKeys(array $keys)
{
$this->queryKeys = [];
foreach ($keys as $key) {
if (is_string($key)) {
$this->addQueryKey($key);
}
}
return $this;
} | php | {
"resource": ""
} |
q2340 | Polyglot.sanitizeLanguage | train | public function sanitizeLanguage($language)
{
if ( 0 === count($this->languages) ) {
throw new RuntimeException('Polyglot features no supported languages.');
}
if ( ! $this->isSupported($language) ) {
$language = $this->getFallbackLanguage();
}
return $language;
} | php | {
"resource": ""
} |
q2341 | Polyglot.isLanguageRequiredInUri | train | public function isLanguageRequiredInUri($state = null)
{
if (isset($state)) {
$this->languageRequiredInUri = (bool) $state;
}
return $this->languageRequiredInUri;
} | php | {
"resource": ""
} |
q2342 | Polyglot.isLanguageIncludedInRoutes | train | public function isLanguageIncludedInRoutes($state = null)
{
if (isset($state)) {
$this->languageIncludedInRoutes = (bool) $state;
}
return $this->languageIncludedInRoutes;
} | php | {
"resource": ""
} |
q2343 | Schema.applyCallback | train | protected function applyCallback(stdClass $schema): stdClass
{
if (is_callable($this->callback)) {
$result = call_user_func_array($this->callback, [Convert::objectToArray($schema)]);
if (is_null($result)) {
throw new InvalidArgumentException('Callback returned `null`. Did you forget to `return $schema;`?');
}
if ($result !== false) {
return Convert::arrayToObject($result);
}
}
return $schema;
} | php | {
"resource": ""
} |
q2344 | FormValidatorExecutor.checkFieldsActivation | train | public function checkFieldsActivation()
{
foreach ($this->getFormObject()->getConfiguration()->getFields() as $field) {
if (false === $this->result->fieldIsDeactivated($field)) {
$this->checkFieldActivation($field);
}
}
return $this;
} | php | {
"resource": ""
} |
q2345 | CacheManager.addCache | train | public function addCache(CacheInterface $cache)
{
$this->cacheMap[$cache->getName()] = $cache;
$this->cacheNames[] = $cache->getName();
} | php | {
"resource": ""
} |
q2346 | Database.query | train | public function query($cql, array $values = [], $consistency = ConsistencyEnum::CONSISTENCY_QUORUM) {
if ($this->batchQuery && in_array(substr($cql, 0, 6), ['INSERT', 'UPDATE', 'DELETE'])) {
$this->appendQueryToStack($cql, $values);
return true;
}
if (empty($values)) {
$response = $this->connection->sendRequest(RequestFactory::query($cql, $consistency));
} else {
$response = $this->connection->sendRequest(RequestFactory::prepare($cql));
$responseType = $response->getType();
if ($responseType !== OpcodeEnum::RESULT) {
throw new QueryException($response->getData());
} else {
$preparedData = $response->getData();
}
$response = $this->connection->sendRequest(
RequestFactory::execute($preparedData, $values, $consistency)
);
}
if ($response->getType() === OpcodeEnum::ERROR) {
throw new CassandraException($response->getData());
} else {
$data = $response->getData();
if ($data instanceof Rows) {
return $data->asArray();
}
}
return !empty($data) ? $data : $response->getType() === OpcodeEnum::RESULT;
} | php | {
"resource": ""
} |
q2347 | FormzConfigurationJavaScriptAssetHandler.getFormzConfiguration | train | protected function getFormzConfiguration()
{
$rootConfigurationArray = $this->getFormObject()
->getConfiguration()
->getRootConfiguration()
->toArray();
$cleanFormzConfigurationArray = [
'view' => $rootConfigurationArray['view']
];
return ArrayService::get()->arrayToJavaScriptJson($cleanFormzConfigurationArray);
} | php | {
"resource": ""
} |
q2348 | ContainerBuilder.setDefaultConfiguration | train | private function setDefaultConfiguration(): void
{
$this->parameterBag->set('app.devmode', false);
$this->parameterBag->set('container.dumper.inline_class_loader', true);
$this->config->addPass($this->parameterBag);
} | php | {
"resource": ""
} |
q2349 | BrowserDumper.dump | train | public function dump()
{
$methods = $this->specification->getMethods();
$result = '<?php
/*
* This file is part of PHP Selenium Library.
* (c) Alexandre Salomé <alexandre.salome@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Selenium;
/**
* Browser class containing all methods of Selenium Server, with documentation.
*
* This class was generated, do not modify it.
*
* @author Alexandre Salomé <alexandre.salome@gmail.com>
*/
class GeneratedBrowser extends BaseBrowser
{
';
foreach ($methods as $method) {
$result .= $this->dumpMethod($method)."\n\n";
}
$result .= "}
";
return $result;
} | php | {
"resource": ""
} |
q2350 | BrowserDumper.dumpMethod | train | protected function dumpMethod(Method $method)
{
$builder = new MethodBuilder();
$documentation = $method->getDescription()."\n\n";
$signature = array();
foreach ($method->getParameters() as $parameter) {
$builder->addParameter($parameter->getName());
$documentation .= "@param string $".$parameter->getName()." ".$parameter->getDescription()."\n\n";
$signature[] = '$'.$parameter->getName();
}
$signature = implode(', ', $signature);
if ($method->isAction()) {
$documentation .= '@return \Selenium\Browser Fluid interface';
$body = '$this->driver->action("'.$method->getName().'"'. ($signature ? ', '.$signature : '') . ');'."\n";
$body .= "\n";
$body .= "return \$this;";
} else {
$returnType = $method->getReturnType();
if ($returnType === 'boolean') {
$getMethod = 'getBoolean';
} elseif ($returnType === 'string') {
$getMethod = 'getString';
} elseif ($returnType === 'string[]') {
$getMethod = 'getStringArray';
} elseif ($returnType === 'number') {
$getMethod = 'getNumber';
$returnType = 'integer';
if (0 === strpos($method->getReturnDescription(), 'of ')) {
$returnType .= ' number';
}
}
$documentation .= '@return '.$returnType.' '.$method->getReturnDescription();
$body = 'return $this->driver->'.$getMethod.'("'.$method->getName().'"'.($signature ? ', '.$signature : '').');';
}
$builder->setName($method->getName());
$builder->setBody($body);
$builder->setDocumentation($documentation);
return $builder->buildCode();
} | php | {
"resource": ""
} |
q2351 | TbbcCacheExtension.createCache | train | private function createCache(array $config, ContainerBuilder $container)
{
$type = $config['type'];
if (array_key_exists($type, $this->cacheFactories)) {
$id = sprintf('tbbc_cache.%s_cache', $config['name']);
$this->cacheFactories[$type]->create($container, $id, $config);
return $id;
}
// TODO: throw exception ?
} | php | {
"resource": ""
} |
q2352 | TbbcCacheExtension.createCacheFactories | train | private function createCacheFactories()
{
if (null !== $this->cacheFactories) {
return $this->cacheFactories;
}
// load bundled cache factories
$tempContainer = new ContainerBuilder();
$loader = new Loader\XmlFileLoader($tempContainer, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('cache_factories.xml');
$cacheFactories = array();
foreach ($tempContainer->findTaggedServiceIds('tbbc_cache.cache_factory') as $id => $factories) {
foreach ($factories as $factory) {
if (!isset($factory['cache_type'])) {
throw new \InvalidArgumentException(sprintf(
'Service "%s" must define a "cache_type" attribute for "tbbc_cache.cache_factory" tag',
$id
));
}
$factoryService = $tempContainer->get($id);
$cacheFactories[str_replace('-', '_', strtolower($factory['cache_type']))] = $factoryService;
}
}
return $this->cacheFactories = $cacheFactories;
} | php | {
"resource": ""
} |
q2353 | MessageService.sanitizeValidatorResult | train | public function sanitizeValidatorResult(Result $result, $validationName)
{
$newResult = new Result;
$this->sanitizeValidatorResultMessages('error', $result->getFlattenedErrors(), $newResult, $validationName);
$this->sanitizeValidatorResultMessages('warning', $result->getFlattenedWarnings(), $newResult, $validationName);
$this->sanitizeValidatorResultMessages('notice', $result->getFlattenedNotices(), $newResult, $validationName);
return $newResult;
} | php | {
"resource": ""
} |
q2354 | MessageService.filterMessages | train | public function filterMessages(array $messages, array $supportedMessages, $canCreateNewMessages = false)
{
// Adding the keys `value` and `extension` to the messages, only if it is missing.
$addValueToArray = function (array &$a) {
foreach ($a as $k => $v) {
if (false === isset($v['value'])) {
$a[$k]['value'] = '';
}
if (false === isset($v['extension'])) {
$a[$k]['extension'] = '';
}
}
return $a;
};
$messagesArray = [];
foreach ($messages as $key => $message) {
if ($message instanceof FormzMessage) {
$message = $message->toArray();
}
$messagesArray[$key] = $message;
}
$addValueToArray($messagesArray);
$addValueToArray($supportedMessages);
$messagesResult = $supportedMessages;
ArrayUtility::mergeRecursiveWithOverrule(
$messagesResult,
$messagesArray,
(bool)$canCreateNewMessages
);
return $messagesResult;
} | php | {
"resource": ""
} |
q2355 | Decorator.render | train | public function render(ElementInterface $formElement, $value = '', $attributes = array())
{
$this->checkDependencies();
$config = $this->di->get('config');
if (empty($this->templateName) && !empty($config->forms->templates->default_name)) {
$this->templateName = $config->forms->templates->default_name;
}
$this->variables['element'] = $formElement;
$this->variables['value'] = $value;
$this->variables['attributes'] = $attributes;
$partial = $this->generatePartial();
return $partial;
} | php | {
"resource": ""
} |
q2356 | Decorator.checkDependencies | train | private function checkDependencies()
{
if (!($this->di instanceof DiInterface)) {
throw new DiNotSetException();
}
if (!$this->di->has('view')) {
throw new ViewNotSetException();
}
if (!$this->di->has('assets')) {
throw new InvalidAssetsManagerException();
}
} | php | {
"resource": ""
} |
q2357 | BasePathFinder.getFilePath | train | protected function getFilePath(string $path): string
{
if (empty($path)) {
$path = $this->fileName;
}
return $path;
} | php | {
"resource": ""
} |
q2358 | BasePathFinder.getDistributionFilePath | train | protected function getDistributionFilePath(string $path): string
{
$postfix = self::DIST_FILENAME_POSTFIX;
if (empty($path)) {
$path = $this->fileName;
}
// Check if this is the distribution file path
$pathinfo = pathinfo($path);
$postfixIndex = strlen($pathinfo['filename']) - strlen($postfix);
$isDistributionFile = substr($pathinfo['filename'], $postfixIndex) === $postfix;
if (!$isDistributionFile) {
$extension = !empty($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
$path = $pathinfo['filename'] . $postfix . $extension;
}
return $path;
} | php | {
"resource": ""
} |
q2359 | BasePathFinder.validatePath | train | protected function validatePath(string $path): void
{
if (empty($path)) {
$this->fail(new InvalidArgumentException("Path is not specified"));
}
if (!is_string($path)) {
$this->fail(new InvalidArgumentException("Path is not a string"));
}
} | php | {
"resource": ""
} |
q2360 | BasePathFinder.addFileExtension | train | protected function addFileExtension(string $path): string
{
$extension = pathinfo($path, PATHINFO_EXTENSION);
if (empty($extension)) {
$path .= $this->extension;
}
return $path;
} | php | {
"resource": ""
} |
q2361 | FormRequestDataJavaScriptAssetHandler.getSubmittedFormValues | train | protected function getSubmittedFormValues()
{
$result = [];
$formName = $this->getFormObject()->getName();
$originalRequest = $this->getControllerContext()
->getRequest()
->getOriginalRequest();
if (null !== $originalRequest
&& $originalRequest->hasArgument($formName)
) {
$result = $originalRequest->getArgument($formName);
}
return $result;
} | php | {
"resource": ""
} |
q2362 | EncryptedCookiesMiddleware.encryptAndRenderCookies | train | private function encryptAndRenderCookies($resCookies)
{
$renderable = [];
foreach ($resCookies as $cookie) {
if (is_string($cookie)) {
$cookie = SetCookie::fromSetCookieString($cookie);
}
if ($cookie instanceof SetCookie) {
$val = $cookie->getValue();
if ($val instanceof OpaqueProperty) {
$val = $val->getValue();
}
if (!in_array($cookie->getName(), $this->unencryptedCookies)) {
$val = $this->encryption->encrypt($val);
}
$renderable[$cookie->getName()] = (string) $cookie->withValue($val);
}
}
return $renderable;
} | php | {
"resource": ""
} |
q2363 | TwigExtension.formatTimepoint | train | public function formatTimepoint($time, $format)
{
if ($time instanceof TimePoint) {
return $time->format($format, $this->displayTimezone);
}
if ($time instanceof DateTime) {
$formatted = clone $time;
$formatted->setTimezone(new DateTimeZone($this->displayTimezone));
return $formatted->format($format);
}
return '';
} | php | {
"resource": ""
} |
q2364 | AjaxValidationController.processRequest | train | public function processRequest(RequestInterface $request, ResponseInterface $response)
{
$this->result = new AjaxResult;
try {
$this->processRequestParent($request, $response);
} catch (Exception $exception) {
if (false === $this->protectedRequestMode) {
throw $exception;
}
$this->result->clear();
$errorMessage = ExtensionService::get()->isInDebugMode()
? $this->getDebugMessageForException($exception)
: ContextService::get()->translate(self::DEFAULT_ERROR_MESSAGE_KEY);
$error = new Error($errorMessage, 1490176818);
$this->result->addError($error);
$this->result->setData('errorCode', $exception->getCode());
}
// Cleaning every external message.
ob_clean();
$this->injectResultInResponse();
} | php | {
"resource": ""
} |
q2365 | AjaxValidationController.initializeActionMethodValidators | train | protected function initializeActionMethodValidators()
{
$this->initializeActionMethodValidatorsParent();
$request = $this->getRequest();
if (false === $request->hasArgument('name')) {
throw MissingArgumentException::ajaxControllerNameArgumentNotSet();
}
if (false === $request->hasArgument('className')) {
throw MissingArgumentException::ajaxControllerClassNameArgumentNotSet();
}
$className = $request->getArgument('className');
if (false === class_exists($className)) {
throw ClassNotFoundException::ajaxControllerFormClassNameNotFound($className);
}
if (false === in_array(FormInterface::class, class_implements($className))) {
throw InvalidArgumentTypeException::ajaxControllerWrongFormType($className);
}
$this->arguments->addNewArgument($request->getArgument('name'), $className, true);
} | php | {
"resource": ""
} |
q2366 | AjaxValidationController.runAction | train | public function runAction($name, $className, $fieldName, $validatorName)
{
$this->formName = $name;
$this->formClassName = $className;
$this->fieldName = $fieldName;
$this->validatorName = $validatorName;
$this->form = $this->getForm();
$this->formObject = $this->getFormObject();
$this->formObject->setForm($this->form);
$this->validation = $this->getFieldValidation();
$validatorDataObject = new ValidatorDataObject($this->formObject, $this->validation);
/** @var ValidatorInterface $validator */
$validator = Core::instantiate(
$this->validation->getClassName(),
$this->validation->getOptions(),
$validatorDataObject
);
$fieldValue = ObjectAccess::getProperty($this->form, $this->fieldName);
$result = $validator->validate($fieldValue);
$this->result->merge($result);
} | php | {
"resource": ""
} |
q2367 | ListParser.normalize | train | protected function normalize(array $data, string $prefix = null): array
{
if ($prefix) {
$prefix .= '.';
}
$result = [];
foreach ($data as $item) {
$value = [
'label' => (string)$item['label'],
'inactive' => (bool)$item['inactive']
];
if (! empty($item['children'])) {
$value['children'] = $this->normalize($item['children'], $prefix . $item['value']);
}
$result[$prefix . $item['value']] = $value;
}
return $result;
} | php | {
"resource": ""
} |
q2368 | ListParser.filter | train | protected function filter(array $data): array
{
$result = [];
foreach ($data as $key => $value) {
if ($value['inactive']) {
continue;
}
$result[$key] = $value;
if (isset($value['children'])) {
$result[$key]['children'] = $this->filter($value['children']);
}
}
return $result;
} | php | {
"resource": ""
} |
q2369 | ListParser.flatten | train | protected function flatten(array $data): array
{
$result = [];
foreach ($data as $key => $value) {
$item = [
'label' => $value['label'],
'inactive' => $value['inactive']
];
$result[$key] = $item;
if (isset($value['children'])) {
$result = array_merge($result, $this->flatten($value['children']));
}
}
return $result;
} | php | {
"resource": ""
} |
q2370 | Cache.setOptions | train | protected function setOptions(array $options = []): void
{
$this->options = $options;
$this->configName = empty($options['cacheConfig']) ? static::DEFAULT_CONFIG : (string)$options['cacheConfig'];
$this->skipCache = empty($this->options['cacheSkip']) ? false : (bool)$this->options['cacheSkip'];
} | php | {
"resource": ""
} |
q2371 | Cache.getKey | train | public function getKey(array $params): string
{
// Push current options to the list of
// params to ensure unique cache key for
// each set of options.
$params[] = $this->options;
$params = json_encode($params);
$params = $params ?: microtime();
$params = md5($params);
$result = $this->name . '_' . $params;
return $result;
} | php | {
"resource": ""
} |
q2372 | Cache.readFrom | train | public function readFrom(string $key)
{
$result = false;
if ($this->skipCache()) {
$this->warnings[] = 'Skipping read from cache';
return $result;
}
$cachedData = CakeCache::read($key, $this->getConfig());
if (!$this->isValidCache($cachedData)) {
CakeCache::delete($key, $this->getConfig());
return $result;
}
$result = $cachedData['data'];
return $result;
} | php | {
"resource": ""
} |
q2373 | BooleanNode.getLogicalResult | train | protected function getLogicalResult(callable $logicalAndFunction, callable $logicalOrFunction)
{
switch ($this->operator) {
case ConditionParser::LOGICAL_AND:
$result = call_user_func($logicalAndFunction);
break;
case ConditionParser::LOGICAL_OR:
$result = call_user_func($logicalOrFunction);
break;
default:
throw InvalidConfigurationException::wrongBooleanNodeOperator($this->operator);
}
return $result;
} | php | {
"resource": ""
} |
q2374 | BooleanNode.processLogicalOrPhp | train | protected function processLogicalOrPhp(PhpConditionDataObject $dataObject)
{
return $this->leftNode->getPhpResult($dataObject) || $this->rightNode->getPhpResult($dataObject);
} | php | {
"resource": ""
} |
q2375 | UtilityPage.requireDefaultRecords | train | public function requireDefaultRecords()
{
parent::requireDefaultRecords();
// Skip creation of default records
if (!self::config()->create_default_pages) {
return;
}
// Ensure that an assets path exists before we do any error page creation
if (!file_exists(ASSETS_PATH)) {
mkdir(ASSETS_PATH);
}
$code = self::$defaults['ErrorCode'];
$page = UtilityPage::get()->filter('ErrorCode', $code)->first();
$pageExists = !empty($page);
if (!$pageExists) {
$page = UtilityPage::get()->first();
$pageExists = ($page && $page->exists());
//Only create a UtilityPage on dev/build if one does not already exist.
$page = UtilityPage::create(array(
'Title' => _t('MaintenanceMode.TITLE', 'Undergoing Scheduled Maintenance'),
'URLSegment' => _t('MaintenanceMode.URLSEGMENT', 'offline'),
'MenuTitle' => _t('MaintenanceMode.MENUTITLE', 'Utility Page'),
'Content' => _t('MaintenanceMode.CONTENT', '<h1>We’ll be back soon!</h1>'
.'<p>Sorry for the inconvenience but '
.'our site is currently down for scheduled maintenance. '
.'If you need to you can always <a href="mailto:#">contact us</a>, '
.'otherwise we’ll be back online shortly!</p>'
.'<p>— The Team</p>'),
'ParentID' => 0
));
$page->write();
$page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
}
// Ensure a static error page is created from latest Utility Page content
// Check if static files are enabled
if (!self::config()->enable_static_file) {
return;
}
// Ensure this page has cached error content
$success = true;
if (!$page->hasStaticPage()) {
// Update static content
$success = $page->writeStaticPage();
} elseif ($pageExists) {
// If page exists and already has content, no alteration_message is displayed
return;
}
if ($success) {
DB::alteration_message(
sprintf('%s error Utility Page created', $code),
'created'
);
} else {
DB::alteration_message(
sprintf('%s error Utility page could not be created. Please check permissions', $code),
'error'
);
}
} | php | {
"resource": ""
} |
q2376 | UtilityPage.get_top_level_templates | train | public static function get_top_level_templates()
{
$ss_templates_array = array();
$current_theme_path = THEMES_PATH.'/'.Config::inst()->get('SSViewer', 'theme');
//theme directories to search
$search_dir_array = array(
MAINTENANCE_MODE_PATH.'/templates',
$current_theme_path.'/templates'
);
foreach ($search_dir_array as $directory) {
//Get all the SS templates in the directory
foreach (glob("{$directory}/*.ss") as $template_path) {
//get the template name from the path excluding the ".ss" extension
$template = basename($template_path, '.ss');
//Add the key=>value pair to the ss_template_array
$ss_templates_array[$template] = $template;
}
}
return $ss_templates_array;
} | php | {
"resource": ""
} |
q2377 | FormObjectFactory.getInstanceFromClassName | train | public function getInstanceFromClassName($className, $name)
{
if (false === class_exists($className)) {
throw ClassNotFoundException::wrongFormClassName($className);
}
if (false === in_array(FormInterface::class, class_implements($className))) {
throw InvalidArgumentTypeException::wrongFormType($className);
}
$cacheIdentifier = $this->getCacheIdentifier($className, $name);
if (false === isset($this->instances[$cacheIdentifier])) {
$cacheInstance = CacheService::get()->getCacheInstance();
if ($cacheInstance->has($cacheIdentifier)) {
$instance = $cacheInstance->get($cacheIdentifier);
} else {
$instance = $this->createInstance($className, $name);
$cacheInstance->set($cacheIdentifier, $instance);
}
/** @var Configuration $formzConfigurationObject */
$formzConfigurationObject = $this->configurationFactory
->getFormzConfiguration()
->getObject(true);
if (false === $formzConfigurationObject->hasForm($instance->getClassName(), $instance->getName())) {
$formzConfigurationObject->addForm($instance);
}
$this->instances[$cacheIdentifier] = $instance;
}
return $this->instances[$cacheIdentifier];
} | php | {
"resource": ""
} |
q2378 | FormObjectFactory.createInstance | train | protected function createInstance($className, $name)
{
$formConfiguration = $this->typoScriptService->getFormConfiguration($className);
/** @var FormObject $instance */
$instance = Core::instantiate(FormObject::class, $className, $name, $formConfiguration);
$this->insertObjectProperties($instance);
$instance->getHash();
return $instance;
} | php | {
"resource": ""
} |
q2379 | FormObjectFactory.insertObjectProperties | train | protected function insertObjectProperties(FormObject $instance)
{
$className = $instance->getClassName();
/** @var ReflectionService $reflectionService */
$reflectionService = GeneralUtility::makeInstance(ReflectionService::class);
$reflectionProperties = $reflectionService->getClassPropertyNames($className);
$classReflection = new \ReflectionClass($className);
$publicProperties = $classReflection->getProperties(\ReflectionProperty::IS_PUBLIC);
foreach ($reflectionProperties as $property) {
if (false === in_array($property, self::$ignoredProperties)
&& false === $reflectionService->isPropertyTaggedWith($className, $property, self::IGNORE_PROPERTY)
&& ((true === in_array($property, $publicProperties))
|| $reflectionService->hasMethod($className, 'get' . ucfirst($property))
)
) {
$instance->addProperty($property);
}
}
unset($publicProperties);
} | php | {
"resource": ""
} |
q2380 | TaxonomyTrait.addTerm | train | public function addTerm($term_id) {
$term = ($term_id instanceof Term) ? $term_id : Term::findOrFail($term_id);
$term_relation = [
'term_id' => $term->id,
'vocabulary_id' => $term->vocabulary_id,
];
return $this->related()->save(new TermRelation($term_relation));
} | php | {
"resource": ""
} |
q2381 | TaxonomyTrait.hasTerm | train | public function hasTerm($term_id) {
$term = ($term_id instanceof Term) ? $term_id : Term::findOrFail($term_id);
$term_relation = [
'term_id' => $term->id,
'vocabulary_id' => $term->vocabulary_id,
];
return ($this->related()->where('term_id', $term_id)->count()) ? TRUE : FALSE;
} | php | {
"resource": ""
} |
q2382 | TaxonomyTrait.getTermsByVocabularyName | train | public function getTermsByVocabularyName($name) {
$vocabulary = \Taxonomy::getVocabularyByName($name);
return $this->related()->where('vocabulary_id', $vocabulary->id)->get();
} | php | {
"resource": ""
} |
q2383 | TaxonomyTrait.getTermsByVocabularyNameAsArray | train | public function getTermsByVocabularyNameAsArray($name) {
$vocabulary = \Taxonomy::getVocabularyByName($name);
$term_relations = $this->related()->where('vocabulary_id', $vocabulary->id)->get();
$data = [];
foreach ($term_relations as $term_relation) {
$data[$term_relation->term->id] = $term_relation->term->name;
}
return $data;
} | php | {
"resource": ""
} |
q2384 | TaxonomyTrait.removeTerm | train | public function removeTerm($term_id) {
$term_id = ($term_id instanceof Term) ? $term_id->id : $term_id;
return $this->related()->where('term_id', $term_id)->delete();
} | php | {
"resource": ""
} |
q2385 | FormViewHelperService.applyBehavioursOnSubmittedForm | train | public function applyBehavioursOnSubmittedForm(ControllerContext $controllerContext)
{
if ($this->formObject->formWasSubmitted()) {
$request = $controllerContext->getRequest()->getOriginalRequest();
$formName = $this->formObject->getName();
if ($request
&& $request->hasArgument($formName)
) {
/** @var BehavioursManager $behavioursManager */
$behavioursManager = GeneralUtility::makeInstance(BehavioursManager::class);
/** @var array $originalForm */
$originalForm = $request->getArgument($formName);
$formProperties = $behavioursManager->applyBehaviourOnPropertiesArray(
$originalForm,
$this->formObject->getConfiguration()
);
$request->setArgument($formName, $formProperties);
}
}
} | php | {
"resource": ""
} |
q2386 | ConditionProcessor.getActivationConditionTreeForField | train | public function getActivationConditionTreeForField(Field $field)
{
$key = $field->getName();
if (false === array_key_exists($key, $this->fieldsTrees)) {
$this->fieldsTrees[$key] = $this->getConditionTree($field->getActivation());
}
$this->fieldsTrees[$key]->injectDependencies($this, $field->getActivation());
return $this->fieldsTrees[$key];
} | php | {
"resource": ""
} |
q2387 | ConditionProcessor.getActivationConditionTreeForValidation | train | public function getActivationConditionTreeForValidation(Validation $validation)
{
$key = $validation->getParentField()->getName() . '->' . $validation->getName();
if (false === array_key_exists($key, $this->validationsTrees)) {
$this->validationsTrees[$key] = $this->getConditionTree($validation->getActivation());
}
$this->validationsTrees[$key]->injectDependencies($this, $validation->getActivation());
return $this->validationsTrees[$key];
} | php | {
"resource": ""
} |
q2388 | ConditionProcessor.calculateAllTrees | train | public function calculateAllTrees()
{
$fields = $this->formObject->getConfiguration()->getFields();
foreach ($fields as $field) {
$this->getActivationConditionTreeForField($field);
foreach ($field->getValidation() as $validation) {
$this->getActivationConditionTreeForValidation($validation);
}
}
} | php | {
"resource": ""
} |
q2389 | Handlers.exceptionHandler | train | public function exceptionHandler($e) : void
{
$this->setError(
(int) $e->getCode(),
(string) $e->getMessage(),
(string) $e->getFile(),
(int) $e->getLine(),
(string) get_class($e),
$e->getTrace()
);
View::render('500.php', (object) $this->errors);
} | php | {
"resource": ""
} |
q2390 | Handlers.fatalHandler | train | public function fatalHandler() : void
{
$errors = error_get_last();
if (is_array($errors)) {
$this->setError(
(int) $errors['type'],
(string) $errors['message'],
(string) $errors['file'],
(int) $errors['line'],
'FatalErrorException'
);
View::render('500.php', (object) $this->errors);
return;
}
} | php | {
"resource": ""
} |
q2391 | MigratorConsole.migrateModels | train | public function migrateModels($models)
{
// run inside callback
$this->set(function ($c) use ($models) {
$c->notice('Preparing to migrate models');
$p = $c->app->db;
foreach ($models as $model) {
if (!is_object($model)) {
$model = $this->factory($model);
$p->add($model);
}
$m = new \atk4\schema\Migration\MySQL($model);
$result = $m->migrate();
$c->debug(' '.get_class($model).'.. '.$result);
}
$c->notice('Done with migration');
});
} | php | {
"resource": ""
} |
q2392 | ExtensionService.getExtensionConfiguration | train | public function getExtensionConfiguration($configurationName)
{
$result = null;
$extensionConfiguration = $this->getFullExtensionConfiguration();
if (null === $configurationName) {
$result = $extensionConfiguration;
} elseif (ArrayUtility::isValidPath($extensionConfiguration, $configurationName, '.')) {
$result = ArrayUtility::getValueByPath($extensionConfiguration, $configurationName, '.');
}
return $result;
} | php | {
"resource": ""
} |
q2393 | CookieHandler.expireCookie | train | public function expireCookie(ResponseInterface $response, $name)
{
$cookie = SetCookie::createExpired($name)
->withMaxAge($this->configuration['maxAge'])
->withPath($this->configuration['path'])
->withDomain($this->configuration['domain'])
->withSecure($this->configuration['secure'])
->withHttpOnly($this->configuration['httpOnly']);
return $response->withAddedHeader(static::RESPONSE_COOKIE_NAME, $cookie);
} | php | {
"resource": ""
} |
q2394 | AbstractValidator.addError | train | protected function addError($key, $code, array $arguments = [], $title = '')
{
$message = $this->addMessage(Error::class, $key, $code, $arguments, $title);
$this->result->addError($message);
} | php | {
"resource": ""
} |
q2395 | AbstractValidator.addWarning | train | protected function addWarning($key, $code, array $arguments = [], $title = '')
{
$message = $this->addMessage(Warning::class, $key, $code, $arguments, $title);
$this->result->addWarning($message);
} | php | {
"resource": ""
} |
q2396 | AbstractValidator.addNotice | train | protected function addNotice($key, $code, array $arguments = [], $title = '')
{
$message = $this->addMessage(Notice::class, $key, $code, $arguments, $title);
$this->result->addNotice($message);
} | php | {
"resource": ""
} |
q2397 | FormObject.addProperty | train | public function addProperty($name)
{
if (false === $this->hasProperty($name)) {
$this->properties[] = $name;
$this->hashService->resetHash();
}
return $this;
} | php | {
"resource": ""
} |
q2398 | DataStream.read | train | protected function read($length) {
if ($this->length < $length) {
throw new \Exception('Reading while at end of stream');
}
$output = substr($this->data, 0, $length);
$this->data = substr($this->data, $length);
$this->length -= $length;
return $output;
} | php | {
"resource": ""
} |
q2399 | DataStream.readInt | train | public function readInt($isCollectionElement = false) {
if ($isCollectionElement) {
$length = $this->readShort();
return unpack('l', strrev($this->read($length)))[1];
}
return unpack('l', strrev($this->read(4)))[1];
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.