Conditional subscription to listener in Laravel - php

I have set up a listener by adding it in EventServiceProvider
protected $subscribe = [
MyListener::class
];
The listener (MyListener) has a subscribe function that subscribes to the events the listener wants to listen for - and it works fine.
Now, I'm trying to add a check to restrict which events should be listened to. Something like
public function subscribe($events)
{
$config = ConfigService::getUserConfig();
if ($config->shouldSubscribe) {
$events->listen(.....);
}
}
I'm having some issues after adding this logic however.
It seems that when running composer install it executes the subscribe method.
This causes an issue, because there is no active session when running composer install - so I'm met with a SQL error - it can't find which database to search for configuration in - followed by this error
Script #php artisan package:discover handling the post-autoload-dump event returned with error code 1
How can I conditionally subscribe to certain events in the listener?

It is not the exact response for your answer, but it should work in your case. You can detect if your code is running from console by using Application::runningInConsole() function.
Example:
public function subscribe($events)
{
// Running from cli script, abort ship!
if(app()->runningInConsole())
{
return;
}
$config = ConfigService::getUserConfig();
if ($config->shouldSubscribe) {
$events->listen(.....);
}
}

Related

Laravel queue keep processing multiple times for a job

Below is what's happening when i run php artisan queue:listen and at my job table only have one job
and this is my code :
public function handle(Xero $xero)
{
$this->getAndCreateXeroSnapshotID();
$this->importInvoices($xero);
$this->importBankTransaction($xero);
$this->importBankStatement($xero);
$this->importBalanceSheet($xero);
$this->importProfitAndLoss($xero);
}
In order for a job to leave the queue, it must reach the end of the handle function -- without errors and exceptions.
There must be something breaking inside one or more of your functions.
If an exception is thrown while the job is being processed, the job will automatically be released back onto the queue so it may be attempted again. https://laravel.com/docs/5.8/queues
The same behavior can be achieved with
$this->release()
If you can't figure out what is breaking, you can set your job to run only once. If an error is thrown, the job will be considered failed and will be put in the failed jobs queue.
The maximum number of attempts is defined by the --tries switch used
on the queue:work Artisan command. https://laravel.com/docs/5.8/queues
php artisan queue:work --tries=1
If you are using the database queue, (awesome for debugging) run this command to create the failed queue table
php artisan queue:failed
Finally, to find out what is wrong with your code. You can catch and log the error.
public function handle(Xero $xero)
{
try{
$this->getAndCreateXeroSnapshotID();
$this->importInvoices($xero);
$this->importBankTransaction($xero);
$this->importBankStatement($xero);
$this->importBalanceSheet($xero);
$this->importProfitAndLoss($xero);
}catch(\Exception $e){
Log::error($e->getMessage());
}
}
You could also set your error log channel to be slack, bugsnag or whatever. Just be sure to check it. Please don't be offended, it's normal to screw up when dealing with laravel queues. How do you think I got here?
Laravel try to run the job again and again.
php artisan queue:work --tries=3
Upper command will only try to run the jobs 3 times.
Hope this helps
In my case the problem was the payload, I've created the variable private, but it needs to by protected.
class EventJob implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
// payload
protected $command;
// Maximum tries of this event
public $tries = 5;
public function __construct(CommandInterface $command)
{
$this->command = $command;
}
public function handle()
{
$event = I_Event::create([
'event_type_id' => $command->getEventTypeId(),
'sender_url' => $command->getSenderUrl(),
'sender_ip' => $command->getSenderIp()
]);
return $event;
}
}
The solution that worked for me to delete the job after pushing them into the queue.
Consider the e.g.
class SomeController extends Controller{
public function uploadProductCsv(){
//process file here and push the code inot Queue
Queue::push('SomeController#processFile', $someDataArray);
}
public function processFile($job, $data){
//logic to process the data
$job->delete(); //after complete the process delete the job
}
}
Note: This is implemented for laravel 4.2

Laravel - Stripe - Ultrahook - Webhook are not caught

I'm using Laravel 5.4 and Laravel Cashier. I would like to be able to catch Stripe webhooks in my localhost:8888
To do so I installed ultrahook and I started it like this
Ultrahook
http://stripe.leococo.ultrahook.com -> http://localhost:8888/stripe/webhook
Laravel routes
Route::post('stripe/webhook', '\Laravel\Cashier\Http\Controllers\WebhookController#handleWebhook');
Stripe Webhook configuration
http://stripe.leococo.ultrahook.com
Problem
When I send a webhook from Stripe I get Test webhook sent successfully
In the terminal ultrahook I get this
[2017-05-31 19:26:04] POST http://localhost:8888/stripe/webhook - 200
But it seems the handleWebhook function is not triggered. It does not stop on a break point neither die('test')
I tried php artisan route:clear php artisan config:clear. I don't know wether it is normal or not, but I do not see anything in the network section in the Chrome Inspector
Add the following line in your .env
CASHIER_ENV=testing
Laravel/Cashier checks if your call to the webhook has a valid event id.
To verify this, eventExistsOnStripe calls back stripe servers with this event id to check its existence.
Here is the main webhook entry point from Laravel/Cashier 7.0:
public function handleWebhook(Request $request)
{
$payload = json_decode($request->getContent(), true);
if (! $this->isInTestingEnvironment() && ! $this->eventExistsOnStripe($payload['id'])) {
return;
}
$method = 'handle'.studly_case(str_replace('.', '_', $payload['type']));
if (method_exists($this, $method)) {
return $this->{$method}($payload);
} else {
return $this->missingMethod();
}
}
isInTestingEnvironment just check whether we are in a testing environnment or not : Thank you Cpt Obvious :)
protected function isInTestingEnvironment()
{
return getenv('CASHIER_ENV') === 'testing';
}

Console.Terminate event on a specific command

I just discovered that it exists a ConsoleEvents::TEMINATE event in Symfony.
I want to use it to execute some additional process after the command execution (and not delaying the command).
But the fact is that i want to execute some process when a specific command is finish, not for all the commands (because i think that consoleevent.terminate is fired for all the commands.
I really don't know how to do that.
Regards.
You can access instance of the command from ConsoleTerminateEvent
It's almost copy paste from documentation of Console component. with full symfony registering listener looks a little different but you should get the idea.
$dispatcher->addListener(
ConsoleEvents::TERMINATE,
function(ConsoleTerminateEvent $event) {
$command = $event->getCommand();
// if it's not the command you want
if (!$command instanceof YourDesiredCommand) {
return;
}
// put your logic here
}
);

Laravel Queue using Beanstalkd Failing

I've tried to using queue for everytime user register and send an email to them to verify.
I'm doing it successfully using Laravel 5.1
I just wandering how can I can stop current queue if I got an error and then when I fix it I restart the job from the last queue?.
How about the error like this:
[InvalidArgumentException]
View [emails.versify_email] not found.
[InvalidArgumentException]
View [emails.versify_email] not found.
[InvalidArgumentException]
View [emails.versify_email] not found.
I've tried at homestead using:
public function failed(){
//I've tried send email but it not sending
}
or at AppServiceProvider
Queue::failing(function ($connection, $job, $data) {
$user ='mymail#gmail.com';
Mail::send('emails.fail_queue', ['user' => $user], function ($m) use ($user) {
$m->subject('Failing:' . $user)
->to($user);
});
});
None of the them is working.
what should i do if its like that when happened at production?.
When an exception is thrown from the handler Laravel tries to release the job back to the queue unless it is explicitly deleted.
https://github.com/laravel/framework/blob/5.1/src/Illuminate/Queue/Worker.php#L198-L227
You can use the $delay parameter to put back in the queue with delay. Or better just bury the job yourself, if you are able to detect the issue.
$this->job->bury()

Laravel 4.2 Queue - force job fail

I want to do something like this in my fire method:
class MyClass{
public function fire($job) {
if(something) {
$job->fail();
}else {
//processing
}
$job->delete();
}
There is no such method as fail(), is it possible to do something like this?
There is no such thing as fail a job but what you can do:
release it back to the queue with
$job->release();
After defined number of attempts it will end up in failed jobs table.
throw an exception. The job will be released back to the queue on it's own.
if you're using beanstalkd as a queue driver you can bury a job
$job->bury();
If your condition is unrecoverable you can log this fact and simply delete the job.

Categories