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 |
|---|---|---|---|---|---|---|---|---|
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/form.php | src/form.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* this file is a generic form class
* after an object is added to any part, you can modify that object without
* affecting the form
* Requires gettext and jqueryui
*/
/*
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
*/
require_once('html.php');
/* This class is the base of either a question or a group
*/
abstract class FormPart
{
var $class = "form-part";
/**
* @param FormPart $parent
* @param array $defaults
* @return Html
*/
abstract function get_html($parent, $defaults = array());
/**
* @param FormPart $parent
* @param array $defaults
* @return Html
*/
abstract protected function get_specific_html($parent, $defaults);
}
/* this class is to group multiple questions together
*/
class FormGroup extends FormPart
{
/** @var FormPart[] */
var $list = array();
var $title = false;
function __construct($title = false, $class = false)
{
$this->title = $title;
$this->class .= " form-group";
if ($class !== false)
$this->class = " $class";
}
/* add a category or question */
function add_part(FormPart $item)
{
$this->list[] = $item;
}
function get_html($parent, $defaults = array())
{
// If a FormGroup is embedded in another FormGroup we want to
// start a new table. If it isn't, we assume that our parent
// (radio or dropdown) has already created the table for us.
if (!is_a($parent, 'FormGroup'))
return $this->get_specific_html($parent, $defaults);
$tag = tag('tr', attrs("class=\"{$this->class}\""));
$cell = tag('td');
if ($this->title !== false)
$tag->add(tag('th', $this->title));
else
$cell->add(attrs("colspan=\"2\""));
$cell->add(tag('table', $this->get_specific_html($parent,
$defaults)));
$tag->add($cell);
return $tag;
}
protected function get_specific_html($parent, $defaults)
{
$results = array();
foreach ($this->list as $child) {
$results[] = $child->get_html($this, $defaults);
}
return $results;
}
}
/* this is the base class for all questions
*/
abstract class FormQuestion extends FormPart
{
/** @var string|bool */
var $qid;
/** @var string|bool */
var $subject;
/** @var string|bool */
var $description;
/**
* FormQuestion constructor.
* @param string $qid
* @param string $subject
* @param string|bool $description
*/
function __construct($qid, $subject, $description)
{
$this->class .= " form-question";
$this->qid = $qid;
$this->subject = $subject;
$this->description = $description;
}
function get_html($parent, $defaults = array())
{
$tag = tag('tr', attrs("class=\"{$this->class}\""));
$cell = tag('td');
if ($this->subject !== false)
$tag->add(tag('th', tag('label', attributes("for=\"{$this->qid}\""), $this->subject)));
else
$cell->add(attrs("colspan=\"2\""));
if ($this->description !== false)
$cell->add(tag('label', attrs("for=\"{$this->qid}\"", 'class="form-question-description"'),
$this->description));
$cell->add($this->get_specific_html($parent, $defaults));
$tag->add($cell);
return $tag;
}
}
/* this class is the base for all simple types of questions
*/
abstract class FormAtomicQuestion extends FormQuestion
{
/**
* FormAtomicQuestion constructor.
* @param string $qid
* @param string $subject
* @param string $description
*/
function __construct($qid, $subject, $description)
{
parent::__construct($qid, $subject, $description);
$this->class .= " form-atomic-question";
}
}
/* This class is for free response questions with responses that are a few
* sentences long at most
*/
class FormFreeQuestion extends FormAtomicQuestion
{
var $maxlen;
var $type;
function __construct($qid, $subject, $description = false, $maxlen = false)
{
parent::__construct($qid, $subject, $description);
$this->maxlen = $maxlen;
$this->class .= " form-free-question";
$this->type = "text";
}
protected function get_specific_html($parent, $defaults)
{
$attrs = attrs("name=\"{$this->qid}\"", "id=\"{$this->qid}\"",
"type=\"$this->type\"");
if (!empty($defaults[$this->qid])) {
$attrs->add("value=\"{$defaults[$this->qid]}\"");
}
if ($this->maxlen !== false) {
$attrs->add("maxlength=\"{$this->maxlen}\"");
$size = min(50, $this->maxlen);
$attrs->add("size=\"$size\"");
}
return tag('input', $attrs);
}
}
/* this class is for longer free reponse questions
*/
class FormLongFreeQuestion extends FormAtomicQuestion
{
var $rows;
var $cols;
function __construct($qid, $subject, $description = false, $rows = 8, $cols = 80)
{
parent::__construct($qid, $subject, $description);
$this->rows = $rows;
$this->cols = $cols;
$this->class .= " form-long-free-question";
}
protected function get_specific_html($parent, $defaults)
{
if (isset($defaults[$this->qid]))
$text = $defaults[$this->qid];
else
$text = '';
$tag = tag('textarea', attrs("rows=\"{$this->rows}\"",
"name=\"{$this->qid}\"",
"id=\"{$this->qid}\"",
"cols=\"{$this->cols}\""), $text);
return tag('div', attrs("class=\"form-textarea\""), $tag);
}
}
function form_date_input($qid, $defaults, $dateFormat)
{
$date_attrs = attrs('type="text"', 'class="form-date"',
"name=\"$qid-date\"", "id=\"$qid-date\"");
if (isset($defaults["$qid-date"]))
$date_attrs->add("value=\"{$defaults["$qid-date"]}\"");
return array(tag('input', $date_attrs),
tag('script', attrs('type="text/javascript"'),
"\$('#$qid-date').datepicker({dateFormat: \"$dateFormat\", firstDay: " . day_of_week_start() . " });"));
/**** */
}
/* this class is for date input
*/
class FormDateQuestion extends FormAtomicQuestion
{
var $date_format;
function __construct($qid, $subject, $date_format, $description = false)
{
parent::__construct($qid, $subject, $description);
$this->class .= " form-date-question";
$this->date_format = $date_format;
}
protected function get_specific_html($parent, $defaults)
{
switch ($this->date_format) {
case 0: // Month Day Year
$dateFormat = "mm/dd/yy";
$date_string = "MM/DD/YYYY";
break;
case 1: // Year Month Day
$dateFormat = "yy-mm-dd";
$date_string = "YYYY-MM-DD";
break;
case 2: // Day Month Year
$dateFormat = "dd-mm-yy";
$date_string = "DD-MM-YYYY";
break;
default:
soft_error("Unrecognized date format.");
}
return tag('div', attrs("class=\"{$this->class}\""),
tag('label', attrs("for=\"{$this->qid}-date\""), __("Date") . " ($date_string): "),
form_date_input($this->qid, $defaults,
$dateFormat));
}
}
function form_time_input($qid, $defaults, $hour24)
{
$showPeriod = $hour24 ? "false" : "true";
$time_attrs = attrs('type="text"', 'class="form-time"',
"name=\"$qid-time\"", "id=\"$qid-time\"");
if (isset($defaults["$qid-time"]))
$time_attrs->add("value=\"{$defaults["$qid-time"]}\"");
return array(tag('input', $time_attrs),
tag('script', attrs('type="text/javascript"'),
"\$('#$qid-time').timepicker({showPeriod: $showPeriod, showLeadingZero: false });"));
}
/* this class is for time input
*/
class FormTimeQuestion extends FormAtomicQuestion
{
var $hour24;
function __construct($qid, $subject, $hour24, $description = false)
{
parent::__construct($qid, $subject, $description);
$this->class .= " form-time-question";
$this->hour24 = $hour24;
}
protected function get_specific_html($parent, $defaults)
{
return tag('div', attrs("class=\"{$this->class}\""),
form_time_input($this->qid, $defaults, $this->hour24));
}
}
/* this class is for date input
*/
class FormDateTimeQuestion extends FormAtomicQuestion
{
var $hour24;
var $date_format;
function __construct($qid, $subject, $hour24, $date_format, $description = false)
{
parent::__construct($qid, $subject, $description);
$this->class .= " form-date-time-question";
$this->hour24 = $hour24;
$this->date_format = $date_format;
}
protected function get_specific_html($parent, $defaults)
{
switch ($this->date_format) {
case 0: // Month Day Year
$dateFormat = "mm/dd/yy";
$date_string = "MM/DD/YYYY";
break;
case 1: // Year Month Day
$dateFormat = "yy-mm-dd";
$date_string = "YYYY-MM-DD";
break;
case 2: // Day Month Year
$dateFormat = "dd-mm-yy";
$date_string = "DD-MM-YYYY";
break;
default:
soft_error("Unrecognized date format.");
}
return array(tag('label', attrs("for=\"{$this->qid}-date\""), __("Date") . " ($date_string): "),
form_date_input($this->qid, $defaults,
$dateFormat),
" ", tag('label', attrs("for=\"{$this->qid}-time\""), __('Time') . ": "),
form_time_input($this->qid, $defaults,
$this->hour24));
}
}
/* creates a submit button
*/
class FormSubmitButton extends FormQuestion
{
var $title;
function __construct($title = false)
{
parent::__construct(false, false, false);
$this->title = $title;
$this->class .= " form-submit";
}
protected function get_specific_html($parent, $defaults)
{
$attrs = attrs('type="submit"');
if ($this->title !== false) {
$attrs->add("value=\"{$this->title}\"");
}
return tag('div', attrs("class=\"{$this->class}\""),
tag('input', $attrs));
}
}
/* this class is for questions where depending on the answer you need
* to answer more questions
*/
abstract class FormCompoundQuestion extends FormQuestion
{
/** @var FormPart[] */
var $conditionals = array();
var $options = array();
var $descriptions = array();
function __construct($qid, $subject, $description)
{
parent::__construct($qid, $subject, $description);
}
function add_option($key, $title, $description = NULL,
$conditional = NULL)
{
$this->options[$key] = $title;
if ($description !== NULL)
$this->descriptions[$key] = $description;
if ($conditional !== NULL)
$this->conditionals[$key] = $conditional;
}
function add_options($options)
{
foreach ($options as $key => $title) {
$this->add_option($key, $title);
}
}
}
/* this class is for questions with a true/false answer
*/
class FormCheckBoxQuestion extends FormAtomicQuestion
{
var $checkbox_description;
function __construct($qid, $subject = false, $description = false)
{
parent::__construct($qid, $subject, false);
$this->class .= " form-checkbox-question";
$this->checkbox_description = $description;
}
protected function get_specific_html($parent, $defaults)
{
$attrs = attrs('type="checkbox"',
"name=\"{$this->qid}\"",
"id=\"{$this->qid}\"",
'value="1"',
'class="form-checkbox"');
if (!empty($defaults[$this->qid]))
$attrs->add("checked=\"checked\"");
$tag = tag('div', tag('input', $attrs));
if (!empty($this->checkbox_description))
$tag->add(tag('label', attrs("for=\"{$this->qid}\"",
'class="form-question-description"'),
$this->checkbox_description));
return $tag;
}
}
/* this class is for questions where you need to choose between
* multiple things
*/
class FormDropdownQuestion extends FormCompoundQuestion
{
function __construct($qid, $subject = false, $description = false)
{
parent::__construct($qid, $subject, $description);
$this->class .= " form-dropdown-question";
}
protected function get_specific_html($parent, $defaults)
{
$select = tag('select', attrs("id=\"{$this->qid}\"",
"name=\"{$this->qid}\"",
'class="form-select"'));
$children = array();
foreach ($this->options as $value => $name) {
$attrs = attrs("value=\"$value\"");
if (!empty($defaults[$this->qid])
&& $defaults[$this->qid] == $value
)
$attrs->add('selected');
$select->add(tag('option', $attrs, $name));
if (!empty($this->conditionals[$value])) {
$children[] = tag('table', attrs("id=\"{$this->qid}-{$value}\""),
$this->conditionals[$value]->get_html($this, $defaults));
}
}
if (empty($children))
return $select;
return array($select, $children);
}
}
/* this class is for questions where you need to choose between
* multiple things
*/
class FormMultipleSelectQuestion extends FormCompoundQuestion
{
function __construct($qid, $subject = false, $description = false)
{
parent::__construct($qid, $subject, $description);
$this->class .= " form-multi-select-question";
}
protected function get_specific_html($parent, $defaults)
{
$select = tag('select', attrs("id=\"{$this->qid}\"",
"name=\"{$this->qid}\"",
'multiple="multiple"',
'class="form-select"'));
$children = array();
foreach ($this->options as $value => $name) {
$attrs = attrs("value=\"$value\"");
if (!empty($defaults[$this->qid])
&& $defaults[$this->qid] == $value
)
$attrs->add('selected');
$select->add(tag('option', $attrs, $name));
if (!empty($this->conditionals[$value])) {
$children[] = tag('table', attrs("id=\"{$this->qid}-{$value}\""),
$this->conditionals[$value]->get_html($this, $defaults));
}
}
if (empty($children))
return $select;
return array($select, $children);
}
}
/* this class is for colorpickerer
*/
class FormColorPicker extends FormAtomicQuestion
{
function __construct($qid, $subject, $selectedcolor = false, $description = false)
{
parent::__construct($qid, $subject, $description);
$this->class .= " form-color-picker";
}
protected function get_specific_html($parent, $defaults)
{
if (isset($defaults[$this->qid]))
$value = $defaults[$this->qid];
else
$value = '';
return tag('input', attrs('type="text"',
'class="form-color-input"',
"name=\"{$this->qid}\"",
"value=\"$value\"",
"id=\"{$this->qid}\""));
}
}
/* this is the main form class
*/
class Form extends FormGroup
{
var $vars;
var $action;
var $method;
var $hidden = array();
function __construct($action, $title = false, $method = false)
{
parent::__construct($title);
$this->action = $action;
$this->method = $method;
$this->class .= " form";
}
function get_form($defaults = array())
{
$form_attrs = attrs("action=\"{$this->action}\"",
'method="POST"');
if ($this->method !== false) {
$form_attrs->add("method=\"{$this->method}\"");
}
$table = tag('table', attrs("class=\"{$this->class}\""));
foreach ($this->list as $child) {
$table->add($child->get_html($this, $defaults));
}
$form = tag('form', $form_attrs);
$hidden_div = tag('div');
$have_hidden = false;
foreach ($this->hidden as $name => $value) {
$have_hidden = true;
$hidden_div->add(tag('input', attrs('type="hidden"',
"name=\"$name\"",
"value=\"$value\"",
"id=\"$name\"")));
}
if ($have_hidden)
$form->add($hidden_div);
$form->add($table);
return $form;
}
function add_hidden($name, $value)
{
$this->hidden[$name] = $value;
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/Gettext_PHP.php | src/Gettext_PHP.php | <?php
/*
* Copyright (c) 2009 David Soria Parra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Gettext implementation in PHP
*
* @copyright (c) 2009 David Soria Parra <sn_@gmx.net>
* @author David Soria Parra <sn_@gmx.net>
*
* Changes:
* 04/25/2013 sproctor - Changed unpack format in parseHeader to unsigned
* 09/07/2013 sproctor - Added pgettext
*/
class Gettext_PHP //extends Gettext
{
/**
* First magic word in the MO header
*/
const MAGIC1 = 0xde120495;
/**
* First magic word in the MO header
*/
const MAGIC2 = 0x950412de;
protected $mofile;
protected $translationTable = array();
protected $parsed = false;
/**
* Initialize a new gettext class
*
* @param string $directory
* @param string $domain
* @param string $locale
*/
public function __construct($directory, $domain, $locale)
{
$this->mofile = sprintf("%s/%s/LC_MESSAGES/%s.mo", $directory,
$locale, $domain);
}
/**
* Parse the MO file header and returns the table
* offsets as described in the file header.
*
* If an exception occured, null is returned. This is intentionally
* as we need to get close to ext/gettexts beahvior.
*
* @param resource $fp The open file handler to the MO file
*
* @return array of offset
*/
private function parseHeader($fp)
{
$data = fread($fp, 8);
$header = unpack("Lmagic/Lrevision", $data);
if ((int) self::MAGIC1 != $header['magic']
&& (int) self::MAGIC2 != $header['magic']) {
return null;
}
if (0 != $header['revision']) {
return null;
}
$data = fread($fp, 4 * 5);
$offsets = unpack("lnum_strings/lorig_offset/"
. "ltrans_offset/lhash_size/lhash_offset", $data);
return $offsets;
}
/**
* Parse and reutnrs the string offsets in a a table. Two table can be found in
* a mo file. The table with the translations and the table with the original
* strings. Both contain offsets to the strings in the file.
*
* If an exception occured, null is returned. This is intentionally
* as we need to get close to ext/gettexts beahvior.
*
* @param resource $fp The open file handler to the MO file
* @param Integer $offset The offset to the table that should be parsed
* @param Integer $num The number of strings to parse
*
* @return array of offsets
*/
private function parseOffsetTable($fp, $offset, $num)
{
if (fseek($fp, $offset, SEEK_SET) < 0) {
return null;
}
$table = array();
for ($i = 0; $i < $num; $i++) {
$data = fread($fp, 8);
$table[] = unpack("lsize/loffset", $data);
}
return $table;
}
/**
* Parse a string as referenced by an table. Returns an
* array with the actual string.
*
* @param resource $fp The open file handler to the MO fie
* @param array $entry The entry as parsed by parseOffsetTable()
*
* @return string
*/
private function parseEntry($fp, $entry)
{
if (fseek($fp, $entry['offset'], SEEK_SET) < 0) {
return null;
}
if ($entry['size'] > 0) {
return fread($fp, $entry['size']);
}
return '';
}
/**
* Parse the MO file
*/
private function parse()
{
$this->translationTable = array();
if (!file_exists($this->mofile)) {
return;
}
$filesize = filesize($this->mofile);
if ($filesize < 4 * 7) {
return;
}
/* check for filesize */
$fp = fopen($this->mofile, "rb");
$offsets = $this->parseHeader($fp);
if (null == $offsets || $filesize < 4 * ($offsets['num_strings'] + 7)) {
fclose($fp);
return;
}
$transTable = array();
$table = $this->parseOffsetTable($fp, $offsets['trans_offset'],
$offsets['num_strings']);
if (null == $table) {
fclose($fp);
return;
}
foreach ($table as $idx => $entry) {
$transTable[$idx] = $this->parseEntry($fp, $entry);
}
$table = $this->parseOffsetTable($fp, $offsets['orig_offset'],
$offsets['num_strings']);
foreach ($table as $idx => $entry) {
$entry = $this->parseEntry($fp, $entry);
$formes = explode(chr(0), $entry);
$translation = explode(chr(0), $transTable[$idx]);
foreach($formes as $form) {
$this->translationTable[$form] = $translation;
}
}
fclose($fp);
$this->parsed = true;
}
/**
* Return a translated string
*
* If the translation is not found, the original passed message
* will be returned.
*
* @param string $msg
* @return string Translated message
*/
public function gettext($msg)
{
if (!$this->parsed) {
$this->parse();
}
if (array_key_exists($msg, $this->translationTable)) {
$t = $this->translationTable[$msg][0];
if(!empty($t))
return $t;
}
return $msg;
}
/**
* Return a translated string with the given context
*
* If the translation is not found, the original passed message
* will be returned.
*
* @param string $context The context of the message to search for
* @param string $msg The message to search for
*
* @return string Translated message
*/
public function pgettext($context, $msg)
{
if (!$this->parsed) {
$this->parse();
}
$key = "{$context}\04{$msg}";
if (array_key_exists($key, $this->translationTable)) {
$t = $this->translationTable[$key][0];
if(!empty($t))
return $t;
}
return $msg;
}
/**
* Return a translated string in it's plural form
*
* Returns the given $count (e.g second, third,...) plural form of the
* given string. If the id is not found and $num == 1 $msg is returned,
* otherwise $msg_plural
*
* @param string $msg The message to search for
* @param string $msg_plural A fallback plural form
* @param int $count Which plural form
*
* @return string Translated string
*/
public function ngettext($msg, $msg_plural, $count)
{
if (!$this->parsed) {
$this->parse();
}
$msg = (string) $msg;
if (array_key_exists($msg, $this->translationTable)) {
$translation = $this->translationTable[$msg];
/* the gettext api expect an unsigned int, so we just fake 'cast' */
if ($count <= 0 || count($translation) < $count) {
$count = count($translation);
}
return $translation[$count - 1];
}
/* not found, handle count */
if (1 == $count) {
return $msg;
} else {
return $msg_plural;
}
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/phpcoccurrence.class.php | src/phpcoccurrence.class.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once("$phpc_includes_path/phpcevent.class.php");
class PhpcOccurrence extends PhpcEvent
{
/** @var int */
var $oid;
var $start_year;
var $start_month;
var $start_day;
var $end_year;
var $end_month;
var $end_day;
var $time_type;
var $start_hour = NULL;
var $start_minute = NULL;
var $end_hour = NULL;
var $end_minute = NULL;
var $duration;
function __construct($event) {
parent::__construct($event);
$this->oid = intval($event['oid']);
if(!empty($event['start_ts'])) {
$start_ts = $event['start_ts'];
$this->start_year = date('Y', $start_ts);
$this->start_month = date('n', $start_ts);
$this->start_day = date('j', $start_ts);
$this->start_hour = date('H', $start_ts);
$this->start_minute = date('i', $start_ts);
}
if(!empty($event['start_date'])) {
if(preg_match('/^(\d{4})(\d{2})(\d{2})$/',
$event['start_date'],
$start_matches) < 1) {
soft_error(__('DB returned an invalid date.')
. "({$event['start_date']})");
}
$this->start_year = $start_matches[1];
$this->start_month = $start_matches[2];
$this->start_day = $start_matches[3];
}
if(!empty($event['end_ts'])) {
$end_ts = $event['end_ts'];
$this->end_year = date('Y', $end_ts);
$this->end_month = date('n', $end_ts);
$this->end_day = date('j', $end_ts);
$this->end_hour = date('H', $end_ts);
$this->end_minute = date('i', $end_ts);
}
if(!empty($event['end_date'])) {
if(preg_match('/^(\d{4})(\d{2})(\d{2})$/',
$event['end_date'],
$end_matches) < 1) {
soft_error(__('DB returned an invalid date.')
. "({$event['start_date']})");
}
$this->end_year = $end_matches[1];
$this->end_month = $end_matches[2];
$this->end_day = $end_matches[3];
}
$this->time_type = $event['time_type'];
if(!empty($event['end_ts'])) {
$this->duration=$event['end_ts'] - $event['start_ts'];
}
}
// formats the time according to type
// returns the formatted string
function get_time_string()
{
switch($this->time_type) {
default:
return $this->get_start_time();
case 1: // FULL DAY
case 3: // None
return '';
case 2:
return __('TBA');
}
}
function get_time_span_string()
{
switch($this->time_type) {
default:
$start_time = $this->get_start_time();
$end_time = $this->get_end_time();
return $start_time.' '.__('to').' '.$end_time;
case 1: // FULL DAY
case 3: // None
return '';
case 2:
return __('TBA');
}
}
function get_start_year()
{
return $this->start_year;
}
function get_start_month()
{
return $this->start_month;
}
function get_start_day()
{
return $this->start_day;
}
function get_end_year()
{
return $this->end_year;
}
function get_end_month()
{
return $this->end_month;
}
function get_end_day()
{
return $this->end_day;
}
function get_start_hour()
{
return $this->start_hour;
}
function get_start_minute()
{
return $this->start_minute;
}
function get_end_hour()
{
return $this->end_hour;
}
function get_end_minute()
{
return $this->end_minute;
}
function get_start_date() {
return format_date_string($this->start_year, $this->start_month,
$this->start_day,
$this->cal->date_format);
}
function get_short_start_date() {
return format_short_date_string($this->start_year,
$this->start_month, $this->start_day,
$this->cal->date_format);
}
function get_start_time() {
if($this->start_hour == NULL || $this->start_minute == NULL)
return NULL;
return format_time_string($this->start_hour,
$this->start_minute,
$this->cal->hours_24);
}
function get_end_date() {
return format_date_string($this->end_year, $this->end_month,
$this->end_day,
$this->cal->date_format);
}
function get_short_end_date() {
return format_short_date_string($this->end_year,
$this->end_month, $this->end_day,
$this->cal->date_format);
}
function get_end_time() {
if($this->end_hour == NULL || $this->end_minute == NULL)
return NULL;
return format_time_string($this->end_hour,
$this->end_minute,
$this->cal->hours_24);
}
function get_start_timestamp() {
return mktime(0, 0, 0, $this->get_start_month(),
$this->get_start_day(),
$this->get_start_year());
}
function get_end_timestamp() {
$hour = $this->end_hour ? $this->end_hour : 23;
$minute = $this->end_minute ? $this->end_minute : 59;
return mktime($hour, $minute, 59, $this->get_end_month(),
$this->get_end_day(), $this->get_end_year());
}
// takes start and end dates and returns a nice display
function get_date_string()
{
$start_time = $this->get_start_timestamp();
$end_time = $this->get_end_timestamp();
$str = $this->get_start_date();
if($start_time != $end_time)
$str .= ' - ' . $this->get_end_date();
return $str;
}
function get_datetime_string()
{
if ($this->duration <= 86400 && $this->start_day==$this->end_day)
{
//normal behaviour
$event_time = $this->get_time_span_string();
if(!empty($event_time))
$event_time = ' ' . __('at') . " $event_time";
$str= $this->get_date_string() . $event_time;
}
else
{
//format on multiple days
$str = ' ' . __('From') . ' ' . $this->get_start_date()
. ' ' . __('at') . ' ' . $this->get_start_time()
. ' ' . __('to') . ' ' . $this->get_end_date()
. ' ' . __('at') . ' ' . $this->get_end_time();
}
return $str;
}
function get_oid()
{
return $this->oid;
}
function get_time_type() {
return $this->time_type;
}
function get_start_ts() {
$start_hour = $this->start_hour;
if($start_hour == NULL)
$start_hour = 0;
$start_minute = $this->start_minute;
if($start_minute == NULL);
$start_minute = 0;
return mktime($start_hour, $start_minute, 0,
$this->start_month, $this->start_day,
$this->start_year);
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Money.php | src/Money.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use ArchTech\Money\Currency;
use Closure;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Str;
use Leandrocfe\FilamentPtbrFormFields\Currencies\BRL;
class Money extends TextInput
{
protected string|int|float|null $initialValue = '0,00';
protected ?Currency $currency = null;
protected bool|Closure $dehydrateMask = false;
protected bool|Closure $intFormat = false;
protected function setUp(): void
{
$this
->currency()
->prefix('R$')
->extraAlpineAttributes(fn () => [
...$this->getOnKeyPress(),
...$this->getOnKeyUp(),
...$this->getOnBlur(),
])
->formatStateUsing(fn ($state) => $this->hydrateCurrency($state))
->dehydrateStateUsing(fn ($state) => $this->dehydrateCurrency($state));
}
public function initialValue(null|string|int|float|Closure $value = '0,00'): static
{
$this->initialValue = $value;
return $this;
}
public function currency(string|null|Closure $currency = BRL::class): static
{
$this->currency = new ($currency);
currencies()->add($currency);
if ($currency !== 'BRL') {
$this->prefix(null);
}
return $this;
}
protected function hydrateCurrency($state): string
{
$sanitized = $this->sanitizeState($state);
$money = money(amount: $sanitized, currency: $this->getCurrency());
return $money->formatted(prefix: '');
}
protected function dehydrateCurrency($state): int|float|string
{
$sanitized = $this->sanitizeState($state);
$money = money(amount: $sanitized, currency: $this->getCurrency());
if ($this->getDehydrateMask()) {
return $money->formatted();
}
return $this->getIntFormat() ? $money->value() : $money->decimal();
}
public function dehydrateMask(bool $condition = true): static
{
$this->dehydrateMask = $condition;
return $this;
}
public function intFormat(bool|Closure $intFormat = true): static
{
$this->intFormat = $intFormat;
return $this;
}
protected function sanitizeState(?string $state): ?int
{
$state = Str::of($state)
->replace('.', '')
->replace(',', '')
->toInteger();
return $state;
}
protected function getOnKeyPress(): array
{
return [
'x-on:keypress' => 'function() {
var charCode = event.keyCode || event.which;
if (charCode < 48 || charCode > 57) {
event.preventDefault();
return false;
}
return true;
}',
];
}
protected function getOnKeyUp(): array
{
$currency = new ($this->getCurrency());
$numberFormatter = $currency->locale;
return [
'x-on:keyup' => 'function() {
$el.value = Currency.masking($el.value, {locales:\''.$numberFormatter.'\'});
}',
];
}
protected function getOnBlur(): array
{
return [
'x-on:blur' => 'function() {
$wire.set(\''.$this->getStatePath().'\', $el.value);
}',
];
}
public function getCurrency(): ?Currency
{
return $this->currency;
}
public function getDehydrateMask(): bool
{
return $this->dehydrateMask;
}
public function getIntFormat(): bool
{
return $this->intFormat;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/FilamentPtbrFormFieldsServiceProvider.php | src/FilamentPtbrFormFieldsServiceProvider.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use Filament\FilamentServiceProvider;
use Filament\Support\Assets\Js;
use Filament\Support\Facades\FilamentAsset;
use Spatie\LaravelPackageTools\Package;
class FilamentPtbrFormFieldsServiceProvider extends FilamentServiceProvider
{
public function packageBooted(): void
{
parent::packageBooted();
FilamentAsset::register([
Js::make('money-script', __DIR__.'/../resources/js/money.js'),
]);
}
public function configurePackage(Package $package): void
{
/*
* This class is a Package Service Provider
*
* More info: https://github.com/spatie/laravel-package-tools
*/
$package
->name('filament-ptbr-form-fields')
->hasConfigFile()
->hasViews();
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Cep.php | src/Cep.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use Filament\Forms\Components\TextInput;
use Illuminate\Contracts\Support\Htmlable;
use InvalidArgumentException;
use Leandrocfe\FilamentPtbrFormFields\Concerns\HasCepModes;
use Leandrocfe\FilamentPtbrFormFields\Providers\CepProviderInterface;
use Leandrocfe\FilamentPtbrFormFields\Providers\ViaCepProvider;
/**
* Brazilian ZIP code (CEP) field with automatic address lookup.
*/
class Cep extends TextInput
{
use HasCepModes;
protected null|string|Htmlable $errorMessage = 'CEP inválido';
protected function setUp(): void
{
parent::setUp();
$this
->minLength(9)
->mask('99999-999')
->placeholder('00000-000');
}
public function errorMessage(null|string|Htmlable $message): static
{
$this->errorMessage = $message;
return $this;
}
public function getErrorMessage(): null|string|Htmlable
{
return $this->errorMessage;
}
/**
* Configure the CEP provider and callback.
*/
public function api(string|CepProviderInterface $provider, callable $callback): static
{
$providerInstance = $this->resolveProvider($provider);
$this->configureFieldMode($providerInstance, $callback);
return $this;
}
private function resolveProvider(string|CepProviderInterface $provider): CepProviderInterface
{
$providerInstance = is_string($provider) ? new $provider : $provider;
if (! $providerInstance instanceof CepProviderInterface) {
throw new InvalidArgumentException(
'The provider must implement the CepProviderInterface interface.'
);
}
return $providerInstance;
}
/**
* Legacy method for backward compatibility.
*
* @deprecated Use api() method instead.
*/
public function viaCep(string $mode = 'suffix', string $errorMessage = 'CEP inválido.', array $setFields = []): static
{
return $this->api(
provider: ViaCepProvider::class,
callback: function ($set, $response) use ($setFields) {
foreach ($setFields as $key => $value) {
$set($key, $response[$value] ?? null);
}
},
);
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/PtbrCep.php | src/PtbrCep.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use Filament\Actions\Action;
use Filament\Forms\Components\Component;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Set;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use Livewire\Component as Livewire;
/**
* @deprecated Use `Cep` instead.
*/
class PtbrCep extends TextInput
{
public function viaCep(string $mode = 'suffix', string $errorMessage = 'CEP inválido.', array $setFields = []): static
{
$viaCepRequest = function ($state, $livewire, $set, $component, $errorMessage, array $setFields) {
$livewire->validateOnly($component->getKey());
$request = Http::get("viacep.com.br/ws/$state/json/")->json();
foreach ($setFields as $key => $value) {
$set($key, $request[$value] ?? null);
}
if (blank($request) || Arr::has($request, 'erro')) {
throw ValidationException::withMessages([
$component->getKey() => $errorMessage,
]);
}
};
$this
->minLength(9)
->mask('99999-999')
->afterStateUpdated(function ($state, Livewire $livewire, Set $set, Component $component) use ($errorMessage, $setFields, $viaCepRequest) {
$viaCepRequest($state, $livewire, $set, $component, $errorMessage, $setFields);
})
->suffixAction(function () use ($mode, $errorMessage, $setFields, $viaCepRequest) {
if ($mode === 'suffix') {
return Action::make('search-action')
->label('Buscar CEP')
->icon('heroicon-o-magnifying-glass')
->action(function ($state, Livewire $livewire, Set $set, Component $component) use ($errorMessage, $setFields, $viaCepRequest) {
$viaCepRequest($state, $livewire, $set, $component, $errorMessage, $setFields);
})
->cancelParentActions();
}
})
->prefixAction(function () use ($mode, $errorMessage, $setFields, $viaCepRequest) {
if ($mode === 'prefix') {
return Action::make('search-action')
->label('Buscar CEP')
->icon('heroicon-o-magnifying-glass')
->action(function ($state, Livewire $livewire, Set $set, Component $component) use ($errorMessage, $setFields, $viaCepRequest) {
$viaCepRequest($state, $livewire, $set, $component, $errorMessage, $setFields);
})
->cancelParentActions();
}
});
return $this;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/FilamentPtbrFormFields.php | src/FilamentPtbrFormFields.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
class FilamentPtbrFormFields {}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/PtbrPhone.php | src/PtbrPhone.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use Closure;
use Filament\Forms\Components\TextInput;
use Filament\Support\RawJs;
/**
* @deprecated Use `PhoneNumber` instead.
*/
class PtbrPhone extends TextInput
{
protected function setUp(): void
{
$this->dynamic();
}
public function dynamic(bool $condition = true): static
{
if ($condition) {
$this->mask(RawJs::make(<<<'JS'
$input.length > 14 ? '(99)99999-9999' : '(99)9999-9999'
JS));
}
return $this;
}
public function format(string|Closure $format = '(99)99999-9999'): static
{
$this->dynamic(false)
->minLength(0)
->mask($format);
return $this;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/PhoneNumber.php | src/PhoneNumber.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use Closure;
use Filament\Forms\Components\TextInput;
use Filament\Support\RawJs;
class PhoneNumber extends TextInput
{
protected function setUp(): void
{
$this->dynamic();
}
public function dynamic(bool $condition = true): static
{
if ($condition) {
$this->mask(RawJs::make(<<<'JS'
$input.length >= 14 ? '(99)99999-9999' : '(99)9999-9999'
JS));
}
return $this;
}
public function format(string|Closure $format = '(99)99999-9999'): static
{
$this->dynamic(false)
->minLength(0)
->mask($format);
return $this;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/CepFieldMode.php | src/CepFieldMode.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
enum CepFieldMode: string
{
case SUFFIX = 'suffix';
case ON_BLUR = 'on_blur';
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/PtbrMoney.php | src/PtbrMoney.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use Closure;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Str;
/**
* @deprecated Use `Money` instead.
*/
class PtbrMoney extends TextInput
{
protected string|int|float|null $initialValue = '0,00';
protected function setUp(): void
{
$this
->prefix('R$')
->maxLength(13)
->extraAlpineAttributes([
'x-on:keypress' => 'function() {
var charCode = event.keyCode || event.which;
if (charCode < 48 || charCode > 57) {
event.preventDefault();
return false;
}
return true;
}',
'x-on:keyup' => 'function() {
var money = $el.value.replace(/\D/g, "");
money = (money / 100).toFixed(2) + "";
money = money.replace(".", ",");
money = money.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,");
money = money.replace(/(\d)(\d{3}),/g, "$1.$2,");
$el.value = money;
}',
])
->dehydrateMask()
->default(0.00)
->formatStateUsing(fn ($state) => $state ? number_format(floatval($state), 2, ',', '.') : $this->initialValue);
}
public function dehydrateMask(bool|Closure $condition = true): static
{
if ($condition) {
$this->dehydrateStateUsing(
fn ($state): ?float => $state ?
floatval(
Str::of($state)
->replace('.', '')
->replace(',', '.')
->toString()
) :
null
);
} else {
$this->dehydrateStateUsing(null);
}
return $this;
}
public function initialValue(null|string|int|float|Closure $value = '0,00'): static
{
$this->initialValue = $value;
return $this;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/PtbrCpfCnpj.php | src/PtbrCpfCnpj.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use Closure;
use Filament\Forms\Components\TextInput;
use Filament\Support\RawJs;
/**
* @deprecated Use `Document` instead.
*/
class PtbrCpfCnpj extends TextInput
{
protected function setUp(): void
{
$this->dynamic();
}
public function dynamic(bool $condition = true): static
{
if ($condition) {
$this->mask(RawJs::make(<<<'JS'
$input.length > 14 ? '99.999.999/9999-99' : '999.999.999-99'
JS))->minLength(14);
}
return $this;
}
public function cpf(string|Closure $format = '999.999.999-99'): static
{
$this->dynamic(false)
->mask($format);
return $this;
}
public function cnpj(string|Closure $format = '99.999.999/9999-99'): static
{
$this->dynamic(false)
->mask($format);
return $this;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Document.php | src/Document.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields;
use Closure;
use Filament\Forms\Components\TextInput;
use Filament\Support\RawJs;
class Document extends TextInput
{
public bool $validation = true;
public function dynamic(bool $condition = true): static
{
if (self::getValidation()) {
$this->rule('cpf_ou_cnpj');
}
if ($condition) {
$this->mask(RawJs::make(<<<'JS'
$input.length > 14 ? '99.999.999/9999-99' : '999.999.999-99'
JS))->minLength(14);
}
return $this;
}
public function cpf(string|Closure $format = '999.999.999-99'): static
{
$this->dynamic(false)
->mask($format);
if (self::getValidation()) {
$this->rule('cpf');
}
return $this;
}
public function cnpj(string|Closure $format = '99.999.999/9999-99'): static
{
$this->dynamic(false)
->mask($format);
if (self::getValidation()) {
$this->rule('cnpj');
}
return $this;
}
public function validation(bool|Closure $condition = true): static
{
$this->validation = $condition;
return $this;
}
public function getValidation(): bool
{
return $this->validation;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Facades/FilamentPtbrFormFields.php | src/Facades/FilamentPtbrFormFields.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @see \Leandrocfe\FilamentPtbrFormFields\FilamentPtbrFormFields
*/
class FilamentPtbrFormFields extends Facade
{
protected static function getFacadeAccessor()
{
return \Leandrocfe\FilamentPtbrFormFields\FilamentPtbrFormFields::class;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Concerns/HasCepModes.php | src/Concerns/HasCepModes.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields\Concerns;
use Filament\Actions\Action;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Support\Icons\Heroicon;
use Leandrocfe\FilamentPtbrFormFields\CepFieldMode;
use Leandrocfe\FilamentPtbrFormFields\Providers\CepProviderInterface;
use Livewire\Component;
trait HasCepModes
{
protected CepFieldMode $mode = CepFieldMode::ON_BLUR;
public function mode(CepFieldMode $mode): static
{
$this->mode = $mode;
return $this;
}
public function getMode(): CepFieldMode
{
return $this->mode;
}
protected function configureFieldMode(CepProviderInterface $provider, callable $callback): static
{
return match ($this->getMode()) {
CepFieldMode::ON_BLUR => $this->configureOnBlurMode($provider, $callback),
CepFieldMode::SUFFIX => $this->configureSuffixMode($provider, $callback),
default => $this,
};
}
protected function configureOnBlurMode(CepProviderInterface $provider, callable $callback): static
{
return $this
->live(onBlur: true)
->afterStateUpdated(function (?string $state, Set $set, TextInput $component, Component $livewire) use ($provider, $callback) {
$livewire->validateOnly($component->getStatePath());
$response = $this->fetchCepData($state, $provider);
if (blank($response)) {
$livewire->addError($component->getStatePath(), $this->getErrorMessage());
}
$callback($set, $response);
});
}
protected function configureSuffixMode(CepProviderInterface $provider, callable $callback): static
{
return $this
->suffixAction(function () use ($provider, $callback) {
return Action::make('searchCep')
->icon(Heroicon::OutlinedMagnifyingGlass)
->action(function (?string $state, Set $set, TextInput $component, Component $livewire) use ($provider, $callback) {
$livewire->validateOnly($component->getStatePath());
$response = $this->fetchCepData($state, $provider);
if (blank($response)) {
$livewire->addError($component->getStatePath(), $this->getErrorMessage());
}
$callback($set, $response);
})
->cancelParentActions();
});
}
protected function fetchCepData(?string $cep, CepProviderInterface $provider): null|array|\Illuminate\Support\Collection
{
if (blank($cep)) {
return null;
}
return $provider->fetch($cep);
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Commands/FilamentPtbrFormFieldsCommand.php | src/Commands/FilamentPtbrFormFieldsCommand.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields\Commands;
use Illuminate\Console\Command;
class FilamentPtbrFormFieldsCommand extends Command
{
public $signature = 'filament-ptbr-form-fields';
public $description = 'My command';
public function handle(): int
{
$this->comment('All done');
return self::SUCCESS;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Currencies/USD.php | src/Currencies/USD.php | <?php
declare(strict_types=1);
namespace Leandrocfe\FilamentPtbrFormFields\Currencies;
use ArchTech\Money\Currency;
class USD extends Currency
{
public string $code = 'USD';
public string $name = 'United States Dollar';
public float $rate = 1.0;
public int $mathDecimals = 2;
public int $displayDecimals = 2;
public int $rounding = 2;
public string $prefix = '';
public string $locale = 'en';
public string $decimalSeparator = '.';
public string $thousandsSeparator = ',';
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Currencies/BRL.php | src/Currencies/BRL.php | <?php
declare(strict_types=1);
namespace Leandrocfe\FilamentPtbrFormFields\Currencies;
use ArchTech\Money\Currency;
class BRL extends Currency
{
public string $code = 'BRL';
public string $name = 'Real Brasileiro';
public float $rate = 1.0;
public int $mathDecimals = 2;
public int $displayDecimals = 2;
public int $rounding = 2;
public string $prefix = '';
public string $locale = 'pt-BR';
public string $decimalSeparator = ',';
public string $thousandsSeparator = '.';
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Providers/ViaCepProvider.php | src/Providers/ViaCepProvider.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields\Providers;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
class ViaCepProvider implements CepProviderInterface
{
protected ?string $url = null;
public function __construct(?string $url = null)
{
$this->url = $url ?? config('filament-ptbr-form-fields.viacep_url');
}
public function fetch(string $cep): null|Collection|array
{
$url = Str::of($this->url)
->append($cep)
->append('/json/');
$response = Http::get($url)->json();
if (blank($response) || Arr::has($response, 'erro')) {
return null;
}
return $response;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Providers/BrasilApiProvider.php | src/Providers/BrasilApiProvider.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields\Providers;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
class BrasilApiProvider implements CepProviderInterface
{
protected ?string $url = null;
public function __construct(?string $url = null)
{
$this->url = $url ?? config('filament-ptbr-form-fields.brasilapi_url');
}
public function fetch(string $cep): null|Collection|array
{
$url = Str::of($this->url)
->append($cep);
$response = Http::get($url)->json();
if (blank($response) || Arr::has($response, 'error')) {
return null;
}
return $response;
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/src/Providers/CepProviderInterface.php | src/Providers/CepProviderInterface.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields\Providers;
use Illuminate\Support\Collection;
interface CepProviderInterface
{
public function fetch(string $cep): null|Collection|array;
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/tests/Pest.php | tests/Pest.php | <?php
use Leandrocfe\FilamentPtbrFormFields\Tests\TestCase;
uses(TestCase::class)->in(__DIR__);
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/tests/TestCase.php | tests/TestCase.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields\Tests;
use Illuminate\Database\Eloquent\Factories\Factory;
use Leandrocfe\FilamentPtbrFormFields\FilamentPtbrFormFieldsServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;
class TestCase extends Orchestra
{
protected function setUp(): void
{
parent::setUp();
Factory::guessFactoryNamesUsing(
fn (string $modelName) => 'Leandrocfe\\FilamentPtbrFormFields\\Database\\Factories\\'.class_basename($modelName).'Factory'
);
}
protected function getPackageProviders($app)
{
return [
\Livewire\LivewireServiceProvider::class,
\Filament\Support\SupportServiceProvider::class,
\Filament\Forms\FormsServiceProvider::class,
FilamentPtbrFormFieldsServiceProvider::class,
];
}
public function getEnvironmentSetUp($app)
{
config()->set('database.default', 'testing');
/*
$migration = include __DIR__.'/../database/migrations/create_filament-ptbr-form-fields_table.php.stub';
$migration->up();
*/
}
}
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/tests/ArchTest.php | tests/ArchTest.php | <?php
it('will not use debugging functions')
->expect(['dd', 'dump', 'ray'])
->each->not->toBeUsed();
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/tests/ExampleTest.php | tests/ExampleTest.php | <?php
it('can test', function () {
expect(true)->toBeTrue();
});
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/config/filament-ptbr-form-fields.php | config/filament-ptbr-form-fields.php | <?php
return [
'viacep_url' => env('VIACEP_URL', 'viacep.com.br/ws/'),
'brasilapi_url' => env('BRASILAPI_URL', 'brasilapi.com.br/api/cep/v1/'),
];
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
leandrocfe/filament-ptbr-form-fields | https://github.com/leandrocfe/filament-ptbr-form-fields/blob/09ecd3b6ce4da148715df46c3161c8544a22316a/database/factories/ModelFactory.php | database/factories/ModelFactory.php | <?php
namespace Leandrocfe\FilamentPtbrFormFields\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/*
class ModelFactory extends Factory
{
protected $model = YourModel::class;
public function definition()
{
return [
];
}
}
*/
| php | MIT | 09ecd3b6ce4da148715df46c3161c8544a22316a | 2026-01-05T04:51:28.752482Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/helpers.php | app/helpers.php | <?php
declare(strict_types=1);
namespace App;
if (! function_exists('format_dns_type')) {
function format_dns_type(array $dnsRecord): string
{
return match ($dnsRecord['type']) {
'A' => (string) $dnsRecord['ip'],
'AAAA' => (string) $dnsRecord['ipv6'],
'MX' => "{$dnsRecord['target']} / PRI {$dnsRecord['pri']}",
'NS' => (string) $dnsRecord['target'],
'SOA' => "{$dnsRecord['mname']} / SN {$dnsRecord['serial']}",
'TXT' => (string) $dnsRecord['txt'],
default => (string) $dnsRecord['type']
};
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Exceptions/Handler.php | app/Exceptions/Handler.php | <?php
declare(strict_types=1);
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use OhDear\PhpSdk\Exceptions\UnauthorizedException;
use Throwable;
use function Termwind\render;
class Handler extends ExceptionHandler
{
public function renderForConsole($output, Throwable $e): void
{
if ($e instanceof UnauthorizedException) {
render(view('unauthorised')->render());
return;
}
parent::renderForConsole($output, $e);
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/BrokenLinkShowCommand.php | app/Commands/BrokenLinkShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\Dto\BrokenLink;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class BrokenLinkShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'broken-link:show {monitor-id : The id of the monitor to view broken links for}';
/** @var string */
protected $description = 'Display the broken links for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$brokenLinkList = collect($ohDear->brokenLinks($this->argument('monitor-id')))
->mapToGroups(fn (BrokenLink $brokenLink) => [$brokenLink->foundOnUrl => $brokenLink]);
render(view('broken-link-show', ['brokenLinkList' => $brokenLinkList]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MonitorAddCommand.php | app/Commands/MonitorAddCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MonitorAddCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'monitor:add
{url : The URL or location that you want to monitor}
{--http : Create an HTTP monitor (default)}
{--ping : Create an ICMP ping monitor}
{--tcp : Create a TCP port monitor}
{--t|team= : The id of the team that the monitor should be added to}
{--c|checks=* : The list of checks that should be used, defaults to all checks}';
/** @var string */
protected $description = 'Add a new monitor to Oh Dear';
/** {@inheritdoc} */
protected $aliases = ['sites:add'];
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
if (! ($url = $this->argument('url'))) {
$this->warn('A valid URL must be provided');
return;
}
if (! ($teamId = $this->option('team')) || ! is_numeric($teamId)) {
$this->warn('A valid team id must be provided');
return;
}
$checks = $this->hasOption('checks') ? ['checks' => $this->option('checks')] : [];
$type = match (true) {
$this->option('ping') => 'ping',
$this->option('tcp') => 'tcp',
default => 'http',
};
$monitor = $ohDear->createMonitor(array_merge([
'url' => $url,
'type' => $type,
'team_id' => $teamId,
], $checks));
render(view('notice', ['notice' => "Created a new monitor with id {$monitor->id}"]));
render(view('monitor-show', ['monitor' => $monitor, 'uptimePercentage' => 'N/A']));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/CronCheckAddCommand.php | app/Commands/CronCheckAddCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\Enums\CronType;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class CronCheckAddCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'cron-check:add
{monitor-id : The id of the monitor that you want to create a cron check for}
{name : The name of the cron check}
{frequency-or-expression : The frequency of the cron check in minutes, or cron expression}
{--grace-time=5 : The grace time in minutes}
{--description= : The description for the cron check}
{--timezone=UTC : The timezone of your server}';
/** @var string */
protected $description = 'Add a new cron check for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
if (! $name = $this->argument('name')) {
$this->warn('A valid name must be provided');
return;
}
$cronCheck = match (true) {
is_numeric($this->argument('frequency-or-expression')) => $ohDear->createCronCheckDefinition(
$this->argument('monitor-id'),
[
'name' => $name,
'type' => CronType::Simple,
'frequency_in_minutes' => (int) $this->argument('frequency-or-expression'),
'grace_time_in_minutes' => (int) $this->option('grace-time'),
'description' => $this->option('description') ?? '',
],
),
default => $ohDear->createCronCheckDefinition(
$this->argument('monitor-id'),
[
'name' => $name,
'type' => CronType::Cron,
'frequency_in_minutes' => (int) $this->argument('frequency-or-expression'),
'grace_time_in_minutes' => (int) $this->option('grace-time'),
'description' => $this->option('description') ?? '',
'timezone' => $this->option('timezone'),
],
)
};
$schedule = $cronCheck->cronExpression ?: "every {$cronCheck->frequencyInMinutes} minutes";
render(view('notice', [
'notice' => "{$cronCheck->name} (schedule: {$schedule}, grace time: {$cronCheck->graceTimeInMinutes} minutes) (ping url: {$cronCheck->pingUrl})",
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/CertificateHealthShowCommand.php | app/Commands/CertificateHealthShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class CertificateHealthShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'certificate-health:show {monitor-id : The id of the monitor to view certificate health for}
{--c|checks : Include a list of the certificate checks that were performed}
{--i|issuers : Include a list of the certificate issuers}
{--f|full : Include all certificate information}';
/** @var string */
protected $description = 'Display the certificate health for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('certificate-health-show', [
'certificateHealth' => $ohDear->certificateHealth($this->argument('monitor-id')),
'withChecks' => $this->option('checks') || $this->option('full'),
'withIssuers' => $this->option('issuers') || $this->option('full'),
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/CronCheckShowCommand.php | app/Commands/CronCheckShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class CronCheckShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'cron-check:show {monitor-id : The id of the monitor to view cron checks for}';
/** @var string */
protected $description = 'Display the cron checks for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('cron-check-show', ['cronChecks' => $ohDear->cronCheckDefinitions($this->argument('monitor-id'))]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MixedContentShowCommand.php | app/Commands/MixedContentShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\Dto\MixedContent;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MixedContentShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'mixed-content:show {monitor-id : The id of the monitor to view mixed content for}';
/** @var string */
protected $description = 'Display the mixed content for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$mixedContentList = collect($ohDear->mixedContent($this->argument('monitor-id')))
->mapToGroups(fn (MixedContent $mixedContent) => [$mixedContent->foundOnUrl => $mixedContent]);
render(view('mixed-content-show', ['mixedContentList' => $mixedContentList]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/LighthouseReportListCommand.php | app/Commands/LighthouseReportListCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class LighthouseReportListCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'lighthouse-report:list {monitor-id : The id of the monitor to view Lighthouse reports for}';
/** @var string */
protected $description = 'Display a list of Lighthouse reports and their summary';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('lighthouse-report-list', ['lighthouseReports' => $ohDear->lighthouseReports($this->argument('monitor-id'))]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/DowntimeShowCommand.php | app/Commands/DowntimeShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use Carbon\Carbon;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class DowntimeShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'downtime:show {monitor-id : The id of the monitor to view downtime for}
{start-date? : The date to start at}
{end-date? : The date to end at}
{--limit=10 : The number of downtime records to show}';
/** @var string */
protected $description = 'Display the recent downtime for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
if (! $startDate = $this->argument('start-date')) {
$startDate = Carbon::yesterday()->format('Y-m-d H:i:s');
}
if (! $endDate = $this->argument('end-date')) {
$endDate = now()->format('Y-m-d H:i:s');
}
$downtime = collect($ohDear->downtime($this->argument('monitor-id'), $startDate, $endDate))
->take((int) $this->option('limit'));
render(view('downtime-show', ['downtime' => $downtime]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MaintenancePeriodDeleteCommand.php | app/Commands/MaintenancePeriodDeleteCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MaintenancePeriodDeleteCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'maintenance-period:delete
{id : The id of the maintenance period that you want to delete}';
/** @var string */
protected $description = 'Delete a maintenance period';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$ohDear->deleteMaintenancePeriod($this->argument('id'));
render(view('notice', [
'notice' => "Removed the maintenance period with id {$this->argument('id')}",
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/StatusPageShowCommand.php | app/Commands/StatusPageShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class StatusPageShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'status-page:show {id : The id of the status page to view}';
/** @var string */
protected $description = 'Display a single status page and its details';
/** {@inheritdoc} */
protected $aliases = ['status-pages:show'];
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('status-page-show', ['statusPage' => $ohDear->statusPage($this->argument('id'))]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/DnsHistoryListCommand.php | app/Commands/DnsHistoryListCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class DnsHistoryListCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'dns-history:list {monitor-id : The id of the monitor to view DNS history for}';
/** @var string */
protected $description = 'Display a list of DNS history items and their summary';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('dns-history-list', ['dnsHistoryItems' => $ohDear->dnsHistoryItems($this->argument('monitor-id'))]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MaintenancePeriodShowCommand.php | app/Commands/MaintenancePeriodShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MaintenancePeriodShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'maintenance-period:show {monitor-id : The id of the monitor to view maintenance periods for}';
/** @var string */
protected $description = 'Display the maintenance periods for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('maintenance-period-show', [
'maintenancePeriods' => $ohDear->maintenancePeriods($this->argument('monitor-id')),
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/ApplicationHealthShowCommand.php | app/Commands/ApplicationHealthShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class ApplicationHealthShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'application-health:show {monitor-id : The id of the monitor to view application health for}';
/** @var string */
protected $description = 'Display the application health for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('application-health-show', [
'applicationHealthChecks' => $ohDear->applicationHealthChecks($this->argument('monitor-id')),
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/StatusPageUpdateDeleteCommand.php | app/Commands/StatusPageUpdateDeleteCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class StatusPageUpdateDeleteCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'status-page-update:delete
{id : The id of the status page update that you want to delete}';
/** @var string */
protected $description = 'Delete a status page update';
/** {@inheritdoc} */
protected $aliases = ['status-page-updates:delete'];
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$ohDear->deleteStatusPageUpdate($this->argument('id'));
render(view('notice', [
'notice' => "Removed the status page update with id {$this->argument('id')}",
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MaintenancePeriodStopCommand.php | app/Commands/MaintenancePeriodStopCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MaintenancePeriodStopCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'maintenance-period:stop
{monitor-id : The id of the monitor that you want to stop the maintenance period for}';
/** @var string */
protected $description = 'Stop the current maintenance period for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$ohDear->stopMaintenancePeriod($this->argument('monitor-id'));
render(view('notice', ['notice' => "Stopped the current maintenance period for monitor with id {$this->argument('monitor-id')}"]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/LighthouseReportShowCommand.php | app/Commands/LighthouseReportShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class LighthouseReportShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'lighthouse-report:show {monitor-id : The id of the monitor to access Lighthouse reports for}
{id=latest : The id of the Lighthouse report to view}';
/** @var string */
protected $description = 'Display the latest Lighthouse report for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$lighthouseReport = $this->argument('id') === 'latest'
? $ohDear->latestLighthouseReport($this->argument('monitor-id'))
: $ohDear->lighthouseReport($this->argument('monitor-id'), $this->argument('id'));
render(view('lighthouse-report-show', [
'lighthouseReport' => $lighthouseReport,
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/StatusPageUpdateAddCommand.php | app/Commands/StatusPageUpdateAddCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class StatusPageUpdateAddCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'status-page-update:add
{status-page-id : The id of the status page that the update should be added to}
{title : The title of the update}
{text : The main text of the update}
{--s|severity=info : The severity of the update (info, warning, high, resolved, or scheduled)}
{--p|pinned : The update should be pinned to the top of the status page}
{--t|time= : The time that the update should be registered at (default: now)}';
/** @var string */
protected $description = 'Add a new update to a status page';
/** {@inheritdoc} */
protected $aliases = ['status-page-updates:add'];
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
if ($this->option('severity') && ! in_array($this->option('severity'), ['info', 'warning', 'high', 'resolved', 'scheduled'])) {
$this->warn('Invalid severity level provided');
return 1;
}
$statusPageUpdate = $ohDear->createStatusPageUpdate([
'status_page_id' => $this->argument('status-page-id'),
'title' => $this->argument('title'),
'text' => $this->argument('text'),
'severity' => $this->option('severity'),
'pinned' => (bool) $this->option('pinned'),
'time' => $this->option('time') ?? now()->format('Y-m-d H:i'),
]);
render(view('notice', ['notice' => "Created a new status page update with id {$statusPageUpdate->id}"]));
render(view('status-page-update-show', ['statusPageUpdate' => $statusPageUpdate]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/CheckRequestRunCommand.php | app/Commands/CheckRequestRunCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class CheckRequestRunCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'check:request-run {id : The id of the check to run}';
/** @var string */
protected $description = 'Request a new run for a specific check';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$ohDear->requestCheckRun($this->argument('id'));
render(view('notice', [
'notice' => "Requested a run for the check with id {$this->argument('id')}",
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MaintenancePeriodAddCommand.php | app/Commands/MaintenancePeriodAddCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MaintenancePeriodAddCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'maintenance-period:add
{monitor-id : The id of the monitor that you want to create a maintenance period for}
{start-date : The start date that you want to create a maintenance period for}
{end-date : The end date that you want to create a maintenance period for}';
/** @var string */
protected $description = 'Add a new maintenance period for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
if (! $startDate = $this->argument('start-date')) {
$this->warn('A valid start date must be provided');
return;
}
if (! $endDate = $this->argument('end-date')) {
$this->warn('A valid end date must be provided');
return;
}
$maintenancePeriod = $ohDear->createMaintenancePeriod([
'monitor_id' => $this->argument('id'),
'starts_at' => $startDate,
'ends_at' => $endDate,
]);
render(view('notice', ['notice' => "Created a new maintenance period with id {$maintenancePeriod->id}"]));
render(view('maintenance-period-show', ['maintenancePeriods' => [$maintenancePeriod]]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/CheckDisableCommand.php | app/Commands/CheckDisableCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class CheckDisableCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'check:disable {id : The id of the check to disable}';
/** @var string */
protected $description = 'Disable a specific check';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$ohDear->disableCheck($this->argument('id'));
render(view('notice', [
'notice' => "Disabled the check with id {$this->argument('id')}",
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MonitorShowCommand.php | app/Commands/MonitorShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MonitorShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'monitor:show {id : The id of the monitor to view}';
/** @var string */
protected $description = 'Display a single monitor and its current status';
/** {@inheritdoc} */
protected $aliases = ['sites:show'];
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$monitor = $ohDear->monitor($this->argument('id'));
render(view('monitor-show', ['monitor' => $monitor]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/StatusPageUpdateListCommand.php | app/Commands/StatusPageUpdateListCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class StatusPageUpdateListCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'status-page-update:list { status-page-id : The id of the status page }';
/** @var string */
protected $description = 'Display a list of status page updates';
/** {@inheritdoc} */
protected $aliases = ['status-page-updates:list'];
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('status-page-update-list', ['statusPageUpdates' => $ohDear->statusPage($this->argument('status-page-id'))->updates]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/CronCheckDeleteCommand.php | app/Commands/CronCheckDeleteCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class CronCheckDeleteCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'cron-check:delete
{id : The id of the cron check that you want to delete}';
/** @var string */
protected $description = 'Delete a cron check';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$ohDear->deleteCronCheckDefinition($this->argument('id'));
render(view('notice', [
'notice' => "Removed the cron check with id {$this->argument('id')}",
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/StatusPageListCommand.php | app/Commands/StatusPageListCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class StatusPageListCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'status-page:list';
/** @var string */
protected $description = 'Display a list of status pages and their summary';
/** {@inheritdoc} */
protected $aliases = ['status-pages:list'];
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('status-page-list', ['statusPages' => $ohDear->statusPages()]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/DnsHistoryShowCommand.php | app/Commands/DnsHistoryShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class DnsHistoryShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'dns-history:show {monitor-id : The id of the monitor to access DNS history items for}
{id : The id of the DNS history item to view}';
/** @var string */
protected $description = 'Display the latest performance details for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('dns-history-show', [
'dnsHistoryItem' => $ohDear->dnsHistoryItem($this->argument('monitor-id'), $this->argument('id')),
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MonitorListCommand.php | app/Commands/MonitorListCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MonitorListCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'monitor:list';
/** @var string */
protected $description = 'Display a list of monitors and their current status';
/** {@inheritdoc} */
protected $aliases = ['sites:list'];
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('monitor-list', ['monitors' => $ohDear->monitors()]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/CheckShowCommand.php | app/Commands/CheckShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class CheckShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'check:show {monitor-id : The id of the monitor to view checks for}';
/** @var string */
protected $description = 'Display the checks for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$checks = $ohDear->monitor($this->argument('monitor-id'))->checks;
render(view('check-show', ['checks' => $checks]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MeCommand.php | app/Commands/MeCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MeCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'me';
/** @var string */
protected $description = 'Display information about the currently authenticated user';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
render(view('me', ['user' => $ohDear->me()]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/UptimeShowCommand.php | app/Commands/UptimeShowCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use Carbon\Carbon;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\Enums\UptimeSplit;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class UptimeShowCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'uptime:show {monitor-id : The id of the monitor to view uptime for}
{start-date? : The date to start at}
{end-date? : The date to end at}
{--limit=10 : The number of uptime records to show}
{--timeframe=hour : The timeframe to query data by (hour, day, month)}';
/** @var string */
protected $description = 'Display the recent uptime for a monitor';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
if (! $startDate = $this->argument('start-date')) {
$startDate = Carbon::yesterday()->format('Y-m-d H:i:s');
}
if (! $endDate = $this->argument('end-date')) {
$endDate = now()->format('Y-m-d H:i:s');
}
$timeframe = $this->timeframeToSplit($this->option('timeframe'));
$uptime = $ohDear->uptime($this->argument('monitor-id'), $startDate, $endDate, $timeframe);
render(view('uptime-show', ['uptime' => collect($uptime)->take((int) $this->option('limit'))]));
}
private function timeframeToSplit(mixed $timeframe): UptimeSplit
{
return match ($timeframe) {
'month' => UptimeSplit::Month,
'day' => UptimeSplit::Day,
default => UptimeSplit::Hour,
};
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/MaintenancePeriodStartCommand.php | app/Commands/MaintenancePeriodStartCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class MaintenancePeriodStartCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'maintenance-period:start
{monitor-id : The id of the monitor that you want to create a maintenance period for}
{seconds : The maintenance period in seconds}';
/** @var string */
protected $description = 'Start a new maintenance period for a monitor from the current time';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$seconds = $this->argument('seconds');
if (! $seconds || ! is_numeric($seconds)) {
$this->warn('A valid number of seconds must be provided');
return;
}
$maintenancePeriod = $ohDear->startMaintenancePeriod($this->argument('monitor-id'), (int) $seconds);
render(view('notice', ['notice' => "Started a new maintenance period with id {$maintenancePeriod->id}"]));
render(view('maintenance-period-show', ['maintenancePeriods' => [$maintenancePeriod]]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/CheckEnableCommand.php | app/Commands/CheckEnableCommand.php | <?php
namespace App\Commands;
use App\Commands\Concerns\EnsureHasToken;
use LaravelZero\Framework\Commands\Command;
use OhDear\PhpSdk\OhDear;
use function Termwind\render;
class CheckEnableCommand extends Command
{
use EnsureHasToken;
/** @var string */
protected $signature = 'check:enable {id : The id of the check to enable}';
/** @var string */
protected $description = 'Enable a specific check';
public function handle(OhDear $ohDear)
{
if (! $this->ensureHasToken()) {
return 1;
}
$ohDear->enableCheck($this->argument('id'));
render(view('notice', [
'notice' => "Enabled the check with id {$this->argument('id')}",
]));
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/Concerns/HasUsefulConsoleMethods.php | app/Commands/Concerns/HasUsefulConsoleMethods.php | <?php
declare(strict_types=1);
namespace App\Commands\Concerns;
use Illuminate\Console\Command;
use function Termwind\render;
/**
* @mixin Command
*/
trait HasUsefulConsoleMethods
{
private function success(string $message): self
{
render("
<div class='mx-2 px-2 py-1 bg-green-500 font-bold'>$message</div>
");
return $this;
}
private function warning(string $message): self
{
render("
<div class='mx-2 px-2 py-1 bg-yellow-500 text-black font-bold'>$message</div>
");
return $this;
}
private function information(string $message): self
{
render("
<div class='mx-2 my-1 px-2 py-1 bg-blue-500 text-black font-bold text-gray-50'>$message</div>
");
return $this;
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Commands/Concerns/EnsureHasToken.php | app/Commands/Concerns/EnsureHasToken.php | <?php
namespace App\Commands\Concerns;
use function Termwind\render;
trait EnsureHasToken
{
protected function hasToken(): bool
{
return config('settings.ohdear_api_token') !== null && config('settings.ohdear_api_token') !== '';
}
protected function ensureHasToken(): bool
{
if (! $this->hasToken()) {
render(view('unauthorised'));
return false;
}
return true;
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/app/Providers/AppServiceProvider.php | app/Providers/AppServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use OhDear\PhpSdk\OhDear;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->app->singleton(OhDear::class, function () {
return new OhDear(config('settings.ohdear_api_token') ?? '');
});
}
public function register(): void
{
//
}
}
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/bootstrap/app.php | bootstrap/app.php | <?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new LaravelZero\Framework\Application(
dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
LaravelZero\Framework\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/config/commands.php | config/commands.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Command
|--------------------------------------------------------------------------
|
| Laravel Zero will always run the command specified below when no command name is
| provided. Consider update the default command for single command applications.
| You cannot pass arguments to the default command because they are ignored.
|
*/
'default' => NunoMaduro\LaravelConsoleSummary\SummaryCommand::class,
/*
|--------------------------------------------------------------------------
| Commands Paths
|--------------------------------------------------------------------------
|
| This value determines the "paths" that should be loaded by the console's
| kernel. Foreach "path" present on the array provided below the kernel
| will extract all "Illuminate\Console\Command" based class commands.
|
*/
'paths' => [app_path('Commands')],
/*
|--------------------------------------------------------------------------
| Added Commands
|--------------------------------------------------------------------------
|
| You may want to include a single command class without having to load an
| entire folder. Here you can specify which commands should be added to
| your list of commands. The console's kernel will try to load them.
|
*/
'add' => [
// ..
],
/*
|--------------------------------------------------------------------------
| Hidden Commands
|--------------------------------------------------------------------------
|
| Your application commands will always be visible on the application list
| of commands. But you can still make them "hidden" specifying an array
| of commands below. All "hidden" commands can still be run/executed.
|
*/
'hidden' => [
NunoMaduro\LaravelConsoleSummary\SummaryCommand::class,
Symfony\Component\Console\Command\DumpCompletionCommand::class,
Symfony\Component\Console\Command\HelpCommand::class,
Illuminate\Console\Scheduling\ScheduleRunCommand::class,
Illuminate\Console\Scheduling\ScheduleListCommand::class,
Illuminate\Console\Scheduling\ScheduleFinishCommand::class,
LaravelZero\Framework\Commands\StubPublishCommand::class,
],
/*
|--------------------------------------------------------------------------
| Removed Commands
|--------------------------------------------------------------------------
|
| Do you have a service provider that loads a list of commands that
| you don't need? No problem. Laravel Zero allows you to specify
| below a list of commands that you don't to see in your app.
|
*/
'remove' => [
// ..
],
];
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/config/app.php | config/app.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => 'Oh Dear',
/*
|--------------------------------------------------------------------------
| Application Version
|--------------------------------------------------------------------------
|
| This value determines the "version" your application is currently running
| in. You may want to follow the "Semantic Versioning" - Given a version
| number MAJOR.MINOR.PATCH when an update happens: https://semver.org.
|
*/
'version' => app('git.version'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. This can be overridden using
| the global command line "--env" option when calling commands.
|
*/
'env' => 'development',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
App\Providers\AppServiceProvider::class,
],
];
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/config/view.php | config/view.php | <?php
return [
'paths' => [
resource_path('views'),
],
'compiled' => sys_get_temp_dir(),
];
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/config/settings.php | config/settings.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Oh Dear API Token
|--------------------------------------------------------------------------
|
| An Oh Dear API token.
|
| Learn how to get an API token at the Oh Dear docs.
| https://ohdear.app/docs/integrations/api/authentication
|
*/
'ohdear_api_token' => env('OHDEAR_API_TOKEN'),
];
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/status-page-update-list.blade.php | resources/views/status-page-update-list.blade.php | @php /** @var list<array<string, mixed>> $statusPageUpdates */ @endphp
<x-layouts.app>
<table style="box">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Severity</th>
<th>Text</th>
<th>Pinned</th>
<th>Time</th>
</tr>
</thead>
@forelse($statusPageUpdates as $statusPageUpdate)
<tr>
<td>
<span>{{ $statusPageUpdate['id'] }}</span>
</td>
<td>
<span>{{ $statusPageUpdate['title'] }}</span>
</td>
<td>
<span>{{ $statusPageUpdate['severity'] }}</span>
</td>
<td>
<span>{{ $statusPageUpdate['text'] }}</span>
</td>
<td>
<span>{{ $statusPageUpdate['pinned'] ? 'Yes' : 'No' }}</span>
</td>
<td>
<span>{{ $statusPageUpdate['time'] }}</span>
</td>
</tr>
@empty
<tr>
<td colspan="6">No updates were found for the specified status page.</td>
</tr>
@endforelse
</table>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/status-page-update-show.blade.php | resources/views/status-page-update-show.blade.php | @php /** @var OhDear\PhpSdk\Dto\StatusPageUpdate $statusPageUpdate */ @endphp
<x-layouts.app>
<div>
<span class="font-bold text-gray block">ID:</span> {{ $statusPageUpdate->id }}
<span class="font-bold text-gray block">Title:</span> {{ $statusPageUpdate->title }}
<span class="font-bold text-gray block">Severity:</span> {{ $statusPageUpdate->severity }}
<span class="font-bold text-gray block">Pinned:</span> {{ $statusPageUpdate->pinned ? 'Yes' : 'No' }}
<span class="font-bold text-gray block">Time:</span> {{ $statusPageUpdate->time }}
</div>
<pre class="mt-1">{{ $statusPageUpdate->text }}</pre>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/cron-check-show.blade.php | resources/views/cron-check-show.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\CronCheckDefinition> $cronChecks */ @endphp
<x-layouts.app>
<div class="underline">Cron Checks:</div>
<ul>
@forelse($cronChecks as $cronCheck)
<li>
<span class="font-bold text-gray">{{ $cronCheck->name }}</span> (schedule: {{ $cronCheck->cronExpression ?: "every {$cronCheck->frequencyInMinutes} minutes" }}, grace time: {{ $cronCheck->graceTimeInMinutes }} minutes) (ping url: {{ $cronCheck->pingUrl }})
</li>
@empty
<li class="list-none">
<span>No cron checks were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/broken-link-show.blade.php | resources/views/broken-link-show.blade.php | @php /** @var array<string, list<OhDear\PhpSdk\Dto\BrokenLink>> $brokenLinkList */ @endphp
<x-layouts.app>
@forelse($brokenLinkList as $foundOnUrl => $brokenLinks)
<div>
<div class="underline mt-1">{{ $foundOnUrl }}</div>
<ul>
@forelse ($brokenLinks as $brokenLink)
<li>
<span class="font-bold text-gray">{{ $brokenLink->statusCode }}</span> ({{ $brokenLink->crawledUrl }})
</li>
@empty
<li class="list-none">
<span>No broken links were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</div>
@empty
<div>
<span>No broken links were found for the specified monitor.</span>
</div>
@endforelse
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/lighthouse-report-list.blade.php | resources/views/lighthouse-report-list.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\LighthouseReport> $lighthouseReports */ @endphp
<x-layouts.app>
<table style="box">
<thead>
<tr>
<th>ID</th>
<th>P</th>
<th>A</th>
<th>BP</th>
<th>SEO</th>
<th>PWA</th>
<th>Created</th>
</tr>
</thead>
@forelse($lighthouseReports as $lighthouseReport)
<tr>
<td>
<span>{{ $lighthouseReport->id }}</span>
</td>
<td>
<span>{{ $lighthouseReport->performanceScore }}</span>
</td>
<td>
<span>{{ $lighthouseReport->accessibilityScore }}</span>
</td>
<td>
<span>{{ $lighthouseReport->bestPracticesScore }}</span>
</td>
<td>
<span>{{ $lighthouseReport->seoScore }}</span>
</td>
<td>
<span>{{ $lighthouseReport->progressiveWebAppScore }}</span>
</td>
<td>
<span>{{ $lighthouseReport->createdAt }}</span>
</td>
</tr>
@empty
<tr>
<td colspan="3">No Lighthouse reports were found for the authenticated user.</td>
</tr>
@endforelse
</table>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/unauthorised.blade.php | resources/views/unauthorised.blade.php | <x-layouts.app>
<div class="text-red-500">
<span>Unauthorised</span>
</div>
<p class="mt-1">
Please set the <span class="font-bold">OHDEAR_API_TOKEN</span> environment variable to your <a href="https://ohdear.app/user/api-tokens">Oh Dear API token</a>.
</p>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/status-page-show.blade.php | resources/views/status-page-show.blade.php | @php /** @var OhDear\PhpSdk\Dto\StatusPage $statusPage */ @endphp
<x-layouts.app>
<div>
<span class="font-bold text-gray block">ID:</span> {{ $statusPage->id }}
<span class="font-bold text-gray block">Name:</span> {{ $statusPage->title }}
<span class="font-bold text-gray block">URL:</span> {{ $statusPage->fullUrl }}
<span class="font-bold text-gray block">Timezone:</span> {{ $statusPage->timezone }}
<span class="font-bold text-gray block">Status Summary:</span> {{ $statusPage->summarizedStatus }}
</div>
<div class="underline mt-1">Monitors:</div>
<ul>
@forelse ($statusPage->monitors as $monitor)
<li>
<span class="font-bold text-gray">{{ $monitor['sort_url'] }}</span>
</li>
@empty
<li class="list-none">
<span>No monitors were found for the specified status page.</span>
</li>
@endforelse
</ul>
<div class="underline mt-1">Latest Updates:</div>
<ul>
@forelse (collect($statusPage->updates)->take(5) as $update)
<li>
<span class="font-bold text-gray">{{ $update['title'] }}</span> ({{ $update['severity'] }}, {{ $update['time'] }})
</li>
@empty
<li class="list-none">
<span>No updates were found for the specified status page.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/status-page-list.blade.php | resources/views/status-page-list.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\StatusPage> $statusPage */ @endphp
<x-layouts.app>
<table style="box">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status Summary</th>
<th>Monitors</th>
</tr>
</thead>
@forelse($statusPages as $statusPage)
<tr>
<td>
<span>{{ $statusPage->id }}</span>
</td>
<td>
<span>{{ $statusPage->title }}</span>
</td>
<td>
<span>{{ $statusPage->summarizedStatus }}</span>
</td>
<td>
<span>{{ implode(',', collect($statusPage->monitors)->map(fn (array $monitor) => $monitor['sort_url'])->toArray()) }}</span>
</td>
</tr>
@empty
<tr>
<td colspan="4">No monitors were found for the authenticated user.</td>
</tr>
@endforelse
</table>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/lighthouse-report-show.blade.php | resources/views/lighthouse-report-show.blade.php | @php /** @var OhDear\PhpSdk\Dto\LighthouseReport $lighthouseReport */ @endphp
<x-layouts.app>
<div>
<span class="font-bold text-gray block">ID:</span> {{ $lighthouseReport->id }}
<span class="font-bold text-gray block">Performed on Server:</span> {{ $lighthouseReport->performedOnCheckerServer }}
<span class="font-bold text-gray block">Created At:</span> {{ $lighthouseReport->createdAt }}
</div>
<div class="underline mt-1">Scores:</div>
<div>
<span class="font-bold text-gray block">Performance Score:</span> {{ $lighthouseReport->performanceScore }}
<span class="font-bold text-gray block">Accessibility Score:</span> {{ $lighthouseReport->accessibilityScore }}
<span class="font-bold text-gray block">Best Practices Score:</span> {{ $lighthouseReport->bestPracticesScore }}
<span class="font-bold text-gray block">SEO Score:</span> {{ $lighthouseReport->seoScore }}
<span class="font-bold text-gray block">PWA Score:</span> {{ $lighthouseReport->progressiveWebAppScore }}
</div>
<div class="underline mt-1">Speed:</div>
<div>
<span class="font-bold text-gray block">First Contentful Pain (ms):</span> {{ $lighthouseReport->firstContentfulPaintInMs }}
<span class="font-bold text-gray block">Speed Index (ms):</span> {{ $lighthouseReport->speedIndexInMs }}
<span class="font-bold text-gray block">Largest Contentful Paint (ms):</span> {{ $lighthouseReport->largestContentfulPaintInMs }}
<span class="font-bold text-gray block">Time to Interactive (ms):</span> {{ $lighthouseReport->timeToInteractiveInMs }}
<span class="font-bold text-gray block">Total Blocking Time (ms):</span> {{ $lighthouseReport->totalBlockingTimeInMs }}
<span class="font-bold text-gray block">Cumulative Layout Shift:</span> {{ $lighthouseReport->cumulativeLayoutShift }}
</div>
<div class="underline mt-1">Issues:</div>
<ul>
@forelse ($lighthouseReport->issues as $issue)
<li>
<span class="font-bold text-gray">{{ $issue['category'] }} ({{ $issue['actualScore'] }})</span>
</li>
@empty
<li class="list-none">
<span>No issues were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/uptime-show.blade.php | resources/views/uptime-show.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\Uptime> $uptime */ @endphp
<x-layouts.app>
<div class="underline">Uptime:</div>
<ul>
@forelse ($uptime as $entry)
<li>
<span class="font-bold text-gray">{{ $entry->datetime }}</span> ({{ $entry->uptimePercentage }}%)
</li>
@empty
<li class="list-none">
<span>No uptime entries were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/notice.blade.php | resources/views/notice.blade.php | <x-layouts.app>
<span>{{ $notice }}</span>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/downtime-show.blade.php | resources/views/downtime-show.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\DowntimePeriod> $downtime */ @endphp
<x-layouts.app>
<div class="underline">Downtime:</div>
<ul>
@forelse($downtime as $entry)
<li>
<span class="font-bold text-gray">{{ $entry->startedAt }}</span> to {{ $cronCheck->endedAt ?? 'ongoing' }}
</li>
@empty
<li class="list-none">
<span>No downtime entries were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/dns-history-show.blade.php | resources/views/dns-history-show.blade.php | @php /** @var OhDear\PhpSdk\Dto\DnsHistoryItem $dnsHistoryItem */ @endphp
<x-layouts.app>
<div>
<span class="font-bold text-gray block">ID:</span> {{ $dnsHistoryItem->id }}
<span class="font-bold text-gray block">Status Summary:</span> {{ $dnsHistoryItem->diffSummary }}
<span class="font-bold text-gray block">Created At:</span> {{ $dnsHistoryItem->createdAt }}
</div>
<div class="underline mt-1">Authoritative Nameservers:</div>
<ul>
@forelse ($dnsHistoryItem->authoritativeNameservers as $nameserver)
<li>
<span class="font-bold text-gray">{{ $nameserver }}</span>
</li>
@empty
<li class="list-none">
<span>No nameservers were found for the specified monitor.</span>
</li>
@endforelse
</ul>
<div class="underline mt-1">DNS Records:</div>
<ul>
@forelse ($dnsHistoryItem->dnsRecords as $dnsRecord)
<li>
<span class="font-bold text-gray">{{ $dnsRecord['type'] }}</span> - {{ $dnsRecord['host'] }}, <span class="text-gray">{{ App\format_dns_type($dnsRecord) }}</span> (TTL {{ $dnsRecord['ttl'] }})
</li>
@empty
<li class="list-none">
<span>No nameservers were found for the specified monitor.</span>
</li>
@endforelse
</ul>
<div class="underline mt-1">Issues:</div>
<ul>
@forelse ($dnsHistoryItem->issues as $issue)
<li>
<span class="font-bold text-gray">{{ $dnsRecord['name'] }}</span>
</li>
@empty
<li class="list-none">
<span>No issues were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/dns-history-list.blade.php | resources/views/dns-history-list.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\DnsHistoryItem> $dnsHistoryItems */ @endphp
<x-layouts.app>
<table style="box">
<thead>
<tr>
<th>ID</th>
<th>Difference Summary</th>
<th>Created</th>
</tr>
</thead>
@forelse($dnsHistoryItems as $dnsHistoryItem)
<tr>
<td>
<span>{{ $dnsHistoryItem->id }}</span>
</td>
<td>
<span>{{ $dnsHistoryItem->diffSummary }}</span>
</td>
<td>
<span>{{ $dnsHistoryItem->createdAt }}</span>
</td>
</tr>
@empty
<tr>
<td colspan="3">No DNS history items were found for the authenticated user.</td>
</tr>
@endforelse
</table>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/mixed-content-show.blade.php | resources/views/mixed-content-show.blade.php | @php /** @var array<string, list<OhDear\PhpSdk\Dto\MixedContent>> $mixedContentList */ @endphp
<x-layouts.app>
@forelse($mixedContentList as $foundOnUrl => $mixedContents)
<div>
<div class="underline mt-1">{{ $foundOnUrl }}</div>
<ul>
@forelse ($mixedContents as $mixedContent)
<li>
<span class="font-bold text-gray">{{ $mixedContent->elementName }}</span> ({{ $mixedContent->mixedContentUrl }})
</li>
@empty
<li class="list-none">
<span>No mixed content was found for the specified monitor.</span>
</li>
@endforelse
</ul>
</div>
@empty
<div>
<span>No mixed content was found for the specified monitor.</span>
</div>
@endforelse
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/me.blade.php | resources/views/me.blade.php | @php /** @var OhDear\PhpSdk\Dto\User $user */ @endphp
<x-layouts.app>
<div>
<span class="font-bold text-gray block">ID:</span> {{ $user->id }}
<span class="font-bold text-gray block">Name:</span> {{ $user->name }}
<span class="font-bold text-gray block">Email:</span> {{ $user->email }}
</div>
<div class="underline mt-1">Teams:</div>
<ul>
@forelse ($user->teams as $team)
<li>
<span class="font-bold text-gray capitalize">{{ $team['name'] }}</span> ({{ $team['id'] }})
</li>
@empty
<li class="list-none">
<span>No teams were found for the authenticated user.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/monitor-show.blade.php | resources/views/monitor-show.blade.php | @php /** @var OhDear\PhpSdk\Dto\Monitor $monitor */ @endphp
<x-layouts.app>
<div>
<span class="font-bold text-gray block">ID:</span> {{ $monitor->id }}
<span class="font-bold text-gray block">URL:</span> {{ $monitor->url }}
<span class="font-bold text-gray block">Status Summary:</span> {{ $monitor->summarizedCheckResult }}
<span class="font-bold text-gray block">Last Run At:</span> {{ $monitor->latestRunDate }}
<span class="font-bold text-gray block">Uptime in last 24hrs:</span> {{ $uptimePercentage ?? 'N/A' }}
</div>
<div class="underline mt-1">Checks:</div>
<ul>
@forelse ($monitor->checks as $check)
<li>
<span class="font-bold text-gray capitalize">{{ $check['label'] }}</span> ({{ $check['enabled'] ? 'Enabled' : 'Disabled' }})
</li>
@empty
<li class="list-none">
<span>No checks were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/maintenance-period-show.blade.php | resources/views/maintenance-period-show.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\MaintenancePeriod> $maintenancePeriods */ @endphp
<x-layouts.app>
<div class="underline">Maintenance Periods:</div>
<ul>
@forelse($maintenancePeriods as $maintenancePeriod)
<li>
<span class="font-bold text-gray">{{ $maintenancePeriod->id }}</span> (monitor: {{ $maintenancePeriod->monitorId }}) ({{ $maintenancePeriod->startsAt }} to {{ $maintenancePeriod->endsAt }})
</li>
@empty
<li class="list-none">
<span>No maintenance periods were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/monitor-list.blade.php | resources/views/monitor-list.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\Monitor> $monitors */ @endphp
<x-layouts.app>
<table style="box">
<thead>
<tr>
<th>ID</th>
<th>URL</th>
<th>Status Summary</th>
<th>Last Checked</th>
</tr>
</thead>
@forelse($monitors as $monitor)
<tr>
<td>
<span>{{ $monitor->id }}</span>
</td>
<td>
<a href="{{ $monitor->url }}">{{ $monitor->url }}</a>
</td>
<td>
<span>{{ $monitor->summarizedCheckResult }}</span>
</td>
<td>
<span>{{ $monitor->latestRunDate }}</span>
</td>
</tr>
@empty
<tr>
<td colspan="4">No monitors were found for the authenticated user.</td>
</tr>
@endforelse
</table>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/application-health-show.blade.php | resources/views/application-health-show.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\ApplicationHealthCheck> $applicationHealthChecks */ @endphp
<x-layouts.app>
<div class="underline mt-1">Application Health:</div>
<ul>
@forelse ($applicationHealthChecks as $check)
<li>
<span class="font-bold text-gray">{{ $check->label }}</span>
({{ $check->status }}) @if($check->message) - {{ $check->message }}@endif
</li>
@empty
<li class="list-none">
<span>No application checks were found for the specified monitor.</span>
</li>
@endforelse
</ul>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/check-show.blade.php | resources/views/check-show.blade.php | @php /** @var list<OhDear\PhpSdk\Dto\Check> $checks */ @endphp
<x-layouts.app>
<table style="box">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Type</th>
<th>Enabled</th>
</tr>
</thead>
@forelse($checks as $check)
<tr>
<td>
<span>{{ $check['id'] }}</span>
</td>
<td>
<span>{{ $check['label'] }}</span>
</td>
<td>
<span>{{ $check['type'] }}</span>
</td>
<td>
<span>{{ $check['enabled'] ? 'Yes' : 'No' }}</span>
</td>
</tr>
@empty
<tr>
<td colspan="2">No checks were found for the specified monitor.</td>
</tr>
@endforelse
</table>
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/certificate-health-show.blade.php | resources/views/certificate-health-show.blade.php | @php /** @var OhDear\PhpSdk\Dto\CertificateHealth $certificateHealth */ @endphp
<x-layouts.app>
<div>
<span class="underline">Certificate Details</span>
<span class="font-bold text-gray block">Issuer:</span> {{ $certificateHealth->certificateDetails['issuer'] }}
<span
class="font-bold text-gray block">Valid From:</span> {{ $certificateHealth->certificateDetails['valid_from'] }}
<span
class="font-bold text-gray block">Valid Until:</span> {{ $certificateHealth->certificateDetails['valid_until'] }}
</div>
@if ($withChecks)
<div class="underline mt-1">Certificate Checks:</div>
<ul>
@forelse ($certificateHealth->certificateChecks as $check)
<li>
<span class="font-bold text-gray">{{ $check['label'] }}</span>
({{ $check['passed'] ? 'Passed' : 'Failed' }})
</li>
@empty
<li class="list-none">
<span>No certificate checks were found for the specified monitor.</span>
</li>
@endforelse
</ul>
@endif
@if ($withIssuers)
<div class="underline mt-1">Issuers:</div>
<ul>
@forelse ($certificateHealth->certificateChainIssuers as $issuer)
<li>
<span class="font-bold text-gray">{{ $issuer }}</span>
</li>
@empty
<li class="list-none">
<span>No issuers were found for the specified monitor.</span>
</li>
@endforelse
</ul>
@endif
</x-layouts.app>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
ohdearapp/ohdear-cli | https://github.com/ohdearapp/ohdear-cli/blob/b3ddc4c382552c3a43ffb5ef5135577474caf34f/resources/views/components/layouts/app.blade.php | resources/views/components/layouts/app.blade.php | <div {{ $attributes->merge(['class' => 'ml-2 my-1']) }}>
{{ $slot }}
</div>
| php | MIT | b3ddc4c382552c3a43ffb5ef5135577474caf34f | 2026-01-05T04:51:23.368653Z | false |
SiavashBamshadnia/Laravel-Query-Enrich | https://github.com/SiavashBamshadnia/Laravel-Query-Enrich/blob/bafb849ed83b7c816d9a94a0d71651821db780a0/workbench/app/Enums/BookPrice.php | workbench/app/Enums/BookPrice.php | <?php
namespace Workbench\App\Enums;
/**
* An example enum showing values in uppercase, lowercase, and mixed case.
*/
enum BookPrice: string
{
case EXPENSIVE = 'expensive';
case CHEAP = 'CHEAP';
case Affordable = 'Affordable';
}
| php | MIT | bafb849ed83b7c816d9a94a0d71651821db780a0 | 2026-01-05T04:51:45.342665Z | false |
SiavashBamshadnia/Laravel-Query-Enrich | https://github.com/SiavashBamshadnia/Laravel-Query-Enrich/blob/bafb849ed83b7c816d9a94a0d71651821db780a0/workbench/app/Models/Author.php | workbench/app/Models/Author.php | <?php
namespace Workbench\App\Models;
use Illuminate\Database\Eloquent\Concerns\HasTimestamps;
use Illuminate\Database\Eloquent\Model;
class Author extends Model
{
use HasTimestamps;
protected $guarded = [];
public function books()
{
return $this->hasMany(Book::class);
}
}
| php | MIT | bafb849ed83b7c816d9a94a0d71651821db780a0 | 2026-01-05T04:51:45.342665Z | false |
SiavashBamshadnia/Laravel-Query-Enrich | https://github.com/SiavashBamshadnia/Laravel-Query-Enrich/blob/bafb849ed83b7c816d9a94a0d71651821db780a0/workbench/app/Models/Book.php | workbench/app/Models/Book.php | <?php
namespace Workbench\App\Models;
use Illuminate\Database\Eloquent\Concerns\HasTimestamps;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
use HasTimestamps;
protected $guarded = [];
public function author()
{
return $this->belongsTo(Author::class);
}
}
| php | MIT | bafb849ed83b7c816d9a94a0d71651821db780a0 | 2026-01-05T04:51:45.342665Z | false |
SiavashBamshadnia/Laravel-Query-Enrich | https://github.com/SiavashBamshadnia/Laravel-Query-Enrich/blob/bafb849ed83b7c816d9a94a0d71651821db780a0/workbench/app/Providers/WorkbenchServiceProvider.php | workbench/app/Providers/WorkbenchServiceProvider.php | <?php
namespace Workbench\App\Providers;
use Illuminate\Support\ServiceProvider;
class WorkbenchServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
//
}
/**
* Bootstrap services.
*/
public function boot(): void
{
//
}
}
| php | MIT | bafb849ed83b7c816d9a94a0d71651821db780a0 | 2026-01-05T04:51:45.342665Z | false |
SiavashBamshadnia/Laravel-Query-Enrich | https://github.com/SiavashBamshadnia/Laravel-Query-Enrich/blob/bafb849ed83b7c816d9a94a0d71651821db780a0/workbench/BaseTest/BaseTest.php | workbench/BaseTest/BaseTest.php | <?php
namespace Workbench\BaseTest;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\DB;
use Orchestra\Testbench\TestCase;
use function Orchestra\Testbench\workbench_path;
abstract class BaseTest extends TestCase
{
use WithFaker;
protected function getPackageProviders($app)
{
return ['sbamtr\\LaravelQueryEnrich\\QueryEnrichServiceProvider'];
}
protected function defineEnvironment($app)
{
// Setup default database to use sqlite :memory:
tap($app['config'], function (Repository $config) {
$config->set('database.connections.sqlite', [
'driver' => 'sqlite',
'database' => ':memory:',
'version' => '3.43.0',
]);
$config->set('database.connections.mysql', [
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'test',
'username' => 'root',
'password' => 'mysql',
]);
$config->set('database.connections.mariadb', [
'driver' => 'mariadb',
'host' => '127.0.0.1',
'database' => 'test',
'username' => 'root',
'password' => 'mysql',
]);
$config->set('database.connections.pgsql', [
'driver' => 'pgsql',
'host' => '127.0.0.1',
'database' => 'test',
'username' => 'postgres',
'password' => 'my_password',
]);
$config->set('database.connections.sqlsrv', [
'driver' => 'sqlsrv',
'host' => '127.0.0.1',
'database' => 'tempdb',
'username' => 'sa',
'password' => 'yourStrong(!)Password',
'trust_server_certificate' => true,
]);
$config->set('database.default', $this->getDatabaseEngine());
});
}
abstract protected function getDatabaseEngine(): string;
protected function defineDatabaseMigrations()
{
$this->loadMigrationsFrom(workbench_path('database/migrations'));
}
protected function setUp(): void
{
parent::setUp();
DB::table('books')->delete();
DB::table('authors')->delete();
}
}
| php | MIT | bafb849ed83b7c816d9a94a0d71651821db780a0 | 2026-01-05T04:51:45.342665Z | false |
SiavashBamshadnia/Laravel-Query-Enrich | https://github.com/SiavashBamshadnia/Laravel-Query-Enrich/blob/bafb849ed83b7c816d9a94a0d71651821db780a0/workbench/BaseTest/BaseProjectionTest.php | workbench/BaseTest/BaseProjectionTest.php | <?php
namespace Workbench\BaseTest;
use DateTime;
use Illuminate\Database\QueryException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use sbamtr\LaravelQueryEnrich\Date\Unit;
use sbamtr\LaravelQueryEnrich\Exception\InvalidArgumentException;
use sbamtr\LaravelQueryEnrich\QE;
use Workbench\App\Enums\BookPrice;
use Workbench\App\Models\Author;
use Workbench\App\Models\Book;
use function sbamtr\LaravelQueryEnrich\c;
abstract class BaseProjectionTest extends BaseTest
{
public function testColumn()
{
Author::insert([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$author = Author::select(
'authors.first_name',
c('first_name')->as('name')
)->first();
$actual = $author->name;
$expected = $author->first_name;
self::assertEquals($expected, $actual);
}
public function testRaw()
{
$number_1 = $this->faker->randomNumber();
$number_2 = $this->faker->randomNumber();
$queryResult = DB::selectOne(
'select '.QE::raw('?+?', [$number_1, $number_2])->as('result'),
);
$actual = $queryResult->result;
$expected = $number_1 + $number_2;
self::assertEquals($expected, $actual);
}
public function testRawWithEnumBinding()
{
$queryResult = DB::selectOne(
'select '.implode(',', [
(string) QE::raw('?', [BookPrice::CHEAP])->as('x'),
(string) QE::raw('?', [BookPrice::EXPENSIVE])->as('y'),
(string) QE::raw('?', [BookPrice::Affordable])->as('z'),
]),
);
self::assertEquals('CHEAP', $queryResult->x);
self::assertEquals('expensive', $queryResult->y);
self::assertEquals('Affordable', $queryResult->z);
}
public function testRawInvalidArgumentException()
{
self::expectException(InvalidArgumentException::class);
QE::raw('? + ?', [1]);
}
public function testCaseWhen()
{
$author = Author::query()->create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::query()->insert([
[
'title' => $this->faker->title,
'description' => null,
'author_id' => $author->id,
'price' => 150,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author->id,
'price' => 62,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author->id,
'price' => 20,
'year' => $this->faker->year,
],
]);
$books = Book::query()
->select(
QE::case()
->when(c('price'), '>', 100)->then('expensive')
->when(
QE::condition(50, '<', c('price')),
QE::condition(c('price'), '<=', 100)
)->then('moderate')
->else('affordable')
->as('price_category'),
QE::case()
->when(QE::isNull(c('description')))->then('without_description')
->else('with_description')
->as('described')
)
->get();
self::assertEquals('expensive', $books[0]->price_category);
self::assertEquals('moderate', $books[1]->price_category);
self::assertEquals('affordable', $books[2]->price_category);
self::assertEquals('without_description', $books[0]->described);
self::assertEquals('with_description', $books[1]->described);
self::assertEquals('with_description', $books[2]->described);
}
public function testCaseWhenWithEnum()
{
$author = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author->id,
'price' => 150,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author->id,
'price' => 62,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author->id,
'price' => 20,
'year' => $this->faker->year,
],
]);
$books = Book::select(
QE::case()
->when(c('price'), '>', 100)->then(BookPrice::EXPENSIVE)
->when(
QE::condition(50, '<', c('price')),
QE::condition(c('price'), '<=', 100)
)->then(BookPrice::Affordable)
->else(BookPrice::CHEAP)
->as('price_category')
)->get();
self::assertEquals('expensive', $books[0]->price_category);
self::assertEquals('Affordable', $books[1]->price_category);
self::assertEquals('CHEAP', $books[2]->price_category);
}
public function testCaseWhenWithSubQuery()
{
$author1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$author2 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$author3 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author1->id,
'price' => $this->faker->randomNumber(3),
'year' => 2020,
],
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author2->id,
'price' => $this->faker->randomNumber(3),
'year' => 2005,
],
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author3->id,
'price' => $this->faker->randomNumber(3),
'year' => 1910,
],
]);
$books = Book::select(
QE::case()
->when(c('year'), '>', 2000)->then(
Author::query()
->whereColumn('authors.id', 'books.author_id')
->select('email')
)
->else('too old')
->as('author_email')
)->get();
self::assertEquals($author1->email, $books[0]->author_email);
self::assertEquals($author2->email, $books[1]->author_email);
self::assertEquals('too old', $books[2]->author_email);
}
public function testCaseWhenInvalidArgumentException()
{
self::expectException(InvalidArgumentException::class);
QE::case()->when(1, 2, 3, 4)->then('expensive');
}
public function testIf()
{
$author = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author->id,
'price' => 150,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author->id,
'price' => 62,
'year' => $this->faker->year,
],
]);
$books = Book::select(
QE::if(QE::condition(c('price'), '>', 100), 'expensive', 'not expensive')->as('price_category')
)->get();
self::assertEquals('expensive', $books[0]->price_category);
self::assertEquals('not expensive', $books[1]->price_category);
}
public function testCoalesce()
{
$author = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
'title' => $this->faker->title,
'author_id' => $author->id,
'price' => 150,
'year' => $this->faker->year,
]);
$book = Book::select(
QE::coalesce(c('description'), '----')->as('description')
)->first();
$actualDescription = $book->description;
$expectedDescription = '----';
self::assertEquals($expectedDescription, $actualDescription);
}
public function testIsNull()
{
$author = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
[
'title' => $this->faker->title,
'author_id' => $author->id,
'price' => 150,
'year' => $this->faker->year,
'description' => null,
],
[
'title' => $this->faker->title,
'author_id' => $author->id,
'price' => 150,
'year' => $this->faker->year,
'description' => $this->faker->text,
],
]);
$books = Book::select(
QE::isNull(c('description'))->as('is_null')
)->get();
$actualIsNull = $books[0]->is_null;
self::assertEquals(true, $actualIsNull);
$actualIsNull = $books[1]->is_null;
self::assertEquals(false, $actualIsNull);
}
public function testCondition()
{
$queryResult = DB::selectOne(
'select '.
QE::condition(1, 1)->as('equal').','.
QE::condition(1, '=', 1)->as('equal_2').','.
QE::condition(2, '>', 1)->as('greater').','.
QE::condition(2, '>=', 1)->as('greater_equal').','.
QE::condition(2, '>=', 2)->as('greater_equal_2').','.
QE::condition(1, '<', 2)->as('less').','.
QE::condition(1, '<=', 2)->as('less_equal').','.
QE::condition(1, '<=', 1)->as('less_equal_2').','.
QE::condition('a', 'like', 'a')->as('like').','.
QE::condition(1, '<>', 2)->as('not_equal').','.
QE::condition(1, '!=', 2)->as('not_equal_2').','.
QE::condition('a', 'not like', 'b')->as('not_like').','.
QE::condition('b', 'in', ['a', 'b', 'c', 'd'])->as('in').','.
QE::condition('e', 'not in', ['a', 'b', 'c', 'd'])->as('not_in').','.
QE::condition(1, 'is not', null)->as('is_not').','.
QE::condition('expensive', 'in', [BookPrice::EXPENSIVE, BookPrice::CHEAP])->as('in_enums').','.
QE::condition('x', 'not in', [BookPrice::EXPENSIVE, BookPrice::CHEAP])->as('not_in_enums'),
);
self::assertEquals(1, $queryResult->equal_2);
self::assertEquals(1, $queryResult->equal);
self::assertEquals(1, $queryResult->greater);
self::assertEquals(1, $queryResult->greater_equal);
self::assertEquals(1, $queryResult->greater_equal_2);
self::assertEquals(1, $queryResult->less);
self::assertEquals(1, $queryResult->less_equal);
self::assertEquals(1, $queryResult->less_equal_2);
self::assertEquals(1, $queryResult->like);
self::assertEquals(1, $queryResult->not_equal);
self::assertEquals(1, $queryResult->not_equal_2);
self::assertEquals(1, $queryResult->not_like);
self::assertEquals(1, $queryResult->in);
self::assertEquals(1, $queryResult->not_in);
self::assertEquals(1, $queryResult->is_not);
self::assertEquals(1, $queryResult->in_enums);
self::assertEquals(1, $queryResult->not_in_enums);
}
public function testAddDate()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne('select '.
QE::addDate($datetime, 2, Unit::SECOND)->as('created_at_modified_second').','.
QE::addDate($datetime, 2, Unit::MINUTE)->as('created_at_modified_minute').','.
QE::addDate($datetime, 2, Unit::HOUR)->as('created_at_modified_hour').','.
QE::addDate($datetime, 2, Unit::DAY)->as('created_at_modified_day').','.
QE::addDate($datetime, 2, Unit::WEEK)->as('created_at_modified_week').','.
QE::addDate($datetime, 2, Unit::MONTH)->as('created_at_modified_month').','.
QE::addDate($datetime, 2, Unit::QUARTER)->as('created_at_modified_quarter').','.
QE::addDate($datetime, 2, Unit::YEAR)->as('created_at_modified_year'));
self::assertEquals(Carbon::parse($datetime)->addSeconds(2)->toDateTimeString(), $queryResult->created_at_modified_second);
self::assertEquals(Carbon::parse($datetime)->addMinutes(2)->toDateTimeString(), $queryResult->created_at_modified_minute);
self::assertEquals(Carbon::parse($datetime)->addHours(2)->toDateTimeString(), $queryResult->created_at_modified_hour);
self::assertEquals(Carbon::parse($datetime)->addDays(2)->toDateTimeString(), $queryResult->created_at_modified_day);
self::assertEquals(Carbon::parse($datetime)->addWeeks(2)->toDateTimeString(), $queryResult->created_at_modified_week);
self::assertNotFalse(DateTime::createFromFormat('Y-m-d H:i:s', $queryResult->created_at_modified_month));
self::assertNotFalse(DateTime::createFromFormat('Y-m-d H:i:s', $queryResult->created_at_modified_quarter));
self::assertNotFalse(DateTime::createFromFormat('Y-m-d H:i:s', $queryResult->created_at_modified_year));
}
public function testCurrentDate()
{
$author = DB::selectOne(
'select '.QE::currentDate()->as('d')
);
$actual = $author->d;
$expected = Carbon::now()->toDateString();
self::assertEquals($expected, $actual);
}
public function testCurrentTime()
{
$queryResult = DB::selectOne(
'select '.QE::currentTime()->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::now()->toTimeString();
$hasLessThan5SecondsDifference = Carbon::parse($actual)->diffInSeconds($expected) < 5;
self::assertTrue($hasLessThan5SecondsDifference);
}
public function testDate()
{
$datetime = $this->faker->dateTime;
$author = DB::selectOne(
'select '.QE::date($datetime)->as('result')
);
$actual = $author->result;
$expected = Carbon::parse($datetime)->toDateString();
self::assertEquals($expected, $actual);
}
public function testDateDiff()
{
$date1 = $this->faker->date;
$date2 = $this->faker->date;
$author = DB::selectOne(
'select '.QE::dateDiff($date1, $date2)->as('result')
);
$actual = $author->result;
$expected = Carbon::parse($date2)->diffInDays($date1, false);
self::assertEquals($expected, $actual);
}
public function testHour()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne(
'select '.QE::hour($datetime)->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::parse($datetime)->hour;
self::assertEquals($expected, $actual);
}
public function testMinute()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne(
'select '.QE::minute($datetime)->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::parse($datetime)->minute;
self::assertEquals($expected, $actual);
}
public function testMonth()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne(
'select '.QE::month($datetime)->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::parse($datetime)->month;
self::assertEquals($expected, $actual);
}
public function testMonthName()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne(
'select '.QE::monthName($datetime)->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::parse($datetime)->monthName;
self::assertEquals($expected, $actual);
}
public function testNow()
{
$queryResult = DB::selectOne(
'select '.QE::now()->as('result'),
);
$actual = $queryResult->result;
$expected = Carbon::now()->toDateTimeString();
$hasLessThan5SecondsDifference = Carbon::parse($actual)->diffInSeconds($expected) < 5;
self::assertTrue($hasLessThan5SecondsDifference);
}
public function testSecond()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne(
'select '.QE::second($datetime)->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::parse($datetime)->second;
self::assertEquals($expected, $actual);
}
public function testSubDate()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne('select '.
QE::subDate($datetime, 2, Unit::SECOND)->as('created_at_modified_second').','.
QE::subDate($datetime, 2, Unit::MINUTE)->as('created_at_modified_minute').','.
QE::subDate($datetime, 2, Unit::HOUR)->as('created_at_modified_hour').','.
QE::subDate($datetime, 2, Unit::DAY)->as('created_at_modified_day').','.
QE::subDate($datetime, 2, Unit::WEEK)->as('created_at_modified_week').','.
QE::subDate($datetime, 2, Unit::MONTH)->as('created_at_modified_month').','.
QE::subDate($datetime, 2, Unit::QUARTER)->as('created_at_modified_quarter').','.
QE::subDate($datetime, 2, Unit::YEAR)->as('created_at_modified_year'));
self::assertEquals(Carbon::parse($datetime)->subSeconds(2)->toDateTimeString(), $queryResult->created_at_modified_second);
self::assertEquals(Carbon::parse($datetime)->subMinutes(2)->toDateTimeString(), $queryResult->created_at_modified_minute);
self::assertEquals(Carbon::parse($datetime)->subHours(2)->toDateTimeString(), $queryResult->created_at_modified_hour);
self::assertEquals(Carbon::parse($datetime)->subDays(2)->toDateTimeString(), $queryResult->created_at_modified_day);
self::assertEquals(Carbon::parse($datetime)->subWeeks(2)->toDateTimeString(), $queryResult->created_at_modified_week);
self::assertNotFalse(DateTime::createFromFormat('Y-m-d H:i:s', $queryResult->created_at_modified_month));
self::assertNotFalse(DateTime::createFromFormat('Y-m-d H:i:s', $queryResult->created_at_modified_quarter));
self::assertNotFalse(DateTime::createFromFormat('Y-m-d H:i:s', $queryResult->created_at_modified_year));
}
public function testTime()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne(
'select '.QE::time($datetime)->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::parse($datetime)->toTimeString();
self::assertEquals($expected, $actual);
}
public function testDayOfWeek()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne(
'select '.QE::dayOfWeek($datetime)->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::parse($datetime)->dayOfWeek;
self::assertEquals($expected, $actual);
}
public function testYear()
{
$datetime = $this->faker->dateTime;
$queryResult = DB::selectOne(
'select '.QE::year($datetime)->as('result')
);
$actual = $queryResult->result;
$expected = Carbon::parse($datetime)->year;
self::assertEquals($expected, $actual);
}
public function testAbs()
{
$number_1 = $this->faker->numberBetween(-1000, 0);
$number_2 = $this->faker->numberBetween();
$queryResult = DB::selectOne('select '.
QE::abs($number_1)->as('result_1').','.
QE::abs($number_2)->as('result_2'));
$actual_1 = $queryResult->result_1;
$expected_1 = abs($number_1);
self::assertEquals($expected_1, $actual_1);
$actual_2 = $queryResult->result_2;
$expected_2 = abs($number_2);
self::assertEquals($expected_2, $actual_2);
}
public function testAcos()
{
$number = $this->faker->randomFloat(min: -1, max: 1);
$queryResult = DB::selectOne(
'select '.QE::acos($number)->as('result'),
);
$actual = $queryResult->result;
$expected = acos($number);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testAdd()
{
$number_1 = $this->faker->randomFloat();
$number_2 = $this->faker->randomFloat();
$queryResult = DB::selectOne(
'select '.QE::add($number_1, $number_2)->as('result')
);
$actual = $queryResult->result;
$expected = $number_1 + $number_2;
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testAsin()
{
$number = $this->faker->randomFloat(min: -1, max: 1);
$queryResult = DB::selectOne(
'select '.QE::asin($number)->as('result'),
);
$actual = $queryResult->result;
$expected = asin($number);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testAtan()
{
$number = $this->faker->randomFloat(min: -100, max: 100);
$queryResult = DB::selectOne(
'select '.QE::atan($number)->as('result'),
);
$actual = $queryResult->result;
$expected = atan($number);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testAtan2()
{
$y = $this->faker->randomFloat();
$x = $this->faker->randomFloat();
$queryResult = DB::selectOne(
'select '.QE::atan2($y, $x)->as('result'),
);
$actual = $queryResult->result;
$expected = atan2($y, $x);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testAvg()
{
$author_1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$author_2 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$count = $this->faker->numberBetween(2, 100);
$booksToInsert = [];
for ($i = 0; $i < $count; $i++) {
$booksToInsert[] = [
'title' => $this->faker->title,
'description' => $this->faker->text,
'price' => $this->faker->randomFloat(2, 1, 100),
'year' => $this->faker->year,
];
if ($i % 2 == 0) {
$booksToInsert[$i]['author_id'] = $author_1->id;
} else {
$booksToInsert[$i]['author_id'] = $author_2->id;
}
}
Book::insert($booksToInsert);
$books = Book::select(
QE::avg(c('price'))->as('result')
)->groupBy(
'author_id'
)->orderBy(
'author_id'
)->get();
$actual_1 = $books[0]->result;
$expected_1 = Book::where('author_id', 1)->avg('price');
self::assertEqualsWithDelta($expected_1, $actual_1, 0.001);
$actual_2 = $books[1]->result;
$expected_2 = Book::where('author_id', 2)->avg('price');
self::assertEqualsWithDelta($expected_2, $actual_2, 0.001);
}
public function testCeil()
{
$number = $this->faker->randomFloat();
$queryResult = DB::selectOne(
'select '.QE::ceil($number)->as('result')
);
$actual = $queryResult->result;
$expected = ceil($number);
self::assertEquals($expected, $actual);
}
public function testCos()
{
$number = $this->faker->randomFloat();
$queryResult = DB::selectOne(
'select '.QE::cos($number)->as('result')
);
$actual = $queryResult->result;
$expected = cos($number);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testCot()
{
$number = $this->faker->randomFloat(2, 1, 10);
$queryResult = DB::selectOne(
'select '.QE::cot($number)->as('result')
);
$actual = $queryResult->result;
$expected = 1 / tan($number);
self::assertEqualsWithDelta($expected, $actual, 0.01);
}
public function testCount()
{
$author_1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$author_2 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$count = $this->faker->numberBetween(2, 100);
$booksToInsert = [];
for ($i = 0; $i < $count; $i++) {
$booksToInsert[] = [
'title' => $this->faker->title,
'description' => $this->faker->text,
'price' => 100,
'year' => $this->faker->year,
];
if ($i % 2 == 0) {
$booksToInsert[$i]['author_id'] = $author_1->id;
} else {
$booksToInsert[$i]['author_id'] = $author_2->id;
}
}
Book::insert($booksToInsert);
$books = Book::select(
QE::count(c('author_id'))->as('result')
)->groupBy(
'author_id'
)->orderBy(
'author_id'
)->get();
$actual_1 = $books[0]->result;
$expected_1 = Book::where('author_id', 1)->count('author_id');
self::assertEquals($expected_1, $actual_1);
$actual_2 = $books[1]->result;
$expected_2 = Book::where('author_id', 2)->count('author_id');
self::assertEquals($expected_2, $actual_2);
}
public function testCountWithoutParameter()
{
$author_1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$author_2 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$count = $this->faker->numberBetween(2, 100);
$booksToInsert = [];
for ($i = 0; $i < $count; $i++) {
$booksToInsert[] = [
'title' => $this->faker->title,
'description' => $this->faker->text,
'price' => 100,
'year' => $this->faker->year,
];
if ($i % 2 == 0) {
$booksToInsert[$i]['author_id'] = $author_1->id;
} else {
$booksToInsert[$i]['author_id'] = $author_2->id;
}
}
Book::insert($booksToInsert);
$books = Book::select(
QE::count()->as('result')
)->groupBy(
'author_id'
)->orderBy(
'author_id'
)->get();
$actual_1 = $books[0]->result;
$expected_1 = Book::where('author_id', 1)->count();
self::assertEquals($expected_1, $actual_1);
$actual_2 = $books[1]->result;
$expected_2 = Book::where('author_id', 2)->count();
self::assertEquals($expected_2, $actual_2);
}
public function testRadianToDegrees()
{
$number = $this->faker->randomFloat();
$queryResult = DB::selectOne(
'select '.QE::radianToDegrees($number)->as('result')
);
$actual = $queryResult->result;
$expected = rad2deg($number);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testDivide()
{
$number_1 = $this->faker->randomFloat(2);
$number_2 = $this->faker->randomFloat(2, 1);
$queryResult = DB::selectOne(
'select '.QE::divide($number_1, $number_2)->as('result')
);
$actual = $queryResult->result;
$expected = $number_1 / $number_2;
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testExp()
{
$number = $this->faker->randomFloat(max: 10);
$queryResult = DB::selectOne(
'select '.QE::exp($number)->as('result')
);
$actual = $queryResult->result;
$expected = exp($number);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testFloor()
{
$number = $this->faker->randomFloat();
$queryResult = DB::selectOne(
'select '.QE::floor($number)->as('result')
);
$actual = $queryResult->result;
$expected = floor($number);
self::assertEquals($expected, $actual);
}
public function testGreatest()
{
$array = [];
$count = $this->faker->numberBetween(2, 100);
for ($i = 0; $i < $count; $i++) {
$array[] = $this->faker->randomFloat();
}
$queryResult = DB::selectOne(
'select '.QE::greatest(...$array)->as('result')
);
$actual = $queryResult->result;
$expected = max($array);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testLeast()
{
$array = [];
$count = $this->faker->numberBetween(2, 100);
for ($i = 0; $i < $count; $i++) {
$array[] = $this->faker->randomFloat();
}
$queryResult = DB::selectOne(
'select '.QE::least(...$array)->as('result')
);
$actual = $queryResult->result;
$expected = min($array);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testLn()
{
$number = $this->faker->randomFloat(min: 1);
$queryResult = DB::selectOne(
'select '.QE::ln($number)->as('result')
);
$actual = $queryResult->result;
$expected = log($number);
self::assertEqualsWithDelta($expected, $actual, 0.001);
}
public function testLog()
{
$number = $this->faker->numberBetween(2, 1000);
$base = $this->faker->numberBetween(2, 1000);
| php | MIT | bafb849ed83b7c816d9a94a0d71651821db780a0 | 2026-01-05T04:51:45.342665Z | true |
SiavashBamshadnia/Laravel-Query-Enrich | https://github.com/SiavashBamshadnia/Laravel-Query-Enrich/blob/bafb849ed83b7c816d9a94a0d71651821db780a0/workbench/BaseTest/BaseWhereClauseTest.php | workbench/BaseTest/BaseWhereClauseTest.php | <?php
namespace Workbench\BaseTest;
use Illuminate\Support\Facades\DB;
use sbamtr\LaravelQueryEnrich\Exception\InvalidArgumentException;
use sbamtr\LaravelQueryEnrich\QE;
use Workbench\App\Models\Author;
use Workbench\App\Models\Book;
use function sbamtr\LaravelQueryEnrich\c;
abstract class BaseWhereClauseTest extends BaseTest
{
public function testCondition()
{
$expected = Book::where('year', '>', 2000)->toRawSql();
$actual = Book::whereRaw(
QE::condition(c('year'), '>', 2000)
)->toRawSql();
self::assertEquals($expected, $actual);
self::expectException(InvalidArgumentException::class);
QE::condition(1, 'invalid operator', 2);
}
public function testConditionInvalidArgumentException()
{
self::expectException(InvalidArgumentException::class);
QE::condition(1, 'invalid operator', 2);
}
public function testExists()
{
$author_1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$author_2 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert(
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author_2->id,
'price' => 150,
'year' => $this->faker->year,
],
);
$queryResult = DB::table('books')->select(
'author_id',
)->whereRaw(
QE::exists(
Db::table('authors')->where('authors.id', c('books.author_id'))
)
)->get();
self::assertEquals(1, count($queryResult));
$actual_1 = $queryResult[0]->author_id;
$expected_1 = $author_2->id;
self::assertEquals($expected_1, $actual_1);
}
public function testIsNull()
{
$author_1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author_1->id,
'price' => 150,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => null,
'author_id' => $author_1->id,
'price' => 150,
'year' => $this->faker->year,
],
]);
$queryResult = DB::table('books')->whereRaw(
QE::isNull(c('description'))
)->count();
$actual_1 = $queryResult;
$expected_1 = 1;
self::assertEquals($expected_1, $actual_1);
}
public function testAnd()
{
$author_1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author_1->id,
'price' => 50,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => null,
'author_id' => $author_1->id,
'price' => 150,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => null,
'author_id' => $author_1->id,
'price' => 250,
'year' => $this->faker->year,
],
]);
$queryResult = DB::table('books')->whereRaw(
QE::and(
QE::condition(c('price'), '>', 100),
QE::condition(c('price'), '<', 200),
)
)->get();
$actual_1 = count($queryResult);
$expected_1 = 1;
self::assertEquals($expected_1, $actual_1);
$actual_2 = $queryResult[0]->price;
$expected_2 = 150;
self::assertEquals($expected_2, $actual_2);
}
public function testOr()
{
$author_1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author_1->id,
'price' => 50,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => null,
'author_id' => $author_1->id,
'price' => 150,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => null,
'author_id' => $author_1->id,
'price' => 250,
'year' => $this->faker->year,
],
]);
$queryResult = DB::table('books')->whereRaw(
QE::or(
QE::condition(c('price'), 150),
QE::condition(c('price'), 250),
)
)->get();
$actual_1 = count($queryResult);
$expected_1 = 2;
self::assertEquals($expected_1, $actual_1);
$actual_2 = $queryResult[0]->price;
$expected_2 = 150;
$actual_3 = $queryResult[1]->price;
$expected_3 = 250;
self::assertEquals($expected_2, $actual_2);
self::assertEquals($expected_3, $actual_3);
}
public function testNot()
{
$author_1 = Author::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
Book::insert([
[
'title' => $this->faker->title,
'description' => $this->faker->text,
'author_id' => $author_1->id,
'price' => 50,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => null,
'author_id' => $author_1->id,
'price' => 150,
'year' => $this->faker->year,
],
[
'title' => $this->faker->title,
'description' => null,
'author_id' => $author_1->id,
'price' => 250,
'year' => $this->faker->year,
],
]);
$queryResult = DB::table('books')->whereRaw(
QE::not(
QE::condition(c('price'), 150),
)
)->get();
$actual_1 = count($queryResult);
$expected_1 = 2;
self::assertEquals($expected_1, $actual_1);
$actual_2 = $queryResult[0]->price;
$expected_2 = 50;
$actual_3 = $queryResult[1]->price;
$expected_3 = 250;
self::assertEquals($expected_2, $actual_2);
self::assertEquals($expected_3, $actual_3);
}
public function testStartsWith()
{
Author::insert([
[
'first_name' => 'Walter',
'last_name' => 'White',
'email' => 'info@example.com',
],
[
'first_name' => 'Walt',
'last_name' => 'White',
'email' => 'info2@example.com',
],
[
'first_name' => 'Skyler',
'last_name' => 'White',
'email' => 'info3@example.com',
],
]);
$queryResult = DB::table('authors')->whereRaw(
QE::startsWith(c('first_name'), 'Walt')
)->get();
self::assertEquals(2, count($queryResult));
self::assertEquals('Walter', $queryResult[0]->first_name);
self::assertEquals('Walt', $queryResult[1]->first_name);
}
public function testEndsWith()
{
Author::insert([
[
'first_name' => 'Sandor',
'last_name' => 'Clegane',
'email' => 'info@example.com',
],
[
'first_name' => 'Gregor',
'last_name' => 'Clegane',
'email' => 'info2@example.com',
],
[
'first_name' => 'Gared',
'last_name' => 'Clegane',
'email' => 'info3@example.com',
],
]);
$queryResult = DB::table('authors')->whereRaw(
QE::endsWith(c('first_name'), 'or')
)->get();
self::assertEquals(2, count($queryResult));
self::assertEquals('Sandor', $queryResult[0]->first_name);
self::assertEquals('Gregor', $queryResult[1]->first_name);
}
public function testContains()
{
Author::insert([
[
'first_name' => 'Sandor',
'last_name' => 'Clegane',
'email' => 'info@example.com',
],
[
'first_name' => 'Gregor',
'last_name' => 'Clegane',
'email' => 'info2@example.com',
],
[
'first_name' => 'Gared',
'last_name' => 'Clegane',
'email' => 'info3@example.com',
],
]);
$queryResult = DB::table('authors')->whereRaw(
QE::contains(c('first_name'), 'o')
)->get();
self::assertEquals(2, count($queryResult));
self::assertEquals('Sandor', $queryResult[0]->first_name);
self::assertEquals('Gregor', $queryResult[1]->first_name);
}
}
| php | MIT | bafb849ed83b7c816d9a94a0d71651821db780a0 | 2026-01-05T04:51:45.342665Z | false |
SiavashBamshadnia/Laravel-Query-Enrich | https://github.com/SiavashBamshadnia/Laravel-Query-Enrich/blob/bafb849ed83b7c816d9a94a0d71651821db780a0/workbench/BaseTest/BaseBasicFunctionsTest.php | workbench/BaseTest/BaseBasicFunctionsTest.php | <?php
namespace Workbench\BaseTest;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use sbamtr\LaravelQueryEnrich\QE;
use Workbench\App\Models\Author;
use function sbamtr\LaravelQueryEnrich\c;
abstract class BaseBasicFunctionsTest extends BaseTest
{
public function testEscapeCondition()
{
Author::insert([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
]);
$queryResult = Author::whereRaw(
QE::condition(c('first_name'), 'like', '%%')
)->count();
self::assertEquals(0, $queryResult);
}
public function testEscapeDatetime()
{
$datetime = Carbon::parse($this->faker->dateTime)->toDateTimeString();
$queryResult = DB::selectOne('SELECT '.QE::raw('?', [$datetime])->as('result'));
self::assertEquals($datetime, $queryResult->result);
}
public function testEscapeNull()
{
$queryResult = DB::selectOne('SELECT '.QE::raw('?', [null])->as('result'));
self::assertNull($queryResult->result);
}
}
| php | MIT | bafb849ed83b7c816d9a94a0d71651821db780a0 | 2026-01-05T04:51:45.342665Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.