_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5800 | RepositoryMakeCommand.getMethods | train | protected function getMethods()
{
if ($this->option('plain')) {
return [];
}
$methods = ['all', 'find', 'create', 'update', 'delete'];
if (($only = $this->option('only')) && $only != '') {
$methods = array_flip(array_only(array_flip($methods), $this->getArray($only)));
}
if (($except = $this->option('except')) && $except != '') {
$methods = array_flip(array_except(array_flip($methods), $this->getArray($except)));
}
return $methods;
} | php | {
"resource": ""
} |
q5801 | RepositoryMakeCommand.getArray | train | protected function getArray($values)
{
$values = explode(',', $values);
array_walk($values, function (&$value) {
$value = trim($value);
});
return $values;
} | php | {
"resource": ""
} |
q5802 | RepositoryMakeCommand.compileFileName | train | protected function compileFileName($className)
{
if (!$className) {
return false;
}
$className = str_replace($this->getAppNamespace(), '', $className);
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
return $className . '.php';
} | php | {
"resource": ""
} |
q5803 | RepositoryMakeCommand.getContractName | train | protected function getContractName()
{
if (!$this->input->getOption('contract')) {
return false;
}
$className = $this->getClassName();
return $this->getContractNamespace() . '\\' . $className;
} | php | {
"resource": ""
} |
q5804 | RepositoryMakeCommand.getRepositoryName | train | protected function getRepositoryName()
{
$prefix = $this->getClassNamePrefix();
$name = $this->getClassName();
if ($this->input->getOption('contract')) {
$name = $prefix . $name;
}
return $this->getNamespace() . '\\' . $name;
} | php | {
"resource": ""
} |
q5805 | RepositoryMakeCommand.getClassNamePrefix | train | protected function getClassNamePrefix()
{
$prefix = $this->input->getOption('prefix');
if (empty($prefix)) {
$prefix = $this->classNamePrefix;
}
return $prefix;
} | php | {
"resource": ""
} |
q5806 | RepositoryMakeCommand.getClassNameSuffix | train | protected function getClassNameSuffix()
{
$suffix = $this->input->getOption('suffix');
if (empty($suffix)) {
$suffix = $this->classNameSuffix;
}
return $suffix;
} | php | {
"resource": ""
} |
q5807 | RepositoryMakeCommand.getModelReflection | train | protected function getModelReflection()
{
$modelClassName = str_replace('/', '\\', $this->input->getArgument('model'));
try {
$reflection = new ReflectionClass($this->getAppNamespace() . $modelClassName);
} catch (\ReflectionException $e) {
$reflection = new ReflectionClass($modelClassName);
}
if (!$reflection->isSubclassOf(Model::class) || !$reflection->isInstantiable()) {
throw new NotAnInstanceOfException(sprintf('The model must be an instance of [%s]', Model::class));
}
return $reflection;
} | php | {
"resource": ""
} |
q5808 | RepositoryMakeCommand.getNamespace | train | protected function getNamespace($namespace = null)
{
if (!is_null($namespace)) {
$parts = explode('\\', $namespace);
array_pop($parts);
return join('\\', $parts);
}
return $this->getAppNamespace() . $this->namespace;
} | php | {
"resource": ""
} |
q5809 | UserSubscriber.submit | train | public function submit(FormEvent $event)
{
$user = $event->getData();
if (null === $user) {
return;
}
if ($this->currentUser !== null && $this->currentUser !== $user && $event->getForm()->has('activated')) {
$activated = $event->getForm()->get('activated')->getData();
if ($activated && $user->getRegistrationToken()) {
$user->setRegistrationToken(null);
} elseif (!$activated && !$user->getRegistrationToken()) {
$user->setRegistrationToken(hash("sha1",rand()));
}
}
} | php | {
"resource": ""
} |
q5810 | UserSubscriber.preSetData | train | public function preSetData(FormEvent $event)
{
$user = $event->getData();
if (null === $user) {
return;
}
if($this->currentUser !== null && $this->currentUser !== $user) {
$event->getForm()->add($this->factory->createNamed('activated', 'checkbox', null, array(
'data' => $user->getRegistrationToken() ? false : true,
'auto_initialize' => false,
'label' => 'Activated',
'required' => false,
'mapped' => false)));
}
} | php | {
"resource": ""
} |
q5811 | ServerManager.server | train | public function server($name = null)
{
if (empty($name)) {
$name = $this->getDefaultServerName();
}
if (!isset($this->servers[$name])) {
$this->servers[$name] = $this->makeServer($name);
}
return $this->servers[$name];
} | php | {
"resource": ""
} |
q5812 | ServerManager.makeServer | train | protected function makeServer($name)
{
$config = $this->getConfig($name);
if (empty($config)) {
throw new \InvalidArgumentException("Unable to instantiate Glide server because you provide en empty configuration, \"{$name}\" is probably a wrong server name.");
}
if (array_key_exists($config['source'], $this->app['config']['filesystems']['disks'])) {
$config['source'] = $this->app['filesystem']->disk($config['source'])->getDriver();
}
if (array_key_exists($config['cache'], $this->app['config']['filesystems']['disks'])) {
$config['cache'] = $this->app['filesystem']->disk($config['cache'])->getDriver();
}
if (isset($config['watermarks']) && array_key_exists($config['watermarks'], $this->app['config']['filesystems']['disks'])) {
$config['watermarks'] = $this->app['filesystem']->disk($config['watermarks'])->getDriver();
}
return new GlideServer($this->app, $config);
} | php | {
"resource": ""
} |
q5813 | HelpController.listCommand | train | public function listCommand()
{
$this->console->writeLn('manaphp commands:', Console::FC_GREEN | Console::AT_BOLD);
foreach (glob(__DIR__ . '/*Controller.php') as $file) {
$plainName = basename($file, '.php');
if (in_array($plainName, ['BashCompletionController', 'HelpController'], true)) {
continue;
}
$this->console->writeLn(' - ' . $this->console->colorize(Text::underscore(basename($plainName, 'Controller')), Console::FC_YELLOW));
$commands = $this->_getCommands(__NAMESPACE__ . "\\" . $plainName);
$width = max(max(array_map('strlen', array_keys($commands))), 18);
foreach ($commands as $command => $description) {
$this->console->writeLn(' ' . $this->console->colorize($command, Console::FC_CYAN, $width) . ' ' . $description);
}
}
if ($this->alias->has('@cli')) {
$this->console->writeLn('application commands: ', Console::FC_GREEN | Console::AT_BOLD);
foreach (glob($this->alias->resolve('@cli/*Controller.php')) as $file) {
$plainName = basename($file, '.php');
$this->console->writeLn(' - ' . $this->console->colorize(Text::underscore(basename($plainName, 'Controller')), Console::FC_YELLOW));
$commands = $this->_getCommands($this->alias->resolveNS("@ns.cli\\$plainName"));
$width = max(max(array_map('strlen', array_keys($commands))), 18);
foreach ($commands as $command => $description) {
$this->console->writeLn(' ' . $this->console->colorize($command, Console::FC_CYAN, $width + 1) . ' ' . $description);
}
}
}
return 0;
} | php | {
"resource": ""
} |
q5814 | CreateSourceBackboneFactory.getInstance | train | public static function getInstance(ContextInterface $context)
{
return new CreateSourceBackbone(
MetadataSourceQuestionFactory::getInstance($context),
MetaDataConfigDAOFactory::getInstance($context),
$context
);
} | php | {
"resource": ""
} |
q5815 | TaskController.listCommand | train | public function listCommand()
{
$this->console->writeLn('tasks list:');
$tasks = [];
$tasksDir = $this->alias->resolve('@app/Tasks');
if (is_dir($tasksDir)) {
foreach (glob("$tasksDir/*Task.php") as $file) {
$task = basename($file, 'Task.php');
$tasks[] = ['name' => Text::underscore($task), 'desc' => $this->_getTaskDescription($task)];
}
}
$width = max(array_map(static function ($v) {
return strlen($v['name']);
}, $tasks)) + 3;
foreach ($tasks as $task) {
$this->console->writeLn([' :1 :2', $this->console->colorize($task['name'], Console::FC_MAGENTA, $width), $task['desc']]);
}
} | php | {
"resource": ""
} |
q5816 | VendorResources.isVendorClass | train | public static function isVendorClass($classNameOrObject)
{
$className = (is_object($classNameOrObject)) ? get_class($classNameOrObject) : $classNameOrObject;
if (!class_exists($className)) {
$message = '"' . $className . '" is not the name of a loadable class.';
throw new \InvalidArgumentException($message);
}
$reflection = new \ReflectionClass($className);
if ($reflection->isInternal()) {
return false;
}
return static::isVendorFile($reflection->getFileName());
} | php | {
"resource": ""
} |
q5817 | VendorResources.isVendorFile | train | public static function isVendorFile($pathOrFileObject)
{
$path = ($pathOrFileObject instanceof \SplFileInfo) ? $pathOrFileObject->getPathname() : $pathOrFileObject;
if (!file_exists($path)) {
$message = '"' . $path . '" does not reference a file or directory.';
throw new \InvalidArgumentException($message);
}
// The file path must start with the vendor directory.
return strpos($path, static::getVendorDirectory()) === 0;
} | php | {
"resource": ""
} |
q5818 | PaymentMethodCode.code | train | public static function code($constant)
{
$ref = new \ReflectionClass('\PayPay\Structure\PaymentMethodCode');
$constants = $ref->getConstants();
if (!isset($constants[$constant])) {
throw new \InvalidArgumentException("Invalid payment method code constant " . $constant);
}
return $ref->getConstant($constant);
} | php | {
"resource": ""
} |
q5819 | CssToXPath._transform | train | protected function _transform($path_src)
{
$path = (string)$path_src;
if (strpos($path, ',') !== false) {
$paths = explode(',', $path);
$expressions = [];
foreach ($paths as $path) {
$xpath = $this->transform(trim($path));
if (is_string($xpath)) {
$expressions[] = $xpath;
} elseif (is_array($xpath)) {
/** @noinspection SlowArrayOperationsInLoopInspection */
$expressions = array_merge($expressions, $xpath);
}
}
return implode('|', $expressions);
}
$paths = ['//'];
$path = preg_replace('|\s+>\s+|', '>', $path);
$segments = preg_split('/\s+/', $path);
foreach ($segments as $key => $segment) {
$pathSegment = static::_tokenize($segment);
if (0 === $key) {
if (0 === strpos($pathSegment, '[contains(')) {
$paths[0] .= '*' . ltrim($pathSegment, '*');
} else {
$paths[0] .= $pathSegment;
}
continue;
}
if (0 === strpos($pathSegment, '[contains(')) {
foreach ($paths as $pathKey => $xpath) {
$paths[$pathKey] .= '//*' . ltrim($pathSegment, '*');
$paths[] = $xpath . $pathSegment;
}
} else {
foreach ($paths as $pathKey => $xpath) {
$paths[$pathKey] .= '//' . $pathSegment;
}
}
}
if (1 === count($paths)) {
return $paths[0];
}
return implode('|', $paths);
} | php | {
"resource": ""
} |
q5820 | CssToXPath._tokenize | train | protected static function _tokenize($expression_src)
{
// Child selectors
$expression = str_replace('>', '/', $expression_src);
// IDs
$expression = preg_replace('|#([a-z][a-z0-9_-]*)|i', "[@id='$1']", $expression);
$expression = preg_replace('|(?<![a-z0-9_-])(\[@id=)|i', '*$1', $expression);
// arbitrary attribute strict equality
$expression = preg_replace_callback(
'|\[@?([a-z0-9_-]*)([~\*\^\$\|\!])?=([^\[]+)\]|i',
static function ($matches) {
$attr = strtolower($matches[1]);
$type = $matches[2];
$val = trim($matches[3], "'\" \t");
$field = ($attr === '' ? 'text()' : '@' . $attr);
$items = [];
foreach (explode(strpos($val, '|') !== false ? '|' : '&', $val) as $word) {
if ($type === '') {
$items[] = "$field='$word'";
} elseif ($type === '~') {
$items[] = "contains(concat(' ', normalize-space($field), ' '), ' $word ')";
} elseif ($type === '|') {
$item = "$field='$word' or starts-with($field,'$word-')";
$items[] = $word === $val ? $item : "($item)";
} elseif ($type === '!') {
$item = "not($field) or $field!='$word'";
$items[] = $word === $val ? $item : "($item)";
} else {
$items[] = ['*' => 'contains', '^' => 'starts-with', '$' => 'ends-with'][$type] . "($field, '$word')";
}
}
return '[' . implode(strpos($val, '|') !== false ? ' or ' : ' and ', $items) . ']';
},
$expression
);
//attribute contains specified content
$expression = preg_replace_callback(
'|\[(!?)([a-z][a-z0-9_-\|&]*)\]|i',
static function ($matches) {
$val = $matches[2];
$op = strpos($val, '|') !== false ? '|' : '&';
$items = [];
foreach (explode($op, $val) as $word) {
$items[] = '@' . $word;
}
$r = '[' . implode($op === '|' ? ' or ' : ' and ', $items) . ']';
return $matches[1] === '!' ? "not($r)" : $r;
},
$expression
);
// Classes
if (false === strpos($expression, '[@')) {
$expression = preg_replace(
'|\.([a-z][a-z0-9_-]*)|i',
"[contains(concat(' ', normalize-space(@class), ' '), ' \$1 ')]",
$expression
);
}
/** ZF-9764 -- remove double asterisk */
$expression = str_replace('**', '*', $expression);
return $expression;
} | php | {
"resource": ""
} |
q5821 | ConfigurationMenuProvider.sortItems | train | protected function sortItems(&$items)
{
$this->safeUaSortItems($items, function ($item1, $item2) {
if (empty($item1['order']) || empty($item2['order']) || $item1['order'] == $item2['order']) {
return 0;
}
return ($item1['order'] < $item2['order']) ? -1 : 1;
});
} | php | {
"resource": ""
} |
q5822 | ConfigurationMenuProvider.isGranted | train | protected function isGranted(array $configuration)
{
// If no role configuration. Grant rights.
if (!isset($configuration['roles'])) {
return true;
}
// If no configuration. Grant rights.
if (!is_array($configuration['roles'])) {
return true;
}
// Check if one of the role is granted
foreach ($configuration['roles'] as $role) {
if ($this->authorizationChecker->isGranted($role)) {
return true;
}
}
// Else return false
return false;
} | php | {
"resource": ""
} |
q5823 | RemoteShell.process | train | protected function process()
{
$output = "";
$offset = 0;
$this->shell->_initShell();
while( true ) {
$temp = $this->shell->_get_channel_packet(SSH2::CHANNEL_EXEC);
switch( true ) {
case $temp === true:
case $temp === false:
return $output;
default:
$output .= $temp;
if( $this->handle_data(substr($output, $offset)) ) {
$offset = strlen($output);
}
}
}
} | php | {
"resource": ""
} |
q5824 | KeyController.generateCommand | train | public function generateCommand($length = 32, $lowercase = 0)
{
$key = $this->random->getBase($length);
$this->console->writeLn($lowercase ? strtolower($key) : $key);
} | php | {
"resource": ""
} |
q5825 | Grid.addColumn | train | public final function addColumn(Column\ColumnAbstract $column)
{
//dodawanie Columnu (nazwa unikalna)
return $this->_columns[$column->getName()] = $column->setGrid($this);
} | php | {
"resource": ""
} |
q5826 | MessageRepository.countUnread | train | public function countUnread(User $user)
{
return $this->createQueryBuilder('m')
->select('count(m)')
->join('m.userMessages', 'um')
->where('m.user != :sender')
->orWhere('m.user IS NULL')
->andWhere('um.user = :user')
->andWhere('um.isRead = 0')
->andWhere('um.isRemoved = 0')
->setParameter(':user', $user)
->setParameter(':sender', $user)
->getQuery()
->getSingleScalarResult();
} | php | {
"resource": ""
} |
q5827 | CmsFileQuery.imagesByObject | train | public static function imagesByObject($object = null, $objectId = null)
{
//zapytanie po obiekcie
return self::byObject($object, $objectId)
->whereClass()->equals('image');
} | php | {
"resource": ""
} |
q5828 | CmsFileQuery.stickyByObject | train | public static function stickyByObject($object = null, $objectId = null, $class = null)
{
//zapytanie po obiekcie
$q = self::byObject($object, $objectId)
->whereSticky()->equals(1);
//dodawanie klasy jeśli wyspecyfikowana
if (null !== $class) {
$q->andFieldClass()->equals($class);
}
return $q;
} | php | {
"resource": ""
} |
q5829 | CmsFileQuery.notImagesByObject | train | public static function notImagesByObject($object = null, $objectId = null)
{
//zapytanie po obiekcie i id
return self::byObject($object, $objectId)
->whereClass()->notEquals('image');
} | php | {
"resource": ""
} |
q5830 | HashManager.option | train | public function option($option = null)
{
if ( ! is_null($option)) {
$this->option = $option;
$this->buildDrivers();
}
return $this;
} | php | {
"resource": ""
} |
q5831 | HashManager.buildDrivers | train | private function buildDrivers()
{
$drivers = $this->getHasherConfig('drivers', []);
foreach ($drivers as $name => $driver) {
$this->buildDriver($name, $driver);
}
} | php | {
"resource": ""
} |
q5832 | HashManager.buildDriver | train | private function buildDriver($name, array $driver)
{
return $this->drivers[$name] = new $driver['driver'](
Arr::get($driver, 'options.'.$this->getDefaultOption(), [])
);
} | php | {
"resource": ""
} |
q5833 | FrameworkController.minifyCommand | train | public function minifyCommand()
{
$ManaPHPSrcDir = $this->alias->get('@manaphp');
$ManaPHPDstDir = $ManaPHPSrcDir . '_' . date('ymd');
$totalClassLines = 0;
$totalInterfaceLines = 0;
$totalLines = 0;
$fileLines = [];
$sourceFiles = $this->_getSourceFiles($ManaPHPSrcDir);
foreach ($sourceFiles as $file) {
$dstFile = str_replace($ManaPHPSrcDir, $ManaPHPDstDir, $file);
$content = $this->_minify($this->filesystem->fileGet($file));
$lineCount = substr_count($content, strpos($content, "\r") !== false ? "\r" : "\n");
if (strpos($file, 'Interface.php')) {
$totalInterfaceLines += $lineCount;
$totalLines += $lineCount;
} else {
$totalClassLines += $lineCount;
$totalLines += $lineCount;
}
$this->console->writeLn($content);
$this->filesystem->filePut($dstFile, $content);
$fileLines[$file] = $lineCount;
}
asort($fileLines);
$i = 1;
$this->console->writeLn('------------------------------------------------------');
foreach ($fileLines as $file => $line) {
$this->console->writeLn(sprintf('%3d %3d %.3f', $i++, $line, $line / $totalLines * 100) . ' ' . substr($file, strpos($file, 'ManaPHP')));
}
$this->console->writeLn('------------------------------------------------------');
$this->console->writeLn('total lines: ' . $totalLines);
$this->console->writeLn('class lines: ' . $totalClassLines);
$this->console->writeLn('interface lines: ' . $totalInterfaceLines);
return 0;
} | php | {
"resource": ""
} |
q5834 | FrameworkController.genJsonCommand | train | public function genJsonCommand($source)
{
$classNames = [];
/** @noinspection ForeachSourceInspection */
/** @noinspection PhpIncludeInspection */
foreach (require $source as $className) {
if (preg_match('#^ManaPHP\\\\.*$#', $className)) {
$classNames[] = $className;
}
}
$output = __DIR__ . '/manaphp_lite.json';
if ($this->filesystem->fileExists($output)) {
$data = json_encode($this->filesystem->fileGet($output));
} else {
$data = [
'output' => '@root/manaphp.lite'
];
}
$data['classes'] = $classNames;
$this->filesystem->filePut($output, json_encode($data, JSON_PRETTY_PRINT));
$this->console->writeLn(json_encode($classNames, JSON_PRETTY_PRINT));
} | php | {
"resource": ""
} |
q5835 | TaggedServiceIterator.getIterator | train | public function getIterator()
{
$tagsById = $this->container->findTaggedServiceIds($this->tag);
$taggedServices = array();
foreach ($tagsById as $id => $tagDefinitions) {
/* @var $id string */
/* @var $tagDefinitions array(array(string=>string)) */
foreach ($tagDefinitions as $tagDefinition) {
/* @var $tagDefinition array(string=>string) */
$taggedServices[] = new TaggedService($id, $tagDefinition);
}
}
return new \ArrayIterator($taggedServices);
} | php | {
"resource": ""
} |
q5836 | OperationColumn.addCustomButton | train | public function addCustomButton($iconName, array $params = [], $hashTarget = '')
{
$customButtons = is_array($this->getOption('customButtons')) ? $this->getOption('customButtons') : [];
$customButtons[] = ['iconName' => $iconName, 'params' => $params, 'hashTarget' => $hashTarget];
return $this->setOption('customButtons', $customButtons);
} | php | {
"resource": ""
} |
q5837 | MetaDataColumn.getName | train | public function getName($ucfirst = false)
{
$value = $this->camelCase($this->name);
if (true === $ucfirst) {
return ucfirst($value);
} else {
return $value;
}
} | php | {
"resource": ""
} |
q5838 | Request.getFiles | train | public function getFiles($onlySuccessful = true)
{
$context = $this->_context;
$files = [];
/** @var $_FILES array */
foreach ($context->_FILES as $key => $file) {
if (is_int($file['error'])) {
if (!$onlySuccessful || $file['error'] === UPLOAD_ERR_OK) {
$fileInfo = [
'name' => $file['name'],
'type' => $file['type'],
'tmp_name' => $file['tmp_name'],
'error' => $file['error'],
'size' => $file['size'],
];
$files[] = new File($key, $fileInfo);
}
} else {
$countFiles = count($file['error']);
/** @noinspection ForeachInvariantsInspection */
for ($i = 0; $i < $countFiles; $i++) {
if (!$onlySuccessful || $file['error'][$i] === UPLOAD_ERR_OK) {
$fileInfo = [
'name' => $file['name'][$i],
'type' => $file['type'][$i],
'tmp_name' => $file['tmp_name'][$i],
'error' => $file['error'][$i],
'size' => $file['size'][$i],
];
$files[] = new File($key, $fileInfo);
}
}
}
}
return $files;
} | php | {
"resource": ""
} |
q5839 | Contact.beforeSave | train | public function beforeSave()
{
$this->getRecord()->active = 0;
$this->getRecord()->cmsAuthIdReply = \App\Registry::$auth->getId();
return true;
} | php | {
"resource": ""
} |
q5840 | Session.destroy | train | public function destroy($session_id = null)
{
if ($session_id) {
$this->eventsManager->fireEvent('session:destroy', $this, ['session_id' => $session_id]);
$this->do_destroy($session_id);
} else {
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
$this->eventsManager->fireEvent('session:destroy', $this, ['session_id' => $session_id, 'context' => $context]);
$context->started = false;
$context->is_dirty = false;
$context->session_id = null;
$context->_SESSION = null;
$this->do_destroy($context->session_id);
$params = $this->_cookie_params;
$this->cookies->delete($this->_name, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
} | php | {
"resource": ""
} |
q5841 | Session.get | train | public function get($name = null, $default = null)
{
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
if ($name === null) {
return $context->_SESSION;
} elseif (isset($context->_SESSION[$name])) {
return $context->_SESSION[$name];
} else {
return $default;
}
} | php | {
"resource": ""
} |
q5842 | Session.set | train | public function set($name, $value)
{
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
$context->is_dirty = true;
$context->_SESSION[$name] = $value;
} | php | {
"resource": ""
} |
q5843 | Session.has | train | public function has($name)
{
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
return isset($context->_SESSION[$name]);
} | php | {
"resource": ""
} |
q5844 | Session.remove | train | public function remove($name)
{
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
$context->is_dirty = true;
unset($context->_SESSION[$name]);
} | php | {
"resource": ""
} |
q5845 | Ma27ApiKeyAuthenticationExtension.loadCore | train | private function loadCore(ContainerBuilder $container, Loader\YamlFileLoader $loader, $config)
{
$isCacheEnabled = $config['metadata_cache'];
$container->setParameter('ma27_api_key_authentication.model_name', $config['model_name']);
$container->setParameter('ma27_api_key_authentication.object_manager', $config['object_manager']);
$container->setParameter('ma27_api_key_authentication.property.apiKeyLength', $config['api_key_length']);
$container->setParameter('ma27_api_key_authentication.metadata_cache_enabled', $isCacheEnabled);
if ($isCacheEnabled) {
$loader->load('metadata_cache_warmer.yml');
}
$this->loadPassword($container, $config['password'], $loader);
} | php | {
"resource": ""
} |
q5846 | Ma27ApiKeyAuthenticationExtension.loadPassword | train | private function loadPassword(ContainerBuilder $container, $passwordConfig, Loader\YamlFileLoader $loader)
{
$container->setParameter('ma27_api_key_authentication.password_hashing_service', $passwordConfig['strategy']);
$container->setParameter('ma27_api_key_authentication.password_hasher.phpass.iteration_length', 8);
$container->setParameter('ma27_api_key_authentication.password_hasher.php55.cost', 12);
$loader->load('hashers.yml');
} | php | {
"resource": ""
} |
q5847 | Ma27ApiKeyAuthenticationExtension.loadServices | train | private function loadServices(Loader\YamlFileLoader $loader)
{
foreach (array('security_key', 'authentication', 'security', 'annotation') as $file) {
$loader->load(sprintf('%s.yml', $file));
}
} | php | {
"resource": ""
} |
q5848 | Ma27ApiKeyAuthenticationExtension.loadApiKeyPurger | train | private function loadApiKeyPurger(ContainerBuilder $container, Loader\YamlFileLoader $loader, array $purgerConfig)
{
$container->setParameter('ma27_api_key_authentication.cleanup_command.date_time_rule', $purgerConfig['outdated_rule']);
$loader->load('session_cleanup.yml');
if ($this->isConfigEnabled($container, $purgerConfig['last_action_listener'])) {
$loader->load('last_action_listener.yml');
}
} | php | {
"resource": ""
} |
q5849 | Ma27ApiKeyAuthenticationExtension.overrideServices | train | private function overrideServices(ContainerBuilder $container, array $services)
{
$serviceConfig = array(
'auth_handler' => 'ma27_api_key_authentication.auth_handler',
'key_factory' => 'ma27_api_key_authentication.key_factory',
);
foreach ($serviceConfig as $configIndex => $replaceableServiceId) {
if (!isset($services[$configIndex]) || null === $serviceId = $services[$configIndex]) {
continue;
}
$container->removeDefinition($replaceableServiceId);
$container->setAlias($replaceableServiceId, new Alias($serviceId));
}
} | php | {
"resource": ""
} |
q5850 | Text.text | train | public function text($key)
{
return nl2br(\Cms\Model\Text::textByKeyLang($key, \Mmi\App\FrontController::getInstance()->getView()->request->lang));
} | php | {
"resource": ""
} |
q5851 | SettingsParser.getSites | train | public function getSites()
{
$sites = [];
$defaultSet = false;
if (!$this->getValid()) {
return $sites;
}
foreach ($this->xml->children() as $child) {
if ($child->getName() == "site") {
$site = $this->parseSite($child);
if ($site !== false) {
if ($defaultSet && $site['default']) {
$this->logger->error('There can be only one default site.');
} else {
$sites[$site['url']] = $site;
$defaultSet |= $site['default'];
}
}
}
}
return $sites;
} | php | {
"resource": ""
} |
q5852 | SettingsParser.getStaticTokens | train | public function getStaticTokens()
{
$tokens = [];
$sites = [];
if (!$this->getValid()) {
return $sites;
}
foreach ($this->xml->children() as $child) {
if ($child->getName() == "token") {
$token = $this->parseToken($child);
if ($token !== false) {
$tokens[$token['token']] = $token;
}
}
}
return $tokens;
} | php | {
"resource": ""
} |
q5853 | AclManager.setObjectACL | train | public function setObjectACL($entity, $aces, $type)
{
if ($type != "object") {
throw new \RuntimeException('ACEs of type ' . $type . ' are not supported.');
}
$acl = $this->getAcl($entity);
$oldAces = $acl->getObjectAces();
// Delete old ACEs
foreach (array_reverse(array_keys($oldAces)) as $idx) {
$acl->deleteObjectAce(intval($idx));
}
$this->aclProvider->updateAcl($acl);
// Add new ACEs
foreach (array_reverse($aces) as $idx => $ace) {
// If no mask is given, we might as well not insert the ACE
if ($ace['mask'] === 0) {
continue;
}
$acl->insertObjectAce($ace['sid'], $ace['mask']);
}
$this->aclProvider->updateAcl($acl);
} | php | {
"resource": ""
} |
q5854 | AclManager.getACL | train | public function getACL($entity, $create = true)
{
$acl = null;
$oid = $this->getEntityObjectId($entity);
try {
$acl = $this->aclProvider->findAcl($oid);
} catch (NotAllAclsFoundException $e) {
$acl = $e->getPartialResult();
} catch (AclNotFoundException $e) {
if($create){
$acl = $this->aclProvider->createAcl($oid);
}
}
return $acl;
} | php | {
"resource": ""
} |
q5855 | TinyMce._modeSimple | train | protected function _modeSimple()
{
if ($this->getToolbars() === null) {
$this->setToolbars('bold italic underline strikethrough | alignleft aligncenter alignright alignjustify');
}
if ($this->getContextMenu() === null) {
$this->setContextMenu('link image inserttable | cell row column deletetable');
}
if ($this->getResize() === null) {
$this->setResize(false);
}
if ($this->getMenubar() === null) {
$this->setMenubar(false);
}
} | php | {
"resource": ""
} |
q5856 | TinyMce._modeAdvanced | train | protected function _modeAdvanced()
{
if ($this->getToolbars() === null) {
$this->setToolbars([
'undo redo | cut copy paste pastetext | searchreplace | bold italic underline strikethrough | subscript superscript | alignleft aligncenter alignright alignjustify | fontselect fontsizeselect | forecolor backcolor',
'styleselect | table | bullist numlist outdent indent blockquote | link unlink anchor | image media lioniteimages | preview fullscreen code | charmap visualchars nonbreaking inserttime hr'
]);
}
if ($this->getContextMenu() === null) {
$this->setContextMenu('link image media inserttable | cell row column deletetable');
}
} | php | {
"resource": ""
} |
q5857 | TinyMce._modeDefault | train | protected function _modeDefault()
{
if ($this->getToolbars() === null) {
$this->setToolbars('undo redo | bold italic underline strikethrough | forecolor backcolor | styleselect | bullist numlist outdent indent | fontselect fontsizeselect | alignleft aligncenter alignright alignjustify | link unlink anchor | image media lioniteimages | preview');
}
if ($this->getContextMenu() === null) {
$this->setContextMenu('link image media inserttable | cell row column deletetable');
}
} | php | {
"resource": ""
} |
q5858 | CmsTextQuery.lang | train | public static function lang()
{
if (!\Mmi\App\FrontController::getInstance()->getRequest()->lang) {
return new self;
}
return (new self)
->whereLang()->equals(\Mmi\App\FrontController::getInstance()->getRequest()->lang)
->orFieldLang()->equals(null)
->orderDescLang();
} | php | {
"resource": ""
} |
q5859 | Dispatcher.getParam | train | public function getParam($name, $default = null)
{
$params = $this->_context->params;
return isset($params[$name]) ? $params[$name] : $default;
} | php | {
"resource": ""
} |
q5860 | Dispatcher.dispatch | train | public function dispatch($router)
{
$context = $this->_context;
if ($router instanceof RouterContext) {
$area = $router->area;
$controller = $router->controller;
$action = $router->action;
$params = $router->params;
} else {
$area = $router->getArea();
$controller = $router->getController();
$action = $router->getAction();
$params = $router->getParams();
}
if ($area) {
$area = strpos($area, '_') === false ? ucfirst($area) : Text::camelize($area);
$context->area = $area;
}
$controller = strpos($controller, '_') === false ? ucfirst($controller) : Text::camelize($controller);
$context->controller = $controller;
$action = strpos($action, '_') === false ? $action : lcfirst(Text::camelize($action));
$context->action = $action;
$context->params = $params;
if ($area) {
if ($action === 'index') {
if ($controller === 'Index') {
$context->path = $area === 'Index' ? '/' : '/' . Text::underscore($area);
} else {
$context->path = '/' . Text::underscore($area) . '/' . Text::underscore($controller);
}
} else {
$context->path = '/' . Text::underscore($area) . '/' . Text::underscore($controller) . '/' . Text::underscore($action);
}
} else {
if ($action === 'index') {
$context->path = $controller === 'Index' ? '/' : '/' . Text::underscore($controller);
} else {
$context->path = '/' . Text::underscore($controller) . '/' . Text::underscore($action);
}
}
$controllerClassName = $this->_getControllerClassName();
/**
* @var \ManaPHP\Rest\Controller $controllerInstance
*/
$controllerInstance = $this->_di->getShared($controllerClassName);
$context->controllerInstance = $controllerInstance;
return $this->invokeAction($controllerInstance, $action, $params);
} | php | {
"resource": ""
} |
q5861 | Secint.encode | train | public function encode($id, $type = '')
{
if (!isset($this->_keys[$type])) {
if ($this->_key === null) {
$this->_key = $this->crypt->getDerivedKey('secint');
}
$this->_keys[$type] = md5($this->_key . $type, true);
}
while (true) {
$rand = mt_rand() & 0xFFFF0000;
$r = base64_encode(mcrypt_encrypt(MCRYPT_XTEA, $this->_keys[$type], pack('VV', $id, $rand), MCRYPT_MODE_ECB));
if (strcspn($r, '+/') === 12) {
return substr($r, 0, -1);
}
}
return $id;
} | php | {
"resource": ""
} |
q5862 | Secint.decode | train | public function decode($hash, $type = '')
{
if (strlen($hash) !== 11) {
return false;
}
if (!isset($this->_keys[$type])) {
if ($this->_key === null) {
$this->_key = $this->crypt->getDerivedKey('secint');
}
$this->_keys[$type] = md5($this->_key . $type, true);
}
$r = unpack('Vid/Vr', mcrypt_decrypt(MCRYPT_XTEA, $this->_keys[$type], base64_decode($hash . '='), MCRYPT_MODE_ECB));
if ($r['r'] & 0xFFFF) {
return false;
} else {
return $r['id'];
}
} | php | {
"resource": ""
} |
q5863 | WallPosterExtension.getConfigurationDirectory | train | protected function getConfigurationDirectory()
{
$reflector = new \ReflectionClass($this);
$fileName = $reflector->getFileName();
if (!is_dir($directory = dirname($fileName) . $this->configDirectory)) {
throw new \RuntimeException(sprintf('The configuration directory "%s" does not exists.', $directory));
}
return $directory;
} | php | {
"resource": ""
} |
q5864 | UserAjax.postCreate | train | public function postCreate()
{
$response = array(
"method" => "create",
"success" => false,
"user" => "",
"error_code" => 0,
"error_message" => ""
);
try {
AuthorizerHelper::can(UserValidator::USER_CAN_SAVE);
$data = json_decode(file_get_contents("php://input"));
if (empty($data)) {
$data = (object) $_POST;
}
$userModel = new User();
// Check required fields
$requiredParams = array('email', 'name', 'role', 'password');
$params = (array) $data;
foreach ($requiredParams as $param){
if (empty($params[$param])) {
throw new \Exception(ucfirst($param) .' is required.');
}
}
// Check Dupe email [ER-155]
if(!empty($data->email)) {
if (false === $userModel->isEmailUnique($data->email)) {
throw new \Exception("The email you entered already exists.");
}
}
$userId = $userModel->save($data);
if (empty($userId)) {
throw new \Exception('Could not create new user.');
}
$user = $userModel->getById($userId);
$output = array('id' => $user->getId(),
'email' => $user->getEmail(),
'role' => $this->getRoleInfo($user),
'name' => $user->getName(),
'last_login' => $user->getLastLogin(),
'gateway_customer_id'=> $user->getGatewayCustomerId()
);
$response['user'] = $output;
$response['success'] = true;
$this->setStatusCode(200);
} catch (\Exception $e) {
$response['error_message'] = $e->getMessage();
$response['error_code'] = $e->getCode();
}
$this->setContent($response);
} | php | {
"resource": ""
} |
q5865 | ResponseCreationListener.onResponseCreation | train | public function onResponseCreation(OnAssembleResponseEvent $event)
{
if ($event->isSuccess()) {
$event->setResponse(new JsonResponse(array(
$this->apiKeyValue => $this->metadata->getPropertyValue($event->getUser(), ClassMetadata::API_KEY_PROPERTY),
)));
return;
}
$event->setResponse(new JsonResponse(
array($this->messageValue => $this->translator->trans($event->getException()->getMessage() ?: 'Credentials refused!')),
JsonResponse::HTTP_UNAUTHORIZED
));
} | php | {
"resource": ""
} |
q5866 | Node.fromRawEntry | train | public static function fromRawEntry($entry)
{
$className = get_called_class();
$class = new $className();
foreach ($entry as $property=> $value)
$class->{$property} = $value;
return $class;
} | php | {
"resource": ""
} |
q5867 | ParseNode.abs_end | train | function abs_end(){
$Node = $this;
while( $Child = end( $Node->children ) ){
$Node = $Child;
}
return $Node;
} | php | {
"resource": ""
} |
q5868 | ParseNode.abs_pop | train | function abs_pop(){
$Node = $this->abs_end();
if( is_null($Node->pidx) ){
// cannot pop self from self
return false;
}
// pop node from it's parent
return $Node->get_parent()->pop();
} | php | {
"resource": ""
} |
q5869 | ParseNode.terminate | train | function terminate( $tok ){
if( is_scalar($tok) ){
// scalar token e.g. ";"
if( is_null($this->t) ){
$this->t = $tok;
}
$this->value = $tok;
}
else if( is_array($tok) ){
// PHP tokenizer style array token
$this->t = $tok[0];
$this->value = $tok[1];
// store additional info in terminal node
if( isset($tok[2]) ){
$this->l = $tok[2];
if( isset($tok[3]) ){
$this->c = $tok[3];
}
}
}
// destroy all children
while( $Child = $this->pop() ){
$Child->destroy();
}
} | php | {
"resource": ""
} |
q5870 | ParseNode.get_child | train | function get_child( $i ){
return isset($this->children[$i]) ? $this->children[$i] : null;
} | php | {
"resource": ""
} |
q5871 | ParseNode.get_line_num | train | function get_line_num(){
if( ! isset($this->l) ){
if( isset($this->children[0]) ){
$this->l = $this->children[0]->get_line_num();
}
else {
$this->l = 0;
}
}
return $this->l;
} | php | {
"resource": ""
} |
q5872 | ParseNode.get_col_num | train | function get_col_num(){
if( ! isset($this->c) ){
if( isset($this->children[0]) ){
$this->c = $this->children[0]->get_col_num();
}
else {
$this->c = 0;
}
}
return $this->c;
} | php | {
"resource": ""
} |
q5873 | ParseNode.push | train | function push( ParseNode $Node, $recursion = true ){
if( $Node->pidx ){
trigger_error("Node $Node->idx already has parent $Node->pidx", E_USER_WARNING );
}
// Resolve recursion on the fly if required
if( $this->t === $Node->t && $Node->length ){
// allow node's own setting to override parameter
if( isset($Node->recursion) ){
$recursion = $Node->recursion;
}
if( ! $recursion ){
$this->push_thru( $Node );
$Node->destroy();
return $this->length;
}
}
// else set node as child of self
$Node->pidx = $this->idx;
$Node->depth = $this->depth + 1;
$this->p = 0;
return $this->length = array_push( $this->children, $Node );
} | php | {
"resource": ""
} |
q5874 | ParseNode.push_thru | train | function push_thru( ParseNode $Node ){
foreach( $Node->children as $Child ){
$Node->remove( $Child );
$this->push( $Child );
}
return $this->length;
} | php | {
"resource": ""
} |
q5875 | ParseNode.pop | train | function pop(){
if( ! $this->length ){
return null;
}
if( --$this->length <= 0 ){
$this->length = 0;
$this->p = null;
}
else {
$this->p = 0;
}
$Node = array_pop( $this->children );
$Node->pidx = null;
$Node->depth = 0;
return $Node;
} | php | {
"resource": ""
} |
q5876 | ParseNode.remove | train | function remove( ParseNode $Node ){
foreach( $this->children as $i => $Child ){
if( $Child->idx === $Node->idx ){
return $this->remove_at( $i );
}
}
} | php | {
"resource": ""
} |
q5877 | ParseNode.remove_at | train | function remove_at( $i ){
$Child = $this->children[$i];
$Child->pidx = null;
$Child->depth = 0;
array_splice( $this->children, $i, 1 );
if( ! --$this->length ){
$this->p = null;
}
else {
$this->p = 0;
}
return $Child;
} | php | {
"resource": ""
} |
q5878 | ParseNode.splice | train | function splice( ParseNode $Node, array $nodes ){
foreach( $this->children as $i => $Child ){
if( $Child->idx === $Node->idx ){
return $this->splice_at( $i, $nodes, 1 );
}
}
} | php | {
"resource": ""
} |
q5879 | ParseNode.splice_at | train | function splice_at( $i, array $nodes, $len = 0){
$Child = $this->children[$i];
$Child->pidx = null;
$Child->depth = 0;
array_splice( $this->children, $i, $len, $nodes );
foreach( $nodes as $Node ){
$Node->pidx = $this->idx;
}
$this->length = count( $this->children );
$this->p = 0;
return $Child;
} | php | {
"resource": ""
} |
q5880 | ParseNode.get_parent | train | function get_parent(){
if( !is_null($this->pidx) && isset(self::$reg[$this->pidx]) ){
return self::$reg[$this->pidx];
}
else {
return null;
}
} | php | {
"resource": ""
} |
q5881 | ParseNode.export | train | function export(){
if( $this->is_terminal() ){
if( $this->t === $this->value ){
// scalar token
return $this->value;
}
// PHP Tokenizer style array
return array( $this->t, $this->value );
}
// else is a branch
$a = array();
foreach( $this->children as $Child ){
$a[] = array( $this->t, $Child->export() );
}
return $a;
} | php | {
"resource": ""
} |
q5882 | ParseNode.dump | train | function dump( Lex $Lex, $tab = '' ){
$tag = $Lex->name( $this->t );
if( $this->is_terminal() ){
if( $this->value && $this->value !== $this->t ){
echo $tab, '<',$tag,">\n ", $tab, htmlspecialchars($this->value),"\n",$tab,'</',$tag,">\n";
}
else {
echo $tab, htmlspecialchars($this->value),"\n";
}
}
else if( ! $this->length ){
echo $tab, '<', $tag, " />\n";
}
else {
echo $tab, '<',$tag,">\n";
foreach( $this->children as $Child ){
$Child->dump( $Lex, " ".$tab);
}
echo $tab, '</', $tag, ">\n";
}
} | php | {
"resource": ""
} |
q5883 | Setup.run | train | public static function run(Event $event)
{
$event->getIO()->write('<info>Now running setup tasks...</info>');
$config = static::getConfig($event);
$tasks = static::getSetupTasks($event);
foreach ($tasks as $task) {
/** @var SetupTask $taskStep */
$taskStep = new $task($config, $event);
$event->getIO()->write(
sprintf(
'<info>Task %1$s</info>',
$taskStep->getName()
)
);
$taskStep->complete();
}
$event->getIO()->write('<info>Setup tasks complete, cleaning up...</info>');
} | php | {
"resource": ""
} |
q5884 | Setup.getSetupTasks | train | protected static function getSetupTasks(Event $event)
{
return [
AskAboutProjectParameters::class,
VerifyProjectParameters::class,
RemoveExistingRootFiles::class,
ReplacePlaceholdersInTemplateFiles::class,
MoveTemplateFilesToRootFolder::class,
RemoveConfigFolder::class,
RemoveTemplatesFolder::class,
RemoveOriginalVCSData::class,
InitializeVCS::class,
// Removing the vendor folder also removes the autoloader,
// so this task needs to run last.
RemoveVendorFolder::class,
];
} | php | {
"resource": ""
} |
q5885 | Sharing.update | train | public function update(int $vehicleId, int $sharingId, ?string $description, ?string $duration = '1D'): Response
{
$this->requiresAccessToken();
return $this->sendJson(
'PATCH',
"vehicles/{$vehicleId}/sharing/{$sharingId}",
$this->getApiHeaders(),
$this->mergeApiBody(\compact('description', 'duration'))
);
} | php | {
"resource": ""
} |
q5886 | Sharing.destroy | train | public function destroy(int $vehicleId, int $sharingId): Response
{
$this->requiresAccessToken();
return $this->send(
'DELETE',
"vehicles/{$vehicleId}/sharing/{$sharingId}",
$this->getApiHeaders()
);
} | php | {
"resource": ""
} |
q5887 | modelMS.conn | train | protected function conn($db_config_name = '')
{
$db_config_name = $db_config_name ? $db_config_name : $this->db_config_name;
if (! isset(self::$_db_handle[$db_config_name])) {
if (true == C('sql_log')) {
wlog('SQL-Log', '#'.$db_config_name);
}
$dbdriver = 'db_'.C('dbdriver');
include_once FW_PATH.'/dbdrivers/'. $dbdriver .'.class.php';
self::$_db_handle[$db_config_name] = $this->db = new $dbdriver($db_config_name);
} else {
$this->db = self::$_db_handle[$db_config_name];
}
return $this->db;
} | php | {
"resource": ""
} |
q5888 | RelationshipExtension.processNoDataRelationship | train | protected function processNoDataRelationship($source, DocumentHydrator $hydrator): NoDataRelationship
{
$relationship = new NoDataRelationship();
$hydrator->hydrateObject($relationship, $source);
return $relationship;
} | php | {
"resource": ""
} |
q5889 | RelationshipExtension.processSingleIdentifierRelationship | train | protected function processSingleIdentifierRelationship($source, DocumentHydrator $hydrator): SingleIdentifierRelationship
{
$identifier = $this->createResourceIdentifier($source->data, $hydrator);
$relationship = new SingleIdentifierRelationship($identifier);
$hydrator->hydrateObject($relationship, $source);
return $relationship;
} | php | {
"resource": ""
} |
q5890 | RelationshipExtension.processIdentifierCollectionRelationship | train | protected function processIdentifierCollectionRelationship($source, DocumentHydrator $hydrator): IdentifierCollectionRelationship
{
$relationship = new IdentifierCollectionRelationship();
foreach ($source->data as $resourceSrc)
{
$relationship->addIdentifier($this->createResourceIdentifier($resourceSrc, $hydrator));
}
$hydrator->hydrateObject($relationship, $source);
return $relationship;
} | php | {
"resource": ""
} |
q5891 | GuzzleAdapter.createException | train | protected function createException(GuzzleRequestException $exception): RequestException
{
if ($exception instanceof GuzzleResponseException) {
return new ResponseException(
$exception->getRequest(),
$exception->getResponse(),
$exception
);
}
throw new RequestException(
$exception->getRequest(),
$exception
);
} | php | {
"resource": ""
} |
q5892 | MetadataContainer.setMetadataAttribute | train | public function setMetadataAttribute(string $name, $value)
{
if (array_key_exists($name, $this->metadata)) {
throw new MetadataAttributeOverrideException($this, $name);
}
$this->metadata[$name] = $value;
} | php | {
"resource": ""
} |
q5893 | MetadataContainer.getMetadataAttribute | train | public function getMetadataAttribute(string $name)
{
if (array_key_exists($name, $this->metadata)) {
return $this->metadata[$name];
}
throw new MetadataAttributeNotFoundException($this, $name);
} | php | {
"resource": ""
} |
q5894 | Webservice.setup | train | public function setup()
{
//====================================================================//
// Read Parameters
$this->id = Splash::configuration()->WsIdentifier;
$this->key = Splash::configuration()->WsEncryptionKey;
//====================================================================//
// If Another Host is Defined => Allow Overide of Server Host Address
if (!empty(Splash::configuration()->WsHost)) {
$this->host = Splash::configuration()->WsHost;
} else {
$this->host = self::SPLASHHOST;
}
//====================================================================//
// If Http Auth is Required => Setup User & Password
if (isset(Splash::configuration()->HttpAuth) && !empty(Splash::configuration()->HttpAuth)) {
$this->httpAuth = true;
}
if ($this->httpAuth && isset(Splash::configuration()->HttpUser)) {
$this->httpUser = Splash::configuration()->HttpUser;
}
if ($this->httpAuth && isset(Splash::configuration()->HttpPassword)) {
$this->httpPassword = Splash::configuration()->HttpPassword;
}
//====================================================================//
// Safety Check
if (!$this->verify()) {
return false;
}
return Splash::log()->deb('MsgWsSetParams');
} | php | {
"resource": ""
} |
q5895 | Webservice.pack | train | public function pack($data, $isUncrypted = false)
{
//====================================================================//
// Debug Log
Splash::log()->deb('MsgWsPack');
//====================================================================//
// Encode Data Buffer
//====================================================================//
if ('XML' == Splash::configuration()->WsEncode) {
//====================================================================//
// Convert Data Buffer To XML
$serial = Splash::xml()->objectToXml($data);
} else {
//====================================================================//
// Serialize Data Buffer
$serial = serialize($data);
}
//====================================================================//
// Encrypt serialized data buffer
//====================================================================//
if (!$isUncrypted) {
$out = $this->crypt('encrypt', $serial, $this->key, $this->id);
//====================================================================//
// Else, switch to base64
} else {
$out = base64_encode($serial);
}
//====================================================================//
// Debug Informations
//====================================================================//
if (defined('SPLASH_SERVER_MODE') && !empty(SPLASH_SERVER_MODE) && (Splash::configuration()->TraceOut)) {
Splash::log()->war('MsgWsFinalPack', print_r($serial, true));
}
return $out;
} | php | {
"resource": ""
} |
q5896 | Webservice.unPack | train | public function unPack($data, $isUncrypted = false)
{
//====================================================================//
// Debug Log
Splash::log()->deb('MsgWsunPack');
//====================================================================//
// Decrypt response
//====================================================================//
if (!empty($data) && !$isUncrypted) {
$decode = $this->crypt('decrypt', $data, $this->key, $this->id);
//====================================================================//
// Else, switch from base64
} else {
$decode = base64_decode($data, true);
}
//====================================================================//
// Decode Data Response
//====================================================================//
// Convert Data Buffer To XML
if ('XML' == Splash::configuration()->WsEncode) {
if ($decode && false !== strpos($decode, '<SPLASH>')) {
$out = Splash::xml()->XmlToArrayObject($decode);
}
//====================================================================//
// Unserialize Data buffer
} else {
if (!empty($decode)) {
$out = unserialize($decode);
}
}
//====================================================================//
// Trow Exception if fails
if (empty($out)) {
Splash::log()->err('ErrWsunPack');
}
//====================================================================//
// Messages Debug Informations
//====================================================================//
// // Data Decoded (PHP Serialized Objects or XML)
// if ((!SPLASH_SERVER_MODE) && (Splash::configuration()->TraceIn)) {
// Splash::log()->war("Splash unPack - Data Decode : " . print_r($Decode, true));
// }
// //====================================================================//
// // Final Decoded Data (ArrayObject Structure)
// Splash::log()->deb("Splash unPack - Data unSerialized : " . print_r($Out,true) );
//====================================================================//
// Return Result or False
return empty($out) ? false : $out;
} | php | {
"resource": ""
} |
q5897 | Webservice.call | train | public function call($service, $tasks = null, $isUncrypted = false, $clean = true)
{
//====================================================================//
// WebService Call =>> Initialisation
if (!$this->init($service)) {
return false;
}
//====================================================================//
// WebService Call =>> Add Tasks
if (!$this->addTasks($tasks)) {
return false;
}
//====================================================================//
// Prepare Raw Request Data
//====================================================================//
$this->rawOut = array(
'id' => $this->id,
'data' => $this->pack($this->outputs, $isUncrypted), );
//====================================================================//
// Prepare Webservice Client
//====================================================================//
if (false === $this->buildClient()) {
return false;
}
//====================================================================//
// Call Execution
$this->rawIn = Splash::com()->call($this->outputs->service, $this->rawOut);
//====================================================================//
// Analyze & Decode Response
//====================================================================//
if (!$this->decodeResponse($isUncrypted)) {
return false;
}
//====================================================================//
// If required, lean _Out buffer parameters before exit
if ($clean) {
$this->cleanOut();
}
return $this->inputs;
} | php | {
"resource": ""
} |
q5898 | Webservice.simulate | train | public function simulate($service, $tasks = null, $isUncrypted = false, $clean = true)
{
//====================================================================//
// WebService Call =>> Initialisation
if (!$this->init($service)) {
return false;
}
//====================================================================//
// WebService Call =>> Add Tasks
if (!$this->addTasks($tasks)) {
return false;
}
//====================================================================//
// Execute Action From Splash Server to Module
$response = SplashServer::$service(
Splash::configuration()->WsIdentifier,
$this->pack($this->outputs, $isUncrypted)
);
//====================================================================//
// If required, lean _Out buffer parameters before exit
if ($clean) {
$this->cleanOut();
}
return $response;
} | php | {
"resource": ""
} |
q5899 | Webservice.addTask | train | public function addTask($name, $params, $desc = 'No Description')
{
//====================================================================//
// Create a new task
$task = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS);
//====================================================================//
// Prepare Task Id
$taskId = $this->tasks->count() + 1;
//====================================================================//
// Fill task with informations
$task['id'] = $taskId;
$task['name'] = $name;
$task['desc'] = $desc;
$task['params'] = $params;
//====================================================================//
// Add Task to Tasks list
$this->tasks[$taskId] = $task;
//====================================================================//
// Debug
Splash::log()->deb('TasksAdd', $task['name'], $task['desc']);
return $this;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.