_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q249600
ToolbarDashboards.dashboards
validation
public function dashboards(Environment $environment, $size) { //Checks user's rights $dashboards = null; if ($this->tokenStorage->getToken()->getUser() !== null) { //Defines installed dashboards $dashboardsAvailable = array('ContactForm', 'Email', 'Events', 'ExceptionChecker', 'GiftVoucher', 'PageEdit', 'Payment', 'PurchaseCredits', 'Site', 'User'); foreach ($dashboardsAvailable as $dashboardAvailable) { //Checks if the bundle is installed if (is_dir($this->container->getParameter('kernel.root_dir') . '/../vendor/c975l/' . strtolower($dashboardAvailable) . '-bundle') && //Checks if roleNeeded for that dashboard is defined $this->configService->hasParameter('c975L' . $dashboardAvailable . '.roleNeeded') && //Checks if User has good roleNeeded for that dashboard $this->container->get('security.authorization_checker')->isGranted($this->configService->getParameter('c975L' . $dashboardAvailable . '.roleNeeded')) ) { $dashboards[] = strtolower($dashboardAvailable); } } } //Defines toolbar return $environment->render('@c975LToolbar/dashboards.html.twig', array( 'dashboards' => $dashboards, 'size' => $size, )); }
php
{ "resource": "" }
q249601
QueueCommand.startProcessQueue
validation
private function startProcessQueue() { $this->logger->info('Starting queue in process mode'); $dispatcher = new ProcessDispatcher( $this->client, $this->logger, $this->queue, \array_merge($this->queueConfig, ['process' => $this->config['process']]), [ 'configFile' => $this->configName ] ); $dispatcher->start(); }
php
{ "resource": "" }
q249602
Locale.init
validation
public static function init(RawRequest $request = null) { if (self::$isInit === false) { self::$translations = array(); $settings = Config::getSettings(); if (isset($settings['locale']) === false || isset($settings['locale']['default']) === false) { throw new BadUse('locale.default isn\'t defined in settings'); } self::$currentLanguage = $settings['locale']['default']; if ($request != null) { if (Session::has('_stray_language') === true) { self::$currentLanguage = Session::get('_stray_language'); } else { $domain = HttpHelper::extractDomain($request); if (isset($settings['locale']['hosts']) === true && isset($settings['locale']['hosts'][$domain]) === true) { self::$currentLanguage = $settings['locale']['hosts'][$domain]; } Session::set('_stray_language', self::$currentLanguage); } } self::$isInit = true; } }
php
{ "resource": "" }
q249603
Locale.registerTranslations
validation
public static function registerTranslations($baseDir, $localesDir, $prefix = null) { if (self::$isInit === true) { $dir = $baseDir . DIRECTORY_SEPARATOR . $localesDir; if (is_dir($dir) === false) { throw new InvalidDirectory('directory "' . $dir . '" can\'t be identified'); } $language = self::$currentLanguage; if (($pos = strpos($language, '-')) !== false) { $pos = (int) $pos; // re: https://github.com/phpstan/phpstan/issues/647 $language = substr($language, 0, $pos); } if (($pos = strpos($language, '_')) !== false) { $pos = (int) $pos; // re: https://github.com/phpstan/phpstan/issues/647 $language = substr($language, 0, $pos); } if (is_readable($dir . DIRECTORY_SEPARATOR . $language . '.yml') === true) { $newOnes = Config::get($dir . DIRECTORY_SEPARATOR . $language . '.yml'); if (is_array($newOnes) === true) { if ($prefix != null) { $newOnes = array($prefix => $newOnes); } self::$translations = array_merge(self::$translations, $newOnes); } } else { Logger::get()->notice('can\'t find language "' . $language . '" in directory "' . $dir . '"'); } } }
php
{ "resource": "" }
q249604
Locale.translate
validation
public static function translate($key, array $args = array()) { if (self::$isInit === false) { throw new BadUse('locale doesn\'t seem to have been initialized'); } $oldKey = $key; $section = self::$translations; while (isset($section[$key]) === false && ($pos = strpos($key, '.')) !== false) { if (! is_int($pos)) { // re: https://github.com/phpstan/phpstan/issues/647 break; } $subSection = substr($key, 0, $pos); if (isset($section[$subSection]) === false) { break; } $section = $section[$subSection]; $key = substr($key, $pos + 1); } if (isset($section[$key]) === false) { Logger::get()->error('can\'t find translation for key "' . $oldKey . '"'); return '(null)'; } return $section[$key]; }
php
{ "resource": "" }
q249605
Locale.setCurrentLanguage
validation
public static function setCurrentLanguage($language) { self::$currentLanguage = $language; Session::set('_stray_language', self::$currentLanguage); setlocale(LC_ALL, $language); }
php
{ "resource": "" }
q249606
PostTimelineSubscriber.createPostTimelineEntry
validation
public function createPostTimelineEntry(EntityPublishedEvent $event): void { // Only act on post objects. $post = $event->getObject(); if (!$post instanceof Post) { return; } // Get the author for the post. $author = $this->user_provider->loadUserByUsername($post->getAuthor()); // Create components for this action. $post_component = $this->action_manager->findOrCreateComponent($post); $author_component = $this->action_manager->findOrCreateComponent($author); // Add timeline entries for each group. foreach ($post->getGroups() as $group) { // Create the group component. $group_component = $this->action_manager->findOrCreateComponent($group); // Either a new post was created or a reply was created. if (null === $post->getParent()) { $verb = 'post'; } else { $verb = 'reply'; } // Create the action and link it. $action = $this->action_manager->create($author_component, $verb, [ 'directComplement' => $post_component, 'indirectComplement' => $group_component, ]); // Update the action. $this->action_manager->updateAction($action); } }
php
{ "resource": "" }
q249607
Mapping.registerMapping
validation
public static function registerMapping(array $config) { self::validateConfig($config); if (isset(self::$mappings[$config['name']]) === false) { self::$mappings[$config['name']] = array( 'config' => $config ); Database::registerDatabase($config['database']); } else { Logger::get()->warning('mapping with name "' . $config['name'] . '" was already set'); } }
php
{ "resource": "" }
q249608
Mapping.get
validation
public static function get(string $name) : array { if (isset(self::$mappings[$name]) === false) { throw new MappingNotFound('there\'s no registered mapping with name "' . $name . '"'); } return self::$mappings[$name]; }
php
{ "resource": "" }
q249609
Mapping.validateConfig
validation
private static function validateConfig(array $config) { if (isset($config['name']) === false) { throw new BadUse('there\'s no name in mapping configuration'); } if (isset($config['schema']) === false) { throw new BadUse('there\'s no schema in mapping configuration'); } if (isset($config['provider']) === false) { throw new BadUse('there\'s no provider in mapping configuration'); } if (isset($config['models']) === false) { throw new BadUse('there\'s no models in mapping configuration'); } if (isset($config['models']['path']) === false) { throw new BadUse('there\'s no models.path in mapping configuration'); } if (isset($config['models']['namespace']) === false) { throw new BadUse('there\'s no models.namespace in mapping configuration'); } }
php
{ "resource": "" }
q249610
BoardController.archiveAction
validation
public function archiveAction( string $production_slug, AuthorizationCheckerInterface $auth, PaginatorInterface $paginator, Request $request ): Response { // Lookup the production by production_slug. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Check permissions for this action. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Get notice board posts. $query = $this->em->getRepository(Post::class)->getAllInactiveQuery($production); // Return response. $posts = $paginator->paginate($query, $request->query->getInt('page', 1)); return new Response($this->templating->render('@BkstgNoticeBoard/Board/archive.html.twig', [ 'production' => $production, 'posts' => $posts, ])); }
php
{ "resource": "" }
q249611
BatchEmailJob.perform
validation
public function perform(array $args = []): int { // Store our args $this->args = $args; unset($this->args['messages']); // Create a new transport $transport = new Swift_SmtpTransport( $args['smtp']['host'], $args['smtp']['port'] ); $transport->setUsername($args['smtp']['username']); $transport->setPassword($args['smtp']['password']); // Make a copy of all of our messages, and interate over each message $this->messages = $args['messages']; foreach ($messages as &$message) { // If shutdown is called, abort what we are doing. if ($shutdown) { break; } // Create a message $mailer = new Swift_Mailer($transport); $m = (new Swift_Message($message['subject'])) ->setFrom([$message['from']['email'] => $message['from']['email']]) ->setTo([$message['to']['email'] => $message['to']['name']]) ->setBody($message['message']); // Send the message, and indicate if it was sent $message['sent'] = ($mailer->send($m) === 1); } return 0; }
php
{ "resource": "" }
q249612
BatchEmailJob.shutdown
validation
protected function shutdown() { // Indicate to our main loop that we should stop processing additonal messages $this->shutdown = true; // Get a list of all the messages that have not yet been handled $this->args['messages'] = array_filter($this->messages, function($message) { if (!isset($message['sent']) || $message['sent'] === false) { return $message; } }); $redis = new Redis; $client = new Client($redis); // Push the unfinished jobs back onto the priority queue with a priority of 100 // So they get processed as soon as possible. $client->push(static::class, $this->args, 1, 100); // Indicate that we've handled SIGTERM, and are ready to shut down return true; }
php
{ "resource": "" }
q249613
Controller.help
validation
public function help(Request $request) { $routes = Console::getRoutes(); echo 'strayFw console help screen' . PHP_EOL . 'Available actions :' . PHP_EOL . PHP_EOL; $namespace = null; foreach ($routes as $route) { if ($namespace != $route['namespace']) { $namespace = $route['namespace']; echo $namespace . PHP_EOL . PHP_EOL; } echo ' ' . $route['usage'] . PHP_EOL; if (isset($route['help']) != null) { echo ' ' . $route['help']; } echo PHP_EOL . PHP_EOL; } }
php
{ "resource": "" }
q249614
ProcessWorkerCommand.configure
validation
protected function configure() { $this->setName('worker/process') ->setHidden(true) ->setDescription('Runs a given worker') ->setDefinition(new InputDefinition([ new InputOption('config', 'c', InputOption::VALUE_REQUIRED, 'A YAML configuration file'), new InputOption('jobId', null, InputOption::VALUE_REQUIRED, 'A Job UUID'), new InputOption('name', null, InputOption::VALUE_REQUIRED, 'The queue name to work with. Defaults to `default`.'), ])); }
php
{ "resource": "" }
q249615
Update.set
validation
public function set($set) { if (is_array($set) === true) { $this->set = ''; foreach ($set as $name => $value) { $pos = stripos($name, '.'); if ($pos !== false) { $this->set .= substr($name, $pos + 1); } else { $this->set .= $name; } $this->set .= ' = ' . $value . ', '; } $this->set = substr($this->set, 0, -2); } else { $this->set = $set; } return $this; }
php
{ "resource": "" }
q249616
Update.where
validation
public function where($where) { $this->where = ($where instanceof Condition ? $where : new Condition($where)); return $this; }
php
{ "resource": "" }
q249617
Update.orderBy
validation
public function orderBy($orderBy) { if (is_array($orderBy) === true) { $this->orderBy = ''; foreach ($orderBy as $key => $elem) { $this->orderBy .= $key . ' ' . $elem . ', '; } $this->orderBy = substr($this->orderBy, 0, -2); } else { $this->orderBy = $orderBy; } return $this; }
php
{ "resource": "" }
q249618
Session.init
validation
public static function init() { if (self::$isInit === false) { if (session_id() == null) { $settings = Config::getSettings(); session_name(isset($settings['session_name']) === true ? $settings['session_name'] : 'stray_session'); if (isset($settings['session_cookie_domain']) === true) { session_set_cookie_params(0, '/', $settings['session_cookie_domain']); } session_start(); } self::$isInit = true; } }
php
{ "resource": "" }
q249619
ArrayContainer.setAction
validation
public function setAction(AbstractAction $action) { $this->action = $action; $this->action->setArrayContainer($this); return $this; }
php
{ "resource": "" }
q249620
ArrayContainer.getNested
validation
public function getNested($keyString, $default = null, $separator = '.') { $keys = explode($separator, $keyString); $data = $this->array; foreach ($keys as $key) { if(!is_array($data) or !array_key_exists($key, $data)) { return $default; } $data = $data[$key]; } return $data; }
php
{ "resource": "" }
q249621
ArrayContainer.applyFilters
validation
protected function applyFilters($value, $key) { foreach ($this->filters as $filter) { $value = $filter($value, $key); } return $value; }
php
{ "resource": "" }
q249622
Select.execute
validation
public function execute() { if ($this->statement == null) { $this->statement = Database::get($this->database)->{($this->isCritical === true ? 'getMasterLink' : 'getLink')}()->prepare($this->toSql()); } foreach ($this->parameters as $name => $value) { $type = \PDO::PARAM_STR; if (is_int($value) === true) { $type = \PDO::PARAM_INT; } elseif (is_bool($value) === true) { $type = \PDO::PARAM_BOOL; } elseif (is_null($value) === true) { $type = \PDO::PARAM_NULL; } $this->statement->bindValue($name, $value, $type); } $result = $this->statement->execute(); $this->errorInfo = $this->statement->errorInfo(); if ($this->getErrorState() != '00000') { Logger::get()->error('select query failed : ' . $this->getErrorMessage() . ' (' . $this->toSql() . ')'); if (constant('STRAY_ENV') === 'development') { throw new AppException('select query failed : ' . $this->getErrorMessage() . ' (' . $this->toSql() . ')'); } } return $result; }
php
{ "resource": "" }
q249623
Select.fetch
validation
public function fetch() { if ($this->statement == null || $this->getErrorState() != '00000') { return false; } return $this->statement->fetch(\PDO::FETCH_ASSOC); }
php
{ "resource": "" }
q249624
Select.fetchAll
validation
public function fetchAll() { if ($this->statement == null || $this->getErrorState() != '00000') { return false; } return $this->statement->fetchAll(\PDO::FETCH_ASSOC); }
php
{ "resource": "" }
q249625
Select.select
validation
public function select($select) { if (is_array($select) === true) { $this->select = ''; foreach ($select as $key => $elem) { $this->select .= $elem; if (is_numeric($key) === false) { $this->select .= ' AS ' . $key; } $this->select .= ', '; } $this->select = substr($this->select, 0, -2); } elseif (! is_string($select)) { throw new InvalidArgumentException(sprintf( 'Argument 1 passed to %s must be an array or string!', __METHOD__ )); } else { $this->select = $select; } return $this; }
php
{ "resource": "" }
q249626
Select.groupBy
validation
public function groupBy($groupBy) { if (is_array($groupBy) === true) { $this->groupBy = implode(', ', $groupBy); } else { $this->groupBy = $groupBy; } return $this; }
php
{ "resource": "" }
q249627
Select.having
validation
public function having($having) { $this->having = ($having instanceof Condition ? $having : new Condition($having)); return $this; }
php
{ "resource": "" }
q249628
Select.distinct
validation
public function distinct($distinct) { if (is_array($distinct) === true) { $this->distinct = implode(', ', $distinct); } else { $this->distinct = $distinct; } return $this; }
php
{ "resource": "" }
q249629
Select.addInnerJoin
validation
public function addInnerJoin($table, $on) { $this->innerJoins[] = array( 'table' => $table, 'on' => ($on instanceof Condition ? $on : new Condition($on)) ); return $this; }
php
{ "resource": "" }
q249630
Select.addLeftOuterJoin
validation
public function addLeftOuterJoin($table, $on) { $this->leftOuterJoins[] = array( 'table' => $table, 'on' => ($on instanceof Condition ? $on : new Condition($on)) ); return $this; }
php
{ "resource": "" }
q249631
Select.addRightOuterJoin
validation
public function addRightOuterJoin($table, $on) { $this->rightOuterJoins[] = array( 'table' => $table, 'on' => ($on instanceof Condition ? $on : new Condition($on)) ); return $this; }
php
{ "resource": "" }
q249632
Select.addFullOuterJoin
validation
public function addFullOuterJoin($table, $on) { $this->fullOuterJoins[] = array( 'table' => $table, 'on' => ($on instanceof Condition ? $on : new Condition($on)) ); return $this; }
php
{ "resource": "" }
q249633
Console.routes
validation
public function routes(Request $request) { $table = new \cli\Table(); $table->setHeaders([ 'Type', 'Subdomain', 'Method', 'Path', 'Action' ]); $rows = []; $routes = Http::getRoutes(); usort($routes, function (array $a, array $b) { if ($a['subdomain'] != $b['subdomain']) { return strcmp($a['subdomain'], $b['subdomain']); } if ($a['path'] != $a['path']) { return strcmp($a['path'], $b['path']); } return strcmp($a['method'], $b['method']); }); foreach ($routes as $route) { $rows[] = [ $route['type'], $route['subdomain'], $route['method'], empty($route['uri']) === false ? '/' . ltrim(rtrim($route['uri'], '/'), '/') . $route['path'] : $route['path'], $route['action'][0] == '\\' ? $route['action'] : rtrim($route['namespace'], '\\') . '\\' . $route['action'], ]; } $table->setRows($rows); $table->display(); }
php
{ "resource": "" }
q249634
Console.run
validation
public static function run() { if (self::$isInit === true) { self::$request = new Request(self::$routes); self::$controllers = array(); try { $before = self::$request->getBefore(); foreach ($before as $b) { $controller = Controllers::get($b['class']); $action = $b['action']; $controller->$action(self::$request); } if (self::$request->hasEnded() === false) { $controller = Controllers::get(self::$request->getClass()); $action = self::$request->getAction(); $controller->$action(self::$request); if (self::$request->hasEnded() === false) { $after = self::$request->getAfter(); foreach ($after as $a) { $controller = Controllers::get($a['class']); $action = $a['action']; $controller->$action(self::$request); } } } } catch (\Exception $e) { echo 'Exception: ' . $e->getMessage() . PHP_EOL; echo $e->getTraceAsString(); } } }
php
{ "resource": "" }
q249635
Console.before
validation
public static function before(string $path, string $usage, string $help, string $action) { if (self::$isInit === true) { self::$routes[] = array( 'type' => 'before', 'path' => $path, 'usage' => $usage, 'help' => $help, 'action' => $action, 'namespace' => self::$namespace ); } }
php
{ "resource": "" }
q249636
Logger.get
validation
public static function get() : Logger { if (self::$log == null) { self::$log = new Logger(); } return self::$log; }
php
{ "resource": "" }
q249637
Migration.ensureTable
validation
public static function ensureTable(array $mapping) : bool { $database = Database::get($mapping['config']['database']); $statement = 'CREATE TABLE IF NOT EXISTS _stray_migration ('; $statement .= 'date TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, '; $statement .= 'migration VARCHAR(255)'; $statement .= ')'; $statement = $database->getMasterLink()->prepare($statement); if ($statement->execute() === false) { echo 'Can\'t create _stray_migration (' . $statement->errorInfo()[2] . ')' . PHP_EOL; return false; } $select = new Select($mapping['config']['database'], true); $select->select('COUNT(*) as count') ->from('_stray_migration'); if ($select->execute() === false) { echo 'Can\'t fetch from _stray_migration (' . $select->getErrorMessage() . ')' . PHP_EOL; return false; } if ($select->fetch()['count'] == 0) { $insert = new Insert($mapping['config']['database']); $insert->into('_stray_migration'); if ($insert->execute() === false) { echo 'Can\'t insert into _stray_migration (' . $insert->getErrorMessage() . ')' . PHP_EOL; return false; } } return true; }
php
{ "resource": "" }
q249638
Schema.getDefinition
validation
public function getDefinition() : array { if ($this->definition == null) { $data = Mapping::get($this->mapping); $this->definition = Config::get($data['config']['schema']); } return $this->definition; }
php
{ "resource": "" }
q249639
Schema.getSchema
validation
public static function getSchema(string $mapping) : Schema { $data = Mapping::get($mapping); $class = rtrim(ucfirst($data['config']['provider']), '\\') . '\\Schema'; return new $class($mapping); }
php
{ "resource": "" }
q249640
ToolbarDisplay.display
validation
public function display(Environment $environment, $template, $type = null, $size = 'md', $object = null) { //Defines tools $tools = $environment->render($template, array( 'type' => $type, 'object' => $object, )); //Defines toolbar return $environment->render('@c975LToolbar/toolbar.html.twig', array( 'tools' => $tools, 'size' => $size, )); }
php
{ "resource": "" }
q249641
ToolbarButtonText.button
validation
public function button(Environment $environment, $link, $button, $size = 'md', $iconDisplay = 'true', $location = 'right', $label = null, $userStyle = null) { //Defines $icon and $style extract($this->toolbarService->defineButton($button)); //Defines button return $environment->render('@c975LToolbar/buttonText.html.twig', array( 'link' => $link, 'style' => $style, 'size' => $size, 'button' => $button, 'icon' => $icon, 'label' => $label, 'iconDisplay' => $iconDisplay, 'location' => $location, )); }
php
{ "resource": "" }
q249642
Response.render
validation
public function render(RenderInterface $render, $status = 200) { $this->renderInst = $render; $this->status = $status; }
php
{ "resource": "" }
q249643
Bootstrap.init
validation
public static function init() { if (self::$isInit === false) { self::$namespaces = array(); self::$applications = array(); spl_autoload_register(__CLASS__ . '::loadClass'); self::$isInit = true; Console::init(); Console::prefix('\\RocknRoot\\StrayFw\\Console'); Console::route('help', 'help', 'this screen', 'Controller.help'); Console::prefix('\\RocknRoot\\StrayFw\\Database'); Console::route('db/list', 'db/list', 'list registered mappings', 'Console.mappings'); Console::route('db/build', 'db/build mapping_name', 'build data structures', 'Console.build'); Console::route('db/generate', 'db/generate mapping_name', 'generate base models', 'Console.generate'); Console::route('db/migration/create', 'db/migration/create mapping_name migration_name', 'create a new migration', 'Migration.create'); Console::route('db/migration/generate', 'db/migration/generate mapping_name migration_name', 'generate migration code', 'Migration.generate'); Console::route('db/migration/migrate', 'db/migration/migrate mapping_name', 'migrate', 'Migration.migrate'); Console::route('db/migration/rollback', 'db/migration/rollback mapping_name', 'rollback last migration', 'Migration.rollback'); Console::prefix('\\RocknRoot\\StrayFw\\Http'); Console::route('http/routing/list', 'http/routing/list', 'list registered routes', 'Console.routes'); Http::init(); if (defined('STRAY_IS_HTTP') === true && constant('STRAY_IS_HTTP') === true && constant('STRAY_ENV') === 'development') { Debug\ErrorPage::init(); } } }
php
{ "resource": "" }
q249644
Bootstrap.loadClass
validation
public static function loadClass(string $className) { if (self::$isInit === false) { throw new BadUse('bootstrap doesn\'t seem to have been initialized'); } $fileName = null; if (($namespacePos = strripos($className, '\\')) !== false) { $namespacePos = (int) $namespacePos; // re: https://github.com/phpstan/phpstan/issues/647 $namespace = substr($className, 0, $namespacePos); $subNamespaces = array(); while ($fileName === null && $namespace != null) { if (isset(self::$namespaces[$namespace]) === false) { $subNamespacePos = strripos($namespace, '\\'); $subNamespacePos = (int) $subNamespacePos; // re: https://github.com/phpstan/phpstan/issues/647 $subNamespaces[] = substr($namespace, $subNamespacePos); $namespace = substr($namespace, 0, $subNamespacePos); } else { $fileName = self::$namespaces[$namespace]; } } if ($fileName === null) { throw new UnknownNamespace('can\'t find namespace "' . substr($className, 0, $namespacePos) . '"'); } $fileName = self::$namespaces[$namespace] . str_replace('\\', DIRECTORY_SEPARATOR, implode('', array_reverse($subNamespaces))); $className = substr($className, $namespacePos + 1); } if ($fileName != null) { $fileName .= DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; require $fileName; } }
php
{ "resource": "" }
q249645
Bootstrap.registerApp
validation
public static function registerApp(string $namespace, string $path = null) { $namespace = rtrim($namespace, '\\'); if ($path == null) { $path = constant('STRAY_PATH_APPS') . str_replace( '_', DIRECTORY_SEPARATOR, str_replace('\\', DIRECTORY_SEPARATOR, $namespace) ); } self::$namespaces[$namespace] = $path; self::$applications[] = $namespace; }
php
{ "resource": "" }
q249646
Bootstrap.run
validation
public static function run() { if (self::$isInit === false) { throw new BadUse('bootstrap doesn\'t seem to have been initialized'); } foreach (self::$namespaces as $name => $path) { if (is_readable($path . DIRECTORY_SEPARATOR . 'init.php') === true) { require $path . DIRECTORY_SEPARATOR . 'init.php'; } elseif (stripos($path, 'vendor') === false || stripos($path, 'vendor') == strlen($path) - strlen('vendor')) { Logger::get()->error('namespace "' . $name . '" doesn\'t have an init.php'); } } if (defined('STRAY_IS_CLI') === true && constant('STRAY_IS_CLI') === true) { Console::run(); } elseif (defined('STRAY_IS_HTTP') === true && constant('STRAY_IS_HTTP') === true) { if (count(self::$applications) == 0) { throw new BadUse('no application has been registered'); } Http::run(); } else { throw new BadUse('unknown mode, not CLI_IS_CLI nor STRAY_IS_HTTP'); } }
php
{ "resource": "" }
q249647
IconChooser.getModelName
validation
private function getModelName() { // Provided name will override if( isset( $this->class ) ) { return $this->class; } // Return class name if model is given if( isset( $this->model ) ) { $rClass = new \ReflectionClass( $this->model ); return $rClass->getShortName(); } return 'Icon'; }
php
{ "resource": "" }
q249648
IconChooser.getIcon
validation
private function getIcon() { // Provided name will override if( isset( $this->model ) ) { $icon = $this->attribute; if( isset( $this->model->$icon ) ) { return $this->model->$icon; } } if( isset( $this->icon ) ) { return $this->icon; } return $this->default; }
php
{ "resource": "" }
q249649
Cookie.set
validation
public static function set($name, $value, $expire = 0, $path = null) { if ($path === null) { setcookie($name, $value, $expire); } else { setcookie($name, $value, $expire, $path); } }
php
{ "resource": "" }
q249650
Cookie.clear
validation
public static function clear() { $keys = array_keys($_COOKIE); foreach ($keys as $key) { setcookie($key, '', time() - 1); } }
php
{ "resource": "" }
q249651
Database.connect
validation
public function connect() { if ($this->isConnected() === false) { try { if (isset($this->servers['all']) === true) { $dsn = $this->providerDatabase->getDsn($this->servers['all']); $this->servers['all']['link'] = new \PDO($dsn, $this->servers['all']['user'], $this->servers['all']['pass']); } else { $dsn = $this->providerDatabase->getDsn($this->servers['read']); $this->servers['read']['link'] = new \PDO($dsn, $this->servers['read']['user'], $this->servers['read']['pass']); $dsn = $this->providerDatabase->getDsn($this->servers['write']); $this->servers['write']['link'] = new \PDO($dsn, $this->servers['write']['user'], $this->servers['write']['pass']); } } catch (\PDOException $e) { throw new ExternalLink('can\'t connect to database (' . $e->getMessage() . ')'); } } }
php
{ "resource": "" }
q249652
Database.disconnect
validation
public function disconnect() { if (isset($this->servers['all']) === true) { unset($this->servers['all']['link']); } else { unset($this->servers['read']['link']); unset($this->servers['write']['link']); } }
php
{ "resource": "" }
q249653
Database.isConnected
validation
public function isConnected() : bool { if (isset($this->servers['all']) === true) { return isset($this->servers['all']['link']); } return isset($this->servers['read']['link']) && isset($this->servers['write']['link']); }
php
{ "resource": "" }
q249654
Database.getLink
validation
public function getLink() { if ($this->isConnected() === false) { $this->connect(); } if (isset($this->servers['all']) === true) { return $this->servers['all']['link']; } if ($this->transactionLevel >= 1) { return $this->servers['write']['link']; } return $this->servers['read']['link']; }
php
{ "resource": "" }
q249655
Database.getMasterLink
validation
public function getMasterLink() { if ($this->isConnected() === false) { $this->connect(); } if (isset($this->servers['all']) === true) { return $this->servers['all']['link']; } return $this->servers['write']['link']; }
php
{ "resource": "" }
q249656
Database.beginTransaction
validation
public function beginTransaction() : bool { if ($this->isConnected() === false) { $this->connect(); } ++$this->transactionLevel; if ($this->transactionLevel == 1) { return $this->providerDatabase->beginTransaction($this->GetMasterLink()); } return $this->providerDatabase->savePoint($this->GetMasterLink(), 'LEVEL' . ($this->transactionLevel - 1)); }
php
{ "resource": "" }
q249657
Database.commit
validation
public function commit() : bool { if ($this->isConnected() === false) { $this->connect(); } if ($this->transactionLevel > 0) { --$this->transactionLevel; if ($this->transactionLevel == 0) { return $this->providerDatabase->commit($this->GetMasterLink()); } return $this->providerDatabase->releaseSavePoint($this->GetMasterLink(), 'LEVEL' . $this->transactionLevel); } return false; }
php
{ "resource": "" }
q249658
Database.rollBack
validation
public function rollBack() : bool { if ($this->isConnected() === false) { $this->connect(); } if ($this->transactionLevel > 0) { --$this->transactionLevel; if ($this->transactionLevel == 0) { return $this->providerDatabase->rollBack($this->GetMasterLink()); } return $this->providerDatabase->rollBackSavePoint($this->GetMasterLink(), 'LEVEL' . $this->transactionLevel); } return false; }
php
{ "resource": "" }
q249659
Database.registerDatabase
validation
public static function registerDatabase(string $alias) { if (isset(self::$databases[$alias]) === false) { self::$databases[$alias] = new static($alias); } }
php
{ "resource": "" }
q249660
Database.get
validation
public static function get(string $alias) { if (isset(self::$databases[$alias]) === false) { throw new DatabaseNotFound('database "' . $alias . '" doesn\'t seem to be registered'); } return self::$databases[$alias]; }
php
{ "resource": "" }
q249661
TextureChooser.renderWidget
validation
public function renderWidget( $config = [] ) { $widgetHtml = $this->render( $this->template, [ 'name' => $this->getModelName(), 'attribute' => $this->attribute, 'label' => $this->label, 'texture' => $this->getTexture(), 'disabled' => $this->disabled ]); if( $this->wrap ) { return Html::tag( $this->wrapper, $widgetHtml, $this->options ); } return $widgetHtml; }
php
{ "resource": "" }
q249662
TextureChooser.getTexture
validation
private function getTexture() { // Provided name will override if( isset( $this->model ) ) { $texture = $this->attribute; if( isset( $this->model->$texture ) ) { return $this->model->$texture; } } if( isset( $this->texture ) ) { return $this->texture; } return $this->default; }
php
{ "resource": "" }
q249663
ProductionMenuSubscriber.addNoticeBoardItem
validation
public function addNoticeBoardItem(ProductionMenuCollectionEvent $event): void { $menu = $event->getMenu(); $group = $event->getGroup(); // Create notice_board menu item. $board = $this->factory->createItem('menu_item.notice_board', [ 'route' => 'bkstg_board_show', 'routeParameters' => ['production_slug' => $group->getSlug()], 'extras' => [ 'icon' => 'comment', 'translation_domain' => BkstgNoticeBoardBundle::TRANSLATION_DOMAIN, ], ]); $menu->addChild($board); // If this user is an editor create the post and archive items. if ($this->auth->isGranted('GROUP_ROLE_EDITOR', $group)) { $posts = $this->factory->createItem('menu_item.notice_board_posts', [ 'route' => 'bkstg_board_show', 'routeParameters' => ['production_slug' => $group->getSlug()], 'extras' => ['translation_domain' => BkstgNoticeBoardBundle::TRANSLATION_DOMAIN], ]); $board->addChild($posts); $archive = $this->factory->createItem('menu_item.notice_board_archive', [ 'route' => 'bkstg_board_archive', 'routeParameters' => ['production_slug' => $group->getSlug()], 'extras' => ['translation_domain' => BkstgNoticeBoardBundle::TRANSLATION_DOMAIN], ]); $board->addChild($archive); } }
php
{ "resource": "" }
q249664
Console.mappings
validation
public function mappings(Request $request) { $table = new \cli\Table(); $table->setHeaders([ 'Mapping', 'Database', 'Models path' ]); $rows = []; $mappings = Mapping::getMappings(); usort($mappings, function (array $a, array $b) { return strcmp($a['config']['name'], $b['config']['name']); }); foreach ($mappings as $mapping) { $rows[] = [ $mapping['config']['name'], $mapping['config']['database'], $mapping['config']['models']['path'], ]; } $table->setRows($rows); $table->display(); }
php
{ "resource": "" }
q249665
Console.generate
validation
public function generate(Request $request) { if (count($request->getArgs()) != 1) { echo 'Wrong arguments.' . PHP_EOL . 'Usage : db/generate mapping_name' . PHP_EOL; } else { $mapping = $request->getArgs()[0]; $schema = Schema::getSchema($mapping); $schema->generateModels(); } }
php
{ "resource": "" }
q249666
PostRepository.getAllActiveQuery
validation
public function getAllActiveQuery(Production $production): Query { $qb = $this->createQueryBuilder('p'); return $qb ->join('p.groups', 'g') // Add conditions. ->andWhere($qb->expr()->eq('g', ':group')) ->andWhere($qb->expr()->eq('p.active', ':active')) ->andWhere($qb->expr()->isNull('p.parent')) ->andWhere($qb->expr()->orX( $qb->expr()->isNull('p.expiry'), $qb->expr()->gt('p.expiry', ':now') )) // Add parameters. ->setParameter('group', $production) ->setParameter('active', true) ->setParameter('now', new \DateTime()) // Order by and get results. ->orderBy('p.pinned', 'DESC') ->addOrderBy('p.created', 'DESC') ->getQuery(); }
php
{ "resource": "" }
q249667
PostRepository.getAllInactiveQuery
validation
public function getAllInactiveQuery(Production $production): Query { $qb = $this->createQueryBuilder('p'); return $qb ->join('p.groups', 'g') // Add conditions. ->andWhere($qb->expr()->eq('g', ':group')) ->andWhere($qb->expr()->isNull('p.parent')) ->andWhere($qb->expr()->orX( $qb->expr()->eq('p.active', ':active'), $qb->expr()->lt('p.expiry', ':now') )) // Add parameters. ->setParameter('group', $production) ->setParameter('active', false) ->setParameter('now', new \DateTime()) // Order by and get results. ->addOrderBy('p.updated', 'DESC') ->getQuery(); }
php
{ "resource": "" }
q249668
Controllers.get
validation
public static function get(string $class) { if (isset(self::$controllers[$class]) === false) { self::$controllers[$class] = new $class(); } return self::$controllers[$class]; }
php
{ "resource": "" }
q249669
IconManager.getFileIcon
validation
public function getFileIcon( $fileType, $iconLib = 'cmti' ) { switch( $iconLib ) { case 'cmti': { return $this->getCmtiFileIcon( $fileType ); } case 'fa': { return $this->getFaFileIcon( $fileType ); } } }
php
{ "resource": "" }
q249670
IconManager.getCmtiFileIcon
validation
protected function getCmtiFileIcon( $fileType ) { switch( $fileType ) { case FileManager::FILE_TYPE_IMAGE: { return 'cmti-image'; } case FileManager::FILE_TYPE_VIDEO: { return 'cmti-file-video'; } case FileManager::FILE_TYPE_AUDIO: { return 'cmti-file-audio'; } case FileManager::FILE_TYPE_DOCUMENT: { return 'cmti-document'; } case FileManager::FILE_TYPE_COMPRESSED: { return 'cmti-file-zip'; } } }
php
{ "resource": "" }
q249671
IconManager.getFaFileIcon
validation
protected function getFaFileIcon( $fileType ) { switch( $fileType ) { case FileManager::FILE_TYPE_IMAGE: { return 'fa-file-image'; } case FileManager::FILE_TYPE_VIDEO: { return 'fa-file-video'; } case FileManager::FILE_TYPE_AUDIO: { return 'fa-file-audio'; } case FileManager::FILE_TYPE_DOCUMENT: { return 'fa-file'; } case FileManager::FILE_TYPE_COMPRESSED: { return 'fa-file-archive'; } } }
php
{ "resource": "" }
q249672
Dispatcher.start
validation
public function start() { Loop::run(function () { $this->logger->info(sprintf("RPQ is now started, and is listening for new jobs every %d ms", $this->config['poll_interval']), [ 'queue' => $this->queue->getName() ]); $this->setIsRunning(false); Loop::repeat($this->config['poll_interval'], function ($watcherId, $callback) { if (!$this->isRunning) { return; } // Pushes scheduled jobs onto the main queue $this->queue->rescheduleJobs(); // Only allow `max_jobs` to run if (count($this->processes) === $this->config['max_jobs']) { return; } // ZPOP a job from the priority queue $job = $this->queue->pop(); if ($job !== null) { // Spawn a new worker process to handle the job $command = sprintf( 'exec %s %s --jobId=%s --name=%s', ($this->config['process']['script'] ?? $_SERVER["SCRIPT_FILENAME"]), $this->config['process']['command'], $job->getId(), $this->queue->getName() ); if ($this->config['process']['config'] === true) { $command .= " --config={$this->args['configFile']}"; } $process = new Process($command); $process->start(); // Grab the PID and push it onto the process stack $pid = yield $process->getPid(); $this->logger->info('Started worker', [ 'pid' => $pid, 'command' => $command, 'id' => $job->getId(), 'queue' => $this->queue->getName() ]); $this->processes[$pid] = [ 'process' => $process, 'id' => $job->getId() ]; // Stream any output from the worker in realtime $stream = $process->getStdout(); while ($chunk = yield $stream->read()) { $this->logger->info($chunk, [ 'pid' => $pid, 'jobId' => $job->getId(), 'queue' => $this->queue->getName() ]); } // When the job is done, it will emit an exit status code $code = yield $process->join(); $this->jobHandler->exit( $job->getId(), $pid, $code, false, $this->config['failed_job_backoff_time'] ); unset($this->processes[$pid]); } }); $this->registerSignals(); }); }
php
{ "resource": "" }
q249673
Database.getDsn
validation
public function getDsn(array $info) : string { $dsn = 'pgsql:host='; $dsn .= (isset($info['host']) === true ? $info['host'] : 'localhost') . ';'; if (isset($info['port']) === true) { $dsn .= 'port=' . $info['port'] . ';'; } $dsn .= 'dbname=' . $info['name'] . ';'; return $dsn; }
php
{ "resource": "" }
q249674
Migration.migrate
validation
public function migrate(Request $req) { if (count($req->getArgs()) != 1) { echo 'Wrong arguments.' . PHP_EOL . 'Usage : db/migration/migrate mapping_name' . PHP_EOL; } else { $mappingName = $req->getArgs()[0]; $mapping = Mapping::get($mappingName); $cl = '\\' . ltrim(rtrim($mapping['config']['provider'], '\\'), '\\') . '\\Migration::migrate'; if (is_callable($cl) === false) { throw new RuntimeException( 'Migration migrate method is not callable on configured provider!' ); } call_user_func($cl, $mapping); echo 'Migrate - Done' . PHP_EOL; } }
php
{ "resource": "" }
q249675
Migration.write
validation
private function write(array $mapping, string $mappingName, string $name, array $up = [], array $down = [], array $import = []) { $path = rtrim($mapping['config']['migrations']['path'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $path .= $name . DIRECTORY_SEPARATOR; if (file_exists($path . $name . '.php') === true) { echo 'A migration with this name already exists. Do you want to overwrite it ? [y/n] : '; if (fgetc(STDIN) != 'y') { return false; } } if (is_dir($path) === false) { if (mkdir($path) === false) { throw new FileNotWritable('can\'t mkdir "' . $path . '"'); } } $path .= $name . '.php'; $file = fopen($path, 'w+'); if ($file === false) { throw new FileNotWritable('can\'t open "' . $path . '" with write permission'); } $content = "<?php\n\nnamespace " . ltrim(rtrim($mapping['config']['migrations']['namespace'], '\\'), '\\') . '\\' . $name . ";\n\nuse " . ltrim(rtrim($mapping['config']['provider'], '\\'), '\\') . '\\Migration;' . PHP_EOL; if (count($import) >= 1) { $content .= 'use ' . ltrim(rtrim($mapping['config']['provider'], '\\'), '\\') . '\\Mutation\\{'; $content .= implode(', ', $import) . "};\n"; } $up = implode('', array_map(function (string $a) { return ' ' . $a . '->execute();' . PHP_EOL; }, $up)); $down = implode('', array_map(function (string $a) { return ' ' . $a . '->execute();' . PHP_EOL; }, $down)); var_dump($up); $content .= "\nclass " . $name . " extends Migration\n{\n"; $content .= ' const NAME = \'' . $name . "';\n\n"; $content .= " public function getMappingName() : string\n {\n return '" . $mappingName . "';\n }\n\n"; $content .= " public function up()\n {\n" . $up . " }\n\n"; $content .= " public function down()\n {\n" . $down . " }\n"; $content .= "}"; if (fwrite($file, $content) === false) { throw new FileNotWritable('can\'t write in "' . $path . '"'); } fclose($file); return true; }
php
{ "resource": "" }
q249676
Model.delete
validation
public function delete() : bool { $status = false; if ($this->new === false) { $deleteQuery = new Delete($this->getDatabaseName()); $deleteQuery->from($this->getTableName()); $where = array(); foreach ($this->getPrimary() as $primary) { $field = $this->{'field' . ucfirst($primary)}; $realName = constant(get_called_class() . '::FIELD_' . strtoupper(Helper::codifyName($primary))); $where[$realName] = ':primary' . ucfirst($primary); $deleteQuery->bind('primary' . ucfirst($primary), $field['value']); } $deleteQuery->where($where); $status = $deleteQuery->execute(); } return $status; }
php
{ "resource": "" }
q249677
Model.fetchArray
validation
public static function fetchArray(array $conditions, array $orderBy = null, bool $critical = false) { $entity = new static(); $selectQuery = new Select($entity->getDatabaseName(), $critical); $selectQuery->select($entity->getAllFieldsRealNames()); $selectQuery->from($entity->getTableName()); if (count($conditions) > 0) { $where = array(); foreach ($conditions as $key => $value) { $realName = constant(get_called_class() . '::FIELD_' . strtoupper(Helper::codifyName($key))); $where[$realName] = ':where' . ucfirst($key); $selectQuery->bind('where' . ucfirst($key), $value); } $selectQuery->where($where); } if (is_array($orderBy) && count($orderBy) > 0) { $orders = array(); foreach ($orderBy as $key => $value) { $realName = constant(get_called_class() . '::FIELD_' . strtoupper(Helper::codifyName($key))); $orders[$realName] = strtoupper(ucfirst($value)); } $selectQuery->orderBy($orders); } $selectQuery->limit(1); if ($selectQuery->execute() === false) { return false; } $data = $selectQuery->fetch(); if (is_array($data) === false) { return false; } return $data; }
php
{ "resource": "" }
q249678
Model.countRows
validation
public static function countRows(array $conditions, bool $critical = false) { $entity = new static(); $selectQuery = new Select($entity->getDatabaseName(), $critical); $selectQuery->select([ 'count' => 'COUNT(*)' ]); $selectQuery->from($entity->getTableName()); if (count($conditions) > 0) { $where = array(); foreach ($conditions as $key => $value) { $realName = constant(get_called_class() . '::FIELD_' . strtoupper(Helper::codifyName($key))); $where[$realName] = ':where' . ucfirst($key); $selectQuery->bind('where' . ucfirst($key), $value); } $selectQuery->where($where); } if ($selectQuery->execute() === false) { return false; } $data = $selectQuery->fetch(); if ($data === false) { return false; } return $data['count']; }
php
{ "resource": "" }
q249679
PostLinkSubscriber.setPostLink
validation
public function setPostLink(TimelineLinkEvent $event): void { $action = $event->getAction(); if (!in_array($action->getVerb(), ['post', 'reply'])) { return; } $production = $action->getComponent('indirectComplement')->getData(); $post = $action->getComponent('directComplement')->getData(); $event->setLink($this->url_generator->generate('bkstg_board_show', [ 'production_slug' => $production->getSlug(), '_fragment' => 'post-' . $post->getId(), ])); }
php
{ "resource": "" }
q249680
IncludePanel.completeFilesCountsAndEditorLinks
validation
protected static function completeFilesCountsAndEditorLinks () { if (!static::$files) { $rawList = get_included_files(); $list = []; $docRoot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']); $docRootLength = mb_strlen($docRoot); $tracyFileDetectionSubstr = '/tracy'; foreach ($rawList as & $file) { $file = str_replace('\\', '/', $file); $text = mb_substr($file, $docRootLength); $tracyFile = mb_stripos($text, $tracyFileDetectionSubstr) !== FALSE; if (!$tracyFile) static::$appFilesCount += 1; static::$allFilesCount += 1; $href = \Tracy\Helpers::editorUri($file, 1); $list[] = '<a '.($tracyFile ? 'class="tracy" ':'').'href="'.$href.'"><nobr>'.$text.'</nobr></a><br />'; } static::$files = & $list; } }
php
{ "resource": "" }
q249681
PostController.createAction
validation
public function createAction( string $production_slug, Request $request, TokenStorageInterface $token, AuthorizationCheckerInterface $auth ): Response { // Lookup the production by production_slug. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Check permissions for this action. if (!$auth->isGranted('GROUP_ROLE_USER', $production)) { throw new AccessDeniedException(); } // Get some basic information about the user. $user = $token->getToken()->getUser(); // Create a new post. $post = new Post(); $post->setActive(true); $post->setPinned(false); $post->setAuthor($user->getUsername()); $post->addGroup($production); // This post is a reply. if ($request->query->has('reply-to')) { // Make sure the parent post is valid. $repo = $this->em->getRepository(Post::class); if (null === $parent = $repo->findOneBy(['id' => $request->query->get('reply-to')])) { throw new NotFoundHttpException(); } // Must be a member of the same group. if (!$parent->getGroups()->contains($production)) { throw new AccessDeniedException(); } // Parent must not be a child. if (null !== $parent->getParent()) { throw new AccessDeniedException(); } $post->setParent($parent); // This is a reply, use the basic reply form. $form = $this->form->create(ReplyType::class, $post); } else { // This is a new post, use the post form. $form = $this->form->create(PostType::class, $post); } // Handle the form. $form->handleRequest($request); // Form is submitted and valid. if ($form->isSubmitted() && $form->isValid()) { // Persist the post. $this->em->persist($post); $this->em->flush(); // Set success message and redirect. $this->session->getFlashBag()->add( 'success', $this->translator->trans('post.created', [], BkstgNoticeBoardBundle::TRANSLATION_DOMAIN) ); return new RedirectResponse($this->url_generator->generate( 'bkstg_board_show', ['production_slug' => $production->getSlug()] )); } // Render the form. return new Response($this->templating->render('@BkstgNoticeBoard/Post/create.html.twig', [ 'form' => $form->createView(), 'post' => $post, 'production' => $production, ])); }
php
{ "resource": "" }
q249682
PostController.updateAction
validation
public function updateAction( string $production_slug, int $id, Request $request, TokenStorageInterface $token, AuthorizationCheckerInterface $auth ): Response { // Lookup the post and production. list($post, $production) = $this->lookupEntity(Post::class, $id, $production_slug); // Check permissions for this action. if (!$auth->isGranted('edit', $post)) { throw new AccessDeniedException(); } // Get some basic information about the user. $user = $token->getToken()->getUser(); // Create a new form for the post and handle. if (null !== $post->getParent()) { $form = $this->form->create(ReplyType::class, $post); } else { $form = $this->form->create(PostType::class, $post); } // Handle the form submission. $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // Flush entity manager, set success message and redirect. $this->em->flush(); $this->session->getFlashBag()->add( 'success', $this->translator->trans('post.updated', [], BkstgNoticeBoardBundle::TRANSLATION_DOMAIN) ); return new RedirectResponse($this->url_generator->generate( 'bkstg_board_show', ['production_slug' => $production->getSlug()] )); } // Render the form. return new Response($this->templating->render('@BkstgNoticeBoard/Post/update.html.twig', [ 'form' => $form->createView(), 'post' => $post, 'production' => $production, ])); }
php
{ "resource": "" }
q249683
RenderJson.render
validation
public function render(array $args, bool $prettyPrint = null) { header('Content-type: application/json'); if ((constant('STRAY_ENV') === 'development' && $prettyPrint !== false) || $prettyPrint === true) { return (string) json_encode($args, JSON_PRETTY_PRINT); } return (string) json_encode($args); }
php
{ "resource": "" }
q249684
JobHandler.exit
validation
public function exit($id, $pid, $code, $forceRetry = false, $queueBackoffTime = null) { $this->logger->info('Job ended', [ 'exitCode' => $code, 'pid' => $pid, 'jobId' => $id, 'queue' => $this->queue->getName() ]); $hash = explode(':', $id); $jobId = $hash[count($hash) - 1]; try { $job = $this->queue->getJob($jobId); } catch (JobNotFoundException $e) { $this->logger->info('Unable to process job exit code or retry status. Job data unavailable', [ 'exitCode' => $code, 'pid' => $pid, 'jobId' => $job->getId(), 'queue' => $this->queue->getName() ]); return true; } // If the job ended successfully, remove the data from redis if ($code === 0) { $this->logger->info('Job succeeded and is now complete', [ 'exitCode' => $code, 'pid' => $pid, 'jobId' => $job->getId(), 'queue' => $this->queue->getName() ]); return $job->end(); } else { $retry = $job->getRetry(); // If force retry was specified, force this job to retry indefinitely if ($forceRetry === true) { $retry = true; } if ($retry === true || $retry > 0) { $this->logger->info('Rescheduling job', [ 'exitCode' => $code, 'pid' => $pid, 'jobId' => $job->getId(), 'queue' => $this->queue->getName(), 'time' => \time() + $queueBackoffTime ?? 0 ]); // If a retry is specified, repush the job back onto the queue with the same Job ID return $job->retry($queueBackoffTime); } else { $this->logger->info('Job failed', [ 'exitCode' => $code, 'pid' => $pid, 'jobId' => $job->getId(), 'queue' => $this->queue->getName() ]); return $job->fail(); } } return; }
php
{ "resource": "" }
q249685
TwitterDriver.matchesRequest
validation
public function matchesRequest() { if (isset($this->headers['x-twitter-webhooks-signature'])) { $signature = $this->headers['x-twitter-webhooks-signature'][0]; $hash = hash_hmac('sha256', json_encode($this->payload->all()), $this->config->get('consumer_secret'), true); return $signature === 'sha256='.base64_encode($hash); } return false; }
php
{ "resource": "" }
q249686
TwitterDriver.getUser
validation
public function getUser(IncomingMessage $matchingMessage) { $sender_id = $matchingMessage->getRecipient(); $user = Collection::make($this->payload->get('users'))->first(function ($user) use ($sender_id) { return $user['id'] === $sender_id; }); return new User($user['id'], null, null, $user['name'], $user); }
php
{ "resource": "" }
q249687
TwitterDriver.convertQuestion
validation
private function convertQuestion(Question $question) { $buttons = Collection::make($question->getButtons())->map(function ($button) { return [ 'label' => $button['text'], 'metadata' => $button['value'] ]; }); return [ 'text' => $question->getText(), 'quick_reply' => [ 'type'=>'options', 'options' => $buttons->toArray(), ], ]; }
php
{ "resource": "" }
q249688
TwitterDriver.sendRequest
validation
public function sendRequest($endpoint, array $parameters, IncomingMessage $matchingMessage) { $this->connection->post($endpoint, $parameters, true); return Response::create($this->connection->getLastBody(), $this->connection->getLastHttpCode()); }
php
{ "resource": "" }
q249689
TgCommands.broadcastMsg
validation
public function broadcastMsg(array $peers, $msg) { $peerList = $this->formatPeers($peers); return $this->exec('broadcast ' . $peerList . ' ' . $msg); }
php
{ "resource": "" }
q249690
TgCommands.contactAdd
validation
public function contactAdd($phoneNumber, $firstName, $lastName) { $phoneNumber = $this->formatPhoneNumber($phoneNumber); return $this->exec('add_contact ' . $phoneNumber . ' ' . $this->escapeStringArgument($firstName) . ' ' . $this->escapeStringArgument($lastName)); }
php
{ "resource": "" }
q249691
TgCommands.contactRename
validation
public function contactRename($contact, $firstName, $lastName) { $contact = $this->escapePeer($contact); $firstName = $this->escapeStringArgument($firstName); $lastName = $this->escapeStringArgument($lastName); return $this->exec('rename_contact ' . $contact . ' ' . $firstName . ' ' . $lastName); }
php
{ "resource": "" }
q249692
TgCommands.setProfilePhoto
validation
public function setProfilePhoto($mediaUri) { //Process the requested media file. $processedMedia = $this->processMediaUri($mediaUri); if ( ! $processedMedia) { return false; } //Send media file. $result = $this->exec('set_profile_photo ' . $processedMedia['filepath']); //Clean up if media file came from REMOTE address $this->cleanUpMedia($processedMedia); return $result; }
php
{ "resource": "" }
q249693
TgCommands.checkUrlExistsAndSize
validation
protected function checkUrlExistsAndSize($fileUri, array $mediaFileInfo) { $mediaFileInfo['url'] = $fileUri; //File is a URL. Create a curl connection but DON'T download the body content //because we want to see if file is too big. $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$fileUri"); curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_NOBODY, true); if (curl_exec($curl) === false) { return false; } //While we're here, get mime type and filesize and extension $info = curl_getinfo($curl); $mediaFileInfo['filesize'] = $info['download_content_length']; $mediaFileInfo['filemimetype'] = $info['content_type']; $mediaFileInfo['fileextension'] = pathinfo(parse_url($mediaFileInfo['url'], PHP_URL_PATH), PATHINFO_EXTENSION); curl_close($curl); return $mediaFileInfo; }
php
{ "resource": "" }
q249694
TgCommands.determineFilename
validation
protected function determineFilename($originalFilename, array $mediaFileInfo) { if (is_null($originalFilename) || ! isset($originalFilename) || is_file(sys_get_temp_dir() . '/' . $originalFilename)) { //Need to create a unique file name as file either exists or we couldn't determine it. //Create temp file in system folder. $uniqueFilename = tempnam(sys_get_temp_dir(), 'tg'); //Add file extension rename($uniqueFilename, $uniqueFilename . '.' . $mediaFileInfo['fileextension']); $mediaFileInfo['filepath'] = $uniqueFilename . '.' . $mediaFileInfo['fileextension']; } else { $mediaFileInfo['filepath'] = sys_get_temp_dir() . '/' . $originalFilename; } return $mediaFileInfo; }
php
{ "resource": "" }
q249695
TgCommands.downloadMediaFileFromURL
validation
protected function downloadMediaFileFromURL($fileUri, $tempFileName) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$fileUri"); curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_NOBODY, false); curl_setopt($curl, CURLOPT_BUFFERSIZE, 1024); curl_setopt($curl, CURLOPT_FILE, $tempFileName); curl_exec($curl); curl_close($curl); }
php
{ "resource": "" }
q249696
DrushStack.argsForNextCommand
validation
protected function argsForNextCommand($args) { if (!is_array($args)) { $args = func_get_args(); } $this->argumentsForNextCommand .= ' ' . implode(' ', $args); return $this; }
php
{ "resource": "" }
q249697
DrushStack.drush
validation
public function drush($command, $assumeYes = true) { if (is_array($command)) { $command = implode(' ', array_filter($command)); } return $this->exec($this->injectArguments($command, $assumeYes)); }
php
{ "resource": "" }
q249698
DrushStack.injectArguments
validation
protected function injectArguments($command, $assumeYes) { $cmd = $this->siteAlias . ' ' . $command . ($assumeYes ? ' -y': '') . $this->arguments . $this->argumentsForNextCommand; $this->argumentsForNextCommand = ''; return $cmd; }
php
{ "resource": "" }
q249699
DrushStack.updateDb
validation
public function updateDb() { $this->printTaskInfo('Do database updates'); $this->drush('updb'); $drushVersion = $this->getVersion(); if (-1 === version_compare($drushVersion, '6.0')) { $this->printTaskInfo('Will clear cache after db updates for drush ' . $drushVersion); $this->clearCache(); } else { $this->printTaskInfo('Will not clear cache after db updates, since drush ' . $drushVersion . ' should do it automatically'); } return $this; }
php
{ "resource": "" }