_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q5500
CategoryModel._buildTree
train
private function _buildTree(array &$tree, array $parents, array $orderedCategories, CmsCategoryRecord $parentCategory = null) { //uzupełnienie rodziców if ($parentCategory !== null) { $parents[$parentCategory->id] = $parentCategory; } else { $parentCategory = new CmsCategoryRecord; $parentCategory->id = null; } /* @var $categoryRecord CmsCategoryRecord */ foreach ($orderedCategories as $key => $categoryRecord) { //niezgodny rodzic if ($categoryRecord->parentId != $parentCategory->id) { continue; } //dodawanie do płaskiej listy $this->_flatCategories[$categoryRecord->id] = $categoryRecord; //usuwanie wykorzystanego rekordu kategorii unset($orderedCategories[$key]); //zapis do drzewa $tree[$categoryRecord->id] = []; $tree[$categoryRecord->id]['record'] = $categoryRecord->setOption('parents', $parents); $tree[$categoryRecord->id]['children'] = []; //zejście rekurencyjne do dzieci $this->_buildTree($tree[$categoryRecord->id]['children'], $parents, $orderedCategories, $categoryRecord); } }
php
{ "resource": "" }
q5501
User.getRoles
train
public function getRoles() { $roles = array(); foreach ($this->groups as $group) { $roles[] = $group->getAsRole(); } $roles[] = 'ROLE_USER'; return $roles; }
php
{ "resource": "" }
q5502
CmsFileRecord.getHashName
train
public function getHashName() { //brak pliku if ($this->id === null) { return; } return substr(md5($this->name . \App\Registry::$config->salt), 0, 8); }
php
{ "resource": "" }
q5503
CmsFileRecord.getPosterUrl
train
public function getPosterUrl($scaleType = 'default', $scale = null, $https = null) { //brak pliku if (null === $this->id || !$this->data->posterFileName) { return; } //ścieżka CDN $cdnPath = rtrim(\Mmi\App\FrontController::getInstance()->getView()->cdn ? \Mmi\App\FrontController::getInstance()->getView()->cdn : \Mmi\App\FrontController::getInstance()->getView()->url([], true, $https), '/'); //pobranie ścieżki z systemu plików return $cdnPath . (new \Cms\Model\FileSystemModel($this->data->posterFileName))->getPublicPath($scaleType, $scale); }
php
{ "resource": "" }
q5504
CmsFileRecord.delete
train
public function delete() { //usuwanie meta if (!parent::delete()) { return false; } //plik jest ciągle potrzebny (ma linki) if (0 != (new CmsFileQuery)->whereName()->equals($this->name)->count()) { return true; } //kasowanie z systemu plików (new \Cms\Model\FileSystemModel($this->name))->unlink(); //usuwanie rekordu return true; }
php
{ "resource": "" }
q5505
Query.limit
train
public function limit($limit, $offset = null) { $this->_limit = $limit > 0 ? (int)$limit : null; $this->_offset = $offset > 0 ? (int)$offset : null; return $this; }
php
{ "resource": "" }
q5506
GridRequestHandler._retrievePostFilter
train
protected function _retrievePostFilter(\Mmi\Http\RequestPost $post) { //brak filtracji dla tego grida if (false === strpos($post->filter, $this->_grid->getClass())) { return; } $columnName = substr($post->filter, strpos($post->filter, '[') + 1, -1); $tableName = null; $fieldName = $columnName; //obsługa joinowanych if (strpos($columnName, '.')) { $fieldTable = explode('.', $columnName); $tableName = $fieldTable[0]; $fieldName = $fieldTable[1]; } //paginator if ($fieldName == '_paginator_') { //ustawianie filtra return (new GridStateFilter()) ->setField($fieldName) ->setValue($post->value); } //iteracja po kolumnach foreach ($this->_grid->getColumns() as $column) { if ($column->getName() != $columnName) { continue; } //ustawianie filtra return (new GridStateFilter()) ->setField($fieldName) ->setTableName($tableName) ->setMethod($column->getMethod()) ->setValue($post->value); } }
php
{ "resource": "" }
q5507
RepositoryCreator.create
train
public function create( ReflectionClass $modelReflection, $classFileName, $shortClassName, $classNamespace, $contractFileName, $shortContractName, $contractNamespace, array $methods ) { $createdFiles = [$this->createRepository( $modelReflection, $classFileName, $shortClassName, $classNamespace, $shortContractName, $contractNamespace, $methods )]; if ($shortContractName) { $createdFiles[] = $this->createContract( $modelReflection, $contractFileName, $shortContractName, $contractNamespace, $methods ); } return $createdFiles; }
php
{ "resource": "" }
q5508
RepositoryCreator.createRepository
train
protected function createRepository( ReflectionClass $model, $fileName, $shortName, $namespace, $contractName, $contractNamespace, array $methods ) { $path = app_path($fileName); $stub = $this->compileStub('repository.stub', [ 'namespace' => $namespace, 'class' => $shortName, 'model.fullname' => $model->getName(), 'model' => $model->getShortName(), 'implementation' => $this->getImplementationClass($contractName), 'implementation.use' => $this->getImplementationUse($contractNamespace, $contractName), ]); $stub = $this->compileMethods($stub, $methods); $this->files->makeDirectory(dirname($path), 0755, true, true); $this->files->put($path, $stub); return $namespace . '\\' . $shortName; }
php
{ "resource": "" }
q5509
RepositoryCreator.createContract
train
protected function createContract(ReflectionClass $model, $fileName, $shortName, $namespace, array $methods) { $path = app_path($fileName); $stub = $this->compileStub('contract.stub', [ 'namespace' => $namespace, 'class' => $shortName, 'model.fullname' => $model->getName(), 'model' => $model->getShortName(), ]); $stub = $this->compileMethods($stub, $methods); $this->files->makeDirectory(dirname($path), 0755, true, true); $this->files->put($path, $stub); return $namespace . '\\' . $shortName; }
php
{ "resource": "" }
q5510
RepositoryCreator.compileMethods
train
protected function compileMethods($stub, array $methods) { foreach ($methods as $method) { $stub = str_replace(['{{' . $method . '}}', '{{/' . $method . '}}'], '', $stub); } foreach ($this->methods as $method) { $stub = preg_replace('/{{' . $method . '}}(.*){{\/' . $method . '}}(\r\n)?/s', '', $stub); } return $stub; }
php
{ "resource": "" }
q5511
RepositoryCreator.compileStub
train
protected function compileStub($stub, array $data) { $stub = $this->files->get(__DIR__ . '/../stub/' . $stub); foreach ($data as $key => $value) { $stub = str_replace('{{' . $key . '}}', $value, $stub); } return $stub; }
php
{ "resource": "" }
q5512
MenuNodeDefinition.menuNodeHierarchy
train
public function menuNodeHierarchy($depth = 10) { if ($depth == 0) { return $this; } return $this ->prototype('array') ->children() ->scalarNode('route')->end() ->arrayNode('routeParameters') ->prototype('variable') ->end() ->end() ->scalarNode('uri')->end() ->scalarNode('label')->end() ->booleanNode('display')->defaultTrue()->end() ->booleanNode('displayChildren')->defaultTrue()->end() ->integerNode('order')->end() ->arrayNode('attributes') ->prototype('variable') ->end() ->end() ->arrayNode('linkAttributes') ->prototype('variable') ->end() ->end() ->arrayNode('childrenAttributes') ->prototype('variable') ->end() ->end() ->arrayNode('labelAttributes') ->prototype('variable') ->end() ->end() ->arrayNode('roles') ->prototype('scalar') ->end() ->end() ->arrayNode('extras') ->prototype('scalar') ->end() ->end() ->menuNode('children')->menuNodeHierarchy($depth - 1) ->end() ->end(); }
php
{ "resource": "" }
q5513
AclController.deleteRoleAction
train
public function deleteRoleAction() { //wyszukiwanie i usuwanie roli if ((null !== $role = (new \Cms\Orm\CmsRoleQuery)->findPk($this->id))) { $this->getMessenger()->addMessage(($deleteResult = (bool) $role->delete()) ? 'messenger.acl.role.deleted' : 'messenger.acl.role.delete.error', $deleteResult); } //redirect $this->getResponse()->redirect('cmsAdmin', 'acl', 'index', ['roleId' => $this->id]); }
php
{ "resource": "" }
q5514
UploadController.pluploadAction
train
public function pluploadAction() { set_time_limit(5 * 60); //obiekt handlera plupload $pluploadHandler = new Model\PluploadHandler(); //jeśli wystąpił błąd if (!$pluploadHandler->handle()) { return $this->_jsonError($pluploadHandler->getErrorCode(), $pluploadHandler->getErrorMessage()); } //jeśli wykonać operację po przesłaniu całego pliku i zapisaniu rekordu if ($this->getPost()->afterUpload && null !== $record = $pluploadHandler->getSavedCmsFileRecord()) { $this->_operationAfter($this->getPost()->afterUpload, $record); } return json_encode(['result' => 'OK', 'cmsFileId' => $pluploadHandler->getSavedCmsFileId()]); }
php
{ "resource": "" }
q5515
UploadController.deleteAction
train
public function deleteAction() { //szukamy rekordu pliku if (!$this->getPost()->cmsFileId || null === $record = (new CmsFileQuery)->findPk($this->getPost()->cmsFileId)) { return $this->_jsonError(178); } //sprawdzenie zgodności z obiektem formularza if ($record->object === $this->getPost()->object && $record->objectId == $this->getPost()->objectId) { //usuwanie if ($record->delete()) { //jeśli wykonać operację po usunięciu if ($this->getPost()->afterDelete) { $this->_operationAfter($this->getPost()->afterDelete, $record); } return json_encode(['result' => 'OK']); } } return $this->_jsonError(178); }
php
{ "resource": "" }
q5516
UploadController.downloadAction
train
public function downloadAction() { if (null === $file = (new CmsFileQuery)->byObject($this->object, $this->objectId) ->findPk($this->id)) { return ''; } $this->getResponse()->redirectToUrl($file->getUrl()); }
php
{ "resource": "" }
q5517
UploadController._savePoster
train
protected function _savePoster($blob, \Cms\Orm\CmsFileRecord $file) { //brak danych if (!\preg_match('/^data:(image\/[a-z]+);base64,(.*)/i', $blob, $match)) { return; } //nazwa postera $posterFileName = substr($file->name, 0, strpos($file->name, '.')) . '-' . $file->id . '.' . \Mmi\Http\ResponseTypes::getExtensionByType($match[1]); //próba utworzenia katalogu try { //tworzenie katalogu mkdir(dirname($file->getRealPath()), 0777, true); } catch (\Exception $e) { //nic } //zapis file_put_contents(str_replace($file->name, $posterFileName, $file->getRealPath()), base64_decode($match[2])); //zapis do rekordu $file->data->posterFileName = $posterFileName; return $posterFileName; }
php
{ "resource": "" }
q5518
GeneratorFinderCache.getAllClasses
train
public function getAllClasses(MetaDataInterface $metadata = null) { $cacheFilename = $this->directories['Cache'] . DIRECTORY_SEPARATOR; $cacheFilename .= md5('genrator_getAllClasses' . ($metadata !== null) ? get_class($metadata) : ''); if ($this->fileManager->isFile($cacheFilename) === true && $this->noCache === false) { $data = unserialize($this->fileManager->fileGetContent($cacheFilename)); } else { $data = $this->generatorFinder->getAllClasses($metadata); $this->fileManager->filePutsContent($cacheFilename, serialize($data)); } return $data; }
php
{ "resource": "" }
q5519
Manager.fireEvent
train
public function fireEvent($event, $source, $data = []) { if ($this->_listeners) { list($p1, $p2) = explode(':', $event, 2); if (isset($this->_listeners[$p1])) { foreach ($this->_listeners[$p1] as $k => $v) { /**@var \ManaPHP\Event\Listener $listener */ if (is_int($v)) { $this->_listeners[$p1][$k] = $listener = $this->_di->getShared($k); } else { $listener = $v; } $listener->process($p2, $source, $data); } } } foreach ($this->_peekers as $handler) { if ($handler instanceof \Closure) { $handler($event, $source, $data); } else { $handler[0]->{$handler[1]}($event, $source, $data); } } if (!isset($this->_events[$event])) { return; } foreach ($this->_events[$event] as $handler) { if ($handler instanceof \Closure) { $handler($source, $data, $event); } else { $handler[0]->{$handler[1]}($source, $data, $event); } } }
php
{ "resource": "" }
q5520
ACLType.getStandardPermissions
train
protected function getStandardPermissions(array $options, $master, $owner) { switch ($options['permissions']) { case 'standard::object': $disable = array (); // if not owner or master, disable all permissions if (!$master && !$owner) { $disable = array (1, 3, 4, 6, 7, 8); } // if not master, disable // 5 -> undelete is not used return array ( 'show' => array ( 1 => 'View', 3 => 'Edit', 4 => 'Delete', 6 => 'Operator', 7 => 'Master', 8 => 'Owner' ), 'disable' => $disable); break; case 'standard::class': return array ( 'show' => array ( 1 => 'View', 2 => 'Create', 3 => 'Edit', 4 => 'Delete', 6 => 'Operator', 7 => 'Master', 8 => 'Owner' )); break; default: throw new \RuntimeException('"' . $options['permissions'] . '" is not a valid standard permission set identifier'); } }
php
{ "resource": "" }
q5521
PharController.manacliCommand
train
public function manacliCommand() { $this->alias->set('@phar', '@data/manacli_phar'); $pharFile = $this->alias->resolve('@root/manacli.phar'); $this->console->writeLn(['cleaning `:dir` dir', 'dir' => $this->alias->resolve('@phar')]); $this->filesystem->dirReCreate('@phar'); $this->console->writeLn('copying manaphp framework files.'); $this->filesystem->dirCopy('@root/ManaPHP', '@phar/ManaPHP'); //$di->filesystem->dirCopy('@root/Application', '@phar/Application'); $this->filesystem->fileCopy('@root/manacli.php', '@phar/manacli.php'); $phar = new \Phar($pharFile, \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME, basename($pharFile)); $phar->buildFromDirectory($this->alias->resolve('@phar')); $phar->setStub($phar::createDefaultStub('manacli.php')); $this->console->writeLn('compressing files'); $phar->compressFiles(\Phar::BZ2); $this->console->writeLn(['`:phar` created successfully', 'phar' => $this->alias->resolve($pharFile)]); }
php
{ "resource": "" }
q5522
FileConflictManager.handle
train
public function handle($filePath, $results) { $responseCollection = new PredefinedResponseCollection(); $responseCollection->append( new PredefinedResponse('postpone', 'postpone', self::POSTPONE) ); $responseCollection->append( new PredefinedResponse('show diff', 'show diff', self::SHOW_DIFF) ); $responseCollection->append( new PredefinedResponse('erase', 'erase', self::ERASE) ); $responseCollection->append( new PredefinedResponse('cancel', 'cancel', self::CANCEL) ); $question = new QuestionWithPredefinedResponse( sprintf('File "%s" already exist, erase it with the new', $filePath), 'conflict' . $filePath, $responseCollection ); $question->setShutdownWithoutResponse(true, sprintf('Conflict with file "%s" not resolved', $filePath)); while (($response = $this->context->askCollection($question)) !== null) { $response = intval($response); if ($response === self::SHOW_DIFF) { // write to output the diff $this->context->log( '<info>' . $this->diffPHP->diff($results, $this->fileManager->fileGetContent($filePath)) . '</info>' ); } else { break; } } if ($response === self::POSTPONE) { //Generate the diff file $this->fileManager->filePutsContent( $filePath . '.diff', $this->diffPHP->diff( $results, $this->fileManager->fileGetContent($filePath) ) ); $this->context->log('--> Generate diff and new file ' . $filePath . '.diff', 'generationLog'); } elseif ($response === self::ERASE) { $this->fileManager->filePutsContent($filePath, $results); $this->context->log('--> Replace file ' . $filePath, 'generationLog'); } }
php
{ "resource": "" }
q5523
GeneratorParser.analyzeDependencies
train
private function analyzeDependencies(array $process, PhpStringParser $phpParser, GeneratorDataObject $generator) { $generator = clone $generator; if (isset($process['dependencies']) === true && is_array($process['dependencies']) === true) { foreach ($process['dependencies'] as $dependencieName) { $generator->addDependency( $this->analyze($dependencieName, $phpParser, $generator, $generator->getDto()->getMetadata()) ); } $generator = $this->addDependenciesVariablesToMainGenerator($generator); } return $generator; }
php
{ "resource": "" }
q5524
GeneratorParser.analyzePreParser
train
private function analyzePreParser( array $process, PhpStringParser $phpParser, GeneratorDataObject $generator, $firstIteration ) { $generator = clone $generator; if ($this->parserCollection->getPreParse()->count() > 0) { foreach ($this->parserCollection->getPreParse() as $parser) { $generator = $parser->evaluate($process, $phpParser, $generator, $firstIteration); } } return $generator; }
php
{ "resource": "" }
q5525
GeneratorParser.analyzePostParser
train
private function analyzePostParser( array $process, PhpStringParser $phpParser, GeneratorDataObject $generator, $firstIteration ) { $generator = clone $generator; if ($this->parserCollection->getPostParse()->count() > 0) { foreach ($this->parserCollection->getPostParse() as $parser) { $generator = $parser->evaluate($process, $phpParser, $generator, $firstIteration); } } return $generator; }
php
{ "resource": "" }
q5526
PasswordController.setContainer
train
public function setContainer(ContainerInterface $container = null) { parent::setContainer($container); if (!$this->container->getParameter('fom_user.reset_password')) { throw new AccessDeniedHttpException(); } }
php
{ "resource": "" }
q5527
MetaDataConfigDAO.retrieveAll
train
public function retrieveAll() { $adapterCollection = new MetaDataSourceCollection(); foreach ($this->fileManager->glob(Installer::BASE_PATH . self::SOURCE_PATH . '*' . self::EXTENSION) as $file) { // Decode $config = $this->transtyper->decode($this->fileManager->fileGetContent($file)); // Validate try { $this->arrayValidator->isValid('CrudGenerator\Metadata\MetaDataSource', $config); } catch (ValidationException $e) { continue; // Do nothing } // Hydrate $adapter = $this->metaDataSourceHydrator->adapterNameToMetaDataSource( $config[MetaDataSource::METADATA_DAO_FACTORY] ); $adapter->setMetadataDaoFactory($config[MetaDataSource::METADATA_DAO_FACTORY]); $adapter->setMetadataDao($config[MetaDataSource::METADATA_DAO]); // Test if have a config if (isset($config[MetaDataSource::CONFIG]) === true) { $adapter->setConfig($this->driverHydrator->arrayToDto($config[MetaDataSource::CONFIG])); } $adapterCollection->append($adapter); } return $adapterCollection; }
php
{ "resource": "" }
q5528
MySQLMetaDataDAOFactory.getInstance
train
public static function getInstance(DriverConfig $config) { $pdoDriver = PdoDriverFactory::getInstance(); return new MySQLMetaDataDAO( $pdoDriver->getConnection($config), $config ); }
php
{ "resource": "" }
q5529
CategoryWidgetController.deleteAttributeRelationAction
train
public function deleteAttributeRelationAction() { //usuwanie relacji (new AttributeController($this->getRequest(), $this->view))->deleteAttributeRelationAction(); $this->getResponse()->redirect('cmsAdmin', 'categoryWidget', 'edit', ['id' => $this->id]); }
php
{ "resource": "" }
q5530
PostgreSQLMetaDataDAOFactory.getInstance
train
public static function getInstance(DriverConfig $config) { $pdoDriver = PdoDriverFactory::getInstance(); return new PostgreSQLMetaDataDAO( $pdoDriver->getConnection($config), $config, new SqlManager() ); }
php
{ "resource": "" }
q5531
Project.addGuest
train
public function addGuest($id,$guest) { if(is_string($guest)) { $params = array('email'=>$guest); } elseif(is_numeric($guest)) { $params = array('user_id'=>$guest); }else { throw new \Exception('Invalid parameter'); } return $this->post('/projects/'.$id.'/add_guest.json', $params); }
php
{ "resource": "" }
q5532
Category.afterSave
train
public function afterSave() { //jeśli czegoś nie uddało się zapisać wcześniej if (!parent::afterSave()) { return false; } //jeśli nie udało się zapisać powiązań z rolami if (!$this->_saveRoles()) { return false; } //commit wersji if ($this->getElement('commit')->getValue()) { $this->getRecord()->commitVersion(); } //usunięcie locka return (new CategoryLockModel($this->getRecord()->cmsCategoryOriginalId))->releaseLock(); }
php
{ "resource": "" }
q5533
ReplacePlaceholdersInTemplateFiles.getPlaceholderArray
train
protected function getPlaceholderArray() { $placeholderArray = []; foreach ($this->getConfigKey('Placeholders') as $key => $data) { $placeholderArray[$key] = $data['value']; } return $placeholderArray; }
php
{ "resource": "" }
q5534
TagRelation.beforeSave
train
public function beforeSave() { $tag = $this->getElement('tag')->getValue(); //wyszukanie tagu if (null === $tagRecord = (new \Cms\Orm\CmsTagQuery) ->whereTag()->equals($tag) ->findFirst()) { //utworzenie tagu $tagRecord = new \Cms\Orm\CmsTagRecord; $tagRecord->tag = $tag; $tagRecord->save(); } //przypisanie id tagu $this->getRecord()->cmsTagId = $tagRecord->id; return true; }
php
{ "resource": "" }
q5535
Di.set
train
public function set($name, $definition) { if (is_string($definition)) { if (strpos($definition, '/') !== false || preg_match('#^[\w\\\\]+$#', $definition) !== 1) { $definition = ['class' => $this->_interClassName($name), $definition, 'shared' => false]; } else { if (strpos($definition, '\\') === false) { $definition = $this->_completeClassName($name, $definition); } $definition = ['class' => $definition, 'shared' => false]; } } elseif (is_array($definition)) { if (isset($definition['class'])) { if (strpos($definition['class'], '\\') === false) { $definition['class'] = $this->_completeClassName($name, $definition['class']); } } elseif (isset($definition[0]) && count($definition) !== 1) { if (strpos($definition[0], '\\') === false) { $definition[0] = $this->_completeClassName($name, $definition[0]); } } else { $definition['class'] = $this->_interClassName($name); } $definition['shared'] = false; } elseif (is_object($definition)) { $definition = ['class' => $definition, 'shared' => !$definition instanceof \Closure]; } else { throw new UnexpectedValueException(['`:definition` definition is unknown', 'definition' => $name]); } $this->_definitions[$name] = $definition; return $this; }
php
{ "resource": "" }
q5536
Di.setShared
train
public function setShared($name, $definition) { if (isset($this->_instances[$name])) { throw new MisuseException(['it\'s too late to setShared(): `:name` instance has been created', 'name' => $name]); } if (is_string($definition)) { if (strpos($definition, '/') !== false || preg_match('#^[\w\\\\]+$#', $definition) !== 1) { $definition = ['class' => $this->_interClassName($name), $definition]; } elseif (strpos($definition, '\\') === false) { $definition = $this->_completeClassName($name, $definition); } } elseif (is_array($definition)) { if (isset($definition['class'])) { if (strpos($definition['class'], '\\') === false) { $definition['class'] = $this->_completeClassName($name, $definition['class']); } } elseif (isset($definition[0]) && count($definition) !== 1) { if (strpos($definition[0], '\\') === false) { $definition[0] = $this->_completeClassName($name, $definition[0]); } } else { $definition['class'] = $this->_interClassName($name); } } elseif (is_object($definition)) { $definition = ['class' => $definition]; } else { throw new UnexpectedValueException(['`:definition` definition is unknown', 'definition' => $name]); } $this->_definitions[$name] = $definition; return $this; }
php
{ "resource": "" }
q5537
Di.remove
train
public function remove($name) { unset($this->_definitions[$name], $this->_instances[$name], $this->{$name}); return $this; }
php
{ "resource": "" }
q5538
Di.get
train
public function get($name, $parameters = null) { if (isset($this->_instances[$name])) { return $this->_instances[$name]; } if (isset($this->_definitions[$name])) { $definition = $this->_definitions[$name]; } else { return $this->getInstance($name, $parameters, $name); } $instance = $this->getInstance($definition, $parameters, $name); if (is_string($definition) || !isset($definition['shared']) || $definition['shared'] === true) { $this->_instances[$name] = $instance; } return $instance; }
php
{ "resource": "" }
q5539
Di.getShared
train
public function getShared($name) { if (isset($this->_instances[$name])) { return $this->_instances[$name]; } if (isset($this->_definitions[$name])) { return $this->_instances[$name] = $this->getInstance($this->_definitions[$name], null, $name); } elseif (strpos($name, '\\') !== false) { return $this->_instances[$name] = $this->getInstance($name, null, $name); } else { $className = $this->_getPatterned($name); if ($className === null) { throw new InvalidValueException(['`:component` component is not exists', 'component' => $name]); } return $this->_instances[$name] = $this->getInstance($className, null, $name); } }
php
{ "resource": "" }
q5540
Timer.reset
train
function reset(){ $tmp = $this->milliseconds(); $this->started = microtime( false ); $this->stopped = null; return $tmp; }
php
{ "resource": "" }
q5541
Timer.stop
train
function stop(){ if( $this->is_running() ){ $this->stopped = microtime( false ); return $this->milliseconds(); } else{ trigger_error("Timer already stopped", E_USER_NOTICE); return false; } }
php
{ "resource": "" }
q5542
Timer.is_running
train
function is_running(){ if( isset( $this->stopped ) ){ return false; } if( ! isset( $this->started ) ){ trigger_error("Timer has been stopped some how (".gettype($this->started).")'$this->started'", E_USER_WARNING); return false; } return true; }
php
{ "resource": "" }
q5543
Timer.milliseconds
train
function milliseconds( $dp = null ){ if( $this->is_running() ){ $now = microtime( false ); } else { $now = $this->stopped; } $started = self::parse_microtime( $this->started ); $stopped = self::parse_microtime( $now ); $ms = $stopped - $started; if( ! is_null($dp) ){ $mult = pow( 10, $dp ); $ms = round( $mult * $ms ) / $mult; } return $ms; }
php
{ "resource": "" }
q5544
Timer.seconds
train
function seconds( $dp = 2 ){ $secs = $this->milliseconds() / 1000; if( ! is_null($dp) ){ $mult = pow( 10, $dp ); $secs = round( $mult * $secs ) / $mult; } return $secs; }
php
{ "resource": "" }
q5545
Timer.parse_microtime
train
static function parse_microtime( $microtime ){ list($usec, $sec) = explode( ' ', $microtime ); $ms1 = (float) $usec * 1000; $ms2 = (float) $sec * 1000; return $ms1 + $ms2; }
php
{ "resource": "" }
q5546
Doctrine2MetaDataDAO.getMetadataFor
train
public function getMetadataFor($entityName, array $parentName = array()) { return $this->hydrateDataObject( $this->entityManager->getMetadataFactory()->getMetadataFor($entityName), $parentName ); }
php
{ "resource": "" }
q5547
PLUGCli.init
train
static function init() { switch( PHP_SAPI ) { // Ideally we want to be runnning as CLI case 'cli': break; // Special conditions to ensure CGI runs as CLI case 'cgi': // Ensure resource constants are defined if( ! defined('STDERR') ){ define( 'STDERR', fopen('php://stderr', 'w') ); } if( ! defined('STDOUT') ){ define( 'STDOUT', fopen('php://stdout', 'w') ); } break; default: echo "Command line only\n"; exit(1); } // Default error logger function PLUG::set_error_logger( array(__CLASS__,'format_logline') ); // parse command line arguments from argv global global $argv, $argc; // first cli arg is always current script. second arg will be script arg passed to shell wrapper for( $i = 1; $i < $argc; $i++ ){ $arg = $argv[ $i ]; // Each command line argument may take following forms: // 1. "Any single argument", no point parsing this unless it follows #2 below // 2. "-aBCD", one or more switches, parse into 'a'=>true, 'B'=>true, and so on // 3. "-a value", flag used with following value, parsed to 'a'=>'value' // 4. "--longoption", GNU style long option, parse into 'longoption'=>true // 5. "--longoption=value", as above, but parse into 'longoption'=>'value' // 6."any variable name = any value" $pair = explode( '=', $arg, 2 ); if( isset($pair[1]) ){ $name = trim( $pair[0] ); if( strpos($name,'--') === 0 ){ // #5. trimming "--" from option, tough luck if you only used one "-" $name = trim( $name, '-' ); } // else is #6, any pair $name and self::$args[$name] = trim( $pair[1] ); } else if( strpos($arg,'--') === 0 ){ // #4. long option, no value $name = trim( $arg, "-\n\r\t " ); $name and self::$args[ $name ] = true; } else if( $arg && $arg{0} === '-' ){ $flags = preg_split('//', trim($arg,"-\n\r\t "), -1, PREG_SPLIT_NO_EMPTY ); foreach( $flags as $flag ){ self::$args[ $flag ] = true; } // leave $flag set incase a value follows. continue; } // else is a standard argument. use as value only if it follows a flag, e.g "-a apple" else if( isset($flag) ){ self::$args[ $flag ] = trim( $arg ); } // dispose of last flag unset( $flag ); // next arg } }
php
{ "resource": "" }
q5548
PLUGCli.arg
train
final static function arg( $a, $default = null ){ if( is_int($a) ){ global $argv; // note: arg(0) will always be the script path return isset($argv[$a]) ? $argv[$a] : $default; } else { return isset(self::$args[$a]) ? self::$args[$a] : $default; } }
php
{ "resource": "" }
q5549
PLUGCli.stderr
train
final static function stderr( $s ){ if( func_num_args() > 1 ){ $args = func_get_args(); $s = call_user_func_array( 'sprintf', $args ); } fwrite( STDERR, $s ); }
php
{ "resource": "" }
q5550
PLUGCli.format_logline
train
static function format_logline( PLUGError $Err ){ if( PLUG::is_compiled() ){ return sprintf( '%s: %s: %s', basename(self::arg(0)), $Err->getTypeString(), $Err->getMessage() ); } else { return sprintf( '%s: %s: %s in %s#%u', basename(self::arg(0)), $Err->getTypeString(), $Err->getMessage(), basename($Err->getFile()), $Err->getLine() ); } }
php
{ "resource": "" }
q5551
GlideServer.getLeagueGlideServer
train
public function getLeagueGlideServer() { if (null === $this->server) { $config = $this->config + [ 'response' => new LaravelResponseFactory($this->app['request']) ]; $this->server = ServerFactory::create($config); } return $this->server; }
php
{ "resource": "" }
q5552
GlideServer.url
train
public function url($path, array $params = []) { $urlBuilder = UrlBuilderFactory::create($this->config['base_url'], $this->config['sign_key']); return $urlBuilder->getUrl($path, $params); }
php
{ "resource": "" }
q5553
InvalidLength.rise
train
public function rise(array $params, $line, $filename) { $this->message = "The length of \"" . $params[0] . "\" is invalid! Must be " . $params[1] . " then " . $params[2] . ". File: " . $filename . " Line: " . $line; return $this; }
php
{ "resource": "" }
q5554
Issue.buildLabels
train
private function buildLabels($labels) { $collection = []; foreach ($labels as $label) { $collection[] = Label::createFromData($label); } return $collection; }
php
{ "resource": "" }
q5555
Doctrine2MetaDataDAOFactory.getInstance
train
public static function getInstance() { $fileManager = new FileManager(); $serviceManager = ZendFramework2Environnement::getDependence($fileManager); $entityManager = $serviceManager->get('doctrine.entitymanager.orm_default'); if (($entityManager instanceof EntityManager) === false) { throw new \Exception( sprintf( 'Service manager return instanceof "%s" instead of "%s"', is_object($entityManager) === true ? get_class($entityManager) : gettype($entityManager), 'Doctrine\ORM\EntityManager' ) ); } return new Doctrine2MetaDataDAO($entityManager); }
php
{ "resource": "" }
q5556
Client.getUploadResult
train
public function getUploadResult($token) { $jwt = new Jwt(); $claims = $jwt->decode($token, false); if (!isset($claims['scope'])) { throw new AuthenticationException('scope is not exists'); } if ($claims['scope'] !== 'bos.object.create.response') { throw new AuthenticationException(['`:scope` scope is not valid', 'scope' => $claims['scope']]); } if (!isset($claims['bucket'])) { throw new AuthenticationException('bucket is not exists'); } $bucket = $claims['bucket']; $this->logger->info($token, 'bosClient.getUploadResult'); $jwt->verify($token, is_string($this->_access_key) ? $this->_access_key : $this->_access_key[$bucket]); return array_except($claims, ['scope', 'iat', 'exp']); }
php
{ "resource": "" }
q5557
GridExporter.passCsv
train
public function passCsv() { $csv = fopen('php://output', 'w'); //nagłówek CSV fputcsv($csv, $this->_getHeader()); //iteracja po danych foreach ($this->_getData() as $data) { //zapis linii CSV fputcsv($csv, $data); } fclose($csv); }
php
{ "resource": "" }
q5558
GridExporter._getHeader
train
protected function _getHeader() { $header = []; foreach ($this->_grid->getColumns() as $column) { if ($column instanceof Column\IndexColumn || $column instanceof Column\OperationColumn) { continue; } if ($column instanceof Column\CustomColumn && !$column->getExporting()) { continue; } $header[] = $column->getLabel(); } return $header; }
php
{ "resource": "" }
q5559
ApplicationServiceIterator.accept
train
public function accept() { /* @var $serviceId string|object */ $serviceId = $this->current(); if (in_array($serviceId, $this->getIdsOfServicesThatAreDefinedInApplication())) { return true; } if ($this->startsWithPrefix($serviceId, $this->getPrefixesOfApplicationServices())) { return true; } return false; }
php
{ "resource": "" }
q5560
ApplicationServiceIterator.getIdsOfServicesThatAreDefinedInApplication
train
protected function getIdsOfServicesThatAreDefinedInApplication() { if ($this->serviceIdWhitelist === null) { $builder = $this->createContainerBuilder(); $this->applyToExtensions(function (ExtensionInterface $extension) use ($builder) { $extension->load($builder->getExtensionConfig($extension->getAlias()), $builder); }); $this->serviceIdWhitelist = $builder->getServiceIds(); } return $this->serviceIdWhitelist; }
php
{ "resource": "" }
q5561
ApplicationServiceIterator.getPrefixesOfApplicationServices
train
protected function getPrefixesOfApplicationServices() { if ($this->allowedServicePrefixes === null) { $this->allowedServicePrefixes = $this->applyToExtensions(function (ExtensionInterface $extension) { return $extension->getAlias() . '.'; }); } return $this->allowedServicePrefixes; }
php
{ "resource": "" }
q5562
ApplicationServiceIterator.applyToExtensions
train
protected function applyToExtensions($callback) { $results = array(); foreach (new ApplicationBundleIterator($this->kernel) as $bundle) { /* @var $bundle BundleInterface */ $extension = $bundle->getContainerExtension(); if ($extension !== null) { $results[] = call_user_func($callback, $extension); } } return $results; }
php
{ "resource": "" }
q5563
ApplicationServiceIterator.startsWithPrefix
train
protected function startsWithPrefix($serviceId, $allowedPrefixes) { foreach ($allowedPrefixes as $prefix) { /* @var $prefix string */ if (strpos($serviceId, $prefix) === 0) { return true; } } return false; }
php
{ "resource": "" }
q5564
ApplicationServiceIterator.createContainerBuilder
train
protected function createContainerBuilder() { $builder = new ContainerBuilder(); $this->kernel->boot(); foreach ($this->kernel->getBundles() as $bundle) { // Register all extensions, otherwise there might be config parts that cannot be processed. $extension = $bundle->getContainerExtension(); if ($extension !== null) { $builder->registerExtension($extension); } } // Load the application configuration, which might affect the loaded services. /* @var $locator FileLocatorInterface */ $locator = $this->kernel->getContainer()->get('file_locator'); $loaders = array( new XmlFileLoader($builder, $locator), new YamlFileLoader($builder, $locator), new IniFileLoader($builder, $locator), new PhpFileLoader($builder, $locator), (class_exists(DirectoryLoader::class) ? new DirectoryLoader($builder, $locator) : null), new ClosureLoader($builder), ); $loaders = array_filter($loaders); $resolver = new LoaderResolver($loaders); $loader = new DelegatingLoader($resolver); $this->kernel->registerContainerConfiguration($loader); return $builder; }
php
{ "resource": "" }
q5565
PullRequest.getCommits
train
public function getCommits() { if ('' === ini_get('user_agent')) { throw new UserAgentNotFoundException(); } if (!ini_get('allow_url_fopen')) { throw new AllowUrlFileOpenException(); } $jsonResponse = $this->getFileContent($this->getCommitsUrl(), ini_get('user_agent')); $response = json_decode($jsonResponse, true); foreach ($response as $commitArray) { $commit = Commit::createFromData($commitArray['commit']) ->setSha($commitArray['sha']) ; $commits[] = $commit; } return $commits; }
php
{ "resource": "" }
q5566
PullRequest.getFileContent
train
private function getFileContent($url, $userAgent) { $opts = [ 'http' => [ 'method' => 'GET', 'header' => [ 'User-Agent: '. $userAgent ] ] ]; $context = stream_context_create($opts); return file_get_contents($url, false, $context); }
php
{ "resource": "" }
q5567
Helper.downloadRemoteFile
train
static function downloadRemoteFile($url, $destinationFilename) { if (!ini_get('allow_url_fopen')) { throw new \Exception('allow_url_fopen is disable', 501); } $message = "File was not loaded"; if (function_exists('curl_init')) { try { $raw = file_get_contents($url); } catch (\Exception $e) { throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST); } } else { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);// таймаут4 $response = parse_url($url); curl_setopt($ch, CURLOPT_REFERER, $response['scheme'] . '://' . $response['host']); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) ' . 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.99 YaBrowser/19.1.1.907 Yowser/2.5 Safari/537.36'); $raw = curl_exec($ch); if (!$raw) { throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST); } curl_close($ch); } if ($raw) { file_put_contents($destinationFilename, $raw); } else { throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST); } }
php
{ "resource": "" }
q5568
LRParseTable.lookup
train
function lookup( $state, $la ){ if( ! isset($this->table[$state][$la]) ){ return null; } else { return $this->table[$state][$la]; } }
php
{ "resource": "" }
q5569
GridState._applyFilters
train
private function _applyFilters(\Mmi\Orm\Query $query) { //iteracja po filtrach foreach ($this->getFilters() as $filter) { //filtr nie jest prawidłowy if (!($filter instanceof GridStateFilter)) { throw new GridException('Invalid state filter object'); } //operator równości if ($filter->getMethod() == 'equals') { $query->andField($filter->getField(), $filter->getTableName())->equals($filter->getValue()); continue; } //podobieństwo if ($filter->getMethod() == 'like') { $query->andField($filter->getField(), $filter->getTableName())->like($filter->getValue() . '%'); continue; } //większość if ($filter->getMethod() == 'null') { if ($filter->getValue()) { $query->andField($filter->getField(), $filter->getTableName())->notEquals(null); continue; } $query->andField($filter->getField(), $filter->getTableName())->equals(null); continue; } if ($filter->getMethod() == 'between') { $range = explode(';', $filter->getValue()); //zdefiniowane od if (!empty($range[0])) { $query->andField($filter->getField(), $filter->getTableName())->greaterOrEquals($range[0]); } //zdefiniowane do if (isset($range[1]) && !empty($range[1])) { $query->andField($filter->getField(), $filter->getTableName())->lessOrEquals($range[1]); } continue; } //domyślnie - wyszukanie $query->andField($filter->getField(), $filter->getTableName())->like('%' . $filter->getValue() . '%'); } return $this; }
php
{ "resource": "" }
q5570
GridState._applyOrder
train
private function _applyOrder(\Mmi\Orm\Query $query) { $orders = $this->getOrder(); //resetowanie domyślnego orderu jeśli podany if (!empty($orders)) { $query->resetOrder(); } //iteracja po orderze foreach ($orders as $order) { //order nie jest obiektem sortowania if (!($order instanceof GridStateOrder)) { throw new GridException('Invalid state order object'); } //aplikacja na querę $query->{$order->getMethod()}($order->getField(), $order->getTableName()); } return $this; }
php
{ "resource": "" }
q5571
File.isGoodFile
train
public function isGoodFile(Config $source) { $info = pathinfo($this->path); if (!isset($info['extension']) or (!in_array(strtolower($info['extension']), $source->extensions))) { return false; } if (in_array(strtolower($info['extension']), $source->imageExtensions) and !$this->isImage()) { return false; } return true; }
php
{ "resource": "" }
q5572
File.isImage
train
public function isImage() { try { if (!function_exists('exif_imagetype') && !function_exists('Jodit\exif_imagetype')) { function exif_imagetype($filename) { if ((list(, , $type) = getimagesize($filename)) !== false) { return $type; } return false; } } return in_array(exif_imagetype($this->getPath()), [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP]); } catch (\Exception $e) { return false; } }
php
{ "resource": "" }
q5573
DbController.listCommand
train
public function listCommand($services = [], $table_pattern = '') { foreach ($services ?: $this->_getDbServices() as $service) { /** @var \ManaPHP\DbInterface $db */ $db = $this->_di->getShared($service); $this->console->writeLn(['service: `:service`', 'service' => $service], Console::FC_CYAN); foreach ($this->_getTables($service, $table_pattern) as $row => $table) { $columns = (array)$db->getMetadata($table)[Db::METADATA_ATTRIBUTES]; $primaryKey = $db->getMetadata($table)[Db::METADATA_PRIMARY_KEY]; foreach ($columns as $i => $column) { if (in_array($column, $primaryKey, true)) { $columns[$i] = $this->console->colorize($column, Console::FC_RED); } } $this->console->writeLn([' :row :table(:columns)', 'row' => sprintf('%2d ', $row + 1), 'table' => $this->console->colorize($table, Console::FC_GREEN), 'columns' => implode(', ', $columns)]); } } }
php
{ "resource": "" }
q5574
DbController.modelCommand
train
public function modelCommand($table, $service = '', $namespace = 'App\Models', $optimized = false) { if (strpos($namespace, '\\') === false) { $namespace = 'App\\' . ucfirst($namespace) . '\\Models'; } /** @var \ManaPHP\DbInterface $db */ if ($service) { $db = $this->_di->getShared($service); if (!in_array($table, $db->getTables(), true)) { throw new Exception(['`:table` is not exists', 'table' => $table]); } } else { foreach ($this->_getDbServices() as $s) { $db = $this->_di->getShared($s); if (in_array($table, $db->getTables(), true)) { $service = $s; break; } } if (!$service) { throw new Exception(['`:table` is not found in services`', 'table' => $table]); } } $this->console->progress(['`:table` processing...', 'table' => $table], ''); $plainClass = Text::camelize($table); $fileName = "@tmp/db_model/$plainClass.php"; $model_str = $this->_renderModel($service, $table, $namespace, $optimized); $this->filesystem->filePut($fileName, $model_str); $this->console->progress(['`:table` table saved to `:file`', 'table' => $table, 'file' => $fileName]); }
php
{ "resource": "" }
q5575
DbController.modelsCommand
train
public function modelsCommand($services = [], $table_pattern = '', $namespace = 'App\Models', $optimized = false) { if (strpos($namespace, '\\') === false) { $namespace = 'App\\' . ucfirst($namespace) . '\\Models'; } foreach ($services ?: $this->_getDbServices() as $service) { foreach ($this->_getTables($service, $table_pattern) as $table) { $this->console->progress(['`:table` processing...', 'table' => $table], ''); $plainClass = Text::camelize($table); $fileName = "@tmp/db_models/$plainClass.php"; $model_str = $this->_renderModel($service, $table, $namespace, $optimized); $this->filesystem->filePut($fileName, $model_str); $this->console->progress([' `:table` table saved to `:file`', 'table' => $table, 'file' => $fileName]); } } }
php
{ "resource": "" }
q5576
AnnotationDriver.isMetadataFullyLoaded
train
private function isMetadataFullyLoaded(array $metadata) { return $metadata[ClassMetadata::LOGIN_PROPERTY] && $metadata[ClassMetadata::PASSWORD_PROPERTY] && $metadata[ClassMetadata::API_KEY_PROPERTY] && $metadata[ClassMetadata::LAST_ACTION_PROPERTY]; }
php
{ "resource": "" }
q5577
Navigation.decorateConfiguration
train
public function decorateConfiguration(\Mmi\Navigation\NavigationConfig $config) { $objectArray = (new CmsCategoryQuery) ->lang() ->andFieldStatus()->equals(\Cms\Orm\CmsCategoryRecord::STATUS_ACTIVE) ->orderAscParentId() ->orderAscOrder() ->find() ->toObjectArray(); foreach ($objectArray as $key => $record) {/* @var $record CmsCategoryRecord */ if ($record->parentId != 0) { continue; } $element = new \Mmi\Navigation\NavigationConfigElement($record->uri); $this->_setNavigationElementFromRecord($record, $element); $config->addElement($element); unset($objectArray[$key]); $this->_buildChildren($record, $element, $objectArray); } }
php
{ "resource": "" }
q5578
Navigation._setNavigationElementFromRecord
train
protected function _setNavigationElementFromRecord(CmsCategoryRecord $record, \Mmi\Navigation\NavigationConfigElement $element) { $params = []; parse_str($record->mvcParams, $params); $params['uri'] = $record->customUri ? $record->customUri : $record->uri; $config = $record->getConfig(); $config->typeId = $record->cmsCategoryTypeId; $config->categoryId = $record->id; $element ->setModule('cms') ->setController('category') ->setAction('dispatch') ->setParams($params) ->setBlank($record->blank ? true : false) ->setDisabled($record->active ? false : true) ->setHttps($record->https) ->setUri($record->redirectUri ? : null) ->setLabel($record->name) ->setLang($record->lang) ->setFollow($record->follow ? true : false) ->setConfig($config) ->setDateStart($record->dateStart) ->setDateEnd($record->dateEnd); if ($record->title) { $element->setTitle($record->title); } if ($record->description) { $element->setDescription($record->description); } return $this->_setNavigationElementRoles($record, $element); }
php
{ "resource": "" }
q5579
Tube.render
train
public function render(array $options = array()) { $url = $this->service->generateEmbedUrl($this); $options = array_replace(array( 'width' => 560, 'height' => 315, 'frameborder' => 0, 'allowfullscreen' => '' ), $options); $html = <<<HTML <iframe src="$url" width="{$options['width']}" height="{$options['height']}" frameborder="{$options['frameborder']}" {$options['allowfullscreen']}></iframe> HTML; return $html; }
php
{ "resource": "" }
q5580
Cron.run
train
public static function run() { foreach (Orm\CmsCronQuery::active()->find() as $cron) { if (!self::_getToExecute($cron)) { continue; } $output = ''; try { $start = microtime(true); $output = \Mmi\Mvc\ActionHelper::getInstance()->action(new \Mmi\Http\Request(['module' => $cron->module, 'controller' => $cron->controller, 'action' => $cron->action])); $elapsed = round(microtime(true) - $start, 2); } catch (\Exception $e) { //error logging \Mmi\App\FrontController::getInstance()->getLogger()->error('CRON failed: @' . gethostname() . $cron->name . ' ' . $e->getMessage()); return; } //zmień datę ostatniego wywołania $cron->dateLastExecute = date('Y-m-d H:i:s'); //ponowne łączenie \App\Registry::$db->connect(); //zapis do bazy bez modyfikowania daty ostatniej modyfikacji $cron->saveWithoutLastDateModify(); //logowanie uruchomienia \Mmi\App\FrontController::getInstance()->getLogger()->info('CRON done: @' . gethostname() . ' ' . $cron->name . ' ' . $output . ' in ' . $elapsed . 's'); } }
php
{ "resource": "" }
q5581
Cron._getToExecute
train
protected static function _getToExecute($record) { return self::_valueMatch(date('i'), $record->minute) && self::_valueMatch(date('H'), $record->hour) && self::_valueMatch(date('d'), $record->dayOfMonth) && self::_valueMatch(date('m'), $record->month) && self::_valueMatch(date('N'), $record->dayOfWeek); }
php
{ "resource": "" }
q5582
GroupController.indexAction
train
public function indexAction() { $oid = new ObjectIdentity('class', 'FOM\UserBundle\Entity\Group'); $query = $this->getDoctrine()->getManager()->createQuery('SELECT g FROM FOMUserBundle:Group g'); $groups = $query->getResult(); $allowed_groups = array(); // ACL access check foreach($groups as $index => $group) { if($this->get('security.authorization_checker')->isGranted('VIEW', $group)) { $allowed_groups[] = $group; } } return array( 'groups' => $allowed_groups, 'create_permission' => $this->get('security.authorization_checker')->isGranted('CREATE', $oid) ); }
php
{ "resource": "" }
q5583
OracleMetaDataDAOFactory.getInstance
train
public static function getInstance(DriverConfig $config) { $pdoDriver = PdoDriverFactory::getInstance(); return new OracleMetaDataDAO( $pdoDriver->getConnection($config) ); }
php
{ "resource": "" }
q5584
Config.getSource
train
public function getSource($sourceName = null) { if ($sourceName === 'default') { $sourceName = null; } foreach ($this->sources as $key => $item) { if ((!$sourceName || $sourceName === $key)) { return $item; } $source = $item !== $this ? $item->getSource($sourceName) : null; if ($source) { return $source; } } if ($sourceName) { return null; } return $this; }
php
{ "resource": "" }
q5585
SetupHelper.getRootFolder
train
public static function getRootFolder() { $filesystem = new Filesystem(); $folder = $filesystem->normalizePath(__DIR__ . '/../'); if (! is_dir($folder)) { throw new RuntimeException( sprintf( 'Could not find a matching folder for folder name "%1$s".', $folder ) ); } return $folder; }
php
{ "resource": "" }
q5586
SetupHelper.getFile
train
public static function getFile($fileName) { $filesystem = new Filesystem(); $file = $filesystem->normalizePath(__DIR__ . '/../' . $fileName); if (! file_exists($file)) { throw new RuntimeException( sprintf( 'Could not find a matching file for file name "%1$s".', $fileName ) ); } return $file; }
php
{ "resource": "" }
q5587
ServiceCreator.create
train
public function create($serviceId) { try { return $this->container->get($serviceId, Container::NULL_ON_INVALID_REFERENCE); } catch (\Exception $e) { if ($this->isCausedBySyntheticServiceRequest($e)) { // Ignore errors that are caused by synthetic services. It is simply not // possible to create them in a reliable way. return null; } throw new CannotInstantiateServiceException($serviceId, 0, $e); } }
php
{ "resource": "" }
q5588
ServiceCreator.isCausedBySyntheticServiceRequest
train
protected function isCausedBySyntheticServiceRequest(\Exception $exception) { if (!($exception instanceof RuntimeException)) { return false; } return strpos($exception->getMessage(), 'requested a synthetic service') !== false; }
php
{ "resource": "" }
q5589
Router._addRoute
train
protected function _addRoute($pattern, $paths = null, $method = null) { $route = new Route($pattern, $paths, $method); if ($method !== 'REST' && strpos($pattern, '{') === false) { $this->_simple_routes[$method][$pattern] = $route; } else { $this->_regex_routes[] = $route; } return $route; }
php
{ "resource": "" }
q5590
Router.add
train
public function add($pattern, $paths = null, $method = null) { return $this->_addRoute($pattern, $paths, $method); }
php
{ "resource": "" }
q5591
ApiKeyAuthenticator.authenticateToken
train
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $apiKey = $token->getCredentials(); $user = $this ->om ->getRepository($this->modelName) ->findOneBy(array($this->metadata->getPropertyName(ClassMetadata::API_KEY_PROPERTY) => (string) $apiKey)); if (!$user) { $this->dispatcher->dispatch(Ma27ApiKeyAuthenticationEvents::FIREWALL_FAILURE, new OnFirewallFailureEvent()); throw new AuthenticationException( sprintf('API key %s does not exist!', $apiKey) ); } $token = new PreAuthenticatedToken( $user, $apiKey, $providerKey, $user->getRoles() ?: array() ); $firewallEvent = new OnFirewallAuthenticationEvent($user); $firewallEvent->setToken($token); $this->dispatcher->dispatch(Ma27ApiKeyAuthenticationEvents::FIREWALL_LOGIN, $firewallEvent); return $token; }
php
{ "resource": "" }
q5592
ApiKeyAuthenticator.createToken
train
public function createToken(Request $request, $providerKey) { $apiKey = $request->headers->get($this->header); if (!$apiKey) { throw new BadCredentialsException('No ApiKey found in request!'); } return new PreAuthenticatedToken( 'unauthorized', $apiKey, $providerKey ); }
php
{ "resource": "" }
q5593
ViewFactory.getInstance
train
public static function getInstance() { $classAwake = new ClassAwake(); $viewHelpers = $classAwake->wakeByInterfaces( array( __DIR__, ), 'CrudGenerator\View\ViewHelperFactoryInterface' ); return new View(new ViewRenderer($viewHelpers)); }
php
{ "resource": "" }
q5594
AttributeController.deleteAttributeRelationAction
train
public function deleteAttributeRelationAction() { //wyszukiwanie rekordu relacji $record = (new \Cms\Orm\CmsAttributeRelationQuery) ->whereObjectId()->equals($this->id) ->findPk($this->relationId); //jeśli znaleziono rekord if ($record && $record->delete()) { //wyszukiwanie stron w zmienionym szablonie foreach ((new \Cms\Orm\CmsCategoryQuery)->whereCmsCategoryTypeId() ->equals($this->id) ->findPairs('id', 'id') as $categoryId) { //usuwanie wartości usuniętych atrybutów (new \Cms\Model\AttributeValueRelationModel('category', $categoryId)) ->deleteAttributeValueRelationsByAttributeId($record->cmsAttributeId); } $this->getMessenger()->addMessage('messenger.attribute.attributeRelation.deleted', true); } }
php
{ "resource": "" }
q5595
Validator.verify
train
public function verify($data, array $callbacks = [], $cast = '') { if (empty($callbacks) === true) { return $this->fields[$cast] = $data; } // Create a Closure $isValid = function ($data) use ($callbacks, $cast) { if (empty($cast) === false) { $this->cast = $cast; } foreach ($callbacks as $callback) { $this->{$callback}($data); } }; // return boolean as such return $isValid($data); }
php
{ "resource": "" }
q5596
Validator.setLength
train
public function setLength(array $condition) { if (is_array($condition) === true) { $this->{key($condition)} = (int) current($condition); } return $this; }
php
{ "resource": "" }
q5597
Validator.isNotNull
train
protected function isNotNull($value) { if (is_null($value) === true || empty($value) === true) { throw new ExceptionFactory('DataType', [$value, 'string']); } return true; }
php
{ "resource": "" }
q5598
Validator.isAcceptLength
train
protected function isAcceptLength($value) { $value = strlen(utf8_decode($value)); if ($value < $this->min) { throw new ExceptionFactory('InvalidLength', [$value, 'greater', $this->min]); } else if ($value > $this->max) { throw new ExceptionFactory('InvalidLength', [$value, 'less', $this->max]); } return true; }
php
{ "resource": "" }
q5599
Validator.isExists
train
protected function isExists(array $value) { // validate fields by exist in tables foreach ($value as $table => $fields) { // load model metaData if ($this->isModel($table) === true) { $model = (new Manager())->load($table, new $table); // check fields of table $this->validColumns($model->getModelsMetaData(), $fields, $table, $model); // setup clear used tables $columnDefines = (new $table)->getReadConnection()->describeColumns($model->getSource()); // add using tables with model alias $this->fields['tables'][$model->getSource()] = $table; // checking columns & fields foreach ($columnDefines as $column) { if (in_array($column->getName(), $fields) === true) { $this->validTypes($column); // add column to table collection $this->fields[$this->cast][$model->getSource()][$column->getName()] = $column->getType(); } } } } return true; }
php
{ "resource": "" }