My code is working prefectly on sending http request and in case a website is down or a response code is not 200, it sends a slack notification. What I am trying to figure out now is, in the notifications table I have check_frequency and alert_frequence. If a website is down, instead of using check frequency to calculate the elapse time, it should use alert_frequence.
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use App\Utilities\Reporter;
use GuzzleHttp\Exception\ClientException;
use App\Notification;
use App\Status;
use App\Setting;
class GuzzleController extends Controller
{
private $default_check_frequency;
protected $client;
protected $reporter;
public function __construct()
{
$this->client = new Client;
$this->reporter = new Reporter;
$this->default_check_frequency = Setting::defaultCheckFrequency();
}
public function status()
{
$notifications = Notification::where('active', 1)->get();
$status = Status::where('name', 'health')->first();
foreach ($notifications as $notification) {
$this->updateStatus($notification, $status);
}
}
private function updateStatus(Notification $notification, Status $status)
{
$status_health = $notification->status('health');
$frequency = $this->getFrequency($notification);
$elapsed_time = \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes();
if($elapsed_time >= $frequency) {
$response = $this->client->get($notification->website_url, [
'http_errors' => false
]);
$resCode = $response->getStatusCode();
$notification->statuses()->attach($status, [
'values' => $resCode === 200 ? 'up' : 'down'
]);
if($resCode != 200){
/* how to send slack to different slach channels, now it is sending only to one channel!*/
$this->reporter->slack($notification->website_url.':'.' is down'. ' please check your email for the status code!'.' #- '.$notification->email,
$notification->slack_channel);
$this->reporter->mail($notification->email,$resCode );
}
}
}
private function getFrequency(Notification $notification)
{
return isset($notification->check_frequency)
? intval($notification->check_frequency)
: $this->default_check_frequency;
}
}
I'm not sure this is what you need, but here's what you can do to select a different column from your table, depending on the status:
<?php
class GuzzleController extends Controller
{
private $default_check_frequency;
protected $client;
protected $reporter;
public function __construct()
{
$this->client = new Client;
$this->reporter = new Reporter;
$this->default_check_frequency = Setting::defaultCheckFrequency();
}
public function status()
{
$notifications = Notification::where('active', 1)->get();
$status = Status::where('name', 'health')->first();
foreach ($notifications as $notification) {
$this->updateStatus($notification, $status);
}
}
private function updateStatus(Notification $notification, Status $status)
{
$status_health = $notification->status('health');
/// move it here
$response = $this->client->get($notification->website_url, [
'http_errors' => false
]);
$resCode = $response->getStatusCode();
/// --- end
$frequency = $this->getFrequency($notification, $resCode);
$elapsed_time = \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes();
if($elapsed_time >= $frequency) {
$notification->statuses()->attach($status, [
'values' => $resCode === 200 ? 'up' : 'down'
]);
if($resCode != 200){
/* how to send slack to different slach channels, now it is sending only to one channel!*/
$this->reporter->slack($notification->website_url.':'.' is down'. ' please check your email for the status code!'.' #- '.$notification->email,
$notification->slack_channel);
$this->reporter->mail($notification->email,$resCode );
}
}
}
private function getFrequency(Notification $notification, $resCode)
{
/// -- select your column here
$column = $resCode == '200' ? 'check_frequency' : 'alert_frequence';
return isset($notification->{$column})
? intval($notification->{$column})
: $this->default_check_frequency;
}
}
And I took the liberty to refactor it, separating method concerns:
<?php
use Carbon\Carbon;
class GuzzleController extends Controller
{
private $default_check_frequency;
protected $client;
protected $reporter;
public function __construct()
{
$this->client = new Client;
$this->reporter = new Reporter;
$this->default_check_frequency = Setting::defaultCheckFrequency();
}
private function addStatusToNotification(Notification $notification, Status $status, $resCode)
{
$notification->statuses()->attach($status, [
'values' => $resCode === 200
? 'up'
: 'down'
]);
}
private function report(Notification $notification, $resCode)
{
/* how to send slack to different slach channels, now it is sending only to one channel!*/
$this->reporter->slack($notification->website_url . ':' . ' is down' . ' please check your email for the status code!' . ' #- ' . $notification->email,
$notification->slack_channel);
$this->reporter->mail($notification->email, $resCode);
}
private function sendNotification(Notification $notification, Status $status, $status_health, $frequency, $resCode)
{
$elapsed_time = Carbon::parse($status_health['timestamp'])->diffInMinutes();
if ($elapsed_time >= $frequency) {
$this->addStatusToNotification($notification, $status, $resCode);
if ($resCode != 200) {
$this->report($notification, $resCode);
}
}
}
public function status()
{
$notifications = Notification::where('active', 1)->get();
$status = Status::where('name', 'health')->first();
foreach ($notifications as $notification) {
$this->updateStatus($notification, $status);
}
}
private function updateStatus(Notification $notification, Status $status)
{
$resCode = $this->getStatusCode($notification->website_url);
$this->sendNotification(
$notification,
$status,
$notification->status('health'),
$this->getFrequency($notification, $resCode),
$resCode
);
}
private function getFrequency(Notification $notification, $resCode)
{
$column = $resCode == '200' ? 'check_frequency' : 'alert_frequence';
return isset($notification->{$column})
? intval($notification->{$column})
: $this->default_check_frequency;
}
private function getStatusCode($url)
{
$response = $this->client->get($url, [
'http_errors' => false
]);
return $response->getStatusCode();
}
}
Related
I've set an OIDC authentication with a custom authenticator as follow:
class SsoAuthenticator implements AuthenticatorInterface, AuthenticationEntryPointInterface
{
private UserProviderInterface $user_provider;
private ?LoggerInterface $logger;
public function __construct(LdapUserRepository $ldap_user_repository, UserProviderInterface $user_provider, LoggerInterface $logger = null)
{
$this->user_provider = $user_provider;
$this->logger = $logger;
$this->ldap_user_repository = $ldap_user_repository;
}
public function start(Request $request, AuthenticationException $authException = null): Response
{
$response = new Response();
$response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'emmaus.example.com'));
$response->setStatusCode(401);
return $response;
}
public function supports(Request $request): ?bool
{
return $request->headers->has('Authorization') || $request->get('token');
}
public function authenticate(Request $request): Passport
{
$oidc = new Oidc($this->ldap_user_repository);
$token = $request->get('token');
$decoded_token = $oidc->decodeToken($token);
$user_name = $oidc = $oidc->getUserName($decoded_token);
if(!(is_a($this->user_provider, UserProviderInterface::class)))
{
throw new AuthenticationException('error forbidden buddy');
}
$user_badge = new UserBadge($user_name);
$credentials = new BadgeCredentials();
return new Passport($user_badge, $credentials);
}
public function createToken(Passport $passport, string $firewallName): TokenInterface
{
return new UsernamePasswordToken($passport->getUser(), $firewallName, $passport->getUser()->getRoles());
}
public function createAuthenticatedToken(PassportInterface $passport, string $firewallName): TokenInterface
{
return new OidcToken(['ROLE_USER'], null);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
$oidc = new Oidc($this->ldap_user_repository);
$token = $request->get('token') ? $request->get('token') : $request->get('Authorization');
$decoded_token = $oidc->decodeToken($token);
$user_identifier = $oidc->getUserName($decoded_token);
$user = $this->ldap_user_repository->findOneBy(['username' => $user_identifier]);
$last_name = $user->getLastName();
$first_name = $user->getFirstName();
$roles = $user->getRoles();
$email = $user->getEmail();
$group_results = array();
$groups = $user->getGroupBase();
foreach($groups as $group)
{
array_push($group_results, $group->getName());
}
$token = $request->get('token') ? $request->get('token') : $request->headers->has('Authorization');
$_SESSION['token_lemon_ldap'] = $token;
$data = array(
'roles' => $roles,
'userName' => $user_identifier,
'firstName' => $first_name,
'lastName' => $last_name,
'email' => $email,
'token' => $token,
'groups' => $group_results
);
return new Response(
json_encode($data)
);
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$oidc = new Oidc($this->ldap_user_repository);
$decoded_token = $oidc->decodeToken($request->get('token'));
try
{
return $this->start($request, $exception);
}catch(UnexpectedValueException $exception)
{
throw new $exception('wrong number of segment');
}
}
}
?>
I've the authorization to access resources from API after successful authentication, but when I'm fetching response from controller, it return onAutenticationSucess() response's data at each request, and can't access data from controllers, do you have an idea what i'm missing? I'm looking at session or kernel.response, but can't make my head around a proper solution.
Thanks
I create a service to encrypt and decrypt my data in my database.
So when I create a new Fiche or update one, I encrypt the name and the surname
Here my subscriber FicheEntitySubscriber :
class FicheEntitySubscriber implements EventSubscriberInterface
{
private $security;
private $encryptionService;
public function __construct(Security $security, EncryptionService $encryptionService)
{
$this->security = $security;
$this->encryptionService = $encryptionService;
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => ['setFicheEntity', 10],
BeforeEntityUpdatedEvent::class => ['setFicheEntity', 10]
];
}
/**
* #throws Exception
*/
public function setFicheEntity(AbstractLifecycleEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof FicheEntity)) {
return;
}
if ($event instanceof BeforeEntityPersistedEvent) {
$entity->setUtilisateur($this->security->getUser());
}
$entity->setNom($this->encryptionService->encrypt_decrypt('encrypt', mb_strtoupper($entity->getNom())));
$entity->setPrenom($this->encryptionService->encrypt_decrypt('encrypt', mb_strtoupper($entity->getPrenom())));
}
}
Here my FicheController :
class FicheEntityCrudController extends AbstractCrudController
{
private $_adminContextFactory;
private $encryptService;
private $ficheEntityRepo;
public function __construct(AdminContextFactory $adminContextFactory, EncryptionService $encryptionService, FicheEntityRepository $ficheEntityRepo)
{
$this->_adminContextFactory = $adminContextFactory;
$this->encryptService = $encryptionService;
$this->ficheEntityRepo = $ficheEntityRepo;
}
public static function getEntityFqcn(): string
{
return FicheEntity::class;
}
public function configureCrud(Crud $crud): Crud
{
return $crud
->setEntityLabelInPlural('Fiches')
->setEntityLabelInSingular('Fiche informative')
->setSearchFields(['nom', 'prenom', 'nomAntibio'])
->setPaginatorPageSize(10)
->setPaginatorRangeSize(2);
}
public function configureFilters(Filters $filters): Filters
{
return $filters
->add(TextFilter::new('nomAntibio')->setLabel('Nom ATB'))
->add(DateTimeFilter::new('dateDebut')->setLabel('Date Debut'))
->add(DateTimeFilter::new('dateRappel3Jour')->setLabel('Rappel 3e Jour'))
->add(DateTimeFilter::new('dateRappel7Jour')->setLabel('Rappel 7e Jours'));
}
public function configureActions(Actions $actions): Actions
{
$export = Action::new('exportAction', 'Export')
->setIcon('fa fa-download')
->linkToCrudAction('exportAction')
->setCssClass('btn')
->createAsGlobalAction();
return $actions
->add(Crud::PAGE_INDEX, $export);
}
public function exportAction(Request $request): Response
{
$context = $this->_getEasyAdminRefererContext($request);
$searchDto = $this->_adminContextFactory->getSearchDto($request, $context->getCrud());
$fields = FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
$filters = $this->get(FilterFactory::class)->create($context->getCrud()->getFiltersConfig(), $fields, $context->getEntity());
$result = $this->createIndexQueryBuilder(
$searchDto, $context->getEntity(), $fields, $filters
)
->getQuery()->getResult();
$data = [];
/**
* #var $record FicheEntity
*/
foreach ($result as $record) {
$data[] = [
'Nom Complet' => $record->getFullname(),
'Chambre' => $record->getChambre(),
'Date Debut' => $record->getDateDebut()->format('y-m-d'),
'Duree ATB' => $record->getDureeJour(),
'Nom ATB' => $record->getNomAntibio(),
'Rappel 3e Jour' => ($record->getDateRappel3Jour() !== null ? $record->getDateRappel3Jour()->format('y-m-d') : $record->getDateRappel3Jour()),
'Réévalué' => ($record->getDateRappel3Jour() !== null ? ($record->getReevalue() === true ? 'oui' : 'non') : ''),
'Rappel 7e Jour' => ($record->getDateRappel7Jour() !== null ? $record->getDateRappel7Jour()->format('y-m-d') : $record->getDateRappel7Jour()),
'Justifié' => ($record->getDateRappel7Jour() !== null ? ($record->getJustifie() === true ? 'oui' : 'non') : ''),
'Pathologie' => $record->getPathologie(),
'Hospitalier' => ($record->getHospitalier() === true ? 'oui' : '')
];
}
$filename = 'export_fiche_' . date_create()->format('d-m-y H:i:s') . '.csv';
$serializer = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);
$response = new Response($serializer->encode($data, CsvEncoder::FORMAT));
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', "attachment; filename=\"$filename\"");
return $response;
}
private function _getEasyAdminRefererContext(Request $request)
{
\parse_str(\parse_url($request->query->get(EA::REFERRER))[EA::QUERY], $referrerQuery);
if (array_key_exists(EA::FILTERS, $referrerQuery)) {
$request->query->set(EA::FILTERS, $referrerQuery);
}
return $request->attributes->get(EA::CONTEXT_REQUEST_ATTRIBUTE);
}
public function configureFields(string $pageName): iterable
{
return [
IntegerField::new('id')->hideOnForm()->hideOnIndex(),
TextField::new('nom')->hideOnIndex()->setColumns(6),
TextField::new('prenom')->hideOnIndex()->setColumns(6),
TextField::new('fullname')->setLabel('Nom complet')->hideOnForm(),
IntegerField::new('chambre')->setColumns(4),
TextField::new('nomAntibio')->setLabel('Nom ATB')->setColumns(4),
IntegerField::new('dureeJour')->setLabel('Durée ATB TTT')->setColumns(4),
DateField::new('dateDebut'),
DateField::new('dateRappel3Jour')->setLabel('Rappel 3e Jour')->hideOnForm(),
BooleanField::new('reevalue')->setLabel('Réévalué')->hideOnForm(),
DateField::new('dateRappel7Jour')->setLabel('Rappel 7e Jour')->hideOnForm(),
BooleanField::new('justifie')->setLabel('Justifié')->hideOnForm(),
TextField::new('pathologie'),
AssociationField::new('utilisateur', 'Admin')->setLabel('Utilisateur')->hideOnForm(),
BooleanField::new('hospitalier')
];
}
My issue is that when I display my list of fiches, I want to decrypt the encrypted data, for now I try :
use the AfterEntityBuiltEvent (did not working)
listen on Event postLoad
create an custom action
but none of these are working. Does someone try something similar ?
Thanks in advance
I have installed Iyzico payment method by Composer and I followed each step in the documentation but
I Am Trying To Load Default Form Of Iyzico Payment
But It's Show Me That Failure Status When i am reloading the page it is just Dispaly the
odeme sayfa and Failure
so how can i do it please
here is my code in controller
public function payment()
{
$iyzico = new Iyzico();
$payment = $iyzico->setForm([
'conversationID' => '123456789',
'price' => '120.0',
])
->paymentForm();
$paymentContent = $payment->getCheckoutFormContent();
$paymentStatus = $payment->getStatus();
return view(
'iyzico',
compact('paymentContent', 'paymentStatus')
);
}
here is iyzico class code
<?php
namespace App\Libraries;
use PhpParser\Node\Expr\Cast\Array_;
class Iyzico
{
protected $options;
protected $request;
protected $basketItems;
public function __construct()
{
$this->options = new \Iyzipay\Options();
$this->options->setApiKey("your api key");
$this->options->setSecretKey("your secret key");
$this->options->setBaseUrl("https://sandbox-api.iyzipay.com");
$this->basketItems = [];
}
public function setForm(array $params)
{
$this->request = new \Iyzipay\Request\CreateCheckoutFormInitializeRequest();
$this->request->setLocale(\Iyzipay\Model\Locale::TR);
$this->request->setConversationId($params['conversationID']);
$this->request->setPrice($params['price']);
return $this;
}
public function setBuyer(array $params)
{
$buyer = new \Iyzipay\Model\Buyer();
$buyer->setId($params['id']);
$buyer->setName($params['name']);
return $this;
}
public function setShipping(array $params)
{
$shippingAddress = new \Iyzipay\Model\Address();
$shippingAddress->setContactName($params['name']);
$this->request->setShippingAddress($shippingAddress);
return $this;
}
public function setBilling(array $params)
{
$billingAddress = new \Iyzipay\Model\Address();
$billingAddress->setContactName($params['name']);
$this->request->setBillingAddress($billingAddress);
return $this;
}
public function setItem(array $items)
{
foreach ($items as $key => $value) {
$basketItem = new \Iyzipay\Model\BasketItem();
$basketItem->setId($value['id']);
$basketItem->setName($value['name']);
array_push($this->basketItems, $basketItem);
}
$this->request->setBasketItems($this->basketItems);
return $this;
}
public function paymentForm()
{
$form = \Iyzipay\Model\CheckoutFormInitialize::create($this->request, $this->options);
return $form;
}
}
here is my iyzico.blade.php page
<article>
<h1>odeme sayfa</h1>
<div>
{{ $paymentContent }}
{{ $paymentStatus }}
<div id="iyzipay-checkout-form" class="responsive"></div>
</div>
</article>
I have below Order Controller and have created Mailable as well. I am stuck at point what argument should be passed so I can pass data on shipped.blade file. I have gone through few examples but couldn't get it working.
Also, where should I use foreach function to attach all items for which order is placed.
class Order extends Controller
{
public function addOrder(Request $req)
{
// User detail
$results = DB::table('users')->get()->where('id' , $req->input('user_id'));
foreach($results as $userrow) {
$address_id = $userrow->address;
}
// Address
$address_query = DB::table('shippings')->get()->where('id' , $address_id);
foreach($address_query as $ad_row) {
$address = $ad_row->address;
$name = $ad_row->name;
}
// Generate Orderid
$order_id = mt_rand();
// Bag total
$amount = DB::table('bag')->where('user_id' , $req->input('user_id'))->where('order_id', 0)->sum('bag.sale_price');
// add order
// get user email
$emailId = DB::table('users')->where('id' , $req->input('user_id'))->value('email');
$addAddress = DB::table('orders')->insert([
'email' => $emailId,
'user_id' => $req->input('user_id'),
'name' => $req->input('name'),
'order_id' => $order_id,
'payment_method'=> $req->input('payment_method'),
'mobile_number'=> $req->input('mobile_number'),
'pincode'=> $req->input('pincode'),
'city'=> $req->input('city'),
'state'=> $req->input('state'),
'house_number'=> $req->input('house_number'),
'address_area'=> $req->input('address_area'),
'landmark'=> $req->input('landmark'),
'amount'=> $amount
]);
if ($addAddress ==1) {
$response = array('message'=>"Order Added" , 'result'=>1);
//update bag items
$affected = DB::table('bag')->where('user_id', $req->input('user_id'))->where('order_id', 0)->update(['order_id' => $order_id]);
Mail::to($emailId)->send(new OrderShipped());
} else {
$response = array('message'=>"Problem in adding order" , 'result'=>0);
}
return $response;
}
}
OrderShipped Mailable
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('orders#factory2homes.com', 'Factory2Homes')
->subject('New Order Received')
->bcc('mail#androidapp.factory2homes.com')
->markdown('emails.orders.shipped');
}
You create public properties on your mailable and then inject them via the constructor
public $prop1;
public $prop2;
...
public function __construct($arg1, $arg2, ...)
{
$this->prop1 = $arg1;
$this->prop2 = $arg2;
...
}
public function build()
{
return $this->from('orders#factory2homes.com', 'Factory2Homes')
->subject('New Order Received')
->bcc('mail#androidapp.factory2homes.com')
->markdown('emails.orders.shipped', ['arg1' => $this->prop1, 'arg2' => $this->prop2, ...]);
}
Mail::to($emailId)->send(new OrderShipped($arg1, $arg2, ...));
I have two tables notification and alerFrequency. they have a one to many relationships respectively. the notification_id is a foreign key in the alerFrequency table. Both tables have models. now what I am trying to do is, to automatically insert data into the alertFrequency table if website is add in the notification table. this is the notification table
<?php
namespace App;
use App\Status;
use App\Notification;
use App\AlertFrequency;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];
public function statuses(){
return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
public function alertFrequencies(){
return $this->hasMany('App\AlertFrequency');
}
public function alert(){
$alert_timestamp = AlertFrequency::with('notification')->orderBy('created_at','desc')->select('created_at')->first();
$alert_timestamp=$alert_timestamp->created_at->toDateTimeString();
if($alert_timestamp==null){
return false;
}
return $alert_timestamp; }
and in the guzzle controller, I am using 3 functions: the add function to add a new alertFrequency into the table (which is not working at all) and the I called it in the sendnotification function, so that if it is time to send notification, it will add a new created_at in the alerFrequency table. Here is the guzzle controller
<?php
namespace App\Http\Controllers;
use \GuzzleHttp\Client;
use App\Utilities\Reporter;
use GuzzleHttp\Exception\ClientException;
use App\Notification;
use App\Status;
use App\Setting;
use Carbon;
use App\AlertFrequency;
class GuzzleController extends Controller
{
private $default_check_frequency;
protected $client;
protected $reporter;
public function __construct()
{
$this->client = new Client();
$this->reporter = new Reporter;
$this->default_check_frequency = Setting::defaultCheckFrequency();
}
private function addStatusToNotification(Notification $notification, Status $status, $resCode)
{
$notification->statuses()->attach($status, [
'values' => strval($resCode)
]);
}
/*function to add new time stamp into the alertFrequency table*/
private function add(Notification $notification, AlertFrequency $alert){
$notification->alertFrequency()->save();
}
private function report(Notification $notification, $resCode)
{
if(empty($resCode)){
$resCode = "no response found";
}
$status = Notification::health($resCode);
$this->reporter->slack($notification->website_url . ':' . ' is '. $status . ' this is the status code!' . ' #- ' .$resCode, $notification->slack_channel);
$this->reporter->mail($notification->email,$notification->website_url.' is '. $status . ' this is the status Code: '. $resCode);
}
private function sendNotification(Notification $notification, $status_health, $alert_frequency, $resCode,$alert)
{
echo "elpse time alert";
var_dump(\Carbon\Carbon::parse($alert)->diffInMinutes());
// If this is the first time we check, OR if the status changed from up to down and vice versa, notify!!!
if (empty($status_health['timestamp']) || Notification::health($resCode) <> Notification::health($status_health['value'])){
$this->report($notification,$resCode);
return;
}
// If the website is (still) down and the alert frequency is exceeded, notify!!!
if(Notification::health($resCode) === 'down' && \Carbon\Carbon::parse($alert)->diffInMinutes() >= $alert_frequency){
$this->report($notification,$resCode);
$this->add($notification,$alert);
}
}
public function status()
{
$notifications = Notification::where('active', 1)->get();
//$alert = AlertFrequency::
$status = Status::where('name', 'health')->first();
foreach ($notifications as $notification) {
$frequency = $this->updateStatus($notification, $status);
if (!empty($frequency)) {
$notification->alertFrequencies()->create([
'notification_id' => $frequency
]);
}
}
}
private function updateStatus(Notification $notification, Status $status)
{
$status_health = $notification->status('health');
$check = empty($status_health['timestamp']);
$elapsed_time = $check ? 10000 : \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes();
$check_frequency = $this->getCheckFrequency($notification);
/* create an attachemtn in to the alerFrequenct table*/
$alert = $notification->alert();
var_dump($alert);
if ($check || $elapsed_time >= $check_frequency) {
$resCode = $this->getStatusCode($notification->website_url);
$this->addStatusToNotification($notification, $status, $resCode);
$this->sendNotification(
$notification,
$status_health,
$this->getAlertFrequency($notification),
$resCode,
$alert
);
}
}
private function getCheckFrequency(Notification $notification)
{
return isset($notification->check_frequency)
? intval($notification->check_frequency)
: $this->default_check_frequency;
}
private function getAlertFrequency(Notification $notification)
{
return isset($notification->alert_frequency)
? intval($notification->alert_frequency)
: $this->default_check_frequency;
}
private function getStatusCode($url)
{
try {
$response = $this->client->get($url, [
'http_errors' => false
]);
return $response->getStatusCode();
} catch (\GuzzleHttp\Exception\ConnectException $e) {
}
}
}