repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Exception/InvalidParameterException.php
src/Exception/InvalidParameterException.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Exception; use Sonata\CoreBundle\Exception\InvalidParameterException as CoreBundleException; if (class_exists(CoreBundleException::class)) { class InvalidParameterException extends CoreBundleException { } } else { /** * @final since sonata-project/notification-bundle 3.13 */ class InvalidParameterException extends \RuntimeException { } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Consumer/Metadata.php
src/Consumer/Metadata.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Consumer; /** * @final since sonata-project/notification-bundle 3.13 */ class Metadata { /** * @var array */ protected $informations; public function __construct(array $informations = []) { $this->informations = $informations; } /** * @return array */ public function getInformations() { return $this->informations; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Consumer/ConsumerEvent.php
src/Consumer/ConsumerEvent.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Consumer; use Sonata\NotificationBundle\Model\MessageInterface; use Symfony\Contracts\EventDispatcher\Event; /** * @final since sonata-project/notification-bundle 3.13 */ class ConsumerEvent extends Event implements ConsumerEventInterface { /** * @var MessageInterface */ protected $message; /** * @var ConsumerReturnInfo */ protected $returnInfo; public function __construct(MessageInterface $message) { $this->message = $message; } public function getMessage() { return $this->message; } /** * @param ConsumerReturnInfo $returnInfo */ public function setReturnInfo($returnInfo) { $this->returnInfo = $returnInfo; } /** * @return ConsumerReturnInfo */ public function getReturnInfo() { return $this->returnInfo; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Consumer/LoggerConsumer.php
src/Consumer/LoggerConsumer.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Consumer; use Psr\Log\LoggerInterface; use Sonata\NotificationBundle\Exception\InvalidParameterException; /** * @final since sonata-project/notification-bundle 3.13 */ class LoggerConsumer implements ConsumerInterface { /** * @var LoggerInterface */ protected $logger; /** * @var string[] */ protected $types = [ 'emerg' => 'emergency', 'alert' => 'alert', 'crit' => 'critical', 'err' => 'error', 'warn' => 'warning', 'notice' => 'notice', 'info' => 'info', 'debug' => 'debug', ]; public function __construct(LoggerInterface $logger) { $this->logger = $logger; } public function process(ConsumerEvent $event) { $message = $event->getMessage(); if (!\array_key_exists($message->getValue('level'), $this->types)) { throw new InvalidParameterException(); } $level = $this->types[$message->getValue('level')]; $this->logger->{$level}($message->getValue('message')); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Consumer/ConsumerReturnInfo.php
src/Consumer/ConsumerReturnInfo.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Consumer; /** * Return informations for comsumers. * * @author Kevin Nedelec <kevin.nedelec@ekino.com> * * @final since sonata-project/notification-bundle 3.13 */ class ConsumerReturnInfo { /** * @var string */ protected $returnMessage; /** * @param string $returnMessage */ public function setReturnMessage($returnMessage) { $this->returnMessage = $returnMessage; } /** * @return string */ public function getReturnMessage() { return $this->returnMessage; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Consumer/SwiftMailerConsumer.php
src/Consumer/SwiftMailerConsumer.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Consumer; use Sonata\NotificationBundle\Model\MessageInterface; /** * @final since sonata-project/notification-bundle 3.13 */ class SwiftMailerConsumer implements ConsumerInterface { /** * @var \Swift_Mailer */ protected $mailer; public function __construct(\Swift_Mailer $mailer) { $this->mailer = $mailer; } public function process(ConsumerEvent $event) { if (!$this->mailer->getTransport()->isStarted()) { $this->mailer->getTransport()->start(); } $exception = false; try { $this->sendEmail($event->getMessage()); } catch (\Exception $e) { $exception = $e; } $this->mailer->getTransport()->stop(); if ($exception) { throw $exception; } } private function sendEmail(MessageInterface $message) { $mail = $this->mailer->createMessage() ->setSubject($message->getValue('subject')) ->setFrom([$message->getValue(['from', 'email']) => $message->getValue(['from', 'name'])]) ->setTo($message->getValue('to')); if ($replyTo = $message->getValue('replyTo')) { $mail->setReplyTo($replyTo); } if ($returnPath = $message->getValue('returnPath')) { $mail->setReturnPath($returnPath); } if ($cc = $message->getValue('cc')) { $mail->setCc($cc); } if ($bcc = $message->getValue('bcc')) { $mail->setBcc($bcc); } if ($text = $message->getValue(['message', 'text'])) { $mail->addPart($text, 'text/plain'); } if ($html = $message->getValue(['message', 'html'])) { $mail->addPart($html, 'text/html'); } if ($attachment = $message->getValue(['attachment', 'file'])) { $attachmentName = $message->getValue(['attachment', 'name']); $mail->attach(new \Swift_Attachment($attachment, $attachmentName)); } $this->mailer->send($mail); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Consumer/ConsumerEventInterface.php
src/Consumer/ConsumerEventInterface.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Consumer; use Sonata\NotificationBundle\Model\MessageInterface; interface ConsumerEventInterface { /** * @return MessageInterface */ public function getMessage(); }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Consumer/ConsumerInterface.php
src/Consumer/ConsumerInterface.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Consumer; interface ConsumerInterface { /** * Process a ConsumerEvent. */ public function process(ConsumerEvent $event); }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Command/RestartCommand.php
src/Command/RestartCommand.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Command; use Sonata\NotificationBundle\Backend\BackendInterface; use Sonata\NotificationBundle\Event\IterateEvent; use Sonata\NotificationBundle\Iterator\ErroneousMessageIterator; use Sonata\NotificationBundle\Model\MessageManagerInterface; use Sonata\NotificationBundle\Selector\ErroneousMessagesSelector; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * @final since sonata-project/notification-bundle 3.13 */ class RestartCommand extends ContainerAwareCommand { public function configure() { $this->setName('sonata:notification:restart'); $this->setDescription('Restart messages with erroneous statuses, only for doctrine backends'); $this->addOption('type', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'List of messages types to restart (separate multiple types with a space)'); $this->addOption('max-attempts', null, InputOption::VALUE_REQUIRED, 'Maximum number of attempts', 6); $this->addOption('attempt-delay', null, InputOption::VALUE_OPTIONAL, 'Min seconds between two attempts', 10); $this->addOption('pulling', null, InputOption::VALUE_NONE, 'Run the command as an infinite pulling loop'); $this->addOption('pause', null, InputOption::VALUE_OPTIONAL, 'Seconds between each data pull (used only when pulling option is set)', 500000); $this->addOption('batch-size', null, InputOption::VALUE_OPTIONAL, 'Number of message to process on each pull (used only when pulling option is set)', 10); } public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('<info>Starting... </info>'); if (!is_numeric($input->getOption('max-attempts'))) { throw new \Exception('Option "max-attempts" is invalid (integer value needed).'); } $pullMode = $input->getOption('pulling'); $manager = $this->getMessageManager(); if ($pullMode) { $messages = new ErroneousMessageIterator( $manager, $input->getOption('type'), $input->getOption('pause'), $input->getOption('batch-size'), $input->getOption('max-attempts'), $input->getOption('attempt-delay') ); } else { $messages = $this->getErroneousMessageSelector()->getMessages( $input->getOption('type'), $input->getOption('max-attempts') ); /* * Check messages count only for not pulling mode * to avoid PHP warning message * since ErroneousMessageIterator does not implement Countable. */ if (0 === \count($messages)) { $output->writeln('Nothing to restart, bye.'); return 0; } } /** @var EventDispatcherInterface $eventDispatcher */ $eventDispatcher = $this->getContainer()->get('event_dispatcher'); foreach ($messages as $message) { $id = $message->getId(); $newMessage = $manager->restart($message); $this->getBackend()->publish($newMessage); $output->writeln(sprintf( 'Reset Message %s <info>#%d</info>, new id %d. Attempt #%d', $newMessage->getType(), $id, $newMessage->getId(), $newMessage->getRestartCount() )); if ($pullMode) { $eventDispatcher->dispatch(new IterateEvent($messages, null, $newMessage), IterateEvent::EVENT_NAME); } } $output->writeln('<info>Done!</info>'); return 0; } /** * Return the erroneous message selector service. * * @return ErroneousMessagesSelector */ protected function getErroneousMessageSelector() { return $this->getContainer()->get('sonata.notification.erroneous_messages_selector'); } /** * @return MessageManagerInterface */ protected function getMessageManager() { return $this->getContainer()->get('sonata.notification.manager.message'); } /** * @return BackendInterface */ protected function getBackend() { return $this->getContainer()->get('sonata.notification.backend'); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Command/CleanupCommand.php
src/Command/CleanupCommand.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Command; use Sonata\NotificationBundle\Backend\BackendInterface; use Sonata\NotificationBundle\Backend\QueueDispatcherInterface; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @final since sonata-project/notification-bundle 3.13 */ class CleanupCommand extends ContainerAwareCommand { public function configure() { $this->setName('sonata:notification:cleanup'); $this->setDescription('Clean up backend message'); } public function execute(InputInterface $input, OutputInterface $output) { $output->write('<info>Starting ... </info>'); $this->getBackend()->cleanup(); $output->writeln('done!'); return 0; } /** * @return BackendInterface */ private function getBackend() { $backend = $this->getContainer()->get('sonata.notification.backend'); if ($backend instanceof QueueDispatcherInterface) { return $backend->getBackend(null); } return $backend; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Command/ListHandlerCommand.php
src/Command/ListHandlerCommand.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @final since sonata-project/notification-bundle 3.13 */ class ListHandlerCommand extends ContainerAwareCommand { public function configure() { $this->setName('sonata:notification:list-handler'); $this->setDescription('List all consumers available'); } public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('<info>List of consumers available</info>'); foreach ($this->getMetadata() as $type => $ids) { foreach ($ids as $id) { $output->writeln(sprintf('<info>%s</info> - <comment>%s</comment>', $type, $id)); } } $output->writeln(' done!'); return 0; } /** * @return array */ private function getMetadata() { return $this->getContainer()->get('sonata.notification.consumer.metadata')->getInformations(); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Command/ListQueuesCommand.php
src/Command/ListQueuesCommand.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Command; use Sonata\NotificationBundle\Backend\QueueDispatcherInterface; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @final since sonata-project/notification-bundle 3.13 */ class ListQueuesCommand extends ContainerAwareCommand { public function configure() { $this->setName('sonata:notification:list-queues'); $this->setDescription('List all queues available'); } public function execute(InputInterface $input, OutputInterface $output) { $backend = $this->getContainer()->get('sonata.notification.backend'); if (!$backend instanceof QueueDispatcherInterface) { $output->writeln( 'The backend class <info>'.\get_class($backend).'</info> does not provide multiple queues.' ); return 0; } $output->writeln('<info>List of queues available</info>'); foreach ($backend->getQueues() as $queue) { $output->writeln(sprintf( 'queue: <info>%s</info> - routing_key: <info>%s</info>', $queue['queue'], $queue['routing_key'] )); } return 0; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Command/ConsumerHandlerCommand.php
src/Command/ConsumerHandlerCommand.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Command; use Sonata\NotificationBundle\Backend\BackendInterface; use Sonata\NotificationBundle\Backend\QueueDispatcherInterface; use Sonata\NotificationBundle\Consumer\ConsumerInterface; use Sonata\NotificationBundle\Event\IterateEvent; use Sonata\NotificationBundle\Exception\HandlingException; use Sonata\NotificationBundle\Model\MessageInterface; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * @final since sonata-project/notification-bundle 3.13 */ class ConsumerHandlerCommand extends ContainerAwareCommand { public function configure() { $this->setName('sonata:notification:start'); $this->setDescription('Listen for incoming messages'); $this->addOption('iteration', 'i', InputOption::VALUE_OPTIONAL, 'Only run n iterations before exiting', false); $this->addOption('type', null, InputOption::VALUE_OPTIONAL, 'Use a specific backed based on a message type, "all" with doctrine backend will handle all notifications no matter their type', null); $this->addOption('show-details', 'd', InputOption::VALUE_OPTIONAL, 'Show consumers return details', true); } public function execute(InputInterface $input, OutputInterface $output) { $startDate = new \DateTime(); $output->writeln(sprintf('[%s] <info>Checking listeners</info>', $startDate->format('r'))); foreach ($this->getNotificationDispatcher()->getListeners() as $type => $listeners) { $output->writeln(sprintf(' - %s', $type)); foreach ($listeners as $listener) { if (!$listener[0] instanceof ConsumerInterface) { throw new \RuntimeException(sprintf( 'The registered service does not implement the ConsumerInterface (class=%s', \get_class($listener[0]) )); } $output->writeln(sprintf(' > %s', \get_class($listener[0]))); } } $type = $input->getOption('type'); $showDetails = $input->getOption('show-details'); $output->write(sprintf('[%s] <info>Retrieving backend</info> ...', $startDate->format('r'))); $backend = $this->getBackend($type); $output->writeln(''); $output->write(sprintf('[%s] <info>Initialize backend</info> ...', $startDate->format('r'))); // initialize the backend $backend->initialize(); $output->writeln(' done!'); if (null === $type) { $output->writeln(sprintf( '[%s] <info>Starting the backend handler</info> - %s', $startDate->format('r'), \get_class($backend) )); } else { $output->writeln(sprintf( '[%s] <info>Starting the backend handler</info> - %s (type: %s)', $startDate->format('r'), \get_class($backend), $type )); } $startMemoryUsage = memory_get_usage(true); $i = 0; $iterator = $backend->getIterator(); foreach ($iterator as $message) { ++$i; if (!$message instanceof MessageInterface) { throw new \RuntimeException('The iterator must return a MessageInterface instance'); } if (!$message->getType()) { $output->write('<error>Skipping : no type defined </error>'); continue; } $date = new \DateTime(); $output->write(sprintf('[%s] <info>%s</info> #%s: ', $date->format('r'), $message->getType(), $i)); $memoryUsage = memory_get_usage(true); try { $start = microtime(true); $returnInfos = $backend->handle($message, $this->getNotificationDispatcher()); $currentMemory = memory_get_usage(true); $output->writeln(sprintf( '<comment>OK! </comment> - %0.04fs, %ss, %s, %s - %s = %s, %0.02f%%', microtime(true) - $start, $date->format('U') - $message->getCreatedAt()->format('U'), $this->formatMemory($currentMemory - $memoryUsage), $this->formatMemory($currentMemory), $this->formatMemory($startMemoryUsage), $this->formatMemory($currentMemory - $startMemoryUsage), ($currentMemory - $startMemoryUsage) / $startMemoryUsage * 100 )); if ($showDetails && null !== $returnInfos) { $output->writeln($returnInfos->getReturnMessage()); } } catch (HandlingException $e) { $output->writeln(sprintf('<error>KO! - %s</error>', $e->getPrevious()->getMessage())); } catch (\Exception $e) { $output->writeln(sprintf('<error>KO! - %s</error>', $e->getMessage())); } $this->getEventDispatcher()->dispatch( new IterateEvent($iterator, $backend, $message), IterateEvent::EVENT_NAME ); if ($input->getOption('iteration') && $i >= (int) $input->getOption('iteration')) { $output->writeln('End of iteration cycle'); return 0; } } return 0; } /** * @param string $type * @param object $backend * * @throws \RuntimeException */ protected function throwTypeNotFoundException($type, $backend) { throw new \RuntimeException( "The requested backend for the type '".$type." 'does not exist. \nMake sure the backend '". \get_class($backend)."' \nsupports multiple queues and the routing_key is defined. (Currently rabbitmq only)" ); } /** * @param $memory * * @return string */ private function formatMemory($memory) { if ($memory < 1024) { return $memory.'b'; } elseif ($memory < 1048576) { return round($memory / 1024, 2).'Kb'; } return round($memory / 1048576, 2).'Mb'; } /** * @param string $type * * @return BackendInterface */ private function getBackend($type = null) { $backend = $this->getContainer()->get('sonata.notification.backend'); if ($type && !\array_key_exists($type, $this->getNotificationDispatcher()->getListeners())) { throw new \RuntimeException(sprintf('The type `%s` does not exist, available types: %s', $type, implode(', ', array_keys($this->getNotificationDispatcher()->getListeners())))); } if (null !== $type && !$backend instanceof QueueDispatcherInterface) { throw new \RuntimeException(sprintf( 'Unable to use the provided type %s with a non QueueDispatcherInterface backend', $type )); } if ($backend instanceof QueueDispatcherInterface) { return $backend->getBackend($type); } return $backend; } /** * @return EventDispatcherInterface */ private function getNotificationDispatcher() { return $this->getContainer()->get('sonata.notification.dispatcher'); } /** * @return EventDispatcherInterface */ private function getEventDispatcher() { return $this->getContainer()->get('event_dispatcher'); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/src/Command/CreateAndPublishCommand.php
src/Command/CreateAndPublishCommand.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @final since sonata-project/notification-bundle 3.13 */ class CreateAndPublishCommand extends ContainerAwareCommand { public function configure() { $this ->setName('sonata:notification:create-and-publish') ->addArgument('type', InputArgument::REQUIRED, 'Type of the notification') ->addArgument('body', InputArgument::REQUIRED, 'Body of the notification (json)'); } public function execute(InputInterface $input, OutputInterface $output) { $type = $input->getArgument('type'); $body = json_decode($input->getArgument('body'), true); if (null === $body) { throw new \InvalidArgumentException('Body does not contain valid json.'); } $this->getContainer() ->get('sonata.notification.backend') ->createAndPublish($type, $body); $output->writeln('<info>Done !</info>'); return 0; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/bootstrap.php
tests/bootstrap.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Doctrine\Deprecations\Deprecation; /* * DO NOT EDIT THIS FILE! * * It's auto-generated by sonata-project/dev-kit package. */ /* * fix encoding issue while running text on different host with different locale configuration */ setlocale(\LC_ALL, 'en_US.UTF-8'); require_once __DIR__.'/../vendor/autoload.php'; if (class_exists(Deprecation::class)) { Deprecation::enableWithTriggerError(); } if (file_exists($file = __DIR__.'/custom_bootstrap.php')) { require_once $file; }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Event/DoctrineOptimizeListenerTest.php
tests/Event/DoctrineOptimizeListenerTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Event; use Doctrine\ORM\EntityManager; use Doctrine\ORM\UnitOfWork; use Doctrine\Persistence\ManagerRegistry; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Backend\BackendInterface; use Sonata\NotificationBundle\Event\DoctrineOptimizeListener; use Sonata\NotificationBundle\Event\IterateEvent; use Sonata\NotificationBundle\Iterator\MessageIteratorInterface; class DoctrineOptimizeListenerTest extends TestCase { public function testWithClosedManager(): void { $this->expectException(\RuntimeException::class); $manager = $this->createMock(EntityManager::class); $manager->expects(static::once())->method('isOpen')->willReturn(false); $registry = $this->createMock(ManagerRegistry::class); $registry->expects(static::once())->method('getManagers')->willReturn([ 'default' => $manager, ]); $optimizer = new DoctrineOptimizeListener($registry); $optimizer->iterate(new IterateEvent( $this->createMock(MessageIteratorInterface::class), $this->createMock(BackendInterface::class) )); } public function testOptimize(): void { $unitofwork = $this->createMock(UnitOfWork::class); $unitofwork->expects(static::once())->method('clear'); $manager = $this->createMock(EntityManager::class); $manager->expects(static::once())->method('isOpen')->willReturn(true); $manager->expects(static::once())->method('getUnitOfWork')->willReturn($unitofwork); $registry = $this->createMock(ManagerRegistry::class); $registry->expects(static::once())->method('getManagers')->willReturn([ 'default' => $manager, ]); $optimizer = new DoctrineOptimizeListener($registry); $optimizer->iterate(new IterateEvent( $this->createMock(MessageIteratorInterface::class), $this->createMock(BackendInterface::class) )); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Iterator/MessageManagerMessageIteratorTest.php
tests/Iterator/MessageManagerMessageIteratorTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Iterator; use Doctrine\Persistence\ManagerRegistry; use PHPUnit\Framework\TestCase; /** * @author Kevin Nedelec <kevin.nedelec@ekino.com> */ class MessageManagerMessageIteratorTest extends TestCase { /** * @var ManagerRegistry */ private $registry; protected function setUp(): void { $this->registry = $this->createMock(ManagerRegistry::class); } public function testBufferize(): void { $iterator = new MessageManagerMessageIterator($this->registry, 0); $iterator->_bufferize(); static::assertCount(10, $iterator->getBuffer()); } public function testIterations(): void { $size = 10; $iterator = new MessageManagerMessageIterator($this->registry, 0); $iterator->rewind(); static::assertTrue($iterator->valid()); static::assertNotNull($iterator->current()); $iterator->next(); static::assertTrue($iterator->valid()); static::assertNotNull($iterator->current()); --$size; while (--$size >= 1) { $iterator->next(); } static::assertTrue($iterator->valid()); static::assertNotNull($iterator->current()); } public function testLongForeach(): void { $iterator = new MessageManagerMessageIterator($this->registry, 500000, 2); $count = 0; foreach ($iterator as $message) { ++$count; static::assertNotNull($message); if ($count > 20) { return; } } } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Iterator/MessageManagerMessageIterator.php
tests/Iterator/MessageManagerMessageIterator.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Iterator; use Doctrine\Persistence\ManagerRegistry; use Sonata\NotificationBundle\Iterator\MessageManagerMessageIterator as Iterator; use Sonata\NotificationBundle\Model\Message; use Sonata\NotificationBundle\Tests\Entity\DummyMessageManager; /** * @author Kevin Nedelec <kevin.nedelec@ekino.com> */ class MessageManagerMessageIterator extends Iterator { public function __construct(ManagerRegistry $registry, $pause = 0, $batchSize = 10) { parent::__construct( new DummyMessageManager(Message::class, $registry), [], $pause, $batchSize ); } /** * @param array $types */ public function _bufferize($types = []): void { $this->bufferize($types); } public function getBuffer(): array { return $this->buffer; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Iterator/IteratorProxyMessageIteratorTest.php
tests/Iterator/IteratorProxyMessageIteratorTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Iterator; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Iterator\IteratorProxyMessageIterator; /** * @covers \Sonata\NotificationBundle\Iterator\IteratorProxyMessageIterator */ class IteratorProxyMessageIteratorTest extends TestCase { public function testIteratorProxiesIteratorMethods(): void { $actualIterator = new \ArrayIterator([ 'foo', 'bar', ]); $proxy = new IteratorProxyMessageIterator($actualIterator); foreach ($proxy as $eachKey => $eachEntry) { static::assertNotNull($eachKey); static::assertNotEmpty($eachEntry); } } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Iterator/AMQPMessageIteratorTest.php
tests/Iterator/AMQPMessageIteratorTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Iterator; use Interop\Amqp\AmqpConsumer; use Interop\Amqp\AmqpQueue; use Interop\Amqp\Impl\AmqpMessage; use PhpAmqpLib\Channel\AMQPChannel; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Iterator\AMQPMessageIterator; use Sonata\NotificationBundle\Iterator\MessageIteratorInterface; use Sonata\NotificationBundle\Model\Message; /** * @covers \Sonata\NotificationBundle\Iterator\AMQPMessageIterator */ class AMQPMessageIteratorTest extends TestCase { public function testShouldImplementMessageIteratorInterface(): void { $rc = new \ReflectionClass(AMQPMessageIterator::class); static::assertTrue($rc->implementsInterface(MessageIteratorInterface::class)); } /** * @doesNotPerformAssertions */ public function testCouldBeConstructedWithChannelAndContextAsArguments(): void { new AMQPMessageIterator($this->createChannelStub(), $this->createConsumerMock()); } public function testShouldIterateOverThreeMessagesAndExit(): void { $firstMessage = new AmqpMessage('{"body": {"value": "theFirstMessageBody"}, "type": "aType", "state": "aState"}'); $secondMessage = new AmqpMessage('{"body": {"value": "theSecondMessageBody"}, "type": "aType", "state": "aState"}'); $thirdMessage = new AmqpMessage('{"body": {"value": "theThirdMessageBody"}, "type": "aType", "state": "aState"}'); $consumerMock = $this->createConsumerMock('aQueueName'); $consumerMock ->expects(static::exactly(4)) ->method('receive') ->willReturnOnConsecutiveCalls($firstMessage, $secondMessage, $thirdMessage, null); $iterator = new AMQPMessageIterator($this->createChannelStub(), $consumerMock); $values = []; foreach ($iterator as $message) { /* @var Message $message */ static::assertInstanceOf(Message::class, $message); static::assertInstanceOf(\Interop\Amqp\AmqpMessage::class, $message->getValue('interopMessage')); static::assertInstanceOf(\PhpAmqpLib\Message\AMQPMessage::class, $message->getValue('AMQMessage')); $values[] = $message->getValue('value'); } static::assertSame(['theFirstMessageBody', 'theSecondMessageBody', 'theThirdMessageBody'], $values); } /** * @param mixed $queueName * * @return AmqpConsumer&MockObject */ private function createConsumerMock($queueName = null) { $queue = $this->createMock(AmqpQueue::class); $queue ->method('getQueueName') ->willReturn($queueName); $consumer = $this->createMock(AmqpConsumer::class); $consumer ->method('getQueue') ->willReturn($queue); return $consumer; } /** * @return AMQPChannel&Stub */ private function createChannelStub() { return $this->createStub(AMQPChannel::class); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Entity/DummyMessageManager.php
tests/Entity/DummyMessageManager.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Entity; use Doctrine\ORM\QueryBuilder; use Doctrine\Persistence\ManagerRegistry; use Sonata\DatagridBundle\Pager\Doctrine\Pager; use Sonata\DatagridBundle\Pager\PagerInterface; use Sonata\NotificationBundle\Model\MessageInterface; use Sonata\NotificationBundle\Model\MessageManagerInterface; final class DummyMessageManager implements MessageManagerInterface { /** * @var ManagerRegistry */ private $registry; /** * @phpstan-var class-string */ private $class; /** * @phpstan-param class-string $class */ public function __construct(string $class, ManagerRegistry $registry) { $this->registry = $registry; $this->class = $class; } public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null): array { $result = []; while (null !== $limit && $limit > 0) { $result[$limit] = new Message(); --$limit; } return $result; } public function findByTypes(array $types, $state, $batchSize): array { $result = []; while (null !== $batchSize && $batchSize > 0) { $result[$batchSize] = new Message(); --$batchSize; } return $result; } public function save($entity, $andFlush = true): void { } public function getClass(): string { return $this->class; } public function findAll(): array { return []; } public function findOneBy(array $criteria, ?array $orderBy = null): ?object { return null; } public function find($id): ?object { return null; } public function create(): object { return new $this->class(); } public function delete($entity, $andFlush = true): void { } public function getTableName(): string { throw new \LogicException('Not implemented.'); } public function getConnection() { return $this->registry->getConnection(); } public function countStates(): int { return 0; } public function cleanup($maxAge): void { } public function cancel(MessageInterface $message): void { } public function restart(MessageInterface $message): object { return $message; } public function findByAttempts(array $types, $state, $batchSize, $maxAttempts = null, $attemptDelay = 10): array { return []; } public function getPager(array $criteria, int $page, int $limit = 10, array $sort = []): PagerInterface { return Pager::create($this->createStub(QueryBuilder::class), $limit, $page); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Entity/MessageManagerTest.php
tests/Entity/MessageManagerTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Entity; use Doctrine\ORM\AbstractQuery; use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\QueryBuilder; use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\Mapping\ClassMetadata; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Entity\BaseMessage; use Sonata\NotificationBundle\Entity\MessageManager; use Sonata\NotificationBundle\Model\MessageInterface; class MessageManagerTest extends TestCase { public function testCancel(): void { $manager = $this->createMessageManager(); $message = $this->getMessage(); $manager->cancel($message); static::assertTrue($message->isCancelled()); } public function testRestart(): void { $manager = $this->createMessageManager(); // test un-restartable status static::assertNull($manager->restart($this->getMessage(MessageInterface::STATE_OPEN))); static::assertNull($manager->restart($this->getMessage(MessageInterface::STATE_CANCELLED))); static::assertNull($manager->restart($this->getMessage(MessageInterface::STATE_IN_PROGRESS))); $message = $this->getMessage(MessageInterface::STATE_ERROR); $message->setRestartCount(12); $newMessage = $manager->restart($message); static::assertSame(MessageInterface::STATE_OPEN, $newMessage->getState()); static::assertSame(13, $newMessage->getRestartCount()); } public function testGetPager(): void { $self = $this; $this ->getMessageManager(static function ($qb) use ($self) { $qb->expects($self->once())->method('getRootAliases')->willReturn(['m']); $qb->expects($self->never())->method('andWhere'); $qb->expects($self->once())->method('setParameters')->with([]); $qb->expects($self->once())->method('orderBy')->with( $self->equalTo('m.type'), $self->equalTo('ASC') ); }) ->getPager([], 1); } public function testGetPagerWithInvalidSort(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Invalid sort field \'invalid\' in \'Sonata\\NotificationBundle\\Entity\\BaseMessage\' class'); $this ->getMessageManager(static function ($qb) { }) ->getPager([], 1, 10, ['invalid' => 'ASC']); } public function testGetPagerWithMultipleSort(): void { $self = $this; $this ->getMessageManager(static function ($qb) use ($self) { $qb->expects($self->once())->method('getRootAliases')->willReturn(['m']); $qb->expects($self->never())->method('andWhere'); $qb->expects($self->once())->method('setParameters')->with([]); $qb->expects($self->exactly(2))->method('orderBy')->with( $self->logicalOr( $self->equalTo('m.type'), $self->equalTo('m.state') ), $self->logicalOr( $self->equalTo('ASC'), $self->equalTo('DESC') ) ); $qb->expects($self->once())->method('setParameters')->with($self->equalTo([])); }) ->getPager([], 1, 10, [ 'type' => 'ASC', 'state' => 'DESC', ]); } public function testGetPagerWithOpenedMessages(): void { $self = $this; $this ->getMessageManager(static function ($qb) use ($self) { $qb->expects($self->once())->method('getRootAliases')->willReturn(['m']); $qb->expects($self->once())->method('andWhere')->with($self->equalTo('m.state = :state')); $qb->expects($self->once())->method('setParameters')->with($self->equalTo([ 'state' => MessageInterface::STATE_OPEN, ])); }) ->getPager(['state' => MessageInterface::STATE_OPEN], 1); } public function testGetPagerWithCanceledMessages(): void { $self = $this; $this ->getMessageManager(static function ($qb) use ($self) { $qb->expects($self->once())->method('getRootAliases')->willReturn(['m']); $qb->expects($self->once())->method('andWhere')->with($self->equalTo('m.state = :state')); $qb->expects($self->once())->method('setParameters')->with($self->equalTo([ 'state' => MessageInterface::STATE_CANCELLED, ])); }) ->getPager(['state' => MessageInterface::STATE_CANCELLED], 1); } public function testGetPagerWithInProgressMessages(): void { $self = $this; $this ->getMessageManager(static function ($qb) use ($self) { $qb->expects($self->once())->method('getRootAliases')->willReturn(['m']); $qb->expects($self->once())->method('andWhere')->with($self->equalTo('m.state = :state')); $qb->expects($self->once())->method('setParameters')->with($self->equalTo([ 'state' => MessageInterface::STATE_IN_PROGRESS, ])); }) ->getPager(['state' => MessageInterface::STATE_IN_PROGRESS], 1); } protected function getMessageManager($qbCallback): MessageManager { $query = $this->getMockForAbstractClass( AbstractQuery::class, [], '', false, true, true, ['execute', 'getSingleScalarResult'] ); $query->method('execute')->willReturn(true); $query->method('getSingleScalarResult')->willReturn(1); $qb = $this->getMockBuilder(QueryBuilder::class) ->setConstructorArgs([$this->createMock(EntityManager::class)]) ->getMock(); $qb->method('select')->willReturn($qb); $qb->method('getQuery')->willReturn($query); $qbCallback($qb); $repository = $this->createMock(EntityRepository::class); $repository->method('createQueryBuilder')->willReturn($qb); $metadata = $this->createMock(ClassMetadata::class); $metadata->method('getFieldNames')->willReturn([ 'state', 'type', ]); $em = $this->createMock(EntityManager::class); $em->method('getRepository')->willReturn($repository); $em->method('getClassMetadata')->willReturn($metadata); $registry = $this->createMock(ManagerRegistry::class); $registry->method('getManagerForClass')->willReturn($em); return new MessageManager(BaseMessage::class, $registry); } /** * @param int $state */ protected function getMessage($state = MessageInterface::STATE_OPEN): Message { $message = new Message(); $message->setState($state); return $message; } private function createMessageManager(): MessageManager { $repository = $this->createMock(EntityRepository::class); $metadata = $this->createMock(ClassMetadata::class); $metadata->method('getFieldNames')->willReturn([ 'state', 'type', ]); $em = $this->createMock(EntityManager::class); $em->method('getRepository')->willReturn($repository); $em->method('getClassMetadata')->willReturn($metadata); $registry = $this->createMock(ManagerRegistry::class); $registry->method('getManagerForClass')->willReturn($em); return new MessageManager(BaseMessage::class, $registry); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Entity/MessageTest.php
tests/Entity/MessageTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Entity; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Model\MessageInterface; class MessageTest extends TestCase { /** * @dataProvider getBodyValues */ public function testGetValue($body, $names, $expected, $default): void { $message = new Message(); $message->setBody($body); static::assertSame($expected, $message->getValue($names, $default)); } public function testClone(): void { $message = new Message(); $message->setId(42); $message->setState(Message::STATE_ERROR); static::assertTrue($message->isError()); static::assertSame(42, $message->getId()); $newMessage = clone $message; static::assertTrue($newMessage->isOpen()); static::assertNull($newMessage->getId()); } public function testStatuses(): void { $message = new Message(); $message->setState(MessageInterface::STATE_IN_PROGRESS); static::assertTrue($message->isRunning()); $message->setState(MessageInterface::STATE_CANCELLED); static::assertTrue($message->isCancelled()); $message->setState(MessageInterface::STATE_ERROR); static::assertTrue($message->isError()); $message->setState(MessageInterface::STATE_OPEN); static::assertTrue($message->isOpen()); } public function getBodyValues(): array { return [ [['name' => 'foobar'], ['name'], 'foobar', null], [['name' => 'foobar'], ['fake'], 'bar', 'bar'], [['name' => ['foo' => 'bar']], ['name', 'foo'], 'bar', null], ]; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Entity/Message.php
tests/Entity/Message.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Entity; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Entity\BaseMessage; use Sonata\NotificationBundle\Model\MessageInterface; class Message extends BaseMessage { public function setId($id): void { $this->id = $id; } } class BaseMessageTest extends TestCase { public function testClone(): void { $originalMessage = new Message(); $originalMessage->setId(42); $originalMessage->setBody(['body']); $originalMessage->setState(MessageInterface::STATE_ERROR); $clonedMessage = clone $originalMessage; static::assertSame(['body'], $clonedMessage->getBody()); static::assertSame(MessageInterface::STATE_ERROR, $clonedMessage->getState()); static::assertNull($clonedMessage->getId()); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Controller/Api/MessageControllerTest.php
tests/Controller/Api/MessageControllerTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Controller\Api; use FOS\RestBundle\Request\ParamFetcherInterface; use PHPUnit\Framework\TestCase; use Sonata\DatagridBundle\Pager\PagerInterface; use Sonata\NotificationBundle\Controller\Api\MessageController; use Sonata\NotificationBundle\Model\MessageInterface; use Sonata\NotificationBundle\Model\MessageManagerInterface; use Sonata\PageBundle\Model\SiteManagerInterface; use Symfony\Component\Form\Form; use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\Request; /** * @author Hugo Briand <briand@ekino.com> */ class MessageControllerTest extends TestCase { public function testGetMessagesAction(): void { $messageManager = $this->createMock(MessageManagerInterface::class); $pager = $this->createStub(PagerInterface::class); $messageManager->expects(static::once())->method('getPager')->willReturn($pager); $paramFetcher = $this->createMock(ParamFetcherInterface::class); $paramFetcher ->expects(static::exactly(3)) ->method('get') ->withConsecutive( ['page'], ['count'], ['orderBy'] )->willReturnOnConsecutiveCalls( 1, 10, 'ASC' ); $paramFetcher->expects(static::once())->method('all')->willReturn([]); static::assertSame($pager, $this->createMessageController(null, $messageManager)->getMessagesAction($paramFetcher)); } public function testPostMessageAction(): void { $message = $this->createMock(MessageInterface::class); $messageManager = $this->createMock(MessageManagerInterface::class); $messageManager->expects(static::once())->method('save')->willReturn($message); $form = $this->createMock(Form::class); $form->expects(static::once())->method('handleRequest'); $form->expects(static::once())->method('isSubmitted')->willReturn(true); $form->expects(static::once())->method('isValid')->willReturn(true); $form->expects(static::once())->method('getData')->willReturn($message); $formFactory = $this->createMock(FormFactoryInterface::class); $formFactory->expects(static::once())->method('createNamed')->willReturn($form); $message = $this->createMessageController(null, $messageManager, $formFactory)->postMessageAction(new Request()); static::assertInstanceOf(MessageInterface::class, $message); } public function testPostMessageInvalidAction(): void { $message = $this->createMock(MessageInterface::class); $messageManager = $this->createMock(MessageManagerInterface::class); $messageManager->expects(static::never())->method('save')->willReturn($message); $form = $this->createMock(Form::class); $form->expects(static::once())->method('handleRequest'); $form->expects(static::once())->method('isSubmitted')->willReturn(false); $formFactory = $this->createMock(FormFactoryInterface::class); $formFactory->expects(static::once())->method('createNamed')->willReturn($form); $form = $this->createMessageController(null, $messageManager, $formFactory)->postMessageAction(new Request()); static::assertInstanceOf(FormInterface::class, $form); } /** * @param $message * @param $messageManager * @param $formFactory */ public function createMessageController($message = null, $messageManager = null, $formFactory = null): MessageController { if (null === $messageManager) { $messageManager = $this->createMock(SiteManagerInterface::class); } if (null !== $message) { $messageManager->expects(static::once())->method('findOneBy')->willReturn($message); } if (null === $formFactory) { $formFactory = $this->createMock(FormFactoryInterface::class); } return new MessageController($messageManager, $formFactory); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Functional/RoutingTest.php
tests/Functional/RoutingTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Functional; use Nelmio\ApiDocBundle\Annotation\Operation; use Sonata\NotificationBundle\Tests\App\AppKernel; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; /** * @author Javier Spagnoletti <phansys@gmail.com> */ final class RoutingTest extends WebTestCase { /** * @group legacy * * @dataProvider getRoutes */ public function testRoutes(string $name, string $path, array $methods): void { $client = static::createClient(); $router = $client->getContainer()->get('router'); $route = $router->getRouteCollection()->get($name); static::assertNotNull($route); static::assertSame($path, $route->getPath()); static::assertEmpty(array_diff($methods, $route->getMethods())); } public function getRoutes(): iterable { // API if (class_exists(Operation::class)) { yield ['app.swagger_ui', '/api/doc', ['GET']]; yield ['app.swagger', '/api/doc.json', ['GET']]; } else { yield ['nelmio_api_doc_index', '/api/doc/{view}', ['GET']]; } // API - Message yield ['sonata_api_notification_message_get_messages', '/api/notification/messages.{_format}', ['GET']]; yield ['sonata_api_notification_message_post_message', '/api/notification/messages.{_format}', ['POST']]; } protected static function getKernelClass(): string { return AppKernel::class; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Backend/AMQPBackendDispatcherTest.php
tests/Backend/AMQPBackendDispatcherTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Backend; use Enqueue\AmqpLib\AmqpConnectionFactory; use Interop\Amqp\AmqpContext; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Backend\AMQPBackend; use Sonata\NotificationBundle\Backend\AMQPBackendDispatcher; use Sonata\NotificationBundle\Exception\BackendNotFoundException; use Sonata\NotificationBundle\Tests\Mock\AmqpConnectionFactoryStub; class AMQPBackendDispatcherTest extends TestCase { protected function setUp(): void { if (!class_exists(AmqpConnectionFactory::class)) { static::markTestSkipped('enqueue/amqp-lib library is not installed'); } AmqpConnectionFactoryStub::$config = null; AmqpConnectionFactoryStub::$context = null; } public function testThrowIfSettingsMissFactoryClassOptionOnGetContext(): void { $dispatcher = new AMQPBackendDispatcher([], [], 'default', []); $this->expectException(\LogicException::class); $this->expectExceptionMessage('The factory_class option is missing though it is required.'); $dispatcher->getContext(); } public function testThrowIfFactoryClassIsNotRealClass(): void { $dispatcher = new AMQPBackendDispatcher(['factory_class' => 'anInvalidClass'], [], 'default', []); $this->expectException(\LogicException::class); $this->expectExceptionMessage('The factory_class option "anInvalidClass" has to be valid class that implements "Interop\Amqp\AmqpConnectionFactory"'); $dispatcher->getContext(); } public function testThrowIfFactoryClassIsNotInstanceOfAmqpConnectionFactoryInterface(): void { $dispatcher = new AMQPBackendDispatcher(['factory_class' => \stdClass::class], [], 'default', []); $this->expectException(\LogicException::class); $this->expectExceptionMessage('The factory_class option "stdClass" has to be valid class that implements "Interop\Amqp\AmqpConnectionFactory"'); $dispatcher->getContext(); } public function testShouldPassExpectedOptionsToAmqpConnectionFactoryConstructor(): void { $dispatcher = new AMQPBackendDispatcher( [ 'host' => 'theHost', 'port' => 'thePort', 'user' => 'theUser', 'pass' => 'thePass', 'vhost' => 'theVhost', 'factory_class' => AmqpConnectionFactoryStub::class, ], [], 'default', [] ); $dispatcher->getContext(); static::assertSame([ 'host' => 'theHost', 'port' => 'thePort', 'user' => 'theUser', 'pass' => 'thePass', 'vhost' => 'theVhost', ], AmqpConnectionFactoryStub::$config); } public function testShouldReturnExpectedAmqpContext(): void { $expectedContext = $this->createMock(AmqpContext::class); $dispatcher = new AMQPBackendDispatcher( [ 'host' => 'aHost', 'port' => 'aPort', 'user' => 'aUser', 'pass' => 'aPass', 'vhost' => 'aVhost', 'factory_class' => AmqpConnectionFactoryStub::class, ], [], 'default', [] ); AmqpConnectionFactoryStub::$context = $expectedContext; $actualContext = $dispatcher->getContext(); static::assertSame($expectedContext, $actualContext); } public function testQueue(): void { $mock = $this->getMockQueue('foo', 'message.type.foo', static::once()); $mock2 = $this->getMockQueue('bar', 'message.type.foo', static::never()); $fooBackend = ['type' => 'message.type.foo', 'backend' => $mock]; $barBackend = ['type' => 'message.type.bar', 'backend' => $mock2]; $backends = [$fooBackend, $barBackend]; $dispatcher = $this->getDispatcher($backends); $dispatcher->createAndPublish('message.type.foo', []); } public function testDefaultQueue(): void { $mock = $this->getMockQueue('foo', 'message.type.foo', static::once()); $fooBackend = ['type' => 'default', 'backend' => $mock]; $dispatcher = $this->getDispatcher([$fooBackend]); $dispatcher->createAndPublish('some.other.type', []); } public function testDefaultQueueNotFound(): void { $mock = $this->getMockQueue('foo', 'message.type.foo', static::never()); $fooBackend = ['type' => 'message.type.foo', 'backend' => $mock]; $dispatcher = $this->getDispatcher([$fooBackend]); $this->expectException(BackendNotFoundException::class); $dispatcher->createAndPublish('some.other.type', []); } public function testInvalidQueue(): void { $mock = $this->getMockQueue('foo', 'message.type.bar'); $dispatcher = $this->getDispatcher( [['type' => 'bar', 'backend' => $mock]], [['queue' => 'foo', 'routing_key' => 'message.type.bar']] ); $this->expectException(BackendNotFoundException::class); $dispatcher->createAndPublish('message.type.bar', []); } public function testAllQueueInitializeOnce(): void { $queues = [ ['queue' => 'foo', 'routing_key' => 'message.type.foo'], ['queue' => 'bar', 'routing_key' => 'message.type.bar'], ['queue' => 'baz', 'routing_key' => 'message.type.baz'], ]; $backends = []; foreach ($queues as $queue) { $mock = $this->getMockQueue($queue['queue'], $queue['routing_key']); $mock->expects(static::once()) ->method('initialize'); $backends[] = ['type' => $queue['routing_key'], 'backend' => $mock]; } $dispatcher = $this->getDispatcher($backends, $queues); $dispatcher->createAndPublish('message.type.foo', []); $dispatcher->createAndPublish('message.type.foo', []); } protected function getDispatcher(array $backends, array $queues = [['queue' => 'foo', 'routing_key' => 'message.type.foo']]): AMQPBackendDispatcher { $settings = [ 'host' => 'foo', 'port' => 'port', 'user' => 'user', 'pass' => 'pass', 'vhost' => '/', ]; return new AMQPBackendDispatcher($settings, $queues, 'default', $backends); } private function getMockQueue($queue, $type, $called = null): MockObject { $methods = ['createAndPublish', 'initialize']; $args = ['', 'foo', false, 'message.type.foo']; $mock = $this->getMockBuilder(AMQPBackend::class) ->setConstructorArgs($args) ->setMethods($methods) ->getMock(); if (null !== $called) { $mock->expects($called) ->method('createAndPublish'); } return $mock; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Backend/BackendHealthCheckTest.php
tests/Backend/BackendHealthCheckTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Backend; use Laminas\Diagnostics\Result\Success; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Backend\BackendHealthCheck; use Sonata\NotificationBundle\Backend\BackendInterface; class BackendHealthCheckTest extends TestCase { public function testCheck(): void { $result = new Success('Test check', 'OK'); $backend = $this->createMock(BackendInterface::class); $backend->expects(static::once())->method('getStatus')->willReturn($result); $health = new BackendHealthCheck($backend); static::assertSame($result, $health->check()); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Backend/AMQPBackendTest.php
tests/Backend/AMQPBackendTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Backend; use Enqueue\AmqpLib\AmqpConnectionFactory; use Enqueue\AmqpLib\AmqpConsumer; use Enqueue\AmqpLib\AmqpContext; use Interop\Amqp\AmqpBind; use Interop\Amqp\AmqpQueue; use Interop\Amqp\AmqpTopic; use Interop\Amqp\Impl\AmqpBind as ImplAmqpBind; use Interop\Amqp\Impl\AmqpQueue as ImplAmqpQueue; use Interop\Amqp\Impl\AmqpTopic as ImplAmqpTopic; use PhpAmqpLib\Channel\AMQPChannel; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Backend\AMQPBackend; use Sonata\NotificationBundle\Backend\AMQPBackendDispatcher; use Sonata\NotificationBundle\Iterator\AMQPMessageIterator; use Sonata\NotificationBundle\Tests\Mock\AmqpConnectionFactoryStub; class AMQPBackendTest extends TestCase { public const EXCHANGE = 'exchange'; public const QUEUE = 'foo'; public const KEY = 'message.type.foo'; public const DEAD_LETTER_EXCHANGE = 'dlx'; public const DEAD_LETTER_ROUTING_KEY = 'message.type.dl'; public const TTL = 60000; public const PREFETCH_COUNT = 1; protected function setUp(): void { if (!class_exists(AmqpConnectionFactory::class)) { static::markTestSkipped('enqueue/amqp-lib library is not installed'); } AmqpConnectionFactoryStub::$context = null; AmqpConnectionFactoryStub::$config = null; } public function testInitializeWithNoDeadLetterExchangeAndNoDeadLetterRoutingKey(): void { $backend = $this->buildBackend(); $queue = new ImplAmqpQueue(self::QUEUE); $topic = new ImplAmqpTopic(self::EXCHANGE); $contextMock = $this->createMock(AmqpContext::class); $contextMock->expects(static::once()) ->method('createQueue') ->with(static::identicalTo(self::QUEUE)) ->willReturn($queue); $contextMock->expects(static::once()) ->method('declareQueue') ->with(static::identicalTo($queue)) ->willReturnCallback(function (AmqpQueue $queue) { $this->assertTrue((bool) ($queue->getFlags() & AmqpQueue::FLAG_DURABLE)); $this->assertSame([], $queue->getArguments()); }); $contextMock->expects(static::once()) ->method('createTopic') ->with(static::identicalTo(self::EXCHANGE)) ->willReturn($topic); $contextMock->expects(static::once()) ->method('declareTopic') ->with(static::identicalTo($topic)) ->willReturnCallback(function (AmqpTopic $topic) { $this->assertTrue((bool) ($topic->getFlags() & AmqpTopic::FLAG_DURABLE)); $this->assertSame(AmqpTopic::TYPE_DIRECT, $topic->getType()); $this->assertSame([], $topic->getArguments()); }); $contextMock->expects(static::once()) ->method('bind') ->with(static::isInstanceOf(AmqpBind::class)) ->willReturnCallback(function (ImplAmqpBind $bind) use ($queue, $topic) { $this->assertSame($queue, $bind->getTarget()); $this->assertSame($topic, $bind->getSource()); $this->assertSame(self::KEY, $bind->getRoutingKey()); }); AmqpConnectionFactoryStub::$context = $contextMock; $backend->initialize(); } public function testInitializeWithDeadLetterExchangeAndNoDeadLetterRoutingKey(): void { $backend = $this->buildBackend(false, self::DEAD_LETTER_EXCHANGE); $queue = new ImplAmqpQueue(self::QUEUE); $topic = new ImplAmqpTopic(self::EXCHANGE); $deadLetterTopic = new ImplAmqpTopic(self::DEAD_LETTER_EXCHANGE); $contextMock = $this->createMock(AmqpContext::class); $contextMock->expects(static::once()) ->method('createQueue') ->with(static::identicalTo(self::QUEUE)) ->willReturn($queue); $contextMock->expects(static::once()) ->method('declareQueue') ->with(static::identicalTo($queue)) ->willReturnCallback(function (AmqpQueue $queue) { $this->assertTrue((bool) ($queue->getFlags() & AmqpQueue::FLAG_DURABLE)); $this->assertSame(['x-dead-letter-exchange' => self::DEAD_LETTER_EXCHANGE], $queue->getArguments()); }); $contextMock->expects(static::exactly(2)) ->method('createTopic') ->willReturnMap([ [self::EXCHANGE, $topic], [self::DEAD_LETTER_EXCHANGE, $deadLetterTopic], ]); $contextMock->expects(static::atLeastOnce()) ->method('bind') ->with(static::isInstanceOf(AmqpBind::class)); $contextMock->expects(static::exactly(2)) ->method('declareTopic') ->willReturnCallback(function (AmqpTopic $topic) use ($deadLetterTopic) { if ($topic === $deadLetterTopic) { $this->assertTrue((bool) ($topic->getFlags() & AmqpTopic::FLAG_DURABLE)); $this->assertSame(AmqpTopic::TYPE_DIRECT, $topic->getType()); $this->assertSame([], $topic->getArguments()); } }); AmqpConnectionFactoryStub::$context = $contextMock; $backend->initialize(); } public function testInitializeWithDeadLetterExchangeAndDeadLetterRoutingKey(): void { $backend = $this->buildBackend(false, self::DEAD_LETTER_EXCHANGE, self::DEAD_LETTER_ROUTING_KEY); $queue = new ImplAmqpQueue(self::QUEUE); $topic = new ImplAmqpTopic(self::EXCHANGE); $contextMock = $this->createMock(AmqpContext::class); $contextMock->expects(static::once()) ->method('createQueue') ->with(static::identicalTo(self::QUEUE)) ->willReturn($queue); $contextMock->expects(static::once()) ->method('declareQueue') ->with(static::identicalTo($queue)) ->willReturnCallback(function (AmqpQueue $queue) { $this->assertTrue((bool) ($queue->getFlags() & AmqpQueue::FLAG_DURABLE)); $this->assertSame( [ 'x-dead-letter-exchange' => self::DEAD_LETTER_EXCHANGE, 'x-dead-letter-routing-key' => self::DEAD_LETTER_ROUTING_KEY, ], $queue->getArguments() ); }); $contextMock->expects(static::once()) ->method('createTopic') ->with(static::identicalTo(self::EXCHANGE)) ->willReturn($topic); $contextMock->expects(static::once()) ->method('declareTopic') ->with(static::identicalTo($topic)); $contextMock->expects(static::once()) ->method('bind') ->with(static::isInstanceOf(AmqpBind::class)); AmqpConnectionFactoryStub::$context = $contextMock; $backend->initialize(); } public function testInitializeWithTTL(): void { $backend = $this->buildBackend(false, null, null, self::TTL); $queue = new ImplAmqpQueue(self::QUEUE); $topic = new ImplAmqpTopic(self::EXCHANGE); $contextMock = $this->createMock(AmqpContext::class); $contextMock->expects(static::once()) ->method('createQueue') ->with(static::identicalTo(self::QUEUE)) ->willReturn($queue); $contextMock->expects(static::once()) ->method('declareQueue') ->with(static::identicalTo($queue)) ->willReturnCallback(function (AmqpQueue $queue) { $this->assertTrue((bool) ($queue->getFlags() & AmqpQueue::FLAG_DURABLE)); $this->assertSame(['x-message-ttl' => self::TTL], $queue->getArguments()); }); $contextMock->expects(static::once()) ->method('createTopic') ->with(static::identicalTo(self::EXCHANGE)) ->willReturn($topic); $contextMock->expects(static::once()) ->method('declareTopic') ->with(static::identicalTo($topic)); $contextMock->expects(static::once()) ->method('bind') ->with(static::isInstanceOf(AmqpBind::class)); AmqpConnectionFactoryStub::$context = $contextMock; $backend->initialize(); } public function testGetIteratorWithNoPrefetchCount(): void { $backend = $this->buildBackend(); $queue = new ImplAmqpQueue('aQueue'); $consumerMock = $this->createMock(AmqpConsumer::class); $consumerMock->expects(static::once()) ->method('getQueue') ->willReturn($queue); $contextMock = $this->createMock(AmqpContext::class); $contextMock->expects(static::never()) ->method('setQos'); $contextMock->expects(static::once()) ->method('createQueue') ->willReturn($queue); $contextMock->expects(static::once()) ->method('createConsumer') ->with(static::identicalTo($queue)) ->willReturn($consumerMock); $contextMock->expects(static::once()) ->method('getLibChannel') ->willReturn($this->createMock(AMQPChannel::class)); AmqpConnectionFactoryStub::$context = $contextMock; $iterator = $backend->getIterator(); static::assertInstanceOf(AMQPMessageIterator::class, $iterator); } public function testGetIteratorWithPrefetchCount(): void { $backend = $this->buildBackend(false, null, null, null, self::PREFETCH_COUNT); $queue = new ImplAmqpQueue('aQueue'); $consumerMock = $this->createMock(AmqpConsumer::class); $consumerMock->expects(static::once()) ->method('getQueue') ->willReturn($queue); $contextMock = $this->createMock(AmqpContext::class); $contextMock->expects(static::once()) ->method('setQos') ->with(static::isNull(), static::identicalTo(self::PREFETCH_COUNT), static::isFalse()); $contextMock->expects(static::once()) ->method('createQueue') ->willReturn($queue); $contextMock->expects(static::once()) ->method('createConsumer') ->with(static::identicalTo($queue)) ->willReturn($consumerMock); $contextMock->expects(static::once()) ->method('getLibChannel') ->willReturn($this->createMock(AMQPChannel::class)); AmqpConnectionFactoryStub::$context = $contextMock; $iterator = $backend->getIterator(); static::assertInstanceOf(AMQPMessageIterator::class, $iterator); } protected function buildBackend($recover = false, $deadLetterExchange = null, $deadLetterRoutingKey = null, $ttl = null, $prefetchCount = null): AMQPBackend { $backend = new AMQPBackend( self::EXCHANGE, self::QUEUE, $recover, self::KEY, $deadLetterExchange, $deadLetterRoutingKey, $ttl, $prefetchCount ); $settings = [ 'host' => 'foo', 'port' => 'port', 'user' => 'user', 'pass' => 'pass', 'vhost' => '/', 'factory_class' => AmqpConnectionFactoryStub::class, ]; $queues = [ ['queue' => self::QUEUE, 'routing_key' => self::KEY], ]; $dispatcherMock = $this->getMockBuilder(AMQPBackendDispatcher::class) ->setConstructorArgs([$settings, $queues, 'default', [['type' => self::KEY, 'backend' => $backend]]]) ->getMock(); $backend->setDispatcher($dispatcherMock); return $backend; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Backend/RuntimeBackendTest.php
tests/Backend/RuntimeBackendTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Backend; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Backend\RuntimeBackend; use Sonata\NotificationBundle\Exception\HandlingException; use Sonata\NotificationBundle\Model\MessageInterface; use Sonata\NotificationBundle\Tests\Entity\Message; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class RuntimeBackendTest extends TestCase { public function testCreateAndPublish(): void { $dispatcher = $this->createMock(EventDispatcherInterface::class); $backend = new RuntimeBackend($dispatcher); $message = $backend->createAndPublish('foo', ['message' => 'salut']); static::assertInstanceOf(MessageInterface::class, $message); static::assertSame(MessageInterface::STATE_DONE, $message->getState()); static::assertNotNull($message->getCreatedAt()); static::assertSame('foo', $message->getType()); static::assertSame(['message' => 'salut'], $message->getBody()); } public function testIterator(): void { $dispatcher = $this->createMock(EventDispatcherInterface::class); $backend = new RuntimeBackend($dispatcher); static::assertInstanceOf('Iterator', $backend->getIterator()); } public function testHandleSuccess(): void { $message = new Message(); $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher->expects(static::once())->method('dispatch'); $backend = new RuntimeBackend($dispatcher); $backend->handle($message, $dispatcher); static::assertSame(MessageInterface::STATE_DONE, $message->getState()); static::assertNotNull($message->getCreatedAt()); static::assertNotNull($message->getCompletedAt()); } public function testHandleError(): void { $message = new Message(); $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher->expects(static::once())->method('dispatch')->will(static::throwException(new \RuntimeException())); $backend = new RuntimeBackend($dispatcher); $e = false; try { $backend->handle($message, $dispatcher); } catch (HandlingException $e) { } static::assertInstanceOf(HandlingException::class, $e); static::assertSame(MessageInterface::STATE_ERROR, $message->getState()); static::assertNotNull($message->getCreatedAt()); static::assertNotNull($message->getCompletedAt()); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Backend/MessageManagerBackendDispatcherTest.php
tests/Backend/MessageManagerBackendDispatcherTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Backend; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Backend\MessageManagerBackend; use Sonata\NotificationBundle\Backend\MessageManagerBackendDispatcher; use Sonata\NotificationBundle\Model\Message; use Sonata\NotificationBundle\Model\MessageManagerInterface; /** * @author Hugo Briand <briand@ekino.com> */ class MessageManagerBackendDispatcherTest extends TestCase { public function testCreate(): void { $testBackend = $this->createMock(MessageManagerBackend::class); $testBackend->expects(static::once()) ->method('setDispatcher'); $message = new Message(); $message->setType('test'); $message->setBody([]); $testBackend->expects(static::once()) ->method('create') ->willReturn($message); $mMgr = $this->createMock(MessageManagerInterface::class); $mMgrBackend = new MessageManagerBackendDispatcher($mMgr, [], '', [['types' => ['test'], 'backend' => $testBackend]]); static::assertSame($message, $mMgrBackend->create('test', [])); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Backend/MessageManagerBackendTest.php
tests/Backend/MessageManagerBackendTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Backend; use Laminas\Diagnostics\Result\Failure; use Laminas\Diagnostics\Result\Success; use Laminas\Diagnostics\Result\Warning; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Backend\MessageManagerBackend; use Sonata\NotificationBundle\Exception\HandlingException; use Sonata\NotificationBundle\Model\MessageInterface; use Sonata\NotificationBundle\Model\MessageManagerInterface; use Sonata\NotificationBundle\Tests\Entity\Message; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class MessageManagerBackendTest extends TestCase { public function testCreateAndPublish(): void { $message = new Message(); $modelManager = $this->createMock(MessageManagerInterface::class); $modelManager->expects(static::once())->method('save')->willReturn($message); $modelManager->expects(static::once())->method('create')->willReturn($message); $backend = new MessageManagerBackend($modelManager, []); $message = $backend->createAndPublish('foo', ['message' => 'salut']); static::assertInstanceOf(MessageInterface::class, $message); static::assertSame(MessageInterface::STATE_OPEN, $message->getState()); static::assertNotNull($message->getCreatedAt()); static::assertSame('foo', $message->getType()); static::assertSame(['message' => 'salut'], $message->getBody()); } public function testHandleSuccess(): void { $message = new Message(); $modelManager = $this->createMock(MessageManagerInterface::class); $modelManager->expects(static::exactly(2))->method('save')->willReturn($message); $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher->expects(static::once())->method('dispatch'); $backend = new MessageManagerBackend($modelManager, []); $backend->handle($message, $dispatcher); static::assertSame(MessageInterface::STATE_DONE, $message->getState()); static::assertNotNull($message->getCreatedAt()); static::assertNotNull($message->getCompletedAt()); } public function testHandleError(): void { $message = new Message(); $modelManager = $this->createMock(MessageManagerInterface::class); $modelManager->expects(static::exactly(2))->method('save')->willReturn($message); $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher->expects(static::once())->method('dispatch')->will(static::throwException(new \RuntimeException())); $backend = new MessageManagerBackend($modelManager, []); $e = false; try { $backend->handle($message, $dispatcher); } catch (HandlingException $e) { } static::assertInstanceOf(HandlingException::class, $e); static::assertSame(MessageInterface::STATE_ERROR, $message->getState()); static::assertNotNull($message->getCreatedAt()); static::assertNotNull($message->getCompletedAt()); } /** * @dataProvider statusProvider */ public function testStatus($counts, $expectedStatus, $message): void { $modelManager = $this->createMock(MessageManagerInterface::class); $modelManager->expects(static::once())->method('countStates')->willReturn($counts); $backend = new MessageManagerBackend($modelManager, [ MessageInterface::STATE_IN_PROGRESS => 10, MessageInterface::STATE_ERROR => 30, MessageInterface::STATE_OPEN => 100, MessageInterface::STATE_DONE => 10000, ]); $status = $backend->getStatus(); static::assertInstanceOf(\get_class($expectedStatus), $status); static::assertSame($message, $status->getMessage()); } public static function statusProvider(): array { if (!class_exists(Success::class)) { return [[1, 1, 1]]; } $data = []; $data[] = [ [ MessageInterface::STATE_IN_PROGRESS => 11, //here MessageInterface::STATE_ERROR => 31, MessageInterface::STATE_OPEN => 100, MessageInterface::STATE_DONE => 10000, ], new Failure(), 'Too many messages processed at the same time (Database)', ]; $data[] = [ [ MessageInterface::STATE_IN_PROGRESS => 1, MessageInterface::STATE_ERROR => 31, //here MessageInterface::STATE_OPEN => 100, MessageInterface::STATE_DONE => 10000, ], new Failure(), 'Too many errors (Database)', ]; $data[] = [ [ MessageInterface::STATE_IN_PROGRESS => 1, MessageInterface::STATE_ERROR => 1, MessageInterface::STATE_OPEN => 101, //here MessageInterface::STATE_DONE => 10000, ], new Warning(), 'Too many messages waiting to be processed (Database)', ]; $data[] = [ [ MessageInterface::STATE_IN_PROGRESS => 1, MessageInterface::STATE_ERROR => 1, MessageInterface::STATE_OPEN => 100, MessageInterface::STATE_DONE => 10001, //here ], new Warning(), 'Too many processed messages, please clean the database (Database)', ]; $data[] = [ [ MessageInterface::STATE_IN_PROGRESS => 1, MessageInterface::STATE_ERROR => 1, MessageInterface::STATE_OPEN => 1, MessageInterface::STATE_DONE => 1, ], new Success(), 'Ok (Database)', ]; return $data; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Backend/PostponeRuntimeBackendTest.php
tests/Backend/PostponeRuntimeBackendTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Backend; use Laminas\Diagnostics\Result\Success; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Backend\PostponeRuntimeBackend; use Sonata\NotificationBundle\Consumer\ConsumerEventInterface; use Sonata\NotificationBundle\Model\MessageInterface; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; /** * @covers \Sonata\NotificationBundle\Backend\PostponeRuntimeBackend */ class PostponeRuntimeBackendTest extends TestCase { public function testIteratorContainsPublishedMessages(): void { $backend = new PostponeRuntimeBackend( $this->createMock(EventDispatcherInterface::class), true ); $messages = []; $message = $backend->create('foo', []); $messages[] = $message; $backend->publish($message); $message = $backend->create('bar', []); $messages[] = $message; $backend->publish($message); $message = $backend->create('baz', []); $messages[] = $message; $backend->publish($message); $backend->create('not_published', []); $iterator = $backend->getIterator(); foreach ($iterator as $eachKey => $eachMessage) { static::assertSame($messages[$eachKey], $eachMessage); } } public function testNoMessagesOnEvent(): void { $backend = $this->getMockBuilder(PostponeRuntimeBackend::class) ->setMethods(['handle']) ->setConstructorArgs([$this->createMock(EventDispatcherInterface::class)]) ->getMock(); $backend ->expects(static::never()) ->method('handle'); $backend->onEvent(); } public function testLiveEnvironment(): void { $dispatcher = new EventDispatcher(); $backend = new PostponeRuntimeBackend($dispatcher, true); $dispatcher->addListener('kernel.terminate', [$backend, 'onEvent']); $message = $backend->create('notification.demo', []); $backend->publish($message); // This message will not be handled. $backend->create('notification.demo', []); $phpunit = $this; $phpunit->passed = false; $dispatcher->addListener('notification.demo', static function (ConsumerEventInterface $event) use ($phpunit, $message) { $phpunit->assertSame($message, $event->getMessage()); $phpunit->passed = true; }); $dispatcher->dispatch(new GenericEvent(), 'kernel.terminate'); static::assertTrue($phpunit->passed); static::assertSame(MessageInterface::STATE_DONE, $message->getState()); } public function testRecursiveMessage(): void { $dispatcher = new EventDispatcher(); $backend = new PostponeRuntimeBackend($dispatcher, true); $dispatcher->addListener('kernel.terminate', [$backend, 'onEvent']); $message1 = $backend->create('notification.demo1', []); $message2 = $backend->create('notification.demo2', []); $backend->publish($message1); $phpunit = $this; $phpunit->passed1 = false; $phpunit->passed2 = false; $dispatcher->addListener('notification.demo1', static function (ConsumerEventInterface $event) use ($phpunit, $message1, $message2, $backend) { $phpunit->assertSame($message1, $event->getMessage()); $phpunit->passed1 = true; $backend->publish($message2); }); $dispatcher->addListener('notification.demo2', static function (ConsumerEventInterface $event) use ($phpunit, $message2) { $phpunit->assertSame($message2, $event->getMessage()); $phpunit->passed2 = true; }); $dispatcher->dispatch(new GenericEvent(), 'kernel.terminate'); static::assertTrue($phpunit->passed1); static::assertTrue($phpunit->passed2); static::assertSame(MessageInterface::STATE_DONE, $message1->getState()); static::assertSame(MessageInterface::STATE_DONE, $message2->getState()); } public function testStatusIsOk(): void { $backend = new PostponeRuntimeBackend( $this->createMock(EventDispatcherInterface::class), true ); $status = $backend->getStatus(); static::assertInstanceOf(Success::class, $status); } public function testOnCliPublishHandlesDirectly(): void { $backend = $this->getMockBuilder(PostponeRuntimeBackend::class) ->setMethods(['handle']) ->setConstructorArgs([$this->createMock(EventDispatcherInterface::class)]) ->getMock(); $backend ->expects(static::once()) ->method('handle'); $message = $backend->create('notification.demo', []); $backend->publish($message); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Mock/AmqpConnectionFactoryStub.php
tests/Mock/AmqpConnectionFactoryStub.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Mock; use Interop\Amqp\AmqpConnectionFactory; class AmqpConnectionFactoryStub implements AmqpConnectionFactory { public static $config; public static $context; public function __construct($config) { static::$config = $config; } public function createContext() { return static::$context; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/DependencyInjection/ConfigurationTest.php
tests/DependencyInjection/ConfigurationTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\DependencyInjection; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionConfigurationTestCase; use Sonata\NotificationBundle\Admin\MessageAdmin; use Sonata\NotificationBundle\DependencyInjection\Configuration; use Sonata\NotificationBundle\DependencyInjection\SonataNotificationExtension; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; final class ConfigurationTest extends AbstractExtensionConfigurationTestCase { public function testDefault(): void { $this->assertProcessedConfigurationEquals([ 'backend' => 'sonata.notification.backend.runtime', 'queues' => [], 'consumers' => [ 'register_default' => true, ], 'iteration_listeners' => [], 'class' => [ 'message' => 'App\Entity\Message', ], 'admin' => [ 'enabled' => true, 'message' => [ 'class' => MessageAdmin::class, 'controller' => 'SonataNotificationBundle:MessageAdmin', 'translation' => 'SonataNotificationBundle', ], ], ], [ __DIR__.'/../Fixtures/configuration.yaml', ]); } protected function getContainerExtension(): ExtensionInterface { return new SonataNotificationExtension(); } protected function getConfiguration(): ConfigurationInterface { return new Configuration(); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/DependencyInjection/SonataNotificationExtensionTest.php
tests/DependencyInjection/SonataNotificationExtensionTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\DependencyInjection; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase; use Sonata\NotificationBundle\DependencyInjection\SonataNotificationExtension; final class SonataNotificationExtensionTest extends AbstractExtensionTestCase { protected function setUp(): void { parent::setUp(); $this->container->setParameter('kernel.bundles', [ 'SonataDoctrineBundle' => true, 'SonataAdminBundle' => true, ]); } public function testEmptyConfig(): void { $this->load(); $this->assertContainerBuilderHasAlias('sonata.notification.backend', 'sonata.notification.backend.runtime'); $this->assertContainerBuilderHasService('sonata.notification.consumer.swift_mailer'); $this->assertContainerBuilderHasService('sonata.notification.consumer.logger'); $this->assertContainerBuilderHasParameter('sonata.notification.backend', 'sonata.notification.backend.runtime'); } public function testDoNotRegisterDefaultConsumers(): void { $this->load([ 'consumers' => [ 'register_default' => false, ], ]); $this->assertContainerBuilderNotHasService('sonata.notification.consumer.swift_mailer'); $this->assertContainerBuilderNotHasService('sonata.notification.consumer.logger'); $this->assertContainerBuilderNotHasService('sonata.notification.manager.message.default'); $this->assertContainerBuilderNotHasService('sonata.notification.erroneous_messages_selector'); $this->assertContainerBuilderNotHasService('sonata.notification.event.doctrine_optimize'); $this->assertContainerBuilderNotHasService('sonata.notification.event.doctrine_backend_optimize'); $this->assertContainerBuilderHasParameter('sonata.notification.event.iteration_listeners', []); } public function testDoctrineBackendNoConfig(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Please configure the sonata_notification.backends.doctrine section'); $this->load([ 'backend' => 'sonata.notification.backend.doctrine', ]); } public function testDoctrineBackend(): void { $this->load([ 'backend' => 'sonata.notification.backend.doctrine', 'backends' => [ 'doctrine' => null, ], 'consumers' => [ 'register_default' => false, ], ]); $this->assertContainerBuilderHasService('sonata.notification.manager.message.default'); $this->assertContainerBuilderHasService('sonata.notification.erroneous_messages_selector'); $this->assertContainerBuilderHasService('sonata.notification.event.doctrine_optimize'); $this->assertContainerBuilderHasService('sonata.notification.event.doctrine_backend_optimize'); $this->assertContainerBuilderHasParameter('sonata.notification.event.iteration_listeners', [ 'sonata.notification.event.doctrine_backend_optimize', ]); } public function testRabbitMQBackendNoConfig(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Please configure the sonata_notification.backends.rabbitmq section'); $this->load([ 'backend' => 'sonata.notification.backend.rabbitmq', ]); } public function testRabbitMQBackend(): void { $this->load([ 'backend' => 'sonata.notification.backend.rabbitmq', 'backends' => [ 'rabbitmq' => [ 'exchange' => 'logs', ], ], 'consumers' => [ 'register_default' => false, ], ]); $this->assertContainerBuilderNotHasService('sonata.notification.manager.message.default'); $this->assertContainerBuilderNotHasService('sonata.notification.erroneous_messages_selector'); $this->assertContainerBuilderNotHasService('sonata.notification.event.doctrine_optimize'); $this->assertContainerBuilderNotHasService('sonata.notification.event.doctrine_backend_optimize'); $this->assertContainerBuilderHasParameter('sonata.notification.event.iteration_listeners', []); } protected function getContainerExtensions(): array { return [ new SonataNotificationExtension(), ]; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Exception/InvalidParameterExceptionTest.php
tests/Exception/InvalidParameterExceptionTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Exception; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Exception\InvalidParameterException; /** * @author Hugo Briand <briand@ekino.com> */ class InvalidParameterExceptionTest extends TestCase { public function testException(): void { $this->expectException(InvalidParameterException::class); throw new InvalidParameterException(); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/App/AppKernel.php
tests/App/AppKernel.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\App; use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; use FOS\RestBundle\FOSRestBundle; use JMS\SerializerBundle\JMSSerializerBundle; use Nelmio\ApiDocBundle\Annotation\Operation; use Nelmio\ApiDocBundle\NelmioApiDocBundle; use Sonata\Doctrine\Bridge\Symfony\SonataDoctrineBundle; use Sonata\Form\Bridge\Symfony\SonataFormBundle; use Sonata\NotificationBundle\SonataNotificationBundle; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Bundle\SecurityBundle\SecurityBundle; use Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle; use Symfony\Bundle\TwigBundle\TwigBundle; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Routing\RouteCollectionBuilder; final class AppKernel extends Kernel { use MicroKernelTrait; public function __construct() { parent::__construct('test', false); } public function registerBundles(): iterable { return [ new FrameworkBundle(), new SecurityBundle(), new TwigBundle(), new FOSRestBundle(), new SonataDoctrineBundle(), new SonataNotificationBundle(), new JMSSerializerBundle(), new DoctrineBundle(), new NelmioApiDocBundle(), new SwiftmailerBundle(), new SonataFormBundle(), ]; } public function getCacheDir(): string { return $this->getBaseDir().'cache'; } public function getLogDir(): string { return $this->getBaseDir().'log'; } public function getProjectDir(): string { return __DIR__; } protected function configureRoutes(RouteCollectionBuilder $routes): void { if (class_exists(Operation::class)) { $routes->import(__DIR__.'/Resources/config/routing/api_nelmio_v3.yml', '/', 'yaml'); } else { $routes->import(__DIR__.'/Resources/config/routing/api_nelmio_v2.yml', '/', 'yaml'); } } protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void { $loader->load(__DIR__.'/Resources/config/config.yml'); $loader->load(__DIR__.'/Resources/config/security.yml'); $container->setParameter('app.base_dir', $this->getBaseDir()); } private function getBaseDir(): string { return sys_get_temp_dir().'/sonata-notification-bundle/var/'; } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/App/Entity/Message.php
tests/App/Entity/Message.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\App\Entity; use Doctrine\ORM\Mapping as ORM; use Sonata\NotificationBundle\Entity\BaseMessage; /** * @ORM\Entity * @ORM\Table(name="notification__message") */ class Message extends BaseMessage { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ protected $id; }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Consumer/LoggerConsumerTest.php
tests/Consumer/LoggerConsumerTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Consumer; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; use Sonata\NotificationBundle\Consumer\ConsumerEvent; use Sonata\NotificationBundle\Consumer\LoggerConsumer; use Sonata\NotificationBundle\Exception\InvalidParameterException; use Sonata\NotificationBundle\Tests\Entity\Message; class LoggerConsumerTest extends TestCase { /** * @dataProvider calledTypeProvider * * @param $type * @param $calledType */ public function testProcess($type, $calledType): void { $logger = $this->createMock(LoggerInterface::class); $logger->expects(static::once())->method($calledType); $message = new Message(); $message->setBody([ 'level' => $type, 'message' => 'Alert - Area 52 get compromised!!', ]); $event = new ConsumerEvent($message); $consumer = new LoggerConsumer($logger); $consumer->process($event); } /** * @return array[] */ public function calledTypeProvider(): array { return [ ['emerg', 'emergency'], ['alert', 'alert'], ['crit', 'critical'], ['err', 'error'], ['warn', 'warning'], ['notice', 'notice'], ['info', 'info'], ['debug', 'debug'], ]; } public function testInvalidType(): void { $this->expectException(InvalidParameterException::class); $logger = $this->createMock(LoggerInterface::class); $message = new Message(); $message->setBody([ 'level' => 'ERROR', 'message' => 'Alert - Area 52 get compromised!!', ]); $event = new ConsumerEvent($message); $consumer = new LoggerConsumer($logger); $consumer->process($event); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
sonata-project/SonataNotificationBundle
https://github.com/sonata-project/SonataNotificationBundle/blob/bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e/tests/Consumer/SwiftMailerConsumerTest.php
tests/Consumer/SwiftMailerConsumerTest.php
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\NotificationBundle\Tests\Consumer; use PHPUnit\Framework\TestCase; use Sonata\NotificationBundle\Consumer\SwiftMailerConsumer; use Sonata\NotificationBundle\Model\Message; /** * Tests the SwiftMailerConsumer. */ class SwiftMailerConsumerTest extends TestCase { /** * @var SwiftMailerConsumer */ private $consumer; /** * @var \Swift_Mailer */ private $mailer; /** * Initializes some dependencies used by tests. */ protected function setUp(): void { $this->mailer = $this->createMock('Swift_Mailer'); $this->consumer = new SwiftMailerConsumer($this->mailer); } /** * Tests the sendEmail method. */ public function testSendEmail(): void { $message = new Message(); $message->setBody([ 'subject' => 'subject', 'from' => [ 'email' => 'from@mail.fr', 'name' => 'nameFrom', ], 'to' => [ 'to1@mail.fr', 'to2@mail.fr' => 'nameTo2', ], 'replyTo' => [ 'replyTo1@mail.fr', 'replyTo2@mail.fr' => 'nameReplyTo2', ], 'returnPath' => [ 'email' => 'returnPath@mail.fr', ], 'cc' => [ 'cc1@mail.fr', 'cc2@mail.fr' => 'nameCc2', ], 'bcc' => [ 'bcc1@mail.fr', 'bcc2@mail.fr' => 'nameBcc2', ], 'message' => [ 'text' => 'message text', 'html' => 'message html', ], 'attachment' => [ 'file' => 'path to file', 'name' => 'file name', ], ]); $mail = $this->createMock('Swift_Message'); $mail->expects(static::once())->method('setSubject')->with(static::equalTo('subject'))->willReturnSelf(); $mail->expects(static::once())->method('setFrom')->with(static::equalTo(['from@mail.fr' => 'nameFrom']))->willReturnSelf(); $mail->expects(static::once())->method('setTo')->with(static::equalTo(['to1@mail.fr', 'to2@mail.fr' => 'nameTo2']))->willReturnSelf(); $mail->expects(static::once())->method('setReplyTo')->with(static::equalTo(['replyTo1@mail.fr', 'replyTo2@mail.fr' => 'nameReplyTo2']))->willReturnSelf(); $mail->expects(static::once())->method('setReturnPath')->with(static::equalTo(['email' => 'returnPath@mail.fr']))->willReturnSelf(); $mail->expects(static::once()) ->method('setCc') ->with(static::equalTo(['cc1@mail.fr', 'cc2@mail.fr' => 'nameCc2'])) ->willReturnSelf(); $mail->expects(static::once()) ->method('setBcc') ->with(static::equalTo(['bcc1@mail.fr', 'bcc2@mail.fr' => 'nameBcc2'])) ->willReturnSelf(); $mail->expects(static::exactly(2)) ->method('addPart') ->withConsecutive( [static::equalTo('message text'), static::equalTo('text/plain')], [static::equalTo('message html'), static::equalTo('text/html')] ) ->willReturnSelf(); $mail->expects(static::once()) ->method('attach') ->willReturnSelf(); $this->mailer->expects(static::once())->method('createMessage')->willReturn($mail); $method = new \ReflectionMethod($this->consumer, 'sendEmail'); $method->setAccessible(true); $method->invoke($this->consumer, $message); } }
php
MIT
bb87afcd43c3d64e0b92404ceb0bf038c51d8b2e
2026-01-05T04:47:35.154999Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Jobs/IncrementMonitorPageViewJob.php
app/Jobs/IncrementMonitorPageViewJob.php
<?php namespace App\Jobs; use App\Models\Monitor; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Facades\Cache; class IncrementMonitorPageViewJob implements ShouldQueue { use Queueable; /** * The cooldown period in seconds (5 minutes). */ protected const VIEW_COOLDOWN = 300; /** * Create a new job instance. */ public function __construct( public int $monitorId, public string $ipAddress ) { $this->onQueue('default'); } /** * Execute the job. */ public function handle(): void { // Create a unique cache key based on monitor ID and hashed IP $cacheKey = $this->getCacheKey(); // Check if this IP already viewed this monitor recently if (Cache::has($cacheKey)) { return; } // Increment the view count Monitor::where('id', $this->monitorId)->increment('page_views_count'); // Set cooldown to prevent duplicate counts Cache::put($cacheKey, true, self::VIEW_COOLDOWN); } /** * Get the cache key for rate limiting. */ protected function getCacheKey(): string { $ipHash = md5($this->ipAddress); return "monitor_view_{$this->monitorId}_{$ipHash}"; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Jobs/CalculateSingleMonitorUptimeJob.php
app/Jobs/CalculateSingleMonitorUptimeJob.php
<?php namespace App\Jobs; use App\Services\MonitorPerformanceService; use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class CalculateSingleMonitorUptimeJob implements ShouldBeUnique, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public int $monitorId; public string $date; // Job configuration public $tries = 3; public $timeout = 300; // 5 minutes public $backoff = [30, 60, 120]; // Exponential backoff in seconds public $uniqueFor = 3600; // 1 hour uniqueness /** * Get the unique ID for the job. */ public function uniqueId(): string { return "uptime_calc_{$this->monitorId}_{$this->date}"; } /** * The number of seconds after which the job's unique lock will be released. */ public function uniqueFor(): int { return 3600; // 1 hour } /** * Create a new job instance. */ public function __construct(int $monitorId, ?string $date = null) { $this->monitorId = $monitorId; $this->date = $date ?? Carbon::today()->toDateString(); // Set the queue for this job $this->onQueue('uptime-calculations'); } /** * Execute the job. */ public function handle(): void { Log::info('Starting uptime calculation', [ 'monitor_id' => $this->monitorId, 'date' => $this->date, 'attempt' => $this->attempts(), ]); try { // Validate monitor exists first if (! $this->monitorExists()) { Log::warning('Monitor not found, skipping calculation', [ 'monitor_id' => $this->monitorId, ]); return; } // Validate date format if (! $this->isValidDate()) { throw new Exception("Invalid date format: {$this->date}"); } $this->calculateAndStoreUptime(); Log::info('Uptime calculation completed successfully', [ 'monitor_id' => $this->monitorId, 'date' => $this->date, ]); } catch (Exception $e) { Log::error('Uptime calculation failed', [ 'monitor_id' => $this->monitorId, 'date' => $this->date, 'attempt' => $this->attempts(), 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); // Re-throw to trigger retry mechanism throw $e; } } /** * Check if monitor exists */ private function monitorExists(): bool { return DB::table('monitors') ->where('id', $this->monitorId) ->exists(); } /** * Validate date format */ private function isValidDate(): bool { try { Carbon::createFromFormat('Y-m-d', $this->date); return true; } catch (Exception $e) { return false; } } /** * Calculate and store uptime data */ private function calculateAndStoreUptime(): void { // Use efficient date range queries instead of whereDate() $startDate = Carbon::parse($this->date)->startOfDay(); $endDate = $startDate->copy()->endOfDay(); // Use a single database query to get both total and up counts $result = DB::table('monitor_histories') ->selectRaw(' COUNT(*) as total_checks, SUM(CASE WHEN uptime_status = "up" THEN 1 ELSE 0 END) as up_checks ') ->where('monitor_id', $this->monitorId) ->whereBetween('created_at', [$startDate, $endDate]) ->first(); Log::info('Monitor history result', [ 'result' => $result, 'monitor_id' => $this->monitorId, 'date' => $this->date, ]); // Handle case where no checks found if (! $result || $result->total_checks === 0) { Log::info('No monitor history found for date', [ 'monitor_id' => $this->monitorId, 'date' => $this->date, ]); $this->updateUptimeRecord(0, []); return; } $uptimePercentage = ($result->up_checks / $result->total_checks) * 100; // Calculate response time metrics $performanceService = app(MonitorPerformanceService::class); $responseMetrics = $performanceService->aggregateDailyMetrics($this->monitorId, $this->date); Log::debug('Uptime calculation details', [ 'monitor_id' => $this->monitorId, 'date' => $this->date, 'total_checks' => $result->total_checks, 'up_checks' => $result->up_checks, 'uptime_percentage' => $uptimePercentage, 'response_metrics' => $responseMetrics, ]); $this->updateUptimeRecord($uptimePercentage, $responseMetrics); } /** * Update or create the uptime record using efficient updateOrInsert */ private function updateUptimeRecord(float $uptimePercentage, array $responseMetrics = []): void { // Ensure date is in correct format (Y-m-d, not datetime) $dateOnly = Carbon::parse($this->date)->toDateString(); $roundedPercentage = round($uptimePercentage, 2); // Prepare data for upsert $data = [ 'uptime_percentage' => $roundedPercentage, 'updated_at' => now(), ]; // Add response metrics if available if (! empty($responseMetrics)) { $data['avg_response_time'] = $responseMetrics['avg_response_time']; $data['min_response_time'] = $responseMetrics['min_response_time']; $data['max_response_time'] = $responseMetrics['max_response_time']; $data['total_checks'] = $responseMetrics['total_checks']; $data['failed_checks'] = $responseMetrics['failed_checks']; } // For new records, add created_at $insertData = array_merge($data, [ 'created_at' => now(), ]); try { // Use Laravel's efficient updateOrInsert method DB::table('monitor_uptime_dailies') ->updateOrInsert( [ 'monitor_id' => $this->monitorId, 'date' => $dateOnly, ], $insertData ); Log::debug('Uptime record updated/created successfully', [ 'monitor_id' => $this->monitorId, 'date' => $dateOnly, 'uptime_percentage' => $roundedPercentage, ]); } catch (\Illuminate\Database\QueryException $e) { Log::error('Database error in uptime record operation', [ 'monitor_id' => $this->monitorId, 'date' => $dateOnly, 'error' => $e->getMessage(), ]); throw $e; } } /** * Handle job retry logic */ public function retryUntil() { return now()->addMinutes(30); } /** * The job failed to process. */ public function failed(\Throwable $exception): void { Log::error('CalculateSingleMonitorUptimeJob permanently failed', [ 'monitor_id' => $this->monitorId, 'date' => $this->date, 'attempts' => $this->attempts(), 'error' => $exception->getMessage(), 'trace' => $exception->getTraceAsString(), ]); // Optional: Send notification to administrators // event(new UptimeCalculationFailed($this->monitorId, $this->date, $exception)); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Jobs/SendTelemetryPingJob.php
app/Jobs/SendTelemetryPingJob.php
<?php namespace App\Jobs; use App\Services\TelemetryService; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; class SendTelemetryPingJob implements ShouldQueue { use Queueable; public $tries = 3; public $backoff = [60, 300, 900]; // 1 min, 5 min, 15 min public $timeout = 30; /** * Create a new job instance. */ public function __construct() { $this->onQueue('default'); } /** * Execute the job. */ public function handle(TelemetryService $telemetryService): void { // Double-check telemetry is still enabled if (! $telemetryService->isEnabled()) { Log::debug('Telemetry is disabled, skipping ping.'); return; } $data = $telemetryService->collectData(); $endpoint = $telemetryService->getEndpoint(); // Debug mode: log instead of send if (config('telemetry.debug')) { Log::info('Telemetry Debug - Would send data:', $data); $telemetryService->recordPing(); return; } try { $response = Http::timeout(config('telemetry.timeout', 10)) ->acceptJson() ->withHeaders([ 'User-Agent' => 'Uptime-Kita/'.config('app.last_update', 'unknown'), 'Content-Type' => 'application/json', ]) ->post($endpoint, $data); if ($response->successful()) { $telemetryService->recordPing(); Log::debug('Telemetry ping sent successfully.'); } else { Log::warning('Telemetry ping failed with status: '.$response->status()); } } catch (\Exception $e) { // Silent failure - telemetry should never impact the main app Log::debug('Telemetry ping failed: '.$e->getMessage()); throw $e; // Re-throw to trigger retry } } /** * Handle a job failure. */ public function failed(\Throwable $exception): void { // Final failure after all retries - just log quietly Log::info('Telemetry ping failed after all retries: '.$exception->getMessage()); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Jobs/CalculateMonitorUptimeDailyJob.php
app/Jobs/CalculateMonitorUptimeDailyJob.php
<?php namespace App\Jobs; use App\Models\Monitor; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class CalculateMonitorUptimeDailyJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. */ public function __construct() {} /** * Execute the job. */ public function handle(): void { Log::info('Starting daily uptime calculation batch job'); try { // Get all monitor IDs $monitorIds = $this->getMonitorIds(); if (empty($monitorIds)) { Log::info('No monitors found for uptime calculation'); return; } Log::info('Creating batch jobs for monitors', [ 'total_monitors' => count($monitorIds), // 'monitorIds' => $monitorIds, ]); // Chunk monitors into smaller batches for better memory management $chunkSize = 10; // Process 10 monitors per batch to reduce database contention $monitorChunks = array_chunk($monitorIds, $chunkSize); $totalChunks = count($monitorChunks); $totalJobs = 0; Log::info('Processing monitors in chunks', [ 'total_monitors' => count($monitorIds), 'chunk_size' => $chunkSize, 'total_chunks' => $totalChunks, ]); foreach ($monitorChunks as $index => $monitorChunk) { $chunkNumber = $index + 1; Log::info("Processing chunk {$chunkNumber}/{$totalChunks}", [ 'chunk_size' => count($monitorChunk), 'monitors_in_chunk' => $monitorChunk, ]); // Dispatch jobs individually instead of using batches foreach ($monitorChunk as $monitorId) { $job = new \App\Jobs\CalculateSingleMonitorUptimeJob($monitorId); dispatch($job); $totalJobs++; } Log::info("Chunk {$chunkNumber}/{$totalChunks} dispatched successfully", [ 'chunk_size' => count($monitorChunk), 'total_jobs_dispatched' => $totalJobs, ]); // Small delay between chunks to reduce database contention if ($chunkNumber < $totalChunks) { usleep(500000); // 0.5 second delay } } Log::info('All chunks dispatched successfully', [ 'total_chunks' => $totalChunks, 'total_jobs' => $totalJobs, ]); } catch (\Exception $e) { Log::error('Failed to dispatch batch job', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); throw $e; } } /** * Get all monitor IDs for uptime calculation. */ protected function getMonitorIds(): array { return Monitor::pluck('id')->toArray(); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Jobs/ConfirmMonitorDowntimeJob.php
app/Jobs/ConfirmMonitorDowntimeJob.php
<?php namespace App\Jobs; use App\Models\Monitor; use App\Services\SmartRetryResult; use App\Services\SmartRetryService; use Carbon\Carbon; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Facades\Log; use Spatie\UptimeMonitor\Events\UptimeCheckFailed; use Spatie\UptimeMonitor\Helpers\Period; class ConfirmMonitorDowntimeJob implements ShouldQueue { use Queueable; public int $tries = 1; public int $timeout = 30; /** * Create a new job instance. */ public function __construct( public int $monitorId, public string $failureReason, public ?int $previousFailureCount = null ) { // } /** * Execute the job. */ public function handle(SmartRetryService $smartRetry): void { $monitor = Monitor::withoutGlobalScopes()->find($this->monitorId); if (! $monitor) { Log::warning('ConfirmMonitorDowntimeJob: Monitor not found', [ 'monitor_id' => $this->monitorId, ]); return; } // If monitor is no longer enabled, skip if (! $monitor->uptime_check_enabled) { Log::info('ConfirmMonitorDowntimeJob: Monitor disabled, skipping confirmation', [ 'monitor_id' => $this->monitorId, ]); return; } // If monitor has recovered since the failure, skip if ($monitor->uptime_status === 'up') { Log::info('ConfirmMonitorDowntimeJob: Monitor already recovered, marking as transient failure', [ 'monitor_id' => $this->monitorId, 'url' => (string) $monitor->url, ]); $this->logTransientFailure($monitor); return; } // Get per-monitor settings or use sensitivity preset $sensitivity = $monitor->sensitivity ?? 'medium'; $preset = SmartRetryService::getPreset($sensitivity); $options = [ 'retries' => $monitor->confirmation_retries ?? $preset['retries'], 'initial_delay_ms' => $preset['initial_delay_ms'], 'backoff_multiplier' => $preset['backoff_multiplier'], ]; // Perform smart confirmation check $result = $smartRetry->performSmartCheck($monitor, $options); if ($result->isSuccess()) { Log::info('ConfirmMonitorDowntimeJob: Confirmation check passed, marking as transient failure', [ 'monitor_id' => $this->monitorId, 'url' => (string) $monitor->url, 'attempts' => $result->getAttemptCount(), ]); $this->logTransientFailure($monitor); $this->resetMonitorStatus($monitor); } else { $this->confirmDowntime($monitor, $result); } } /** * Reset monitor status after transient failure. */ protected function resetMonitorStatus(Monitor $monitor): void { $monitor->uptime_check_times_failed_in_a_row = 0; $monitor->uptime_status = 'up'; $monitor->uptime_check_failure_reason = null; $monitor->saveQuietly(); } /** * Confirm monitor downtime and fire event. */ protected function confirmDowntime(Monitor $monitor, SmartRetryResult $result): void { Log::info('ConfirmMonitorDowntimeJob: Confirmed DOWN status', [ 'monitor_id' => $this->monitorId, 'url' => (string) $monitor->url, 'failure_reason' => $result->message ?? $this->failureReason, 'attempts' => $result->getAttemptCount(), ]); // Update failure reason with smart retry result message if ($result->message) { $monitor->uptime_check_failure_reason = $result->message; $monitor->saveQuietly(); } // Fire the UptimeCheckFailed event manually to trigger notifications $downtimePeriod = new Period( $monitor->uptime_status_last_change_date ?? Carbon::now(), Carbon::now() ); event(new UptimeCheckFailed($monitor, $downtimePeriod)); } /** * Log transient failure for tracking purposes. */ protected function logTransientFailure(Monitor $monitor): void { Log::info('ConfirmMonitorDowntimeJob: Transient failure detected', [ 'monitor_id' => $this->monitorId, 'url' => (string) $monitor->url, 'original_failure_reason' => $this->failureReason, ]); // Increment transient failure counter if the field exists if (isset($monitor->transient_failures_count)) { $monitor->transient_failures_count = ($monitor->transient_failures_count ?? 0) + 1; $monitor->saveQuietly(); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Jobs/CalculateMonitorStatisticsJob.php
app/Jobs/CalculateMonitorStatisticsJob.php
<?php namespace App\Jobs; use App\Models\Monitor; use App\Models\MonitorHistory; use App\Models\MonitorStatistic; use Carbon\Carbon; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Facades\Log; class CalculateMonitorStatisticsJob implements ShouldBeUnique, ShouldQueue { use Queueable; public $timeout = 600; // 10 minutes timeout public $tries = 3; public $backoff = [60, 120, 300]; // Exponential backoff: 1 min, 2 min, 5 min /** * The number of seconds after which the job's unique lock will be released. * This should be longer than the timeout + backoff time to prevent duplicates. * * @var int */ public $uniqueFor = 900; // 15 minutes - matches the scheduler interval protected ?int $monitorId; /** * Create a new job instance. */ public function __construct(?int $monitorId = null) { $this->monitorId = $monitorId; $this->onQueue('statistics'); // Use dedicated queue for statistics } /** * Get the unique ID for the job. * This ensures only one job per monitor (or one global job when monitorId is null) can exist. */ public function uniqueId(): string { return $this->monitorId ? 'monitor-'.$this->monitorId : 'all-monitors'; } /** * Execute the job. */ public function handle(): void { if ($this->monitorId) { $monitors = Monitor::where('id', $this->monitorId) ->where('is_public', true) ->get(); } else { // Process in batches to avoid memory issues $monitors = Monitor::where('is_public', true) ->where('uptime_check_enabled', true) ->chunk(10, function ($chunk) { foreach ($chunk as $monitor) { try { $this->calculateStatistics($monitor); } catch (\Exception $e) { Log::error("Failed to calculate statistics for monitor {$monitor->id}", [ 'monitor_id' => $monitor->id, 'monitor_url' => $monitor->url, 'error' => $e->getMessage(), ]); continue; } } }); Log::info('Monitor statistics calculation completed successfully!'); return; } if ($monitors->isEmpty()) { Log::info('No public monitors found for statistics calculation.'); return; } Log::info("Calculating statistics for {$monitors->count()} monitor(s)..."); foreach ($monitors as $monitor) { try { $this->calculateStatistics($monitor); } catch (\Exception $e) { Log::error("Failed to calculate statistics for monitor {$monitor->id}", [ 'monitor_id' => $monitor->id, 'monitor_url' => $monitor->url, 'error' => $e->getMessage(), ]); continue; } } Log::info('Monitor statistics calculation completed successfully!'); } private function calculateStatistics(Monitor $monitor): void { $now = now(); // Calculate uptime percentages for different periods $uptimeStats = [ '1h' => $this->calculateUptimePercentage($monitor, $now->copy()->subHour()), '24h' => $this->calculateUptimePercentage($monitor, $now->copy()->subDay()), '7d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(7)), '30d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(30)), '90d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(90)), ]; // Calculate response time stats for last 24h $responseTimeStats = $this->calculateResponseTimeStats($monitor, $now->copy()->subDay()); // Calculate incident counts $incidentCounts = [ '24h' => $this->calculateIncidentCount($monitor, $now->copy()->subDay()), '7d' => $this->calculateIncidentCount($monitor, $now->copy()->subDays(7)), '30d' => $this->calculateIncidentCount($monitor, $now->copy()->subDays(30)), ]; // Calculate total checks $totalChecks = [ '24h' => $this->calculateTotalChecks($monitor, $now->copy()->subDay()), '7d' => $this->calculateTotalChecks($monitor, $now->copy()->subDays(7)), '30d' => $this->calculateTotalChecks($monitor, $now->copy()->subDays(30)), ]; // Get recent history for last 100 minutes $recentHistory = $this->getRecentHistory($monitor); // Upsert statistics record MonitorStatistic::updateOrCreate( ['monitor_id' => $monitor->id], [ 'uptime_1h' => $uptimeStats['1h'], 'uptime_24h' => $uptimeStats['24h'], 'uptime_7d' => $uptimeStats['7d'], 'uptime_30d' => $uptimeStats['30d'], 'uptime_90d' => $uptimeStats['90d'], 'avg_response_time_24h' => $responseTimeStats['avg'], 'min_response_time_24h' => $responseTimeStats['min'], 'max_response_time_24h' => $responseTimeStats['max'], 'incidents_24h' => $incidentCounts['24h'], 'incidents_7d' => $incidentCounts['7d'], 'incidents_30d' => $incidentCounts['30d'], 'total_checks_24h' => $totalChecks['24h'], 'total_checks_7d' => $totalChecks['7d'], 'total_checks_30d' => $totalChecks['30d'], 'recent_history_100m' => $recentHistory, 'calculated_at' => $now, ] ); Log::debug("Statistics calculated for monitor {$monitor->id} ({$monitor->url})"); } private function calculateUptimePercentage(Monitor $monitor, Carbon $startDate): float { // Use aggregation query instead of fetching all records $stats = MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $startDate) ->selectRaw(' COUNT(*) as total, SUM(CASE WHEN uptime_status = ? THEN 1 ELSE 0 END) as up_count ', ['up']) ->first(); if (! $stats || $stats->total == 0) { return 100.0; } return round(($stats->up_count / $stats->total) * 100, 2); } private function calculateResponseTimeStats(Monitor $monitor, Carbon $startDate): array { // Use aggregation query instead of fetching all records $stats = MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $startDate) ->whereNotNull('response_time') ->selectRaw(' AVG(response_time) as avg, MIN(response_time) as min, MAX(response_time) as max ') ->first(); if (! $stats || ! $stats->avg) { return ['avg' => null, 'min' => null, 'max' => null]; } return [ 'avg' => (int) round($stats->avg), 'min' => (int) $stats->min, 'max' => (int) $stats->max, ]; } private function calculateIncidentCount(Monitor $monitor, Carbon $startDate): int { return MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $startDate) ->where('uptime_status', '!=', 'up') ->count(); } private function calculateTotalChecks(Monitor $monitor, Carbon $startDate): int { return MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $startDate) ->count(); } private function getRecentHistory(Monitor $monitor): array { $oneHundredMinutesAgo = now()->subMinutes(100); // Simpler approach - just get recent history without complex window functions $histories = MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $oneHundredMinutesAgo) ->orderBy('created_at', 'desc') ->limit(100) ->select(['created_at', 'uptime_status', 'response_time', 'message']) ->get(); // Transform to a lighter format for JSON storage return $histories->map(function ($history) { return [ 'created_at' => $history->created_at->toISOString(), 'uptime_status' => $history->uptime_status, 'response_time' => $history->response_time, 'message' => $history->message, ]; })->toArray(); } /** * Handle a job failure. */ public function failed(\Throwable $exception): void { Log::error('CalculateMonitorStatisticsJob failed', [ 'monitor_id' => $this->monitorId, 'error' => $exception->getMessage(), 'trace' => $exception->getTraceAsString(), ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Requests/ImportMonitorFileRequest.php
app/Http/Requests/ImportMonitorFileRequest.php
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class ImportMonitorFileRequest extends FormRequest { public function authorize(): bool { return true; } public function rules(): array { return [ 'import_file' => [ 'required', 'file', 'mimes:csv,txt,json', 'max:10240', // 10MB max ], 'format' => [ 'nullable', 'string', 'in:csv,json', ], ]; } public function messages(): array { return [ 'import_file.required' => 'Please select a file to import.', 'import_file.mimes' => 'Only CSV and JSON files are supported.', 'import_file.max' => 'The file must not exceed 10MB.', ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Requests/ProcessMonitorImportRequest.php
app/Http/Requests/ProcessMonitorImportRequest.php
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class ProcessMonitorImportRequest extends FormRequest { public function authorize(): bool { return true; } public function rules(): array { return [ 'rows' => ['required', 'array', 'min:1'], // URL validation is relaxed here since error rows may have invalid URLs // The service will skip error rows during import 'rows.*.url' => ['nullable', 'string'], 'rows.*.display_name' => ['nullable', 'string', 'max:255'], 'rows.*.uptime_check_enabled' => ['nullable'], 'rows.*.certificate_check_enabled' => ['nullable'], 'rows.*.uptime_check_interval' => ['nullable', 'integer', 'min:1', 'max:60'], 'rows.*.is_public' => ['nullable'], 'rows.*.sensitivity' => ['nullable', 'string', 'in:low,medium,high'], 'rows.*.expected_status_code' => ['nullable', 'integer', 'min:100', 'max:599'], 'rows.*.tags' => ['nullable', 'array'], 'rows.*.tags.*' => ['string', 'max:255'], 'rows.*._row_number' => ['required', 'integer'], 'rows.*._status' => ['required', 'string', 'in:valid,error,duplicate'], 'rows.*._errors' => ['nullable', 'array'], 'duplicate_action' => ['required', 'string', 'in:skip,update,create'], 'resolutions' => ['nullable', 'array'], 'resolutions.*' => ['string', 'in:skip,update,create'], ]; } public function messages(): array { return [ 'rows.required' => 'No monitors to import.', 'rows.min' => 'At least one monitor is required.', 'duplicate_action.required' => 'Please select how to handle duplicate monitors.', ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Requests/Auth/LoginRequest.php
app/Http/Requests/Auth/LoginRequest.php
<?php namespace App\Http\Requests\Auth; use Illuminate\Auth\Events\Lockout; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; class LoginRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ 'email' => ['required', 'string', 'email'], 'password' => ['required', 'string'], ]; } /** * Attempt to authenticate the request's credentials. * * @throws \Illuminate\Validation\ValidationException */ public function authenticate(): void { $this->ensureIsNotRateLimited(); if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) { RateLimiter::hit($this->throttleKey()); throw ValidationException::withMessages([ 'email' => trans('auth.failed'), ]); } RateLimiter::clear($this->throttleKey()); } /** * Ensure the login request is not rate limited. * * @throws \Illuminate\Validation\ValidationException */ public function ensureIsNotRateLimited(): void { if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) { return; } event(new Lockout($this)); $seconds = RateLimiter::availableIn($this->throttleKey()); throw ValidationException::withMessages([ 'email' => trans('auth.throttle', [ 'seconds' => $seconds, 'minutes' => ceil($seconds / 60), ]), ]); } /** * Get the rate limiting throttle key for the request. */ public function throttleKey(): string { return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip()); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Requests/Settings/RestoreDatabaseRequest.php
app/Http/Requests/Settings/RestoreDatabaseRequest.php
<?php namespace App\Http\Requests\Settings; use Illuminate\Foundation\Http\FormRequest; class RestoreDatabaseRequest extends FormRequest { public function authorize(): bool { return true; } /** * @return array<string, array<int, mixed>> */ public function rules(): array { return [ 'database' => [ 'required', 'file', 'extensions:sql,sqlite,sqlite3,db', 'max:'.(512 * 1024), // 500MB max in KB ], ]; } /** * @return array<string, string> */ public function messages(): array { return [ 'database.required' => 'Please select a database file to upload.', 'database.max' => 'The database file must not exceed 500MB.', ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Requests/Settings/ProfileUpdateRequest.php
app/Http/Requests/Settings/ProfileUpdateRequest.php
<?php namespace App\Http\Requests\Settings; use App\Models\User; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; class ProfileUpdateRequest extends FormRequest { /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ 'name' => ['required', 'string', 'max:255'], 'email' => [ 'required', 'string', 'lowercase', 'email', 'max:255', Rule::unique(User::class)->ignore($this->user()->id), ], ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/OgImageController.php
app/Http/Controllers/OgImageController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use App\Models\StatusPage; use App\Services\OgImageService; use Illuminate\Http\Response; use Illuminate\Support\Facades\Cache; class OgImageController extends Controller { public function __construct( private OgImageService $ogImageService ) {} /** * Generate OG image for public monitors list page. * Route: /og/monitors.png */ public function monitorsIndex(): Response { $cacheKey = 'og_image_monitors_index'; $image = Cache::remember($cacheKey, 300, function () { $stats = [ 'total' => Monitor::query()->where('is_public', true)->count(), 'up' => Monitor::query()->where('is_public', true)->where('uptime_status', 'up')->count(), 'down' => Monitor::query()->where('is_public', true)->where('uptime_status', 'down')->count(), ]; return $this->ogImageService->generateMonitorsIndex($stats); }); return $this->pngResponse($image); } /** * Generate OG image for individual monitor. * Route: /og/monitor/{domain}.png */ public function monitor(string $domain): Response { $url = 'https://'.urldecode($domain); $monitor = Monitor::query() ->where('url', $url) ->where('is_public', true) ->with('statistics') ->first(); if (! $monitor) { return $this->notFoundImage($domain); } $cacheKey = "og_image_monitor_{$monitor->id}"; $image = Cache::remember($cacheKey, 300, function () use ($monitor) { return $this->ogImageService->generateMonitor($monitor); }); return $this->pngResponse($image); } /** * Generate OG image for status page. * Route: /og/status/{path}.png */ public function statusPage(string $path): Response { $statusPage = StatusPage::query() ->where('path', $path) ->with(['monitors' => function ($query) { $query->with('statistics'); }]) ->first(); if (! $statusPage) { return $this->notFoundImage($path); } $cacheKey = "og_image_status_page_{$statusPage->id}"; $image = Cache::remember($cacheKey, 300, function () use ($statusPage) { return $this->ogImageService->generateStatusPage($statusPage); }); return $this->pngResponse($image); } /** * Return PNG response with proper headers. */ private function pngResponse(string $imageData): Response { return response($imageData, 200, [ 'Content-Type' => 'image/png', 'Cache-Control' => 'public, max-age=300, s-maxage=300', 'Expires' => now()->addMinutes(5)->toRfc7231String(), ]); } /** * Generate and return not found image. */ private function notFoundImage(string $identifier): Response { $image = $this->ogImageService->generateNotFound($identifier); return $this->pngResponse($image); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/PublicMonitorShowController.php
app/Http/Controllers/PublicMonitorShowController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\MonitorResource; use App\Jobs\IncrementMonitorPageViewJob; use App\Models\Monitor; use App\Models\MonitorHistory; use App\Services\MonitorPerformanceService; use Carbon\Carbon; use Illuminate\Http\Request; use Inertia\Inertia; use Inertia\Response; class PublicMonitorShowController extends Controller { /** * Display the public monitor page. */ public function show(Request $request, MonitorPerformanceService $performanceService): Response { // Get the domain from the request $domain = urldecode($request->route('domain')); // Build the full HTTPS URL $url = 'https://'.$domain; // Find the monitor by URL with its statistics $monitor = Monitor::where('url', $url) ->where('is_public', true) ->where('uptime_check_enabled', true) ->with(['statistics', 'tags']) ->first(); // If monitor not found, show the not found page if (! $monitor) { return $this->showNotFound($domain); } // Dispatch job to increment page view count (non-blocking) IncrementMonitorPageViewJob::dispatch($monitor->id, $request->ip()); // Use real-time data with short cache like private monitor show $histories = cache()->remember("public_monitor_{$monitor->id}_histories", 60, function () use ($monitor) { return $this->getLiveHistory($monitor); }); $uptimeStats = cache()->remember("public_monitor_{$monitor->id}_uptime_stats", 60, function () use ($monitor) { return $this->calculateUptimeStats($monitor); }); $responseTimeStats = cache()->remember("public_monitor_{$monitor->id}_response_stats", 60, function () use ($monitor, $performanceService) { return $this->getLiveResponseTimeStats($monitor, $performanceService); }); // Load uptime daily data and latest incidents (these are still needed) $monitor->load(['uptimesDaily' => function ($query) { $query->orderBy('date', 'desc')->limit(90); }, 'latestIncidents' => function ($query) { $query->orderBy('started_at', 'desc')->limit(10); }]); $appUrl = config('app.url'); $monitorName = $monitor->name ?? $domain; $uptimePercent = $uptimeStats['24h'] ?? 0; $statusText = $monitor->uptime_status === 'up' ? 'Operational' : 'Down'; return Inertia::render('monitors/PublicShow', [ 'monitor' => new MonitorResource($monitor), 'histories' => $histories, 'uptimeStats' => $uptimeStats, 'responseTimeStats' => $responseTimeStats, 'latestIncidents' => $monitor->latestIncidents, ])->withViewData([ 'ogTitle' => "{$monitorName} Status - Uptime Kita", 'ogDescription' => "{$statusText} - {$uptimePercent}% uptime in the last 24 hours. Monitor real-time status and performance.", 'ogImage' => "{$appUrl}/og/monitor/{$domain}.png", 'ogUrl' => "{$appUrl}/m/{$domain}", ]); } /** * Calculate uptime statistics for different periods. */ private function calculateUptimeStats($monitor): array { $now = now(); return [ '24h' => $this->calculateUptimePercentage($monitor, $now->copy()->subDay()), '7d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(7)), '30d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(30)), '90d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(90)), ]; } /** * Calculate uptime percentage for a specific period. */ private function calculateUptimePercentage($monitor, $startDate): float { // Get unique history IDs using raw SQL to ensure only one record per minute $sql = " SELECT id FROM ( SELECT id, created_at, ROW_NUMBER() OVER ( PARTITION BY monitor_id, strftime('%Y-%m-%d %H:%M', created_at) ORDER BY created_at DESC, id DESC ) as rn FROM monitor_histories WHERE monitor_id = ? AND created_at >= ? ) ranked WHERE rn = 1 "; $uniqueIds = \DB::select($sql, [$monitor->id, $startDate]); $ids = array_column($uniqueIds, 'id'); if (empty($ids)) { return 100.0; } // Get unique histories $histories = MonitorHistory::whereIn('id', $ids)->get(); $upCount = $histories->where('uptime_status', 'up')->count(); $totalCount = $histories->count(); return round(($upCount / $totalCount) * 100, 2); } /** * Get live history data when cached version is not available */ private function getLiveHistory($monitor): array { $oneHundredMinutesAgo = now()->subMinutes(100); // Get unique history IDs using raw SQL to ensure only one record per minute $sql = " SELECT id FROM ( SELECT id, created_at, ROW_NUMBER() OVER ( PARTITION BY monitor_id, strftime('%Y-%m-%d %H:%M', created_at) ORDER BY created_at DESC, id DESC ) as rn FROM monitor_histories WHERE monitor_id = ? ) ranked WHERE rn = 1 ORDER BY created_at DESC LIMIT 100 "; $uniqueIds = \DB::select($sql, [$monitor->id]); $ids = array_column($uniqueIds, 'id'); // Get unique histories and filter by time $histories = MonitorHistory::whereIn('id', $ids) ->where('created_at', '>=', $oneHundredMinutesAgo) ->orderBy('created_at', 'desc') ->get(); // Transform to match the cached format return $histories->map(function ($history) { return [ 'created_at' => $history->created_at->toISOString(), 'uptime_status' => $history->uptime_status, 'response_time' => $history->response_time, 'message' => $history->message, ]; })->toArray(); } /** * Get live response time statistics when cached version is not available */ private function getLiveResponseTimeStats($monitor, MonitorPerformanceService $performanceService): array { $responseTimeStats = $performanceService->getResponseTimeStats( $monitor->id, Carbon::now()->subDay(), Carbon::now() ); return [ 'average' => $responseTimeStats['avg'], 'min' => $responseTimeStats['min'], 'max' => $responseTimeStats['max'], ]; } /** * Display the not found page for monitors. */ private function showNotFound(string $domain): Response { $appUrl = config('app.url'); return Inertia::render('monitors/PublicShowNotFound', [ 'domain' => $domain, 'suggestedUrl' => 'https://'.$domain, ])->withViewData([ 'ogTitle' => 'Monitor Not Found - Uptime Kita', 'ogDescription' => "The monitor for {$domain} was not found or is not public.", 'ogImage' => "{$appUrl}/og/monitors.png", 'ogUrl' => "{$appUrl}/m/{$domain}", ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/SubscribeMonitorController.php
app/Http/Controllers/SubscribeMonitorController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use Illuminate\Http\Request; class SubscribeMonitorController extends Controller { public function __invoke(Request $request, $monitorId) { try { $monitor = Monitor::withoutGlobalScopes()->findOrFail($monitorId); $errorMessage = null; $statusCode = 200; // Check if already subscribed $isSubscribed = $monitor->users()->where('user_id', auth()->id())->exists(); // Check if monitor is disabled globally if (! $monitor->uptime_check_enabled) { $errorMessage = 'Cannot subscribe to disabled monitor'; $statusCode = 403; } elseif (! $monitor->is_public) { // For private monitors, only owner can be subscribed if (! $isSubscribed) { $errorMessage = 'Cannot subscribe to private monitor'; $statusCode = 403; } } // Check for duplicate subscription (for public monitors or if already subscribed to private) if (! $errorMessage && $isSubscribed) { // If it's a private monitor and they're the owner, allow it (idempotent) if (! $monitor->is_public) { // Already handled, just return success $successMessage = 'Subscribed to monitor successfully'; if ($request->wantsJson()) { return response()->json(['message' => $successMessage], 200); } return redirect()->back()->with('flash', [ 'type' => 'success', 'message' => 'Berhasil berlangganan monitor: '.$monitor?->url, ]); } $errorMessage = 'Already subscribed to this monitor'; $statusCode = 400; } if ($errorMessage) { if ($request->wantsJson()) { return response()->json(['message' => $errorMessage], $statusCode); } return redirect()->back()->with('flash', [ 'type' => 'error', 'message' => $errorMessage, ]); } $monitor->users()->attach(auth()->id(), ['is_active' => true]); // clear monitor cache cache()->forget('public_monitors_authenticated_'.auth()->id()); $successMessage = 'Subscribed to monitor successfully'; if ($request->wantsJson()) { return response()->json(['message' => $successMessage], 200); } return redirect()->back()->with('flash', [ 'type' => 'success', 'message' => 'Berhasil berlangganan monitor: '.$monitor?->url, ]); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { if ($request->wantsJson()) { return response()->json(['message' => 'Monitor not found'], 404); } return redirect()->back()->with('flash', [ 'type' => 'error', 'message' => 'Monitor tidak ditemukan', ]); } catch (\Exception $e) { if ($request->wantsJson()) { return response()->json(['message' => 'Failed to subscribe: '.$e->getMessage()], 500); } return redirect()->back()->with('flash', [ 'type' => 'error', 'message' => 'Gagal berlangganan monitor: '.$e->getMessage(), ]); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/StatusPageAvailableMonitorsController.php
app/Http/Controllers/StatusPageAvailableMonitorsController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\MonitorResource; use App\Models\StatusPage; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\Request; class StatusPageAvailableMonitorsController extends Controller { use AuthorizesRequests; public function __invoke(Request $request, StatusPage $statusPage) { try { $this->authorize('view', $statusPage); } catch (AuthorizationException $e) { return response()->json(['message' => 'Unauthorized.'], 403); } $availableMonitors = auth()->user()->monitors() ->whereNotIn('monitors.id', function ($query) use ($statusPage) { $query->select('monitor_id') ->from('status_page_monitor') ->where('status_page_id', $statusPage->id); }) ->get(); return response()->json(MonitorResource::collection($availableMonitors)); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/PublicServerStatsController.php
app/Http/Controllers/PublicServerStatsController.php
<?php namespace App\Http\Controllers; use App\Services\ServerResourceService; use Illuminate\Http\JsonResponse; class PublicServerStatsController extends Controller { public function __construct( protected ServerResourceService $serverResourceService ) {} /** * Get public server stats (limited data for transparency). */ public function __invoke(): JsonResponse { // Check if public stats are enabled if (! config('app.show_public_server_stats', true)) { return response()->json(['enabled' => false]); } $metrics = $this->serverResourceService->getMetrics(); // Return only limited, non-sensitive data return response()->json([ 'enabled' => true, 'cpu_percent' => $metrics['cpu']['usage_percent'], 'memory_percent' => $metrics['memory']['usage_percent'], 'uptime' => $metrics['uptime']['formatted'], 'uptime_seconds' => $metrics['uptime']['seconds'], 'response_time' => $this->calculateResponseTime(), 'timestamp' => $metrics['timestamp'], ]); } /** * Calculate a simple response time metric. */ protected function calculateResponseTime(): int { $start = microtime(true); // Simple DB ping to measure response time try { \DB::connection()->getPdo(); } catch (\Exception $e) { // Ignore connection errors } $end = microtime(true); return (int) round(($end - $start) * 1000); // Convert to milliseconds } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/StatusPageController.php
app/Http/Controllers/StatusPageController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\StatusPageCollection; use App\Http\Resources\StatusPageResource; use App\Models\StatusPage; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\Request; use Illuminate\Validation\Rule; use Inertia\Inertia; use Inertia\Response; class StatusPageController extends Controller { use AuthorizesRequests; /** * Display a listing of the resource. */ public function index(Request $request): Response { $statusPages = auth()->user()->statusPages()->latest()->paginate(9); return Inertia::render('status-pages/Index', [ 'statusPages' => new StatusPageCollection($statusPages), ]); } /** * Show the form for creating a new resource. */ public function create(): Response { return Inertia::render('status-pages/Create'); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|string|max:255', 'description' => 'required|string|max:1000', 'icon' => 'required|string|max:255', 'path' => [ 'nullable', 'string', 'max:255', 'unique:status_pages,path', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', ], 'custom_domain' => [ 'nullable', 'string', 'max:255', 'regex:/^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i', 'unique:status_pages,custom_domain', ], 'force_https' => 'boolean', ]); $statusPage = auth()->user()->statusPages()->create([ 'title' => $validated['title'], 'description' => $validated['description'], 'icon' => $validated['icon'], 'path' => $validated['path'] ?? StatusPage::generateUniquePath($validated['title']), 'custom_domain' => $validated['custom_domain'] ?? null, 'force_https' => $validated['force_https'] ?? true, ]); // Generate verification token if custom domain is provided if ($statusPage->custom_domain) { $statusPage->generateVerificationToken(); } return redirect()->route('status-pages.show', $statusPage) ->with('success', 'Status page created successfully.'); } /** * Display the specified resource. */ public function show(StatusPage $statusPage): Response { $this->authorize('view', $statusPage); return Inertia::render('status-pages/Show', [ 'statusPage' => (new StatusPageResource($statusPage->load([ 'monitors' => function ($query) { $query->orderBy('status_page_monitor.order', 'asc') ->with(['uptimeDaily']); }, ])))->toArray(request()), ]); } /** * Show the form for editing the specified resource. */ public function edit(StatusPage $statusPage): Response { $this->authorize('update', $statusPage); return Inertia::render('status-pages/Edit', [ 'statusPage' => $statusPage->only([ 'id', 'title', 'description', 'icon', 'path', 'custom_domain', 'custom_domain_verified', 'force_https', ]), ]); } /** * Update the specified resource in storage. */ public function update(Request $request, StatusPage $statusPage) { $this->authorize('update', $statusPage); $validated = $request->validate([ 'title' => 'required|string|max:255', 'description' => 'required|string|max:1000', 'icon' => 'required|string|max:255', 'path' => [ 'nullable', 'string', 'max:255', Rule::unique('status_pages', 'path')->ignore($statusPage->id), 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', ], ]); $statusPage->update([ 'title' => $validated['title'], 'description' => $validated['description'], 'icon' => $validated['icon'], 'path' => $validated['path'] ?? $statusPage->path, ]); return redirect()->route('status-pages.show', $statusPage) ->with('success', 'Status page updated successfully.'); } /** * Remove the specified resource from storage. */ public function destroy(StatusPage $statusPage) { $this->authorize('delete', $statusPage); $statusPage->delete(); return redirect()->route('status-pages.index') ->with('success', 'Status page deleted successfully.'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/TestFlashController.php
app/Http/Controllers/TestFlashController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; class TestFlashController extends Controller { public function __invoke(): RedirectResponse { return redirect()->route('dashboard')->with('flash', [ 'message' => 'This is a test flash message!', 'type' => 'success', ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/UptimesDailyController.php
app/Http/Controllers/UptimesDailyController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use Illuminate\Http\Request; class UptimesDailyController extends Controller { /** * Handle the incoming request. */ public function __invoke(Request $request, Monitor $monitor) { $date = $request->query('date'); if ($date) { $uptime = $monitor->uptimesDaily()->whereDate('date', $date)->first(); if ($uptime) { return response()->json([ 'uptimes_daily' => [[ 'date' => $uptime->date->toDateString(), 'uptime_percentage' => $uptime->uptime_percentage, ]], ]); } else { return response()->json(['uptimes_daily' => []]); } } $uptimes = cache()->remember("monitor_{$monitor->id}_uptimes_daily", 60, function () use ($monitor) { return $monitor->uptimesDaily()->get()->map(function ($uptime) { return [ 'date' => $uptime->date->toDateString(), 'uptime_percentage' => $uptime->uptime_percentage, ]; }); }); return response()->json(['uptimes_daily' => $uptimes]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Controller.php
app/Http/Controllers/Controller.php
<?php namespace App\Http\Controllers; abstract class Controller { // }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/ToggleMonitorActiveController.php
app/Http/Controllers/ToggleMonitorActiveController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class ToggleMonitorActiveController extends Controller { use AuthorizesRequests; /** * Handle the incoming request. */ public function __invoke(Request $request, $monitorId): RedirectResponse { try { $user = auth()->user(); if (! $user) { return redirect()->back() ->with('flash', ['message' => 'User not authenticated', 'type' => 'error']); } // Get monitor without global scopes $monitor = Monitor::withoutGlobalScopes() ->where('id', $monitorId) ->first(); if (! $monitor) { return redirect()->back() ->with('flash', ['message' => 'Monitor not found', 'type' => 'error']); } // Check if user is subscribed to this monitor $userMonitor = $monitor->users()->where('user_id', $user->id)->first(); if (! $userMonitor) { return redirect()->back() ->with('flash', ['message' => 'User is not subscribed to this monitor', 'type' => 'error']); } // Use policy authorization $this->authorize('update', $monitor); // Toggle the active status $newStatus = ! $monitor->uptime_check_enabled; $monitor->update(['uptime_check_enabled' => $newStatus]); // Clear cache cache()->forget('public_monitors_authenticated_'.$user->id); cache()->forget('private_monitors_page_'.$user->id.'_1'); $message = $newStatus ? 'Monitor berhasil diaktifkan!' : 'Monitor berhasil dinonaktifkan!'; return redirect()->back() ->with('flash', ['message' => $message, 'type' => 'success']); } catch (\Exception $e) { return redirect()->back() ->with('flash', ['message' => 'Gagal mengubah status monitor: '.$e->getMessage(), 'type' => 'error']); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/PublicStatusPageController.php
app/Http/Controllers/PublicStatusPageController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\StatusPageResource; use App\Models\StatusPage; use App\Models\StatusPageMonitor; use Inertia\Inertia; use Inertia\Response; class PublicStatusPageController extends Controller { /** * Display the public status page (without monitors). */ public function show(string $path): Response { // Check if this request is from a custom domain $customDomainStatusPage = request()->attributes->get('custom_domain_status_page'); if ($customDomainStatusPage) { $statusPage = $customDomainStatusPage; } else { $cacheKey = 'public_status_page_'.$path; $statusPage = cache()->remember($cacheKey, 60, function () use ($path) { return StatusPage::where('path', $path)->firstOrFail(); }); } $statusPageResource = new StatusPageResource($statusPage); $appUrl = config('app.url'); $title = $statusPage->title ?? 'Status Page'; $description = $statusPage->description ?? "View the current status of {$title} services."; return Inertia::render('status-pages/Public', [ 'statusPage' => $statusPageResource, 'isAuthenticated' => auth()->check(), 'isCustomDomain' => $customDomainStatusPage !== null, ])->withViewData([ 'ogTitle' => "{$title} - Uptime Kita", 'ogDescription' => $description, 'ogImage' => "{$appUrl}/og/status/{$path}.png", 'ogUrl' => "{$appUrl}/status/{$path}", ]); } /** * Return monitors for a public status page as JSON. */ public function monitors(string $path) { $monitors = cache()->remember('public_status_page_monitors_'.$path, 60, function () { return StatusPageMonitor::with(['monitor']) ->whereHas('statusPage', function ($query) { $query->where('path', request()->route('path')); }) ->orderBy('order') ->get() ->map(function ($statusPageMonitor) { return $statusPageMonitor->monitor; }) ->filter(function ($monitor) { // only return if monitor is not null return $monitor !== null; }); }); // info($monitors); if ($monitors->isEmpty()) { return response()->json([ 'message' => 'No monitors found', ], 404); } return response()->json( \App\Http\Resources\MonitorResource::collection($monitors) ); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/UptimeMonitorController.php
app/Http/Controllers/UptimeMonitorController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\MonitorCollection; use App\Http\Resources\MonitorHistoryResource; use App\Http\Resources\MonitorResource; use App\Models\Monitor; use App\Models\MonitorHistory; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\Request; use Illuminate\Support\Facades\Artisan; use Inertia\Inertia; class UptimeMonitorController extends Controller { use AuthorizesRequests; /** * Display a listing of the monitors. */ public function index(Request $request) { $page = $request->input('page', 1); $search = $request->input('search'); $statusFilter = $request->input('status_filter', 'all'); $perPage = $request->input('per_page', '15'); $visibilityFilter = $request->input('visibility_filter', 'all'); $tagFilter = $request->input('tag_filter'); $cacheKey = 'monitors_list_page_'.$page.'_per_page_'.$perPage.'_user_'.auth()->id(); if ($search) { $cacheKey .= '_search_'.md5($search); } if ($statusFilter !== 'all') { $cacheKey .= '_filter_'.$statusFilter; } if ($visibilityFilter !== 'all') { $cacheKey .= '_visibility_'.$visibilityFilter; } if ($tagFilter) { $cacheKey .= '_tag_'.md5($tagFilter); } $monitors = cache()->remember($cacheKey, 60, function () use ($search, $statusFilter, $visibilityFilter, $tagFilter, $perPage) { $query = Monitor::with(['uptimeDaily', 'tags'])->search($search); if ($statusFilter === 'up' || $statusFilter === 'down') { $query->where('uptime_status', $statusFilter); } if ($visibilityFilter === 'public') { $query->public(); } elseif ($visibilityFilter === 'private') { $query->private(); } if ($tagFilter) { $query->withAnyTags([$tagFilter]); } return new MonitorCollection( $query->orderBy('created_at', 'desc')->paginate($perPage) ); }); $flash = session('flash'); // Get all unique tags used in monitors $availableTags = \Spatie\Tags\Tag::whereIn('id', function ($query) { $query->select('tag_id') ->from('taggables') ->where('taggable_type', 'App\Models\Monitor'); })->orderBy('name')->get(['id', 'name']); return Inertia::render('uptime/Index', [ 'monitors' => $monitors, 'flash' => $flash, 'search' => $search, 'statusFilter' => $statusFilter, 'perPage' => $perPage, 'visibilityFilter' => $visibilityFilter, 'tagFilter' => $tagFilter, 'availableTags' => $availableTags, ]); } /** * Show the monitor by id. */ public function show(Monitor $monitor) { // implements cache for monitor data with histories included $monitorData = cache()->remember("monitor_{$monitor->id}", 60, function () use ($monitor) { // Get unique history IDs using raw SQL to ensure only one record per minute $sql = " SELECT id FROM ( SELECT id, created_at, ROW_NUMBER() OVER ( PARTITION BY monitor_id, strftime('%Y-%m-%d %H:%M', created_at) ORDER BY created_at DESC, id DESC ) as rn FROM monitor_histories WHERE monitor_id = ? ) ranked WHERE rn = 1 ORDER BY created_at DESC LIMIT 100 "; $uniqueIds = \DB::select($sql, [$monitor->id]); $ids = array_column($uniqueIds, 'id'); $uniqueHistories = MonitorHistory::whereIn('id', $ids) ->orderBy('created_at', 'desc') ->get(); $monitor->load(['uptimeDaily', 'tags']); $monitor->setRelation('histories', $uniqueHistories); return new MonitorResource($monitor); }); return Inertia::render('uptime/Show', [ 'monitor' => $monitorData, ]); } public function getHistory(Monitor $monitor) { $histories = cache()->remember("monitor_{$monitor->id}_histories", 60, function () use ($monitor) { // Get unique history IDs using raw SQL to ensure only one record per minute $sql = " SELECT id FROM ( SELECT id, created_at, ROW_NUMBER() OVER ( PARTITION BY monitor_id, strftime('%Y-%m-%d %H:%M', created_at) ORDER BY created_at DESC, id DESC ) as rn FROM monitor_histories WHERE monitor_id = ? ) ranked WHERE rn = 1 ORDER BY created_at DESC LIMIT 100 "; $uniqueIds = \DB::select($sql, [$monitor->id]); $ids = array_column($uniqueIds, 'id'); $uniqueHistories = MonitorHistory::whereIn('id', $ids) ->orderBy('created_at', 'desc') ->get(); return MonitorHistoryResource::collection($uniqueHistories); }); return response()->json([ 'histories' => $histories->toArray(request()), ]); } /** * Show the form for creating a new monitor. */ public function create() { return Inertia::render('uptime/Create'); } /** * Store a newly created monitor in storage. */ public function store(Request $request) { // sanitize url and enforce HTTPS $url = rtrim(filter_var($request->url, FILTER_VALIDATE_URL), '/'); // Convert HTTP to HTTPS if (str_starts_with($url, 'http://')) { $url = 'https://'.substr($url, 7); } $request->merge(['url' => $url]); $monitor = Monitor::withoutGlobalScope('user') ->where('url', $url) ->first(); if ($monitor) { // attach to user $monitor->users()->attach(auth()->id(), ['is_active' => true]); return redirect()->route('monitor.index') ->with('flash', ['message' => 'Monitor berhasil ditambahkan!', 'type' => 'success']); } $request->validate([ 'url' => ['required', 'url', 'unique:monitors,url'], 'uptime_check_enabled' => ['boolean'], 'certificate_check_enabled' => ['boolean'], 'uptime_check_interval' => ['required', 'integer', 'min:1'], 'tags' => ['nullable', 'array'], 'tags.*' => ['string', 'max:255'], ]); try { $monitor = Monitor::create([ 'url' => $url, 'is_public' => $request->boolean('is_public', false), 'uptime_check_enabled' => $request->boolean('uptime_check_enabled'), 'certificate_check_enabled' => $request->boolean('certificate_check_enabled'), 'uptime_check_interval_in_minutes' => $request->uptime_check_interval, ]); // Attach tags if provided if ($request->filled('tags')) { $monitor->attachTags($request->tags); } // check certificate using command Artisan::call('monitor:check-certificate', [ '--url' => $monitor->url, ]); // remove cache index cache()->forget('monitor_list_page_1_per_page_15_user_'.auth()->id()); return redirect()->route('monitor.index') ->with('flash', ['message' => 'Monitor berhasil ditambahkan!', 'type' => 'success']); } catch (\Exception $e) { return redirect()->back() ->with('flash', ['message' => 'Gagal menambahkan monitor: '.$e->getMessage(), 'type' => 'error']) ->withInput(); } } /** * Show the form for editing the specified monitor. */ public function edit(Monitor $monitor) { return Inertia::render('uptime/Edit', [ 'monitor' => new MonitorResource($monitor->load(['uptimeDaily', 'tags'])), ]); } /** * Update the specified monitor in storage. */ public function update(Request $request, Monitor $monitor) { $this->authorize('update', $monitor); $url = rtrim(filter_var($request->url, FILTER_VALIDATE_URL), '/'); // Convert HTTP to HTTPS if (str_starts_with($url, 'http://')) { $url = 'https://'.substr($url, 7); } $monitorExists = Monitor::withoutGlobalScope('user') ->where('url', $url) ->where('uptime_check_interval_in_minutes', $request->uptime_check_interval) ->where('is_public', 0) ->whereDoesntHave('users', function ($query) { $query->where('user_id', auth()->id()); }) ->first(); if ($monitorExists) { // attach to user $monitorExists->users()->sync(auth()->id(), ['is_active' => true]); return redirect()->route('monitor.index') ->with('flash', ['message' => 'Monitor berhasil diperbarui!', 'type' => 'success']); } $request->validate([ 'url' => ['required', 'url', 'unique:monitors,url,'.$monitor->id], 'uptime_check_enabled' => ['boolean'], 'certificate_check_enabled' => ['boolean'], 'uptime_check_interval' => ['required', 'integer', 'min:1'], 'tags' => ['nullable', 'array'], 'tags.*' => ['string', 'max:255'], 'sensitivity' => ['nullable', 'string', 'in:low,medium,high'], 'confirmation_delay_seconds' => ['nullable', 'integer', 'min:5', 'max:300'], 'confirmation_retries' => ['nullable', 'integer', 'min:1', 'max:10'], ]); try { $monitor->update([ 'url' => $request->url, 'is_public' => $request->boolean('is_public', false), 'uptime_check_enabled' => $request->boolean('uptime_check_enabled'), 'certificate_check_enabled' => $request->boolean('certificate_check_enabled'), 'uptime_check_interval_in_minutes' => $request->uptime_check_interval, 'sensitivity' => $request->input('sensitivity', 'medium'), 'confirmation_delay_seconds' => $request->input('confirmation_delay_seconds'), 'confirmation_retries' => $request->input('confirmation_retries'), ]); // Sync tags if ($request->has('tags')) { $monitor->syncTags($request->tags ?? []); } return redirect()->route('monitor.index') ->with('flash', ['message' => 'Monitor berhasil diperbarui!', 'type' => 'success']); } catch (\Exception $e) { return redirect()->back() ->with('flash', ['message' => 'Gagal memperbarui monitor: '.$e->getMessage(), 'type' => 'error']) ->withInput(); } } /** * Remove the specified monitor from storage. */ public function destroy(Monitor $monitor) { try { // if monitor is not owned by the logged in user, detach from user if (! $monitor->isOwnedBy(auth()->user()) && ! auth()->user()?->is_admin) { $monitor->users()->detach(auth()->id()); } else { if (! auth()->user()?->is_admin) { $this->authorize('delete', $monitor); } $monitor->delete(); } // remove cache index cache()->forget('monitor_list_page_1_per_page_15_user_'.auth()->id()); return redirect()->route('monitor.index') ->with('flash', ['message' => 'Monitor berhasil dihapus!', 'type' => 'success']); } catch (\Exception $e) { return redirect()->back() ->with('flash', ['message' => 'Gagal menghapus monitor: '.$e->getMessage(), 'type' => 'error']); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/LatestHistoryController.php
app/Http/Controllers/LatestHistoryController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\MonitorHistoryResource; use App\Models\Monitor; use Illuminate\Http\Request; class LatestHistoryController extends Controller { /** * Handle the incoming request. */ public function __invoke(Request $request, Monitor $monitor) { $latestHistory = cache()->remember("monitor_{$monitor->id}_latest_history", 60, function () use ($monitor) { return $monitor->latestHistory()->first(); }); return response()->json([ 'latest_history' => $latestHistory ? new MonitorHistoryResource($latestHistory) : null, ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/DebugStatsController.php
app/Http/Controllers/DebugStatsController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use App\Models\MonitorHistory; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class DebugStatsController extends Controller { public function __invoke(Request $request) { $results = [ 'timezone' => config('app.timezone'), 'current_time' => now()->toString(), 'today' => today()->toString(), 'cache_keys' => [ 'daily_checks' => cache()->has('public_monitors_daily_checks'), 'monthly_checks' => cache()->has('public_monitors_monthly_checks'), ], ]; // Get public monitor count $results['public_monitors_count'] = Monitor::where('is_public', true)->count(); // Get monitor_statistics data $results['monitor_statistics'] = [ 'total_rows' => DB::table('monitor_statistics')->count(), 'sum_24h' => DB::table('monitor_statistics') ->join('monitors', 'monitor_statistics.monitor_id', '=', 'monitors.id') ->where('monitors.is_public', true) ->sum('monitor_statistics.total_checks_24h'), 'sum_30d' => DB::table('monitor_statistics') ->join('monitors', 'monitor_statistics.monitor_id', '=', 'monitors.id') ->where('monitors.is_public', true) ->sum('monitor_statistics.total_checks_30d'), ]; // Get monitor_histories data $results['monitor_histories'] = [ 'total_rows' => MonitorHistory::count(), 'public_monitor_checks_today' => MonitorHistory::whereIn('monitor_id', function ($query) { $query->select('id') ->from('monitors') ->where('is_public', true); }) ->whereDate('checked_at', today()) ->count(), 'public_monitor_checks_this_month' => MonitorHistory::whereIn('monitor_id', function ($query) { $query->select('id') ->from('monitors') ->where('is_public', true); }) ->whereMonth('checked_at', now()->month) ->whereYear('checked_at', now()->year) ->count(), 'latest_check' => MonitorHistory::latest('checked_at')->first(['checked_at'])?->checked_at, ]; // Raw SQL queries for verification $results['raw_queries'] = [ 'daily_direct' => DB::select(" SELECT COUNT(*) as count FROM monitor_histories WHERE monitor_id IN ( SELECT id FROM monitors WHERE is_public = 1 ) AND DATE(checked_at) = DATE('now', 'localtime') ")[0]->count ?? 0, 'monthly_direct' => DB::select(" SELECT COUNT(*) as count FROM monitor_histories WHERE monitor_id IN ( SELECT id FROM monitors WHERE is_public = 1 ) AND strftime('%Y-%m', checked_at) = strftime('%Y-%m', 'now', 'localtime') ")[0]->count ?? 0, ]; // Clear cache if requested if ($request->get('clear_cache')) { cache()->forget('public_monitors_daily_checks'); cache()->forget('public_monitors_monthly_checks'); $results['cache_cleared'] = true; } return response()->json($results); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/CustomDomainController.php
app/Http/Controllers/CustomDomainController.php
<?php namespace App\Http\Controllers; use App\Models\StatusPage; use Illuminate\Http\Request; use Illuminate\Validation\Rule; class CustomDomainController extends Controller { /** * Update or set a custom domain for a status page. */ public function update(Request $request, StatusPage $statusPage) { // Ensure user owns this status page if ($statusPage->user_id !== auth()->id()) { abort(403, 'Unauthorized'); } $validated = $request->validate([ 'custom_domain' => [ 'nullable', 'string', 'max:255', 'regex:/^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i', Rule::unique('status_pages')->ignore($statusPage->id), ], 'force_https' => 'boolean', ]); // If domain is being changed, reset verification if ($statusPage->custom_domain !== $validated['custom_domain']) { $statusPage->custom_domain_verified = false; $statusPage->custom_domain_verified_at = null; // Generate new verification token if domain is set if ($validated['custom_domain']) { $statusPage->generateVerificationToken(); } else { $statusPage->custom_domain_verification_token = null; } } $statusPage->update([ 'custom_domain' => $validated['custom_domain'], 'force_https' => $validated['force_https'] ?? true, ]); // Clear cache cache()->forget('public_status_page_'.$statusPage->path); return back()->with('flash', [ 'type' => 'success', 'message' => $validated['custom_domain'] ? 'Custom domain updated. Please verify DNS settings.' : 'Custom domain removed.', ]); } /** * Verify custom domain DNS settings. */ public function verify(StatusPage $statusPage) { // Ensure user owns this status page if ($statusPage->user_id !== auth()->id()) { abort(403, 'Unauthorized'); } if (! $statusPage->custom_domain) { return back()->with('flash', [ 'type' => 'error', 'message' => 'No custom domain configured.', ]); } $verified = $statusPage->verifyCustomDomain(); if ($verified) { // Clear cache cache()->forget('public_status_page_'.$statusPage->path); return back()->with('flash', [ 'type' => 'success', 'message' => 'Domain verified successfully!', ]); } return back()->with('flash', [ 'type' => 'error', 'message' => 'Domain verification failed. Please check your DNS settings.', ]); } /** * Get DNS instructions for domain verification. */ public function dnsInstructions(StatusPage $statusPage) { // Ensure user owns this status page if ($statusPage->user_id !== auth()->id()) { abort(403, 'Unauthorized'); } if (! $statusPage->custom_domain) { return response()->json([ 'error' => 'No custom domain configured.', ], 400); } // Generate token if not exists if (! $statusPage->custom_domain_verification_token) { $statusPage->generateVerificationToken(); } return response()->json([ 'domain' => $statusPage->custom_domain, 'verification_token' => $statusPage->custom_domain_verification_token, 'dns_records' => [ [ 'type' => 'TXT', 'name' => '_uptime-kita.'.$statusPage->custom_domain, 'value' => $statusPage->custom_domain_verification_token, 'ttl' => 3600, ], [ 'type' => 'CNAME', 'name' => $statusPage->custom_domain, 'value' => parse_url(config('app.url'), PHP_URL_HOST), 'ttl' => 3600, 'note' => 'Point your domain to our servers', ], ], ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/PrivateMonitorController.php
app/Http/Controllers/PrivateMonitorController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\MonitorCollection; use App\Models\Monitor; use Illuminate\Http\Request; class PrivateMonitorController extends Controller { /** * Handle the incoming request. */ public function __invoke(Request $request) { $page = $request->input('page', 1); $search = $request->input('search'); $statusFilter = $request->input('status_filter', 'all'); // Build cache key based on search query and status filter $cacheKey = 'private_monitors_page_'.auth()->id().'_'.$page; if ($search) { $cacheKey .= '_search_'.md5($search); } if ($statusFilter !== 'all') { $cacheKey .= '_filter_'.$statusFilter; } $monitors = cache()->remember($cacheKey, 60, function () use ($search, $statusFilter) { $baseQuery = Monitor::query() ->where('is_public', false) ->whereHas('users', function ($query) { $query->where('user_monitor.is_pinned', false); }) ->with(['users:id', 'uptimeDaily']); if ($statusFilter === 'disabled') { // User-specific disabled: monitors where user has is_active = false $query = $baseQuery->whereHas('users', function ($query) { $query->where('user_id', auth()->id()); $query->where('user_monitor.is_active', false); }) ->orderBy('created_at', 'desc'); } elseif ($statusFilter === 'globally_enabled') { $query = $baseQuery->withoutGlobalScope('enabled') ->where('uptime_check_enabled', true) ->orderBy('created_at', 'desc'); } elseif ($statusFilter === 'globally_disabled') { $query = $baseQuery->withoutGlobalScope('enabled') ->where('uptime_check_enabled', false) ->orderBy('created_at', 'desc'); } else { $query = $baseQuery->orderBy('created_at', 'desc'); if ($statusFilter === 'up' || $statusFilter === 'down') { $query->where('uptime_status', $statusFilter); } } // Apply search filter if provided if ($search && strlen($search) >= 3) { $query->where(function ($q) use ($search) { $q->where('url', 'like', "%$search%") ->orWhereRaw('REPLACE(REPLACE(url, "https://", ""), "http://", "") LIKE ?', ["%$search%"]); }); } return new MonitorCollection($query->paginate(12)); }); return response()->json($monitors); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/UserController.php
app/Http/Controllers/UserController.php
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Inertia\Inertia; class UserController extends Controller { /** * Display a listing of the resource. */ public function index(Request $request) { $query = User::query() ->withCount('monitors') ->withCount('statusPages') ->withCount('notificationChannels'); // Search functionality if ($request->filled('search') && strlen($request->search) >= 3) { $query->where(function ($q) use ($request) { $q->where('name', 'like', '%'.$request->search.'%') ->orWhere('email', 'like', '%'.$request->search.'%'); }); } // Per page functionality $perPage = $request->get('per_page', 15); if (! in_array($perPage, [5, 10, 15, 20, 50, 100])) { $perPage = 15; } $users = $query->paginate($perPage); return Inertia::render('users/Index', [ 'users' => $users, 'search' => $request->search, 'perPage' => (int) $perPage, ]); } /** * Show the form for creating a new resource. */ public function create() { return Inertia::render('users/Create'); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8|confirmed', ]); User::create([ 'name' => $validated['name'], 'email' => $validated['email'], 'password' => bcrypt($validated['password']), ]); return redirect()->route('users.index')->with('success', 'User created successfully.'); } /** * Display the specified resource. */ public function show(User $user) { $user->load([ 'monitors' => function ($query) { $query->select('monitors.id', 'monitors.display_name', 'monitors.url', 'monitors.uptime_status', 'monitors.created_at') ->withPivot(['is_active', 'is_pinned', 'created_at']); }, 'statusPages' => function ($query) { $query->select('id', 'user_id', 'title', 'description', 'path', 'created_at'); }, 'notificationChannels' => function ($query) { $query->select('id', 'user_id', 'type', 'destination', 'is_enabled', 'created_at'); }, ]); return Inertia::render('users/Show', [ 'user' => $user, ]); } /** * Show the form for editing the specified resource. */ public function edit(User $user) { // Ensure the user is not the default admin user if ($user->id === 1) { return redirect()->route('users.index')->with('error', 'Cannot edit the default admin user.'); } return Inertia::render('users/Edit', [ 'user' => $user, ]); } /** * Update the specified resource in storage. */ public function update(Request $request, User $user) { // Ensure the user is not the default admin user if ($user->id === 1) { return redirect()->route('users.index')->with('error', 'Cannot edit the default admin user.'); } $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users,email,'.$user->id, 'password' => 'nullable|string|min:8|confirmed', ]); $user->name = $validated['name']; $user->email = $validated['email']; if (! empty($validated['password'])) { $user->password = bcrypt($validated['password']); } $user->save(); return redirect()->route('users.index')->with('success', 'User updated successfully.'); } /** * Remove the specified resource from storage. */ public function destroy(User $user) { $errorMessage = null; if ($user->id === 1) { $errorMessage = 'Cannot delete the default admin user.'; } elseif ($user->monitors()->count() > 0) { $errorMessage = 'Cannot delete user with associated monitors.'; } elseif ($user->statusPages()->count() > 0) { $errorMessage = 'Cannot delete user with associated status pages.'; } if ($errorMessage) { return redirect()->route('users.index')->with('error', $errorMessage); } $user->delete(); return redirect()->route('users.index')->with('success', 'User deleted successfully.'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/TelegramWebhookController.php
app/Http/Controllers/TelegramWebhookController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use NotificationChannels\Telegram\TelegramMessage; class TelegramWebhookController extends Controller { public function handle(Request $request) { // Mengambil update dari request yang dikirim Telegram $updates = $request->all(); // info('request', $request->all()); // --- BAGIAN YANG DIPERBAIKI TOTAL --- // Periksa apakah update berisi 'message' dan di dalamnya ada 'text' if (isset($updates['message']) && isset($updates['message']['text'])) { $message = $updates['message']; // Ambil data langsung dari properti array $chatId = $message['chat']['id']; $firstName = $message['from']['first_name']; // Periksa secara manual apakah teksnya adalah '/start' if ($message['text'] === '/start') { $responseText = "Halo, {$firstName}!\n\n" .'Terima kasih telah memulai bot. ' ."Gunakan Chat ID berikut untuk menerima notifikasi dari Uptime Monitor:\n\n`{$chatId}`"; // Mengirim balasan menggunakan TelegramMessage TelegramMessage::create($responseText) ->to($chatId) ->options(['parse_mode' => 'Markdown']) ->send(); info('send message success'); } } // --- AKHIR BAGIAN YANG DIPERBAIKI --- return response()->json(['status' => 'ok']); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/PinnedMonitorController.php
app/Http/Controllers/PinnedMonitorController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\MonitorCollection; use App\Models\Monitor; use Illuminate\Http\Request; class PinnedMonitorController extends Controller { /** * Get all pinned monitors for the authenticated user. */ public function index(Request $request) { $page = $request->input('page', 1); $search = $request->input('search'); $statusFilter = $request->input('status_filter', 'all'); // Build cache key based on search query and status filter $cacheKey = 'pinned_monitors_page_'.auth()->id().'_'.$page; if ($search) { $cacheKey .= '_search_'.md5($search); } if ($statusFilter !== 'all') { $cacheKey .= '_filter_'.$statusFilter; } $monitors = cache()->remember($cacheKey, 60, function () use ($search, $statusFilter) { $baseQuery = Monitor::withoutGlobalScope('user') ->whereHas('users', function ($query) { $query->where('user_monitor.user_id', auth()->id()) ->where('user_monitor.is_pinned', true); }) ->with(['users:id', 'uptimeDaily']); if ($statusFilter === 'disabled') { // User-specific disabled: monitors where user has is_active = false $query = $baseQuery->whereHas('users', function ($query) { $query->where('user_id', auth()->id()); $query->where('user_monitor.is_active', false); }) ->orderBy('created_at', 'desc'); } elseif ($statusFilter === 'globally_enabled') { $query = $baseQuery->withoutGlobalScope('enabled') ->where('uptime_check_enabled', true) ->orderBy('created_at', 'desc'); } elseif ($statusFilter === 'globally_disabled') { $query = $baseQuery->withoutGlobalScope('enabled') ->where('uptime_check_enabled', false) ->orderBy('created_at', 'desc'); } else { $query = $baseQuery->orderBy('created_at', 'desc'); if ($statusFilter === 'up' || $statusFilter === 'down') { $query->where('uptime_status', $statusFilter); } } // Apply search filter if provided if ($search && strlen($search) >= 3) { $query->where(function ($q) use ($search) { $q->where('url', 'like', "%$search%") ->orWhereRaw('REPLACE(REPLACE(url, "https://", ""), "http://", "") LIKE ?', ["%$search%"]); }); } return new MonitorCollection($query->paginate(12)); }); return response()->json($monitors); } /** * Toggle pin status for a monitor. */ public function toggle(Request $request, $monitorId) { // Validate the request $request->validate([ 'is_pinned' => 'required|boolean', ]); // Find the monitor without global scopes $monitor = Monitor::withoutGlobalScope('user')->withoutGlobalScope('enabled')->find($monitorId); if (! $monitor) { if ($request->wantsJson()) { return response()->json([ 'success' => false, 'message' => 'Monitor not found.', ], 404); } abort(404); } $user = auth()->user(); // Get the pivot record directly from the database // Need to remove global scopes to handle disabled monitors $pivotRecord = $user->monitors() ->withoutGlobalScopes() ->wherePivot('monitor_id', $monitor->id) ->withPivot('is_pinned', 'is_active') ->first(); $isPinned = $request->input('is_pinned'); if (! $pivotRecord) { // User is not subscribed to this monitor if ($isPinned) { // If trying to pin any monitor they're not subscribed to if ($request->wantsJson()) { return response()->json([ 'success' => false, 'message' => 'You must be subscribed to this monitor to pin it.', ], 403); } return back()->with('flash', [ 'type' => 'error', 'message' => 'You must be subscribed to this monitor to pin it.', ]); } // If unpinning a monitor they're not subscribed to, just return success $newPinnedStatus = false; } else { // Update the pinned status // Need to use withoutGlobalScopes to handle disabled monitors $user->monitors()->withoutGlobalScopes()->updateExistingPivot($monitor->id, [ 'is_pinned' => $isPinned, ]); $newPinnedStatus = $isPinned; } // Clear related caches $userId = auth()->id(); cache()->forget("is_pinned_{$monitor->id}_{$userId}"); // Clear monitor listing caches $cacheKeys = [ "pinned_monitors_page_{$userId}_1", "private_monitors_page_{$userId}_1", "public_monitors_authenticated_{$userId}_1", "public_monitors_authenticated_{$userId}", // Also clear this cache variant ]; foreach ($cacheKeys as $key) { cache()->forget($key); } // Return appropriate response if ($request->wantsJson()) { return response()->json([ 'success' => true, 'is_pinned' => $newPinnedStatus, 'message' => $newPinnedStatus ? 'Monitor pinned successfully' : 'Monitor unpinned successfully', ]); } return back()->with('flash', [ 'type' => 'success', 'message' => $newPinnedStatus ? 'Monitor pinned successfully' : 'Monitor unpinned successfully', ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/PublicMonitorController.php
app/Http/Controllers/PublicMonitorController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\MonitorCollection; use App\Models\Monitor; use App\Models\MonitorHistory; use App\Models\MonitorIncident; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Inertia\Inertia; class PublicMonitorController extends Controller { /** * Display the public monitors page. */ public function index(Request $request) { // $authenticated = auth()->check(); // Ensure page is numeric and valid $page = (int) $request->get('page', 1); if ($page < 1) { $page = 1; } $perPage = min((int) $request->get('per_page', 15), 100); // Max 100 monitors per page, default 15 $search = $request->get('search'); $statusFilter = $request->get('status_filter', 'all'); $tagFilter = $request->get('tag_filter'); $sortBy = $request->get('sort_by', 'default'); // Default sort by id if ($search && mb_strlen($search) < 3) { $search = null; } // Validate sort option $validSortOptions = ['default', 'popular', 'uptime', 'response_time', 'newest', 'name', 'status']; if (! in_array($sortBy, $validSortOptions)) { $sortBy = 'default'; } // Differentiate cache keys for authenticated and guest users, and also by page number $cacheKey = 'public_monitors_page_'.$page.'_sort_'.$sortBy; if ($search) { $cacheKey .= '_search_'.md5($search); } if ($statusFilter !== 'all') { $cacheKey .= '_filter_'.$statusFilter; } if ($tagFilter) { $cacheKey .= '_tag_'.md5($tagFilter); } $publicMonitors = cache()->remember($cacheKey, 60, function () use ($page, $perPage, $search, $statusFilter, $tagFilter, $sortBy) { // Always only show public monitors $query = Monitor::withoutGlobalScope('user') ->with([ 'users:id', 'uptimeDaily', 'tags', 'statistics', 'uptimesDaily' => function ($query) { $query->where('date', '>=', now()->subDays(7)->toDateString()) ->orderBy('date', 'asc'); }, ]) ->public(); // Exclude pinned monitors for authenticated users // if (auth()->check()) { // $query->whereDoesntHave('users', function ($subQuery) { // $subQuery->where('user_id', auth()->id()) // ->where('user_monitor.is_pinned', true); // }); // } // Apply status filter if ($statusFilter === 'up' || $statusFilter === 'down') { $query->where('uptime_status', $statusFilter); } elseif ($statusFilter === 'disabled' || $statusFilter === 'globally_disabled') { $query->withoutGlobalScope('enabled')->where('uptime_check_enabled', false); } elseif ($statusFilter === 'globally_enabled') { $query->withoutGlobalScope('enabled')->where('uptime_check_enabled', true); } elseif ($statusFilter === 'unsubscribed') { $query->whereDoesntHave('users', function ($query) { $query->where('user_id', auth()->id()); }); } if ($search) { $query->search($search); } // Apply tag filter if ($tagFilter) { $query->withAnyTags([$tagFilter]); } // Apply sorting switch ($sortBy) { case 'popular': $query->orderBy('page_views_count', 'desc'); break; case 'uptime': $query->leftJoin('monitor_statistics', 'monitors.id', '=', 'monitor_statistics.monitor_id') ->orderByRaw('COALESCE(monitor_statistics.uptime_24h, 0) DESC') ->select('monitors.*'); break; case 'response_time': $query->leftJoin('monitor_statistics', 'monitors.id', '=', 'monitor_statistics.monitor_id') ->orderByRaw('COALESCE(monitor_statistics.avg_response_time_24h, 999999) ASC') ->select('monitors.*'); break; case 'name': $query->orderBy('url', 'asc'); break; case 'status': $query->orderByRaw("CASE WHEN uptime_status = 'down' THEN 0 WHEN uptime_status = 'up' THEN 1 ELSE 2 END"); break; case 'newest': $query->orderBy('created_at', 'desc'); break; case 'default': default: $query->orderBy('id', 'asc'); break; } return new MonitorCollection( $query->paginate($perPage, ['*'], 'page', $page) ); }); // Check if request wants JSON response (for load more functionality) if ($request->wantsJson() || $request->header('Accept') === 'application/json') { return response()->json($publicMonitors); } // Get all unique tags used in public monitors $availableTags = \Spatie\Tags\Tag::whereIn('id', function ($query) { $query->select('tag_id') ->from('taggables') ->where('taggable_type', 'App\Models\Monitor') ->whereIn('taggable_id', function ($subQuery) { $subQuery->select('id') ->from('monitors') ->where('is_public', true); }); })->orderBy('name')->get(['id', 'name']); // Get latest incidents for public monitors $latestIncidents = cache()->remember('public_monitors_latest_incidents', 300, function () { return MonitorIncident::with(['monitor:id,url,name,is_public']) ->whereHas('monitor', function ($query) { $query->where('is_public', true); }) ->orderBy('started_at', 'desc') ->limit(10) ->get(['id', 'monitor_id', 'type', 'started_at', 'ended_at', 'duration_minutes', 'reason', 'status_code']); }); $appUrl = config('app.url'); $upCount = Monitor::public()->where('uptime_status', 'up')->count(); $totalPublic = Monitor::public()->count(); return Inertia::render('monitors/PublicIndex', [ 'monitors' => $publicMonitors, 'filters' => [ 'search' => $search, 'status_filter' => $statusFilter, 'tag_filter' => $tagFilter, 'sort_by' => $sortBy, ], 'availableTags' => $availableTags, 'latestIncidents' => $latestIncidents, 'stats' => [ 'total' => $publicMonitors->total(), 'up' => $upCount, 'down' => Monitor::public()->where('uptime_status', 'down')->count(), 'total_public' => $totalPublic, 'daily_checks' => $this->getDailyChecksCount(), 'monthly_checks' => $this->getMonthlyChecksCount(), ], ])->withViewData([ 'ogTitle' => 'Public Monitors - Uptime Kita', 'ogDescription' => "Monitoring {$totalPublic} public services. {$upCount} services are up and running.", 'ogImage' => "{$appUrl}/og/monitors.png", 'ogUrl' => "{$appUrl}/public-monitors", ]); } /** * Handle the incoming request for JSON API. */ public function __invoke(Request $request) { $authenticated = auth()->check(); // Ensure page is numeric and valid $page = (int) $request->get('page', 1); if ($page < 1) { $page = 1; } $perPage = min((int) $request->get('per_page', 15), 100); // Max 100 monitors per page, default 15 $search = $request->get('search'); $statusFilter = $request->get('status_filter', 'all'); $tagFilter = $request->get('tag_filter'); $sortBy = $request->get('sort_by', 'default'); if ($search && mb_strlen($search) < 3) { $search = null; } // Validate sort option $validSortOptions = ['default', 'popular', 'uptime', 'response_time', 'newest', 'name', 'status']; if (! in_array($sortBy, $validSortOptions)) { $sortBy = 'default'; } // Differentiate cache keys for authenticated and guest users, and also by page number $cacheKey = ($authenticated ? 'public_monitors_authenticated_'.auth()->id() : 'public_monitors_guest').'_page_'.$page.'_sort_'.$sortBy; if ($search) { $cacheKey .= '_search_'.md5($search); } if ($statusFilter !== 'all') { $cacheKey .= '_filter_'.$statusFilter; } if ($tagFilter) { $cacheKey .= '_tag_'.md5($tagFilter); } $publicMonitors = cache()->remember($cacheKey, 60, function () use ($page, $perPage, $search, $statusFilter, $tagFilter, $sortBy) { // Always only show public monitors $query = Monitor::withoutGlobalScope('user') ->with([ 'users:id', 'uptimeDaily', 'tags', 'statistics', 'uptimesDaily' => function ($query) { $query->where('date', '>=', now()->subDays(7)->toDateString()) ->orderBy('date', 'asc'); }, ]) ->public(); // Exclude pinned monitors for authenticated users if (auth()->check()) { $query->whereDoesntHave('users', function ($subQuery) { $subQuery->where('user_id', auth()->id()) ->where('user_monitor.is_pinned', true); }); } // Apply status filter if ($statusFilter === 'up' || $statusFilter === 'down') { $query->where('uptime_status', $statusFilter); } elseif ($statusFilter === 'disabled' || $statusFilter === 'globally_disabled') { $query->withoutGlobalScope('enabled')->where('uptime_check_enabled', false); } elseif ($statusFilter === 'globally_enabled') { $query->withoutGlobalScope('enabled')->where('uptime_check_enabled', true); } elseif ($statusFilter === 'unsubscribed') { $query->whereDoesntHave('users', function ($query) { $query->where('user_id', auth()->id()); }); } if ($search) { $query->search($search); } // Apply tag filter if ($tagFilter) { $query->withAnyTags([$tagFilter]); } // Apply sorting switch ($sortBy) { case 'popular': $query->orderBy('page_views_count', 'desc'); break; case 'uptime': $query->leftJoin('monitor_statistics', 'monitors.id', '=', 'monitor_statistics.monitor_id') ->orderByRaw('COALESCE(monitor_statistics.uptime_24h, 0) DESC') ->select('monitors.*'); break; case 'response_time': $query->leftJoin('monitor_statistics', 'monitors.id', '=', 'monitor_statistics.monitor_id') ->orderByRaw('COALESCE(monitor_statistics.avg_response_time_24h, 999999) ASC') ->select('monitors.*'); break; case 'name': $query->orderBy('url', 'asc'); break; case 'status': $query->orderByRaw("CASE WHEN uptime_status = 'down' THEN 0 WHEN uptime_status = 'up' THEN 1 ELSE 2 END"); break; case 'newest': $query->orderBy('created_at', 'desc'); break; case 'default': default: $query->orderBy('id', 'asc'); break; } return new MonitorCollection( $query->paginate($perPage, ['*'], 'page', $page) ); }); return response()->json($publicMonitors); } /** * Get the total number of checks performed today for public monitors. */ private function getDailyChecksCount(): int { // Cache the daily checks count for 15 minutes return cache()->remember('public_monitors_daily_checks', 900, function () { // First try to get from monitor_statistics table (if data exists) $statsCount = DB::table('monitor_statistics') ->join('monitors', 'monitor_statistics.monitor_id', '=', 'monitors.id') ->where('monitors.is_public', true) ->sum('monitor_statistics.total_checks_24h'); if ($statsCount > 0) { return (int) $statsCount; } // Fallback to counting from monitor_histories for today return MonitorHistory::whereIn('monitor_id', function ($query) { $query->select('id') ->from('monitors') ->where('is_public', true); }) ->whereDate('checked_at', today()) ->count(); }); } /** * Get the total number of checks performed this month for public monitors. */ private function getMonthlyChecksCount(): int { // Cache the monthly checks count for 1 hour return cache()->remember('public_monitors_monthly_checks', 3600, function () { // First try to get from monitor_statistics table (if data exists) $statsCount = DB::table('monitor_statistics') ->join('monitors', 'monitor_statistics.monitor_id', '=', 'monitors.id') ->where('monitors.is_public', true) ->sum('monitor_statistics.total_checks_30d'); if ($statsCount > 0) { return (int) $statsCount; } // Fallback to counting from monitor_histories for the current month return MonitorHistory::whereIn('monitor_id', function ($query) { $query->select('id') ->from('monitors') ->where('is_public', true); }) ->whereMonth('checked_at', now()->month) ->whereYear('checked_at', now()->year) ->count(); }); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/TelemetryDashboardController.php
app/Http/Controllers/TelemetryDashboardController.php
<?php namespace App\Http\Controllers; use App\Models\TelemetryPing; use Illuminate\Http\JsonResponse; use Inertia\Inertia; use Inertia\Response; use Symfony\Component\HttpFoundation\Response as HttpResponse; class TelemetryDashboardController extends Controller { /** * Display the telemetry dashboard. */ public function index(): Response|JsonResponse { if (! auth()->user()?->is_admin) { abort(HttpResponse::HTTP_FORBIDDEN, 'Only administrators can access telemetry dashboard.'); } // Check if receiver is enabled if (! config('telemetry.receiver_enabled')) { return Inertia::render('admin/TelemetryDashboard', [ 'receiverEnabled' => false, 'statistics' => null, 'versionDistribution' => null, 'osDistribution' => null, 'growthData' => null, 'recentPings' => [], ]); } return Inertia::render('admin/TelemetryDashboard', [ 'receiverEnabled' => true, 'statistics' => TelemetryPing::getStatistics(), 'versionDistribution' => TelemetryPing::getVersionDistribution(), 'osDistribution' => TelemetryPing::getOsDistribution(), 'growthData' => TelemetryPing::getGrowthData(12), 'recentPings' => TelemetryPing::query() ->orderByDesc('last_ping_at') ->limit(20) ->get() ->map(fn ($ping) => [ 'id' => $ping->id, 'instance_id' => substr($ping->instance_id, 0, 8).'...', 'app_version' => $ping->app_version, 'php_version' => $ping->php_version, 'laravel_version' => $ping->laravel_version, 'monitors_total' => $ping->monitors_total, 'users_total' => $ping->users_total, 'os_type' => $ping->os_type, 'first_seen_at' => $ping->first_seen_at?->format('Y-m-d'), 'last_ping_at' => $ping->last_ping_at?->diffForHumans(), 'ping_count' => $ping->ping_count, ]), ]); } /** * Get updated statistics as JSON (for polling). */ public function stats(): JsonResponse { if (! auth()->user()?->is_admin) { return response()->json(['error' => 'Forbidden'], HttpResponse::HTTP_FORBIDDEN); } if (! config('telemetry.receiver_enabled')) { return response()->json(['error' => 'Receiver not enabled'], 400); } return response()->json([ 'statistics' => TelemetryPing::getStatistics(), 'versionDistribution' => TelemetryPing::getVersionDistribution(), 'osDistribution' => TelemetryPing::getOsDistribution(), ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/ToggleMonitorPinController.php
app/Http/Controllers/ToggleMonitorPinController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class ToggleMonitorPinController extends Controller { /** * Toggle the pinned status of a monitor for the authenticated user. */ public function __invoke(Request $request, int $monitorId): RedirectResponse { $request->validate([ 'is_pinned' => 'required|boolean', ]); try { // Use withoutGlobalScopes to handle disabled monitors $monitor = Monitor::withoutGlobalScopes()->findOrFail($monitorId); // Check if user is subscribed to this monitor if (! $monitor->is_subscribed) { return redirect()->back()->with('flash', [ 'type' => 'error', 'message' => 'You must be subscribed to this monitor to pin it.', ]); } // Update the pivot table $monitor->users()->updateExistingPivot(auth()->id(), [ 'is_pinned' => $request->boolean('is_pinned'), ]); // Clear the cache for this monitor's pinned status cache()->forget("is_pinned_{$monitor->id}_".auth()->id()); return redirect()->back()->with('flash', [ 'type' => 'success', 'message' => $request->boolean('is_pinned') ? 'Monitor pinned successfully.' : 'Monitor unpinned successfully.', ]); } catch (\Exception $e) { return redirect()->back()->with('flash', [ 'type' => 'error', 'message' => 'Failed to update pin status: '.$e->getMessage(), ]); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/NotificationController.php
app/Http/Controllers/NotificationController.php
<?php namespace App\Http\Controllers; use App\Models\NotificationChannel; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; use Inertia\Inertia; class NotificationController extends Controller { public function index() { $channels = Auth::user()->notificationChannels()->latest()->get(); return Inertia::render('settings/Notifications', [ 'channels' => $channels, ]); } public function create() { return Inertia::render('settings/Notifications', [ 'channels' => Auth::user()->notificationChannels()->latest()->get(), 'showForm' => true, 'isEdit' => false, ]); } public function store(Request $request) { $validated = $request->validate([ 'type' => 'required|string', 'destination' => 'required|string', 'is_enabled' => 'boolean', 'metadata' => 'nullable|array', ]); $validated['user_id'] = Auth::id(); NotificationChannel::create($validated); return Redirect::route('notifications.index') ->with('success', 'Notification channel created successfully.'); } public function show($id) { $channel = Auth::user()->notificationChannels()->findOrFail($id); return Inertia::render('settings/Notifications', [ 'channels' => Auth::user()->notificationChannels()->latest()->get(), 'editingChannel' => $channel, 'showForm' => true, 'isEdit' => true, ]); } public function edit($id) { $channel = Auth::user()->notificationChannels()->findOrFail($id); return Inertia::render('settings/Notifications', [ 'channels' => Auth::user()->notificationChannels()->latest()->get(), 'editingChannel' => $channel, 'showForm' => true, 'isEdit' => true, ]); } public function update(Request $request, $id) { $channel = Auth::user()->notificationChannels()->findOrFail($id); $validated = $request->validate([ 'type' => 'required|string', 'destination' => 'required|string', 'is_enabled' => 'boolean', 'metadata' => 'nullable|array', ]); $channel->update($validated); return Redirect::route('notifications.index') ->with('success', 'Notification channel updated successfully.'); } public function destroy($id) { $channel = Auth::user()->notificationChannels()->findOrFail($id); $channel->delete(); return Redirect::route('notifications.index') ->with('success', 'Notification channel deleted successfully.'); } public function toggle($id) { $channel = Auth::user()->notificationChannels()->findOrFail($id); $channel->update(['is_enabled' => ! $channel->is_enabled]); return Redirect::route('notifications.index') ->with('success', 'Notification channel '.($channel->is_enabled ? 'enabled' : 'disabled').' successfully.'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/MonitorStatusStreamController.php
app/Http/Controllers/MonitorStatusStreamController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\StreamedEvent; use Illuminate\Support\Facades\Cache; class MonitorStatusStreamController extends Controller { /** * Stream monitor status changes via Server-Sent Events (SSE). * * Query parameters: * - monitor_ids: comma-separated list of monitor IDs to watch (optional) * - status_page_id: watch all monitors on a specific status page (optional) * - last_event_id: ID of last received event for resuming (optional) */ public function __invoke(Request $request) { $monitorIds = $request->query('monitor_ids') ? array_map('intval', explode(',', $request->query('monitor_ids'))) : []; $statusPageId = $request->query('status_page_id') ? (int) $request->query('status_page_id') : null; $lastEventId = $request->header('Last-Event-ID') ?? $request->query('last_event_id'); return response()->eventStream(function () use ($monitorIds, $statusPageId, $lastEventId) { $seenIds = $lastEventId ? [$lastEventId] : []; $heartbeatInterval = 30; // seconds $lastHeartbeat = time(); $maxDuration = 300; // 5 minutes max connection $startTime = time(); while (true) { // Check max duration if ((time() - $startTime) > $maxDuration) { yield new StreamedEvent( event: 'reconnect', data: json_encode(['reason' => 'max_duration']), ); break; } // Get status changes from cache $changes = Cache::get('monitor_status_changes', []); foreach ($changes as $change) { // Skip already seen events if (in_array($change['id'], $seenIds)) { continue; } // Filter by monitor IDs if specified if (! empty($monitorIds) && ! in_array($change['monitor_id'], $monitorIds)) { continue; } // Filter by status page if specified if ($statusPageId && ! in_array($statusPageId, $change['status_page_ids'] ?? [])) { continue; } $seenIds[] = $change['id']; yield new StreamedEvent( event: 'status_change', data: json_encode($change), ); } // Send heartbeat every 30 seconds to keep connection alive if ((time() - $lastHeartbeat) >= $heartbeatInterval) { yield new StreamedEvent( event: 'heartbeat', data: json_encode(['time' => now()->toIso8601String()]), ); $lastHeartbeat = time(); } // Small sleep to prevent CPU spinning usleep(500000); // 0.5 seconds } }, endStreamWith: new StreamedEvent(event: 'end', data: '</stream>')); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/MonitorListController.php
app/Http/Controllers/MonitorListController.php
<?php namespace App\Http\Controllers; use App\Http\Resources\MonitorCollection; use App\Models\Monitor; use Illuminate\Http\Request; use Inertia\Inertia; class MonitorListController extends Controller { /** * Display dynamic monitor listing based on type. */ public function index(Request $request, string $type) { // Validate the type parameter if (! in_array($type, ['pinned', 'private', 'public'])) { abort(404); } $page = $request->input('page', 1); $search = $request->input('search'); $statusFilter = $request->input('status_filter', 'all'); $visibilityFilter = $request->input('visibility_filter', 'all'); $tagFilter = $request->input('tag_filter'); $perPage = $request->input('per_page', 12); // Build the base query based on type $query = $this->buildQuery($type, $search, $statusFilter, $visibilityFilter, $tagFilter); // Paginate results $monitors = $query->paginate($perPage); // Return Inertia view return Inertia::render('monitors/List', [ 'monitors' => new MonitorCollection($monitors), 'type' => $type, 'search' => $search, 'statusFilter' => $statusFilter, 'visibilityFilter' => $visibilityFilter, 'tagFilter' => $tagFilter, 'perPage' => $perPage, ]); } /** * Build the query based on monitor type and filters. */ private function buildQuery(string $type, $search, $statusFilter, $visibilityFilter, $tagFilter) { $baseQuery = Monitor::withoutGlobalScope('user'); switch ($type) { case 'pinned': $query = $baseQuery->whereHas('users', function ($q) { $q->where('user_monitor.user_id', auth()->id()) ->where('user_monitor.is_pinned', true); }); break; case 'private': $query = $baseQuery->where('is_public', false) ->whereHas('users', function ($q) { $q->where('user_monitor.user_id', auth()->id()); }); break; case 'public': $query = $baseQuery->where('is_public', true); // If user is authenticated, include subscription status if (auth()->check()) { $query->with(['users' => function ($q) { $q->where('users.id', auth()->id()); }]); } break; default: $query = $baseQuery; } // Add common relationships $query->with(['users:id', 'uptimeDaily']); // Apply status filter if ($statusFilter === 'disabled') { $query->whereHas('users', function ($q) { $q->where('user_id', auth()->id()) ->where('user_monitor.is_active', false); }); } elseif ($statusFilter === 'globally_enabled') { $query->withoutGlobalScope('enabled') ->where('uptime_check_enabled', true); } elseif ($statusFilter === 'globally_disabled') { $query->withoutGlobalScope('enabled') ->where('uptime_check_enabled', false); } elseif (in_array($statusFilter, ['up', 'down'])) { $query->where('uptime_status', $statusFilter); } // Apply visibility filter (only for non-type-specific views) if ($visibilityFilter !== 'all' && ! in_array($type, ['private', 'public'])) { if ($visibilityFilter === 'public') { $query->where('is_public', true); } elseif ($visibilityFilter === 'private') { $query->where('is_public', false); } } // Apply search filter if ($search && strlen($search) >= 3) { $query->where(function ($q) use ($search) { $q->where('url', 'like', "%$search%") ->orWhereRaw('REPLACE(REPLACE(url, "https://", ""), "http://", "") LIKE ?', ["%$search%"]); }); } // Apply tag filter if provided if ($tagFilter) { $query->whereHas('tags', function ($q) use ($tagFilter) { $q->where('tags.id', $tagFilter); }); } // Order by creation date $query->orderBy('created_at', 'desc'); return $query; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/MonitorImportController.php
app/Http/Controllers/MonitorImportController.php
<?php namespace App\Http\Controllers; use App\Http\Requests\ImportMonitorFileRequest; use App\Http\Requests\ProcessMonitorImportRequest; use App\Services\MonitorImportService; use Inertia\Inertia; class MonitorImportController extends Controller { public function __construct( private MonitorImportService $importService ) {} /** * Show the import page */ public function index() { return Inertia::render('uptime/Import'); } /** * Parse uploaded file and return preview data */ public function preview(ImportMonitorFileRequest $request) { $file = $request->file('import_file'); $format = $request->input('format') ?? $this->importService->detectFormat($file); $result = $this->importService->parseFile($file, $format); return response()->json($result); } /** * Process the import with user's duplicate resolution choices */ public function process(ProcessMonitorImportRequest $request) { try { $result = $this->importService->import( $request->input('rows'), $request->input('duplicate_action'), $request->input('resolutions', []) ); $message = "Berhasil mengimport {$result['imported']} monitor."; if ($result['updated'] > 0) { $message .= " {$result['updated']} monitor diupdate."; } if ($result['skipped'] > 0) { $message .= " {$result['skipped']} monitor dilewati."; } return redirect()->route('monitor.index') ->with('flash', [ 'message' => $message, 'type' => 'success', ]); } catch (\Exception $e) { return redirect()->back() ->with('flash', [ 'message' => 'Gagal mengimport monitor: '.$e->getMessage(), 'type' => 'error', ]); } } /** * Download sample CSV template */ public function sampleCsv() { return response()->streamDownload(function () { echo $this->importService->generateSampleCsv(); }, 'monitors-template.csv', [ 'Content-Type' => 'text/csv', ]); } /** * Download sample JSON template */ public function sampleJson() { return response()->streamDownload(function () { echo $this->importService->generateSampleJson(); }, 'monitors-template.json', [ 'Content-Type' => 'application/json', ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/StatusPageAssociateMonitorController.php
app/Http/Controllers/StatusPageAssociateMonitorController.php
<?php namespace App\Http\Controllers; use App\Models\StatusPage; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\Request; class StatusPageAssociateMonitorController extends Controller { use AuthorizesRequests; public function __invoke(Request $request, StatusPage $statusPage) { $this->authorize('update', $statusPage); $validated = $request->validate([ 'monitor_ids' => 'required|array', 'monitor_ids.*' => 'exists:monitors,id', ]); $statusPage->monitors()->syncWithoutDetaching($validated['monitor_ids']); return redirect()->route('status-pages.show', $statusPage) ->with('success', 'Monitors successfully associated.'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/UnsubscribeMonitorController.php
app/Http/Controllers/UnsubscribeMonitorController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; class UnsubscribeMonitorController extends Controller { public function __invoke($monitorId) { try { $monitor = Monitor::withoutGlobalScopes()->findOrFail($monitorId); $errorMessage = null; if (! $monitor->is_public) { $errorMessage = 'Monitor tidak tersedia untuk berlangganan'; } elseif (! $monitor->users()->where('user_id', auth()->id())->exists()) { $errorMessage = 'Anda tidak berlangganan monitor ini'; } if ($errorMessage) { return redirect()->back()->with('flash', [ 'type' => 'error', 'message' => $errorMessage, ]); } $monitor->users()->detach(auth()->id()); // clear monitor cache cache()->forget('public_monitors_authenticated_'.auth()->id()); return redirect()->back()->with('flash', [ 'type' => 'success', 'message' => 'Berhasil berhenti berlangganan monitor: '.$monitor?->url, ]); } catch (\Exception $e) { return redirect()->back()->with('flash', [ 'type' => 'error', 'message' => 'Gagal berhenti berlangganan monitor: '.$e->getMessage(), ]); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/StatusPageOrderController.php
app/Http/Controllers/StatusPageOrderController.php
<?php namespace App\Http\Controllers; use App\Models\StatusPage; use App\Models\StatusPageMonitor; use Illuminate\Http\Request; class StatusPageOrderController extends Controller { public function __invoke(Request $request, StatusPage $statusPage) { // Validate the request data $data = $request->validate([ 'monitor_ids' => 'required|array', 'monitor_ids.*' => 'exists:monitors,id', // Ensure each monitor ID exists in the pivot table ]); // Ensure the status page exists if (! $statusPage) { return response()->json(['error' => 'Status page not found.'], 404); } // Update the order of monitors for the status page foreach ($data['monitor_ids'] as $order => $monitorId) { // Find the status page monitor pivot table entry $statusPageMonitor = StatusPageMonitor::where('status_page_id', $statusPage->id) ->where('monitor_id', $monitorId) ->first(); if (! $statusPageMonitor || $statusPageMonitor->order === $order) { continue; } StatusPageMonitor::where('status_page_id', $statusPage->id) ->where('monitor_id', $monitorId) ->update(['order' => $order]); } // Return a success response return redirect()->route('status-pages.show', $statusPage->id) ->with('success', 'Monitor order updated successfully.'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/StatusPageDisassociateMonitorController.php
app/Http/Controllers/StatusPageDisassociateMonitorController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use App\Models\StatusPage; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\Request; class StatusPageDisassociateMonitorController extends Controller { use AuthorizesRequests; public function __invoke(Request $request, StatusPage $statusPage, Monitor $monitor) { $this->authorize('update', $statusPage); $statusPage->monitors()->detach($monitor->id); return redirect()->route('status-pages.show', $statusPage) ->with('success', 'Monitor disassociated successfully.'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/ServerResourceController.php
app/Http/Controllers/ServerResourceController.php
<?php namespace App\Http\Controllers; use App\Services\ServerResourceService; use Illuminate\Http\JsonResponse; use Inertia\Inertia; use Inertia\Response; use Symfony\Component\HttpFoundation\Response as HttpResponse; class ServerResourceController extends Controller { public function __construct( protected ServerResourceService $serverResourceService ) {} /** * Display the server resources page. */ public function index(): Response|JsonResponse { if (! auth()->user()?->is_admin) { abort(HttpResponse::HTTP_FORBIDDEN, 'Only administrators can access server resources.'); } return Inertia::render('settings/ServerResources', [ 'initialMetrics' => $this->serverResourceService->getMetrics(), ]); } /** * Get server resource metrics as JSON (for polling). */ public function metrics(): JsonResponse { if (! auth()->user()?->is_admin) { return response()->json(['error' => 'Forbidden'], HttpResponse::HTTP_FORBIDDEN); } return response()->json($this->serverResourceService->getMetrics()); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/TagController.php
app/Http/Controllers/TagController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Spatie\Tags\Tag; class TagController extends Controller { /** * Get all available tags for monitors */ public function index() { $tags = Tag::all(['id', 'name', 'type']); return response()->json([ 'tags' => $tags->map(function ($tag) { return [ 'id' => $tag->id, 'name' => $tag->name, 'type' => $tag->type, ]; }), ]); } /** * Search tags by name */ public function search(Request $request) { $search = $request->input('search', ''); $tags = Tag::where('name', 'like', "%{$search}%") ->limit(10) ->get(['id', 'name', 'type']); return response()->json([ 'tags' => $tags->map(function ($tag) { return [ 'id' => $tag->id, 'name' => $tag->name, 'type' => $tag->type, ]; }), ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/StatisticMonitorController.php
app/Http/Controllers/StatisticMonitorController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; class StatisticMonitorController extends Controller { /** * Handle the incoming request. */ public function __invoke(Request $request) { $user = auth()->user(); $statistics = Cache::remember('statistic-monitor:'.$user?->id, 60, function () use ($user) { $publicMonitorCount = Monitor::withoutGlobalScope('user') ->where('is_public', true) ->count(); $privateMonitorCount = Monitor::whereHas('users', function ($query) use ($user) { $query->where('user_id', $user?->id); })->where('is_public', false)->count(); $totalMonitors = Monitor::withoutGlobalScope('user')->count(); $nowInMinutes = now()->timestamp / 60; // get online monitors $onlineMonitors = Monitor::withoutGlobalScope('user') ->where('uptime_status', 'up') ->where('uptime_last_check_date', '>=', $nowInMinutes - 60) ->count(); // get offline monitors $offlineMonitors = Monitor::withoutGlobalScope('user') ->where('uptime_status', 'down') ->where('uptime_last_check_date', '>=', $nowInMinutes - 60) ->count(); // get unsubscribed monitors $unsubscribedMonitors = Monitor::withoutGlobalScope('user') ->where('is_public', true) ->whereDoesntHave('users', function ($query) use ($user) { $query->where('user_id', $user?->id); }) ->count(); // get globally enabled monitors (uptime_check_enabled = true) $globallyEnabledMonitors = Monitor::withoutGlobalScope('user') ->withoutGlobalScope('enabled') ->where('uptime_check_enabled', true) ->count(); // get globally disabled monitors (uptime_check_enabled = false) $globallyDisabledMonitors = Monitor::withoutGlobalScope('user') ->withoutGlobalScope('enabled') ->where('uptime_check_enabled', false) ->count(); $data = [ 'public_monitor_count' => $publicMonitorCount, 'private_monitor_count' => $privateMonitorCount, 'total_monitors' => $totalMonitors, 'online_monitors' => $onlineMonitors, 'offline_monitors' => $offlineMonitors, 'unsubscribed_monitors' => $unsubscribedMonitors, 'globally_enabled_monitors' => $globallyEnabledMonitors, 'globally_disabled_monitors' => $globallyDisabledMonitors, ]; if ($user && $user->id === 1) { $data['user_count'] = \App\Models\User::count(); } return $data; }); return response()->json($statistics); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/DashboardController.php
app/Http/Controllers/DashboardController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Inertia\Inertia; class DashboardController extends Controller { public function index(Request $request) { return Inertia::render('Dashboard'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/BadgeController.php
app/Http/Controllers/BadgeController.php
<?php namespace App\Http\Controllers; use App\Models\Monitor; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; class BadgeController extends Controller { /** * Display the uptime badge for a monitor. */ public function show(Request $request, string $domain): Response { $period = $request->get('period', '24h'); $style = $request->get('style', 'flat'); $showPeriod = $request->boolean('show_period', true); $baseLabel = $request->get('label', 'uptime'); $label = $showPeriod ? "{$baseLabel} {$period}" : $baseLabel; // Build the full HTTPS URL $url = 'https://'.urldecode($domain); // Find the monitor $monitor = Monitor::where('url', $url) ->where('is_public', true) ->where('uptime_check_enabled', true) ->with('statistics') ->first(); if (! $monitor) { return $this->svgResponse( $this->generateBadge($label, 'not found', '#9f9f9f', $style) ); } // Get uptime based on period $uptime = match ($period) { '7d' => $monitor->statistics?->uptime_7d, '30d' => $monitor->statistics?->uptime_30d, '90d' => $monitor->statistics?->uptime_90d, default => $monitor->statistics?->uptime_24h, } ?? 100; $color = $this->getColorForUptime($uptime); $value = number_format($uptime, 1).'%'; // Track badge view in Umami (non-blocking) $this->trackBadgeView($request, $domain); return $this->svgResponse( $this->generateBadge($label, $value, $color, $style) ); } /** * Track badge view in Umami analytics. */ private function trackBadgeView(Request $request, string $domain): void { // Extract only serializable data before dispatching $hostname = parse_url(config('app.url'), PHP_URL_HOST); $referrer = $request->header('Referer', ''); dispatch(function () use ($domain, $hostname, $referrer) { try { $response = Http::timeout(5) ->withHeaders([ 'User-Agent' => 'Uptime-Kita/1.0 (Badge Tracker)', ]) ->post('https://umami.syofyanzuhad.dev/api/send', [ 'payload' => [ 'hostname' => $hostname, 'language' => 'en-US', 'referrer' => $referrer, 'screen' => '1920x1080', 'title' => "Badge: {$domain}", 'url' => "/badge/{$domain}", 'website' => '803a4f91-04d8-43be-9302-82df6ff14481', 'name' => 'badge-view', ], 'type' => 'event', ]); Log::info('Umami badge tracking', [ 'domain' => $domain, 'referrer' => $referrer, 'status' => $response->status(), 'success' => $response->successful(), ]); } catch (\Exception $e) { Log::warning('Umami badge tracking failed', [ 'domain' => $domain, 'error' => $e->getMessage(), ]); } })->afterResponse(); } /** * Get the color based on uptime percentage. */ private function getColorForUptime(float $uptime): string { return match (true) { $uptime >= 99 => '#4c1', // brightgreen $uptime >= 97 => '#97ca00', // green $uptime >= 95 => '#a4a61d', // yellowgreen $uptime >= 90 => '#dfb317', // yellow $uptime >= 80 => '#fe7d37', // orange default => '#e05d44', // red }; } /** * Generate SVG badge using simple approach without complex scaling. */ private function generateBadge(string $label, string $value, string $color, string $style): string { // For "for-the-badge" style, use uppercase and different sizing $isForTheBadge = $style === 'for-the-badge'; $displayLabel = $isForTheBadge ? strtoupper($label) : $label; $displayValue = $isForTheBadge ? strtoupper($value) : $value; // Calculate widths - generous padding for readability $charWidth = $isForTheBadge ? 8 : 7; $padding = 16; $labelWidth = (int) ceil(strlen($displayLabel) * $charWidth + $padding); $valueWidth = (int) ceil(strlen($displayValue) * $charWidth + $padding); $totalWidth = $labelWidth + $valueWidth; $height = $isForTheBadge ? 28 : 20; $fontSize = $isForTheBadge ? 11 : 11; $textY = $isForTheBadge ? 18 : 14; $borderRadius = match ($style) { 'flat-square' => 0, 'for-the-badge' => 4, default => 3, }; $gradient = $style === 'plastic' ? $this->getGradientDef() : ''; // Calculate center positions directly $labelCenterX = $labelWidth / 2; $valueCenterX = $labelWidth + ($valueWidth / 2); return <<<SVG <svg xmlns="http://www.w3.org/2000/svg" width="{$totalWidth}" height="{$height}" role="img" aria-label="{$label}: {$value}"> <title>{$label}: {$value}</title> {$gradient} <linearGradient id="s" x2="0" y2="100%"> <stop offset="0" stop-color="#bbb" stop-opacity=".1"/> <stop offset="1" stop-opacity=".1"/> </linearGradient> <clipPath id="r"> <rect width="{$totalWidth}" height="{$height}" rx="{$borderRadius}" fill="#fff"/> </clipPath> <g clip-path="url(#r)"> <rect width="{$labelWidth}" height="{$height}" fill="#555"/> <rect x="{$labelWidth}" width="{$valueWidth}" height="{$height}" fill="{$color}"/> <rect width="{$totalWidth}" height="{$height}" fill="url(#s)"/> </g> <g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="{$fontSize}"> <text aria-hidden="true" x="{$labelCenterX}" y="{$textY}" fill="#010101" fill-opacity=".3" dy=".1em">{$displayLabel}</text> <text x="{$labelCenterX}" y="{$textY}" fill="#fff">{$displayLabel}</text> <text aria-hidden="true" x="{$valueCenterX}" y="{$textY}" fill="#010101" fill-opacity=".3" dy=".1em">{$displayValue}</text> <text x="{$valueCenterX}" y="{$textY}" fill="#fff">{$displayValue}</text> </g> </svg> SVG; } /** * Get gradient definition for plastic style. */ private function getGradientDef(): string { return <<<'GRADIENT' <linearGradient id="gradient" x2="0" y2="100%"> <stop offset="0" stop-color="#fff" stop-opacity=".7"/> <stop offset=".1" stop-color="#aaa" stop-opacity=".1"/> <stop offset=".9" stop-opacity=".3"/> <stop offset="1" stop-opacity=".5"/> </linearGradient> GRADIENT; } /** * Return SVG response with proper headers. */ private function svgResponse(string $svg): Response { return response($svg, 200, [ 'Content-Type' => 'image/svg+xml', 'Cache-Control' => 'public, max-age=300, s-maxage=300', 'Expires' => now()->addMinutes(5)->toRfc7231String(), ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/EmailVerificationNotificationController.php
app/Http/Controllers/Auth/EmailVerificationNotificationController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class EmailVerificationNotificationController extends Controller { /** * Send a new email verification notification. */ public function store(Request $request): RedirectResponse { if ($request->user()->hasVerifiedEmail()) { return redirect()->intended(route('dashboard', absolute: false)); } $request->user()->sendEmailVerificationNotification(); return back()->with('status', 'verification-link-sent'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/RegisteredUserController.php
app/Http/Controllers/Auth/RegisteredUserController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Models\User; use Illuminate\Auth\Events\Registered; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\Rules; use Inertia\Inertia; use Inertia\Response; class RegisteredUserController extends Controller { /** * Show the registration page. */ public function create(): Response { return Inertia::render('auth/Register'); } /** * Handle an incoming registration request. * * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request): RedirectResponse { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|lowercase|email|max:255|unique:'.User::class, 'password' => ['required', 'confirmed', Rules\Password::defaults()], ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); event(new Registered($user)); Auth::login($user); return to_route('dashboard'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/ConfirmablePasswordController.php
app/Http/Controllers/Auth/ConfirmablePasswordController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\ValidationException; use Inertia\Inertia; use Inertia\Response; class ConfirmablePasswordController extends Controller { /** * Show the confirm password page. */ public function show(): Response { return Inertia::render('auth/ConfirmPassword'); } /** * Confirm the user's password. */ public function store(Request $request): RedirectResponse { if (! Auth::guard('web')->validate([ 'email' => $request->user()->email, 'password' => $request->password, ])) { throw ValidationException::withMessages([ 'password' => __('auth.password'), ]); } $request->session()->put('auth.password_confirmed_at', time()); return redirect()->intended(route('dashboard', absolute: false)); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/PasswordResetLinkController.php
app/Http/Controllers/Auth/PasswordResetLinkController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Password; use Inertia\Inertia; use Inertia\Response; class PasswordResetLinkController extends Controller { /** * Show the password reset link request page. */ public function create(Request $request): Response { return Inertia::render('auth/ForgotPassword', [ 'status' => $request->session()->get('status'), ]); } /** * Handle an incoming password reset link request. * * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request): RedirectResponse { $request->validate([ 'email' => 'required|email', ]); Password::sendResetLink( $request->only('email') ); return back()->with('status', __('A reset link will be sent if the account exists.')); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/EmailVerificationPromptController.php
app/Http/Controllers/Auth/EmailVerificationPromptController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Inertia\Inertia; use Inertia\Response; class EmailVerificationPromptController extends Controller { /** * Show the email verification prompt page. */ public function __invoke(Request $request): RedirectResponse|Response { return $request->user()->hasVerifiedEmail() ? redirect()->intended(route('dashboard', absolute: false)) : Inertia::render('auth/VerifyEmail', ['status' => $request->session()->get('status')]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/SocialiteController.php
app/Http/Controllers/Auth/SocialiteController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Models\SocialAccount; use App\Models\User; use Laravel\Socialite\Facades\Socialite; class SocialiteController extends Controller { /** * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function redirectToProvider($provider) { return Socialite::driver($provider)->redirect(); } /** * @return \Illuminate\Http\RedirectResponse */ public function handleProvideCallback($provider) { try { $user = Socialite::driver($provider)->user(); } catch (\Exception $e) { return redirect()->back(); } $authUser = $this->findOrCreateUser($user, $provider); auth()->login($authUser, true); return redirect()->route('home'); } /** * @return mixed */ public function findOrCreateUser($socialUser, $provider) { $socialAccount = SocialAccount::where('provider_id', $socialUser->getId()) ->where('provider_name', $provider) ->first(); if ($socialAccount) { return $socialAccount->user; } else { $user = User::where('email', $socialUser->getEmail())->first(); if (! $user) { $user = User::create([ 'name' => $socialUser->getName(), 'email' => $socialUser->getEmail(), ]); } $user->socialAccounts()->create([ 'provider_id' => $socialUser->getId(), 'provider_name' => $provider, ]); return $user; } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/NewPasswordController.php
app/Http/Controllers/Auth/NewPasswordController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Auth\Events\PasswordReset; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Password; use Illuminate\Support\Str; use Illuminate\Validation\Rules; use Illuminate\Validation\ValidationException; use Inertia\Inertia; use Inertia\Response; class NewPasswordController extends Controller { /** * Show the password reset page. */ public function create(Request $request): Response { return Inertia::render('auth/ResetPassword', [ 'email' => $request->email, 'token' => $request->route('token'), ]); } /** * Handle an incoming new password request. * * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request): RedirectResponse { $request->validate([ 'token' => 'required', 'email' => 'required|email', 'password' => ['required', 'confirmed', Rules\Password::defaults()], ]); // Here we will attempt to reset the user's password. If it is successful we // will update the password on an actual user model and persist it to the // database. Otherwise we will parse the error and return the response. $status = Password::reset( $request->only('email', 'password', 'password_confirmation', 'token'), function ($user) use ($request) { $user->forceFill([ 'password' => Hash::make($request->password), 'remember_token' => Str::random(60), ])->save(); event(new PasswordReset($user)); } ); // If the password was successfully reset, we will redirect the user back to // the application's home authenticated view. If there is an error we can // redirect them back to where they came from with their error message. if ($status == Password::PasswordReset) { return to_route('login')->with('status', __($status)); } throw ValidationException::withMessages([ 'email' => [__($status)], ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/AuthenticatedSessionController.php
app/Http/Controllers/Auth/AuthenticatedSessionController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Http\Requests\Auth\LoginRequest; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; use Inertia\Inertia; use Inertia\Response; class AuthenticatedSessionController extends Controller { /** * Show the login page. */ public function create(Request $request): Response { return Inertia::render('auth/Login', [ 'canResetPassword' => Route::has('password.request'), 'status' => $request->session()->get('status'), ]); } /** * Handle an incoming authentication request. */ public function store(LoginRequest $request): RedirectResponse { $request->authenticate(); $request->session()->regenerate(); return redirect()->intended(route('dashboard', absolute: false)); } /** * Destroy an authenticated session. */ public function destroy(Request $request): RedirectResponse { Auth::guard('web')->logout(); $request->session()->invalidate(); $request->session()->regenerateToken(); return redirect('/'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Auth/VerifyEmailController.php
app/Http/Controllers/Auth/VerifyEmailController.php
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Auth\Events\Verified; use Illuminate\Foundation\Auth\EmailVerificationRequest; use Illuminate\Http\RedirectResponse; class VerifyEmailController extends Controller { /** * Mark the authenticated user's email address as verified. */ public function __invoke(EmailVerificationRequest $request): RedirectResponse { if ($request->user()->hasVerifiedEmail()) { return redirect()->intended(route('dashboard', absolute: false).'?verified=1'); } if ($request->user()->markEmailAsVerified()) { /** @var \Illuminate\Contracts\Auth\MustVerifyEmail $user */ $user = $request->user(); event(new Verified($user)); } return redirect()->intended(route('dashboard', absolute: false).'?verified=1'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Api/TelemetryReceiverController.php
app/Http/Controllers/Api/TelemetryReceiverController.php
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Models\TelemetryPing; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Validator; class TelemetryReceiverController extends Controller { /** * Receive telemetry ping from an Uptime-Kita instance. */ public function receive(Request $request): JsonResponse { // Check if receiver is enabled if (! config('telemetry.receiver_enabled')) { return response()->json([ 'success' => false, 'message' => 'Telemetry receiver is disabled on this instance.', ], 403); } // Validate incoming data $validator = Validator::make($request->all(), [ 'instance_id' => 'required|string|size:64', 'versions' => 'required|array', 'versions.app' => 'nullable|string|max:50', 'versions.php' => 'nullable|string|max:20', 'versions.laravel' => 'nullable|string|max:20', 'stats' => 'required|array', 'stats.monitors_total' => 'nullable|integer|min:0', 'stats.monitors_public' => 'nullable|integer|min:0', 'stats.users_total' => 'nullable|integer|min:0', 'stats.status_pages_total' => 'nullable|integer|min:0', 'stats.install_date' => 'nullable|date', 'system' => 'required|array', 'system.os_family' => 'nullable|string|max:50', 'system.os_type' => 'nullable|string|max:50', 'system.database_driver' => 'nullable|string|max:50', 'system.queue_driver' => 'nullable|string|max:50', 'system.cache_driver' => 'nullable|string|max:50', 'ping' => 'required|array', 'ping.timestamp' => 'required|string', ]); if ($validator->fails()) { return response()->json([ 'success' => false, 'message' => 'Invalid telemetry data.', 'errors' => $validator->errors(), ], 422); } try { $data = $validator->validated(); // Find or create the telemetry record $ping = TelemetryPing::updateOrCreate( ['instance_id' => $data['instance_id']], [ 'app_version' => $data['versions']['app'] ?? null, 'php_version' => $data['versions']['php'] ?? null, 'laravel_version' => $data['versions']['laravel'] ?? null, 'monitors_total' => $data['stats']['monitors_total'] ?? 0, 'monitors_public' => $data['stats']['monitors_public'] ?? 0, 'users_total' => $data['stats']['users_total'] ?? 0, 'status_pages_total' => $data['stats']['status_pages_total'] ?? 0, 'os_family' => $data['system']['os_family'] ?? null, 'os_type' => $data['system']['os_type'] ?? null, 'database_driver' => $data['system']['database_driver'] ?? null, 'queue_driver' => $data['system']['queue_driver'] ?? null, 'cache_driver' => $data['system']['cache_driver'] ?? null, 'install_date' => $data['stats']['install_date'] ?? null, 'last_ping_at' => now(), 'raw_data' => $data, ] ); // Set first_seen_at only on creation if ($ping->wasRecentlyCreated) { $ping->first_seen_at = now(); $ping->ping_count = 1; $ping->save(); Log::info('New telemetry instance registered', [ 'instance_id' => substr($data['instance_id'], 0, 8).'...', ]); } else { // Increment ping count $ping->increment('ping_count'); } return response()->json([ 'success' => true, 'message' => 'Telemetry received successfully.', ]); } catch (\Exception $e) { Log::error('Failed to process telemetry ping', [ 'error' => $e->getMessage(), ]); return response()->json([ 'success' => false, 'message' => 'Failed to process telemetry.', ], 500); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Settings/ProfileController.php
app/Http/Controllers/Settings/ProfileController.php
<?php namespace App\Http\Controllers\Settings; use App\Http\Controllers\Controller; use App\Http\Requests\Settings\ProfileUpdateRequest; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Inertia\Inertia; use Inertia\Response; class ProfileController extends Controller { /** * Show the user's profile settings page. */ public function edit(Request $request): Response { return Inertia::render('settings/Profile', [ 'mustVerifyEmail' => $request->user() instanceof MustVerifyEmail, 'status' => $request->session()->get('status'), ]); } /** * Update the user's profile information. */ public function update(ProfileUpdateRequest $request): RedirectResponse { $request->user()->fill($request->validated()); if ($request->user()->isDirty('email')) { $request->user()->email_verified_at = null; } $request->user()->save(); return to_route('profile.edit'); } /** * Delete the user's profile. */ public function destroy(Request $request): RedirectResponse { $request->validate([ 'password' => ['required', 'current_password'], ]); $user = $request->user(); Auth::logout(); $user->delete(); $request->session()->invalidate(); $request->session()->regenerateToken(); return redirect('/'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Settings/TelemetryController.php
app/Http/Controllers/Settings/TelemetryController.php
<?php namespace App\Http\Controllers\Settings; use App\Http\Controllers\Controller; use App\Jobs\SendTelemetryPingJob; use App\Services\InstanceIdService; use App\Services\TelemetryService; use Illuminate\Http\JsonResponse; use Inertia\Inertia; use Inertia\Response; use Symfony\Component\HttpFoundation\Response as HttpResponse; class TelemetryController extends Controller { public function __construct( protected TelemetryService $telemetryService, protected InstanceIdService $instanceIdService ) {} /** * Display the telemetry settings page. */ public function index(): Response { if (! auth()->user()?->is_admin) { abort(HttpResponse::HTTP_FORBIDDEN, 'Only administrators can access telemetry settings.'); } return Inertia::render('settings/Telemetry', [ 'settings' => $this->telemetryService->getSettings(), 'previewData' => $this->telemetryService->previewData(), ]); } /** * Preview telemetry data (for transparency). */ public function preview(): JsonResponse { if (! auth()->user()?->is_admin) { return response()->json(['error' => 'Forbidden'], HttpResponse::HTTP_FORBIDDEN); } return response()->json($this->telemetryService->previewData()); } /** * Send a test telemetry ping. */ public function testPing(): JsonResponse { if (! auth()->user()?->is_admin) { return response()->json(['error' => 'Forbidden'], HttpResponse::HTTP_FORBIDDEN); } if (! $this->telemetryService->isEnabled()) { return response()->json([ 'success' => false, 'message' => 'Telemetry is disabled. Enable it first to send a test ping.', ], 400); } SendTelemetryPingJob::dispatch(); return response()->json([ 'success' => true, 'message' => 'Test ping queued successfully.', ]); } /** * Regenerate instance ID. */ public function regenerateInstanceId(): JsonResponse { if (! auth()->user()?->is_admin) { return response()->json(['error' => 'Forbidden'], HttpResponse::HTTP_FORBIDDEN); } $newId = $this->instanceIdService->regenerateInstanceId(); return response()->json([ 'success' => true, 'instance_id' => $newId, 'message' => 'Instance ID regenerated successfully.', ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Settings/PasswordController.php
app/Http/Controllers/Settings/PasswordController.php
<?php namespace App\Http\Controllers\Settings; use App\Http\Controllers\Controller; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\Rules\Password; use Inertia\Inertia; use Inertia\Response; class PasswordController extends Controller { /** * Show the user's password settings page. */ public function edit(): Response { return Inertia::render('settings/Password'); } /** * Update the user's password. */ public function update(Request $request): RedirectResponse { $validated = $request->validate([ 'current_password' => ['required', 'current_password'], 'password' => ['required', Password::defaults(), 'confirmed'], ]); $request->user()->update([ 'password' => Hash::make($validated['password']), ]); return back(); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false