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
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Exceptions/SettingNotSelectedException.php
src/Exceptions/SettingNotSelectedException.php
<?php namespace Sajadsdi\LaravelSettingPro\Exceptions; class SettingNotSelectedException extends \Exception { public function __construct($operation = "") { parent::__construct("Please select setting name in '{$operation}' operation."); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Exceptions/SettingNotFoundException.php
src/Exceptions/SettingNotFoundException.php
<?php namespace Sajadsdi\LaravelSettingPro\Exceptions; class SettingNotFoundException extends \Exception { public function __construct($setting) { parent::__construct("We can't find '{$setting}' setting from store!"); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Exceptions/SettingKeyNotFoundException.php
src/Exceptions/SettingKeyNotFoundException.php
<?php namespace Sajadsdi\LaravelSettingPro\Exceptions; class SettingKeyNotFoundException extends \Exception { public function __construct(public $key, public $keysPath, public $settingName) { parent::__construct("We can't find '{$this->key}' key" . ($this->keysPath ? " in '{$this->keysPath}*' path" : "") . " from '{$this->settingName}' setting ."); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Exceptions/DatabaseConnectionException.php
src/Exceptions/DatabaseConnectionException.php
<?php namespace Sajadsdi\LaravelSettingPro\Exceptions; class DatabaseConnectionException extends \Exception { public function __construct(string $database ,string $error) { parent::__construct("Failed to connect to $database database: \n" . $error); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Drivers/Database.php
src/Drivers/Database.php
<?php namespace Sajadsdi\LaravelSettingPro\Drivers; use Sajadsdi\LaravelSettingPro\Contracts\DatabaseDriverInterface; use Sajadsdi\LaravelSettingPro\Contracts\StoreDriverInterface; class Database implements StoreDriverInterface { private DatabaseDriverInterface $driver; /** * @param array $config */ public function __construct(array $config) { $this->driver = new $config['connections'][$config['connection']]['class']($config['connections'][$config['connection']]); } /** * Get database setting with key. * @param string $key * @return mixed */ public function get(string $key): mixed { return $this->driver->getSetting($key); } /** * Update database setting with key and data. * @param string $key * @param mixed $data * @return void */ public function set(string $key, mixed $data): void { $this->driver->setSetting($key, $data); } /** * Delete setting row with key. * @param string $key * @return void */ public function delete(string $key): void { $this->driver->deleteSetting($key); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Drivers/File.php
src/Drivers/File.php
<?php namespace Sajadsdi\LaravelSettingPro\Drivers; use Sajadsdi\LaravelSettingPro\Contracts\StoreDriverInterface; class File implements StoreDriverInterface { private array $config; private const DS = DIRECTORY_SEPARATOR; /** * @param array $config */ public function __construct(array $config) { $this->config = $config; $this->config['path'] = realpath(str_replace(['/', '\\'], self::DS, $this->config['path'])); } /** * Get setting file with key name. * @param string $key * @return mixed */ public function get(string $key): mixed { $data = null; $file = $this->config['path'] . self::DS . $key . '.php'; if (file_exists($file)) { $data = require $file; } return $data; } /** * Update setting file with key name and data. * @param string $key * @param mixed $data * @return void */ public function set(string $key, mixed $data): void { file_put_contents($this->config['path'] . self::DS . $key . '.php', str_replace([": ", " {", " }", "\n}"], [" => ", " [", " ]", "\n]"], "<?php\n//This file updated in " . date(DATE_ATOM) . "\nreturn " . json_encode($data, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ';')); } /** * Delete setting file with key name. * @param string $key * @return void */ public function delete(string $key): void { $file = $this->config['path'] . self::DS . $key . '.php'; if (file_exists($file)) { unlink($file); } } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Drivers/Database/Mysql.php
src/Drivers/Database/Mysql.php
<?php namespace Sajadsdi\LaravelSettingPro\Drivers\Database; use PDO; use PDOException; use Sajadsdi\LaravelSettingPro\Contracts\DatabaseDriverInterface; use Sajadsdi\LaravelSettingPro\Exceptions\DatabaseConnectionException; class Mysql implements DatabaseDriverInterface { private PDO $connection; private string $table = 'settings'; private string $prefix; /** * Retrieves the value of a setting based on the provided key. * * @param string $key The key of the setting. * @return mixed|null The value of the setting, or null if not found. */ public function getSetting(string $key): mixed { $setting = $this->get($key); return $setting ? json_decode($setting['data'], true) : null; } /** * Sets the value of a setting based on the provided key. * * @param string $key The key of the setting. * @param mixed $data The value to be set for the setting. * @return void */ public function setSetting(string $key, mixed $data): void { $setting = $this->get($key); if ($setting) { $this->set($key, $data); } else { $this->insert($key, $data); } } /** * Delete a setting row with key. * @param string $key * @return void */ public function deleteSetting(string $key): void { $query = $this->connection->prepare("DELETE FROM {$this->table()} WHERE setting = ?"); $query->execute([$key]); } /** * @throws DatabaseConnectionException */ public function __construct(array $config) { $this->prefix = $config['prefix']; $this->setConnection($config); } /** * This method return a full name of setting table. * @return string */ private function table(): string { return $this->prefix ? $this->prefix . '_' . $this->table : $this->table; } /** * Create a PDO connection. * @param $config * @return void * @throws DatabaseConnectionException */ private function setConnection($config): void { try { $dsn = $config['driver'] . ":host=" . $config['host'] . ";port=" . $config['port'] . ";dbname=" . $config['database'] . ";charset=".$config['charset']; $this->connection = new PDO($dsn, $config['username'], $config['password']); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { throw new DatabaseConnectionException('MySQL', $e->getMessage()); } } /** * Get query to retrieve a setting row with key. * @param string $key * @return mixed */ private function get(string $key): mixed { $query = $this->connection->prepare("SELECT * FROM {$this->table()} WHERE setting = ?"); $query->execute([$key]); return $query->fetch(PDO::FETCH_ASSOC); } /** * Update query for set a setting with key and data. * @param string $key * @param mixed $data * @return void */ private function set(string $key, mixed $data): void { $query = $this->connection->prepare("UPDATE {$this->table()} SET updated_at = ? , data = ? WHERE setting = ?"); $query->execute([date('Y-m-d H:i:s'), json_encode($data, JSON_NUMERIC_CHECK | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $key]); } /** * Insert a row in setting table with key and data. * @param string $key * @param mixed $data * @return void */ private function insert(string $key, mixed $data): void { $query = $this->connection->prepare("INSERT INTO {$this->table()} (setting,data,created_at,updated_at) VALUES (?,?,?,?)"); $date = date('Y-m-d H:i:s'); $query->execute([$key, json_encode($data, JSON_NUMERIC_CHECK | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $date, $date]); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Drivers/Database/MongoDB.php
src/Drivers/Database/MongoDB.php
<?php namespace Sajadsdi\LaravelSettingPro\Drivers\Database; use MongoDB\BSON\UTCDateTime; use MongoDB\Client; use MongoDB\Collection; use Sajadsdi\LaravelSettingPro\Contracts\DatabaseDriverInterface; use Sajadsdi\LaravelSettingPro\Exceptions\DatabaseConnectionException; class MongoDB implements DatabaseDriverInterface { private Collection $connection; private string $collection = 'settings'; /** * Retrieves the value of a setting based on the provided key. * * @param string $key The key of the setting. * @return mixed|null The value of the setting, or null if not found. */ public function getSetting(string $key): mixed { $setting = $this->get($key); return $setting ? $setting['data'] : null; } /** * Update the value of a setting based on the provided key. * * @param string $key The key of the setting. * @param mixed $data The value to be set for the setting. * @return void */ public function setSetting(string $key, mixed $data): void { $setting = $this->get($key); if ($setting) { $this->set($key, $data); } else { $this->insert($key, $data); } } /** * Delete a setting document with key. * @param string $key * @return void */ public function deleteSetting(string $key): void { $this->connection->deleteOne(['setting' => $key]); } /** * @throws DatabaseConnectionException */ public function __construct(array $config) { $this->setConnection($config); } /** * Create connection to MongoDB database. * @param $config * @return void * @throws DatabaseConnectionException */ private function setConnection($config): void { try { $uri = "mongodb://{$config['host']}:{$config['port']}"; if ($config['username'] && $config['password']) { $uri = "mongodb://{$config['username']}:{$config['password']}@{$config['host']}:{$config['port']}/{$config['database']}"; } $client = new Client($uri, $config['options']); // The selectDatabase method is lazy and won't immediately cause a connection $database = $client->selectDatabase($config['database']); $collection = $database->selectCollection($this->collection); // The following line triggers an actual connection and will throw a ConnectionException if it fails $database->listCollections(); $this->connection = $collection; } catch (\Exception $e) { throw new DatabaseConnectionException('MongoDB', $e->getMessage()); } } /** * get setting document with key. * @param string $key * @return array|object|null */ private function get(string $key): array|null|object { return $this->connection->findOne(['setting', $key]); } /** * Update a setting document with key and data. * @param string $key * @param mixed $data * @return void */ private function set(string $key, mixed $data): void { $date = new UTCDateTime((new \DateTime())->getTimestamp() * 1000); $document = ['data' => $data, 'updated_at' => $date]; $this->connection->updateOne( ['setting' => $key], ['$set' => $document], ['upsert' => true] ); } /** * Insert a document with key and data. * @param string $key * @param mixed $data * @return void */ private function insert(string $key, mixed $data): void { $date = new UTCDateTime((new \DateTime())->getTimestamp() * 1000); $document = [ 'setting' => $key, 'data' => $data, 'created_at' => $date, 'updated_at' => $date ]; $this->connection->insertOne($document); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Support/helpers.php
src/Support/helpers.php
<?php use Sajadsdi\LaravelSettingPro\Support\Setting; if (!function_exists('setting')) { /** * Get or set values in the LaravelSettingPro package. * * @param string $settingName The name of the setting to retrieve or set. * @param mixed $key The key of the value to retrieve or set. * @param mixed $default The default value to return if the key does not exist. * @param bool $throw flag to disable 'NotFound' exceptions. * @return mixed|Setting Returns a Setting instance if no arguments are provided, otherwise returns the value of the specified key. */ function setting(string $settingName = '', mixed $key = [], mixed $default = null, bool $throw = true): mixed { if (!$settingName) { return Setting::Obj(); } if ($key) { return Setting::Obj()->select($settingName)->get($key, $default); } return Setting::Obj()->select($settingName); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Support/Setting.php
src/Support/Setting.php
<?php namespace Sajadsdi\LaravelSettingPro\Support; use Sajadsdi\ArrayDotNotation\Exceptions\ArrayKeyNotFoundException; use Sajadsdi\LaravelSettingPro\Exceptions\SettingKeyNotFoundException; use Sajadsdi\LaravelSettingPro\Exceptions\SettingNotFoundException; use Sajadsdi\LaravelSettingPro\Exceptions\SettingNotSelectedException; use Sajadsdi\LaravelSettingPro\LaravelSettingPro; use Sajadsdi\LaravelSettingPro\Services\SettingStore; /** * @method select(string $settingName) */ class Setting { private static self $obj; private string $select = ''; private LaravelSettingPro $setting; /** * Create a new Setting instance. * * @param LaravelSettingPro $setting */ public function __construct(LaravelSettingPro $setting) { $this->setting = $setting; self::$obj = $this; } /** * Handle dynamic static method calls. * * @param string $name * @param array $arguments * @return mixed * @throws SettingKeyNotFoundException * @throws SettingNotFoundException * @throws SettingNotSelectedException */ public static function __callStatic(string $name, array $arguments) { if (strtolower($name) == 'select') { return self::Obj()->selectSetting(...$arguments); } elseif ($arguments) { return self::Obj()->setting->get($name, ...$arguments); } else { return self::Obj()->selectSetting($name); } } /** * Handle dynamic method calls. * * @param string $name * @param array $arguments * @return mixed * * @throws SettingKeyNotFoundException * @throws SettingNotFoundException * @throws SettingNotSelectedException */ public function __call(string $name, array $arguments) { if (strtolower($name) == 'select') { return $this->selectSetting(...$arguments); } elseif ($arguments) { return $this->setting->get($name, ...$arguments); } else { return $this->selectSetting($name); } } /** * Get values of keys on selected setting. * * @param mixed $keys Keys to access values in the setting. * @param mixed|null $default Default value to return if the setting or key is not found. * @param bool $throw flag to disable 'NotFound' exceptions * @return mixed * * @throws SettingKeyNotFoundException * @throws SettingNotFoundException * @throws SettingNotSelectedException */ public function get(mixed $keys = [], mixed $default = null, bool $throw = true): mixed { return $this->setting->get($this->getSelect(), $keys, $default, $throw); } /** * Set values of keys on selected setting. * * @param mixed $key * @param mixed $value * @return void * @throws SettingNotSelectedException */ public function set(mixed $key, mixed $value = []): void { if ($key) { if (is_string($key) && $value) { $this->setting->set($this->getSelect(), [$key => $value]); } elseif (is_array($key)) { $this->setting->set($this->getSelect(), $key); } } } /** * delete keys of the selected setting. * * @param mixed $keys * @return void * @throws SettingNotSelectedException * @throws ArrayKeyNotFoundException */ public function delete(mixed $keys = []): void { $this->setting->delete($this->getSelect(), $keys); } /** * @param mixed $keys * @return bool * * @throws SettingNotSelectedException */ public function has(mixed $keys = []): bool { return $this->setting->has($this->getSelect(), $keys); } /** * Select a setting to work with. * * @param string $setting * @return Setting */ private function selectSetting(string $setting = ''): Setting { $this->select = $setting; return $this; } /** * Get the currently selected setting. * * @return string */ private function getSelect(): string { $select = $this->select; $this->selectSetting(); return $select; } /** * Get the instance of the Setting class. * * @return Setting */ public static function Obj(): Setting { if (!isset(self::$obj)) { //this added for resolve conflict with laravel bootstrap configuration $config = require base_path('config') . DIRECTORY_SEPARATOR . "_setting.php"; new Setting(new LaravelSettingPro($config, new SettingStore($config))); } return self::$obj; } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Services/SettingStore.php
src/Services/SettingStore.php
<?php namespace Sajadsdi\LaravelSettingPro\Services; use Sajadsdi\LaravelSettingPro\Contracts\CacheDriverInterface; use Sajadsdi\LaravelSettingPro\Contracts\StoreDriverInterface; class SettingStore { private array $drivers = []; private array $config; private CacheDriverInterface $cache; /** * SettingStore constructor. */ public function __construct(array $config) { $this->config = $config; if ($this->cacheEnabled()) { $this->setCache(new $this->config['cache']['class']($this->config['cache'])); } } /** * Get the value of a setting. * * @param string $name * @return mixed */ public function get(string $name): mixed { $data = null; if ($this->cacheEnabled()) { $data = $this->cache->get($name); } if ($data === null) { $data = $this->getSetting($name); if ($this->cacheEnabled() && $data !== null) { $this->cache->set($name, $data); } } return $data; } /** * Get the value of a setting from the appropriate driver. * * @param string $name * @return mixed */ public function getSetting(string $name): mixed { $data = $this->getDriver($this->config['store']['default'])->get($name); if ($data === null) { if ($this->config['store']['import_from']) { $data = $this->getDriver($this->config['store']['import_from'])->get($name); if ($data) { $this->getDriver($this->config['store']['default'])->set($name, $data); } } } return $data; } /** * Set the value of a setting. * * @param string $name * @param mixed $data * @return void */ public function set(string $name, mixed $data): void { $this->getDriver($this->config['store']['default'])->set($name, $data); } /** * delete a setting. * * @param string $name * @return void */ public function delete(string $name): void { $this->getDriver($this->config['store']['default'])->delete($name); } /** * Check if caching is enabled. * * @return bool */ private function cacheEnabled(): bool { return $this->config['cache']['enabled']; } /** * Get the driver instance for the given name. * * @param string $name * @return StoreDriverInterface */ private function getDriver(string $name): StoreDriverInterface { if (!isset($this->drivers[$name])) { $this->setDriver($name, new $this->config['store']['drivers'][$name]['class']($this->config['store']['drivers'][$name])); } return $this->drivers[$name]; } /** * Set the driver instance for the given name. * * @param string $name * @param StoreDriverInterface $class * @return void */ private function setDriver(string $name, StoreDriverInterface $class) { $this->drivers[$name] = $class; } /** * Set the cache instance. * * @param CacheDriverInterface $cacheDriver * @return void */ private function setCache(CacheDriverInterface $cacheDriver): void { $this->cache = $cacheDriver; } /** * Get the cache instance. * * @return CacheDriverInterface */ public function cache(): CacheDriverInterface { return $this->cache; } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Contracts/StoreDriverInterface.php
src/Contracts/StoreDriverInterface.php
<?php namespace Sajadsdi\LaravelSettingPro\Contracts; interface StoreDriverInterface { public function __construct(array $config); public function get(string $key): mixed; public function set(string $key, mixed $data): void; public function delete(string $key): void; }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Contracts/CacheDriverInterface.php
src/Contracts/CacheDriverInterface.php
<?php namespace Sajadsdi\LaravelSettingPro\Contracts; interface CacheDriverInterface { public function __construct(array $config); public function get(string $key): mixed; public function set(string $key, mixed $data): void; public function clear(string $key): void; public function clearAll(): void; }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Contracts/DatabaseDriverInterface.php
src/Contracts/DatabaseDriverInterface.php
<?php namespace Sajadsdi\LaravelSettingPro\Contracts; interface DatabaseDriverInterface { public function getSetting(string $key): mixed; public function setSetting(string $key, mixed $data): void; public function deleteSetting(string $key): void; }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Cache/Cache.php
src/Cache/Cache.php
<?php namespace Sajadsdi\LaravelSettingPro\Cache; use Sajadsdi\LaravelSettingPro\Contracts\CacheDriverInterface; class Cache implements CacheDriverInterface { private CacheDriverInterface $driver; /** * @param array $config */ public function __construct(array $config) { $this->driver = new $config['drivers'][$config['default']]['class']($config['drivers'][$config['default']]); } /** * Get cache from driver with key. * @param $key * @return mixed */ public function get($key): mixed { return $this->driver->get($key); } /** * Set cache on driver with key and data. * @param string $key * @param mixed $data * @return void */ public function set(string $key, mixed $data): void { $this->driver->set($key, $data); } /** * Clear cache from driver with key. * @param $key * @return void */ public function clear($key): void { $this->driver->clear($key); } /** * Clear all caches from driver. * @return void */ public function clearAll(): void { $this->driver->clearAll(); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Cache/Drivers/Redis.php
src/Cache/Drivers/Redis.php
<?php namespace Sajadsdi\LaravelSettingPro\Cache\Drivers; use Sajadsdi\LaravelSettingPro\Contracts\CacheDriverInterface; use Predis\Client as RedisClient; class Redis implements CacheDriverInterface { private RedisClient $client; /** * @param array $config */ public function __construct(array $config) { $this->client = new RedisClient($config['connection'],$config['options']); } /** * Get cache from redis database with key. * @param string $key * @return mixed */ public function get(string $key): mixed { $value = $this->client->get($key); return $value ? unserialize($value) : null; } /** * Set Cache on redis database with key and data. * @param string $key * @param mixed $data * @return void */ public function set(string $key, mixed $data): void { $this->client->set($key, serialize($data)); } /** * Delete a cache with key. * @param string $key * @return void */ public function clear(string $key): void { $this->client->del([$key]); } /** * Delete all keys from selected redis database. * @return void */ public function clearAll(): void { $this->client->flushdb(); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Cache/Drivers/File.php
src/Cache/Drivers/File.php
<?php namespace Sajadsdi\LaravelSettingPro\Cache\Drivers; use Sajadsdi\LaravelSettingPro\Contracts\CacheDriverInterface; class File implements CacheDriverInterface { private string $path; /** * @param array $config */ public function __construct(array $config) { $this->path = realpath($config['path']); if(!is_dir($this->path)){ mkdir($this->path,0777,true); } } /** * Get cache file with key. * @param string $key * @return mixed */ public function get(string $key): mixed { if (file_exists($file = $this->getFile($key))) { return unserialize(file_get_contents($file)); } return null; } /** * Set cache file with key and data. * @param string $key * @param mixed $data * @return void */ public function set(string $key, mixed $data): void { file_put_contents($this->getFile($key), serialize($data)); } /** * Delete a cache file with key. * @param $key * @return void */ public function clear($key): void { if (file_exists($file = $this->getFile($key))) { unlink($file); } } /** * Get cache file path. * @param string $key * @return string */ private function getFile(string $key): string { return $this->path . DIRECTORY_SEPARATOR . md5($key); } /** * Delete setting cache directory and create again. * @return void */ public function clearAll(): void { $files = scandir($this->path); foreach ($files as $file) { if($file != '.' && $file != '..') { unlink($this->path . DIRECTORY_SEPARATOR . $file); } } } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Console/InstallCommand.php
src/Console/InstallCommand.php
<?php namespace Sajadsdi\LaravelSettingPro\Console; use Illuminate\Console\Command; class InstallCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'setting:install'; /** * The console command description. * * @var string */ protected $description = 'Install Laravel Setting Pro!'; /** * Execute the console command. * * @return int|null */ public function handle() { $this->info('Installing Laravel Setting Pro ...'); $this->installMigrations(); $config = config('_setting'); $this->installSettingDirectory($config); $this->info('Installation completed !'); $this->installTestSetting($config); $this->testSetting(); return null; } private function installSettingDirectory($config) { $this->comment('Creating setting directory ...'); if (is_dir($config['store']['drivers']['file']['path'])) { $this->warn('setting directory is exists ............ SKIPPED'); } else { mkdir($config['store']['drivers']['file']['path'], 0775); $this->info($config['store']['drivers']['file']['path'] . ' directory created ...... DONE'); } } private function installTestSetting($config) { $this->comment('Creating test setting ...'); if (file_exists($config['store']['drivers']['file']['path'] . DIRECTORY_SEPARATOR . 'test.php')) { $this->warn('test.php is exists in setting directory ............ SKIPPED'); } else { file_put_contents($config['store']['drivers']['file']['path'] . DIRECTORY_SEPARATOR . 'test.php', file_get_contents(__DIR__ . "/../../tests/setting/test.php") ); $this->info($config['store']['drivers']['file']['path'] . DIRECTORY_SEPARATOR . 'test.php created ....... DONE'); } } private function installMigrations() { $this->comment('Migrating ...'); $this->call('migrate', ['--path' => "database/migrations/2023_11_03_030451_create_settings_table.php"]); } private function testSetting() { $this->comment("testing ..."); $this->alert(setting('test', 'welcome') . " Ver:" . setting('test', 'version')); $this->comment("nested key testing for 'users.5.profile.address' from test setting ..."); $this->alert('address is: ' . setting('test', 'users.5.profile.address')); $this->comment("removing 'users.5.profile.address' key from test setting ..."); setting('test')->delete('users.5.profile.address'); $has = setting('test')->has('users.5.profile.address'); $this->comment("testing has for deleted key (users.5.profile.address) ..."); $this->alert($has ? "not deleted !" : "deleted successfully !"); $this->comment("set deleted key again. setting 'test value set!' value on 'users.5.profile.address' key ..."); setting('test')->set(['users.5.profile.address' => 'test value set!']); $this->alert('new address is: ' . setting('test', 'users.5.profile.address')); $this->comment("testing finished !"); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Console/ClearCacheCommand.php
src/Console/ClearCacheCommand.php
<?php namespace Sajadsdi\LaravelSettingPro\Console; use Illuminate\Console\Command; use Sajadsdi\LaravelSettingPro\Services\SettingStore; class ClearCacheCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'setting:clear-cache'; /** * The console command description. * * @var string */ protected $description = 'Clear Setting Caches!'; /** * Execute the console command. * * @return null */ public function handle(SettingStore $store) { $this->info('Clearing Setting Caches ...'); if(config('_setting.cache.enabled')) { $store->cache()->clearAll(); $this->info('Caches Cleared !'); }else{ $this->info('Setting cache not enabled. Clear skipped !'); } return null; } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Console/PublishMongoDBCommand.php
src/Console/PublishMongoDBCommand.php
<?php namespace Sajadsdi\LaravelSettingPro\Console; use Illuminate\Console\Command; class PublishMongoDBCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'setting:publish-mongodb'; /** * The console command description. * * @var string */ protected $description = 'Publish Laravel Setting Pro migration for MongoDB!'; /** * Execute the console command. * * @return int|null */ public function handle() { $this->info('Publishing Laravel Setting Pro ...'); $this->publish(); return null; } private function publish() { $this->comment('Publishing migration for mongoDB...'); $this->call('vendor:publish', ['--tag' => "laravel-setting-pro--mongodb-migration"]); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Console/PublishCommand.php
src/Console/PublishCommand.php
<?php namespace Sajadsdi\LaravelSettingPro\Console; use Illuminate\Console\Command; class PublishCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'setting:publish'; /** * The console command description. * * @var string */ protected $description = 'Publish Laravel Setting Pro configure and migration!'; /** * Execute the console command. * * @return int|null */ public function handle() { $this->info('Publishing Laravel Setting Pro ...'); $this->publish(); return null; } private function publish() { $this->comment('Publishing configure ...'); $this->call('vendor:publish', ['--tag' => "laravel-setting-pro-configure"]); $this->comment('Publishing migration ...'); $this->call('vendor:publish', ['--tag' => "laravel-setting-pro-migration"]); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Concerns/GetCallbacksTrait.php
src/Concerns/GetCallbacksTrait.php
<?php namespace Sajadsdi\LaravelSettingPro\Concerns; use Closure; trait GetCallbacksTrait { /** * Get a callback function for default value operation. * * @param string $setting Name of the setting. * @return Closure Callback function. */ private function getCallbackDefaultValueOperation(string $setting): Closure { $class = $this; return function ($default, $key) use ($class, $setting) { $class->set($setting, [$key => $default]); }; } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Concerns/SetCallbacksTrait.php
src/Concerns/SetCallbacksTrait.php
<?php namespace Sajadsdi\LaravelSettingPro\Concerns; use Closure; trait SetCallbacksTrait { /** * Get a callback function for set operation. * * @param string $setting Name of the setting. * @return Closure Callback function. */ private function getCallbackSetOperation(string $setting): Closure { $class = $this; return function ($value, $key) use ($class, $setting) { $class->addToSet($setting, [$key => $value]); }; } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Concerns/ProcessTrait.php
src/Concerns/ProcessTrait.php
<?php namespace Sajadsdi\LaravelSettingPro\Concerns; use Sajadsdi\LaravelSettingPro\Jobs\DeleteSettingJob; use Sajadsdi\LaravelSettingPro\Jobs\UpdateSettingJob; trait ProcessTrait { private array $sets = []; private array $deletes = []; /** * Add key-value pairs to the set of changes to be saved. * * @param string $setting Name of the setting to add the key-value pairs to. * @param array $keyValue Key-value pairs to add to the set. * @return void */ private function addToSet(string $setting, array $keyValue): void { $this->sets[$setting] = array_merge($this->sets[$setting] ?? [], $keyValue); } /** * remove pairs to the set of changes to be saved. * * @param string $settingName * @return void */ private function removeFromSet(string $settingName): void { unset($this->sets[$settingName]); } /** * Add keys pairs to the delete operations. * * @param string $setting Name of the setting to add the key pairs to. * @param array $keys Keys pairs to add to the deletes. * @return void */ private function addToDelete(string $setting, array $keys): void { $this->deletes[$setting] = array_merge($this->deletes[$setting] ?? [], $keys); } /** * Destructor for LaravelSettingPro class. Save changes to settings. * * @return void */ public function __destruct() { $this->deleteProcess(); $this->settingProcess(); } /** * Process changes to settings and save them. * * @return void */ private function settingProcess(): void { foreach ($this->sets as $setting => $keyValue) { $updateParams = [ $setting, $keyValue, $this->config['cache']['enabled'], $this->config['trigger_events'], $this->config['queue'], ]; if ($this->config['process_to_queue']) { UpdateSettingJob::dispatch(...$updateParams); } else { UpdateSettingJob::dispatchSync(...$updateParams); } } } /** * Process delete on settings and save them. * * @return void */ private function deleteProcess(): void { foreach ($this->deletes as $setting => $keys) { $deleteParams = [ $setting, $keys, $this->config['cache']['enabled'], $this->config['trigger_events'], $this->config['queue'], ]; if ($this->config['process_to_queue']) { DeleteSettingJob::dispatch(...$deleteParams); } else { DeleteSettingJob::dispatchSync(...$deleteParams); } } } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Concerns/DeleteCallbacksTrait.php
src/Concerns/DeleteCallbacksTrait.php
<?php namespace Sajadsdi\LaravelSettingPro\Concerns; use Closure; trait DeleteCallbacksTrait { /** * Get a callback function for delete operation. * * @param string $setting Name of the setting. * @return Closure Callback function. */ private function getCallbackDeleteOperation(string $setting): Closure { $class = $this; return function ($key) use ($class, $setting) { $class->addToDelete($setting, [$key]); unset($class->sets[$setting][$key]); if (isset($class->sets[$setting]) && !$class->sets[$setting]) { $this->removeFromSet($setting); } }; } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Providers/LaravelSettingProServiceProvider.php
src/Providers/LaravelSettingProServiceProvider.php
<?php namespace Sajadsdi\LaravelSettingPro\Providers; use Illuminate\Support\ServiceProvider; use Sajadsdi\LaravelSettingPro\Console\ClearCacheCommand; use Sajadsdi\LaravelSettingPro\Console\InstallCommand; use Sajadsdi\LaravelSettingPro\Console\PublishCommand; use Sajadsdi\LaravelSettingPro\Console\PublishMongoDBCommand; use Sajadsdi\LaravelSettingPro\Services\SettingStore; class LaravelSettingProServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton(SettingStore::class,function () { return new SettingStore(config('_setting')); }); //singleton pattern implemented in setting class for work in any laravel files before bootstrap! //$this->app->singleton(LaravelSettingPro::class); //$this->app->singleton(Setting::class); } public function boot(): void { if ($this->app->runningInConsole()) { $this->configurePublishing(); $this->migrationPublishing(); $this->registerCommands(); } } private function configurePublishing() { $this->publishes([__DIR__ . '/../../config/_setting.php' => config_path('_setting.php')], 'laravel-setting-pro-configure'); } private function migrationPublishing() { $this->publishes([__DIR__ . '/../../database/migrations/2023_11_03_030451_create_settings_table.php' => database_path('migrations/2023_11_03_030451_create_settings_table.php')], 'laravel-setting-pro-migration'); $this->publishes([__DIR__ . '/../../database/migrations/2023_12_08_042350_create_settings_mongodb_collection.php' => database_path('migrations/2023_12_08_042350_create_settings_mongodb_collection.php')], 'laravel-setting-pro--mongodb-migration'); } private function registerCommands() { $this->commands([ PublishCommand::class, InstallCommand::class, PublishMongoDBCommand::class, ClearCacheCommand::class ]); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Events/DeleteSettingEvent.php
src/Events/DeleteSettingEvent.php
<?php namespace Sajadsdi\LaravelSettingPro\Events; use Illuminate\Foundation\Events\Dispatchable; class DeleteSettingEvent { use Dispatchable; /** * Create a new event instance. */ public function __construct(public string $settingName, public array $deletedKeys, public array $oldData) { // } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Events/UpdateSettingEvent.php
src/Events/UpdateSettingEvent.php
<?php namespace Sajadsdi\LaravelSettingPro\Events; use Illuminate\Foundation\Events\Dispatchable; class UpdateSettingEvent { use Dispatchable; /** * Create a new event instance. */ public function __construct(public string $settingName, public array $seatedKeyValues, public array $oldData) { // } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/tests/setting/test.php
tests/setting/test.php
<?php return [ 'welcome' => 'welcome to Laravel Setting Pro', 'version' => '2.0.0', 'users' => [ '1' => [ 'name' => 'test user 1', 'profile' => [ 'address' => 'address test 1', 'pic' => 'test1.png' ] ], '2' => [ 'name' => 'test user 2', 'profile' => [ 'address' => 'address test 2', 'pic' => 'test2.png' ] ], '3' => [ 'name' => 'test user 3', 'profile' => [ 'address' => 'address test 3', 'pic' => 'test3.png' ] ], '4' => [ 'name' => 'test user 4', 'profile' => [ 'address' => 'address test 4', 'pic' => 'test4.png' ] ], '5' => [ 'name' => 'test user 5', 'profile' => [ 'address' => 'address test 5', 'pic' => 'test5.png' ] ] ] ];
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/config/_setting.php
config/_setting.php
<?php return [ 'store' => [ //Default setting store driver 'default' => 'file', //If any requested setting is not found in the default driver, //this driver is used and if available, it is imported into //the default driver. you can set empty to disable this feature. 'import_from' => '', //Include drivers and configures for setting store 'drivers' => [ 'file' => [ 'path' => base_path('setting'), 'class' => \Sajadsdi\LaravelSettingPro\Drivers\File::class, ], 'database' => [ //Default database connection if default store is 'database' 'connection' => 'mysql', 'class' => \Sajadsdi\LaravelSettingPro\Drivers\Database::class, 'connections' => [ 'mysql' => [ 'class' => \Sajadsdi\LaravelSettingPro\Drivers\Database\Mysql::class, 'driver' => "mysql", 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8mb4', 'prefix' => '', ], 'mongodb' => [ 'class' => \Sajadsdi\LaravelSettingPro\Drivers\Database\MongoDB::class, 'host' => env('MONGO_DB_HOST', '127.0.0.1'), 'port' => env('MONGO_DB_PORT', 27017), 'database' => env('MONGO_DB_DATABASE', 'forge'), 'username' => env('MONGO_DB_USERNAME', ''), 'password' => env('MONGO_DB_PASSWORD', ''), 'options' => [ ], ] ] ], ], ], 'cache' => [ //flag for enable or disable cache. 'enabled' => false, //Default setting cache driver 'default' => 'file', 'class' => \Sajadsdi\LaravelSettingPro\Cache\Cache::class, //Include drivers and configures for setting cache 'drivers' => [ 'file' => [ 'class' => \Sajadsdi\LaravelSettingPro\Cache\Drivers\File::class, 'path' => storage_path('framework/cache/settings'), ], 'redis' => [ 'class' => \Sajadsdi\LaravelSettingPro\Cache\Drivers\Redis::class, 'connection' => [ 'scheme' => 'tcp', 'host' => env('REDIS_HOST', '127.0.0.1'), 'username' => env('REDIS_USERNAME'), 'password' => env('REDIS_PASSWORD'), 'port' => env('REDIS_PORT', '6379'), 'database' => env('REDIS_CACHE_DB', '1'), ], 'options' => [ 'cluster' => env('REDIS_CLUSTER', 'redis'), 'prefix' => 'setting_caches_', ], ] ] ], //If true ,update and delete Settings handled on background. 'process_to_queue' => false, 'queue' => 'settings', //If true ,trigger events after update and delete settings. you can create listener for: //Sajadsdi\LaravelSettingPro\Events\UpdateSettingEvent //Sajadsdi\LaravelSettingPro\Events\DeleteSettingEvent 'trigger_events' => false ];
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/database/migrations/2023_11_03_030451_create_settings_table.php
database/migrations/2023_11_03_030451_create_settings_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::connection('mysql')->create('settings', function (Blueprint $table) { $table->string('setting')->primary(); $table->longText('data'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::connection('mysql')->dropIfExists('settings'); } };
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/database/migrations/2023_12_08_042350_create_settings_mongodb_collection.php
database/migrations/2023_12_08_042350_create_settings_mongodb_collection.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::connection('mongodb')->create('settings',function ($collection){ $collection->unique('setting'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::connection('mongodb')->dropIfExists('settings'); } };
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/Connection.php
src/Connection.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Illuminate\Support\Str; use InvalidArgumentException; class Connection { private ?string $privateKeyPath = null; public function __construct( public readonly string $host, public readonly int $port, public readonly string $username, public readonly string $privateKey, public readonly string $scriptPath, public readonly ?string $proxyJump = null, ) { if (trim($host) === '') { throw new InvalidArgumentException('The host cannot be empty.'); } if ($port < 1 || $port > 65535) { throw new InvalidArgumentException('The port must be between 1 and 65535.'); } if (trim($username) === '') { throw new InvalidArgumentException('The username cannot be empty.'); } if (trim($privateKey) === '') { throw new InvalidArgumentException('The private key cannot be empty.'); } if (trim($scriptPath) === '') { throw new InvalidArgumentException('The script path cannot be empty.'); } } /** * Checks if the given connection is the same as this one. */ public function is(Connection $connection): bool { return $this->host === $connection->host && $this->port === $connection->port && $this->username === $connection->username && $this->privateKey === $connection->privateKey && $this->scriptPath === $connection->scriptPath && $this->proxyJump === $connection->proxyJump; } /** * Creates a new connection from the given config connection name. */ public static function fromConfig(string $connection): static { $config = config('task-runner.connections.'.$connection); if (! $config) { throw new ConnectionNotFoundException("Connection `{$connection}` not found."); } return static::fromArray($config); } /** * Creates a new connection from the given array. */ public static function fromArray(array $config): static { $username = $config['username'] ?: ''; $scriptPath = $config['script_path'] ?? null; if ($scriptPath) { $scriptPath = rtrim($scriptPath, '/'); } if (! $scriptPath && $username) { $scriptPath = $config['username'] === 'root' ? '/root/.laravel-task-runner' : "/home/{$username}/.laravel-task-runner"; } $privateKey = $config['private_key'] ?? null; if (is_callable($privateKey)) { $privateKey = $privateKey(); } $privateKeyPath = $config['private_key_path'] ?? null; if (! $privateKey && $privateKeyPath) { $privateKey = file_get_contents($privateKeyPath); } $instance = new static( host: $config['host'] ?: null, port: $config['port'] ?: null, username: $username ?: null, privateKey: $privateKey, scriptPath: $scriptPath, proxyJump: $config['proxy_jump'] ?? null, ); if ($privateKeyPath) { $instance->setPrivateKeyPath($privateKeyPath); } return $instance; } /** * Sets the path to the private key. */ public function setPrivateKeyPath(string $privateKeyPath): self { $this->privateKeyPath = $privateKeyPath; return $this; } /** * Returns the path to the private key. */ public function getPrivateKeyPath(): string { if ($this->privateKeyPath) { return $this->privateKeyPath; } return tap( $this->privateKeyPath = Helper::temporaryDirectoryPath(Str::random(32).'.key'), function () { file_put_contents($this->privateKeyPath, $this->privateKey); // Make sure the private key is only readable by the current user chmod($this->privateKeyPath, 0600); } ); } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/RemoteProcessRunner.php
src/RemoteProcessRunner.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Illuminate\Support\Facades\Process as FacadesProcess; use Illuminate\Support\Str; class RemoteProcessRunner { /** * @var callable|null */ private $onOutput = null; public function __construct( private Connection $connection, private ProcessRunner $processRunner ) { } /** * A PHP callback to run whenever there is some output available on STDOUT or STDERR. */ public function onOutput(callable $callback): self { $this->onOutput = $callback; return $this; } /** * Runs the full path of given script on the remote server. */ public function path(string $filename): string { return $this->connection->scriptPath.'/'.$filename; } /** * Creates the script directory on the remote server. * * * @throws \ProtoneMedia\LaravelTaskRunner\CouldNotCreateScriptDirectoryException */ public function verifyScriptDirectoryExists(): self { $output = $this->run( script: 'mkdir -p '.$this->connection->scriptPath, timeout: 10 ); if ($output->isTimeout() || $output->getExitCode() !== 0) { throw CouldNotCreateScriptDirectoryException::fromProcessOutput($output); } return $this; } /** * Returns a set of common SSH options. */ private function sshOptions(): array { $options = [ '-o UserKnownHostsFile=/dev/null', // Don't use known hosts '-o StrictHostKeyChecking=no', // Disable host key checking "-i {$this->connection->getPrivateKeyPath()}", ]; if ($this->connection->proxyJump) { $options[] = "-J {$this->connection->proxyJump}"; } return $options; } /** * Formats the script and output paths, and runs the script. */ public function runUploadedScript(string $script, string $output, int $timeout = 0): ProcessOutput { $scriptPath = $this->path($script); $outputPath = $this->path($output); return $this->run("bash {$scriptPath} 2>&1 | tee {$outputPath}", $timeout); } /** * Formats the script and output paths, and runs the script in the background. */ public function runUploadedScriptInBackground(string $script, string $output, int $timeout = 0): ProcessOutput { $script = Helper::scriptInBackground( scriptPath: $this->path($script), outputPath: $this->path($output), timeout: $timeout, ); return $this->run($script, 10); } /** * Wraps the script in a bash subshell command, and runs it over SSH. */ private function run(string $script, int $timeout = 0): ProcessOutput { $command = implode(' ', [ 'ssh', ...$this->sshOptions(), "-p {$this->connection->port}", "{$this->connection->username}@{$this->connection->host}", Helper::scriptInSubshell($script), ]); $output = $this->processRunner->run( FacadesProcess::command($command)->timeout($timeout > 0 ? $timeout : null), $this->onOutput ); return $this->cleanupOutput($output); } /** * Removes the known hosts warning from the output. */ private function cleanupOutput(ProcessOutput $processOutput): ProcessOutput { $buffer = $processOutput->getBuffer(); if (Str::startsWith($buffer, 'Warning: Permanently added')) { $buffer = Str::after($buffer, "\n"); } return ProcessOutput::make(trim($buffer)) ->setExitCode($processOutput->getExitCode()) ->setTimeout($processOutput->isTimeout()); } /** * Uploads the given contents to the script directory with the given filename. * * @param string $filename * @param string $contents */ public function upload($filename, $contents): self { $localPath = Helper::temporaryDirectoryPath($filename); file_put_contents($localPath, $contents); $command = implode(' ', [ 'scp', ...$this->sshOptions(), '-P '.$this->connection->port, $localPath, "{$this->connection->username}@{$this->connection->host}:".$this->path($filename), ]); $output = $this->processRunner->run( FacadesProcess::command($command)->timeout(10) ); if ($output->isTimeout() || $output->getExitCode() !== 0) { throw CouldNotUploadFileException::fromProcessOutput($output); } return $this; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/CouldNotUploadFileException.php
src/CouldNotUploadFileException.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Exception; class CouldNotUploadFileException extends Exception { public readonly ProcessOutput $output; public static function fromProcessOutput(ProcessOutput $output): static { $exception = new static('Could not upload file'); $exception->output = $output; return $exception; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/ProcessRunner.php
src/ProcessRunner.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Illuminate\Process\Exceptions\ProcessTimedOutException; use Illuminate\Process\PendingProcess; class ProcessRunner { /** * Runs the given process and waits for it to finish. */ public function run(PendingProcess $process, ?callable $onOutput = null): ProcessOutput { $output = new ProcessOutput; if ($onOutput) { $output->onOutput($onOutput); } return tap($output, function (ProcessOutput $output) use ($process) { $timeout = false; try { $illuminateResult = $process->run(output: $output); } catch (ProcessTimedOutException $e) { $illuminateResult = $e->result; $timeout = true; } $output->setIlluminateResult($illuminateResult); $output->setExitCode($illuminateResult->exitCode()); $output->setTimeout($timeout); }); } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/PendingTask.php
src/PendingTask.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Illuminate\Support\Str; use Illuminate\Support\Traits\Conditionable; use Illuminate\Support\Traits\Macroable; class PendingTask { use Conditionable; use Macroable; private ?Connection $connection = null; private bool $inBackground = false; private ?string $id = null; private ?string $outputPath = null; /** * @var callable|null */ private $onOutput = null; public function __construct( public readonly Task $task ) { } /** * Wraps the given task in a PendingTask instance. */ public static function make(string|Task|PendingTask $task): static { if (is_string($task) && class_exists($task)) { $task = app($task); } return $task instanceof PendingTask ? $task : new PendingTask($task); } /** * A PHP callback to run whenever there is some output available on STDOUT or STDERR. */ public function onOutput(callable $callback): self { $this->onOutput = $callback; return $this; } /** * Returns the callback that should be run whenever there is some output available on STDOUT or STDERR. */ public function getOnOutput(): ?callable { return $this->onOutput; } /** * Returns the connection, if set. */ public function getConnection(): ?Connection { return $this->connection; } /** * Setter for the connection. */ public function onConnection(string|Connection $connection): self { $this->connection = is_string($connection) ? Connection::fromConfig($connection) : $connection; return $this; } /** * Checks if the task runs in the background. */ public function shouldRunInBackground(): bool { return $this->inBackground; } /** * Checks if the task runs in the foreground. */ public function shouldRunInForeground(): bool { return ! $this->inBackground; } /** * Sets the 'inBackground' property. */ public function inBackground(bool $value = true): self { $this->inBackground = $value; return $this; } /** * Sets the 'inBackground' property to the opposite of the given value. */ public function inForeground(bool $value = true): self { $this->inBackground = ! $value; return $this; } /** * Returns the 'id' property. */ public function getId(): ?string { return $this->id; } /** * Sets the 'id' property. */ public function id(?string $id = null): self { $this->id = $id; return $this; } /** * Alias for the 'id' method. */ public function as(string $id): self { return $this->id($id); } /** * Returns the 'outputPath' property. */ public function getOutputPath(): ?string { return $this->outputPath; } /** * Sets the 'outputPath' property. */ public function writeOutputTo(?string $outputPath = null): self { $this->outputPath = $outputPath; return $this; } /** * Checks if the given connection is the same as the connection of this task. */ public function shouldRunOnConnection(bool|string|Connection|callable|null $connection = null): bool { if ($connection === null && $this->connection !== null) { return true; } if ($connection === true && $this->connection !== null) { return true; } if ($connection === false && $this->connection === null) { return true; } if (is_callable($connection)) { return $connection($this->connection) === true; } if (is_string($connection)) { $connection = Connection::fromConfig($connection); } if ($connection instanceof Connection) { return $connection->is($this->connection); } return false; } /** * Stores the script in a temporary directory and returns the path. */ public function storeInTemporaryDirectory(): string { $id = $this->id ?: Str::random(32); return tap(Helper::temporaryDirectoryPath("{$id}.sh"), function ($path) { file_put_contents($path, $this->task->getScript()); chmod($path, 0700); }); } /** * Dispatches the task to the given task runner. */ public function dispatch(?TaskDispatcher $taskDispatcher = null): ?ProcessOutput { /** @var TaskDispatcher */ $taskDispatcher = $taskDispatcher ?: app(TaskDispatcher::class); return $taskDispatcher->run($this); } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/Helper.php
src/Helper.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Spatie\TemporaryDirectory\TemporaryDirectory; class Helper { /** * Wraps the given script in a subshell using bash's here document. * * @param string $output */ public static function scriptInSubshell(string $script): string { $eof = static::eof($script); return implode(PHP_EOL, [ "'bash -s' << '{$eof}'", $script, $eof, ]); } /** * Returns a temporary directory that will be deleted on shutdown. */ public static function temporaryDirectory(): TemporaryDirectory { return tap( TemporaryDirectory::make(config('task-runner.temporary_directory') ?: ''), fn ($temporaryDirectory) => register_shutdown_function(fn () => $temporaryDirectory->delete()) ); } /** * Returns the path to the temporary directory. */ public static function temporaryDirectoryPath(string $pathOrFilename = ''): string { return static::temporaryDirectory()->path($pathOrFilename); } /** * Use the nohup command to run a script in the background. */ public static function scriptInBackground(string $scriptPath, ?string $outputPath = null, ?int $timeout = null): string { $outputPath = $outputPath ?: '/dev/null'; $timeout = $timeout ?: 0; $nohup = $timeout > 0 ? "nohup timeout {$timeout}s" : 'nohup'; return "{$nohup} bash {$scriptPath} > {$outputPath} 2>&1 &"; } /** * Returns the EOF string. * * @param string $script * @return void */ public static function eof($script = '') { if ($eof = config('task-runner.eof')) { return $eof; } return 'LARAVEL-TASK-RUNNER-'.md5($script); } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/CouldNotCreateScriptDirectoryException.php
src/CouldNotCreateScriptDirectoryException.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Exception; class CouldNotCreateScriptDirectoryException extends Exception { public readonly ProcessOutput $output; public static function fromProcessOutput(ProcessOutput $output): static { $exception = new static('Could not create script directory'); $exception->output = $output; return $exception; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/ConnectionNotFoundException.php
src/ConnectionNotFoundException.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Exception; class ConnectionNotFoundException extends Exception { }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/TaskDispatcher.php
src/TaskDispatcher.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Process as FacadesProcess; use Illuminate\Support\Str; use ReflectionFunction; use RuntimeException; class TaskDispatcher { use MakesTestAssertions; use PersistsFakeTasks; private array|bool $tasksToFake = false; private array $tasksToDispatch = []; private bool $preventStrayTasks = false; private array $dispatchedTasks = []; public function __construct(private ProcessRunner $processRunner) { } /** * Runs the given task. */ public function run(PendingTask $pendingTask): ?ProcessOutput { if ($fakeTask = $this->taskShouldBeFaked($pendingTask)) { $this->dispatchedTasks[] = $pendingTask; $this->storePersistentFake(); return $fakeTask instanceof FakeTask ? $fakeTask->processOutput : new ProcessOutput; } if ($pendingTask->getConnection()) { return $this->runOnConnection($pendingTask); } if ($pendingTask->shouldRunInBackground()) { return $this->runInBackground($pendingTask); } $command = $pendingTask->storeInTemporaryDirectory(); $timeout = $pendingTask->task->getTimeout(); return $this->processRunner->run( FacadesProcess::command($command)->timeout($timeout) ); } /** * Runs the given task in the background. * * @return void */ private function runInBackground(PendingTask $pendingTask) { $command = Helper::scriptInBackground( scriptPath: $pendingTask->storeInTemporaryDirectory(), outputPath: $pendingTask->getOutputPath(), timeout: $pendingTask->task->getTimeout() ); return $this->processRunner->run( FacadesProcess::command($command)->timeout(10) ); } /** * Runs the given task on the given connection. */ private function runOnConnection(PendingTask $pendingTask): ProcessOutput { /** @var RemoteProcessRunner */ $runner = app()->makeWith( RemoteProcessRunner::class, ['connection' => $pendingTask->getConnection(), 'processRunner' => $this->processRunner] ); if ($outputCallbable = $pendingTask->getOnOutput()) { $runner->onOutput($outputCallbable); } $id = $pendingTask->getId() ?: Str::random(32); $runner->verifyScriptDirectoryExists()->upload("{$id}.sh", $pendingTask->task->getScript()); return $pendingTask->shouldRunInBackground() ? $runner->runUploadedScriptInBackground("{$id}.sh", "{$id}.log", $pendingTask->task->getTimeout() ?: 0) : $runner->runUploadedScript("{$id}.sh", "{$id}.log", $pendingTask->task->getTimeout() ?: 0); } // /** * Fake all or some tasks. * * @param array $tasksToFake */ public function fake(array|string $tasksToFake = []): self { $this->tasksToFake = Collection::wrap($tasksToFake)->map(function ($value, $key) { if (is_string($key) && is_string($value)) { return new FakeTask($key, ProcessOutput::make($value)->setExitCode(0)); } if (is_string($value)) { return new FakeTask($value, ProcessOutput::make()->setExitCode(0)); } if (is_string($key) && $value instanceof ProcessOutput) { return new FakeTask($key, $value); } })->filter()->values()->all(); $this->storePersistentFake(); return $this; } /** * Fake all or some tasks. * * @param array $tasksToFake */ public function dontFake(array|string $taskToDispatch): self { $this->tasksToDispatch = array_merge($this->tasksToDispatch, Arr::wrap($taskToDispatch)); $this->storePersistentFake(); return $this; } /** * Prevents stray tasks from being executed. */ public function preventStrayTasks(bool $prevent = true): self { $this->preventStrayTasks = $prevent; return $this; } /** * Returns a boolean if the task should be faked or the corresponding fake task. */ private function taskShouldBeFaked(PendingTask $pendingTask): bool|FakeTask { foreach ($this->tasksToDispatch as $dontFake) { if ($pendingTask->task instanceof $dontFake) { return false; } } if ($this->tasksToFake === []) { return new FakeTask(get_class($pendingTask->task), ProcessOutput::make()->setExitCode(0)); } if ($this->tasksToFake === false && ! config('task-runner.persistent_fake.enabled')) { return false; } $fakeTask = collect($this->tasksToFake ?: [])->first(function (FakeTask $fakeTask) use ($pendingTask) { return $pendingTask->task instanceof $fakeTask->taskClass; }); if (! $fakeTask && $this->preventStrayTasks) { throw new RuntimeException('Attempted dispatch task ['.get_class($pendingTask->task).'] without a matching fake.'); } return $fakeTask ?: false; } /** * Returns the dispatched tasks, filtered by a callback. */ protected function faked(callable $callback): Collection { $this->loadPersistentFake(); return collect($this->dispatchedTasks) ->filter(function (PendingTask $pendingTask) use ($callback) { $refFunction = new ReflectionFunction($callback); $parameters = $refFunction->getParameters(); if ($typeHint = $parameters[0]->getType()->getName() ?? null) { if (! $typeHint || $typeHint === PendingTask::class) { return $callback($pendingTask); } } return $callback($pendingTask->task); }) ->values(); } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/ServiceProvider.php
src/ServiceProvider.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use ProtoneMedia\LaravelTaskRunner\Commands\TaskMakeCommand; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; class ServiceProvider extends PackageServiceProvider { public function registeringPackage() { $this->app->singleton(ProcessRunner::class, function () { return new ProcessRunner; }); $this->app->singleton(TaskDispatcher::class, function ($app) { $taskDispatcher = new TaskDispatcher($app->make(ProcessRunner::class)); $taskDispatcher->loadPersistentFake(); return $taskDispatcher; }); } public function configurePackage(Package $package): void { $package ->name('laravel-task-runner') ->hasConfigFile() ->hasCommand(TaskMakeCommand::class); } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/ProcessOutput.php
src/ProcessOutput.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Illuminate\Contracts\Process\ProcessResult; class ProcessOutput { private string $buffer = ''; private ?int $exitCode = null; private bool $timeout = false; private ?ProcessResult $illuminateResult = null; /** * @var callable|null */ private $onOutput = null; /** * A PHP callback to run whenever there is some output available on STDOUT or STDERR. */ public function onOutput(callable $callback): self { $this->onOutput = $callback; return $this; } /** * Appends the buffer to the output. * * @param string $buffer * @return void */ public function __invoke(string $type, $buffer) { $this->buffer .= $buffer; if ($this->onOutput) { ($this->onOutput)($type, $buffer); } } /** * Helper to create a new instance. */ public static function make(string $buffer = ''): static { $instance = new static; if ($buffer) { $instance('', $buffer); } return $instance; } public function getIlluminateResult(): ?ProcessResult { return $this->illuminateResult; } /** * Returns the buffer. */ public function getBuffer(): string { return $this->buffer; } /** * Returns the buffer as an array of lines. */ public function getLines(): array { return explode(PHP_EOL, $this->getBuffer()); } /** * Returns the exit code. */ public function getExitCode(): ?int { return $this->exitCode; } /** * Checks if the process was successful. */ public function isSuccessful(): bool { return $this->getExitCode() === 0; } /** * Setter for the Illuminate ProcessResult instance. */ public function setIlluminateResult(ProcessResult $result): self { $this->illuminateResult = $result; return $this; } /** * Setter for the exit code. */ public function setExitCode(?int $exitCode = null): self { $this->exitCode = $exitCode; return $this; } /** * Checks if the process timed out. */ public function isTimeout(): bool { return $this->timeout; } /** * Setter for the timeout. */ public function setTimeout(bool $timeout): self { $this->timeout = $timeout; return $this; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/FakeTask.php
src/FakeTask.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use InvalidArgumentException; class FakeTask { public function __construct( public readonly string $taskClass, public readonly ProcessOutput $processOutput ) { if (trim($taskClass) === '') { throw new InvalidArgumentException('The task class cannot be empty.'); } } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/MakesTestAssertions.php
src/MakesTestAssertions.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use PHPUnit\Framework\Assert as PHPUnit; use ReflectionFunction; trait MakesTestAssertions { public function assertDispatched(string|callable $taskClass, ?callable $additionalCallback = null): self { $faked = $this->faked($this->makeAssertCallback($taskClass, $additionalCallback)); PHPUnit::assertTrue( $faked->count() > 0, 'An expected task was not dispatched.' ); return $this; } public function assertNotDispatched(string|callable $taskClass, ?callable $additionalCallback = null): self { $faked = $this->faked($this->makeAssertCallback($taskClass, $additionalCallback)); PHPUnit::assertTrue( $faked->count() === 0, 'An unexpected task was dispatched.' ); return $this; } public function assertDispatchedTimes(string|callable $taskClass, int $times = 1, ?callable $additionalCallback = null): self { $count = $this->faked($this->makeAssertCallback($taskClass, $additionalCallback))->count(); PHPUnit::assertSame( $times, $count, "The expected [{$taskClass}] task was dispatched {$count} times instead of {$times} times." ); return $this; } protected function typeNameOfFirstParameter(?callable $callback = null): ?string { if (! $callback) { return null; } $reflection = new ReflectionFunction($callback); $parameters = $reflection->getParameters(); if (empty($parameters)) { return null; } return $parameters[0]?->getType()?->getName() ?: null; } protected function callbackExpectsPendingTask(?callable $callback = null): bool { $typeName = $this->typeNameOfFirstParameter($callback); return ! $typeName || $typeName === PendingTask::class; } protected function makeAssertCallback(string|callable $taskClass, ?callable $additionalCallback = null) { if (! $additionalCallback) { $additionalCallback = fn () => true; } if (is_string($taskClass)) { return function (PendingTask $pendingTask) use ($taskClass, $additionalCallback) { return $pendingTask->task instanceof $taskClass && $additionalCallback($this->callbackExpectsPendingTask($additionalCallback) ? $pendingTask : $pendingTask->task); }; } return function (PendingTask $pendingTask) use ($taskClass, $additionalCallback) { $class = $this->typeNameOfFirstParameter($taskClass); return ($class === PendingTask::class || $pendingTask->task instanceof $class) && $taskClass($this->callbackExpectsPendingTask($taskClass) ? $pendingTask : $pendingTask->task) && $additionalCallback($this->callbackExpectsPendingTask($additionalCallback) ? $pendingTask : $pendingTask->task); }; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/PersistentFakeTasks.php
src/PersistentFakeTasks.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Illuminate\Filesystem\Filesystem; trait PersistentFakeTasks { public function setUpPersistentFakeTasks() { // } public function tearDownPersistentFakeTasks() { $directory = rtrim(config('task-runner.persistent_fake.storage_root'), '/'); (new Filesystem)->cleanDirectory($directory); } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/Task.php
src/Task.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Closure; use Illuminate\Container\Container; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use ReflectionMethod; use ReflectionObject; use ReflectionProperty; /* * @method static \ProtoneMedia\LaravelTaskRunner\PendingTask onConnection(string|Connection $connection) * @method static \ProtoneMedia\LaravelTaskRunner\PendingTask inBackground(bool $value = true) * @method static \ProtoneMedia\LaravelTaskRunner\PendingTask inForeground(bool $value = true) * @method static \ProtoneMedia\LaravelTaskRunner\PendingTask id(?string $id = null) * @method static \ProtoneMedia\LaravelTaskRunner\PendingTask writeOutputTo(?string $outputPath = null) * @method static \ProtoneMedia\LaravelTaskRunner\PendingTask as(string $id) * @method static \ProtoneMedia\LaravelTaskRunner\ProcessOutput dispatch(TaskDispatcher $taskDispatcher = null) */ abstract class Task { use Macroable; /** * Returns the name of the task. */ public function getName(): string { if (property_exists($this, 'name')) { return $this->name; } return Str::headline(class_basename($this)); } /** * Returns the timeout of the task in seconds. */ public function getTimeout(): ?int { $timeout = property_exists($this, 'timeout') ? $this->timeout : config('task-runner.default_timeout', 60); return $timeout > 0 ? $timeout : null; } /** * Returns the view name of the task. */ public function getView(): string { $view = property_exists($this, 'view') ? $this->view : Str::kebab(class_basename($this)); $prefix = rtrim(config('task-runner.task_views', 'tasks'), '.'); return $prefix.'.'.$view; } /** * Returns all public properties of the task. */ private function getPublicProperties(): Collection { $properties = (new ReflectionObject($this))->getProperties(ReflectionProperty::IS_PUBLIC); return Collection::make($properties)->mapWithKeys(function (ReflectionProperty $property) { return [$property->getName() => $property->getValue($this)]; }); } /** * Returns all public methods of the task. */ private function getPublicMethods(): Collection { $macros = Collection::make(static::$macros) ->mapWithKeys(function ($macro, $name) { return [$name => Closure::bind($macro, $this, get_class($this))]; }); $methods = (new ReflectionObject($this))->getMethods(ReflectionProperty::IS_PUBLIC); $methodCollection = Collection::make($methods) ->filter(function (ReflectionMethod $method) { if ($method->isConstructor() || $method->isDestructor() || $method->isStatic()) { return false; } $ignoreMethods = [ 'getData', 'getScript', 'getName', 'getTimeout', 'getView', ]; if (in_array($method->getName(), $ignoreMethods)) { return false; } return true; }) ->mapWithKeys(function (ReflectionMethod $method) { return [$method->getName() => $method->getClosure($this)]; }); return $macros->merge($methodCollection); } /** * Returns all data that should be passed to the view. */ public function getData(): array { return $this->getPublicProperties() ->merge($this->getPublicMethods()) ->merge($this->getViewData()) ->all(); } /** * Returns the data that should be passed to the view. */ public function getViewData(): array { return []; } /** * Returns the rendered script. */ public function getScript(): string { if (method_exists($this, 'render')) { return Container::getInstance()->call([$this, 'render']); } return view($this->getView(), $this->getData())->render(); } /** * Returns a new PendingTask with this task. */ public function pending(): PendingTask { return new PendingTask($this); } /** * Returns a new PendingTask with this task. */ public static function make(...$arguments): PendingTask { return (new static(...$arguments))->pending(); } /** * Helper methods to create a new PendingTask. */ public static function __callStatic($name, $arguments) { return (new static)->pending()->{$name}(...$arguments); } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/PersistsFakeTasks.php
src/PersistsFakeTasks.php
<?php namespace ProtoneMedia\LaravelTaskRunner; use Illuminate\Filesystem\Filesystem; trait PersistsFakeTasks { public function storePersistentFake() { if (! config('task-runner.persistent_fake.enabled')) { return; } $directory = rtrim(config('task-runner.persistent_fake.storage_root'), '/'); $storage = $directory.'/serialized'; (new Filesystem)->ensureDirectoryExists($directory); file_put_contents($storage, serialize([ 'tasksToFake' => $this->tasksToFake, 'tasksToDispatch' => $this->tasksToDispatch, 'preventStrayTasks' => $this->preventStrayTasks, 'dispatchedTasks' => $this->dispatchedTasks, ])); } public function loadPersistentFake() { if (! config('task-runner.persistent_fake.enabled')) { return; } $directory = rtrim(config('task-runner.persistent_fake.storage_root'), '/'); $storage = $directory.'/serialized'; (new Filesystem)->ensureDirectoryExists($directory); $unserialized = file_exists($storage) ? rescue(fn () => unserialize(file_get_contents($storage)), [], false) : []; $this->tasksToFake = $unserialized['tasksToFake'] ?? false; $this->tasksToDispatch = $unserialized['tasksToDispatch'] ?? []; $this->preventStrayTasks = $unserialized['preventStrayTasks'] ?? false; $this->dispatchedTasks = $unserialized['dispatchedTasks'] ?? []; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/Facades/TaskRunner.php
src/Facades/TaskRunner.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Facades; use Illuminate\Support\Facades\Facade; use ProtoneMedia\LaravelTaskRunner\PendingTask; use ProtoneMedia\LaravelTaskRunner\ProcessOutput; use ProtoneMedia\LaravelTaskRunner\TaskDispatcher; /** * @method static self assertDispatched(string|callable $taskClass, callable $additionalCallback = null) * @method static self assertDispatchedTimes(string|callable $taskClass, int $times = 1, callable $additionalCallback = null) * @method static self assertNotDispatched(string|callable $taskClass, callable $additionalCallback = null) * @method static self fake(array|string $tasksToFake = []) * @method static self dontFake(array|string $taskToDispatch) * @method static self preventStrayTasks(bool $prevent = true) * @method static ProcessOutput|null run(PendingTask $pendingTask) * * @see \ProtoneMedia\LaravelTaskRunner\TaskDispatcher */ class TaskRunner extends Facade { protected static function getFacadeAccessor() { return TaskDispatcher::class; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/src/Commands/TaskMakeCommand.php
src/Commands/TaskMakeCommand.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Commands; use Illuminate\Console\GeneratorCommand; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputOption; #[AsCommand(name: 'make:task')] class TaskMakeCommand extends GeneratorCommand { /** * The console command name. * * @var string */ protected $name = 'make:task'; /** * The type of class being generated. * * @var string */ protected $type = 'Task'; /** * The name of the console command. * * This name is used to identify the command during lazy loading. * * @var string|null * * @deprecated */ protected static $defaultName = 'make:task'; /** * The console command description. * * @var string */ protected $description = 'Create a new Task class'; /** * Execute the console command. * * @return bool|null * * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function handle() { if (parent::handle() === false) { return false; } if ($this->option('class')) { return; } (new Filesystem)->ensureDirectoryExists( $path = resource_path('views/'.config('task-runner.task_views', 'tasks')) ); touch($path.'/'.$this->viewName().'.blade.php'); } /** * Generate the name of the view. */ protected function viewName(): string { return Str::kebab($this->getNameInput()); } /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return $this->option('class') ? $this->resolveStubPath('/stubs/task.stub') : $this->resolveStubPath('/stubs/task-view.stub'); } /** * Resolve the fully-qualified path to the stub. * * @param string $stub * @return string */ protected function resolveStubPath($stub) { return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) ? $customPath : __DIR__.$stub; } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Tasks'; } /** * Get the console command options. * * @return array */ protected function getOptions() { return [ ['force', 'f', InputOption::VALUE_NONE, 'Create the class even if the class already exists'], ['class', 'c', InputOption::VALUE_NONE, 'Create only the Task class, not the Blade template'], ]; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/CustomTask.php
tests/CustomTask.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use ProtoneMedia\LaravelTaskRunner\Task; class CustomTask extends Task { protected $name = 'Custom Name'; protected $timeout = 120; protected $view = 'custom-view'; public $someData = 'foo'; public function __construct($someData = 'foo') { $this->someData = $someData; } public function someMethod() { return 'bar'; } public function getViewData(): array { return ['hello' => 'world']; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/TaskMakeCommandTest.php
tests/TaskMakeCommandTest.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Facades\Artisan; use ProtoneMedia\LaravelTaskRunner\Commands\TaskMakeCommand; it('can generate a task class and view with a command', function () { (new Filesystem)->cleanDirectory(app_path('Tasks')); (new Filesystem)->cleanDirectory(resource_path('views/tasks')); Artisan::call(TaskMakeCommand::class, ['name' => 'TestTask']); expect($taskPath = app_path('Tasks/TestTask.php'))->toBeFile(); expect(resource_path('views/tasks/test-task.blade.php'))->toBeFile(); $task = file_get_contents($taskPath); expect($task)->toContain('class TestTask extends Task'); expect($task)->not->toContain('public function render()'); }); it('can generate a task class without a view', function () { (new Filesystem)->cleanDirectory(app_path('Tasks')); (new Filesystem)->cleanDirectory(resource_path('views/tasks')); Artisan::call(TaskMakeCommand::class, ['name' => 'TestTask', '--class' => true]); expect($taskPath = app_path('Tasks/TestTask.php'))->toBeFile(); expect(resource_path('views/tasks/test-task.blade.php'))->not->toBeFile(); $task = file_get_contents($taskPath); expect($task)->toContain('public function render()'); });
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/TaskRunnerTest.php
tests/TaskRunnerTest.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use Mockery; use ProtoneMedia\LaravelTaskRunner\ProcessOutput; use ProtoneMedia\LaravelTaskRunner\ProcessRunner; use ProtoneMedia\LaravelTaskRunner\RemoteProcessRunner; use ProtoneMedia\LaravelTaskRunner\Task; class Pwd extends Task { public function render() { return 'pwd'; } } class PwdNoTimeout extends Task { protected $timeout = 0; public function render() { return 'pwd'; } } function addConnectionToConfig() { config(['task-runner.connections.production' => [ 'host' => '1.1.1.1', 'port' => '21', 'username' => 'root', 'private_key' => 'secret', 'passphrase' => 'password', 'script_path' => '', ]]); } it('can run a task on a local machine in the foreground', function () { $result = (new Pwd)->pending()->dispatch(); expect($result->getBuffer())->toContain(realpath(__DIR__.'/..')); }); it('can run a task on a local machine in the background', function () { $processRunner = Mockery::mock(ProcessRunner::class); $processRunner->shouldReceive('run') ->once() ->withArgs(function ($pendingProcess) { expect($pendingProcess->command)->toStartWith('nohup timeout 60s bash'); expect($pendingProcess->command)->toEndWith('.sh > /dev/null 2>&1 &'); return true; }); app()->singleton(ProcessRunner::class, fn () => $processRunner); Pwd::inBackground()->dispatch(); }); it('can run a task on a local machine in the background without a timeout and specify an output path', function () { $processRunner = Mockery::mock(ProcessRunner::class); $processRunner->shouldReceive('run') ->once() ->withArgs(function ($pendingProcess) { expect($pendingProcess->command)->toStartWith('nohup bash'); expect($pendingProcess->command)->toEndWith('.sh > /home/output.log 2>&1 &'); return true; }); app()->singleton(ProcessRunner::class, fn () => $processRunner); PwdNoTimeout::inBackground()->writeOutputTo('/home/output.log')->dispatch(); }); it('can run a task on a remote machine in the foreground', function () { addConnectionToConfig(); $remoteProcessRunner = Mockery::mock(RemoteProcessRunner::class); $remoteProcessRunner->shouldReceive('verifyScriptDirectoryExists') ->once() ->withNoArgs() ->andReturnSelf(); $remoteProcessRunner->shouldReceive('upload') ->once() ->withArgs(function ($filename, $contents) { expect($filename)->toEndWith('.sh'); expect($contents)->toBe('pwd'); return true; }) ->andReturnSelf(); $remoteProcessRunner->shouldReceive('runUploadedScript') ->once() ->withArgs(function ($scriptPath, $outputPath, $timeout) { expect($scriptPath)->toEndWith('.sh'); expect($outputPath)->toEndWith('.log'); expect($timeout)->toBe(60); return true; }) ->andReturn($output = new ProcessOutput); app()->singleton(RemoteProcessRunner::class, fn () => $remoteProcessRunner); $result = Pwd::onConnection('production')->inForeground()->dispatch(); expect($result)->toBe($output); }); it('can run a task on a remote machine in the background', function () { addConnectionToConfig(); $remoteProcessRunner = Mockery::mock(RemoteProcessRunner::class); $remoteProcessRunner->shouldReceive('verifyScriptDirectoryExists') ->once() ->withNoArgs() ->andReturnSelf(); $remoteProcessRunner->shouldReceive('upload') ->once() ->withArgs(function ($filename, $contents) { expect($filename)->toEndWith('.sh'); expect($contents)->toBe('pwd'); return true; }) ->andReturnSelf(); $remoteProcessRunner->shouldReceive('runUploadedScriptInBackground') ->once() ->withArgs(function ($scriptPath, $outputPath, $timeout) { expect($scriptPath)->toEndWith('.sh'); expect($outputPath)->toEndWith('.log'); expect($timeout)->toBe(60); return true; }) ->andReturn($output = new ProcessOutput); app()->singleton(RemoteProcessRunner::class, fn () => $remoteProcessRunner); $result = Pwd::onConnection('production')->inBackground()->dispatch(); expect($result)->toBe($output); }); it('can run a task on a remote machine in the background and define the script name', function () { addConnectionToConfig(); $remoteProcessRunner = Mockery::mock(RemoteProcessRunner::class); $remoteProcessRunner->shouldReceive('verifyScriptDirectoryExists') ->once() ->withNoArgs() ->andReturnSelf(); $remoteProcessRunner->shouldReceive('upload') ->once() ->withArgs(function ($filename, $contents) { expect($filename)->toBe('my-script.sh'); expect($contents)->toBe('pwd'); return true; }) ->andReturnSelf(); $remoteProcessRunner->shouldReceive('runUploadedScriptInBackground') ->once() ->withArgs(function ($scriptPath, $outputPath, $timeout) { expect($scriptPath)->toBe('my-script.sh'); expect($outputPath)->toBe('my-script.log'); expect($timeout)->toBe(60); return true; }) ->andReturn($output = new ProcessOutput); app()->singleton(RemoteProcessRunner::class, fn () => $remoteProcessRunner); $result = Pwd::onConnection('production')->inBackground()->as('my-script')->dispatch(); expect($result)->toBe($output); });
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/Pest.php
tests/Pest.php
<?php use ProtoneMedia\LaravelTaskRunner\Connection; use ProtoneMedia\LaravelTaskRunner\Tests\TestCase; function connection() { return Connection::fromArray([ 'host' => '1.1.1.1', 'port' => '22', 'username' => 'root', 'private_key' => 'secret', 'passphrase' => 'password', 'script_path' => '', ]); } uses(TestCase::class)->in(__DIR__);
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/ConnectionTest.php
tests/ConnectionTest.php
<?php use ProtoneMedia\LaravelTaskRunner\Connection; function addConnectionToConfig($callable = true, $path = false) { config(['task-runner.connections.production' => [ 'host' => '1.1.1.1', 'port' => '21', 'username' => 'root', 'private_key' => $callable ? fn () => 'secret' : null, 'private_key_path' => $path ? __DIR__.'/private_key' : null, 'passphrase' => 'password', 'script_path' => '', ]]); } it('can resolve a private key from a callable', function () { addConnectionToConfig(); $connection = Connection::fromConfig('production'); expect($connection->privateKey)->toBe('secret'); }); it('can resolve a private key from a path', function () { addConnectionToConfig(callable: false, path: true); $connection = Connection::fromConfig('production'); expect($connection->privateKey)->toBe('secret2'); });
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/TestCase.php
tests/TestCase.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use Orchestra\Testbench\TestCase as Orchestra; use ProtoneMedia\LaravelTaskRunner\ServiceProvider; class TestCase extends Orchestra { protected function setUp(): void { parent::setUp(); config(['task-runner.eof' => 'LARAVEL-TASK-RUNNER']); } protected function getPackageProviders($app) { return [ServiceProvider::class]; } }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/FakeTaskTest.php
tests/FakeTaskTest.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use Exception; use PHPUnit\Framework\ExpectationFailedException; use ProtoneMedia\LaravelTaskRunner\Connection; use ProtoneMedia\LaravelTaskRunner\Facades\TaskRunner; use ProtoneMedia\LaravelTaskRunner\PendingTask; use ProtoneMedia\LaravelTaskRunner\PersistentFakeTasks; use ProtoneMedia\LaravelTaskRunner\ProcessOutput; use ProtoneMedia\LaravelTaskRunner\ProcessRunner; use ProtoneMedia\LaravelTaskRunner\TaskDispatcher; use RuntimeException; it('can fake all tasks', function () { TaskRunner::fake(); DemoTask::dispatch(); CustomTask::dispatch(); CustomTask::dispatch(); TaskRunner::assertDispatched(DemoTask::class); TaskRunner::assertDispatched(CustomTask::class); TaskRunner::assertDispatchedTimes(DemoTask::class, 1); TaskRunner::assertDispatchedTimes(CustomTask::class, 2); }); it('can prevent stray tasks', function () { TaskRunner::fake(DemoTask::class); TaskRunner::preventStrayTasks(); DemoTask::dispatch(); try { CustomTask::dispatch(); } catch (RuntimeException $e) { expect($e->getMessage())->toContain('Attempted dispatch task [ProtoneMedia\LaravelTaskRunner\Tests\CustomTask] without a matching fake.'); return; } $this->fail('The expected exception was not thrown.'); }); it('can fake the output', function () { TaskRunner::fake([ DemoTask::class => 'ok!', CustomTask::class => ProcessOutput::make('nope!')->setExitCode(127), Pwd::class, ]); expect(DemoTask::dispatch()->getBuffer())->toBe('ok!'); expect(CustomTask::dispatch()->getBuffer())->toBe('nope!'); expect(Pwd::dispatch()->getBuffer())->toBe(''); TaskRunner::assertDispatched(DemoTask::class); TaskRunner::assertDispatched(CustomTask::class); TaskRunner::assertDispatched(Pwd::class); }); it('can fake specific tests', function () { TaskRunner::fake(DemoTask::class); DemoTask::dispatch(); Pwd::dispatch(); TaskRunner::assertDispatched(DemoTask::class); TaskRunner::assertNotDispatched(Pwd::class); }); it('can persist the fake settings', function () { config(['task-runner.persistent_fake.enabled' => true]); $directory = rtrim(config('task-runner.persistent_fake.storage_root'), '/'); $storage = $directory.'/serialized'; $test = new class { use PersistentFakeTasks; }; $test->tearDownPersistentFakeTasks(); expect($storage)->not->toBeFile(); TaskRunner::fake(DemoTask::class)->dontFake(Pwd::class)->preventStrayTasks(); DemoTask::dispatch(); expect($storage)->toBeFile(); $data = unserialize(file_get_contents($storage)); expect($data)->toHaveKeys(['tasksToFake', 'tasksToDispatch', 'preventStrayTasks', 'dispatchedTasks']); expect($data['tasksToFake'])->toHaveCount(1); expect($data['tasksToDispatch'])->toHaveCount(1); expect($data['preventStrayTasks'])->toBeTrue(); expect($data['dispatchedTasks'])->toHaveCount(1); $taskRunner = new TaskDispatcher(new ProcessRunner); $taskRunner->loadPersistentFake(); $taskRunner->assertDispatched(DemoTask::class); }); it('can allow specific tests', function () { TaskRunner::fake()->dontFake(Pwd::class); DemoTask::dispatch(); Pwd::dispatch(); TaskRunner::assertDispatched(DemoTask::class); TaskRunner::assertNotDispatched(Pwd::class); }); it('can assert with a callback', function () { TaskRunner::fake(); DemoTask::dispatch(); CustomTask::inBackground()->dispatch(); TaskRunner::assertDispatched(DemoTask::class); TaskRunner::assertDispatched(DemoTask::class, function (PendingTask $task) { return $task->shouldRunInForeground(); }); TaskRunner::assertDispatched(DemoTask::class, function (DemoTask $task) { return true; }); TaskRunner::assertDispatched(CustomTask::class, function (PendingTask $task) { return $task->shouldRunInBackground(); }); // try { TaskRunner::assertDispatched(DemoTask::class, function (PendingTask $task) { return $task->shouldRunInBackground(); }); } catch (Exception $e) { expect($e)->toBeInstanceOf(ExpectationFailedException::class); expect($e->getMessage())->toContain('An expected task was not dispatched.'); return; } $this->fail('The expected exception was not thrown.'); }); it('can the connection', function () { $connection = connection(); config(['task-runner.connections.demo' => [ 'host' => '1.1.1.1', 'port' => '22', 'username' => 'root', 'private_key' => 'secret', 'passphrase' => 'password', 'script_path' => '', ]]); TaskRunner::fake(); DemoTask::onConnection($connection)->dispatch(); TaskRunner::assertDispatched(DemoTask::class, function (PendingTask $task) { return $task->shouldRunOnConnection(); }); TaskRunner::assertDispatched(DemoTask::class, function (PendingTask $task) { return $task->shouldRunOnConnection(true); }); TaskRunner::assertDispatched(DemoTask::class, function (PendingTask $task) { return $task->shouldRunOnConnection('demo'); }); TaskRunner::assertDispatched(DemoTask::class, function (PendingTask $task) use ($connection) { return $task->shouldRunOnConnection($connection); }); TaskRunner::assertDispatched(DemoTask::class, function (PendingTask $task) { return $task->shouldRunOnConnection(function (Connection $c) { return $c->host === '1.1.1.1'; }); }); });
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/RemoteProcessRunnerTest.php
tests/RemoteProcessRunnerTest.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use Mockery; use ProtoneMedia\LaravelTaskRunner\ProcessOutput; use ProtoneMedia\LaravelTaskRunner\ProcessRunner; use ProtoneMedia\LaravelTaskRunner\RemoteProcessRunner; it('can determine a path on the remote server', function () { $processRunner = Mockery::mock(ProcessRunner::class); $connection = connection(); $remoteProcessRunner = new RemoteProcessRunner($connection, $processRunner); expect($remoteProcessRunner->path('test'))->toBe('/root/.laravel-task-runner/test'); }); it('can verify whether the script path exists', function () { $connection = connection(); $keyPath = $connection->getPrivateKeyPath(); $processRunner = Mockery::mock(ProcessRunner::class); $processRunner->shouldReceive('run') ->once() ->withArgs(function ($pendingProcess) use ($keyPath) { expect($pendingProcess->command)->toBe("ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {$keyPath} -p 22 root@1.1.1.1 'bash -s' << 'LARAVEL-TASK-RUNNER' mkdir -p /root/.laravel-task-runner LARAVEL-TASK-RUNNER"); return true; }) ->andReturn((new ProcessOutput)->setExitCode(0)); $remoteProcessRunner = new RemoteProcessRunner($connection, $processRunner); $remoteProcessRunner->verifyScriptDirectoryExists(); }); it('can upload a file to the server', function () { $connection = connection(); $keyPath = $connection->getPrivateKeyPath(); $processRunner = Mockery::mock(ProcessRunner::class); $processRunner->shouldReceive('run') ->once() ->withArgs(function ($pendingProcess) use ($keyPath) { expect($pendingProcess->command) ->toStartWith("scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {$keyPath} -P 22") ->toEndWith('/test.sh root@1.1.1.1:/root/.laravel-task-runner/test.sh'); return true; }) ->andReturn((new ProcessOutput)->setExitCode(0)); $remoteProcessRunner = new RemoteProcessRunner($connection, $processRunner); $remoteProcessRunner->upload('test.sh', 'pwd'); }); it('can run an uploaded script on the server', function () { $connection = connection(); $keyPath = $connection->getPrivateKeyPath(); $processRunner = Mockery::mock(ProcessRunner::class); $processRunner->shouldReceive('run') ->once() ->withArgs(function ($pendingProcess) use ($keyPath) { expect($pendingProcess->command)->toBe("ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {$keyPath} -p 22 root@1.1.1.1 'bash -s' << 'LARAVEL-TASK-RUNNER' bash /root/.laravel-task-runner/test.sh 2>&1 | tee /root/.laravel-task-runner/test.log LARAVEL-TASK-RUNNER"); return true; }) ->andReturn((new ProcessOutput)->setExitCode(0)); $remoteProcessRunner = new RemoteProcessRunner($connection, $processRunner); $remoteProcessRunner->runUploadedScript('test.sh', 'test.log', 60); }); it('can run an uploaded script in the background without a timeout on the server', function () { $connection = connection(); $keyPath = $connection->getPrivateKeyPath(); $processRunner = Mockery::mock(ProcessRunner::class); $processRunner->shouldReceive('run') ->once() ->withArgs(function ($pendingProcess) use ($keyPath) { expect($pendingProcess->command)->toBe("ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {$keyPath} -p 22 root@1.1.1.1 'bash -s' << 'LARAVEL-TASK-RUNNER' nohup bash /root/.laravel-task-runner/test.sh > /root/.laravel-task-runner/test.log 2>&1 & LARAVEL-TASK-RUNNER"); return true; }) ->andReturn((new ProcessOutput)->setExitCode(0)); $remoteProcessRunner = new RemoteProcessRunner($connection, $processRunner); $remoteProcessRunner->runUploadedScriptInBackground('test.sh', 'test.log', 0); }); it('can run an uploaded script in the background with a timeout on the server', function () { $connection = connection(); $keyPath = $connection->getPrivateKeyPath(); $processRunner = Mockery::mock(ProcessRunner::class); $processRunner->shouldReceive('run') ->once() ->withArgs(function ($pendingProcess) use ($keyPath) { expect($pendingProcess->command)->toBe("ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {$keyPath} -p 22 root@1.1.1.1 'bash -s' << 'LARAVEL-TASK-RUNNER' nohup timeout 60s bash /root/.laravel-task-runner/test.sh > /root/.laravel-task-runner/test.log 2>&1 & LARAVEL-TASK-RUNNER"); return true; }) ->andReturn((new ProcessOutput)->setExitCode(0)); $remoteProcessRunner = new RemoteProcessRunner($connection, $processRunner); $remoteProcessRunner->runUploadedScriptInBackground('test.sh', 'test.log', 60); });
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/ProcessRunnerTest.php
tests/ProcessRunnerTest.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use Illuminate\Process\PendingProcess; use Illuminate\Process\ProcessResult; use Mockery; use ProtoneMedia\LaravelTaskRunner\ProcessOutput; use ProtoneMedia\LaravelTaskRunner\ProcessRunner; it('can run a process and wait for it', function () { $processResult = Mockery::mock(ProcessResult::class); $processResult->shouldReceive('exitCode')->once()->withNoArgs()->andReturn(0); $pendingProcess = Mockery::mock(PendingProcess::class); $pendingProcess->shouldReceive('run') ->once() ->withArgs(function ($command, $output) { expect($output)->toBeInstanceOf(ProcessOutput::class); return true; }) ->andReturn($processResult); $runner = new ProcessRunner; $output = $runner->run($pendingProcess); expect($output)->toBeInstanceOf(ProcessOutput::class); expect($output->getExitCode())->toBe(0); expect($output->isSuccessful())->toBeTrue(); });
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/TaskTest.php
tests/TaskTest.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use Illuminate\Support\Facades\View; use Mockery; use ProtoneMedia\LaravelTaskRunner\Connection; use ProtoneMedia\LaravelTaskRunner\PendingTask; it('can generate defaults based on the class name and configuration', function () { $task = new DemoTask; expect($task->getName())->toBe('Demo Task'); expect($task->getTimeout())->toBe(60); expect($task->getView())->toBe('tasks.demo-task'); }); it('can return a custom name and timeout and view', function () { $task = new CustomTask; expect($task->getName())->toBe('Custom Name'); expect($task->getTimeout())->toBe(120); expect($task->getView())->toBe('tasks.custom-view'); }); it('adds public properties to the data array', function () { $task = new CustomTask; expect($task->getData())->toHaveKey('someData'); }); it('adds view data to the data array', function () { $task = new CustomTask; expect($task->getData())->toHaveKey('hello'); }); it('add the public methods to the data array', function () { $task = new CustomTask; expect($task->getData())->toHaveKey('someMethod'); expect($task->getData()['someMethod']())->toBe('bar'); }); it('add the macro methods to the data array', function () { $task = new CustomTask; CustomTask::macro('macroMethod', function () { return 'baz'; }); expect($task->getData())->toHaveKey('macroMethod'); expect($task->getData()['macroMethod']())->toBe('baz'); }); it('renders the view with the data', function () { $task = new CustomTask; View::addLocation(__DIR__.'/views'); expect($task->getScript())->toBe('baz foo bar'); }); it('has a helper method to create the task fluently', function () { $task = CustomTask::make('otherData'); expect($task)->toBeInstanceOf(PendingTask::class); expect($task->task->someData)->toBe('otherData'); }); it('can create a pending task with a static method', function () { $pendingTask = DemoTask::inBackground(); expect($pendingTask->task)->toBeInstanceOf(DemoTask::class); expect($pendingTask->shouldRunInBackground())->toBeTrue(); expect($pendingTask->getConnection())->toBeNull(); $pendingTask = DemoTask::inForeground(); expect($pendingTask->shouldRunInBackground())->toBeFalse(); $pendingTask = DemoTask::onConnection(Mockery::mock(Connection::class)); expect($pendingTask->getConnection())->toBeInstanceOf(Connection::class); });
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/DemoTask.php
tests/DemoTask.php
<?php namespace ProtoneMedia\LaravelTaskRunner\Tests; use ProtoneMedia\LaravelTaskRunner\Task; class DemoTask extends Task { }
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/tests/views/tasks/custom-view.blade.php
tests/views/tasks/custom-view.blade.php
baz {{ $someData }} {{ $someMethod() }}
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
protonemedia/laravel-task-runner
https://github.com/protonemedia/laravel-task-runner/blob/18347dc17e1f0e21e780033420a41838b3c360a7/config/task-runner.php
config/task-runner.php
<?php return [ // The default timeout for a task in seconds 'default_timeout' => 60, // The view location for the tasks. 'task_views' => 'tasks', // The connection to use for the tasks. 'connections' => [ // 'production' => [ // 'host' => '', // 'port' => '', // 'username' => '', // 'private_key' => '', // 'private_key_path' => '', // 'passphrase' => '', // 'script_path' => '', // ], ], // Default EOF value. Leave empty to generate a dynamic one. 'eof' => '', // The temporary directory to store the private keys and scripts. Leave empty to use the system's temporary directory. 'temporary_directory' => '', // Store the fakes in a file. This is useful for testing. 'persistent_fake' => [ 'enabled' => env('TASK_RUNNER_PERSISTENT_FAKE', false), 'storage_root' => storage_path('framework/testing/task-runner'), ], ];
php
MIT
18347dc17e1f0e21e780033420a41838b3c360a7
2026-01-05T05:16:56.823834Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tools/rector/config.php
tools/rector/config.php
<?php declare(strict_types=1); use Rector\Config\RectorConfig; use Rector\Set\ValueObject\SetList; use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromStrictConstructorRector; return static function (RectorConfig $rectorConfig): void { $rectorConfig->paths([ __DIR__.'/../../src', __DIR__.'/..', ]); $rectorConfig->skip([ __DIR__.'/../phpstan/build', ]); $rectorConfig->rules([ TypedPropertyFromStrictConstructorRector::class, ]); $rectorConfig->sets([ SetList::PHP_82, SetList::CODE_QUALITY, SetList::DEAD_CODE, SetList::CODING_STYLE, SetList::NAMING, SetList::PRIVATIZATION, SetList::TYPE_DECLARATION, ]); };
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/NimbusServiceProvider.php
src/NimbusServiceProvider.php
<?php namespace Sunchayn\Nimbus; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; use Sunchayn\Nimbus\Modules\Routes\Services\IgnoredRoutesService; class NimbusServiceProvider extends PackageServiceProvider { private bool $enabled; public function __construct($app) { parent::__construct($app); $this->enabled = $this->app->environment(config('nimbus.allowed_envs', ['testing', 'local', 'staging'])); } /** * @see https://github.com/spatie/laravel-package-tools */ public function configurePackage(Package $package): void { $package ->name('nimbus') ->hasConfigFile() ->hasViews('nimbus') ->hasAssets() ->hasRoutes(['api', 'web']); } public function register(): void { if (! $this->enabled) { $this->registerPackageConfigs(); return; } parent::register(); $this->app->singleton( IgnoredRoutesService::class, fn (): \Sunchayn\Nimbus\Modules\Routes\Services\IgnoredRoutesService => new IgnoredRoutesService, ); } public function boot(): void { if (! $this->enabled) { return; } parent::boot(); $this->tagAlongsideLaravelAssets(); } /** * Laravel assets are configured by default in Laravel to be published post update. * We always want to force-publish the assets with Nimbus, so let's tag alongside them. */ private function tagAlongsideLaravelAssets(): void { $vendorAssets = $this->package->basePath('/../resources/dist'); $appAssets = public_path('vendor/'.$this->package->shortName()); $this->publishes([$vendorAssets => $appAssets], 'laravel-assets'); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Http/Web/Controllers/NimbusIndexController.php
src/Http/Web/Controllers/NimbusIndexController.php
<?php namespace Sunchayn\Nimbus\Http\Web\Controllers; use Illuminate\Contracts\Support\Renderable; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Route as RouteFacade; use Illuminate\Support\Facades\Vite; use Illuminate\Support\Str; use Sunchayn\Nimbus\Modules\Routes\Actions; use Sunchayn\Nimbus\Modules\Routes\Exceptions\RouteExtractionException; class NimbusIndexController { private const VIEW_NAME = 'nimbus::app'; public function __invoke( Actions\ExtractRoutesAction $extractRoutesAction, Actions\IgnoreRouteErrorAction $ignoreRouteErrorAction, Actions\BuildGlobalHeadersAction $buildGlobalHeadersAction, Actions\BuildCurrentUserAction $buildCurrentUserAction, Actions\DisableThirdPartyUiAction $disableThirdPartyUiAction, ): Renderable|RedirectResponse { $disableThirdPartyUiAction->execute(); Vite::useBuildDirectory('/vendor/nimbus'); Vite::useHotFile(base_path('/vendor/sunchayn/nimbus/resources/dist/hot')); if (request()->has('ignore')) { $ignoreRouteErrorAction->execute( ignoreData: request()->get('ignore'), ); return redirect()->to(request()->url()); } try { $routes = $extractRoutesAction ->execute( routes: RouteFacade::getRoutes()->getRoutes(), ); } catch (RouteExtractionException $routeExtractionException) { return view(self::VIEW_NAME, [ // @phpstan-ignore-line it cannot find the view. 'routeExtractorException' => $this->renderExtractorException($routeExtractionException), ]); } return view(self::VIEW_NAME, [ // @phpstan-ignore-line it cannot find the view. 'routes' => $routes->toFrontendArray(), 'headers' => $buildGlobalHeadersAction->execute(), 'currentUser' => $buildCurrentUserAction->execute(), ]); } /** * @return array<string, array<string, array<int|string>|string|null>|string|null> */ private function renderExtractorException(RouteExtractionException $routeExtractionException): array { return [ 'exception' => [ 'message' => $routeExtractionException->getMessage(), 'previous' => $routeExtractionException->getPrevious() instanceof \Throwable ? [ 'message' => $routeExtractionException->getPrevious()->getMessage(), 'file' => $routeExtractionException->getPrevious()->getFile(), 'line' => $routeExtractionException->getPrevious()->getLine(), 'trace' => Str::replace("\n", '<br/>', $routeExtractionException->getPrevious()->getTraceAsString()), ] : null, ], 'routeContext' => $routeExtractionException->getRouteContext(), 'suggestedSolution' => $routeExtractionException->getSuggestedSolution(), 'ignoreData' => $routeExtractionException->getIgnoreData(), ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Http/Api/Relay/RelayResponseResource.php
src/Http/Api/Relay/RelayResponseResource.php
<?php namespace Sunchayn\Nimbus\Http\Api\Relay; use Illuminate\Http\Resources\Json\JsonResource; use Sunchayn\Nimbus\Modules\Relay\DataTransferObjects\RelayedRequestResponseData; /** * @property RelayedRequestResponseData $resource * * @mixin RelayedRequestResponseData */ class RelayResponseResource extends JsonResource { public static $wrap; /** * @return array<string, mixed> */ public function toArray($request): array { return [ 'statusCode' => $this->resource->statusCode, 'statusText' => $this->resource->statusText, 'body' => $this->resource->body->toPrettyJSON(), 'headers' => $this->processHeaders($this->headers), 'cookies' => collect($this->resource->cookies)->map->toArray(), 'duration' => $this->resource->durationMs, 'timestamp' => $this->resource->timestamp, ]; } /** * Converts headers from backend format to frontend array format. * * @param string[][] $headers * @return array<array{key: string, value: string}> */ private function processHeaders(array $headers): array { return collect($headers) ->flatMap( // Convert each header value to a separate key-value pair fn (array $values, string $key) => collect($values) ->map(fn (string $value): array => [ 'key' => $key, 'value' => $value, ]), ) ->values() ->all(); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Http/Api/Relay/NimbusRelayRequest.php
src/Http/Api/Relay/NimbusRelayRequest.php
<?php namespace Sunchayn\Nimbus\Http\Api\Relay; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; class NimbusRelayRequest extends FormRequest { /** * @return array<string, string|object|array<array-key, string|object>> */ public function rules(): array { return [ 'method' => 'required', 'endpoint' => 'required', 'authorization' => 'sometimes|array', 'authorization.type' => ['required_with:authorization', Rule::in(AuthorizationTypeEnum::cases())], 'authorization.value' => 'sometimes', 'body' => 'sometimes', 'headers' => 'sometimes', 'headers.*.key' => 'required|string', 'headers.*.value' => 'required', ]; } /** * @return array<string, mixed> */ public function getBody(): array { $body = $this->validated('body') && filled($this->validated('body')) ? $this->validated('body') : []; return is_string($body) ? json_decode($body, true) : $body; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Http/Api/Relay/NimbusRelayController.php
src/Http/Api/Relay/NimbusRelayController.php
<?php namespace Sunchayn\Nimbus\Http\Api\Relay; use Illuminate\Http\Resources\Json\JsonResource; use Sunchayn\Nimbus\Modules\Relay\Actions\RequestRelayAction; use Sunchayn\Nimbus\Modules\Relay\DataTransferObjects\RequestRelayData; /** * Relays the Execution of HTTP requests with authorization and returns structured response data. * * A relay endpoint is needed to access HTTP Only cookies, * and deal with Laravel specific details for response/request life-cycle. */ class NimbusRelayController { public function __invoke( NimbusRelayRequest $nimbusRelayRequest, RequestRelayAction $requestRelayAction, ): JsonResource { $relayedRequestResponseData = $requestRelayAction ->execute( RequestRelayData::fromRelayApiRequest($nimbusRelayRequest), ); return RelayResponseResource::make($relayedRequestResponseData); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/IntellisenseProviders/DumpValueTypeIntellisense.php
src/IntellisenseProviders/DumpValueTypeIntellisense.php
<?php namespace Sunchayn\Nimbus\IntellisenseProviders; use Illuminate\Support\Str; use RuntimeException; use Sunchayn\Nimbus\IntellisenseProviders\Contracts\IntellisenseContract; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\Enums\DumpValueTypeEnum; /** * Generates TypeScript types for dump value types from the backend enum. */ class DumpValueTypeIntellisense implements IntellisenseContract { public const STUB = 'dump-value-types.ts.stub'; public function getTargetFileName(): string { return Str::remove('.stub', self::STUB); } public function generate(): string { $enumCases = []; foreach (DumpValueTypeEnum::cases() as $case) { $enumCases[] = sprintf(" %s = '%s',", $case->name, $case->value); } $enumContent = implode("\n", $enumCases); return $this->replaceStubContent($enumContent); } private function replaceStubContent(string $enumList): string { $stubFile = file_get_contents(__DIR__.'/stubs/'.self::STUB) ?: throw new RuntimeException('Cannot read stub file.'); return str_replace('{{ content }}', rtrim($enumList), $stubFile); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/IntellisenseProviders/AuthorizationTypeIntellisense.php
src/IntellisenseProviders/AuthorizationTypeIntellisense.php
<?php namespace Sunchayn\Nimbus\IntellisenseProviders; use Illuminate\Support\Str; use RuntimeException; use Sunchayn\Nimbus\IntellisenseProviders\Contracts\IntellisenseContract; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; /** * Generates TypeScript types for authorization types from the backend enum. */ class AuthorizationTypeIntellisense implements IntellisenseContract { public const STUB = 'authorization-types.ts.stub'; public function getTargetFileName(): string { return Str::remove('.stub', self::STUB); } public function generate(): string { $enumCases = []; foreach (AuthorizationTypeEnum::cases() as $case) { $enumCases[] = sprintf(" %s = '%s',", $case->name, $case->value); } $enumContent = implode("\n", $enumCases); return $this->replaceStubContent($enumContent); } private function replaceStubContent(string $enumList): string { $stubFile = file_get_contents(__DIR__.'/stubs/'.self::STUB) ?: throw new RuntimeException('Cannot read stub file.'); return str_replace('{{ content }}', rtrim($enumList), $stubFile); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/IntellisenseProviders/RandomValueGeneratorIntellisense.php
src/IntellisenseProviders/RandomValueGeneratorIntellisense.php
<?php namespace Sunchayn\Nimbus\IntellisenseProviders; use Illuminate\Support\Str; use RuntimeException; use Sunchayn\Nimbus\IntellisenseProviders\Contracts\IntellisenseContract; use Sunchayn\Nimbus\Modules\Config\GlobalHeaderGeneratorTypeEnum; /** * Generates TypeScript types for random value generator types from the backend enum. */ class RandomValueGeneratorIntellisense implements IntellisenseContract { public const STUB = 'global-request-types.ts.stub'; public function getTargetFileName(): string { return Str::remove('.stub', self::STUB); } public function generate(): string { $enumCases = []; foreach (GlobalHeaderGeneratorTypeEnum::cases() as $case) { $enumCases[] = sprintf(" %s = '%s',", $case->name, $case->value); } $enumContent = implode("\n", $enumCases); return $this->replaceStubContent($enumContent); } private function replaceStubContent(string $enumList): string { $stubFile = file_get_contents(__DIR__.'/stubs/'.self::STUB) ?: throw new RuntimeException('Cannot read stub file.'); return str_replace('{{ content }}', rtrim($enumList), $stubFile); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/IntellisenseProviders/Contracts/IntellisenseContract.php
src/IntellisenseProviders/Contracts/IntellisenseContract.php
<?php namespace Sunchayn\Nimbus\IntellisenseProviders\Contracts; /** * Contract for intellisense generators that create TypeScript types. * * Each intellisense generator is responsible for converting backend data structures * into frontend TypeScript definitions for better type safety and developer experience. */ interface IntellisenseContract { /** * Returns the target filename for the generated intellisense file. * * The filename should be descriptive and follow TypeScript naming conventions. */ public function getTargetFileName(): string; /** * Generates the intellisense content as TypeScript code. * * The generated content should be valid TypeScript that can be imported * and used in frontend applications for type safety and autocompletion. */ public function generate(): string; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/Collections/Ruleset.php
src/Modules/Schemas/Collections/Ruleset.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\Collections; use Illuminate\Support\Collection; use Illuminate\Validation\Rule; use InvalidArgumentException; use Sunchayn\Nimbus\Modules\Schemas\Enums\RulesFieldType; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\FieldPath; /** * Represents a normalized set of Laravel validation rules. * * Handles conversion from various input formats (string, array) to a consistent * array format for processing throughout the schema building pipeline. * * @example * Input: "required|string|max:255" * Output: ["required", "string", "max:255"] * * @phpstan-type NormalizedRulesShape array<array-key, string|Rule> * * @extends Collection<string, NormalizedRulesShape> */ class Ruleset extends Collection { public function __construct($items = []) { parent::__construct($items); if (! $this->every(fn (mixed $item): true => is_array($item))) { // @phpstan-ignore-line this is a runtime check. throw new InvalidArgumentException('Ruleset items must be an array'); } } /** * Creates a Ruleset from various input formats. * * Handles both string format ("required|string|max:255") and array format * to ensure consistent processing throughout the schema builder. * * @param array<string, mixed> $rules */ public static function fromLaravelRules(array $rules): self { $normalized = array_map( function (mixed $fieldRules): array { // Convert pipe-separated string to array if (is_string($fieldRules)) { return array_values( array_filter(explode('|', $fieldRules)), ); } // Return array as-is if (is_array($fieldRules)) { return $fieldRules; } // Wrap objets in arrays, these can be Rules. if (is_object($fieldRules)) { return [$fieldRules]; } // If unknown, return an empty array. return []; }, $rules, ); return new self($normalized); } public function whereRootField(): self { return $this->where(fn (mixed $_, string $field): bool => FieldPath::fromString($field)->type === RulesFieldType::ROOT); } public function whereDotNotationField(): self { return $this->where(function (mixed $_, string $field): bool { $fieldPath = FieldPath::fromString($field); return $fieldPath->type === RulesFieldType::DOT_NOTATION; }); } public function whereArrayOfPrimitivesField(): self { return $this->where(fn (mixed $_, string $field): bool => FieldPath::fromString($field)->type === RulesFieldType::ARRAY_OF_PRIMITIVES); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/RulesMapper/RuleToSchemaMapper.php
src/Modules/Schemas/RulesMapper/RuleToSchemaMapper.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\RulesMapper; use Illuminate\Validation\Rules\Enum; use Illuminate\Validation\Rules\In; use Illuminate\Validation\ValidationRuleParser; use Sunchayn\Nimbus\Modules\Schemas\RulesMapper\Processors\EnumRuleProcessor; use Sunchayn\Nimbus\Modules\Schemas\RulesMapper\Processors\InRuleProcessor; /** * Converts Laravel validation rules into JSON Schema property definitions. * * @phpstan-import-type NormalizedRulesShape from \Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset * @phpstan-import-type SchemaPropertyTypesShape from \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty * @phpstan-import-type SchemaPropertyFormatsShape from \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty * @phpstan-import-type SchemaPropertyEnumShape from \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty */ class RuleToSchemaMapper { /** * Converts an array of Laravel validation rules into schema property data. * * Laravel's validation rules are processed sequentially, with later rules * potentially overriding earlier ones (e.g., 'string' then 'email'). * * @param NormalizedRulesShape $rules * @return array{ * type: SchemaPropertyTypesShape, * required: bool, * format: SchemaPropertyFormatsShape|null, * enum: SchemaPropertyEnumShape|null, * minimum: ?int, * maximum: ?int, * } */ public function convertRulesToBaseSchemaPropertyMetadata(array $rules): array { $shape = [ 'type' => 'string', 'required' => false, 'format' => null, 'enum' => null, 'minimum' => null, 'maximum' => null, ]; foreach ($rules as $rule) { $ruleSpecificUpdates = $this->processRule($rule); // Amend the original shape to add the changes specific to the rule in hand. $shape = array_merge($shape, $ruleSpecificUpdates); } return $shape; } /** * Processes individual validation rules and returns the changes to apply. * * @return array{}|array{ * type?: SchemaPropertyTypesShape, * format?: SchemaPropertyFormatsShape, * enum?: SchemaPropertyEnumShape|null, * minimum?: int, * maximum?: int, * } */ private function processRule(mixed $rule): array { if (is_object($rule)) { return $this->processObjectRule($rule); } if (! is_scalar($rule)) { return []; } [$name, $params] = ValidationRuleParser::parse((string) $rule); $ruleName = strtolower($name); return match ($ruleName) { 'required' => ['required' => true], 'string' => ['type' => 'string'], 'integer' => ['type' => 'integer'], 'numeric' => ['type' => 'number'], 'boolean' => ['type' => 'boolean'], 'array' => ['type' => 'array'], 'email' => $this->setFormat('email'), 'uuid' => $this->setFormat('uuid'), 'date' => $this->setFormat('date-time'), 'in' => $this->setEnum($params), 'min' => ['minimum' => $params[0] ?? null], 'max' => ['maximum' => $params[0] ?? null], 'size' => ['minimum' => $params[0] ?? null, 'maximum' => $params[0] ?? null], default => [], }; } /** * Handles custom validation rule objects. * * Analyzes specific rule types like Enum and In to extract constraint * information, falling back to string type for unknown rules. * * @return array{type: 'integer'|'string', enum?: SchemaPropertyEnumShape|null} */ private function processObjectRule(object $rule): array { return match (true) { $rule instanceof Enum => EnumRuleProcessor::process($rule), $rule instanceof In => InRuleProcessor::process($rule), default => ['type' => 'string'], }; } /** * Sets the format specification for the property. * * @param SchemaPropertyFormatsShape $format * @return array{format: SchemaPropertyFormatsShape, type?: 'string'} */ private function setFormat(string $format): array { $result = ['format' => $format]; // Email, UUID, and date-time are all string-based formats in JSON Schema if (in_array($format, ['email', 'uuid', 'date-time'], true)) { $result['type'] = 'string'; } return $result; } /** * Sets enum constraints from validation rule parameters. * * The 'in' rule provides explicit allowed values that must be preserved * in the schema for proper validation. * * @param array<int, mixed> $params * @return array{enum: SchemaPropertyEnumShape}|array{} */ private function setEnum(array $params): array { if ($params === []) { return []; } return ['enum' => $params]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/RulesMapper/Processors/EnumRuleProcessor.php
src/Modules/Schemas/RulesMapper/Processors/EnumRuleProcessor.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\RulesMapper\Processors; use BackedEnum; use Illuminate\Validation\Rules\Enum; use UnitEnum; /** * Processes `Enum` validation rules to extract enum values for schema generation. * * @phpstan-import-type SchemaPropertyEnumShape from \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty */ class EnumRuleProcessor { /** * @return array{type: 'string', enum: SchemaPropertyEnumShape|null} */ public static function process(Enum $rule): array { /** @var class-string<UnitEnum> $enumClass */ $enumClass = invade($rule)->type; // @phpstan-ignore-line if (! enum_exists($enumClass)) { return ['type' => 'string', 'enum' => null]; } $values = array_map( fn (UnitEnum|BackedEnum $enum): int|string => $enum->value ?? $enum->name, $enumClass::cases() ); if ($values === []) { return ['type' => 'string', 'enum' => null]; } return ['type' => 'string', 'enum' => $values]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/RulesMapper/Processors/InRuleProcessor.php
src/Modules/Schemas/RulesMapper/Processors/InRuleProcessor.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\RulesMapper\Processors; use BackedEnum; use Illuminate\Validation\Rules\In; use UnitEnum; /** * Processes `In` validation rules to extract allowed values for schema generation. * * @phpstan-import-type SchemaPropertyTypesShape from \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty * @phpstan-import-type SchemaPropertyEnumShape from \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty */ class InRuleProcessor { /** * @return array{type: 'string'|'integer', enum: SchemaPropertyEnumShape|null} */ public static function process(In $in): array { /** @var array<array-key, scalar|object> $rawValues */ $rawValues = invade($in)->values; // @phpstan-ignore-line // Normalize the values into primitives. $values = array_map( fn (bool|float|int|object|string $value): float|bool|int|string|null => match (true) { is_scalar($value) => $value, $value instanceof BackedEnum => $value->value, $value instanceof UnitEnum => $value->name, default => null, }, $rawValues, ); /** @var array<array-key, scalar> $values */ $values = array_values( array_filter($values), // <- Removes null values. ); if (empty($values)) { return ['type' => 'string', 'enum' => null]; } $identityValue = $values[0]; $type = match (true) { is_int($identityValue) => 'integer', default => 'string', }; return ['type' => $type, 'enum' => $values]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/Builders/SchemaBuilder.php
src/Modules/Schemas/Builders/SchemaBuilder.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\Builders; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; use Sunchayn\Nimbus\Modules\Schemas\Enums\RulesFieldType; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\FieldPath; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\PathSegment; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; /** * Converts Laravel validation rules into JSON Schema structures. * * Handles three main patterns: * 1. Root fields: "name" => "required|string" * 2. Nested objects: "user.profile.name" => "required|string" * 3. Arrays: "tags.*" => "string" or "users.*.email" => "email" * * The builder processes rules in a specific order to ensure parent structures * exist before children are added. * * @phpstan-import-type NormalizedRulesShape from Ruleset */ class SchemaBuilder { public function __construct( private readonly PropertyBuilder $propertyBuilder, ) {} public function buildSchemaFromRuleset( Ruleset $ruleset, ?RulesExtractionError $rulesExtractionError = null ): Schema { $properties = $this->buildProperties($ruleset); return new Schema( properties: $properties, extractionError: $rulesExtractionError, ); } /** * @return array<string, SchemaProperty> */ private function buildProperties(Ruleset $ruleset): array { return $this // Process in order: root fields → nested objects → arrays // This ensures parent structures exist before we add children ->sortRulesByProcessingOrder($ruleset) ->reduce( function (array $properties, array $rules, string $fieldName): array { $fieldPath = FieldPath::fromString($fieldName); if ($fieldPath->type === RulesFieldType::ARRAY_OF_PRIMITIVES) { return $this->addSimpleArrayProperty($fieldPath, $rules, $properties); } if ($fieldPath->type === RulesFieldType::DOT_NOTATION) { return $this->addDotNotationStructure($fieldPath, $rules, $properties); } // Builds a root-level property (e.g., "name", "email"). $properties[$fieldName] = $this->propertyBuilder->buildPropertyFromRules($fieldName, $rules); return $properties; }, initial: [], ); } /** * Sorts rules by processing order: root → nested → wildcards. */ private function sortRulesByProcessingOrder(Ruleset $ruleset): Ruleset { return $ruleset ->whereRootField() ->merge( $ruleset ->whereDotNotationField() // Sort nested fields by parent fields first, // this way we make sure we create the parent schema first to keep things simple (relatively). ->sortBy(fn (array $rules, string $field): int => strlen($field)) ) ->merge( $ruleset->whereArrayOfPrimitivesField(), ); } /** * Adds a simple array property (e.g., "tags.*" => "string"). * * @param array<string, SchemaProperty> $properties * @param NormalizedRulesShape $rules * @return array<string, SchemaProperty> */ private function addSimpleArrayProperty(FieldPath $fieldPath, array $rules, array $properties): array { $arrayName = Str::replaceLast('.*', '', $fieldPath->value); // Get existing property to preserve 'required' status $existingProperty = $properties[$arrayName] ?? null; // Build the item schema (primitive type like string, integer, etc.) $schemaProperty = $this->propertyBuilder->buildPropertyFromRules( // Name the items after their array's name but in singular form. // It is an array of items, e.g. Tags -> each item is a tag. // Note: this also helps to make the payload generator more realistic in the FE. field: Str::singular($arrayName), rules: $rules, ); $properties[$arrayName] = new SchemaProperty( name: $arrayName, type: 'array', required: $existingProperty->required ?? false, itemsSchema: $schemaProperty, ); return $properties; } /** * Adds a dot notation structure (objects, arrays, or both). * * Handles both simple dot notation and complex array patterns: * - "user.profile.name" → nested objects * - "users.*.email" → array of objects with email property * - "company.teams.*.members.*.name" → deeply nested arrays * * @param array<string, SchemaProperty> $properties * @param NormalizedRulesShape $rules * @return array<string, SchemaProperty> */ private function addDotNotationStructure(FieldPath $fieldPath, array $rules, array $properties): array { $rootField = $fieldPath->getRootField(); $rootProperty = $properties[$rootField] ?? $this->createEmptyObject($rootField); $properties[$rootField] = $this->buildNestedStructure( $rootProperty, segments: $this->parsePathSegments($fieldPath->value), rules: $rules ); return $properties; } /** * Parses a field path into typed segments. * * Example: "company.teams.*.members.*.name" * Returns: * [ * new PathSegment(value: 'teams'), * new PathSegment(value: '*'), * new PathSegment(value: 'members'), * new PathSegment(value: '*'), * new PathSegment(value: 'name', isLeaf: true), * ] * * @return array<array-key, PathSegment> */ private function parsePathSegments(string $path): array { $parts = explode('.', $path); // Remove root field since we handle it separately. array_shift($parts); $leafIndex = count($parts) - 1; return Arr::map( $parts, fn (string $part, $index): PathSegment => new PathSegment(value: $part, isLeaf: $index === $leafIndex) ); } /** * Recursively builds nested array/object structures. * * @param NormalizedRulesShape $rules * @param PathSegment[] $segments */ private function buildNestedStructure( SchemaProperty $schemaProperty, array $segments, array $rules ): SchemaProperty { if ($segments === []) { return $schemaProperty; } $pathSegment = array_shift($segments); if ($pathSegment->isArray()) { return $this->convertPropertyToArray($schemaProperty, $segments, $rules); } return $this->addPropertyToStructure($schemaProperty, $pathSegment, $segments, $rules); } /** * Converts a property to an array type and processes remaining segments as array items. * * @param NormalizedRulesShape $rules * @param PathSegment[] $segments */ private function convertPropertyToArray( SchemaProperty $schemaProperty, array $segments, array $rules ): SchemaProperty { $itemObject = $schemaProperty->itemsSchema ?? $this->createEmptyObject(name: 'item'); // Build the item structure from remaining segments. $itemSchema = $this->buildNestedStructure($itemObject, $segments, $rules); return new SchemaProperty( name: $schemaProperty->name, type: 'array', required: $schemaProperty->required, itemsSchema: $itemSchema, ); } /** * Adds a property to the current structure (object). * * @param NormalizedRulesShape $rules * @param PathSegment[] $remainingSegments */ private function addPropertyToStructure( SchemaProperty $schemaProperty, PathSegment $pathSegment, array $remainingSegments, array $rules ): SchemaProperty { $propertyName = $pathSegment->value; $existingSchema = $schemaProperty->propertiesSchema ?? new Schema([]); /** @var Collection<string, SchemaProperty> $properties */ $properties = Collection::make($existingSchema->properties)->keyBy('name'); // If this is a leaf, build the final property with rules. if ($pathSegment->isLeaf) { $newProperty = $this->propertyBuilder->buildPropertyFromRules($propertyName, $rules); $properties->put($newProperty->name, $newProperty); return $this->rebuildObjectPropertyWithNewSchema($schemaProperty, $properties->all()); } // Otherwise, create/get intermediate object and recurse. $existingProperty = $properties->get($propertyName); $intermediateProperty = $existingProperty ?? $this->createEmptyObject($propertyName); $updatedProperty = $this->buildNestedStructure($intermediateProperty, $remainingSegments, $rules); $properties->put($updatedProperty->name, $updatedProperty); return $this->rebuildObjectPropertyWithNewSchema($schemaProperty, $properties->all()); } /** * Rebuilds a property with updated child properties. * * @param SchemaProperty[] $properties */ private function rebuildObjectPropertyWithNewSchema( SchemaProperty $schemaProperty, array $properties ): SchemaProperty { return new SchemaProperty( name: $schemaProperty->name, type: 'object', required: $schemaProperty->required, format: $schemaProperty->format, enum: $schemaProperty->enum, propertiesSchema: new Schema($properties), ); } /** * Creates an empty object property. */ private function createEmptyObject(string $name): SchemaProperty { return new SchemaProperty( name: $name, type: 'object', required: false, propertiesSchema: new Schema([]) ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/Builders/PropertyBuilder.php
src/Modules/Schemas/Builders/PropertyBuilder.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\Builders; use Sunchayn\Nimbus\Modules\Schemas\RulesMapper\RuleToSchemaMapper; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; /** * Converts Laravel validation rules into individual schema properties. * * Maps Laravel rule strings like "required|string|max:255" to JSON Schema properties * with proper type, format, and validation constraints. * * @example * Input: "email" field with "required|email" rules * Output: SchemaProperty with type="string", format="email", required=true * * @phpstan-import-type NormalizedRulesShape from \Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset * @phpstan-import-type SchemaPropertyFormatsShape from SchemaProperty */ class PropertyBuilder { public function __construct( private readonly RuleToSchemaMapper $ruleToSchemaMapper, ) {} /** * @param NormalizedRulesShape $rules */ public function buildPropertyFromRules(string $field, array $rules): SchemaProperty { $schemaMetadata = $this->ruleToSchemaMapper->convertRulesToBaseSchemaPropertyMetadata($rules); return new SchemaProperty( name: $field, type: $schemaMetadata['type'], required: $schemaMetadata['required'], format: $this->extractFormat($rules), enum: $schemaMetadata['enum'] ?? null, minimum: $schemaMetadata['minimum'], maximum: $schemaMetadata['maximum'], ); } /** * @param NormalizedRulesShape $rules * @return SchemaPropertyFormatsShape|null */ private function extractFormat(array $rules): ?string { foreach ($rules as $rule) { if (! is_string($rule)) { continue; } $format = $this->detectFormatFromRule($rule); if ($format !== null) { return $format; } } return null; } /** * @return SchemaPropertyFormatsShape|null */ private function detectFormatFromRule(string $rule): ?string { return match ($rule) { 'email' => 'email', 'uuid' => 'uuid', 'date' => 'date-time', default => null, }; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/Enums/RulesFieldType.php
src/Modules/Schemas/Enums/RulesFieldType.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\Enums; enum RulesFieldType { /** @example email */ case ROOT; /** @example person.email */ /** @example persons.*.email */ case DOT_NOTATION; /** @example items.* */ case ARRAY_OF_PRIMITIVES; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/ValueObjects/FieldPath.php
src/Modules/Schemas/ValueObjects/FieldPath.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\ValueObjects; use Sunchayn\Nimbus\Modules\Schemas\Enums\RulesFieldType; /** * Represents a field path in Laravel validation rules. * * Handles parsing, validation, and type detection for field paths * like "user.profile.age" or "tags.*". */ readonly class FieldPath { /** @var string[] */ public array $segments; public function __construct( public string $value, public RulesFieldType $type, ) { $this->segments = explode('.', $this->value); } public static function fromString(string $field): self { $type = match (true) { str_ends_with($field, '.*') => RulesFieldType::ARRAY_OF_PRIMITIVES, str_contains($field, '.') => RulesFieldType::DOT_NOTATION, default => RulesFieldType::ROOT, }; return new self( value: $field, type: $type, ); } public function getRootField(): string { return $this->segments[0]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/ValueObjects/Schema.php
src/Modules/Schemas/ValueObjects/Schema.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\ValueObjects; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Arr; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; /** * @phpstan-import-type SchemaPropertyShape from SchemaProperty * * @phpstan-type SchemaShape array{ * '$schema': 'https://json-schema.org/draft/2020-12/schema', * type: 'object', * properties: array<string, SchemaPropertyShape>, * required: string[], * additionalProperties: false, * } * * @implements Arrayable<string, SchemaPropertyShape> */ class Schema implements Arrayable { /** @var SchemaProperty[] */ public readonly array $properties; /** * @param SchemaProperty[] $properties */ public function __construct( array $properties, public readonly ?RulesExtractionError $extractionError = null, ) { $this->properties = array_values($properties); } public static function empty(): self { return new self( properties: [], ); } public function isEmpty(): bool { return $this->properties === []; } /** * @return string[] */ public function getRequiredProperties(): array { return collect($this->properties) ->filter(fn (SchemaProperty $schemaProperty): bool => $schemaProperty->required) ->map(fn (SchemaProperty $schemaProperty): string => $schemaProperty->name) ->values() ->all(); } public function toArray(): array { return Arr::mapWithKeys( $this->properties, fn (SchemaProperty $schemaProperty): array => [ $schemaProperty->name => $schemaProperty->toArray(), ] ); } /** * Converts this schema to proper JSON Schema format. * * Generates a complete JSON Schema object with all necessary metadata * that can be used directly by JSON Schema validators and editors. * * @return SchemaShape */ public function toJsonSchema(): array { return [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => $this->toArray(), 'required' => $this->getRequiredProperties(), 'additionalProperties' => false, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/ValueObjects/SchemaProperty.php
src/Modules/Schemas/ValueObjects/SchemaProperty.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\ValueObjects; use Illuminate\Support\Arr; // TODO [Refactor] Refactor this into specialized classes with proper support for JSONSchema. // E.g. IntegerSchemaProperty, ObjectSchemaProperty, etc. // Most likely its own package. /** * @phpstan-type SchemaPropertyTypesShape 'number'|'integer'|'array'|'object'|'string'|'boolean' * @phpstan-type SchemaPropertyFormatsShape 'uuid'|'email'|'date-time' * @phpstan-type SchemaPropertyEnumShape array<array-key, scalar> * TODO [Documentation] Figure out how to annotate the `items` and `properties` recursively.` * @phpstan-type SchemaPropertyShape array{ * type: SchemaPropertyTypesShape, * x-name: string, * x-required: bool, * format?: SchemaPropertyFormatsShape, * enum?: SchemaPropertyEnumShape, * items?: array<array-key, mixed>, * properties?: array<string, array<array-key, mixed>>, * required?: bool, * minLength?: int, * minimum?: int, * maxLength?: int, * maximum?: int, * } */ class SchemaProperty { /** * @param SchemaPropertyTypesShape $type * @param SchemaPropertyFormatsShape|null $format * @param SchemaPropertyEnumShape|null $enum Allowed enum values. */ public function __construct( public readonly string $name, public readonly string $type = 'string', // <- Make this an enum. public readonly bool $required = false, public readonly ?string $format = null, // <- Make this an enum. public readonly ?array $enum = null, public readonly ?SchemaProperty $itemsSchema = null, // <- For arrays public readonly ?Schema $propertiesSchema = null, // <- For objects public readonly ?int $minimum = null, public readonly ?int $maximum = null, ) {} /** * @return SchemaPropertyShape */ public function toArray(): array { $result = [ 'type' => $this->type, ]; if ($this->format !== null) { $result['format'] = $this->format; } if ($this->enum !== null && $this->enum !== []) { $result['enum'] = $this->enum; } if ($this->itemsSchema instanceof \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty) { $result['items'] = $this->itemsSchema->toArray(); } if ($this->propertiesSchema instanceof \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema) { $result['properties'] = Arr::mapWithKeys( $this->propertiesSchema->properties, fn (SchemaProperty $schemaProperty): array => [$schemaProperty->name => $schemaProperty->toArray()] ); $result['required'] = $this->propertiesSchema->getRequiredProperties(); } if ($this->minimum !== null && in_array($this->type, ['string', 'integer', 'number'])) { $minPropertyName = $this->type === 'string' ? 'minLength' : 'minimum'; $result[$minPropertyName] = $this->minimum; } if ($this->maximum !== null && in_array($this->type, ['string', 'integer', 'number'])) { $minPropertyName = $this->type === 'string' ? 'maxLength' : 'maximum'; $result[$minPropertyName] = $this->maximum; } /** * @var SchemaPropertyShape $final PHPStan couldn't infer the correct type when building the array incrementally. */ $final = array_merge( $result, // To make dealing with props easier, for instance, for payload generation. // We also add a couple of custom properties to the schema. $this->getCustomProperties(), ); return $final; } /** * @return array{ * x-name: string, * x-required: bool, * } */ private function getCustomProperties(): array { return [ // Keep in mind: the `required` property is reserved for objects to tell what properties are required in the object. // this custom property, on the other hand, is to tell if the current property is required or not. 'x-required' => $this->required, 'x-name' => $this->name, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Schemas/ValueObjects/PathSegment.php
src/Modules/Schemas/ValueObjects/PathSegment.php
<?php namespace Sunchayn\Nimbus\Modules\Schemas\ValueObjects; class PathSegment { public function __construct( public readonly string $value, public readonly bool $isLeaf = true, ) {} public function isArray(): bool { return $this->value === '*'; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Config/GlobalHeaderGeneratorTypeEnum.php
src/Modules/Config/GlobalHeaderGeneratorTypeEnum.php
<?php namespace Sunchayn\Nimbus\Modules\Config; /** * Defines available random value generation strategies for global headers.. */ enum GlobalHeaderGeneratorTypeEnum: string { case Uuid = 'UUID'; case Email = 'Email'; case String = 'String'; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Config/Exceptions/MisconfiguredValueException.php
src/Modules/Config/Exceptions/MisconfiguredValueException.php
<?php namespace Sunchayn\Nimbus\Modules\Config\Exceptions; use Exception; use Sunchayn\Nimbus\Modules\Relay\Authorization\Contracts\SpecialAuthenticationInjectorContract; class MisconfiguredValueException extends Exception { public const SPECIAL_AUTHENTICATION_INJECTOR = 1; public const MISSING_DEPENDENCIES = 2; public const INVALID_GUARD_INJECTOR_COMBINATION = 3; public static function becauseSpecialAuthenticationInjectorIsInvalid(): self { return new self( message: 'The config value for `nimbus.auth.special.injector` MUST be a class string of type <'.SpecialAuthenticationInjectorContract::class.'>', code: self::SPECIAL_AUTHENTICATION_INJECTOR, ); } public static function becauseOfMissingDependency(string $dependency): self { return new self( message: sprintf('The config value for `nimbus.auth.special.injector` is an injector that requires the following dependency <%s>', $dependency), code: self::MISSING_DEPENDENCIES, ); } /** * @param non-empty-string $suggestion */ public static function becauseOfInvalidGuardInjectorCombination(string $suggestion): self { return new self( message: "The config value for `nimbus.auth.guard` doesn't work with the selected injector. ".$suggestion, code: self::INVALID_GUARD_INJECTOR_COMBINATION, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/AuthorizationCredentials.php
src/Modules/Relay/Authorization/AuthorizationCredentials.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization; readonly class AuthorizationCredentials { /** * @param string|array{username: string, password: string}|null $value */ public function __construct( public AuthorizationTypeEnum $type, public string|array|null $value, ) {} public static function none(): self { return new self( type: AuthorizationTypeEnum::None, value: null, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/AuthorizationTypeEnum.php
src/Modules/Relay/Authorization/AuthorizationTypeEnum.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization; /** * Authorization types supported by the relay system. */ enum AuthorizationTypeEnum: string { case None = 'none'; case CurrentUser = 'current-user'; case Bearer = 'bearer'; case Basic = 'basic'; case Impersonate = 'impersonate'; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Exceptions/InvalidAuthorizationValueException.php
src/Modules/Relay/Authorization/Exceptions/InvalidAuthorizationValueException.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Exceptions; use RuntimeException; class InvalidAuthorizationValueException extends RuntimeException { public const BEARER_TOKEN_IS_NOT_STRING = 1; public const BASIC_AUTH_SHAPE_IS_INVALID = 2; public const USER_IS_NOT_FOUND = 3; public static function becauseBearerTokenValueIsNotString(): self { return new self( message: 'Bearer token value is not a string.', code: self::BEARER_TOKEN_IS_NOT_STRING, ); } public static function becauseBasicAuthCredentialsAreInvalid(): self { return new self( message: 'Basic Auth credentials are invalid. Expects array{username: string, password: string}.', code: self::BASIC_AUTH_SHAPE_IS_INVALID, ); } public static function becauseUserIsNotFound(): self { return new self( message: "User ID didn't resolve to a user to impersonate.", code: self::USER_IS_NOT_FOUND, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Contracts/SpecialAuthenticationInjectorContract.php
src/Modules/Relay/Authorization/Contracts/SpecialAuthenticationInjectorContract.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Contracts; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Http\Client\PendingRequest; /** * Contract for injecting authentication context into relayed HTTP requests. * * Implementations of this interface define how an authenticated user should be * attached to a relayed request. For example, this may involve setting a bearer token, * attaching a session cookie, or adding custom authentication headers. */ interface SpecialAuthenticationInjectorContract { public function attach( PendingRequest $pendingRequest, Authenticatable $authenticatable ): PendingRequest; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Concerns/UsesSpecialAuthenticationInjector.php
src/Modules/Relay/Authorization/Concerns/UsesSpecialAuthenticationInjector.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Concerns; use Illuminate\Container\Container; use Illuminate\Contracts\Config\Repository; use Illuminate\Contracts\Container\BindingResolutionException; use Sunchayn\Nimbus\Modules\Config\Exceptions\MisconfiguredValueException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Contracts\SpecialAuthenticationInjectorContract; trait UsesSpecialAuthenticationInjector { /** * @throws BindingResolutionException * @throws MisconfiguredValueException */ public function getInjector(Container $container, Repository $configRepository): SpecialAuthenticationInjectorContract { /** @var ?class-string $injectorClass */ $injectorClass = $configRepository->get('nimbus.auth.special.injector'); if ($injectorClass === null) { throw MisconfiguredValueException::becauseSpecialAuthenticationInjectorIsInvalid(); } $injector = $container->make($injectorClass); if (! $injector instanceof SpecialAuthenticationInjectorContract) { throw MisconfiguredValueException::becauseSpecialAuthenticationInjectorIsInvalid(); } return $injector; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Injectors/RememberMeCookieInjector.php
src/Modules/Relay/Authorization/Injectors/RememberMeCookieInjector.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Injectors; use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Container\Container; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\StatefulGuard; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Cookie\CookieValuePrefix; use Illuminate\Encryption\Encrypter; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Request; use Illuminate\Support\Str; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Sunchayn\Nimbus\Modules\Config\Exceptions\MisconfiguredValueException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Contracts\SpecialAuthenticationInjectorContract; class RememberMeCookieInjector implements SpecialAuthenticationInjectorContract { private UserProvider $userProvider; private Guard $authGuard; private Encrypter $encrypter; /** * @throws NotFoundExceptionInterface * @throws ContainerExceptionInterface * @throws MisconfiguredValueException */ public function __construct( private readonly Request $relayRequest, private readonly Container $container, ConfigRepository $configRepository, ) { $this->encrypter = $this->container->get('encrypter'); $this->authGuard = $this->container->get('auth')->guard( $configRepository->get('nimbus.auth.guard'), ); if (! $this->authGuard instanceof StatefulGuard) { throw MisconfiguredValueException::becauseOfInvalidGuardInjectorCombination('Please use a stateful guard.'); } if (! method_exists($this->authGuard, 'getProvider')) { throw MisconfiguredValueException::becauseOfInvalidGuardInjectorCombination('Please use a guard that exposes a provider.'); } $this->userProvider = $this->authGuard->getProvider(); } public function attach( PendingRequest $pendingRequest, Authenticatable $authenticatable, ): PendingRequest { if ($this->forwardRememberMeCookie($pendingRequest, $authenticatable)) { return $pendingRequest; } // Generate authentication artifacts for the user. $recallerToken = $this->generateRecallerTokenFor($authenticatable); return $pendingRequest->withCookies( [ $this->authGuard->getRecallerName() => $recallerToken, ], // Note: This implementation assumes same-domain requests. Cross-domain // impersonation would require additional configuration for cookie domains. $this->relayRequest->getHost(), ); } private function forwardRememberMeCookie(PendingRequest $pendingRequest, Authenticatable $authenticatable): bool { if ($authenticatable->getAuthIdentifier() !== $this->relayRequest->user()?->getAuthIdentifier()) { return false; } $recallerCookieKey = $this->authGuard->getRecallerName(); $recallerCookieToForward = $this->relayRequest->cookies->get($recallerCookieKey); if (! $recallerCookieToForward) { return false; } $pendingRequest->withCookies( [ $recallerCookieKey => $recallerCookieToForward, ], domain: $this->relayRequest->getHost(), ); return true; } /** * Generate authentication artifacts for the user. * * Creates a recaller cookie that will authenticate the target user * when the request reaches the target application. No session cookie * is needed since we're not forwarding the original session. */ private function generateRecallerTokenFor(Authenticatable $authenticatable): string { // Generate recaller token for "remember me" functionality $recallerToken = $authenticatable->getAuthIdentifier().'|'.$this->getRememberMeTokenFor($authenticatable).'|'.$authenticatable->getAuthPasswordName(); return $this->encrypter->encrypt( CookieValuePrefix::create($this->authGuard->getRecallerName(), $this->encrypter->getKey()).$recallerToken, false, ); } private function getRememberMeTokenFor(Authenticatable $authenticatable): string { $existentToken = $authenticatable->getRememberToken(); if (filled($existentToken)) { return $existentToken; } $newToken = hash('sha256', Str::random(60)); $this->userProvider->updateRememberToken($authenticatable, $newToken); return $newToken; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Injectors/TymonJwtTokenInjector.php
src/Modules/Relay/Authorization/Injectors/TymonJwtTokenInjector.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Injectors; use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Container\Container; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Guard; use Illuminate\Http\Client\PendingRequest; use Sunchayn\Nimbus\Modules\Config\Exceptions\MisconfiguredValueException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Contracts\SpecialAuthenticationInjectorContract; class TymonJwtTokenInjector implements SpecialAuthenticationInjectorContract { private Guard $guard; /** * @throws MisconfiguredValueException */ public function __construct( private readonly ConfigRepository $configRepository, private readonly Container $container, ) { if (! class_exists(\Tymon\JWTAuth\JWTGuard::class)) { throw MisconfiguredValueException::becauseOfMissingDependency(dependency: 'tymon/jwt-auth'); } $this->guard = $this ->container->make('auth') ->guard(name: $this->configRepository->get('nimbus.auth.guard')); if (! $this->guard instanceof \Tymon\JWTAuth\JWTGuard) { throw MisconfiguredValueException::becauseOfInvalidGuardInjectorCombination("Please use a `\Tymon\JWTAuth\JWTGuard` guard."); } } protected function getGuard(): Guard { return $this->guard; } public function attach( PendingRequest $pendingRequest, Authenticatable $authenticatable, ): PendingRequest { /** @var string $bearerToken */ // @phpstan-ignore-next-line The `JWTGuard` will indeed return the token here even though the contract annotates it as void. $bearerToken = $this->getGuard()->login($authenticatable); $pendingRequest->withToken( token: $bearerToken, ); return $pendingRequest; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Handlers/ImpersonateUserAuthorizationHandler.php
src/Modules/Relay/Authorization/Handlers/ImpersonateUserAuthorizationHandler.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers; use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Container\Container; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Http\Client\PendingRequest; use Sunchayn\Nimbus\Modules\Config\Exceptions\MisconfiguredValueException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Concerns\UsesSpecialAuthenticationInjector; use Sunchayn\Nimbus\Modules\Relay\Authorization\Exceptions\InvalidAuthorizationValueException; class ImpersonateUserAuthorizationHandler implements AuthorizationHandler { use UsesSpecialAuthenticationInjector; private UserProvider $userProvider; public function __construct( public readonly int $userId, private readonly Container $container, private readonly ConfigRepository $configRepository, ) { if ($userId <= 0) { throw InvalidAuthorizationValueException::becauseUserIsNotFound(); } $this->userProvider = $this ->container->get('auth') ->guard(name: config('nimbus.auth.guard')) ->getProvider(); } /** * @throws BindingResolutionException * @throws MisconfiguredValueException */ public function authorize(PendingRequest $pendingRequest): PendingRequest { $user = $this->userProvider->retrieveById($this->userId); if ($user === null) { throw InvalidAuthorizationValueException::becauseUserIsNotFound(); } return $this ->getInjector($this->container, $this->configRepository) ->attach($pendingRequest, $user); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Handlers/CurrentUserAuthorizationHandler.php
src/Modules/Relay/Authorization/Handlers/CurrentUserAuthorizationHandler.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers; use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Container\Container; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Request; use Illuminate\Session\SessionManager; use Illuminate\Session\Store; use Illuminate\Support\Arr; use Sunchayn\Nimbus\Modules\Relay\Authorization\Concerns\UsesSpecialAuthenticationInjector; /** * Authorization handler that forwards the current user's session cookies. * * This handler ensures the outbound request is authenticated as the current * Laravel user. It supports two modes: * - Directly from the current authenticated user on the relay request. * - Fallback to session cookie resolution when no user is bound to the request. */ class CurrentUserAuthorizationHandler implements AuthorizationHandler { use UsesSpecialAuthenticationInjector; private readonly UserProvider $userProvider; public function __construct( private readonly Request $relayRequest, private readonly Container $container, private readonly ConfigRepository $configRepository, ) { $this->userProvider = $this->resolveUserProvider(); } public function authorize(PendingRequest $pendingRequest): PendingRequest { $user = $this->getAuthenticatedUser(); if (! $user instanceof \Illuminate\Contracts\Auth\Authenticatable) { return $pendingRequest; } return $this ->getInjector($this->container, $this->configRepository) ->attach($pendingRequest, $user); } /** * Resolve the active user provider for the configured authentication guard. */ private function resolveUserProvider(): UserProvider { $authManager = $this->container->get('auth'); $guardName = $this->configRepository->get('nimbus.auth.guard'); return $authManager->guard($guardName)->getProvider(); } /** * Determine the currently authenticated user either from the relay request * or, if missing, by resolving from a valid Laravel session cookie. */ private function getAuthenticatedUser(): ?Authenticatable { return $this->relayRequest->user() ?? $this->getUserFromSession(); } /** * Attempt to retrieve the authenticated user from the Laravel session cookie. */ private function getUserFromSession(): ?Authenticatable { $sessionCookieName = $this->configRepository->get('session.cookie'); $sessionCookie = $this->relayRequest->cookies->get($sessionCookieName); if (! is_string($sessionCookie)) { return null; } /** @var Store $session */ $session = $this->container->make(SessionManager::class)->driver(); $session->setId(id: $this->extractSessionIdFromCookie($sessionCookie)); $session->start(); $tokenPrefix = 'login_'.$this->configRepository->get('nimbus.auth.guard'); $userId = Arr::first( $session->all(), fn (mixed $value, string $key): bool => str_starts_with($key, $tokenPrefix), ); return $this->userProvider->retrieveById($userId); } /** * Decrypt the Laravel session cookie and extract the session ID. * * Laravel’s session cookie is formatted as "payload|signature", where the * payload contains the encrypted session identifier. */ private function extractSessionIdFromCookie(string $cookieValue): string { $encrypter = $this->container->make('encrypter'); $decrypted = $encrypter->decrypt($cookieValue, unserialize: false); [, $sessionId] = explode('|', $decrypted, 2); return $sessionId; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Handlers/AuthorizationHandlerFactory.php
src/Modules/Relay/Authorization/Handlers/AuthorizationHandlerFactory.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationCredentials; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; /** * Creates authorization handlers based on credential types. * * Uses factory pattern to instantiate appropriate handlers for different * authorization methods (Bearer, Basic, Current User, etc.) with proper validation. * * @example * Input: AuthorizationCredentials(type: 'bearer', value: 'token123') * Output: BearerAuthorizationHandler instance */ class AuthorizationHandlerFactory { public function create(AuthorizationCredentials $authorizationCredentials): AuthorizationHandler { return match ($authorizationCredentials->type) { AuthorizationTypeEnum::CurrentUser => $this->buildCurrentUserHandler(), AuthorizationTypeEnum::Impersonate => $this->buildImpersonateHandler($authorizationCredentials->value), AuthorizationTypeEnum::Bearer => $this->buildBearerHandler($authorizationCredentials->value), AuthorizationTypeEnum::Basic => $this->buildBasicHandler($authorizationCredentials->value), AuthorizationTypeEnum::None => $this->buildNoAuthorizationHandler(), }; } protected function buildCurrentUserHandler(): CurrentUserAuthorizationHandler { // Current user authorization requires access to the application's, so we use the IoT for that. return resolve(CurrentUserAuthorizationHandler::class); } /** * @param string|array{username: string, password: string}|null $rawValue */ protected function buildImpersonateHandler(string|array|null $rawValue): ImpersonateUserAuthorizationHandler { if ($rawValue === null) { throw new \InvalidArgumentException('Impersonate user ID cannot be null.'); } if (! ctype_digit($rawValue)) { throw new \InvalidArgumentException('Impersonate user ID must be an integer.'); } return resolve(ImpersonateUserAuthorizationHandler::class, ['userId' => (int) $rawValue]); } /** * @param string|array{username: string, password: string}|null $rawValue */ protected function buildBearerHandler(string|array|null $rawValue): BearerAuthorizationHandler { if (! is_string($rawValue)) { throw new \InvalidArgumentException('Bearer token must be a string'); } return resolve(BearerAuthorizationHandler::class, ['token' => $rawValue]); } /** * @param string|array{username: string, password: string}|null $rawValue */ protected function buildBasicHandler(string|array|null $rawValue): BasicAuthAuthorizationHandler { if (! is_array($rawValue)) { throw new \InvalidArgumentException('Basic auth credentials must be an array'); } return BasicAuthAuthorizationHandler::fromArray($rawValue); } protected function buildNoAuthorizationHandler(): NoAuthorizationHandler { return resolve(NoAuthorizationHandler::class); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Handlers/NoAuthorizationHandler.php
src/Modules/Relay/Authorization/Handlers/NoAuthorizationHandler.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers; use Illuminate\Http\Client\PendingRequest; /** * Authorization handler that performs no authorization. * * Used when requests should be sent without any authentication headers * or session forwarding, allowing unauthenticated API testing. */ class NoAuthorizationHandler implements AuthorizationHandler { /** * Applies no authorization to the request. * * This handler intentionally does nothing, allowing requests to be * sent without any authentication mechanisms. */ public function authorize(PendingRequest $pendingRequest): PendingRequest { return $pendingRequest; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Handlers/BearerAuthorizationHandler.php
src/Modules/Relay/Authorization/Handlers/BearerAuthorizationHandler.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers; use Illuminate\Http\Client\PendingRequest; use Sunchayn\Nimbus\Modules\Relay\Authorization\Exceptions\InvalidAuthorizationValueException; class BearerAuthorizationHandler implements AuthorizationHandler { public function __construct( public readonly string $token, ) { if (in_array(trim($token), ['', '0'], true)) { throw InvalidAuthorizationValueException::becauseBearerTokenValueIsNotString(); } } public function authorize(PendingRequest $pendingRequest): PendingRequest { return $pendingRequest->withToken($this->token); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Handlers/AuthorizationHandler.php
src/Modules/Relay/Authorization/Handlers/AuthorizationHandler.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers; use Illuminate\Http\Client\PendingRequest; /** * Contract for authorization handlers that manage their own authorization logic. */ interface AuthorizationHandler { /** * Apply authorization to the pending request. * Each handler manages its own authorization logic. */ public function authorize(PendingRequest $pendingRequest): PendingRequest; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Authorization/Handlers/BasicAuthAuthorizationHandler.php
src/Modules/Relay/Authorization/Handlers/BasicAuthAuthorizationHandler.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers; use Illuminate\Http\Client\PendingRequest; use Sunchayn\Nimbus\Modules\Relay\Authorization\Exceptions\InvalidAuthorizationValueException; class BasicAuthAuthorizationHandler implements AuthorizationHandler { public function __construct( public readonly string $username, public readonly string $password, ) { if (in_array(trim($username), ['', '0'], true) || in_array(trim($password), ['', '0'], true)) { throw InvalidAuthorizationValueException::becauseBasicAuthCredentialsAreInvalid(); } } /** * @param array{username?: string, password?: string} $credentials */ public static function fromArray(array $credentials): self { if (! array_key_exists('username', $credentials) || ! array_key_exists('password', $credentials)) { throw InvalidAuthorizationValueException::becauseBasicAuthCredentialsAreInvalid(); } return new self($credentials['username'], $credentials['password']); } public function authorize(PendingRequest $pendingRequest): PendingRequest { return $pendingRequest->withBasicAuth($this->username, $this->password); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false