/**
  * Register bindings in the container.
  *
  * @return void
  */
 public function register()
 {
     $app = $this->app;
     Queue::addConnector('phpredis', function () use($app) {
         return new PHPRedisConnector($app['phpredis']);
     });
 }
Esempio n. 2
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     // Check not 'sync'
     if (Config::get('queue.default') == "sync") {
         Artisan::call('down');
         $this->info("Application maintenance mode enabled.");
         return;
     }
     // Push job onto queue
     Queue::push(function ($job) {
         // Take Application down.
         Artisan::call('down');
         // Add Log message
         Log::info("Application is down, pausing queue while maintenance happens.");
         // Loop, waiting for app to come back up
         while (App::isDownForMaintenance()) {
             echo ".";
             sleep(5);
         }
         // App is back online, kill worker to restart daemon.
         Log::info("Application is up, rebooting queue.");
         Artisan::call('queue:restart');
         $job->delete();
     });
     // Wait until Maintenance Mode enabled.
     while (!App::isDownForMaintenance()) {
         sleep(1);
     }
     $this->info("Application maintenance mode enabled.");
 }
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot()
 {
     $this->publishes([__DIR__ . '/../config/sqs-plain.php' => config_path('sqs-plain.php')]);
     Queue::after(function (JobProcessed $event) {
         $event->job->delete();
     });
 }
 public function boot()
 {
     Queue::failing(function (JobFailed $event) {
         //dump($event);
         //TODO Can post to slack here
     });
 }
 protected function preprocessSendNotification($parsed_tx, $confirmations, $block_seq, $block)
 {
     // throw this transaction into the counterpartyd verification queue
     $data = ['tx' => $parsed_tx, 'confirmations' => $confirmations, 'block_seq' => $block_seq, 'block_id' => $block['id']];
     // Log::debug("pushing ValidateConfirmedCounterpartydTxJob ".json_encode($data['block_id'], 192));
     Queue::connection('blockingbeanstalkd')->push('App\\Jobs\\XChain\\ValidateConfirmedCounterpartydTxJob', $data, 'validate_counterpartytx');
 }
Esempio n. 6
0
 /**
  * Test adding to the queue.
  */
 public function testQueueAdd()
 {
     Queue::push(function ($job) {
         factory(App\Models\TestEntity::class)->create();
         $job->delete();
     });
     $job = $this->pheanstalk->watch('default')->reserve();
     $data = $job->getData();
     $decoded = json_decode($data);
     $this->assertEquals('IlluminateQueueClosure', $decoded->job);
 }
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     $queue = $this->argument('queue') ? $this->argument('queue') : Config::get('queue.connections.beanstalkd.queue');
     $this->info(sprintf('Clearing queue: %s', $queue));
     $pheanstalk = Queue::getPheanstalk();
     $pheanstalk->useTube($queue);
     $pheanstalk->watch($queue);
     while ($job = $pheanstalk->reserve(0)) {
         $pheanstalk->delete($job);
     }
     $this->info('...cleared.');
 }
Esempio n. 8
0
 /**
  * Get a default queue value, if any is available
  *
  * @return Queue|null A default queue value or Null if no default value is available
  */
 public function getDefaultQueue()
 {
     // By default, the Queue Facade does not return the
     // any actual database connection, but rather an
     // instance of \Illuminate\Queue\QueueManager.
     // Therefore, we make sure only to obtain its
     // "connection", to make sure that its only the connection
     // instance that we obtain.
     $manager = QueueFacade::getFacadeRoot();
     if (!is_null($manager)) {
         return $manager->connection();
     }
     return $manager;
 }
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot()
 {
     Queue::failing(function (JobFailed $event) {
         Log::error('Error with Queue');
     });
     User::creating(function ($user) {
         return $user->token = str_random(12);
     });
     Board::creating(function ($board) {
         try {
             $uuid = Uuid::uuid1()->toString();
             $board->identifier = $uuid;
         } catch (UnsatisfiedDependencyException $e) {
             Log::error('UUID creation error => ' . $e);
             return response()->json('Error creating board', 500);
         }
     });
 }
Esempio n. 10
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(CreateTransactionRequest $request, TransactionController $controller)
 {
     $message_code = 57;
     // initialize with illegal transaction
     // log activity
     try {
         $payer = User::findOrFail($request->payer_id)->with(['primary_account', 'account_status'])->first();
         // get payer and primary a/c information
         $payee = OAuth_clients::with('user')->with('user.account_status')->whereId($request->payee_id)->first();
         session()->flash('flash_message', 'Found Payee/Payer');
     } catch (Exception $e) {
         session()->flash('flash_message', 'Cannot find payee/payer');
         $message_code = 14;
     }
     $activity_id = Queue::push($this->logActivity($payer, $payee, $request->txn_currencyid, $request->amount_in_txn_currency), '', 'activity_log');
     // authenticate Payee account
     if ($request->amount_in_txn_currency > 0) {
         // Check fraud
         $fraud = Queue::push($controller->checkFraud($payer));
         if ($this->checkPayeeAccount($payee->user)) {
             // authenticate and transact for payer
             if (Hash::check($request->password, $payer->password)) {
                 // check payee
                 $message_code = $this->checkPayerAccount($payer, $request);
                 if ($message_code = 0) {
                     session()->flash('flash_message', 'Transaction approved');
                 }
             } else {
                 session()->flash('flash_message', 'Payer Kudotsu account/PIN wrong.');
                 $message_code = 28;
             }
         } else {
             session()->flash('flash_message', 'Payee Kudotsu account not approved');
             $message_code = 20;
         }
         Queue::push($controller->store($message_code, $payer, $payee), '', 'activity_log');
     } else {
         session()->flash('flash_message', $payee . $request->payer_id . $payer);
         //'Invalid Amount or trying to pay yourself');
         $message_code = 13;
     }
     return view('transaction.response');
 }
Esempio n. 11
0
 /**
  *  <h1>Описание</h1>
  *  <pre>
  *    Провести авторизацию и выполнить команду
  *  </pre>
  *  <h1>Что возвращает</h1>
  *  <pre>
  *    - JSON-массив:
  *
  *      [
  *        "status"        // Статус результата выполнения команды
  *        "timestamp"     // Timestamp прихода запроса от клиента
  *        "data"          // Данные
  *      ]
  *  </pre>
  *  <h1>Какие статусы бывают, зависимость data от статуса</h1>
  *  <pre>
  *    0   // Команда выполнена успешно. В data результаты её выполненя.
  *    -1  // Нет доступа. В data строка-сообщение об этом.
  *    -2  // Команда завершилась с ошибкой. В data текст ошибки.
  *  </pre>
  *  <h1>Примеры использования</h1>
  *  <pre>
  *
  *    1. Синхронное выполнение
  *
  *      1.1. Простой синхронный запуск
  *        runcommand('\M1\Commands\C1_parseapp');
  *
  *      1.2. С передачей данных
  *        runcommand('\M1\Commands\C1_parseapp', ['key1'=>'value1','key2'=>'value2']);
  *
  *      1.3. С авторизацией по ID текущего пользователя (ID == "15" в примере)
  *        runcommand('\M1\Commands\C1_parseapp', [], 15);
  *
  *    2. Добавление в очередь задач
  *
  *      2.1. Без дополнительной отсрочки выполнения
  *      runcommand('\M1\Commands\C1_parseapp', [], "", ['on'=>true, 'delaysecs'=>'']);
  *
  *      2.2. С дополнительной отсрочкой выполнения в 10 секунд
  *      runcommand('\M1\Commands\C1_parseapp', [], "", ['on'=>true, 'delaysecs'=>'10']);
  *
  *  </pre>
  *
  * @param  mixed $command
  * @param  array $data
  * @param  mixed $userid
  * @param  mixed $queue
  *
  * @return mixed
  */
 function runcommand($command, $data = [], $userid = 0, $queue = ['on' => false, 'delaysecs' => '', 'name' => 'default'])
 {
     // 1. Провести exec-авторизацию, если она включена
     if (config("M5.authorize_exec_ison") == true) {
         // 1.1. Если $userid == -1
         // - Вернуть ответ со статусом -1 (доступ запрещён)
         if ($userid == -1) {
             return ["status" => -1, "data" => $command];
         } else {
             $validator = r4_validate(['userid' => $userid], ["userid" => ["required", "regex:/^[0-9]+\$/ui"]]);
             if ($validator['status'] == -1) {
                 return ["status" => -1, "data" => $command];
             }
         }
         // 1.3. Если $userid !== 0, то провести exec-авторизацию
         if ($userid !== 0) {
             // 1] Извлечь из сессии значение по ключу "authorize_exec"
             $authorize_exec = session('authorize_exec');
             // 2] Провести валидацию $authorize_exec
             $is_authorize_exec_valid = call_user_func(function () use($authorize_exec) {
                 // 2.1] Если $authorize_exec пусто, вернуть false
                 if (empty($authorize_exec)) {
                     return false;
                 }
                 // 2.2] Если $authorize_exec не массив строк, вернуть false
                 $validator = r4_validate(['authorize_exec' => $authorize_exec], ["authorize_exec" => ["required", "array"], "authorize_exec.*" => ["string"]]);
                 if ($validator['status'] == -1) {
                     return false;
                 }
                 // 2.3] Вернуть true
                 return true;
             });
             // 3] Искать $command в $authorize_exec
             // - Если $authorize_exec не пусто и валидно.
             // - Если права нет, вернуть статус -1 (доступ запрещён).
             if ($is_authorize_exec_valid) {
                 if (!in_array($command, $authorize_exec)) {
                     return ["status" => -1, "data" => $command];
                 }
             } else {
                 // 4.1] Получить коллекцию всех команд, которые $userid может выполнять
                 $commands = call_user_func(function () use($userid) {
                     // 4.1.1] Попробовать найти пользователя $userid
                     // - Если найти его не удастся, вернуть пустую коллекцию.
                     $user = \M5\Models\MD1_users::find($userid);
                     if (empty($user)) {
                         return collect([]);
                     }
                     // 4.1.2] Получить коллекцию всех exec-прав, связанных с $user
                     $privileges = call_user_func(function () use($user) {
                         // 1) Состоит ли $user в любой административной группе?
                         $admingroup = \M5\Models\MD2_groups::where('isadmin', 1)->whereHas('users', function ($query) use($user) {
                             $query->where('id', $user->id);
                         })->first();
                         // 2) Если состоит, вернуть все exec-права
                         if (!empty($admingroup)) {
                             return \M5\Models\MD3_privileges::whereHas('privtypes', function ($query) {
                                 $query->where('name', 'exec');
                             })->get();
                         } else {
                             return \M5\Models\MD3_privileges::whereHas('privtypes', function ($query) {
                                 $query->where('name', 'exec');
                             })->where(function ($query) use($user) {
                                 // Права, прямо связанные с пользователем
                                 $query->whereHas('users', function ($query) use($user) {
                                     $query->where('id', $user->id);
                                 });
                                 // Права, связанные с группами, с которыми связан пользователь
                                 $query->orWhereHas('groups', function ($query) use($user) {
                                     $query->whereHas('users', function ($query) use($user) {
                                         $query->where('id', $user->id);
                                     });
                                 });
                                 // Права, связанные с тегами, с которыми связан пользователь
                                 $query->orWhereHas('tags', function ($query) use($user) {
                                     $query->whereHas('users', function ($query) use($user) {
                                         $query->where('id', $user->id);
                                     });
                                 });
                                 // Права, связанные с тегами, связанные с группами, с которыми связан пользователь.
                                 $query->orWhereHas('tags', function ($query) use($user) {
                                     $query->whereHas('groups', function ($query) use($user) {
                                         $query->whereHas('users', function ($query) use($user) {
                                             $query->where('id', $user->id);
                                         });
                                     });
                                 });
                             })->get();
                         }
                     });
                     // 4.1.3] Если у модели MD5_commands в M1 нет связи m5_privileges
                     // - Вернуть пустую коллекцию.
                     if (!r1_rel_exists("m1", "md5_commands", "m5_privileges")) {
                         return collect([]);
                     }
                     // 4.1.4] В противном случае, вернуть коллекцию соотв.команд
                     $commands = r1_query(function () use($privileges) {
                         return \M1\Models\MD5_commands::with(['packages'])->where(function ($query) use($privileges) {
                             $query->whereHas('m5_privileges', function ($query) use($privileges) {
                                 $query->whereIn('id', $privileges->pluck('id'));
                             });
                         })->get();
                     });
                     if (!$commands) {
                         return collect([]);
                     } else {
                         return $commands;
                     }
                 });
                 // 4.2] Превратить $commands в массив полн.квалиф.команд
                 $commands_final = call_user_func(function () use($commands) {
                     // 4.2.1] Если $commands эта пустая коллекция, вернуть пустой массив
                     if (count($commands) == 0) {
                         return [];
                     }
                     // 4.2.2] Подготовить массив для результата
                     $result = [];
                     // 4.2.3] Пробежаться по $commands и наполнить $result
                     $commands->each(function ($item) use(&$result) {
                         array_push($result, "\\" . $item->packages[0]->id_inner . "\\Commands\\" . $item->name);
                     });
                     // 4.2.n] Вернуть результат
                     return $result;
                 });
                 // 4.3] Перезаписать в сессии кэш authorize_exec
                 session(['authorize_exec' => $commands_final]);
                 // 4.4] Если $command не в $commands_final
                 // - Вернуть статус -1 (нет доступа).
                 if (!in_array($command, $commands_final)) {
                     return ["status" => -1, "data" => $command];
                 }
             }
         }
     }
     // 2. Выполнить команду $command
     // - Передав ей данные $data
     // 2.1. Синхронно, если иное не указано в 4-м аргументе runcommand
     if ($queue['on'] == false) {
         $result = Bus::dispatch(new $command($data));
     } else {
         // 1] Без задержки
         if (empty($queue['delaysecs'])) {
             Queue::push(new $command($data), [], $queue['name']);
         } else {
             Queue::later($queue['delaysecs'], new $command($data), [], $queue['name']);
         }
     }
     // 3. Подготовить массив с ответом, и вернуть
     // 3.1. Если команда выполняется синхронно
     if ($queue['on'] == false) {
         $response = ["status" => $result['status'], "data" => $result['data']];
         if (array_key_exists('timestamp', $data)) {
             $response['timestamp'] = $data['timestamp'];
         }
         return $response;
     }
     // 3.2. Если команда выполняется асинхронно
     if ($queue['on'] == true) {
         $response = ["status" => 0, "data" => ""];
         if (array_key_exists('timestamp', $data)) {
             $response['timestamp'] = $data['timestamp'];
         }
         return $response;
     }
 }
Esempio n. 12
0
 public function getIndex()
 {
     Queue::push('Test', array('message' => 'ddddd'));
 }
Esempio n. 13
0
 /**
  * Model save event handler
  *
  * @param Model $model
  */
 public function saved(Model $model)
 {
     if ($model::$__es_enable && $model->shouldIndex()) {
         Queue::push('Iverberk\\Larasearch\\Jobs\\ReindexJob', $this->findAffectedModels($model));
     }
 }
Esempio n. 14
0
 /**
  *
  */
 public function it_shoud_reindex_on_model_delete()
 {
     /**
      *
      * Expectation
      *
      */
     Facade::clearResolvedInstances();
     Queue::shouldReceive('push')->with('Iverberk\\Larasearch\\Jobs\\DeleteJob', ['Husband:2'])->once();
     Queue::shouldReceive('push')->with('Iverberk\\Larasearch\\Jobs\\ReindexJob', ['Wife:2', 'Child:2', 'Toy:2'])->once();
     Config::shouldReceive('get')->with('/^larasearch::reversedPaths\\..*$/', array())->once()->andReturn(['', 'wife', 'children', 'children.toys']);
     $husband = \Husband::find(2);
     with(new Observer())->deleted($husband);
 }
Esempio n. 15
0
 /**
  * Checks the system meets all the requirements needed to run Deployer.
  *
  * @return bool
  */
 protected function checkRequirements()
 {
     $errors = false;
     // Check PHP version:
     if (!version_compare(PHP_VERSION, '5.5.9', '>=')) {
         $this->error('PHP 5.5.9 or higher is required');
         $errors = true;
     }
     // Check for required PHP extensions
     $required_extensions = ['PDO', 'curl', 'gd', 'json', 'tokenizer', 'openssl', 'mbstring'];
     foreach ($required_extensions as $extension) {
         if (!extension_loaded($extension)) {
             $this->error('Extension required: ' . $extension);
             $errors = true;
         }
     }
     if (!count($this->getDatabaseDrivers())) {
         $this->error('At least 1 PDO driver is required. Either sqlite, mysql, pgsql or sqlsrv, check your php.ini file');
         $errors = true;
     }
     // Functions needed by symfony process
     $required_functions = ['proc_open'];
     foreach ($required_functions as $function) {
         if (!function_exists($function)) {
             $this->error('Function required: ' . $function . '. Is it disabled in php.ini?');
             $errors = true;
         }
     }
     // Programs needed in $PATH
     $required_commands = ['ssh', 'ssh-keygen', 'git', 'scp', 'tar', 'gzip', 'rsync', 'bash'];
     foreach ($required_commands as $command) {
         $process = new Process('which ' . $command);
         $process->setTimeout(null);
         $process->run();
         if (!$process->isSuccessful()) {
             $this->error('Program not found in path: ' . $command);
             $errors = true;
         }
     }
     $required_one = ['node', 'nodejs'];
     $found = false;
     foreach ($required_one as $command) {
         $process = new Process('which ' . $command);
         $process->setTimeout(null);
         $process->run();
         if ($process->isSuccessful()) {
             $found = true;
             break;
         }
     }
     if (!$found) {
         $this->error('node.js was not found');
         $errors = true;
     }
     // Files and directories which need to be writable
     $writable = ['.env', 'storage', 'storage/logs', 'storage/app', 'storage/app/mirrors', 'storage/app/tmp', 'storage/framework', 'storage/framework/cache', 'storage/framework/sessions', 'storage/framework/views', 'bootstrap/cache', 'public/upload'];
     foreach ($writable as $path) {
         if (!is_writeable(base_path($path))) {
             $this->error($path . ' is not writeable');
             $errors = true;
         }
     }
     // Check that redis is running
     try {
         Redis::connection()->ping();
     } catch (\Exception $e) {
         $this->error('Redis is not running');
         $errors = true;
     }
     if (config('queue.default') === 'beanstalkd') {
         $connected = Queue::connection()->getPheanstalk()->getConnection()->isServiceListening();
         if (!$connected) {
             $this->error('Beanstalkd is not running');
             $errors = true;
         }
     }
     if ($errors) {
         $this->line('');
         $this->block('Deployer cannot be installed. Please review the errors above before continuing.');
         $this->line('');
         return false;
     }
     return true;
 }
Esempio n. 16
0
 public function run($className)
 {
     Queue::push($className, $this);
 }
Esempio n. 17
0
 protected function pushToQueue(array $hit, DocumentPath $from, DocumentPath $to, $queue, $source = false)
 {
     $from = clone $from;
     $to = clone $to;
     $from->type = $this->extractArgument($from->type, $hit['_type']);
     $from->id = $this->extractArgument($from->id, $hit['_id']);
     $to->type = $this->extractArgument($to->type, $hit['_type']);
     $to->id = $this->extractArgument($to->id, $hit['_id']);
     $job = new JobData();
     $job->pathFrom = $from;
     $job->pathTo = $to;
     $job->source = $source ? $hit['_source'] : [];
     $job->parent = array_get($hit, 'fields._parent');
     if (!$job->pathFrom->isValid() || !$job->pathTo->isValid()) {
         throw new InvalidArgumentException('FROM or TO path is not valid');
     }
     Queue::push(Copier::class, $job->toArray(), $queue);
 }
 public function getQueueSize($queue_name, $connection = null)
 {
     $pheanstalk = Queue::connection($connection)->getPheanstalk();
     $stats = $pheanstalk->statsTube($queue_name);
     return $stats['current-jobs-urgent'];
 }
Esempio n. 19
0
 /**
  * @test
  */
 public function it_should_reindex_on_model_delete()
 {
     /**
      *
      * Expectation
      *
      */
     Facade::clearResolvedInstances();
     Queue::shouldReceive('push')->with('Menthol\\Flexible\\Jobs\\DeleteJob', ['Husband:2'])->once();
     $config = m::mock('Menthol\\Flexible\\Config');
     App::shouldReceive('make')->with('Menthol\\Flexible\\Config')->andReturn($config);
     $config->shouldReceive('get')->with('/^reversedPaths\\..*$/', [])->once()->andReturn(['', 'wife', 'children', 'children.toys']);
     Queue::shouldReceive('push')->with('Menthol\\Flexible\\Jobs\\ReindexJob', ['Wife:2', 'Child:2', 'Toy:2'])->once();
     $husband = \Husband::find(2);
     with(new Observer())->deleted($husband);
 }
Esempio n. 20
0
 /**
  * Model save event handler
  *
  * @param Model $model
  */
 public function saved(Model $model)
 {
     if ($model::$__es_enable && $model->shouldIndex()) {
         Queue::push('Menthol\\Flexible\\Jobs\\ReindexJob', $this->findAffectedModels($model));
     }
 }
    if (!empty($route_url)) {
        Route::post($route_url, function () {
            $listener_type = Config::get('aftership-laravel::web_hook.listener.type');
            $handler = Config::get('aftership-laravel::web_hook.listener.handler');
            if (empty($listener_type) || empty($handler)) {
                throw new Exception('Listener Configuration is incomplete.');
            }
            if ($listener_type == "event") {
                Event::fire($handler, array('data' => Input::all()));
            } elseif ($listener_type == "queue") {
                $queue_connection = Config::get('aftership-laravel::web_hook.listener.queue_connection');
                $queue_name = Config::get('aftership-laravel::web_hook.listener.queue_name');
                if (empty($queue_connection)) {
                    if (empty($queue_name)) {
                        Queue::push($handler, array('data' => Input::all()));
                    } else {
                        Queue::push($handler, array('data' => Input::all()), $queue_name);
                    }
                } else {
                    if (empty($queue_name)) {
                        Queue::connection($queue_connection)->push($handler, array('data' => Input::all()));
                    } else {
                        Queue::connection($queue_connection)->push($handler, array('data' => Input::all()), $queue_name);
                    }
                }
            }
        });
    } else {
        throw new Exception('Route URL cannot be empty when Webhook is enabled.');
    }
}
Esempio n. 22
0
 private function sendEmail(stdClass $subscriber, array $posts)
 {
     Queue::push(new SendNewsletter($subscriber, $posts));
 }
Esempio n. 23
0
 /**
  * Push log to queue.
  *
  * @param int    $userId
  * @param string $title
  * @param string $type
  * @param string $data
  * @param string $sql
  *
  * @return string
  */
 public static function create($userId = 0, $title = '', $type = 'S', $object = '', $object_id = 0, $data = '', $sql = '')
 {
     return Queue::push(new UserLogJob(compact('userId', 'title', 'type', 'object', 'object_id', 'data', 'sql')));
 }
Esempio n. 24
0
 /**
  * Get a default queue manager value, if any is available
  *
  * @return QueueManager|null A default queue manager value or Null if no default value is available
  */
 public function getDefaultQueueManager()
 {
     return Queue::getFacadeRoot();
 }
Esempio n. 25
0
    if (env('ADMIN_PASSWORD', 'admin') !== $inputs['password']) {
        return Util::errorResponse('incorrect password');
    }
    $start2 = json_decode($inputs['data'], true);
    if (Util::exists('api_start2.json')) {
        $data = Util::load('api_start2.json');
        if (Util::compareJson($data, $start2)) {
            return Util::errorResponse('duplicate start2 data');
        }
    }
    Util::dump('api_start2.json', $start2);
    $datetime = new DateTime();
    $today = $datetime->format('YmdH');
    Util::dump("start2/{$today}.json", $start2);
    Queue::push(function ($job) {
        Artisan::call('parse:start2');
        $job->delete();
    });
    return Util::successResponse();
});
$app->get('/start2', function () {
    try {
        $data = Util::read('api_start2.json');
        return response($data)->header('Content-Type', 'application/json');
    } catch (FileNotFoundException $e) {
        return Util::errorResponse('api_start2.json not found in server');
    }
});
$app->get('/start2/archives', function () {
    $files = Storage::disk('local')->files('start2');
    $list = [];
    $matches = [];
Esempio n. 26
0
 /**
  * Run on deleted observer.
  *
  * @param  \Illuminate\Database\Eloquent\Model  $entity
  *
  * @return bool
  */
 public function deleted(Model $entity)
 {
     Queue::push(DeleteTenant::class, ['database' => $this->getConnectionName(), 'driver' => $this->getDriverName(), 'id' => $entity->getKey()]);
     return true;
 }
 public static function enqueue($url, $method, $payload)
 {
     $callback_data = ['callback_url' => $url, 'callback_method' => $method, 'callback_payload_base64' => base64_encode(serialize($payload)), 'callback_timestamp' => time()];
     //Queue::push('QueuedHttp@dequeue', $callback_data, 'queued_http_requests');
     Queue::push('queuedhttpclient@dequeue', $callback_data, 'queued_http_requests');
 }
Esempio n. 28
0
<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
/*
|--------------------------------------------------------------------------
| Database Logging
|--------------------------------------------------------------------------
| 1) Add "require app_path().'/errors.php';" to the end of app/start/global.php
| 2) Uncomment the "Application Error Logger" section in app/start/global.php
| 3) Migrate "create_log_table", or create the table manualy
*/
Log::listen(function ($level, $message, $context) {
    // Save the php sapi and date, because the closure needs to be serialized
    $apiName = php_sapi_name();
    $date = new \DateTime();
    Queue::push(function () use($level, $message, $context, $apiName, $date) {
        DB::insert("INSERT INTO log (php_sapi_name, level, message, context, created_at) VALUES (?, ?, ?, ?, ?)", array($apiName, $level, $message, json_encode($context), $date));
    });
});
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot()
 {
     Queue::after(function (JobProcessed $event) {
         $event->job->delete();
     });
 }
Esempio n. 30
0
 /**
  * Get a default queue factory value, if any is available
  *
  * @return Factory|null A default queue factory value or Null if no default value is available
  */
 public function getDefaultQueueFactory()
 {
     return Queue::getFacadeRoot();
 }