_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5600 | Validator.isOrdered | train | protected function isOrdered(array $ordered)
{
// validate fields by exist in tables
foreach ($ordered as $table => $sort) {
// load model metaData
if ($this->isModel($table) === true) {
$model = (new Manager())->load($table, new $table);
// check fields of table
$this->validColumns($model->getModelsMetaData(), array_keys($sort), $table, $model);
// check sort clause
$sort = array_map('strtolower', $sort);
if (empty($diff = array_diff(array_values($sort), $this->sort)) === false) {
throw new ExceptionFactory('Column', ['ORDER_TYPES_DOES_NOT_EXISTS', $diff]);
}
if (empty($diff = array_diff($sort, $this->sort)) === false) {
throw new ExceptionFactory('Column', ['ORDER_TYPES_DOES_NOT_EXISTS', $diff]);
}
$this->fields[$this->cast][$model->getSource()] = $sort;
}
}
return true;
} | php | {
"resource": ""
} |
q5601 | Validator.validTypes | train | protected function validTypes(Column $column)
{
if (in_array($column->getType(), $this->columns) === false) {
throw new ExceptionFactory('Column', ['COLUMN_DOES_NOT_SUPPORT', $column->getType(), $column->getName()]);
}
return true;
} | php | {
"resource": ""
} |
q5602 | Validator.validColumns | train | protected function validColumns(Memory $meta, array $columns, $table, $model)
{
if (empty($not = array_diff($columns, $meta->getAttributes($model))) === false) {
throw new ExceptionFactory('Column', ['COLUMN_DOES_NOT_EXISTS', $not, $table, $meta->getAttributes($model)]);
}
return true;
} | php | {
"resource": ""
} |
q5603 | HistoryManager.findAll | train | public function findAll()
{
if ($this->fileManager->isDir(Installer::BASE_PATH . self::HISTORY_PATH) === false) {
throw new EnvironnementResolverException(
sprintf(
'Unable to locate "%d"',
Installer::BASE_PATH . self::HISTORY_PATH
)
);
}
$historyCollection = new HistoryCollection();
$searchPath = Installer::BASE_PATH . self::HISTORY_PATH . '*' . self::FILE_EXTENSION;
foreach ($this->fileManager->glob($searchPath) as $file) {
$content = $this->fileManager->fileGetContent($file);
try {
$historyCollection->append($this->historyHydrator->jsonToDTO($content));
} catch (InvalidHistoryException $e) {
continue;
}
}
return $historyCollection;
} | php | {
"resource": ""
} |
q5604 | UserController.indexAction | train | public function indexAction()
{
$allowed_users = array();
$users = $this->getDoctrine()->getManager()->createQuery('SELECT r FROM FOMUserBundle:User r')->getResult();
// ACL access check
foreach ($users as $index => $user) {
if ($this->isGranted('VIEW', $user)) {
$allowed_users[] = $user;
}
}
$oid = new ObjectIdentity('class', 'FOM\UserBundle\Entity\User');
return array(
'users' => $allowed_users,
'create_permission' => $this->isGranted('CREATE', $oid)
);
} | php | {
"resource": ""
} |
q5605 | EnforceContentSecurity.addPolicyHeader | train | protected function addPolicyHeader(ResponseInterface $response)
{
$this->loadDefaultProfiles();
$currentHeader = $response->getHeader($this->header);
$initialConfig = [];
if (count($currentHeader)) {
$initialConfig = $this->decodeConfiguration($currentHeader[0]);
}
$initialDirectives = $this->encodeConfiguration($initialConfig);
$this->mergeProfileWithConfig($initialConfig);
$newDirectives = $this->encodeConfiguration($this->config);
if ($newDirectives != $initialDirectives) {
$response = $response->withHeader($this->header, $newDirectives);
}
return $response;
} | php | {
"resource": ""
} |
q5606 | EnforceContentSecurity.decodeConfiguration | train | protected function decodeConfiguration($string)
{
$config = [];
$directives = explode($this->directiveSeparator, $string);
foreach ($directives as $directive) {
$parts = array_filter(explode($this->sourceSeparator, $directive));
$key = trim(array_shift($parts));
$config[$key] = $parts;
}
return $config;
} | php | {
"resource": ""
} |
q5607 | EnforceContentSecurity.encodeConfiguration | train | protected function encodeConfiguration($config = [])
{
$value = [];
ksort($config);
foreach ($config as $directive => $values) {
$values = array_unique($values);
sort($values);
array_unshift($values, $directive);
$string = implode($this->sourceSeparator, $values);
if ($string) {
$value[] = $string;
}
}
return implode($this->directiveSeparator . ' ', $value);
} | php | {
"resource": ""
} |
q5608 | EnforceContentSecurity.getArrayFromValue | train | protected function getArrayFromValue($value, $separator = ',')
{
if (!is_array($value)) {
$value = explode($separator, $value);
}
return $value;
} | php | {
"resource": ""
} |
q5609 | EnforceContentSecurity.loadDefaultProfiles | train | protected function loadDefaultProfiles()
{
$defaultProfiles = [];
if (isset($this->profiles['default'])) {
$defaultProfiles = $this->getArrayFromValue(
$this->profiles['default']
);
}
array_map([$this, 'loadProfileByKey'], $defaultProfiles);
} | php | {
"resource": ""
} |
q5610 | EnforceContentSecurity.loadProfileByKey | train | protected function loadProfileByKey($key)
{
if (isset($this->profiles['profiles'][$key])) {
$profile = $this->profiles['profiles'][$key];
if (is_array($profile)) {
$this->mergeProfileWithConfig($profile);
}
}
} | php | {
"resource": ""
} |
q5611 | EnforceContentSecurity.mergeProfileWithConfig | train | protected function mergeProfileWithConfig(array $profile)
{
foreach ($profile as $directive => $values) {
if (!isset($this->config[$directive])) {
$this->config[$directive] = [];
}
$values = $this->getArrayFromValue($values);
$this->config[$directive] = array_merge($this->config[$directive], $values);
}
} | php | {
"resource": ""
} |
q5612 | Tags.getValue | train | public function getValue()
{
$arr = [];
if (!is_array($this->_options['value'])) {
return [];
}
foreach ($this->_options['value'] as $key) {
$arr[$key] = $key;
}
return $arr;
} | php | {
"resource": ""
} |
q5613 | File.moveTo | train | public function moveTo($dst, $allowedExtensions = 'jpg,jpeg,png,gif,doc,xls,pdf,zip', $overwrite = false)
{
if ($allowedExtensions !== '*') {
$extension = pathinfo($dst, PATHINFO_EXTENSION);
if (!$extension || preg_match("#\b$extension\b#", $allowedExtensions) !== 1) {
throw new FileException(['`:extension` file type is not allowed upload', 'extension' => $extension]);
}
}
if ($this->_file['error'] !== UPLOAD_ERR_OK) {
throw new FileException(['error code of upload file is not UPLOAD_ERR_OK: :error', 'error' => $this->_file['error']]);
}
if ($this->filesystem->fileExists($dst)) {
if ($overwrite) {
$this->filesystem->fileDelete($dst);
} else {
throw new FileException(['`:file` file already exists', 'file' => $dst]);
}
}
$this->filesystem->dirCreate(dirname($dst));
if (!move_uploaded_file($this->_file['tmp_name'], $this->alias->resolve($dst))) {
throw new FileException(['move_uploaded_file to `:dst` failed: :last_error_message', 'dst' => $dst]);
}
if (!chmod($this->alias->resolve($dst), 0644)) {
throw new FileException(['chmod `:dst` destination failed: :last_error_message', 'dst' => $dst]);
}
} | php | {
"resource": ""
} |
q5614 | File.getExtension | train | public function getExtension()
{
$name = $this->_file['name'];
return ($extension = pathinfo($name, PATHINFO_EXTENSION)) === $name ? '' : $extension;
} | php | {
"resource": ""
} |
q5615 | ProviderSelector.select | train | public function select(string $type = null)
{
if (empty($type)) {
$type = $this->provider;
}
$providers = $this->mergeProviders();
if (!isset($providers[$type])) {
throw new InvalidArgumentException(sprintf('Provider %s does not exist', $type));
}
$providerBeanName = $providers[$type];
return App::getBean($providerBeanName);
} | php | {
"resource": ""
} |
q5616 | PhpStringParser.staticPhp | train | public function staticPhp($text)
{
$textExplode = explode('->', $text);
$variableName = str_replace('$', '', array_shift($textExplode));
$variableVariable = $this->variables;
if (isset($variableVariable[$variableName]) === false) {
throw new \InvalidArgumentException(
sprintf('variable %s does not exist', $variableName)
);
}
$textExplode = array_map(
function ($value) {
return str_replace('()', '', $value);
},
$textExplode
);
$instance = $variableVariable[$variableName];
$keys = array_values($textExplode);
$lastKey = array_pop($keys);
foreach ($textExplode as $key => $method) {
if ($instance === null && $lastKey !== $key) {
throw new \InvalidArgumentException(sprintf('method %s return null', $method));
} elseif (false === method_exists($instance, $method)) {
throw new \InvalidArgumentException(sprintf('method %s does not exist on %s', $method, $text));
} else {
$instance = $instance->$method();
}
}
return $instance;
} | php | {
"resource": ""
} |
q5617 | GlideKeyGenerate.setKeyInEnvironmentFile | train | protected function setKeyInEnvironmentFile($key)
{
$currentContent = file_get_contents(base_path('.env'));
$currentValue = '';
if (preg_match('/^GLIDE_SIGN_KEY=(.*)$/m', $currentContent, $matches) && isset($matches[1])) {
$currentValue = $matches[1];
}
file_put_contents(base_path('.env'), str_replace(
'GLIDE_SIGN_KEY='.$currentValue,
'GLIDE_SIGN_KEY='.$key,
$currentContent
));
} | php | {
"resource": ""
} |
q5618 | ServeController.defaultCommand | train | public function defaultCommand($ip = '127.0.0.1', $port = 1983)
{
$router_str = <<<'STR'
<?php
$_SERVER['SERVER_ADDR'] = ':ip';
$_SERVER['SERVER_PORT'] = ':port';
$_SERVER['REQUEST_SCHEME'] = 'http';
chdir('public');
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if ($uri !== '/') {
if (file_exists('public/' . $uri)
|| preg_match('#\.(?:css|js|gif|png|jpg|jpeg|ttf|woff|ico)$#', $uri) === 1
) {
return false;
}
}
$_GET['_url'] = $uri;
$_REQUEST['_url'] = $uri;
require_once 'index.php';
STR;
if ($value = $this->arguments->getValue(0)) {
if (strpos($value, ':')) {
list($ip, $port) = explode(':', $value, 2);
} elseif (is_numeric($value)) {
$port = (int)$value;
} else {
$ip = $value;
}
}
$router = 'builtin_server_router.php';
$this->filesystem->filePut("@tmp/$router", strtr($router_str, [':ip' => $ip, ':port' => $port]));
echo "server listen on: $ip:$port", PHP_EOL;
$prefix = $this->router->getPrefix();
if (DIRECTORY_SEPARATOR === '\\') {
shell_exec("explorer.exe http://$ip:$port" . $prefix);
}
shell_exec("php -S $ip:$port -t public tmp/$router");
} | php | {
"resource": ""
} |
q5619 | TwigTemplateIterator.getIterator | train | public function getIterator()
{
$this->kernel->boot();
$viewDirectories = $this->getPossibleViewDirectories();
$viewDirectories = $this->removeNotExistingDirectories($viewDirectories);
$templates = $this->getTwigTemplatesIn($viewDirectories);
return new \ArrayIterator($templates);
} | php | {
"resource": ""
} |
q5620 | TwigTemplateIterator.getTwigTemplatesIn | train | protected function getTwigTemplatesIn($directories)
{
if (count($directories) === 0) {
return array();
}
$templates = Finder::create()->in($directories)->files()->name('*.*.twig');
$templates = iterator_to_array($templates, false);
$templates = array_map(function (SplFileInfo $file) {
return $file->getRealPath();
}, $templates);
return $templates;
} | php | {
"resource": ""
} |
q5621 | CategoryWidgetModel.findWidgetRelationById | train | public function findWidgetRelationById($id)
{
//iteracja po relacjach
foreach ($this->_widgetCollection as $widgetRelationRecord) {
//relacja odnaleziona
if ($widgetRelationRecord->id == $id) {
return $widgetRelationRecord;
}
}
} | php | {
"resource": ""
} |
q5622 | PLUGObject.trigger_error | train | protected function trigger_error( $code, $message, $type = E_USER_NOTICE ){
$trace = debug_backtrace();
$Err = PLUG::raise_error( $code, $message, $type, $trace );
$this->on_trigger_error( $Err );
} | php | {
"resource": ""
} |
q5623 | PLUGObject.get_error_level | train | function get_error_level() {
// calculate level in case global errors have been cleared
$e = 0;
foreach( $this->err_stack as $t => $ids ) {
foreach( $ids as $id ){
$Err = PLUGError::get_reference( $t, $id );
if( is_object($Err) ){
$e |= $t;
break;
}
}
}
return $e;
} | php | {
"resource": ""
} |
q5624 | PLUGObject.get_errors | train | function get_errors( $emask = null ) {
$errs = array();
foreach( $this->err_stack as $t => $ids ) {
if( $emask !== NULL && ( $emask & $t ) == 0 ) {
// ignore this error
continue;
}
// collect these errors
foreach( $ids as $id ){
$Err = PLUGError::get_reference( $t, $id );
if( is_object($Err) ){
$errs[] = $Err;
}
}
}
return $errs;
} | php | {
"resource": ""
} |
q5625 | PLUGObject.clear_errors | train | function clear_errors( $emask = null ) {
foreach( $this->err_stack as $t => $ids ) {
if( $emask !== NULL && ( $emask & $t ) == 0 ) {
// ignore this error
continue;
}
// clear these errors
foreach( $ids as $id ){
$Err = PLUGError::get_reference( $t, $id );
$Err->clear();
}
unset( $this->err_stack[$t] );
}
} | php | {
"resource": ""
} |
q5626 | PLUGObject.dump_errors | train | function dump_errors( $emask = null ) {
foreach( $this->err_stack as $t => $ids ) {
if( $emask !== NULL && ( $emask & $t ) == 0 ) {
// ignore this error
continue;
}
// dump these errors
foreach( $ids as $id ){
$Err = PLUGError::get_reference( $t, $id );
echo (string) $Err;
echo $Err->getTraceAsString(), "\n";
}
}
} | php | {
"resource": ""
} |
q5627 | PLUGObject.is_error | train | function is_error( $emask = null ) {
$e = $this->get_error_level();
if( $emask === null ){
return (bool) $e;
}
else {
return (bool) ( $e & $emask );
}
} | php | {
"resource": ""
} |
q5628 | MetaDataDAOCache.getAllMetadata | train | public function getAllMetadata()
{
$configName = ($this->config !== null) ? $this->config->getUniqueName() : '';
$cacheFilename = Installer::BASE_PATH . Installer::CACHE_PATH . DIRECTORY_SEPARATOR;
$cacheFilename .= md5('all_metadata' . get_class($this->metadataDAO) . $configName);
if ($this->fileManager->isFile($cacheFilename) === true && $this->noCache === false) {
$data = unserialize($this->fileManager->fileGetContent($cacheFilename));
} else {
$data = $this->metadataDAO->getAllMetadata();
$this->fileManager->filePutsContent($cacheFilename, serialize($data));
}
return $data;
} | php | {
"resource": ""
} |
q5629 | Lex.defined | train | function defined( $c ){
if( isset($this->literals[$c]) ){
return true;
}
if( ! defined($c) ){
return false;
}
$i = constant( $c );
return isset( $this->names[$i] ) && $this->names[$i] === $c;
} | php | {
"resource": ""
} |
q5630 | Lex.name | train | function name( $i ){
if( is_int($i) ){
if( ! isset($this->names[$i]) ){
trigger_error("symbol ".var_export($i,1)." is unknown in ".get_class($this), E_USER_NOTICE );
return 'UNKNOWN';
}
else {
return $this->names[$i];
}
}
else if ( ! isset($this->literals[$i]) ){
trigger_error("literal symbol ".var_export($i,1)." is unknown in ".get_class($this), E_USER_NOTICE );
}
return $i;
} | php | {
"resource": ""
} |
q5631 | LRNDA.export | train | function export(){
$RootSet = $this->resolve();
$table = array();
$RootSet->export( $table, $this->Grammar );
return new LRParseTableBuilder( $table );
} | php | {
"resource": ""
} |
q5632 | LRNDA.resolve | train | function resolve(){
LRState::clear_index();
LRStation::clear_index();
// create Root Set
// we SHOULD have a single etransition to an intial state
return LRStateSet::init( $this->etransitions[0], $this->Grammar );
} | php | {
"resource": ""
} |
q5633 | MetaDataSourceFinder.getAllAdapters | train | public function getAllAdapters()
{
$classCollection = $this->classAwake->wakeByInterfaces(
array(
__DIR__ . '/Sources/',
),
'CrudGenerator\Metadata\Sources\MetaDataDAOFactoryInterface'
);
$adapterCollection = new MetaDataSourceCollection();
foreach ($classCollection as $className) {
$adapterCollection->append(
$this->metaDataSourceHydrator->adapterNameToMetaDataSource(
$className
)
);
}
return $adapterCollection;
} | php | {
"resource": ""
} |
q5634 | Amqp.purgeQueue | train | public function purgeQueue($name)
{
if (!isset($this->_queues[$name])) {
throw new InvalidKeyException(['purge `:queue` queue failed: it is NOT exists', 'queue' => $name]);
}
try {
$this->_queues[$name]->purge();
} catch (\Exception $e) {
throw new AmqpException(['purge `:queue` queue failed: error', 'queue' => $name, 'error' => $e->getMessage()]);
}
return $this;
} | php | {
"resource": ""
} |
q5635 | Model.getFieldTypes | train | public function getFieldTypes()
{
static $cached = [];
$class = static::class;
if (!isset($cached[$class])) {
if (!$doc = static::sample()) {
if (!$docs = $this->getConnection()->fetchAll($this->getSource(), [], ['limit' => 1])) {
throw new RuntimeException(['`:collection` collection has none record', 'collection' => $this->getSource()]);
}
$doc = $docs[0];
}
$types = [];
foreach ($doc as $field => $value) {
$type = gettype($value);
if ($type === 'integer') {
$types[$field] = 'int';
} elseif ($type === 'string') {
$types[$field] = 'string';
} elseif ($type === 'double') {
$types[$field] = 'float';
} elseif ($type === 'boolean') {
$types[$field] = 'bool';
} elseif ($type === 'array') {
$types[$field] = 'array';
} elseif ($value instanceof ObjectID) {
if ($field === '_id') {
continue;
}
$types[$field] = 'objectid';
} else {
throw new RuntimeException(['`:field` field value type can not be infered.', 'field' => $field]);
}
}
$cached[$class] = $types;
}
return $cached[$class];
} | php | {
"resource": ""
} |
q5636 | Loader.registerNamespaces | train | public function registerNamespaces($namespaces, $merge = true)
{
foreach ($namespaces as $namespace => $path) {
$path = rtrim($path, '\\/');
if (DIRECTORY_SEPARATOR === '\\') {
$namespaces[$namespace] = strtr($path, '\\', '/');
}
}
$this->_namespaces = $merge ? array_merge($this->_namespaces, $namespaces) : $namespaces;
return $this;
} | php | {
"resource": ""
} |
q5637 | Loader.registerClasses | train | public function registerClasses($classes, $merge = true)
{
if (DIRECTORY_SEPARATOR === '\\') {
foreach ($classes as $key => $path) {
$classes[$key] = strtr($path, '\\', '/');
}
}
$this->_classes = $merge ? array_merge($this->_classes, $classes) : $classes;
return $this;
} | php | {
"resource": ""
} |
q5638 | Loader.requireFile | train | public function requireFile($file)
{
if (PHP_EOL !== "\n" && strpos($file, 'phar://') !== 0) {
$realPath = strtr(realpath($file), '\\', '/');
if ($realPath !== $file) {
trigger_error("File name ($realPath) case mismatch for .$file", E_USER_ERROR);
}
}
/** @noinspection PhpIncludeInspection */
require $file;
} | php | {
"resource": ""
} |
q5639 | Loader.load | train | public function load($className)
{
if (isset($this->_classes[$className])) {
$file = $this->_classes[$className];
if (!is_file($file)) {
trigger_error(strtr('load `:class` class failed: `:file` is not exists.', [':class' => $className, ':file' => $file]), E_USER_ERROR);
}
//either linux or phar://
if (PHP_EOL === "\n" || $file[0] === 'p') {
/** @noinspection PhpIncludeInspection */
require $file;
} else {
$this->requireFile($file);
}
return true;
}
/** @noinspection LoopWhichDoesNotLoopInspection */
foreach ($this->_namespaces as $namespace => $path) {
if (strpos($className, $namespace) !== 0) {
continue;
}
$file = $path . strtr(substr($className, strlen($namespace)), '\\', '/') . '.php';
if (is_file($file)) {
//either linux or phar://
if (PHP_EOL === "\n" || $file[0] === 'p') {
/** @noinspection PhpIncludeInspection */
require $file;
} else {
$this->requireFile($file);
}
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q5640 | ACEDataTransformer.transform | train | public function transform($ace)
{
$sid = null;
$mask = null;
$sidPrefix = '';
$sidName = '';
$permissions = array();
if($ace instanceof Entry) {
$sid = $ace->getSecurityIdentity();
$mask = $ace->getMask();
} elseif(is_array($ace)) {
$sid = $ace['sid'];
$mask = $ace['mask'];
}
$sidString = '';
if($sid instanceof RoleSecurityIdentity) {
$sidPrefix = 'r';
$sidName = $sid->getRole();
$sidString = sprintf('%s:%s', $sidPrefix, $sidName);
} elseif($sid instanceof UserSecurityIdentity) {
$sidPrefix = 'u';
$sidName = $sid->getUsername();
$sidClass = $sid->getClass();
$sidString = sprintf('%s:%s:%s', $sidPrefix, $sidName, $sidClass);
}
for($i = 1; $i <= 30; $i++) {
$key = 1 << ($i-1);
if($mask & $key) {
$permissions[$i] = true;
} else {
$permissions[$i] = false;
}
}
return array(
'sid' => $sidString,
'permissions' => $permissions);
} | php | {
"resource": ""
} |
q5641 | ACEDataTransformer.reverseTransform | train | public function reverseTransform($data)
{
$sidParts = explode(':', $data['sid']);
if(strtoupper($sidParts[0]) == 'R') {
/* is rolebased */
$sid = new RoleSecurityIdentity($sidParts[1]);
} else {
if(3 == count($sidParts)) {
/* has 3 sidParts */
$class = $sidParts[2];
} else {
if($this->isLdapUser($sidParts[1])) {
/* is LDAP user*/
$class = 'Mapbender\LdapIntegrationBundle\Entity\LdapUser';
} else {
/* is not a LDAP user*/
$class = 'FOM\UserBundle\Entity\User';
}
}
$sid = new UserSecurityIdentity($sidParts[1], $class);
}
$maskBuilder = new MaskBuilder();
foreach($data['permissions'] as $bit => $permission) {
if(true === $permission) {
$maskBuilder->add(1 << ($bit - 1));
}
}
return array(
'sid' => $sid,
'mask' => $maskBuilder->get());
} | php | {
"resource": ""
} |
q5642 | Neko.snakeCase | train | public static function snakeCase($value)
{
$key = $value;
if (isset(static::$snakeCache[$key])) {
return static::$snakeCache[$key];
}
$value = preg_replace('/\s+/', '', ucwords($value));
$value = str_replace('-', '_', $value);
$value = static::normalizeScreamingCase($value);
return static::$snakeCache[$key] = strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $value));
} | php | {
"resource": ""
} |
q5643 | Neko.kebabCase | train | public static function kebabCase($value)
{
$key = $value;
if (isset(static::$kebabCache[$key])) {
return static::$kebabCache[$key];
}
$value = preg_replace('/\s+/', '', ucwords($value));
$value = str_replace('_', '-', $value);
$value = static::normalizeScreamingCase($value);
return static::$kebabCache[$key] = strtolower(preg_replace('~(?<=\\w)([A-Z])~', '-$1', $value));
} | php | {
"resource": ""
} |
q5644 | Neko.pascalCase | train | public static function pascalCase($value)
{
if (isset(static::$pascalCache[$value])) {
return static::$pascalCache[$value];
}
$value = static::normalizeScreamingCase($value);
return static::$pascalCache[$value] = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $value)));
} | php | {
"resource": ""
} |
q5645 | Neko.camelCase | train | public static function camelCase($value)
{
if (isset(static::$camelCache[$value])) {
return static::$camelCache[$value];
}
return static::$camelCache[$value] = lcfirst(static::pascalCase($value));
} | php | {
"resource": ""
} |
q5646 | CategoryController.dispatchAction | train | public function dispatchAction()
{
//pobranie kategorii
$category = $this->_getPublishedCategoryByUri($this->uri);
//wpięcie kategorii do głównego widoku aplikacji
FrontController::getInstance()->getView()->category = $category;
//klucz bufora
$cacheKey = 'category-html-' . $category->id;
//buforowanie dozwolone
$bufferingAllowed = $this->_bufferingAllowed();
//wczytanie zbuforowanej strony (dla niezalogowanych i z pustym requestem)
if ($bufferingAllowed && (null !== $html = \App\Registry::$cache->load($cacheKey))) {
//wysyłanie nagłówka o buforowaniu strony
$this->getResponse()->setHeader('X-Cache', 'HIT');
//zwrot html
return $this->_decorateHtmlWithEditButton($html, $category);
}
//wysyłanie nagłówka o braku buforowaniu strony
$this->getResponse()->setHeader('X-Cache', 'MISS');
//przekazanie rekordu kategorii do widoku
$this->view->category = $category;
//renderowanie docelowej akcji
$html = \Mmi\Mvc\ActionHelper::getInstance()->forward($this->_prepareForwardRequest($category));
//buforowanie niedozwolone
if (!$bufferingAllowed || 0 == $cacheLifetime = $this->_getCategoryCacheLifetime($category)) {
//zwrot html
return $this->_decorateHtmlWithEditButton($html, $category);
}
//zapis html kategorii do cache
\App\Registry::$cache->save($html, $cacheKey, $cacheLifetime);
//zwrot html
return $this->_decorateHtmlWithEditButton($html, $category);
} | php | {
"resource": ""
} |
q5647 | CategoryController._prepareForwardRequest | train | protected function _prepareForwardRequest(\Cms\Orm\CmsCategoryRecord $category)
{
//tworzenie nowego requestu na podstawie obecnego
$request = clone $this->getRequest();
$request->setModuleName('cms')
->setControllerName('category')
->setActionName('article');
//przekierowanie MVC
if ($category->mvcParams) {
//tablica z tpl
$mvcParams = [];
//parsowanie parametrów mvc
parse_str($category->mvcParams, $mvcParams);
return $request->setParams($mvcParams);
}
//pobranie typu (szablonu) i jego parametrów mvc
if (!$category->getJoined('cms_category_type')->mvcParams) {
return $request;
}
//tablica z tpl
$mvcParams = [];
//parsowanie parametrów mvc
parse_str($category->getJoined('cms_category_type')->mvcParams, $mvcParams);
return $request->setParams($mvcParams);
} | php | {
"resource": ""
} |
q5648 | CategoryController._decorateHtmlWithEditButton | train | protected function _decorateHtmlWithEditButton($html, \Cms\Orm\CmsCategoryRecord $category)
{
//brak roli redaktora
if (!$this->_hasRedactorRole()) {
return $html;
}
//zwraca wyrenderowany HTML
return str_replace('</body>', \Mmi\Mvc\ActionHelper::getInstance()->action(new \Mmi\Http\Request(['module' => 'cms', 'controller' => 'category', 'action' => 'editButton', 'originalId' => $category->cmsCategoryOriginalId, 'categoryId' => $category->id])) . '</body>', $html);
} | php | {
"resource": ""
} |
q5649 | CategoryController._getCategoryCacheLifetime | train | protected function _getCategoryCacheLifetime(\Cms\Orm\CmsCategoryRecord $category)
{
//czas buforowania (na podstawie typu kategorii i pojedynczej kategorii
$cacheLifetime = (null !== $category->cacheLifetime) ? $category->cacheLifetime : ((null !== $category->getJoined('cms_category_type')->cacheLifetime) ? $category->getJoined('cms_category_type')->cacheLifetime : Orm\CmsCategoryRecord::DEFAULT_CACHE_LIFETIME);
//jeśli bufor wyłączony (na poziomie typu kategorii, lub pojedynczej kategorii)
if (0 == $cacheLifetime) {
//brak bufora
return 0;
}
//iteracja po widgetach
foreach ($category->getWidgetModel()->getWidgetRelations() as $widgetRelation) {
//bufor wyłączony przez widget
if (0 == $widgetCacheLifetime = $widgetRelation->getWidgetRecord()->cacheLifetime) {
//brak bufora
return 0;
}
//wpływ widgeta na czas buforowania kategorii
$cacheLifetime = ($cacheLifetime > $widgetCacheLifetime) ? $widgetCacheLifetime : $cacheLifetime;
}
//zwrot długości bufora
return $cacheLifetime;
} | php | {
"resource": ""
} |
q5650 | CategoryController._bufferingAllowed | train | protected function _bufferingAllowed()
{
//jeśli zdefiniowano własny obiekt sprawdzający, czy można buforować
if (\App\Registry::$config->category instanceof \Cms\Config\CategoryConfig && \App\Registry::$config->category->bufferingAllowedClass) {
$class = \App\Registry::$config->category->bufferingAllowedClass;
$buffering = new $class($this->_request);
} else {
//domyślny cmsowy obiekt sprawdzający, czy można buforować
$buffering = new \Cms\Model\CategoryBuffering($this->_request);
}
return $buffering->isAllowed();
} | php | {
"resource": ""
} |
q5651 | FileManager.filePutsContent | train | public function filePutsContent($path, $content)
{
if (@file_put_contents($path, $content) === false) {
throw new \RuntimeException(sprintf("Could't puts content %s", $path));
}
chmod($path, 0777);
} | php | {
"resource": ""
} |
q5652 | FileManager.ifDirDoesNotExistCreate | train | public function ifDirDoesNotExistCreate($directory, $recursive = false)
{
if ($this->isDir($directory) === false) {
$this->mkdir($directory, $recursive);
return true;
} else {
return false;
}
} | php | {
"resource": ""
} |
q5653 | Grammar.get_rules | train | function get_rules( $nt ){
$rules = array();
if( isset($this->ntindex[$nt]) ){
foreach( $this->ntindex[$nt] as $i ){
$rules[$i] = $this->rules[$i];
}
}
return $rules;
} | php | {
"resource": ""
} |
q5654 | Grammar.follow_set | train | function follow_set( $s ){
if( ! isset($this->follows[$s]) ){
$type = $this->is_terminal($s) ? 'terminal' : 'non-terminal';
trigger_error("No follow set for $type $s", E_USER_WARNING );
return array();
}
return $this->follows[$s];
} | php | {
"resource": ""
} |
q5655 | ArrayHydrator.extract | train | public function extract(callable $callback = null)
{
if ($callback === null) {
$result = $this->result->toArray();
}
else {
$result = $callback($this->result->toArray());
}
return $result;
} | php | {
"resource": ""
} |
q5656 | PLUGError.getTraceAsString | train | public function getTraceAsString() {
$lines = array ();
for( $i = 0; $i < count($this->trace); $i++ ){
$a = $this->trace[$i];
$call = "{$a['function']}()";
if( isset($a['class']) ){
$call = "{$a['class']}{$a['type']}$call";
}
$lines[] = "#$i {$a['file']}({$a['line']}): $call";
}
$lines[] = "#$i {main}";
return implode( "\n", $lines );
} | php | {
"resource": ""
} |
q5657 | PLUGError.raise | train | public function raise() {
// log error to file according to PLUG_ERROR_LOGGING
if( PLUG_ERROR_LOGGING & $this->type ) {
// send to standard, or configured log file
$logfile = defined('PLUG_ERROR_LOG') ? PLUG_ERROR_LOG : '';
$logged = self::log( call_user_func(self::$logfunc,$this), $logfile );
}
// add to error stack if we are keeping this type if error
// internal errors are always raised
if( PLUG_ERROR_REPORTING & $this->type || $this->type === E_USER_INTERNAL ) {
// register self as a raised error
$this->id = self::$i++;
self::$stack[ $this->type ][ $this->id ] = $this;
// cli can pipe error to stderr, but not if the logging call already did.
if( PLUG_CLI ){
self::log( call_user_func(self::$logfunc,$this), STDERR );
}
}
// call exit handler on fatal error
// @todo - configurable fatal level
$fatal = E_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR;
if( $this->type & $fatal ){
call_user_func( self::$deathfunc, $this );
}
} | php | {
"resource": ""
} |
q5658 | PLUGError.death | train | private static function death( PLUGError $Err ){
if( PLUG_CLI ){
// Print final death message to stderr if last error was logged
$logfile = ini_get('error_log');
if( $logfile ){
PLUGCli::stdout("Error, %s exiting %s\n", $Err->getMessage(), $Err->code );
}
}
else {
// display all errors in browser
PLUG::dump_errors();
}
exit( $Err->code );
} | php | {
"resource": ""
} |
q5659 | PLUGError.log | train | static function log( $logline, $out = '' ) {
// Output log line, no error checking to save performance
// Send to descriptor or other stream if resource passed
if( is_resource($out) && fwrite( $out, "$logline\n" ) ){
return true;
}
// Log to specified file
else if( $out && error_log( "$logline\n", 3, $out ) ){
return $out;
}
// else default - probably apache error log
else if( error_log( $logline, 0 ) ){
$out = ini_get('error_log');
return $out ? $out : true;
}
else {
return false;
}
} | php | {
"resource": ""
} |
q5660 | PLUGError.display | train | static function display( PLUGError $Err ){
$html = ini_get('html_errors');
if( $html ){
$s = '<div class="error"><strong>%s:</strong> %s. in <strong>%s</strong> on line <strong>%u</strong></div>';
}
else {
$s = "\n%s: %s. in %s on line %u";
}
$args = array (
$s,
$Err->getTypeString(),
$Err->getMessage(),
$Err->getFile(),
$Err->getLine()
);
// add trace in dev mode
if( ! PLUG::is_compiled() ){
$args[0] .= $html ? "\n<pre>%s</pre>" : "\n%s";
$args[] = $Err->getTraceAsString();
}
return call_user_func_array( 'sprintf', $args );
} | php | {
"resource": ""
} |
q5661 | PLUGError.clear | train | public function clear() {
unset( self::$stack[ $this->type ][ $this->id ] );
if( empty( self::$stack[ $this->type ] ) ){
unset( self::$stack[ $this->type ] );
}
$this->id = null;
} | php | {
"resource": ""
} |
q5662 | PLUGError.get_errors | train | static function get_errors( $emask = null ) {
$all = array();
foreach( self::$stack as $type => $errs ){
if( $emask === null || $type & $emask ) {
foreach( $errs as $Err ){
$all[] = $Err;
}
}
}
return $all;
} | php | {
"resource": ""
} |
q5663 | PLUGError.& | train | static function &get_reference( $type, $id ) {
if( empty( self::$stack[ $type ][ $id ] ) ){
$null = null;
return $null;
}
else {
return self::$stack[ $type ][ $id ];
}
} | php | {
"resource": ""
} |
q5664 | PLUGError.is_error | train | static function is_error( $emask = null ) {
if( $emask === null ){
return (bool) self::get_global_level();
}
else {
return (bool) ( self::get_global_level() & $emask );
}
} | php | {
"resource": ""
} |
q5665 | PLUGError.get_global_level | train | static function get_global_level () {
$e = 0;
$types = array_keys( self::$stack );
foreach( $types as $t ) {
$e |= $t;
}
return $e;
} | php | {
"resource": ""
} |
q5666 | JsonMetaDataDAO.isFirstLevelIsDto | train | private function isFirstLevelIsDto(\JSONSchema\Structure\Schema $schema)
{
$isFirstLevelIsDto = false;
foreach ($schema->getProperties() as $propertie) {
if (in_array($propertie->getType(), array('object', 'array')) === false) {
$isFirstLevelIsDto = true;
}
}
return $isFirstLevelIsDto;
} | php | {
"resource": ""
} |
q5667 | JsonMetaDataDAO.hydrateItems | train | private function hydrateItems(
$daddyName,
array $items,
MetadataDataObjectJson $metadata,
MetaDataCollection $mainCollection
) {
$mergeArray = true;
if ($mergeArray === true && $this->itemsAreAllOfType($items, array('object')) === true) {
$metadata->appendRelation(
$this->hydrateMetaDataRelationColumn(
$daddyName,
$this->mergeItems($items),
$metadata,
$mainCollection
)
);
} else {
$specialProperties = array();
foreach ($items as $propName => $item) {
// Relation of relation
if (in_array($item->getType(), array('object', 'array')) === false) {
$specialProperties[$propName] = $item;
continue;
}
$metadata->appendRelation(
$this->hydrateMetaDataRelationColumn($daddyName, $item->getProperties(), $metadata, $mainCollection)
);
}
}
return $metadata;
} | php | {
"resource": ""
} |
q5668 | JsonMetaDataDAO.hydrateProperties | train | private function hydrateProperties(
array $properties,
MetadataDataObjectJson $metadata,
MetaDataCollection $mainCollection
) {
$specialProperties = array();
foreach ($properties as $propName => $propertie) {
if (false === ($propertie instanceof \JSONSchema\Structure\Property)) {
throw new \Exception('$propertie is not an instance of Property');
}
if (in_array($propertie->getType(), array('object', 'array')) === true) {
$specialProperties[$propName] = $propertie;
continue;
}
$column = new MetaDataColumn();
$column->setNullable(!$propertie->getRequired());
$column->setName($propertie->getName());
$column->setType($propertie->getType());
$metadata->appendColumn($column);
}
if ($specialProperties !== array()) {
foreach ($specialProperties as $prop) {
$metadata->appendRelation(
$this->hydrateMetaDataRelationColumn(
$prop->getName(),
$prop->getProperties(),
$metadata,
$mainCollection
)
);
}
}
return $metadata;
} | php | {
"resource": ""
} |
q5669 | JsonMetaDataDAO.getMetadataFor | train | public function getMetadataFor($tableName, array $parentName = array())
{
$avaibleData = array();
foreach ($this->getAllMetadata() as $metadata) {
$avaibleData[] = $metadata->getName();
if ($metadata->getName() === $tableName) {
return $metadata;
}
}
throw new \Exception(sprintf('"%s" not found in "%s"', $tableName, implode(', ', $avaibleData)));
} | php | {
"resource": ""
} |
q5670 | Mail.pushEmail | train | public static function pushEmail($name, $to, array $params = [], $fromName = null, $replyTo = null, $subject = null, $sendAfter = null, array $attachments = [])
{
//brak definicji
if (null === ($def = Orm\CmsMailDefinitionQuery::langByName($name)
->findFirst())) {
return false;
}
//walidacja listy adresów "do"
$email = new \Mmi\Validator\EmailAddressList;
if (!$email->isValid($to)) {
return false;
}
//nowy rekord maila
$mail = new Orm\CmsMailRecord;
$mail->cmsMailDefinitionId = $def->id;
$mail->to = $to;
$mail->fromName = $fromName ? $fromName : $def->fromName;
$mail->replyTo = $replyTo ? $replyTo : $def->replyTo;
$mail->subject = $subject ? $subject : $def->subject;
$mail->dateSendAfter = $sendAfter ? $sendAfter : date('Y-m-d H:i:s');
$files = [];
//załączniki
foreach ($attachments as $fileName => $filePath) {
if (!file_exists($filePath)) {
continue;
}
$files[$fileName] = ($filePath);
}
//serializacja załączników
$mail->attachements = serialize($files);
//przepychanie zmiennych do widoku
$view = \Mmi\App\FrontController::getInstance()->getView();
foreach ($params as $key => $value) {
$view->$key = $value;
}
//rendering wiadomości
$mail->message = $view->renderDirectly($def->message);
//rendering tematu
$mail->subject = $view->renderDirectly($mail->subject);
$mail->dateAdd = date('Y-m-d H:i:s');
//zapis maila
return $mail->save();
} | php | {
"resource": ""
} |
q5671 | Mail.getMultioptions | train | public static function getMultioptions()
{
$rows = (new Orm\CmsMailServerQuery)
->whereActive()->equals(1)
->find();
$pairs = [];
foreach ($rows as $row) {
$pairs[$row->id] = $row->address . ':' . $row->port . ' (' . $row->username . ')';
}
return $pairs;
} | php | {
"resource": ""
} |
q5672 | Compiler._compileComments | train | protected function _compileComments($value)
{
$pattern = sprintf('/%s--(.*?)--%s/s', $this->_escapedTags[0], $this->_escapedTags[1]);
return preg_replace($pattern, '<?php /*$1*/ ?> ', $value);
} | php | {
"resource": ""
} |
q5673 | Compiler._compileEchos | train | protected function _compileEchos($value)
{
foreach ($this->_getEchoMethods() as $method => $length) {
$value = $this->$method($value);
}
return $value;
} | php | {
"resource": ""
} |
q5674 | Compiler._getEchoMethods | train | protected function _getEchoMethods()
{
$methods = [
'_compileRawEchos' => strlen(stripcslashes($this->_rawTags[0])),
'_compileEscapedEchos' => strlen(stripcslashes($this->_escapedTags[0])),
];
uksort($methods, static function ($method1, $method2) use ($methods) {
// Ensure the longest tags are processed first
if ($methods[$method1] > $methods[$method2]) {
return -1;
}
if ($methods[$method1] < $methods[$method2]) {
return 1;
}
// Otherwise give preference to raw tags (assuming they've overridden)
if ($method1 === '_compileRawEchos') {
return -1;
}
if ($method2 === '_compileRawEchos') {
return 1;
}
if ($method1 === '_compileEscapedEchos') {
return -1;
}
if ($method2 === '_compileEscapedEchos') {
return 1;
}
return 0;
});
return $methods;
} | php | {
"resource": ""
} |
q5675 | Compiler._compile_allow | train | protected function _compile_allow($expression)
{
$parts = explode(',', substr($expression, 1, -1));
$expr = $this->compileString($parts[1]);
return "<?php if (\$di->authorization->isAllowed($parts[0])): ?>$expr<?php endif ?>";
} | php | {
"resource": ""
} |
q5676 | Compiler._compile_asset | train | protected function _compile_asset($expression)
{
if (strcspn($expression, '$\'"') === strlen($expression)) {
$expression = '(\'' . trim($expression, '()') . '\')';
}
return asset(substr($expression, 2, -2));
/*return "<?= asset{$expression}; ?>";*/
} | php | {
"resource": ""
} |
q5677 | ConnectorController.importFileAction | train | public function importFileAction()
{
//text/plain
$this->getResponse()->setTypePlain();
//adres endpointu
$endpoint = base64_decode($this->url) . '/?module=cms&controller=connector&name=' . $this->name . '&action=';
try {
//wczytanie danych
$data = json_decode(file_get_contents($endpoint . 'exportFileMeta'), true);
} catch (\Exception $e) {
//zwrot pustego statusu
return 'ERR';
}
//próba importu meta-danych
if (null === $file = (new Model\ConnectorModel)->importFileMeta($data)) {
//plik istnieje, lub próba nie udana
return 'META ERROR';
}
try {
mkdir(dirname($file->getRealPath()), 0777, true);
} catch (\Exception $e) {
//nic
}
try {
//próba pobrania i zapisu binarium
file_put_contents($file->getRealPath(), file_get_contents($endpoint . 'exportFileBinary'));
} catch (\Exception $e) {
die($e->getMessage());
//zwrot pustego statusu
return 'BIN ERROR';
}
return 'OK';
} | php | {
"resource": ""
} |
q5678 | ConnectorController.exportFileBinaryAction | train | public function exportFileBinaryAction()
{
$this->getResponse()->setType('application/octet-stream')
->send();
//wyszukiwanie pliku
if (null === $file = (new Orm\CmsFileQuery)->whereName()->equals($this->name)
->findFirst()) {
throw new \Mmi\Mvc\MvcNotFoundException('File not found');
}
//plik zbyt duży do transferu
if ($file->size > self::MAX_FILE_SIZE) {
throw new \Mmi\Mvc\MvcForbiddenException('File to large');
}
readfile($file->getRealPath());
exit;
} | php | {
"resource": ""
} |
q5679 | ConnectorController.exportFileMetaAction | train | public function exportFileMetaAction()
{
//wyszukiwanie pliku
if (null === $files = (new Orm\CmsFileQuery)->whereName()->equals($this->name)
->find()) {
throw new \Mmi\Mvc\MvcNotFoundException('File not found');
}
$data = [];
//iteracja po plikach
foreach ($files as $file) {
//spłaszczenie meta-danych
$file->data = ($file->data && ($file->data instanceof \Mmi\DataObject)) ? json_encode($file->data->toArray()) : null;
$data[] = $file->toArray();
}
//zwrot meta
return json_encode($data);
} | php | {
"resource": ""
} |
q5680 | Log.add | train | public static function add($operation = null, array $data = [])
{
\Mmi\App\FrontController::getInstance()->getLogger()->info('Legacy log: ' . $operation);
\Mmi\App\FrontController::getInstance()->getLogger()->warning('\Cms\Log\Model deprecated, use MMi PSR logger instead');
} | php | {
"resource": ""
} |
q5681 | Comment.create | train | public function create($projectId,$taskId,array $params = array())
{
$defaults = array(
'text' => null,
'user_id' => null,
'user_email' => null
);
$params = array_filter(array_merge($defaults, $params));
$data = array('comment'=>$params);
$path = '/projects/'.urlencode($projectId).'/tasks/'.urlencode($taskId).'/comments.json';
return $this->post($path,$data);
} | php | {
"resource": ""
} |
q5682 | ColumnAbstract.getFilterValue | train | public function getFilterValue($param = null)
{
//iteracja po filtrach w gridzie
foreach ($this->_grid->getState()->getFilters() as $filter) {
//znaleziony filtr dla tego pola z tabelą
if ($filter->getTableName() . '.' . $filter->getField() == $this->getName()) {
//zwrot wartości filtra
return $filter->getValue();
}
//znaleziony filtr dla tego pola (bez tabeli)
if (!$filter->getTableName() && $filter->getField() == $this->getName()) {
/** @var \stdClass $value */
$valueObj = json_decode($filter->getValue());
if (null !== $param && is_object($valueObj) && property_exists($valueObj, $param)) {
return $valueObj->{$param};
}
//zwrot wartości filtra
return $filter->getValue();
}
}
} | php | {
"resource": ""
} |
q5683 | ColumnAbstract.isFieldInRecord | train | public function isFieldInRecord()
{
//zażądany join
if (strpos($this->getName(), '.')) {
return true;
}
//sorawdzenie w rekordzie
return property_exists($this->_grid->getQuery()->getRecordName(), $this->getName());
} | php | {
"resource": ""
} |
q5684 | ColumnAbstract.getOrderMethod | train | public function getOrderMethod()
{
//iteracja po sortowaniach w gridzie
foreach ($this->_grid->getState()->getOrder() as $order) {
//znalezione sortowanie tego pola
//gdy jest podana nazwa tabeli
if ($order->getTableName()) {
if ($order->getTableName() . '.' . $order->getField() == $this->getName()) {
//zwrot metody sortowania
return $order->getMethod();
}
} else { //bez tabeli
if ($order->getField() == $this->getName()) {
//zwrot metody sortowania
return $order->getMethod();
}
}
}
} | php | {
"resource": ""
} |
q5685 | SubscriptionStatus.augment | train | public function augment(SubscriptionNotification $notification)
{
$this->in = $notification->in;
$this->out = $notification->out;
} | php | {
"resource": ""
} |
q5686 | Tree._generateJs | train | private function _generateJs($treeId)
{
$id = $this->getOption('id');
$treeClearId = $treeId . '_clear';
$view = \Mmi\App\FrontController::getInstance()->getView();
$view->headScript()->appendScript("$(document).ready(function () {
$('#$treeId').jstree({
'core': {
'themes': {
'name': 'default',
'variant': 'small',
'responsive' : true,
'stripes' : true
},
'multiple': " . ($this->getOption('multiple') ? 'true' : 'false') . ",
'expand_selected_onload': true,
'check_callback' : false
}
})
.on('changed.jstree', function (e, data) {
var selectedStr = '';
if (0 in data.selected) {
selectedStr = data.selected[0];
}
for (idx = 1, len = data.selected.length; idx < len; ++idx) {
selectedStr = selectedStr.concat(';' + data.selected[idx])
}
$('#$id').val(selectedStr);
});
$('#$treeClearId').click(function () {
$('#$id').val('');
$('#$treeId').jstree('deselect_all');
});
});
");
} | php | {
"resource": ""
} |
q5687 | CmsFrontControllerPlugin.postDispatch | train | public function postDispatch(\Mmi\Http\Request $request)
{
//ustawienie widoku
$view = \Mmi\App\FrontController::getInstance()->getView();
$base = $view->baseUrl;
$view->domain = \App\Registry::$config->host;
$view->languages = \App\Registry::$config->languages;
$jsRequest = $request->toArray();
$jsRequest['baseUrl'] = $base;
$jsRequest['locale'] = \App\Registry::$translate->getLocale();
unset($jsRequest['controller']);
unset($jsRequest['action']);
//umieszczenie tablicy w headScript()
$view->headScript()->prependScript('var request = ' . json_encode($jsRequest));
} | php | {
"resource": ""
} |
q5688 | CmsFrontControllerPlugin._setLoginRequest | train | protected function _setLoginRequest(\Mmi\Http\Request $request, $preferAdmin)
{
//logowanie bez preferencji admina, tylko gdy uprawniony
if (false === $preferAdmin && \App\Registry::$acl->isRoleAllowed('guest', 'cms:user:login')) {
return $request->setModuleName('cms')
->setControllerName('user')
->setActionName('login');
}
//logowanie admina
return $request->setModuleName('cmsAdmin')
->setControllerName('index')
->setActionName('login');
} | php | {
"resource": ""
} |
q5689 | TagRelationModel.createTagRelation | train | public function createTagRelation($tag)
{
//filtrowanie tagu
$filteredTag = (new \Mmi\Filter\Input)->filter($tag);
//kreacja tagu jeśli brak
if (null === $tagRecord = (new CmsTagQuery)
->whereTag()->equals($filteredTag)
->findFirst()) {
$tagRecord = new CmsTagRecord;
$tagRecord->tag = $filteredTag;
$tagRecord->save();
}
//znaleziona relacja - nic do zrobienia
if (null !== (new CmsTagRelationQuery)
->whereCmsTagId()->equals($tagRecord->id)
->andFieldObject()->equals($this->_object)
->andFieldObjectId()->equals($this->_objectId)
->findFirst()) {
return;
}
//tworzenie relacji
$newRelationRecord = new CmsTagRelationRecord;
$newRelationRecord->cmsTagId = $tagRecord->id;
$newRelationRecord->object = $this->_object;
$newRelationRecord->objectId = $this->_objectId;
//zapis
$newRelationRecord->save();
} | php | {
"resource": ""
} |
q5690 | ErdikoUsersInstall.installRoles | train | public function installRoles()
{
$this->_roleService = new erdiko\users\models\Role();
$results = array(
"successes" => array(),
"failures" => array(),
);
foreach($this->_rolesArray as $role) {
// attempt to create the role
// wrap this in a try/catch since this throws an exception if failure on create
$createResult = false;
try {
$createResult = (boolean)$this->_roleService->create($role);
} catch(\Exception $e) {
// TODO do we need to log this elsewhere?
}
if(true !== $createResult) {
$results["failures"][] = $role;
} else {
$results["successes"][] = $role;
}
}
return $results;
} | php | {
"resource": ""
} |
q5691 | ErdikoUsersInstall.installUsers | train | public function installUsers()
{
$this->_userService = new erdiko\users\models\User();
$results = array(
"successes" => array(),
"failures" => array(),
);
foreach($this->_usersArray as $user) {
// get role ID from the name
$user["role"] = $this->_getRole($user["role"])->getId();
// create the user
$createResult = (boolean)$this->_userService->createUser($user);
unset($user["password"]);
if(true !== $createResult) {
$results["failures"][] = $user;
} else {
$results["successes"][] = $user;
}
}
return $results;
} | php | {
"resource": ""
} |
q5692 | Authorization.isAllowed | train | public function isAllowed($permission = null, $role = null)
{
if ($permission && strpos($permission, '/') !== false) {
list($controllerClassName, $action) = $this->inferControllerAction($permission);
$controllerClassName = $this->alias->resolveNS($controllerClassName);
if (!isset($this->_acl[$controllerClassName])) {
/** @var \ManaPHP\Rest\Controller $controllerInstance */
$controllerInstance = new $controllerClassName;
$this->_acl[$controllerClassName] = $controllerInstance->getAcl();
}
} else {
$controllerInstance = $this->dispatcher->getControllerInstance();
$controllerClassName = get_class($controllerInstance);
$action = $permission ? lcfirst(Text::camelize($permission)) : $this->dispatcher->getAction();
if (!isset($this->_acl[$controllerClassName])) {
$this->_acl[$controllerClassName] = $controllerInstance->getAcl();
}
}
$acl = $this->_acl[$controllerClassName];
$role = $role ?: $this->identity->getRole();
if (strpos($role, ',') === false) {
return $this->isAclAllow($acl, $role, $action);
} else {
foreach (explode($role, ',') as $r) {
if ($this->isAclAllow($acl, $r, $action)) {
return true;
}
}
return false;
}
} | php | {
"resource": ""
} |
q5693 | RequestCreditCardPayment.withRedirectUrls | train | public function withRedirectUrls($redirects)
{
if (isset($redirects['success'])) {
$this->returnUrlSuccess = $redirects['success'];
}
if (isset($redirects['cancel'])) {
$this->returnUrlCancel = $redirects['cancel'];
}
if (isset($redirects['back'])) {
$this->returnUrlBack = $redirects['back'];
}
return $this;
} | php | {
"resource": ""
} |
q5694 | Image.resizeCropCenter | train | public function resizeCropCenter($width, $height)
{
$_width = $this->do_getWidth();
$_height = $this->do_getHeight();
if ($_width / $_height > $width / $height) {
$crop_height = $_height;
$crop_width = $width * $crop_height / $height;
$offsetX = ($_width - $crop_width) / 2;
$offsetY = 0;
} else {
$crop_width = $_width;
$crop_height = $height * $crop_width / $width;
$offsetY = ($_height - $crop_height) / 2;
$offsetX = 0;
}
$this->crop($crop_width, $crop_height, $offsetX, $offsetY);
$this->scale($width / $crop_width);
return $this;
} | php | {
"resource": ""
} |
q5695 | Image.scale | train | public function scale($ratio)
{
$_width = (int)$this->do_getWidth();
$_height = (int)$this->do_getHeight();
if ($ratio === 1) {
return $this;
}
$width = (int)($_width * $ratio);
$height = (int)($_height * $ratio);
$this->do_resize($width, $height);
return $this;
} | php | {
"resource": ""
} |
q5696 | Image.scaleFixedHeight | train | public function scaleFixedHeight($height)
{
$_width = $this->do_getWidth();
$_height = $this->do_getHeight();
$width = (int)($_width * $height / $_height);
$this->do_resize($width, $height);
return $this;
} | php | {
"resource": ""
} |
q5697 | Validation.validatePascalCase | train | public static function validatePascalCase($string)
{
if (SetupHelper::getPascalCase($string) === $string) {
return (string)$string;
}
throw new InvalidArgumentException(
sprintf(
'Provided string "%1$s" was not in PascalCase.',
$string
)
);
} | php | {
"resource": ""
} |
q5698 | Validation.validateLowerCase | train | public static function validateLowerCase($string)
{
if (SetupHelper::getLowerCase($string) === $string) {
return (string)$string;
}
throw new InvalidArgumentException(
sprintf(
'Provided string "%1$s" was not in lowercase.',
$string
)
);
} | php | {
"resource": ""
} |
q5699 | Validation.validateTrimmed | train | public static function validateTrimmed($string)
{
if (SetupHelper::trim($string) === $string) {
return (string)$string;
}
throw new InvalidArgumentException(
sprintf(
'Provided string "%1$s" was not trimmed.',
$string
)
);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.