_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q265900 | Bootstrap.getFieldError | test | protected function getFieldError($field, $format = '<span class="help-block">:message</span>')
{
$field = $this->flattenFieldName($field);
if ($this->getErrors()) {
$allErrors = $this->config->get('html.bootstrap.show_all_errors');
if ($this->getErrorBag()) {
$errorBag = $this->getErrors()->{$this->getErrorBag()};
} else {
$errorBag = $this->getErrors();
}
if ($allErrors) {
return implode('', $errorBag->get($field, $format));
}
return $errorBag->first($field, $format);
}
} | php | {
"resource": ""
} |
q265901 | Cookie.setSameSite | test | public function setSameSite(string $sameSite = null): self
{
if (! \in_array($sameSite, [self::LAX, self::STRICT, null], true)) {
throw new InvalidSameSiteTypeException(
'The "sameSite" parameter value is not valid.'
);
}
$this->sameSite = $sameSite;
return $this;
} | php | {
"resource": ""
} |
q265902 | Archive.cleanAndAddHeader | test | protected function cleanAndAddHeader()
{
if (true === $this->clean || null !== $this->header) {
foreach ($this->files as $translation) {
$formatter = FormatterFactory::getInstance($translation);
if ($this->clean) {
$formatter->clean($translation);
}
if ($this->header) {
$formatter->addHeader($translation, $this->header);
}
}
}
} | php | {
"resource": ""
} |
q265903 | ClassFinderHelper.findClassesPsr4 | test | public static function findClassesPsr4($namespace, $recursively = false, $withoutAutoload = false) {
$classNames = [];
if(is_array($namespace)) {
foreach ($namespace as $ns) {
$classNames = ArrayHelper::merge($classNames, static::findClassesPsr4($ns, $recursively, $withoutAutoload));
}
return $classNames;
}
$namespace = trim($namespace, static::CS);
list($nsPrefix, $namespacePaths) = static::getNamespacePaths($namespace);
if (empty($namespacePaths)) {
return [];
}
$files = [];
$regEx = '/\.php$/';
for ($i = 0; $i < count($namespacePaths); $i++) {
$dir = $namespacePaths[$i];
$dirIt = new \RecursiveDirectoryIterator($dir);
$files = [];
if($recursively) {
foreach(new \RecursiveIteratorIterator($dirIt) as $file)
{
$fileStr = (string)$file;
if (!preg_match($regEx, $fileStr)) {
continue;
}
$fileStr = substr($fileStr, strlen($dir) + 1, -4);
$files[] = $fileStr;
}
} else {
$_files = glob($dir . static::DS . '*.php');
for ($j = 0; $j < count($_files); $j++) {
$fileStr = $_files[$j];
$fileStr = substr($fileStr, strlen($dir) + 1, -4);
$files[] = $fileStr;
}
}
}
for ($i = 0; $i < count($files); $i++) {
$fileStr = $files[$i];
$className = $namespace . static::CS . str_replace(static::DS, static::CS, $fileStr);
if ($withoutAutoload || class_exists($className, true)) {
$classNames[] = $className;
}
}
return $classNames;
} | php | {
"resource": ""
} |
q265904 | ClassFinderHelper.getNamespacePath | test | public static function getNamespacePath($namespace, $first = true)
{
$namespace = trim($namespace, static::CS);
$nsPrefixes = static::getNamespacePrefixes($namespace);
$loaderPrefixes = static::getLoaderPrefixes();
$nsSuffix = '';
foreach ($nsPrefixes as $prefix) {
if (!isset($loaderPrefixes[$prefix])) {
continue;
}
$nsSuffix = trim(mb_substr($namespace, mb_strlen($prefix)), static::CS);
$paths = $loaderPrefixes[$prefix];
break;
}
if (!isset($paths)) {
return $first ? null : [];
}
$results = [];
foreach ($paths as $path) {
$result = $path . static::DS . str_replace('\\', static::DS, $nsSuffix);
if (!file_exists($result) || !is_dir($result)) {
continue;
}
if ($first) {
return $result;
}
$results[] = $result;
}
return $results;
} | php | {
"resource": ""
} |
q265905 | ClassFinderHelper.getNamespacePaths | test | protected static function getNamespacePaths($namespace) {
$paths = [];
$namespace = trim($namespace, static::CS);
$nsPrefixes = static::getNamespacePrefixes($namespace);
$nsPrefixesCount = count($nsPrefixes);
$loaderPrefixes = static::getLoaderPrefixes();
$nsPrefix = null;
for ($i = 0; $i < $nsPrefixesCount; $i++) {
$nsPrefix = $nsPrefixes[$i];
if (!isset($loaderPrefixes[$nsPrefix])) {
continue;
}
if ($nsPrefix === $namespace) {
return $loaderPrefixes[$nsPrefix];
}
$nsSuffix = trim(substr($namespace, strlen($nsPrefix)), static::CS);
$nsSuffix = str_replace(static::CS, static::DS, $nsSuffix);
$loaderPaths = $loaderPrefixes[$nsPrefix];
$loaderPathsCount = count($loaderPaths);
for ($j = 0; $j < $loaderPathsCount; $j++) {
$possiblePath = $loaderPaths[$j] . static::DS . $nsSuffix;
if(file_exists($possiblePath) && is_dir($possiblePath)) { $paths[] = $possiblePath; }
}
if (!empty($paths)) {
break;
}
}
if (empty($paths)) {
return [null, []];
}
return [$nsPrefix, $paths];
} | php | {
"resource": ""
} |
q265906 | ClassFinderHelper.getNamespacePrefixes | test | protected static function getNamespacePrefixes($namespace) {
$namespaceExp = explode(static::CS, trim($namespace, static::CS));
$namespaceExpCount = count($namespaceExp);
if ($namespaceExpCount === 1) {
return $namespaceExp;
}
$prefixes = [];
$currPrefix = '';
for ($i = 0; $i < $namespaceExpCount; $i++) {
$currPrefix .= static::CS . $namespaceExp[$i];
$prefixes[] = trim($currPrefix, static::CS);
}
$prefixes = array_reverse($prefixes);
return $prefixes;
} | php | {
"resource": ""
} |
q265907 | ClassFinderHelper.getLoaderPrefixes | test | protected static function getLoaderPrefixes() {
$loader = static::getLoader();
$_prefixes = [
[],
$loader->getPrefixesPsr4(),
];
$_prefixes = ArrayHelper::merge(...$_prefixes);
$prefixes = [];
foreach ($_prefixes as $prefix => $paths) {
$prefix = trim($prefix, '\\');
$_paths = [];
for ($i = 0; $i < count($paths); $i++) { $_paths[] = realpath($paths[$i]); }
$prefixes[$prefix] = $_paths;
}
return $prefixes;
} | php | {
"resource": ""
} |
q265908 | FilterComponent.updateSession | test | public function updateSession()
{
$existingSession = $this->getSession();
if ($this->form) {
$filters = $this->form->getData() + $this->filterDefaults();
} else {
$filters = $this->filterDefaults();
}
$currentValues = [
'filters' => $filters,
'page' => $this->pageFromQuery(),
];
$newSession = array_merge($this->sessionDefaults(), $existingSession, $currentValues);
$this->session->set($this->sessionKey, $newSession);
} | php | {
"resource": ""
} |
q265909 | FilterComponent.mergeSession | test | public function mergeSession(array $newValues)
{
$existing = $this->getSession();
$new = array_merge($existing, $newValues);
$this->session->set($this->sessionKey, $new);
} | php | {
"resource": ""
} |
q265910 | FilterComponent.getSession | test | public function getSession($key = null)
{
// merge the arrays, using the default values if not in the session
$sessionData = (array) $this->session->get($this->sessionKey) + $this->sessionDefaults();
if (null === $key) {
return $sessionData;
} else if (array_key_exists($key, $sessionData)) {
return $sessionData[$key];
} else {
return null;
}
} | php | {
"resource": ""
} |
q265911 | FilterComponent.pageFromQuery | test | public function pageFromQuery()
{
if ($this->request) {
$page = $this->request->query->getInt('page');
} else {
$page = 0;
}
return ($page > 0) ? $page : 1;
} | php | {
"resource": ""
} |
q265912 | FilterComponent.query | test | public function query()
{
$queryData = [
self::FORM_BLOCK_NAME => $this->getFiltersAsArray(),
'page' => $this->getSession('page'),
];
return http_build_query($queryData);
} | php | {
"resource": ""
} |
q265913 | FilterComponent.getFiltersAsArray | test | protected function getFiltersAsArray()
{
$filters = $this->getSession('filters');
foreach ($filters as $key => $value) {
if ($value instanceof ArrayCollection) {
$filters[$key] = $filters[$key]->map(
function ($entity) {
return $entity->getId();
}
)->toArray();
} else if (is_array($value)) {
foreach ($value as $_key => $_value) {
if ($this->filterIsEntity($_value)) {
$filters[$key][$_key] = $_value->getId();
}
}
} else if ($this->filterIsEntity($value)) {
$filters[$key] = $value->getId();
}
}
return $filters;
} | php | {
"resource": ""
} |
q265914 | FilterComponent.createForm | test | public function createForm(array $formOptions = [])
{
$defaults = $this->filterDefaults();
$this->form = $this->formFactory->create(
$this->formType,
$defaults,
$formOptions
);
if ($this->request) {
$this->form->handleRequest($this->request);
}
return $this->form;
} | php | {
"resource": ""
} |
q265915 | FilterComponent.storeResult | test | public function storeResult($idOnlyQb)
{
$result = $idOnlyQb->getQuery()->getArrayResult();
$resultIds = array_column($result, 'id');
$this->mergeSession(['ids' => $resultIds]);
} | php | {
"resource": ""
} |
q265916 | FilterComponent.getPagination | test | public function getPagination($query)
{
$pagination = $this->paginator->paginate(
$query,
$this->pageFromQuery(),
$this->getPageLimit()
);
return $pagination;
} | php | {
"resource": ""
} |
q265917 | FilterComponent.prevNext | test | public function prevNext($currentRecordId)
{
$recordIds = (array) $this->getSession('ids');
$prevRecordId = $nextRecordId = null;
$currentKey = array_search($currentRecordId, $recordIds);
if (false !== $currentKey) {
if ($currentKey > 0) {
$prevRecordId = $recordIds[$currentKey - 1];
}
if ($currentKey < count($recordIds) - 1) {
$nextRecordId = $recordIds[$currentKey + 1];
}
}
return [$prevRecordId, $nextRecordId];
} | php | {
"resource": ""
} |
q265918 | Module.toArray | test | public function toArray()
{
return [
'icon' => $this->icon,
'title' => $this->title,
'subtitle' => $this->subtitle,
'fields' => $this->fields->map(function ($field) {
return $field->toArray();
})->all(),
'query' => $this->query,
];
} | php | {
"resource": ""
} |
q265919 | Module.addField | test | private function addField(array $args, $type = null)
{
if (count($args) !== 2) {
throw new InvalidFieldParametersException('You need pass only name, and title parameters to field');
}
return $this->fields->put($args[0], new Field($this, $args[0], $type, $args[1]));
} | php | {
"resource": ""
} |
q265920 | AbstractDBALCommand.processOptions | test | protected function processOptions(InputInterface $input)
{
if ($this->getContainer()->offsetExists('dbs')) {
$params = $this->getContainer()['dbs'][$input->getOption('connection')]
->getParams();
$this->getHelperSet()->set(
new ConnectionHelper(
$this->getContainer()['dbs'][$input->getOption('connection')],
'db'
)
);
} else {
$params = $this->getHelper('db')->getConnection()->getParams();
}
if ($input->getOption('user') != null) {
$params['user'] = $input->getOption('user');
$params['password'] = $input->getOption('password');
}
unset($params['dbname']);
unset($params['path']);
$this->setConnection(DriverManager::getConnection($params));
} | php | {
"resource": ""
} |
q265921 | AbstractDBALCommand.getConnectionParams | test | protected function getConnectionParams($connectionName = null)
{
return ($connectionName != null ) ?
$this->getContainer()['dbs'][$connectionName]->getParams():
$this->getHelper('db')->getConnection()->getParams();
} | php | {
"resource": ""
} |
q265922 | SqliteAdapter.isInstalled | test | public function isInstalled($db_name)
{
if (empty($dbname)) $dbname='default';
return file_exists(CarteBlanche::getFullPath('db_dir') . CarteBlanche::getConfig($dbname.'_database.db_name'));
} | php | {
"resource": ""
} |
q265923 | Select.getSql | test | public function getSql()
{
if ($this->adapter === null) {
$msg = __METHOD__ . ": Error, prior to use execute method you must provide a valid database adapter. See Select::setDbAdapter() method.";
throw new Exception\InvalidUsageException($msg);
}
$sql = new Sql($this->adapter);
return $sql->getSqlStringForSqlObject($this);
} | php | {
"resource": ""
} |
q265924 | Select.execute | test | public function execute()
{
if ($this->adapter === null) {
$msg = __METHOD__ . ": Error, prior to use execute method you must provide a valid database adapter. See Select::setDbAdapter() method.";
throw new Exception\InvalidUsageException($msg);
}
$sql = new Sql($this->adapter);
$sql_string = $sql->getSqlStringForSqlObject($this);
//return $this->adapter->createStatement($sql_string)->execute();
//return $this->adapter->query($sql_string, Adapter::QUERY_MODE_EXECUTE);
$result = $this->adapter->getDriver()->getConnection()->execute($sql_string);
$resultset = new ResultSet();
$resultset->initialize($result);
return $resultset;
} | php | {
"resource": ""
} |
q265925 | NativeEntityManager.getRepository | test | public function getRepository(string $entity): Repository
{
if (isset($this->repositories[$entity])) {
return $this->repositories[$entity];
}
/** @var Entity|string $entity */
$repository = $entity::getRepository() ?? PDORepository::class;
return $this->repositories[$entity] = new $repository($this, $entity, $entity::getTable());
} | php | {
"resource": ""
} |
q265926 | NativeEntityManager.create | test | public function create(Entity $entity): void
{
$id = spl_object_id($entity);
$this->createModels[$id] = $entity;
} | php | {
"resource": ""
} |
q265927 | NativeEntityManager.save | test | public function save(Entity $entity): void
{
$id = spl_object_id($entity);
$this->saveModels[$id] = $entity;
} | php | {
"resource": ""
} |
q265928 | NativeEntityManager.remove | test | public function remove(Entity $entity): bool
{
// Get the id of the object
$id = spl_object_id($entity);
// If the model is set to be created
if (isset($this->createModels[$id])) {
// Unset it
unset($this->createModels[$id]);
return true;
}
// If the model is set to be saved
if (isset($this->saveModels[$id])) {
// Unset it
unset($this->saveModels[$id]);
return true;
}
// The model wasn't set for creation or saving
return false;
} | php | {
"resource": ""
} |
q265929 | NativeEntityManager.commit | test | public function commit(): bool
{
// Iterate through the models awaiting creation
foreach ($this->createModels as $cid => $createModel) {
// Create the model
$this->getRepository(\get_class($createModel))->create($createModel);
// Unset the model
unset($this->createModels[$cid]);
}
// Iterate through the models awaiting save
foreach ($this->saveModels as $sid => $saveModel) {
// Save the model
$this->getRepository(\get_class($saveModel))->save($saveModel);
// Unset the model
unset($this->saveModels[$sid]);
}
return $this->store()->commit();
} | php | {
"resource": ""
} |
q265930 | NativeEntityManager.getStore | test | protected function getStore(string $name = null): PDO
{
$name = $name ?? $this->app->config()['database']['default'];
if (isset($this->stores[$name])) {
return $this->stores[$name];
}
$config = $this->getStoreConfig($name);
return $this->stores[$name] = $this->getStoreFromConfig($config);
} | php | {
"resource": ""
} |
q265931 | NativeEntityManager.getStoreConfig | test | protected function getStoreConfig(string $name): array
{
$config = $this->app->config('database.connections.' . $name);
if (null === $config) {
throw new InvalidArgumentException('Invalid connection name specified: ' . $name);
}
return $config;
} | php | {
"resource": ""
} |
q265932 | NativeEntityManager.getStoreFromConfig | test | protected function getStoreFromConfig(array $config): PDO
{
$dsn = $config['driver']
. ':host=' . $config['host']
. ';port=' . $config['port']
. ';dbname=' . $config['database']
. ';charset=' . $config['charset'];
return new PDO(
$dsn,
$config['username'],
$config['password'],
[]
);
} | php | {
"resource": ""
} |
q265933 | Password.validate | test | private function validate($password): void {
if(strlen($password) < $this->validationMinLength()) {
throw new InvalidArgumentException("The password must be at least {$this->validationMinLength()} characters long");
}
if(strlen($password) > $this->validationMaxLength()) {
throw new InvalidArgumentException("The password must be no more than {$this->validationMaxLength()} characters long");
}
} | php | {
"resource": ""
} |
q265934 | Accept.from | test | public static function from($accept = null, $acceptLanguage = null, $acceptEncoding = null, $acceptCharset = null)
{
$medias = static::parse($accept, '/');
$languages = static::parse($acceptLanguage, '-');
$encodings = static::parse($acceptEncoding);
$charsets = static::parse($acceptCharset);
return new static($medias, $languages, $encodings, $charsets);
} | php | {
"resource": ""
} |
q265935 | Accept.parse | test | protected static function parse($string, $separator = null)
{
$items = [];
if($string) {
$string = strtolower(str_replace(' ', '', $string));
$rows = explode(',', $string);
foreach($rows as $row) {
@list($item, $quality) = explode(';q=', $row);
if(!$quality) {
if($separator) {
@list($part, $subpart) = explode($separator, $item);
$quality = ($part = '*' or $subpart == '*') ? 0 : 1;
}
else {
$quality = ($item == '*') ? 0 : 1;
}
}
$items[$item] = (float)$quality;
}
sort($items);
$items = array_keys($items);
}
return $items;
} | php | {
"resource": ""
} |
q265936 | Accept.compare | test | protected static function compare($needle, array $haystack)
{
foreach($haystack as $row) {
if(fnmatch($row, $needle)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q265937 | Earth.earthRadius | test | public function earthRadius($latitude) {
$radLat = deg2rad($latitude);
$x = cos($radLat) / $this->earthRadiusSemimajor();
$y = sin($radLat) / $this->earthRadiusSemiminor();
return 1 / (sqrt($x * $x + $y * $y));
} | php | {
"resource": ""
} |
q265938 | Earth.convertDecToDMS | test | public function convertDecToDMS($coordinate) {
$dms = array();
$parts = explode('.', $coordinate);
// The degrees portion.
$dms['degrees'] = $parts[0];
// Calculate the minutes
$temp = ("0." . $parts[1]) * 3600;
$dms['minutes'] = floor($temp / 60);
// Find the seconds left over
$dms['seconds'] = $temp - ($dms['minutes'] * 60);
return $dms;
} | php | {
"resource": ""
} |
q265939 | Earth.convertDMStoDec | test | public function convertDMStoDec($degrees, $minutes, $seconds) {
if ($degrees < 0) {
return $degrees - ((($minutes * 60) + $seconds) / 3600);
}
return $degrees + ((($minutes * 60) + $seconds) / 3600);
} | php | {
"resource": ""
} |
q265940 | ErrorException.productionRendering | test | public function productionRendering()
{
$args = array('message'=>$this->getAppMessage());
$ft = CarteBlanche::getContainer()->get('front_controller');
return ($ft ? $ft->renderProductionError($args, 500) : parent::__toString());
} | php | {
"resource": ""
} |
q265941 | ErrorException.debugRendering | test | public function debugRendering()
{
$args = array('message'=>$this->getAppMessage());
$ft = CarteBlanche::getContainer()->get('front_controller');
return ($ft ? $ft->renderError($args, $this) : parent::__toString());
} | php | {
"resource": ""
} |
q265942 | ErrorException.log | test | public function log()
{
CarteBlanche::log(
$this->getAppMessage()."\n".$this->getTraceAsString(),
\Library\Logger::ERROR
);
} | php | {
"resource": ""
} |
q265943 | MessageController.actionConfig | test | public function actionConfig(RequestApplicationInterface $app, $filePath)
{
$filePath = Reaction::getAlias($filePath);
if (file_exists($filePath)) {
$confirmPromise = $this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?");
} else {
$confirmPromise = resolve(true);
}
return $confirmPromise
->then(function() use ($filePath) {
$array = VarDumper::export($this->getOptionValues($this->getCurrentAction()));
$content = <<<EOD
<?php
/**
* Configuration file for 'console {$this->getUniqueId()}/{$this->defaultAction}' command.
*
* This file is automatically generated by 'console {$this->getUniqueId()}/{$this->getCurrentAction()}' command.
* It contains parameters for source code messages extraction.
* You may modify this file to suit your needs.
*
* You can use 'console {$this->getUniqueId()}/{$this->getCurrentAction()}-template' command to create
* template configuration file with detailed description for each parameter.
*/
return $array;
EOD;
return FileHelperAsc::exists($filePath)
->then(null, function() use ($filePath) {
return FileHelperAsc::create($filePath, $this->filesystemMode);
})->then(function() use ($filePath, $content) {
return FileHelperAsc::putContents($filePath, $content);
})->then(function() use ($filePath) {
$this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN);
return true;
}, function($error) use ($filePath) {
$this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED);
return reject($error);
});
});
} | php | {
"resource": ""
} |
q265944 | MessageController.actionConfigTemplate | test | public function actionConfigTemplate(RequestApplicationInterface $app, $filePath)
{
$filePath = Reaction::getAlias($filePath);
if (file_exists($filePath)) {
$confirmPromise = $this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?");
} else {
$confirmPromise = resolve(true);
}
return $confirmPromise
->then(function() use ($filePath) {
if (!copy(Reaction::getAlias('@reaction/Views/message/config.php'), $filePath)) {
return reject(new Exception("Configuration file template was NOT created at '{$filePath}'."));
}
$this->stdout("Configuration file template created at '{$filePath}'.\n\n", Console::FG_GREEN);
return true;
});
} | php | {
"resource": ""
} |
q265945 | MessageController.saveMessagesToPHP | test | protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
{
$promises = [];
foreach ($messages as $category => $msgs) {
$file = str_replace('\\', '/', "$dirName/$category.php");
$path = dirname($file);
$msgs = array_values(array_unique($msgs));
$coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
$this->stdout("Saving messages to $coloredFileName...\n");
$promises[] = FileHelperAsc::createDir($path, $this->filesystemMode)
->then(function() use ($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused) {
return $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused);
});
}
return all($promises);
} | php | {
"resource": ""
} |
q265946 | MessageController.saveMessagesToPOT | test | protected function saveMessagesToPOT($messages, $dirName, $catalog)
{
$file = str_replace('\\', '/', "$dirName/$catalog.pot");
FileHelper::createDirectory(dirname($file), $this->filesystemMode);
$this->stdout("Saving messages to $file...\n");
$poFile = new GettextPoFile();
$merged = [];
$hasSomethingToWrite = false;
foreach ($messages as $category => $msgs) {
$msgs = array_values(array_unique($msgs));
sort($msgs);
foreach ($msgs as $message) {
$merged[$category . chr(4) . $message] = '';
}
$this->stdout("Category \"$category\" merged.\n");
$hasSomethingToWrite = true;
}
if ($hasSomethingToWrite) {
return new Promise(function($r, $c) use ($poFile, $merged, $file) {
ksort($merged);
$poFile->save($merged, $file);
$this->stdout("Translation saved.\n", Console::FG_GREEN);
return true;
});
} else {
$this->stdout("Nothing to save.\n", Console::FG_GREEN);
return resolve(true);
}
} | php | {
"resource": ""
} |
q265947 | TimeBuilder.fromArray | test | public static function fromArray(array $data): Time
{
if (!isset($data['hours'])) {
throw new \InvalidArgumentException('Array is not valid.');
}
return new Time(
$data['hours'],
$data['minutes'] ?? 0,
$data['seconds'] ?? 0
);
} | php | {
"resource": ""
} |
q265948 | TimeBuilder.fromString | test | public static function fromString($time): Time
{
if (empty($time)) {
throw new \InvalidArgumentException('Invalid time "".');
}
try {
$date = new \DateTime($time);
} catch (\Exception $e) {
throw new \InvalidArgumentException(\sprintf('Invalid time "%s".', $time), 0, $e);
}
$return = static::fromDate($date);
if (\strpos($time, '24') === 0) {
$return->setHours(24);
}
return $return;
} | php | {
"resource": ""
} |
q265949 | TimeBuilder.fromDate | test | public static function fromDate(\DateTime $date): Time
{
return new Time((int)$date->format('H'), (int)$date->format('i'), (int)$date->format('s'));
} | php | {
"resource": ""
} |
q265950 | TimeBuilder.fromSeconds | test | public static function fromSeconds(int $seconds): Time
{
if ($seconds < 0 || $seconds > 86400) {
throw new \InvalidArgumentException(\sprintf('Invalid time "%s".', $seconds));
}
$data = [
'hours' => (int)($seconds / 3600),
'minutes' => ($seconds / 60) % 60,
'seconds' => $seconds % 60
];
return self::fromArray($data);
} | php | {
"resource": ""
} |
q265951 | TagManager.invalidateTags | test | public function invalidateTags($tags)
{
if (empty($tags) || !$this->isEnabled()) {
return;
}
$tags = $this->encodeTags($tags);
foreach ($tags as $tag) {
if (!in_array($tag, $this->invalidateTags)) {
$this->invalidateTags[] = $tag;
}
}
} | php | {
"resource": ""
} |
q265952 | TagManager.flush | test | public function flush()
{
if (!empty($this->invalidateTags)) {
$this->tagHandler->invalidateTags($this->invalidateTags);
}
if (!empty($this->responseTags)) {
$this->tagHandler->addTags($this->responseTags);
}
$this->reset();
} | php | {
"resource": ""
} |
q265953 | TagManager.encodeTags | test | private function encodeTags($tags)
{
if (!is_array($tags)) {
$tags = array($tags);
}
if ($this->config['tag']['encode']) {
$tmp = [];
foreach ($tags as $tag) {
$tmp[] = hash('crc32b', $this->config['tag']['secret'].$tag, false);
}
$tags = $tmp;
}
return $tags;
} | php | {
"resource": ""
} |
q265954 | Config.register | test | public function register()
{
$namespace = $this->package->getNamespace();
$config = $this->app->make('config');
try
{
$path = $this->getPath() . '/config.php';
if($this->app->environment() === 'testing') {
if( ! $this->filesystem->exists($path)) {
return $config->set([
$namespace => $this->getOptions()
]);
}
}
return $config->set([
$namespace => include($path)
]);
} catch(\Exception $e) {
$msg = "You need to publish the configs for the package {$this->package->getName()}";
$this->error(new PackageConfigMissing($msg));
}
} | php | {
"resource": ""
} |
q265955 | Cookies.all | test | public function all(bool $asString = true): array
{
if (! $asString) {
return $this->cookies;
}
$flattenedCookies = [];
/** @var array $path */
foreach ($this->cookies as $path) {
/** @var array $cookies */
foreach ($path as $cookies) {
/** @var \Valkyrja\Http\Cookie $cookie */
foreach ($cookies as $cookie) {
$flattenedCookies[] = $cookie;
}
}
}
return $flattenedCookies;
} | php | {
"resource": ""
} |
q265956 | Cookies.set | test | public function set(Cookie $cookie): self
{
$this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
return $this;
} | php | {
"resource": ""
} |
q265957 | Cookies.remove | test | public function remove(string $name, string $path = '/', string $domain = null): self
{
$path = $path ?? '/';
unset($this->cookies[$domain][$path][$name]);
if (empty($this->cookies[$domain][$path])) {
unset($this->cookies[$domain][$path]);
if (empty($this->cookies[$domain])) {
unset($this->cookies[$domain]);
}
}
return $this;
} | php | {
"resource": ""
} |
q265958 | PEAR_Frontend_CLI.confirmDialog | test | function confirmDialog($params)
{
$answers = $prompts = $types = array();
foreach ($params as $param) {
$prompts[$param['name']] = $param['prompt'];
$types[$param['name']] = $param['type'];
$answers[$param['name']] = isset($param['default']) ? $param['default'] : '';
}
$tried = false;
do {
if ($tried) {
$i = 1;
foreach ($answers as $var => $value) {
if (!strlen($value)) {
echo $this->bold("* Enter an answer for #" . $i . ": ({$prompts[$var]})\n");
}
$i++;
}
}
$answers = $this->userDialog('', $prompts, $types, $answers);
$tried = true;
} while (is_array($answers) && count(array_filter($answers)) != count($prompts));
return $answers;
} | php | {
"resource": ""
} |
q265959 | AbstractPostType.getLabels | test | protected function getLabels()
{
$pluralName = $this->getPluralName();
$singularName = $this->getSingularName();
return array(
'name' => $singularName,
'singular_name' => $singularName,
'add_new' => 'Add New',
'add_new_item' => 'Add New ' . $singularName,
'edit_item' => 'Edit ' . $singularName,
'new_item' => 'New ' . $singularName,
'all_items' => 'All ' . $pluralName,
'view_item' => 'View ' . $singularName,
'search_items' => 'Search ' . $pluralName,
'not_found' => 'No ' . $pluralName . ' found',
'not_found_in_trash' => 'No ' . $pluralName . ' found in Trash',
'parent_item_colon' => '',
'menu_name' => $pluralName
);
} | php | {
"resource": ""
} |
q265960 | LivePubControllerHooks.WrappedSession | test | public function WrappedSession()
{
LivePubHelper::require_session();
$obj = LivePubHelper::wrap($_SESSION);
$obj->setVar('_SESSION');
return $obj;
} | php | {
"resource": ""
} |
q265961 | ConstraintFinderTrait.getTablePrimaryKey | test | public function getTablePrimaryKey($name, $refresh = false)
{
return $this->getTableMetadata($name, SchemaInterface::META_PK, $refresh);
} | php | {
"resource": ""
} |
q265962 | ConstraintFinderTrait.getTableForeignKeys | test | public function getTableForeignKeys($name, $refresh = false)
{
return $this->getTableMetadata($name, SchemaInterface::META_FK, $refresh);
} | php | {
"resource": ""
} |
q265963 | ConstraintFinderTrait.getTableIndexes | test | public function getTableIndexes($name, $refresh = false)
{
return $this->getTableMetadata($name, SchemaInterface::META_INDEXES, $refresh);
} | php | {
"resource": ""
} |
q265964 | ConstraintFinderTrait.getTableUniques | test | public function getTableUniques($name, $refresh = false)
{
return $this->getTableMetadata($name, SchemaInterface::META_UNIQUES, $refresh);
} | php | {
"resource": ""
} |
q265965 | ConstraintFinderTrait.getTableChecks | test | public function getTableChecks($name, $refresh = false)
{
return $this->getTableMetadata($name, SchemaInterface::META_CHECKS, $refresh);
} | php | {
"resource": ""
} |
q265966 | ConstraintFinderTrait.getTableDefaultValues | test | public function getTableDefaultValues($name, $refresh = false)
{
return $this->getTableMetadata($name, SchemaInterface::META_DEFAULTS, $refresh);
} | php | {
"resource": ""
} |
q265967 | ParameterRepository.get | test | public function get($key)
{
return $this->container->hasParameter($key) ? $this->container->getParameter($key) : null;
} | php | {
"resource": ""
} |
q265968 | OmacTrait.checkAccess | test | protected function checkAccess($permission, $arguments = '') {
if ( $this->acl === false )
return true;
$driver = "acl" . ucfirst( $this->driver );
return $this->$driver($permission, $arguments);
} | php | {
"resource": ""
} |
q265969 | SelectQuery.distinct | test | public function distinct(bool $enable = true)
{
$this->changed = true;
$this->distinct = $enable;
return $this;
} | php | {
"resource": ""
} |
q265970 | SelectQuery.columns | test | public function columns(string ...$column)
{
$this->changed = true;
$this->columns = $column;
return $this;
} | php | {
"resource": ""
} |
q265971 | SelectQuery.join | test | public function join(string $table, array $on)
{
$this->changed = true;
$this->joins[] = ['JOIN', $table, $on];
return $this;
} | php | {
"resource": ""
} |
q265972 | SelectQuery.innerJoin | test | public function innerJoin(string $table, array $on)
{
$this->changed = true;
$this->joins[] = ['INNER JOIN', $table, $on];
return $this;
} | php | {
"resource": ""
} |
q265973 | SelectQuery.leftJoin | test | public function leftJoin(string $table, array $on)
{
$this->changed = true;
$this->joins[] = ['LEFT JOIN', $table, $on];
return $this;
} | php | {
"resource": ""
} |
q265974 | SelectQuery.leftOuterJoin | test | public function leftOuterJoin(string $table, array $on)
{
$this->changed = true;
$this->joins[] = ['LEFT OUTER JOIN', $table, $on];
return $this;
} | php | {
"resource": ""
} |
q265975 | SelectQuery.rightJoin | test | public function rightJoin(string $table, array $on)
{
$this->changed = true;
$this->joins[] = ['RIGHT JOIN', $table, $on];
return $this;
} | php | {
"resource": ""
} |
q265976 | SelectQuery.outerJoin | test | public function outerJoin(string $table, array $on)
{
$this->changed = true;
$this->joins[] = ['OUTER JOIN', $table, $on];
return $this;
} | php | {
"resource": ""
} |
q265977 | SelectQuery.fullOuterJoin | test | public function fullOuterJoin(string $table, array $on)
{
$this->changed = true;
$this->joins[] = ['FULL OUTER JOIN', $table, $on];
return $this;
} | php | {
"resource": ""
} |
q265978 | SelectQuery.groupBy | test | public function groupBy(string ...$field)
{
$this->changed = true;
$this->groupBy = $field;
return $this;
} | php | {
"resource": ""
} |
q265979 | SelectQuery.andHaving | test | public function andHaving(array $conditions)
{
$this->changed = true;
$this->having = [
'AND',
$this->having,
$conditions,
];
return $this;
} | php | {
"resource": ""
} |
q265980 | SelectQuery.orHaving | test | public function orHaving(array $conditions)
{
$this->changed = true;
$this->having = [
'OR',
$this->having,
$conditions,
];
return $this;
} | php | {
"resource": ""
} |
q265981 | SelectQuery.orderBy | test | public function orderBy(string ...$field)
{
$this->changed = true;
$this->orderBy = $field;
return $this;
} | php | {
"resource": ""
} |
q265982 | SelectQuery.limit | test | public function limit(int $limit, int $offset = null)
{
$this->changed = true;
$this->limit = $limit;
if ($offset !== null) {
$this->offset = $offset;
}
return $this;
} | php | {
"resource": ""
} |
q265983 | SelectQuery.offset | test | public function offset(int $offset)
{
$this->changed = true;
$this->offset = $offset;
return $this;
} | php | {
"resource": ""
} |
q265984 | SelectQuery.build | test | protected function build()
{
if (!$this->from) {
throw new \RuntimeException("No tables provided for FROM clause");
}
$this->placeholders = [];
$this->placeholderCounter = 1;
$sql = ['SELECT'];
if ($this->distinct) {
$sql[] = 'DISTINCT';
}
$sql[] = implode(', ', $this->columns);
$sql[] = 'FROM';
$sql[] = implode(', ', $this->from);
if ($this->joins) {
foreach ($this->joins as $join) {
$sql[] = $join[0];
$sql[] = $join[1];
$sql[] = 'ON';
$sql[] = is_string($join[2])
? $join[2]
: $this->buildConditions($join[2], false);
}
}
if ($this->conditions) {
$sql[] = 'WHERE';
$sql[] = $this->buildConditions($this->conditions);
}
if ($this->groupBy) {
$sql[] = 'GROUP BY';
$sql[] = implode(', ', $this->groupBy);
}
if ($this->having) {
$sql[] = 'HAVING';
$sql[] = $this->buildConditions($this->having);
}
if ($this->orderBy) {
$sql[] = 'ORDER BY';
$sql[] = implode(', ', $this->orderBy);
}
if ($this->limit || $this->offset) {
$sql[] = 'LIMIT';
$parts = [];
if ($this->offset) {
if (!$this->limit) {
$this->limit = PHP_INT_MAX;
}
$parts[] = $this->addPlaceholder($this->offset);
}
if ($this->limit) {
$parts[] = $this->addPlaceholder($this->limit);
}
$sql[] = implode(', ', $parts);
}
$this->sql = implode(' ', $sql);
$this->changed = false;
} | php | {
"resource": ""
} |
q265985 | UiExtension.renderLink | test | public function renderLink($href, $label = '', array $options = [], array $attributes = [])
{
$options['type'] = 'link';
$options['path'] = $href;
return $this->renderButton($label, $options, $attributes);
} | php | {
"resource": ""
} |
q265986 | UiExtension.renderButton | test | public function renderButton($label = '', array $options = [], array $attributes = [])
{
$options = $this->getButtonOptionsResolver()->resolve($options);
$tag = 'button';
$classes = ['btn', 'btn-'.$options['theme'], 'btn-'.$options['size']];
$defaultAttributes = [
'class' => sprintf('btn btn-%s btn-%s', $options['theme'], $options['size']),
];
if ($options['type'] == 'link') {
if (0 == strlen($options['path'])) {
throw new \InvalidArgumentException('"path" option must be defined for "link" button type.');
}
$tag = 'a';
$defaultAttributes['href'] = $options['path'];
} else {
$defaultAttributes['type'] = $options['type'];
}
if (array_key_exists('class', $attributes)) {
$classes = array_merge($classes, explode(' ', $attributes['class']));
unset($attributes['class']);
}
$defaultAttributes['class'] = implode(' ', $classes);
$attributes = array_merge($defaultAttributes, $attributes);
$icon = '';
if(0 < strlen($options['icon'])) {
$icon = $options['fa_icon'] ? 'fa fa-'.$options['icon'] : 'glyphicon glyphicon-'.$options['icon'];
}
return $this->controlsTemplate->renderBlock('button', [
'tag' => $tag,
'attr' => $attributes,
'label' => $label,
'icon' => $icon,
]);
} | php | {
"resource": ""
} |
q265987 | UiExtension.renderLocaleSwitcher | test | public function renderLocaleSwitcher($attributes = [])
{
// TODO Check if this is a (esi) sub request, as this must never be used in a esi fragment.
if (null === $request = $this->requestStack->getCurrentRequest()) {
return '';
}
if (!array_key_exists('class', $attributes)) {
$attributes['class'] = 'list-inline locale-switcher';
}
return $this->controlsTemplate->renderBlock('locale_switcher', [
'locales' => $this->config['locales'],
'request' => $request,
'attr' => $attributes,
]);
} | php | {
"resource": ""
} |
q265988 | Line.__equationToString | test | public function __equationToString()
{
$str = '';
$a = $this->getSlope();
if ($a!=1) {
$str .= "({$a} * x)";
} else {
$str .= "x";
}
$b = $this->getYIntercept();
if ($b!=0) {
$str .= " + {$b}";
}
return "y = f(x){ {$str} }";
} | php | {
"resource": ""
} |
q265989 | Line.getOrdinateByAbscissa | test | public function getOrdinateByAbscissa($x)
{
if ($this->isHorizontal()) {
return $this->getPointA()->getOrdinate();
}
return (($this->getSlope() * $x) + $this->getYIntercept());
} | php | {
"resource": ""
} |
q265990 | Line.getAbscissaByOrdinate | test | public function getAbscissaByOrdinate($y)
{
if ($this->isVertical()) {
return $this->getPointA()->getAbscissa();
}
return (($y - $this->getYIntercept()) / $this->getSlope());
} | php | {
"resource": ""
} |
q265991 | Table.findOrFail | test | public function findOrFail($id)
{
$record = $this->find($id);
if ($record === false) {
throw new Exception\NotFoundException(__METHOD__ . ": cannot find record '$id' in table '$this->table'");
}
return $record;
} | php | {
"resource": ""
} |
q265992 | Table.findOneByOrFail | test | public function findOneByOrFail($predicate, $combination = Predicate\PredicateSet::OP_AND)
{
$record = $this->findOneBy($predicate, $combination);
if ($record === false) {
throw new Exception\NotFoundException(__METHOD__ . ": cannot findOneBy record in table '$this->table'");
}
return $record;
} | php | {
"resource": ""
} |
q265993 | Table.exists | test | public function exists($id)
{
$result = $this->select()->where($this->getPrimaryKeyPredicate($id))
->columns(['count' => new Expression('count(*)')])
->execute()
->toArray();
return ($result[0]['count'] > 0);
} | php | {
"resource": ""
} |
q265994 | Table.existsBy | test | public function existsBy($predicate, $combination = Predicate\PredicateSet::OP_AND)
{
try {
$select = $this->select()->where($predicate, $combination)
->columns(['count' => new Expression('count(*)')]);
$result = $select->execute()
->toArray();
} catch (\Exception $e) {
throw new Exception\InvalidArgumentException(__METHOD__ . ": invaid usage ({$e->getMessage()})");
}
return ($result[0]['count'] > 0);
} | php | {
"resource": ""
} |
q265995 | Table.deleteBy | test | public function deleteBy($predicate, $combination = Predicate\PredicateSet::OP_AND)
{
$delete = $this->sql->delete($this->prefixed_table)
->where($predicate, $combination);
$statement = $this->sql->prepareStatementForSqlObject($delete);
$result = $statement->execute();
return $result->getAffectedRows();
} | php | {
"resource": ""
} |
q265996 | Table.deleteOrFail | test | public function deleteOrFail($id)
{
$deleted = $this->delete($id);
if ($deleted == 0) {
throw new Exception\NotFoundException(__METHOD__ . ": cannot delete record '$id' in table '$this->table'");
}
return $this;
} | php | {
"resource": ""
} |
q265997 | Table.update | test | public function update($data, $predicate, $combination = Predicate\PredicateSet::OP_AND, $validate_datatypes = false)
{
$prefixed_table = $this->prefixed_table;
if ($data instanceof ArrayObject) {
$d = (array) $data;
} elseif (is_array($data)) {
$d = $data;
} else {
throw new Exception\InvalidArgumentException(__METHOD__ . ": requires data to be array or an ArrayObject");
}
$this->checkDataColumns($d);
if ($validate_datatypes) {
$this->validateDatatypes($d);
}
$update = $this->sql->update($prefixed_table);
$update->set($d);
$update->where($predicate, $combination);
$result = $this->executeStatement($update);
return $result->getAffectedRows();
} | php | {
"resource": ""
} |
q265998 | Table.insert | test | public function insert($data, $validate_datatypes = false)
{
$prefixed_table = $this->prefixed_table;
if ($data instanceof \ArrayObject) {
$d = (array) $data;
} elseif (is_array($data)) {
$d = $data;
} else {
$type = gettype($data);
throw new Exception\InvalidArgumentException(__METHOD__ . ": expects data to be array or ArrayObject. Type receive '$type'");
}
$this->checkDataColumns($d);
if ($validate_datatypes) {
$this->validateDatatypes($d);
}
$insert = $this->sql->insert($prefixed_table);
$insert->values($d);
$this->executeStatement($insert);
$pks = $this->getPrimaryKeys();
// Should never happen, as getPrimaryKeys throws Exception when no pk exists
//@codeCoverageIgnoreStart
if (!is_array($pks)) {
$msg = __METHOD__ . " Error getting primary keys of table " . $this->table . ", require array, returned type is: " . gettype($pks) ;
throw new Exception\UnexpectedValueException($msg);
}
//@codeCoverageIgnoreEnd
$nb_pks = count($pks);
if ($nb_pks > 1) {
// In multiple keys there should not be autoincrement value
$id = [];
foreach ($pks as $pk) {
$id[$pk] = $d[$pk];
}
} elseif (array_key_exists($pks[0], $d) && $d[$pks[0]] !== null) {
// not using autogenerated value
//$id = $d[$this->getPrimaryKey()];
$id = $d[$pks[0]];
} else {
$id = $this->tableManager->getDbAdapter()->getDriver()->getLastGeneratedValue();
}
return $this->findOrFail($id);
} | php | {
"resource": ""
} |
q265999 | Table.relation | test | public function relation()
{
if ($this->relation === null) {
$this->relation = new Table\Relation($this);
}
return $this->relation;
} | php | {
"resource": ""
} |
Subsets and Splits