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 |
|---|---|---|---|---|---|---|---|---|
codenteq/laerx | https://github.com/codenteq/laerx/blob/1beced57923761b2f07ca20030a4df11eb05b732/resources/views/layouts/stylesheet.blade.php | resources/views/layouts/stylesheet.blade.php | <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs5/dt-1.11.3/r-2.2.9/sb-1.2.2/sp-1.4.0/datatables.min.css"/>
| php | MIT | 1beced57923761b2f07ca20030a4df11eb05b732 | 2026-01-05T05:20:28.495862Z | false |
codenteq/laerx | https://github.com/codenteq/laerx/blob/1beced57923761b2f07ca20030a4df11eb05b732/resources/views/layouts/app.blade.php | resources/views/layouts/app.blade.php | <!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="dc.language" content="{{ app()->getLocale() }}">
<meta http-equiv="content-language" content="{{ app()->getLocale() }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ getSubdomainCompanyName() ?? config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<!-- Styles -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="icon" href="{{asset('images/favicon.png')}}" type="image/x-icon"/>
<link href="{{ asset('css/login.css') }}" rel="stylesheet">
</head>
<body>
<div class="columns container-fluid">
<div class="login-box ">
<img style="width: 50%; margin-bottom: 20px;" src="/storage/{{getSubdomainLogo()}}" alt="">
@yield('content')
</div>
</div>
</body>
</html>
| php | MIT | 1beced57923761b2f07ca20030a4df11eb05b732 | 2026-01-05T05:20:28.495862Z | false |
codenteq/laerx | https://github.com/codenteq/laerx/blob/1beced57923761b2f07ca20030a4df11eb05b732/resources/views/email/invoice.blade.php | resources/views/email/invoice.blade.php | <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Fatura</title>
<style>
.invoice-box {
max-width: 800px;
margin: auto;
padding: 30px;
border: 1px solid #eee;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
font-size: 16px;
line-height: 24px;
font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;
color: #555;
}
.invoice-box table {
width: 100%;
line-height: inherit;
text-align: left;
}
.invoice-box table td {
padding: 5px;
vertical-align: top;
}
.invoice-box table tr td:nth-child(2) {
text-align: right;
}
.invoice-box table tr.top table td {
padding-bottom: 20px;
}
.invoice-box table tr.top table td.title {
font-size: 45px;
line-height: 45px;
color: #333;
}
.invoice-box table tr.information table td {
padding-bottom: 40px;
}
.invoice-box table tr.heading td {
background: #eee;
border-bottom: 1px solid #ddd;
font-weight: bold;
}
.invoice-box table tr.details td {
padding-bottom: 20px;
}
.invoice-box table tr.item td {
border-bottom: 1px solid #eee;
}
.invoice-box table tr.item.last td {
border-bottom: none;
}
.invoice-box table tr.total td:nth-child(2) {
border-top: 2px solid #eee;
font-weight: bold;
}
@media only screen and (max-width: 600px) {
.invoice-box table tr.top table td {
width: 100%;
display: block;
text-align: center;
}
.invoice-box table tr.information table td {
width: 100%;
display: block;
text-align: center;
}
}
/** RTL **/
.invoice-box.rtl {
direction: rtl;
font-family: Tahoma, 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;
}
.invoice-box.rtl table {
text-align: right;
}
.invoice-box.rtl table tr td:nth-child(2) {
text-align: left;
}
</style>
</head>
<body>
<div class="invoice-box">
<table cellpadding="0" cellspacing="0">
<tr class="top">
<td colspan="2">
<table>
<tr>
<td class="title">
<img src="{{asset('images/laerx.png')}}"
style="width: 30%; max-width: 300px"/>
</td>
<td>
Fatura No #: {{$invoice->id}}<br/>
Oluşturma: {{$invoice->created_at->format('d-m-Y')}}<br/>
</td>
</tr>
</table>
</td>
</tr>
<tr class="information">
<td colspan="2">
<table>
<tr>
<td>
{{$invoice->company->title}}.<br/>
{{$invoice->company->info->address}}
</td>
<td>
{{$user->name .' '. $user->surname}}<br>
{{$invoice->company->info->email}}
</td>
</tr>
</table>
</td>
</tr>
<tr class="heading">
<td>Ödeme Yöntemi</td>
<td></td>
</tr>
<tr class="details">
<td>{{$invoice->payment->title}}</td>
<td></td>
</tr>
<tr class="heading">
<td>Ürün</td>
<td>Fiyat</td>
</tr>
<tr class="item">
<td>{{$invoice->package->title}}</td>
<td>₺{{$invoice->price}}</td>
</tr>
<tr class="item">
<td>İndirim Tutarı</td>
<td>- ₺{{$invoice->discount_amount ?? 0}}</td>
</tr>
<tr class="Fiyat">
<td></td>
<td>Toplam: ₺{{$invoice->total_amount}}</td>
</tr>
</table>
</div>
</body>
</html>
| php | MIT | 1beced57923761b2f07ca20030a4df11eb05b732 | 2026-01-05T05:20:28.495862Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/PhpFile.php | src/PhpFile.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\AbstractFile;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
use Desarrolla2\Cache\File\BasicFilename;
/**
* Cache file as PHP script.
*/
class PhpFile extends AbstractFile
{
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Get the filename callable
*
* @return callable
*/
protected function getFilenameOption(): callable
{
if (!isset($this->filename)) {
$this->filename = new BasicFilename('%s.php');
}
return $this->filename;
}
/**
* Create a PHP script returning the cached value
*
* @param mixed $value
* @param int|null $ttl
* @return string
*/
public function createScript($value, ?int $ttl): string
{
$macro = var_export($value, true);
if (strpos($macro, 'stdClass::__set_state') !== false) {
$macro = preg_replace_callback("/('([^'\\\\]++|''\\.)')|stdClass::__set_state/", $macro, function($match) {
return empty($match[1]) ? '(object)' : $match[1];
});
}
return $ttl !== null
? "<?php return time() < {$ttl} ? {$macro} : false;"
: "<?php return {$macro};";
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$cacheFile = $this->getFilename($key);
if (!file_exists($cacheFile)) {
return $default;
}
$packed = include $cacheFile;
return $packed === false ? $default : $this->unpack($packed);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return $this->get($key) !== null;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$cacheFile = $this->getFilename($key);
$packed = $this->pack($value);
$script = $this->createScript($packed, $this->ttlToTimestamp($ttl));
return $this->writeFile($cacheFile, $script);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Redis.php | src/Redis.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Julián Gutiérrez <juliangut@gmail.com>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\UnexpectedValueException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
use Redis as PhpRedis;
/**
* PHP Redis cache adapter.
*
* Errors are silently ignored but ServerExceptions are **not** caught. To PSR-16 compliant disable the `exception`
* option.
*/
class Redis extends AbstractCache
{
/**
* @var PhpRedis
*/
protected $client;
/**
* Redis constructor.
*
* @param PhpRedis $client
*/
public function __construct(PhpRedis $client)
{
$this->client = $client;
}
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Set multiple (mset) with expire
*
* @param array $dictionary
* @param int|null $ttlSeconds
* @return bool
*/
protected function msetExpire(array $dictionary, ?int $ttlSeconds): bool
{
if (empty($dictionary)) {
return true;
}
if (!isset($ttlSeconds)) {
return $this->client->mset($dictionary);
}
$transaction = $this->client->multi();
foreach ($dictionary as $key => $value) {
$transaction->set($key, $value, $ttlSeconds);
}
$responses = $transaction->exec();
return array_reduce(
$responses,
function ($ok, $response) {
return $ok && $response;
},
true
);
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$response = $this->client->get($this->keyToId($key));
return !empty($response) ? $this->unpack($response) : $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$idKeyPairs = $this->mapKeysToIds($keys);
$response = $this->client->mget(array_keys($idKeyPairs));
return array_map(
function ($packed) use ($default) {
return !empty($packed) ? $this->unpack($packed) : $default;
},
array_combine(array_values($idKeyPairs), $response)
);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return $this->client->exists($this->keyToId($key)) !== 0;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$id = $this->keyToId($key);
$packed = $this->pack($value);
if (!is_string($packed)) {
throw new UnexpectedValueException("Packer must create a string for the data");
}
$ttlSeconds = $this->ttlToSeconds($ttl);
if (isset($ttlSeconds) && $ttlSeconds <= 0) {
return $this->client->del($id);
}
return !isset($ttlSeconds)
? $this->client->set($id, $packed)
: $this->client->setex($id, $ttlSeconds, $packed);
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
$dictionary = [];
foreach ($values as $key => $value) {
$id = $this->keyToId(is_int($key) ? (string)$key : $key);
$packed = $this->pack($value);
if (!is_string($packed)) {
throw new UnexpectedValueException("Packer must create a string for the data");
}
$dictionary[$id] = $packed;
}
$ttlSeconds = $this->ttlToSeconds($ttl);
if (isset($ttlSeconds) && $ttlSeconds <= 0) {
return $this->client->del(array_keys($dictionary));
}
return $this->msetExpire($dictionary, $ttlSeconds);
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
return $this->client->del($id) !== false;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$ids = array_keys($this->mapKeysToIds($keys));
return empty($ids) || $this->client->del($ids) !== false;
}
/**
* {@inheritdoc}
*/
public function clear()
{
return $this->client->flushDB();
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/AbstractCache.php | src/AbstractCache.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Option\PrefixTrait as PrefixOption;
use Desarrolla2\Cache\Option\TtlTrait as TtlOption;
use Desarrolla2\Cache\Packer\PackingTrait as Packing;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
use DateTimeImmutable;
use DateInterval;
use Traversable;
/**
* AbstractAdapter
*/
abstract class AbstractCache implements CacheInterface
{
use PrefixOption;
use TtlOption;
use Packing;
/**
* Make a clone of this object.
*
* @return static
*/
protected function cloneSelf(): self
{
return clone $this;
}
/**
* {@inheritdoc}
*/
public function withOption(string $key, $value): self
{
return $this->withOptions([$key => $value]);
}
/**
* {@inheritdoc}
*/
public function withOptions(array $options): self
{
$cache = $this->cloneSelf();
foreach ($options as $key => $value) {
$method = "set" . str_replace('-', '', $key) . "Option";
if (empty($key) || !method_exists($cache, $method)) {
throw new InvalidArgumentException("unknown option '$key'");
}
$cache->$method($value);
}
return $cache;
}
/**
* {@inheritdoc}
*/
public function getOption($key)
{
$method = "get" . str_replace('-', '', $key) . "Option";
if (empty($key) || !method_exists($this, $method)) {
throw new InvalidArgumentException("unknown option '$key'");
}
return $this->$method();
}
/**
* Validate the key
*
* @param string $key
* @return void
* @throws InvalidArgumentException
*/
protected function assertKey($key): void
{
if (!is_string($key)) {
$type = (is_object($key) ? get_class($key) . ' ' : '') . gettype($key);
throw new InvalidArgumentException("Expected key to be a string, not $type");
}
if ($key === '' || preg_match('~[{}()/\\\\@:]~', $key)) {
throw new InvalidArgumentException("Invalid key '$key'");
}
}
/**
* Assert that the keys are an array or traversable
*
* @param iterable $subject
* @param string $msg
* @return void
* @throws InvalidArgumentException if subject are not iterable
*/
protected function assertIterable($subject, $msg): void
{
$iterable = function_exists('is_iterable')
? is_iterable($subject)
: is_array($subject) || $subject instanceof Traversable;
if (!$iterable) {
throw new InvalidArgumentException($msg);
}
}
/**
* Turn the key into a cache identifier
*
* @param string $key
* @return string
* @throws InvalidArgumentException
*/
protected function keyToId($key): string
{
$this->assertKey($key);
return sprintf('%s%s', $this->prefix, $key);
}
/**
* Create a map with keys and ids
*
* @param iterable $keys
* @return array
* @throws InvalidArgumentException
*/
protected function mapKeysToIds($keys): array
{
$this->assertIterable($keys, 'keys not iterable');
$map = [];
foreach ($keys as $key) {
$id = $this->keyToId($key);
$map[$id] = $key;
}
return $map;
}
/**
* Pack all values and turn keys into ids
*
* @param iterable $values
* @return array
*/
protected function packValues(iterable $values): array
{
$packed = [];
foreach ($values as $key => $value) {
$id = $this->keyToId(is_int($key) ? (string)$key : $key);
$packed[$id] = $this->pack($value);
}
return $packed;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$this->assertIterable($keys, 'keys not iterable');
$result = [];
foreach ($keys as $key) {
$result[$key] = $this->get($key, $default);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
$success = true;
foreach ($values as $key => $value) {
$success = $this->set(is_int($key) ? (string)$key : $key, $value, $ttl) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$this->assertIterable($keys, 'keys not iterable');
$success = true;
foreach ($keys as $key) {
$success = $this->delete($key) && $success;
}
return $success;
}
/**
* Get the current time.
*
* @return int
*/
protected function currentTimestamp(): int
{
return time();
}
/**
* Convert TTL to seconds from now
*
* @param null|int|DateInterval $ttl
* @return int|null
* @throws InvalidArgumentException
*/
protected function ttlToSeconds($ttl): ?int
{
if (!isset($ttl)) {
return $this->ttl;
}
if ($ttl instanceof DateInterval) {
$reference = new DateTimeImmutable();
$endTime = $reference->add($ttl);
$ttl = $endTime->getTimestamp() - $reference->getTimestamp();
}
if (!is_int($ttl)) {
$type = (is_object($ttl) ? get_class($ttl) . ' ' : '') . gettype($ttl);
throw new InvalidArgumentException("ttl should be of type int or DateInterval, not $type");
}
return isset($this->ttl) ? min($ttl, $this->ttl) : $ttl;
}
/**
* Convert TTL to epoch timestamp
*
* @param null|int|DateInterval $ttl
* @return int|null
* @throws InvalidArgumentException
*/
protected function ttlToTimestamp($ttl): ?int
{
if (!isset($ttl)) {
return isset($this->ttl) ? time() + $this->ttl : null;
}
if (is_int($ttl)) {
return time() + (isset($this->ttl) ? min($ttl, $this->ttl) : $ttl);
}
if ($ttl instanceof DateInterval) {
$timestamp = (new DateTimeImmutable())->add($ttl)->getTimestamp();
return isset($this->ttl) ? min($timestamp, time() + $this->ttl) : $timestamp;
}
$type = (is_object($ttl) ? get_class($ttl) . ' ' : '') . gettype($ttl);
throw new InvalidArgumentException("ttl should be of type int or DateInterval, not $type");
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Memory.php | src/Memory.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
/**
* Memory
*/
class Memory extends AbstractCache
{
/**
* Limit the amount of entries
* @var int
*/
protected $limit = PHP_INT_MAX;
/**
* @var array
*/
protected $cache = [];
/**
* @var array
*/
protected $cacheTtl = [];
/**
* Create the default packer for this cache implementation.
* {@internal NopPacker might fail PSR-16, as cached objects would change}
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Make a clone of this object.
* Set by cache reference, thus using the same pool.
*
* @return static
*/
protected function cloneSelf(): AbstractCache
{
$clone = clone $this;
$clone->cache =& $this->cache;
$clone->cacheTtl =& $this->cacheTtl;
return $clone;
}
/**
* Set the max number of items
*
* @param int $limit
*/
protected function setLimitOption($limit)
{
$this->limit = (int)$limit ?: PHP_INT_MAX;
}
/**
* Get the max number of items
*
* @return int
*/
protected function getLimitOption()
{
return $this->limit;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
if (!$this->has($key)) {
return $default;
}
$id = $this->keyToId($key);
return $this->unpack($this->cache[$id]);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$id = $this->keyToId($key);
if (!isset($this->cacheTtl[$id])) {
return false;
}
if ($this->cacheTtl[$id] <= time()) {
unset($this->cache[$id], $this->cacheTtl[$id]);
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
if (count($this->cache) >= $this->limit) {
$deleteKey = key($this->cache);
unset($this->cache[$deleteKey], $this->cacheTtl[$deleteKey]);
}
$id = $this->keyToId($key);
$this->cache[$id] = $this->pack($value);
$this->cacheTtl[$id] = $this->ttlToTimestamp($ttl) ?? PHP_INT_MAX;
return true;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
unset($this->cache[$id], $this->cacheTtl[$id]);
return true;
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->cache = [];
$this->cacheTtl = [];
return true;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/MongoDB.php | src/MongoDB.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\MongoDBBinaryPacker;
use Desarrolla2\Cache\Option\InitializeTrait as InitializeOption;
use MongoDB\Collection;
use MongoDB\BSON\UTCDatetime as BSONUTCDateTime;
use MongoDB\Driver\Exception\RuntimeException as MongoDBRuntimeException;
/**
* MongoDB cache implementation
*/
class MongoDB extends AbstractCache
{
use InitializeOption;
/**
* @var Collection
*/
protected $collection;
/**
* Class constructor
*
* @param Collection $collection
*/
public function __construct(Collection $collection)
{
$this->collection = $collection;
}
/**
* Initialize the DB collection.
* Set TTL index.
*/
protected function initialize(): void
{
$this->collection->createIndex(['ttl' => 1], ['expireAfterSeconds' => 0]);
}
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new MongoDBBinaryPacker();
}
/**
* Get filter for key and ttl.
*
* @param string|iterable $key
* @return array
*/
protected function filter($key)
{
if (is_array($key)) {
$key = ['$in' => $key];
}
return [
'_id' => $key,
'$or' => [
['ttl' => ['$gt' => new BSONUTCDateTime($this->currentTimestamp() * 1000)]],
['ttl' => null]
]
];
}
/**
* {@inheritdoc }
*/
public function get($key, $default = null)
{
$filter = $this->filter($this->keyToId($key));
try {
$data = $this->collection->findOne($filter);
} catch (MongoDBRuntimeException $e) {
return $default;
}
return isset($data) ? $this->unpack($data['value']) : $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$idKeyPairs = $this->mapKeysToIds($keys);
if (empty($idKeyPairs)) {
return [];
}
$filter = $this->filter(array_keys($idKeyPairs));
$items = array_fill_keys(array_values($idKeyPairs), $default);
try {
$rows = $this->collection->find($filter);
} catch (MongoDBRuntimeException $e) {
return $items;
}
foreach ($rows as $row) {
$id = $row['_id'];
$key = $idKeyPairs[$id];
$items[$key] = $this->unpack($row['value']);
}
return $items;
}
/**
* {@inheritdoc }
*/
public function has($key)
{
$filter = $this->filter($this->keyToId($key));
try {
$count = $this->collection->count($filter);
} catch (MongoDBRuntimeException $e) {
return false;
}
return $count > 0;
}
/**
* {@inheritdoc }
*/
public function set($key, $value, $ttl = null)
{
$id = $this->keyToId($key);
$item = [
'_id' => $id,
'ttl' => $this->getTtlBSON($ttl),
'value' => $this->pack($value)
];
try {
$this->collection->replaceOne(['_id' => $id], $item, ['upsert' => true]);
} catch (MongoDBRuntimeException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
if (empty($values)) {
return true;
}
$bsonTtl = $this->getTtlBSON($ttl);
$items = [];
foreach ($values as $key => $value) {
$id = $this->keyToId(is_int($key) ? (string)$key : $key);
$items[] = [
'replaceOne' => [
['_id' => $id],
[
'_id' => $id,
'ttl' => $bsonTtl,
'value' => $this->pack($value)
],
[ 'upsert' => true ]
]
];
}
try {
$this->collection->bulkWrite($items);
} catch (MongoDBRuntimeException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
try {
$this->collection->deleteOne(['_id' => $id]);
} catch (MongoDBRuntimeException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$idKeyPairs = $this->mapKeysToIds($keys);
try {
if (!empty($idKeyPairs)) {
$this->collection->deleteMany(['_id' => ['$in' => array_keys($idKeyPairs)]]);
}
} catch (MongoDBRuntimeException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function clear()
{
try {
$this->collection->drop();
} catch (MongoDBRuntimeException $e) {
return false;
}
$this->requireInitialization();
return true;
}
/**
* Get TTL as Date type BSON object
*
* @param null|int|\DateInterval $ttl
* @return BSONUTCDatetime|null
*/
protected function getTtlBSON($ttl): ?BSONUTCDatetime
{
return isset($ttl) ? new BSONUTCDateTime($this->ttlToTimestamp($ttl) * 1000) : null;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/AbstractFile.php | src/AbstractFile.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
use Desarrolla2\Cache\Option\FilenameTrait as FilenameOption;
/**
* Abstract class for using files as cache.
*
* @package Desarrolla2\Cache
*/
abstract class AbstractFile extends AbstractCache
{
use FilenameOption;
/**
* @var string
*/
protected $cacheDir;
/**
* Class constructor
*
* @param string|null $cacheDir
*/
public function __construct(?string $cacheDir = null)
{
if (!$cacheDir) {
$cacheDir = realpath(sys_get_temp_dir()) . DIRECTORY_SEPARATOR . 'cache';
if(!is_dir($cacheDir)) {
mkdir($cacheDir, 0777, true);
}
}
$this->cacheDir = rtrim($cacheDir, '/');
}
/**
* Validate the key
*
* @param string $key
* @return void
* @throws InvalidArgumentException
*/
protected function assertKey($key): void
{
parent::assertKey($key);
if (strpos($key, '*')) {
throw new InvalidArgumentException("Key may not contain the character '*'");
}
}
/**
* Get the contents of the cache file.
*
* @param string $cacheFile
* @return string
*/
protected function readFile(string $cacheFile): string
{
return file_get_contents($cacheFile);
}
/**
* Read the first line of the cache file.
*
* @param string $cacheFile
* @return string
*/
protected function readLine(string $cacheFile): string
{
$fp = fopen($cacheFile, 'r');
$line = fgets($fp);
fclose($fp);
return $line;
}
/**
* Create a cache file
*
* @param string $cacheFile
* @param string $contents
* @return bool
*/
protected function writeFile(string $cacheFile, string $contents): bool
{
$dir = dirname($cacheFile);
if ($dir !== $this->cacheDir && !is_dir($dir)) {
mkdir($dir, 0775, true);
}
return (bool)file_put_contents($cacheFile, $contents);
}
/**
* Delete a cache file
*
* @param string $file
* @return bool
*/
protected function deleteFile(string $file): bool
{
return !is_file($file) || unlink($file);
}
/**
* Remove all files from a directory.
*/
protected function removeFiles(string $dir): bool
{
$success = true;
$generator = $this->getFilenameOption();
$objects = $this->streamSafeGlob($dir, $generator('*'));
foreach ($objects as $object) {
$success = $this->deleteFile($object) && $success;
}
return $success;
}
/**
* Recursive delete an empty directory.
*
* @param string $dir
*/
protected function removeRecursively(string $dir): bool
{
$success = $this->removeFiles($dir);
$objects = $this->streamSafeGlob($dir, '*');
foreach ($objects as $object) {
if (!is_dir($object)) {
continue;
}
if (is_link($object)) {
unlink($object);
} else {
$success = $this->removeRecursively($object) && $success;
rmdir($object);
}
}
return $success;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$cacheFile = $this->getFilename($key);
return $this->deleteFile($cacheFile);
}
/**
* Delete cache directory.
*
* {@inheritdoc}
*/
public function clear()
{
$this->removeRecursively($this->cacheDir);
return true;
}
/**
* Glob that is safe with streams (vfs for example)
*
* @param string $directory
* @param string $filePattern
* @return array
*/
protected function streamSafeGlob(string $directory, string $filePattern): array
{
$filePattern = basename($filePattern);
$files = scandir($directory);
$found = [];
foreach ($files as $filename) {
if (in_array($filename, ['.', '..'])) {
continue;
}
if (fnmatch($filePattern, $filename) || fnmatch($filePattern . '.ttl', $filename)) {
$found[] = "{$directory}/{$filename}";
}
}
return $found;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Memcached.php | src/Memcached.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\NopPacker;
use Memcached as MemcachedServer;
/**
* Memcached
*/
class Memcached extends AbstractCache
{
/**
* @var MemcachedServer
*/
protected $server;
/**
* @param MemcachedServer $server
*/
public function __construct(MemcachedServer $server)
{
$this->server = $server;
}
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new NopPacker();
}
/**
* Validate the key
*
* @param string $key
* @return void
* @throws InvalidArgumentException
*/
protected function assertKey($key): void
{
parent::assertKey($key);
if (strlen($key) > 250) {
throw new InvalidArgumentException("Key to long, max 250 characters");
}
}
/**
* Pack all values and turn keys into ids
*
* @param iterable $values
* @return array
*/
protected function packValues(iterable $values): array
{
$packed = [];
foreach ($values as $key => $value) {
$this->assertKey(is_int($key) ? (string)$key : $key);
$packed[$key] = $this->pack($value);
}
return $packed;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$this->assertKey($key);
$data = $this->server->get($key);
if ($this->server->getResultCode() !== MemcachedServer::RES_SUCCESS) {
return $default;
}
return $this->unpack($data);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$this->assertKey($key);
$this->server->get($key);
$result = $this->server->getResultCode();
return $result === MemcachedServer::RES_SUCCESS;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$this->assertKey($key);
$packed = $this->pack($value);
$ttlTime = $this->ttlToMemcachedTime($ttl);
if ($ttlTime === false) {
return $this->delete($key);
}
$success = $this->server->set($key, $packed, $ttlTime);
return $success;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$this->server->delete($this->keyToId($key));
$result = $this->server->getResultCode();
return $result === MemcachedServer::RES_SUCCESS || $result === MemcachedServer::RES_NOTFOUND;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$this->assertIterable($keys, 'keys not iterable');
$keysArr = is_array($keys) ? $keys : iterator_to_array($keys, false);
array_walk($keysArr, [$this, 'assertKey']);
$result = $this->server->getMulti($keysArr);
if ($result === false) {
return false;
}
$items = array_fill_keys($keysArr, $default);
foreach ($result as $key => $value) {
$items[$key] = $this->unpack($value);
}
return $items;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
$packed = $this->packValues($values);
$ttlTime = $this->ttlToMemcachedTime($ttl);
if ($ttlTime === false) {
return $this->server->deleteMulti(array_keys($packed));
}
return $this->server->setMulti($packed, $ttlTime);
}
/**
* {@inheritdoc}
*/
public function clear()
{
return $this->server->flush();
}
/**
* Convert ttl to timestamp or seconds.
*
* @see http://php.net/manual/en/memcached.expiration.php
*
* @param null|int|\DateInterval $ttl
* @return int|null
* @throws InvalidArgumentException
*/
protected function ttlToMemcachedTime($ttl)
{
$seconds = $this->ttlToSeconds($ttl);
if ($seconds <= 0) {
return isset($seconds) ? false : 0;
}
/* 2592000 seconds = 30 days */
return $seconds <= 2592000 ? $seconds : $this->ttlToTimestamp($ttl);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/CacheInterface.php | src/CacheInterface.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Cache;
use Psr\SimpleCache\CacheInterface as PsrCacheInterface;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\KeyMaker\KeyMakerInterface;
/**
* CacheInterface
*/
interface CacheInterface extends PsrCacheInterface
{
/**
* Set option for cache
*
* @param string $key
* @param mixed $value
* @return static
*/
public function withOption(string $key, $value);
/**
* Set multiple options for cache
*
* @param array $options
* @return static
*/
public function withOptions(array $options);
/**
* Get option for cache
*
* @param string $key
* @return mixed
*/
public function getOption($key);
/**
* Set the packer
*
* @param PackerInterface $packer
* @return static
*/
public function withPacker(PackerInterface $packer);
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/File.php | src/File.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
use Desarrolla2\Cache\Exception\UnexpectedValueException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
/**
* Cache file.
*/
class File extends AbstractFile
{
/**
* @var string 'embed', 'file', 'mtime'
*/
protected $ttlStrategy = 'embed';
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Set TTL strategy
*
* @param string $strategy
*/
protected function setTtlStrategyOption($strategy)
{
if (!in_array($strategy, ['embed', 'file', 'mtime'])) {
throw new InvalidArgumentException("Unknown strategy '$strategy', should be 'embed', 'file' or 'mtime'");
}
$this->ttlStrategy = $strategy;
}
/**
* Get TTL strategy
*
* @return string
*/
protected function getTtlStrategyOption(): string
{
return $this->ttlStrategy;
}
/**
* Get the TTL using one of the strategies
*
* @param string $cacheFile
* @return int
*/
protected function getTtl(string $cacheFile)
{
switch ($this->ttlStrategy) {
case 'embed':
return (int)$this->readLine($cacheFile);
case 'file':
return file_exists("$cacheFile.ttl")
? (int)file_get_contents("$cacheFile.ttl")
: PHP_INT_MAX;
case 'mtime':
return $this->ttl > 0 ? filemtime($cacheFile) + $this->ttl : PHP_INT_MAX;
}
throw new \InvalidArgumentException("Invalid TTL strategy '{$this->ttlStrategy}'");
}
/**
* Set the TTL using one of the strategies
*
* @param int|null $expiration
* @param string $contents
* @param string $cacheFile
* @return string The (modified) contents
*/
protected function setTtl($expiration, $contents, $cacheFile)
{
switch ($this->ttlStrategy) {
case 'embed':
$contents = ($expiration ?? PHP_INT_MAX) . "\n" . $contents;
break;
case 'file':
if ($expiration !== null) {
file_put_contents("$cacheFile.ttl", $expiration);
}
break;
case 'mtime':
// nothing
break;
}
return $contents;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$cacheFile = $this->getFilename($key);
if (!file_exists($cacheFile)) {
return $default;
}
if ($this->ttlStrategy === 'embed') {
[$ttl, $packed] = explode("\n", $this->readFile($cacheFile), 2);
} else {
$ttl = $this->getTtl($cacheFile);
}
if ((int)$ttl <= time()) {
$this->deleteFile($cacheFile);
return $default;
}
if (!isset($packed)) {
$packed = $this->readFile($cacheFile); // Other ttl strategy than embed
}
return $this->unpack($packed);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$cacheFile = $this->getFilename($key);
if (!file_exists($cacheFile)) {
return false;
}
$ttl = $this->getTtl($cacheFile);
if ($ttl <= time()) {
$this->deleteFile($cacheFile);
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$cacheFile = $this->getFilename($key);
$packed = $this->pack($value);
if (!is_string($packed)) {
throw new UnexpectedValueException("Packer must create a string for the data to be cached to file");
}
$contents = $this->setTtl($this->ttlToTimestamp($ttl), $packed, $cacheFile);
return $this->writeFile($cacheFile, $contents);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Mysqli.php | src/Mysqli.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Option\InitializeTrait;
use mysqli as Server;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
/**
* Mysqli cache adapter.
*
* Errors are silently ignored but exceptions are **not** caught. Beware when using `mysqli_report()` to throw a
* `mysqli_sql_exception` on error.
*/
class Mysqli extends AbstractCache
{
use InitializeTrait;
/**
* @var Server
*/
protected $server;
/**
* @var string
*/
protected $table = 'cache';
/**
* Class constructor
*
* @param Server $server
*/
public function __construct(Server $server)
{
$this->server = $server;
}
/**
* Initialize table.
* Automatically delete old cache.
*/
protected function initialize(): void
{
if ($this->initialized !== false) {
return;
}
$this->query(
"CREATE TABLE IF NOT EXISTS `{table}` "
. "( `key` VARCHAR(255), `value` BLOB, `ttl` BIGINT UNSIGNED, PRIMARY KEY (`key`) )"
);
$this->query(
"CREATE EVENT IF NOT EXISTS `apply_ttl_{$this->table}` ON SCHEDULE EVERY 1 HOUR DO BEGIN"
. " DELETE FROM {table} WHERE `ttl` < UNIX_TIMESTAMP();"
. " END"
);
$this->initialized = true;
}
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Set the table name
*
* @param string $table
*/
public function setTableOption(string $table)
{
$this->table = $table;
$this->requireInitialization();
}
/**
* Get the table name
*
* @return string
*/
public function getTableOption(): string
{
return $this->table;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$this->initialize();
$result = $this->query(
'SELECT `value` FROM {table} WHERE `key` = ? AND (`ttl` > ? OR `ttl` IS NULL) LIMIT 1',
'si',
$this->keyToId($key),
$this->currentTimestamp()
);
$row = $result !== false ? $result->fetch_row() : null;
return $row ? $this->unpack($row[0]) : $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$idKeyPairs = $this->mapKeysToIds($keys);
if (empty($idKeyPairs)) {
return [];
}
$this->initialize();
$values = array_fill_keys(array_values($idKeyPairs), $default);
$placeholders = rtrim(str_repeat('?, ', count($idKeyPairs)), ', ');
$paramTypes = str_repeat('s', count($idKeyPairs)) . 'i';
$params = array_keys($idKeyPairs);
$params[] = $this->currentTimestamp();
$result = $this->query(
"SELECT `key`, `value` FROM {table} WHERE `key` IN ($placeholders) AND (`ttl` > ? OR `ttl` IS NULL)",
$paramTypes,
...$params
);
while (([$id, $value] = $result->fetch_row())) {
$key = $idKeyPairs[$id];
$values[$key] = $this->unpack($value);
}
return $values;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$this->initialize();
$result = $this->query(
'SELECT COUNT(`key`) FROM {table} WHERE `key` = ? AND (`ttl` > ? OR `ttl` IS NULL) LIMIT 1',
'si',
$this->keyToId($key),
$this->currentTimestamp()
);
[$count] = $result ? $result->fetch_row() : [null];
return isset($count) && $count > 0;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$this->initialize();
$result = $this->query(
'REPLACE INTO {table} (`key`, `value`, `ttl`) VALUES (?, ?, ?)',
'ssi',
$this->keyToId($key),
$this->pack($value),
$this->ttlToTimestamp($ttl)
);
return $result !== false;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
if (empty($values)) {
return true;
}
$this->initialize();
$count = 0;
$params = [];
$timeTtl = $this->ttlToTimestamp($ttl);
foreach ($values as $key => $value) {
$count++;
$params[] = $this->keyToId(is_int($key) ? (string)$key : $key);
$params[] = $this->pack($value);
$params[] = $timeTtl;
}
$query = 'REPLACE INTO {table} (`key`, `value`, `ttl`) VALUES '
. rtrim(str_repeat('(?, ?, ?), ', $count), ', ');
return (bool)$this->query($query, str_repeat('ssi', $count), ...$params);
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$this->initialize();
return (bool)$this->query(
'DELETE FROM {table} WHERE `key` = ?',
's',
$this->keyToId($key)
);
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$idKeyPairs = $this->mapKeysToIds($keys);
if (empty($idKeyPairs)) {
return true;
}
$this->initialize();
$placeholders = rtrim(str_repeat('?, ', count($idKeyPairs)), ', ');
$paramTypes = str_repeat('s', count($idKeyPairs));
return (bool)$this->query(
"DELETE FROM {table} WHERE `key` IN ($placeholders)",
$paramTypes,
...array_keys($idKeyPairs)
);
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->initialize();
return (bool)$this->query('TRUNCATE {table}');
}
/**
* Query the MySQL server
*
* @param string $query
* @param string $types
* @param mixed[] $params
* @return \mysqli_result|bool
*/
protected function query($query, $types = '', ...$params)
{
$sql = str_replace('{table}', $this->table, $query);
if ($params === []) {
$ret = $this->server->query($sql);
} else {
$statement = $this->server->prepare($sql);
if ($statement !== false) {
$statement->bind_param($types, ...$params);
$ret = $statement->execute();
$ret = $ret ? ($statement->get_result() ?: true) : false;
} else {
$ret = false;
}
}
if ($this->server->error) {
trigger_error($this->server->error . " $sql", E_USER_NOTICE);
}
return $ret;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Chain.php | src/Chain.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Packer\NopPacker;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* Use multiple cache adapters.
*/
class Chain extends AbstractCache
{
/**
* @var CacheInterface[]
*/
protected $adapters;
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new NopPacker();
}
/**
* Chain constructor.
*
* @param CacheInterface[] $adapters Fastest to slowest
*/
public function __construct(array $adapters)
{
foreach ($adapters as $adapter) {
if (!$adapter instanceof CacheInterface) {
throw new InvalidArgumentException("All adapters should be a cache implementation");
}
}
$this->adapters = $adapters;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->set($key, $value, $ttl) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->setMultiple($values, $ttl) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
foreach ($this->adapters as $adapter) {
$result = $adapter->get($key); // Not using $default as we want to get null if the adapter doesn't have it
if (isset($result)) {
return $result;
}
}
return $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$this->assertIterable($keys, 'keys are not iterable');
$missing = [];
$values = [];
foreach ($keys as $key) {
$this->assertKey($key);
$missing[] = $key;
$values[$key] = $default;
}
foreach ($this->adapters as $adapter) {
if (empty($missing)) {
break;
}
$found = [];
foreach ($adapter->getMultiple($missing) as $key => $value) {
if (isset($value)) {
$found[$key] = $value;
}
}
$values = array_merge($values, $found);
$missing = array_values(array_diff($missing, array_keys($found)));
}
return $values;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
foreach ($this->adapters as $adapter) {
if ($adapter->has($key)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->delete($key) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->deleteMultiple($keys) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function clear()
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->clear() && $success;
}
return $success;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Predis.php | src/Predis.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\AbstractCache;
use Desarrolla2\Cache\Exception\UnexpectedValueException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
use Predis\Client;
use Predis\Response\ServerException;
use Predis\Response\Status;
use Predis\Response\ErrorInterface;
/**
* Predis cache adapter.
*
* Errors are silently ignored but ServerExceptions are **not** caught. To PSR-16 compliant disable the `exception`
* option.
*/
class Predis extends AbstractCache
{
/**
* @var Client
*/
protected $predis;
/**
* Class constructor
* @see predis documentation about how know your configuration https://github.com/nrk/predis
*
* @param Client $client
*/
public function __construct(Client $client)
{
$this->predis = $client;
}
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Run a predis command.
*
* @param string $cmd
* @param mixed ...$args
* @return mixed|bool
*/
protected function execCommand(string $cmd, ...$args)
{
$command = $this->predis->createCommand($cmd, $args);
$response = $this->predis->executeCommand($command);
if ($response instanceof ErrorInterface) {
return false;
}
if ($response instanceof Status) {
return $response->getPayload() === 'OK';
}
return $response;
}
/**
* Set multiple (mset) with expire
*
* @param array $dictionary
* @param int|null $ttlSeconds
* @return bool
*/
protected function msetExpire(array $dictionary, ?int $ttlSeconds): bool
{
if (empty($dictionary)) {
return true;
}
if (!isset($ttlSeconds)) {
return $this->execCommand('MSET', $dictionary);
}
$transaction = $this->predis->transaction();
foreach ($dictionary as $key => $value) {
$transaction->set($key, $value, 'EX', $ttlSeconds);
}
try {
$responses = $transaction->execute();
} catch (ServerException $e) {
return false;
}
$ok = array_reduce($responses, function($ok, $response) {
return $ok && $response instanceof Status && $response->getPayload() === 'OK';
}, true);
return $ok;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$id = $this->keyToId($key);
$response = $this->execCommand('GET', $id);
return !empty($response) ? $this->unpack($response) : $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$idKeyPairs = $this->mapKeysToIds($keys);
$ids = array_keys($idKeyPairs);
$response = $this->execCommand('MGET', $ids);
if ($response === false) {
return false;
}
$items = [];
$packedItems = array_combine(array_values($idKeyPairs), $response);
foreach ($packedItems as $key => $packed) {
$items[$key] = isset($packed) ? $this->unpack($packed) : $default;
}
return $items;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return $this->execCommand('EXISTS', $this->keyToId($key));
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$id = $this->keyToId($key);
$packed = $this->pack($value);
if (!is_string($packed)) {
throw new UnexpectedValueException("Packer must create a string for the data");
}
$ttlSeconds = $this->ttlToSeconds($ttl);
if (isset($ttlSeconds) && $ttlSeconds <= 0) {
return $this->execCommand('DEL', [$id]);
}
return !isset($ttlSeconds)
? $this->execCommand('SET', $id, $packed)
: $this->execCommand('SETEX', $id, $ttlSeconds, $packed);
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
$dictionary = [];
foreach ($values as $key => $value) {
$id = $this->keyToId(is_int($key) ? (string)$key : $key);
$packed = $this->pack($value);
if (!is_string($packed)) {
throw new UnexpectedValueException("Packer must create a string for the data");
}
$dictionary[$id] = $packed;
}
$ttlSeconds = $this->ttlToSeconds($ttl);
if (isset($ttlSeconds) && $ttlSeconds <= 0) {
return $this->execCommand('DEL', array_keys($dictionary));
}
return $this->msetExpire($dictionary, $ttlSeconds);
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
return $this->execCommand('DEL', [$id]) !== false;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$ids = array_keys($this->mapKeysToIds($keys));
return empty($ids) || $this->execCommand('DEL', $ids) !== false;
}
/**
* {@inheritdoc}
*/
public function clear()
{
return $this->execCommand('FLUSHDB');
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/NotCache.php | src/NotCache.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\AbstractCache;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\NopPacker;
/**
* Dummy cache handler
*/
class NotCache extends AbstractCache
{
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new NopPacker();
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
return true;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
return false;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
return false;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return false;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
return false;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
return false;
}
/**
* {@inheritdoc}
*/
public function clear()
{
return true;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Apcu.php | src/Apcu.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\CacheException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\NopPacker;
/**
* Apcu
*/
class Apcu extends AbstractCache
{
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new NopPacker();
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$ttlSeconds = $this->ttlToSeconds($ttl);
if (isset($ttlSeconds) && $ttlSeconds <= 0) {
return $this->delete($key);
}
return apcu_store($this->keyToId($key), $this->pack($value), $ttlSeconds ?? 0);
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$packed = apcu_fetch($this->keyToId($key), $success);
return $success ? $this->unpack($packed) : $default;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return apcu_exists($this->keyToId($key));
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
return apcu_delete($id) || !apcu_exists($id);
}
/**
* {@inheritdoc}
*/
public function clear()
{
return apcu_clear_cache();
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/File/TrieFilename.php | src/File/TrieFilename.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\File;
/**
* Create a path for a key as prefix tree directory structure.
*
* @see https://en.wikipedia.org/wiki/Trie
*/
class TrieFilename
{
/**
* @var string
*/
protected $format;
/**
* @var int
*/
protected $levels;
/**
* @var bool
*/
protected $hash;
/**
* TrieFilename constructor.
*
* @param string $format
* @param int $levels The depth of the structure
* @param bool $hash MD5 hash the key to get a better spread
*/
public function __construct(string $format, int $levels = 1, bool $hash = false)
{
$this->format = $format;
$this->levels = $levels;
$this->hash = $hash;
}
/**
* Get the format
*
* @return string
*/
public function getFormat(): string
{
return $this->format;
}
/**
* Get the depth of the structure
*
* @return int
*/
public function getLevels(): int
{
return $this->levels;
}
/**
* Will the key be hashed to create the trie.
*
* @return bool
*/
public function isHashed(): bool
{
return $this->hash;
}
/**
* Create the path for a key
*
* @param string $key
* @return string
*/
public function __invoke(string $key): string
{
if (empty($key)) {
return $this->wildcardPath();
}
$dirname = $this->hash ? base_convert(md5($key), 16, 36) : $key;
$filename = sprintf($this->format, $key);
$path = '';
for ($length = 1; $length <= $this->levels; $length++) {
$path .= substr($dirname, 0, $length) . DIRECTORY_SEPARATOR;
}
return $path . $filename;
}
/**
* Get a path for all files (using glob)
*
* @return string
*/
protected function wildcardPath(): string
{
$filename = sprintf($this->format, '*');
return str_repeat('*' . DIRECTORY_SEPARATOR, $this->levels) . $filename;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/File/BasicFilename.php | src/File/BasicFilename.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\File;
/**
* Create a path for a key
*/
class BasicFilename
{
/**
* @var string
*/
protected $format;
/**
* BasicFilename constructor.
*
* @param string $format
*/
public function __construct(string $format)
{
$this->format = $format;
}
/**
* Get the format
*
* @return string
*/
public function getFormat(): string
{
return $this->format;
}
/**
* Create the path for a key
*
* @param string $key
* @return string
*/
public function __invoke(string $key): string
{
return sprintf($this->format, $key ?: '*');
}
/**
* Cast to string
*
* @return string
*/
public function __toString(): string
{
return $this->getFormat();
}
} | php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Exception/BadMethodCallException.php | src/Exception/BadMethodCallException.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Exception;
use Psr\SimpleCache\CacheException as PsrCacheException;
/**
* Exception bad method calls
*/
class BadMethodCallException extends \BadMethodCallException implements PsrCacheException
{
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Exception/UnexpectedValueException.php | src/Exception/UnexpectedValueException.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Exception;
use Psr\SimpleCache\CacheException as PsrCacheException;
/**
* Exception for unexpected values when reading from cache.
*/
class UnexpectedValueException extends \UnexpectedValueException implements PsrCacheException
{
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Exception/InvalidArgumentException.php | src/Exception/InvalidArgumentException.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Exception;
use Psr\SimpleCache\InvalidArgumentException as PsrInvalidArgumentException;
/**
* Exception for invalid cache arguments.
*/
class InvalidArgumentException extends \InvalidArgumentException implements PsrInvalidArgumentException
{
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Exception/CacheException.php | src/Exception/CacheException.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Exception;
use Psr\SimpleCache\CacheException as PsrCacheException;
/**
* Interface used for all types of exceptions thrown by the implementing library.
*/
class CacheException extends \RuntimeException implements PsrCacheException
{
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Option/InitializeTrait.php | src/Option/InitializeTrait.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Option;
/**
* Auto initialize the cache
*/
trait InitializeTrait
{
/**
* Is cache initialized
* @var bool|null
*/
protected $initialized = false;
/**
* Enable/disable initialization
*
* @param bool $enabled
*/
public function setInitializeOption(bool $enabled)
{
$this->initialized = $enabled ? (bool)$this->initialized : null;
}
/**
* Should initialize
*
* @return bool
*/
protected function getInitializeOption(): bool
{
return $this->initialized !== null;
}
/**
* Mark as initialization required (if enabled)
*/
protected function requireInitialization()
{
$this->initialized = isset($this->initialized) ? false : null;
}
/**
* Initialize
*
* @return void
*/
abstract protected function initialize(): void;
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Option/FilenameTrait.php | src/Option/FilenameTrait.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Option;
use TypeError;
use Desarrolla2\Cache\File\BasicFilename;
/**
* Use filename generator
*/
trait FilenameTrait
{
/**
* @var callable
*/
protected $filename;
/**
* Filename format or callable.
* The filename format will be applied using sprintf, replacing `%s` with the key.
*
* @param string|callable $filename
* @return void
*/
protected function setFilenameOption($filename): void
{
if (is_string($filename)) {
$filename = new BasicFilename($filename);
}
if (!is_callable($filename)) {
throw new TypeError("Filename should be a string or callable");
}
$this->filename = $filename;
}
/**
* Get the filename callable
*
* @return callable
*/
protected function getFilenameOption(): callable
{
if (!isset($this->filename)) {
$this->filename = new BasicFilename('%s.' . $this->getPacker()->getType());
}
return $this->filename;
}
/**
* Create a filename based on the key
*
* @param string|mixed $key
* @return string
*/
protected function getFilename($key): string
{
$id = $this->keyToId($key);
$generator = $this->getFilenameOption();
return $this->cacheDir . DIRECTORY_SEPARATOR . $generator($id);
}
/**
* Get a wildcard for all files
*
* @return string
*/
protected function getWildcard(): string
{
$generator = $this->getFilenameOption();
return $this->cacheDir . DIRECTORY_SEPARATOR . $generator('');
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Option/TtlTrait.php | src/Option/TtlTrait.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Option;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* TTL option
*/
trait TtlTrait
{
/**
* @var int|null
*/
protected $ttl = null;
/**
* Set the maximum time to live (ttl)
*
* @param int|null $value Seconds or null to live forever
* @throws InvalidArgumentException
*/
protected function setTtlOption(?int $value): void
{
if (isset($value) && $value < 1) {
throw new InvalidArgumentException('ttl cant be lower than 1');
}
$this->ttl = $value;
}
/**
* Get the maximum time to live (ttl)
*
* @return int|null
*/
protected function getTtlOption(): ?int
{
return $this->ttl;
}
} | php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Option/PrefixTrait.php | src/Option/PrefixTrait.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Option;
/**
* Prefix option
*/
trait PrefixTrait
{
/**
* @var string
*/
protected $prefix = '';
/**
* Set the key prefix
*
* @param string $prefix
* @return void
*/
protected function setPrefixOption(string $prefix): void
{
$this->prefix = $prefix;
}
/**
* Get the key prefix
*
* @return string
*/
protected function getPrefixOption(): string
{
return $this->prefix;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Packer/MongoDBBinaryPacker.php | src/Packer/MongoDBBinaryPacker.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Cache\Packer;
use Desarrolla2\Cache\Packer\PackerInterface;
use MongoDB\BSON\Binary;
/**
* Pack as BSON binary
*
* @todo Don't use serialize when packer chain is here.
*/
class MongoDBBinaryPacker implements PackerInterface
{
/**
* @var array
*/
protected $options;
/**
* SerializePacker constructor
*
* @param array $options Any options to be provided to unserialize()
*/
public function __construct(array $options = ['allowed_classes' => true])
{
$this->options = $options;
}
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType()
{
return 'bson';
}
/**
* Pack the value
*
* @param mixed $value
* @return string
*/
public function pack($value)
{
return new Binary(serialize($value), Binary::TYPE_GENERIC);
}
/**
* Unpack the value
*
* @param string $packed
* @return string
* @throws \UnexpectedValueException if he value can't be unpacked
*/
public function unpack($packed)
{
if (!$packed instanceof Binary) {
throw new \InvalidArgumentException("packed value should be BSON binary");
}
return unserialize((string)$packed, $this->options);
}
} | php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Packer/NopPacker.php | src/Packer/NopPacker.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
use Desarrolla2\Cache\Packer\PackerInterface;
/**
* Don't pack, just straight passthrough
*/
class NopPacker implements PackerInterface
{
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType()
{
return 'data';
}
/**
* Pack the value
*
* @param mixed $value
* @return mixed
*/
public function pack($value)
{
return $value;
}
/**
* Unpack the value
*
* @param mixed $packed
* @return mixed
*/
public function unpack($packed)
{
return $packed;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Packer/SerializePacker.php | src/Packer/SerializePacker.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* Pack value through serialization
*/
class SerializePacker implements PackerInterface
{
/**
* @var array
*/
protected $options;
/**
* SerializePacker constructor
*
* @param array $options Any options to be provided to unserialize()
*/
public function __construct(array $options = ['allowed_classes' => true])
{
$this->options = $options;
}
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType()
{
return 'php.cache';
}
/**
* Pack the value
*
* @param mixed $value
* @return string
*/
public function pack($value)
{
return serialize($value);
}
/**
* Unpack the value
*
* @param string $packed
* @return string
* @throws \UnexpectedValueException if he value can't be unpacked
*/
public function unpack($packed)
{
if (!is_string($packed)) {
throw new InvalidArgumentException("packed value should be a string");
}
return unserialize($packed, $this->options);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Packer/PackerInterface.php | src/Packer/PackerInterface.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
/**
* Interface for packer / unpacker
*/
interface PackerInterface
{
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType();
/**
* Pack the value
*
* @param mixed $value
* @return string|mixed
*/
public function pack($value);
/**
* Unpack the value
*
* @param string|mixed $packed
* @return string
* @throws \UnexpectedValueException if the value can't be unpacked
*/
public function unpack($packed);
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Packer/JsonPacker.php | src/Packer/JsonPacker.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* Pack value through serialization
*/
class JsonPacker implements PackerInterface
{
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType()
{
return 'json';
}
/**
* Pack the value
*
* @param mixed $value
* @return string
*/
public function pack($value)
{
return json_encode($value);
}
/**
* Unpack the value
*
* @param string $packed
* @return mixed
* @throws InvalidArgumentException
*/
public function unpack($packed)
{
if (!is_string($packed)) {
throw new InvalidArgumentException("packed value should be a string");
}
$ret = json_decode($packed);
if (!isset($ret) && json_last_error()) {
throw new \UnexpectedValueException("packed value is not a valid JSON string");
}
return $ret;
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/src/Packer/PackingTrait.php | src/Packer/PackingTrait.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
/**
* Support packing for Caching adapter
*/
trait PackingTrait
{
/**
* @var PackerInterface
*/
protected $packer;
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
abstract protected static function createDefaultPacker(): PackerInterface;
/**
* Set a packer to pack (serialialize) and unpack (unserialize) the data.
*
* @param PackerInterface $packer
* @return static
*/
public function withPacker(PackerInterface $packer)
{
$cache = $this->cloneSelf();
$cache->packer = $packer;
return $cache;
}
/**
* Get the packer
*
* @return PackerInterface
*/
protected function getPacker(): PackerInterface
{
if (!isset($this->packer)) {
$this->packer = static::createDefaultPacker();
}
return $this->packer;
}
/**
* Pack the value
*
* @param mixed $value
* @return string|mixed
*/
protected function pack($value)
{
return $this->getPacker()->pack($value);
}
/**
* Unpack the data to retrieve the value
*
* @param string|mixed $packed
* @return mixed
* @throws \UnexpectedValueException
*/
protected function unpack($packed)
{
return $this->getPacker()->unpack($packed);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/ChainTest.php | tests/ChainTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Chain as CacheChain;
use Desarrolla2\Cache\Memory as MemoryCache;
/**
* ChainTest
*/
class ChainTest extends AbstractCacheTest
{
public function createSimpleCache()
{
$adapters = [new MemoryCache()]; // For the general PSR-16 tests, we don't need more than 1 adapter
return new CacheChain($adapters);
}
public function tearDown(): void
{
// No need to clear cache, as the adapters don't persist between tests.
}
public function testChainSet()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('set')->with("foo", "bar", 300);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('set')->with("foo", "bar", 300);
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->set("foo", "bar", 300);
}
public function testChainSetMultiple()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('setMultiple')->with(["foo" => 1, "bar" => 2], 300);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('setMultiple')->with(["foo" => 1, "bar" => 2], 300);
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->setMultiple(["foo" => 1, "bar" => 2], 300);
}
public function testChainGetFirst()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('get')->with("foo")->willReturn("bar");
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->never())->method('get');
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertEquals("bar", $cache->get("foo", 42));
}
public function testChainGetSecond()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('get')->with("foo")->willReturn(null);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('get')->with("foo")->willReturn("car");
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertEquals("car", $cache->get("foo", 42));
}
public function testChainGetNone()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('get')->with("foo")->willReturn(null);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('get')->with("foo")->willReturn(null);
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertEquals(42, $cache->get("foo", 42));
}
public function testChainGetMultipleFirst()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('getMultiple')->with(["foo", "bar"])
->willReturn(["foo" => 1, "bar" => 2]);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->never())->method('getMultiple');
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertEquals(["foo" => 1, "bar" => 2], $cache->getMultiple(["foo", "bar"]));
}
public function testChainGetMultipleMixed()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('getMultiple')
->with($this->equalTo(["foo", "bar", "wux", "lot"]))
->willReturn(["foo" => null, "bar" => 2, "wux" => null, "lot" => null]);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('getMultiple')
->with($this->equalTo(["foo", "wux", "lot"]))
->willReturn(["foo" => 11, "wux" => 15, "lot" => null]);
$cache = new CacheChain([$adapter1, $adapter2]);
$expected = ["foo" => 11, "bar" => 2, "wux" => 15, "lot" => 42];
$this->assertEquals($expected, $cache->getMultiple(["foo", "bar", "wux", "lot"], 42));
}
public function testChainHasFirst()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('has')->with("foo")->willReturn(true);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->never())->method('has');
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertTrue($cache->has("foo"));
}
public function testChainHasSecond()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('has')->with("foo")->willReturn(false);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('has')->with("foo")->willReturn(true);
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertTrue($cache->has("foo"));
}
public function testChainHasNone()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('has')->with("foo")->willReturn(false);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('has')->with("foo")->willReturn(false);
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertFalse($cache->has("foo"));
}
public function testChainDelete()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('delete')->with("foo");
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('delete')->with("foo");
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->delete("foo");
}
public function testChainDeleteMultiple()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('deleteMultiple')->with(["foo", "bar"]);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('deleteMultiple')->with(["foo", "bar"]);
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->deleteMultiple(["foo", "bar"]);
}
public function testChainClear()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('clear');
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('clear');
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->clear();
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/FileTtlFileTest.php | tests/FileTtlFileTest.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\File as FileCache;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* FileTest
*/
class FileTtlFileTest extends AbstractCacheTest
{
/**
* @var vfsStreamDirectory
*/
private $root;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 64 bytes'
];
public function createSimpleCache()
{
$this->root = vfsStream::setup('cache');
return (new FileCache(vfsStream::url('cache')))
->withOption('ttl-strategy', 'file');
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/NotCacheTest.php | tests/NotCacheTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\NotCache as NotCache;
use PHPUnit\Framework\TestCase;
/**
* NotCacheTest
*/
class NotCacheTest extends TestCase
{
/**
* @var \Desarrolla2\Cache\NotCache
*/
protected $cache;
public function setUp(): void
{
$this->cache = new NotCache();
}
/**
* @return array
*/
public function dataProvider()
{
return array(
array(),
);
}
/**
* @dataProvider dataProvider
*/
public function testHas()
{
$this->cache->set('key', 'value');
$this->assertFalse($this->cache->has('key'));
}
/**
* @dataProvider dataProvider
*/
public function testGet()
{
$this->cache->set('key', 'value');
$this->assertFalse($this->cache->get('key', false));
}
/**
* @dataProvider dataProvider
*/
public function testSet()
{
$this->assertFalse($this->cache->set('key', 'value'));
}
/**
* @dataProvider dataProvider
*/
public function testDelete()
{
$this->assertTrue($this->cache->delete('key'));
}
/**
* @dataProvider dataProvider
*/
public function testWithOption()
{
$cache = $this->cache->withOption('ttl', 3600);
$this->assertSame(3600, $cache->getOption('ttl'));
$this->assertNotSame($this->cache, $cache);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/FileTest.php | tests/FileTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\File as FileCache;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* FileTest
*/
class FileTest extends AbstractCacheTest
{
/**
* @var vfsStreamDirectory
*/
private $root;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 64 bytes'
];
public function createSimpleCache()
{
$this->root = vfsStream::setup('cache');
return new FileCache(vfsStream::url('cache'));
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/MemoryTest.php | tests/MemoryTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Memory as MemoryCache;
/**
* MemoryTest
*/
class MemoryTest extends AbstractCacheTest
{
public function createSimpleCache()
{
return new MemoryCache();
}
public function tearDown(): void
{
// No need to clear cache, as the adapters don't persist between tests.
}
public function testExceededLimit()
{
$cache = $this->createSimpleCache()->withOption('limit', 1);
$cache->set('foo', 1);
$this->assertTrue($cache->has('foo'));
$cache->set('bar', 1);
$this->assertFalse($cache->has('foo'));
$this->assertTrue($cache->has('bar'));
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/PhpFileTest.php | tests/PhpFileTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\PhpFile as PhpFileCache;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* FileTest with PhpPacker
*/
class PhpFileTest extends AbstractCacheTest
{
/**
* @var vfsStreamDirectory
*/
private $root;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 64 bytes'
];
public function createSimpleCache()
{
$this->root = vfsStream::setup('cache');
return new PhpFileCache(vfsStream::url('cache'));
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/FileTrieTest.php | tests/FileTrieTest.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\File as FileCache;
use Desarrolla2\Cache\File\TrieFilename;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* FileTest with Trie structure
*/
class FileTrieTest extends AbstractCacheTest
{
/**
* @var vfsStreamDirectory
*/
private $root;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 64 bytes'
];
public function createSimpleCache()
{
$this->root = vfsStream::setup('cache');
return (new FileCache(vfsStream::url('cache')))
->withOption('filename', new TrieFilename('%s.php.cache',4));
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/PredisTest.php | tests/PredisTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Predis as PredisCache;
use Predis\Client;
use Predis\Connection\ConnectionException;
/**
* PredisTest
*/
class PredisTest extends AbstractCacheTest
{
/**
* @var Client
*/
protected $client;
public function createSimpleCache()
{
if (!class_exists('Predis\Client')) {
$this->markTestSkipped('The predis library is not available');
}
try {
$this->client = new Client(CACHE_TESTS_PREDIS_DSN, ['exceptions' => false]);
$this->client->connect();
} catch (ConnectionException $e) {
$this->markTestSkipped($e->getMessage());
}
return new PredisCache($this->client);
}
public function tearDown(): void
{
parent::tearDown();
if ($this->client) {
$this->client->disconnect();
}
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/MongoDBTest.php | tests/MongoDBTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\MongoDB as MongoDBCache;
use MongoDB\Client;
/**
* MongoDBTest
*/
class MongoDBTest extends AbstractCacheTest
{
/**
* @var Client
*/
protected static $client;
/**
* Use one client per test, as the MongoDB extension leaves connections open
*/
public static function setUpBeforeClass(): void
{
if (!extension_loaded('mongodb')) {
return;
}
self::$client = new Client(CACHE_TESTS_MONGO_DSN);
self::$client->listDatabases(); // Fail if unable to connect
}
public function createSimpleCache()
{
if (!isset(self::$client)) {
$this->markTestSkipped('The mongodb extension is not available');
}
$collection = self::$client->selectCollection(CACHE_TESTS_MONGO_DATABASE, 'cache');
return (new MongoDBCache($collection))
->withOption('initialize', false);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/MemcachedTest.php | tests/MemcachedTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Memcached as MemcachedCache;
use Memcached;
/**
* MemcachedTest
*/
class MemcachedTest extends AbstractCacheTest
{
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 250 bytes'
];
public function createSimpleCache()
{
if (!extension_loaded('memcached') || !class_exists('\Memcached')) {
$this->markTestSkipped(
'The Memcached extension is not available.'
);
}
// See https://github.com/php-memcached-dev/php-memcached/issues/509
if (version_compare(PHP_VERSION, '8.1.0', '>=')) {
$this->markTestSkipped(
'The Memcached extension is does not work with PHP 8.1 yet.'
);
}
list($host, $port) = explode(':', CACHE_TESTS_MEMCACHED_SERVER) + [1 => 11211];
$adapter = new Memcached();
$adapter->addServer($host, (int)$port);
if (!$adapter->flush()) {
$this->markTestSkipped("Unable to flush Memcached; not running?");
}
return new MemcachedCache($adapter);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/RedisTest.php | tests/RedisTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Redis as RedisCache;
use Redis as PhpRedis;
/**
* RedisTest
*/
class RedisTest extends AbstractCacheTest
{
/**
* @var PhpRedis
*/
protected $client;
public function createSimpleCache()
{
if (!\extension_loaded('redis')) {
$this->markTestSkipped('Redis extension not available.');
}
$client = new PhpRedis();
$success = @$client->connect(CACHE_TESTS_REDIS_HOST, CACHE_TESTS_REDIS_PORT);
if (!$success) {
$this->markTestSkipped('Cannot connect to Redis.');
}
$this->client = $client;
return new RedisCache($this->client);
}
public function tearDown(): void
{
parent::tearDown();
if ($this->client && $this->client->isConnected()) {
$this->client->close();
}
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/AbstractCacheTest.php | tests/AbstractCacheTest.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Cache\IntegrationTests\SimpleCacheTest;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* AbstractCacheTest
*/
abstract class AbstractCacheTest extends SimpleCacheTest
{
/**
* @return array
*/
public function dataProviderForOptions()
{
return [
['ttl', 100],
['prefix', 'test']
];
}
/**
* @dataProvider dataProviderForOptions
*
* @param string $key
* @param mixed $value
*/
public function testWithOption($key, $value)
{
$cache = $this->cache->withOption($key, $value);
$this->assertEquals($value, $cache->getOption($key));
// Check immutability
$this->assertNotSame($this->cache, $cache);
$this->assertNotEquals($value, $this->cache->getOption($key));
}
public function testWithOptions()
{
$data = $this->dataProviderForOptions();
$options = array_combine(array_column($data, 0), array_column($data, 1));
$cache = $this->cache->withOptions($options);
foreach ($options as $key => $value) {
$this->assertEquals($value, $cache->getOption($key));
}
// Check immutability
$this->assertNotSame($this->cache, $cache);
foreach ($options as $key => $value) {
$this->assertNotEquals($value, $this->cache->getOption($key));
}
}
/**
* @return array
*/
public function dataProviderForOptionsException()
{
return [
['ttl', 0, InvalidArgumentException::class],
['foo', 'bar', InvalidArgumentException::class]
];
}
/**
* @dataProvider dataProviderForOptionsException
*
* @param string $key
* @param mixed $value
* @param string $expectedException
*/
public function testWithOptionException($key, $value, $expectedException)
{
$this->expectException($expectedException);
$this->createSimpleCache()->withOption($key, $value);
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/MysqliTest.php | tests/MysqliTest.php | <?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Mysqli as MysqliCache;
/**
* MysqliTest
*/
class MysqliTest extends AbstractCacheTest
{
/**
* @var \mysqli
*/
protected static $mysqli;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 255 bytes'
];
public static function setUpBeforeClass(): void
{
if (class_exists('mysqli')) {
static::$mysqli = new \mysqli(
ini_get('mysqli.default_host') ?: 'localhost',
ini_get('mysqli.default_user') ?: 'root'
);
}
}
public function init(): void
{
if (!class_exists('mysqli')) {
$this->markTestSkipped("mysqli extension not loaded");
}
try {
static::$mysqli->query('CREATE DATABASE IF NOT EXISTS `' . CACHE_TESTS_MYSQLI_DATABASE . '`');
static::$mysqli->select_db(CACHE_TESTS_MYSQLI_DATABASE);
static::$mysqli->query("CREATE TABLE IF NOT EXISTS `cache` "
."( `key` VARCHAR(255), `value` BLOB, `ttl` INT UNSIGNED, PRIMARY KEY (`key`) )");
} catch (\Exception $e) {
$this->markTestSkipped("skipping mysqli test; " . $e->getMessage());
}
if (static::$mysqli->error) {
$this->markTestSkipped(static::$mysqli->error);
}
}
public function createSimpleCache()
{
$this->init();
return (new MysqliCache(static::$mysqli))
->withOption('initialize', false);
}
public static function tearDownAfterClass(): void
{
static::$mysqli->query('DROP DATABASE IF EXISTS `' . CACHE_TESTS_MYSQLI_DATABASE . '`');
static::$mysqli->close();
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/ApcuCacheTest.php | tests/ApcuCacheTest.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Apcu as ApcuCache;
/**
* ApcuCacheTest
*/
class ApcuCacheTest extends AbstractCacheTest
{
public static function setUpBeforeClass(): void
{
// Required to check the TTL for new entries
ini_set('apc.use_request_time', false);
}
public function createSimpleCache()
{
if (!extension_loaded('apcu')) {
$this->markTestSkipped(
'The APCu extension is not available.'
);
}
if (!ini_get('apc.enable_cli')) {
$this->markTestSkipped(
'You need to enable apc.enable_cli'
);
}
return new ApcuCache();
}
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/performance/Apc.php | tests/performance/Apc.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
require_once __DIR__.'/../bootstrap.php';
use Desarrolla2\Cache\Cache;
use Desarrolla2\Cache\Adapter\Apcu;
$cache = new Cache(new Apcu());
require_once __DIR__.'/common.php';
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/performance/NoCache.php | tests/performance/NoCache.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
require_once __DIR__.'/../bootstrap.php';
use Desarrolla2\Cache\Cache;
use Desarrolla2\Cache\Adapter\NotCache;
$cache = new Cache(new NotCache());
require_once __DIR__.'/common.php';
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/performance/common.php | tests/performance/common.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
//build test data outside of timing loop
$data = [];
for ($i = 1; $i <= 10000; $i++) {
$data[$i] = md5($i);
}
$timer = new \Desarrolla2\Timer\Timer(new \Desarrolla2\Timer\Formatter\Human());
for ($i = 1; $i <= 10000; $i++) {
$cache->set($data[$i], $data[$i], 3600);
}
$timer->mark('10.000 set');
for ($i = 1; $i <= 10000; $i++) {
$cache->has($data[$i]);
}
$timer->mark('10.000 has');
for ($i = 1; $i <= 10000; $i++) {
$cache->get($data[$i]);
}
$timer->mark('10.000 get');
for ($i = 1; $i <= 10000; $i++) {
$cache->has($data[$i]);
$cache->get($data[$i]);
}
$timer->mark('10.000 has+get combos');
$benchmarks = $timer->getAll();
foreach ($benchmarks as $benchmark) {
ld($benchmark);
}
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/performance/Mongo.php | tests/performance/Mongo.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
require_once __DIR__.'/../bootstrap.php';
use Desarrolla2\Cache\Cache;
use Desarrolla2\Cache\Adapter\Mongo;
$cache = new Cache(new Mongo('mongodb://localhost:27017'));
require_once __DIR__.'/common.php';
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
desarrolla2/Cache | https://github.com/desarrolla2/Cache/blob/11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5/tests/performance/File.php | tests/performance/File.php | <?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
require_once __DIR__.'/../bootstrap.php';
use Desarrolla2\Cache\Cache;
use Desarrolla2\Cache\Adapter\File;
$cache = new Cache(new File('/tmp'));
require_once __DIR__.'/common.php';
| php | MIT | 11d0e29ebd7ae12e2b53d90d7a9757b1c51c04e5 | 2026-01-05T05:20:41.662521Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/DateTime.php | src/DateTime.php | <?php
namespace Riskihajar\Terbilang;
use Carbon\Carbon;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Riskihajar\Terbilang\Exceptions\InvalidNumber;
class DateTime
{
/**
* Parses a given date into a Carbon object, using the given format.
*
* @param Carbon|string|\DateTime $date The date to parse.
* @param string $format The format to use when parsing the date.
* @return Carbon The parsed date as a Carbon object.
*/
protected function parseDate(Carbon|string|\DateTime $date, string $format = 'Y-m-d'): Carbon
{
if (! $date instanceof Carbon) {
if ($date instanceof \DateTime) {
$date = Carbon::parse($date);
} else {
$date = Carbon::createFromFormat($format, $date);
}
}
return $date;
}
/**
* @throws InvalidNumber
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
*/
public function date(Carbon|string|\DateTime $date, string $format = 'Y-m-d'): Stringable
{
$date = $this->parseDate($date, $format);
$j = $date->format('j');
$n = $date->format('n');
$Y = $date->format('Y');
$numberToWords = new NumberToWords;
$day = $numberToWords->make($j);
$month = strtolower(Lang::get('terbilang::date.month.'.$n, [], config('terbilang.locale') ?: config('app.locale')));
$year = $numberToWords->make($Y);
$template = config('terbilang.output.date', '{DAY} {MONTH} {YEAR}');
$string = str_replace([
'{DAY}',
'{MONTH}',
'{YEAR}',
], [
$day,
$month,
$year,
], $template);
return Str::of($string);
}
/**
* @throws InvalidNumber
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
*/
public function time(Carbon|string|\DateTime $time, string $format = 'H:i:s'): Stringable
{
$time = $this->parseDate($time, $format);
$G = $time->format('G');
$i = $time->format('i');
$s = intval($time->format('s')) ?: null;
$separator = Lang::get('terbilang::date.time.minute-separator', [], config('terbilang.locale') ?: config('app.locale'));
$strMinute = Lang::get('terbilang::date.time.minute', [], config('terbilang.locale') ?: config('app.locale'));
$strSecond = $s ? Lang::get('terbilang::date.time.second', [], config('terbilang.locale') ?: config('app.locale')) : null;
$numberToWords = new NumberToWords;
$hour = $numberToWords->make($G);
$minute = $numberToWords->make($i);
$second = $s ? $numberToWords->make($s) : null;
$template = config('terbilang.output.time', '{HOUR} {SEPARATOR} {MINUTE} {MINUTE_LABEL} {SECOND} {SECOND_LABEL}');
$string = str_replace(
[
'{HOUR}', '{SEPARATOR}', '{MINUTE}', '{MINUTE_LABEL}', '{SECOND}', '{SECOND_LABEL}',
],
[
$hour, $separator, $minute, $strMinute, $second, $strSecond,
],
$template
);
return Str::of($string)->trim();
}
/**
* @throws InvalidNumber
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
*/
public function datetime(Carbon|string|\DateTime $datetime, string $format = 'Y-m-d H:i:s'): Stringable
{
$datetime = $this->parseDate($datetime, $format);
$date = $datetime->format('Y-m-d');
$time = $datetime->format('h:i:s');
$locale = config('terbilang.locale') ?: config('app.locale');
$meridiem = value(function () use ($datetime, $locale) {
$result = Lang::get('terbilang::date.time.'.$datetime->format('a'), [], $locale);
if (is_array($result)) {
$hour = $datetime->format('H');
foreach ($result as $h => $result) {
if ($h <= $hour) {
break;
}
}
}
return $result;
});
$separator = Lang::get('terbilang::date.time.dt-separator', [], $locale);
$string = implode(' ', array_filter([
$this->date($date)->toString(),
$separator,
$this->time($time)->toString(),
$meridiem,
]));
return Str::of($string)->trim();
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Roman.php | src/Roman.php | <?php
namespace Riskihajar\Terbilang;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Riskihajar\Terbilang\Enums\Roman as Enum;
class Roman
{
public function __invoke(mixed $number): Stringable
{
$number = intval($number);
$results = [];
foreach (Enum::cases() as $roman) {
$matches = intval($number / $roman->value);
$results[] = str_repeat($roman->name, $matches);
$number = $number % $roman->value;
}
$results = array_filter($results);
$string = implode('', $results);
return Str::of($string);
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/LargeNumber.php | src/LargeNumber.php | <?php
namespace Riskihajar\Terbilang;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Riskihajar\Terbilang\Enums\LargeNumber as Enum;
class LargeNumber
{
public function __invoke(mixed $number, Enum $target = Enum::Auto, ?int $precision = 2): Stringable
{
$target = $target === Enum::Auto
? Enum::tryFromValue($number)
: $target;
$result = round($number / $target->divider(), $precision);
$string = implode('', [
$result,
$target->abbreviation(),
]);
return Str::of($string);
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/NumberToWords.php | src/NumberToWords.php | <?php
namespace Riskihajar\Terbilang;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
class NumberToWords
{
private $hyphen;
private $conjunction;
private $separator;
private $negative;
private $decimal;
private $dictionary;
private $prenum;
private $locale;
/** @return void */
public function __construct()
{
$this->locale = config('terbilang.locale') ?: config('app.locale');
$this->hyphen = Lang::get('terbilang::terbilang.hyphen', [], $this->locale);
$this->conjunction = Lang::get('terbilang::terbilang.conjunction', [], $this->locale);
$this->separator = Lang::get('terbilang::terbilang.separator', [], $this->locale);
$this->negative = Lang::get('terbilang::terbilang.negative', [], $this->locale);
$this->decimal = Lang::get('terbilang::terbilang.decimal', [], $this->locale);
$this->dictionary = Lang::get('terbilang::terbilang.dictionary', [], $this->locale);
$this->prenum = Lang::get('terbilang::terbilang.prenum', [], $this->locale);
}
/**
* @throws Exceptions\InvalidNumber
*/
private function parseNumber(mixed $number): mixed
{
// parse quoted value and make sure its number
$number = floatval($number);
$isScientific = preg_match('/^[+-]?[0-9]+(\.[0-9]+)?[eE][+-]?[0-9]+$/', $number);
if ($isScientific) { // handle scientific value like 1.0E+15 after parse quoted
$number = sprintf('%0d', $number);
}
if (
($number >= 0 && intval($number) < 0)
|| (intval($number) < 0 - PHP_INT_MAX)
|| $number >= 10_000_000_000_000_000
) {
throw Exceptions\InvalidNumber::isExceed();
}
return $number;
}
private function spellout($number): Stringable
{
$formatter = new \NumberFormatter($this->locale, \NumberFormatter::SPELLOUT);
return Str::of($formatter->format($number));
}
/**
* @throws Exceptions\InvalidNumber
*/
public function make(mixed $number): Stringable
{
if (! is_numeric($number)) {
throw Exceptions\InvalidNumber::isNotNumeric();
}
$number = $this->parseNumber(number: $number);
if (extension_loaded('intl') && config('terbilang.use_intl', true)) {
return $this->spellout($number);
}
if ($number < 0) {
return $this->make(number: abs($number))->prepend($this->negative, ' ');
}
$string = $fraction = null;
if (strpos($number, '.') !== false) {
[$number, $fraction] = explode('.', $number);
}
switch (true) {
case $number < 21:
$string = $this->dictionary[$number];
break;
case $number < 100:
$tens = ((int) ($number / 10)) * 10;
$units = $number % 10;
$string = $this->dictionary[$tens];
if ($units) {
$string .= $this->hyphen.$this->dictionary[$units];
}
break;
case $number < 1000:
$hundreds = $number / 100;
$remains = $number % 100;
if ($this->prenum) {
$lead = (int) substr($number, 0, 1);
$string = ($lead === 1 ? $this->prenum : $this->dictionary[$hundreds].' ').$this->dictionary[100];
} else {
$string = $this->dictionary[$hundreds].' '.$this->dictionary[100];
}
if ($remains) {
$string .= $this->conjunction.$this->make($remains);
}
break;
default:
$baseUnit = pow(1000, floor(log($number, 1000)));
$numBaseUnits = (int) ($number / $baseUnit);
$remains = $number % $baseUnit;
if ($this->prenum) {
$string = ($numBaseUnits === 1 && $baseUnit < 1000000 ? $this->prenum : $this->make($numBaseUnits).' ').$this->dictionary[$baseUnit];
} else {
$string = $this->make($numBaseUnits).' '.$this->dictionary[$baseUnit];
}
if ($remains) {
$string .= $remains < 100 ? $this->conjunction : $this->separator;
$string .= $this->make($remains);
}
break;
}
if ($fraction !== null && is_numeric($fraction)) {
$string .= $this->decimal;
$words = [];
foreach (str_split((string) $fraction) as $number) {
$words[] = $this->dictionary[$number];
}
$string .= implode(' ', $words);
}
return Str::of($string);
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Terbilang.php | src/Terbilang.php | <?php
namespace Riskihajar\Terbilang;
use Carbon\Carbon;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Stringable;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class Terbilang
{
/**
* @throws Exceptions\InvalidNumber
*/
public function make(mixed $number, ?string $suffix = null, ?string $prefix = null): Stringable
{
$locale = config('terbilang.locale') ?: config('app.locale');
$prefix = $prefix ?: Lang::get('terbilang::terbilang.prefix', [], $locale);
$suffix = $suffix ?: Lang::get('terbilang::terbilang.suffix', [], $locale);
return (new NumberToWords)
->make(number: $number)
->prepend($prefix, $prefix ? ' ' : '')
->append($suffix, $suffix ? ' ' : '')
->trim();
}
/**
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
* @throws Exceptions\InvalidNumber
*/
public function distance(Carbon $start, Carbon $end): Stringable
{
return (new DistanceDate)->make(start: $start, end: $end);
}
/**
* @param mixed $template
*
* @deprecated
*/
public function period(
Carbon|string $start,
Carbon|string|null $end = null,
$template = null
): Stringable {
if (! $start instanceof Carbon) {
$start = Carbon::parse($start);
}
if (gettype($end) === 'string') {
$end = Carbon::parse($end);
}
if (is_null($template)) {
$template = config('terbilang.distance.template');
}
return (new DistanceDate)->config([
'template' => $template,
])->make(start: $start, end: $end);
}
/**
* @throws Exceptions\InvalidNumber
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
*/
public function date(Carbon|string $date, string $format = 'Y-m-d'): Stringable
{
return (new DateTime)->date(date: $date, format: $format);
}
/**
* @throws Exceptions\InvalidNumber
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
*/
public function time(Carbon|string $time, string $format = 'H:i:s'): Stringable
{
return (new DateTime)->time(time: $time, format: $format);
}
/**
* @throws Exceptions\InvalidNumber
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
*/
public function datetime(Carbon|string $datetime, string $format = 'Y-m-d H:i:s'): Stringable
{
return (new DateTime)->datetime(datetime: $datetime, format: $format);
}
public function largeNumber(mixed $number, Enums\LargeNumber $target = Enums\LargeNumber::Auto): Stringable
{
return (new LargeNumber)(number: $number, target: $target);
}
/**
* @deprecated
*/
public function short(mixed $number, Enums\LargeNumber|string $target = Enums\LargeNumber::Auto): Stringable
{
if (gettype($target) === 'string') {
$target = Enums\LargeNumber::from($target);
}
return $this->largeNumber(number: $number, target: $target);
}
public function roman(mixed $number): Stringable
{
return (new Roman)(number: $number);
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/DistanceDate.php | src/DistanceDate.php | <?php
namespace Riskihajar\Terbilang;
use Carbon\Carbon;
use DateInterval;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Riskihajar\Terbilang\Enums\DistanceDate as Enum;
use Riskihajar\Terbilang\Exceptions\InvalidNumber;
class DistanceDate
{
private array $config = [];
/** @return void */
public function __construct()
{
$this->config = Config::get('terbilang.distance', []);
}
public function config(array $config): self
{
$this->config = array_merge($this->config, $config);
return $this;
}
/**
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
* @throws InvalidNumber
*/
public function make(
Carbon $start,
?Carbon $end = null): Stringable
{
if (is_null($end)) {
$end = Carbon::now();
}
$type = $this->config['type'];
$interval = $start->diff($end);
if ($type === Enum::Full) {
return $this->full($interval);
} else {
return $this->type($interval, $type);
}
}
/**
* @throws BindingResolutionException
* @throws NotFoundExceptionInterface
* @throws ContainerExceptionInterface
* @throws InvalidNumber
*/
private function full(DateInterval $interval): Stringable
{
$result = $interval->format('%y %m %d %h %i %s');
[$year, $month, $day, $hour, $minute, $second] = explode(' ', $result);
$locale = config('terbilang.locale') ?: config('app.locale');
$listFormat = [
'{YEAR}' => [
'value' => $year,
'label' => Lang::get('terbilang::date.dictionary.year', [], $locale),
'show' => config('terbilang.period.show.year'),
],
'{MONTH}' => [
'value' => $month,
'label' => Lang::get('terbilang::date.dictionary.month', [], $locale),
'show' => config('terbilang.period.show.month'),
],
'{DAY}' => [
'value' => $day,
'label' => Lang::get('terbilang::date.dictionary.day', [], $locale),
'show' => config('terbilang.period.show.day'),
],
'{HOUR}' => [
'value' => $hour,
'label' => Lang::get('terbilang::date.dictionary.hour', [], $locale),
'show' => config('terbilang.period.show.hour'),
],
'{MINUTE}' => [
'value' => $minute,
'label' => Lang::get('terbilang::date.dictionary.minute', [], $locale),
'show' => config('terbilang.period.show.minute'),
],
'{SECOND}' => [
'value' => $second,
'label' => Lang::get('terbilang::date.dictionary.second', [], $locale),
'show' => config('terbilang.period.show.second'),
],
];
$template = $this->config['template'];
$results = [];
$hideZeroValue = $this->config['hide_zero_value'];
$terbilang = $this->config['terbilang'];
$separator = $this->config['separator'];
$numberToWords = new NumberToWords;
foreach (explode(' ', $template) as $key) {
$value = $listFormat[$key]['value'];
$label = $listFormat[$key]['label'];
$show = $listFormat[$key]['show'];
if (($value <= 0 && $hideZeroValue) || ! $show) {
continue;
}
if ($terbilang) {
$value = $numberToWords->make($value);
}
$results[] = $value.$separator.$label;
}
return Str::of(implode(' ', $results))->trim();
}
/**
* @throws InvalidNumber
*/
private function type(DateInterval $interval, Enum $type): Stringable
{
$terbilang = $this->config['terbilang'];
$separator = $this->config['separator'];
$numberToWords = new NumberToWords;
if ($type === Enum::Year) {
$value = $interval->format('%y');
}
$value = match ($type) {
Enum::Year => $interval->format('%y'),
Enum::Month => $interval->format('%m'),
Enum::Day => $interval->format('%a'),
Enum::Hour => intval($interval->format('%h')) + (intval($interval->format('%a')) * 24),
Enum::Minute => intval($interval->format('%i')) + (intval($interval->format('%a')) * 24 * 60),
Enum::Second => intval($interval->format('%s')) + (intval($interval->format('%a')) * 24 * 60 * 60),
default => null,
};
$label = $type->label();
if ($terbilang) {
$value = $numberToWords->make($value);
}
$result = $separator.$value.$separator.$label;
return Str::of($result)->trim();
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/TerbilangServiceProvider.php | src/TerbilangServiceProvider.php | <?php
namespace Riskihajar\Terbilang;
use Riskihajar\Terbilang\Commands\TerbilangLargeNumberCommand;
use Riskihajar\Terbilang\Commands\TerbilangNumberToWordsCommand;
use Riskihajar\Terbilang\Commands\TerbilangRomanCommand;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;
class TerbilangServiceProvider extends PackageServiceProvider
{
public function configurePackage(Package $package): void
{
/*
* This class is a Package Service Provider
*
* More info: https://github.com/spatie/laravel-package-tools
*/
$package
->name('terbilang')
->hasConfigFile()
->hasTranslations()
->hasCommands(
TerbilangNumberToWordsCommand::class,
TerbilangRomanCommand::class,
TerbilangLargeNumberCommand::class,
);
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Exceptions/InvalidNumber.php | src/Exceptions/InvalidNumber.php | <?php
namespace Riskihajar\Terbilang\Exceptions;
use Exception;
final class InvalidNumber extends Exception
{
public static function isExceed(): self
{
return new self('NumToWords only accepts numbers between -'.PHP_INT_MIN.' and '.PHP_INT_MAX);
}
public static function isNotNumeric(): self
{
return new self('Number paramaters is not numeric');
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Facades/Terbilang.php | src/Facades/Terbilang.php | <?php
namespace Riskihajar\Terbilang\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @see \Riskihajar\Terbilang\Terbilang
*/
class Terbilang extends Facade
{
protected static function getFacadeAccessor()
{
return \Riskihajar\Terbilang\Terbilang::class;
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Enums/Roman.php | src/Enums/Roman.php | <?php
namespace Riskihajar\Terbilang\Enums;
enum Roman: int
{
case M = 1000;
case CM = 900;
case D = 500;
case CD = 400;
case C = 100;
case XC = 90;
case L = 50;
case XL = 40;
case X = 10;
case IX = 9;
case V = 5;
case IV = 4;
case I = 1;
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Enums/LargeNumber.php | src/Enums/LargeNumber.php | <?php
namespace Riskihajar\Terbilang\Enums;
use Illuminate\Support\Facades\Lang;
enum LargeNumber: string
{
case Auto = 'auto';
case Kilo = 'kilo';
case Million = 'million';
case Billion = 'billion';
case Trillion = 'trillion';
public function divider(): int
{
return match ($this) {
default => 1,
self::Kilo => 10 ** 3,
self::Million => 10 ** 6,
self::Billion => 10 ** 9,
self::Trillion => 10 ** 12,
};
}
public static function tryFromZeroLength(?int $length): self
{
return match (true) {
default => self::Kilo,
$length >= 12 => self::Trillion,
$length >= 9 => self::Billion,
$length >= 6 => self::Million,
};
}
public static function tryFromBaseUnit(?int $baseUnit): self
{
$zeros = floor(log10($baseUnit));
return self::tryFromZeroLength($zeros);
}
public static function tryFromValue(?float $value): self
{
$baseUnit = pow(1000, floor(log($value, 1000)));
return self::tryFromBaseUnit($baseUnit);
}
public function abbreviation(): ?string
{
$dictionary = Lang::get('terbilang::terbilang.large-number', [], config('terbilang.locale') ?: config('app.locale'));
return $dictionary[$this->value] ?? null;
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Enums/DistanceDate.php | src/Enums/DistanceDate.php | <?php
namespace Riskihajar\Terbilang\Enums;
use Illuminate\Support\Facades\Lang;
enum DistanceDate: string
{
case Day = 'Day';
case Month = 'Month';
case Hour = 'Hour';
case Minute = 'Minute';
case Second = 'Second';
case Year = 'Year';
case Full = 'Full';
public function label(): string
{
return Lang::get('terbilang::date.dictionary.'.strtolower($this->value), [], config('terbilang.locale') ?: config('app.locale'));
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Commands/TerbilangLargeNumberCommand.php | src/Commands/TerbilangLargeNumberCommand.php | <?php
namespace Riskihajar\Terbilang\Commands;
use Illuminate\Console\Command;
use Riskihajar\Terbilang\Enums\LargeNumber;
use Riskihajar\Terbilang\Facades\Terbilang;
class TerbilangLargeNumberCommand extends Command
{
public $signature = 'terbilang:ln {number} {target?}';
public $description = 'Convert Number to Large Number Short Label';
public function handle(): int
{
$number = $this->argument('number');
$target = $this->argument('target') ?: 'kilo';
$target = LargeNumber::from($target);
$result = Terbilang::largeNumber(number: $number, target: $target);
$this->output->writeln("$number : <info>$result</info>");
return self::SUCCESS;
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Commands/TerbilangNumberToWordsCommand.php | src/Commands/TerbilangNumberToWordsCommand.php | <?php
namespace Riskihajar\Terbilang\Commands;
use Illuminate\Console\Command;
use Riskihajar\Terbilang\Facades\Terbilang;
class TerbilangNumberToWordsCommand extends Command
{
public $signature = 'terbilang:word {number}';
public $description = 'Convert Number to Words (terbilang)';
public function handle(): int
{
$number = $this->argument('number');
$result = Terbilang::make($number, ' rupiah', ' senilai');
$this->output->writeln("$number : <info>$result</info>");
return self::SUCCESS;
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/src/Commands/TerbilangRomanCommand.php | src/Commands/TerbilangRomanCommand.php | <?php
namespace Riskihajar\Terbilang\Commands;
use Illuminate\Console\Command;
use Riskihajar\Terbilang\Facades\Terbilang;
class TerbilangRomanCommand extends Command
{
public $signature = 'terbilang:roman {number}';
public $description = 'Convert Number to Roman';
public function handle(): int
{
$number = $this->argument('number');
$result = Terbilang::roman($number);
$this->output->writeln("$number : <info>$result</info>");
return self::SUCCESS;
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/tests/TerbilangNumberToWordsTest.php | tests/TerbilangNumberToWordsTest.php | <?php
namespace Riskihajar\Terbilang\Tests;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Stringable;
use Riskihajar\Terbilang\Exceptions\InvalidNumber;
use Riskihajar\Terbilang\NumberToWords;
it('has make method', function () {
$this->assertTrue(method_exists(NumberToWords::class, 'make'));
});
it('throw InvalidNumber if parameter is not a number', function () {
(new NumberToWords)->make('Rp 1000,-');
})->throws(InvalidNumber::class);
it('throw InvalidNumber if number exceed from PHP_INT_MAX', function () {
(new NumberToWords)->make(PHP_INT_MAX);
})->throws(InvalidNumber::class);
it('can convert number to words', function () {
$this->assertEquals(
'one million',
(new NumberToWords)->make(1_000_000),
);
$this->assertEquals(
'ten thousand',
(new NumberToWords)->make(10_000),
);
});
it('can use language', function () {
Config::set('terbilang.locale', 'id');
$this->assertEquals(
'satu juta',
(new NumberToWords)->make(1_000_000),
);
$this->assertEquals(
'sepuluh ribu',
(new NumberToWords)->make(10_000),
);
$this->assertEquals(
'seribu',
(new NumberToWords)->make(1_000),
);
});
it('allow use \Illuminate\Support\Str pipe like upper', function () {
$this->assertEquals('TWO MILLION', (new NumberToWords)->make(2_000_000)->upper());
});
it('return instance of Stringable', function () {
$this->assertTrue((new NumberToWords)->make(2_500) instanceof Stringable);
});
it('not return string type', function () {
$this->assertFalse(gettype((new NumberToWords)->make(3_500)) === 'string');
});
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/tests/TerbilangLargeNumberTest.php | tests/TerbilangLargeNumberTest.php | <?php
namespace Riskihajar\Terbilang\Tests;
use Illuminate\Support\Stringable;
use Riskihajar\Terbilang\Enums\LargeNumber;
use Riskihajar\Terbilang\LargeNumber as TerbilangLargeNumber;
use Riskihajar\Terbilang\Terbilang;
it('invokeable', function () {
$this->assertTrue(method_exists(TerbilangLargeNumber::class, '__invoke'));
});
it('has default target (Million)', function () {
$this->assertEquals('5M', (new Terbilang)->largeNumber(number: 5_000_000));
});
it('can convert number to large number short', function () {
$this->assertEquals('1M', (new Terbilang)->largeNumber(number: 1_000_000, target: LargeNumber::Million));
});
it('allow use \Illuminate\Support\Str pipe like upper', function () {
$this->assertEquals('1K', (new Terbilang)->largeNumber(number: 1_000, target: LargeNumber::Kilo)->upper());
});
it('return instance of Stringable', function () {
$this->assertTrue((new Terbilang)->largeNumber(2_000) instanceof Stringable);
});
it('not return string type', function () {
$this->assertFalse(gettype((new Terbilang)->largeNumber(3_000)) === 'string');
});
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/tests/Pest.php | tests/Pest.php | <?php
use Riskihajar\Terbilang\Tests\TestCase;
uses(TestCase::class)->in(__DIR__);
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/tests/TerbilangDatetimeToWordTest.php | tests/TerbilangDatetimeToWordTest.php | <?php
namespace Riskihajar\Terbilang\Tests;
use Riskihajar\Terbilang\DateTime;
it('has date method', function () {
expect(method_exists(DateTime::class, 'date'))->toBeTrue();
});
it('has time method', function () {
expect(method_exists(DateTime::class, 'time'))->toBeTrue();
});
it('has datetime method', function () {
expect(method_exists(DateTime::class, 'datetime'))->toBeTrue();
});
it('can convert date to word', function () {
config()->set('terbilang.use_intl', false);
$date = \DateTime::createFromFormat('Y-m-d', '2023-02-01');
$this->assertEquals('one february two thousand and twenty-three', (new DateTime)->date($date));
});
it('can convert time to word', function () {
config()->set('terbilang.use_intl', false);
$time = \DateTime::createFromFormat('H:i:s', '09:30:45');
$this->assertEquals('nine past thirty minutes fourty-five seconds', (new DateTime)->time($time));
});
it('can convert datetime to word', function () {
config()->set('terbilang.use_intl', false);
$datetime = \DateTime::createFromFormat('Y-m-d H:i:s', '2023-03-01 11:12:13');
$this->assertEquals('one march two thousand and twenty-three at eleven past twelve minutes thirteen seconds am', (new DateTime)->datetime($datetime));
});
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/tests/TestCase.php | tests/TestCase.php | <?php
namespace Riskihajar\Terbilang\Tests;
use Orchestra\Testbench\TestCase as Orchestra;
use Riskihajar\Terbilang\Terbilang;
use Riskihajar\Terbilang\TerbilangServiceProvider;
class TestCase extends Orchestra
{
protected $terbilang;
protected function setUp(): void
{
parent::setUp();
$this->terbilang = new Terbilang;
}
protected function getPackageProviders($app)
{
return [
TerbilangServiceProvider::class,
];
}
}
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/tests/TerbilangTest.php | tests/TerbilangTest.php | <?php
namespace Riskihajar\Terbilang\Tests;
use Riskihajar\Terbilang\Terbilang;
it('has make method', function () {
expect(method_exists(Terbilang::class, 'make'))->toBeTrue();
});
it('has distance method', function () {
expect(method_exists(Terbilang::class, 'distance'))->toBeTrue();
});
it('has period method to support old version', function () {
expect(method_exists(Terbilang::class, 'period'))->toBeTrue();
});
it('has date method', function () {
expect(method_exists(Terbilang::class, 'date'))->toBeTrue();
});
it('has time method', function () {
expect(method_exists(Terbilang::class, 'time'))->toBeTrue();
});
it('has datetime method', function () {
expect(method_exists(Terbilang::class, 'datetime'))->toBeTrue();
});
it('has largeNumber method', function () {
expect(method_exists(Terbilang::class, 'largeNumber'))->toBeTrue();
});
it('has short method to support old version', function () {
expect(method_exists(Terbilang::class, 'short'))->toBeTrue();
});
it('has roman method', function () {
expect(method_exists(Terbilang::class, 'roman'))->toBeTrue();
});
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/tests/TerbilangRomanTest.php | tests/TerbilangRomanTest.php | <?php
namespace Riskihajar\Terbilang\Tests;
use Illuminate\Support\Stringable;
use Riskihajar\Terbilang\Roman;
use Riskihajar\Terbilang\Terbilang;
it('invokeable', function () {
$this->assertTrue(method_exists(Roman::class, '__invoke'));
});
it('can convert number to roman', function () {
$this->assertEquals('MMXXIII', (new Terbilang)->roman(2023));
});
it('allow use \Illuminate\Support\Str pipe like lower', function () {
$this->assertEquals('mmxxiii', (new Terbilang)->roman(2023)->lower());
});
it('return instance of Stringable', function () {
$this->assertTrue((new Terbilang)->roman(1234) instanceof Stringable);
});
it('not return string type', function () {
$this->assertFalse(gettype((new Terbilang)->roman(1234)) === 'string');
});
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/config/terbilang.php | config/terbilang.php | <?php
// config for Riskihajar/Terbilang
return [
/*
|--------------------------------------------------------------------------
| Date Output Format
|--------------------------------------------------------------------------
|
| This value is output format for function Terbilang::date()
| default date format is '{DAY} {MONTH} {YEAR}'
| default time format is '{HOUR} {SEPARATOR} {MINUTE} {MINUTE_LABEL} {SECOND} {SECOND_LABEL}'
| you can mondify for example 'day {DAY} month {MONTH} year {YEAR}'
*/
'output' => [
'date' => '{DAY} {MONTH} {YEAR}',
'time' => '{HOUR} {SEPARATOR} {MINUTE} {MINUTE_LABEL} {SECOND} {SECOND_LABEL}',
],
/**
* Locale
* if you want to change locale for output this package only
* but want keep app using default locale
*/
'locale' => 'en',
/**
* use intl module if enabled
* just disabled if you want use native intl module php
* look : https://www.php.net/manual/en/class.numberformatter.php#numberformatter.constants.spellout
*/
'use_intl' => true,
/*
|--------------------------------------------------------------------------
| Distance Between Date Output Format
|--------------------------------------------------------------------------
|
| This value is output template for function Terbilang::distance()
| default template FULL, available template FULL, YEAR, MONTH, DAY, HOUR, MINUTE, SECOND
*/
'distance' => [
'type' => \Riskihajar\Terbilang\Enums\DistanceDate::Day,
'template' => '{YEAR} {MONTH} {DAY} {HOUR} {MINUTE} {SECOND}',
'hide_zero_value' => true,
'separator' => ' ',
'terbilang' => false,
'show' => [
'year' => true,
'month' => true,
'day' => true,
'hour' => true,
'minute' => true,
'second' => true,
],
],
];
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/resources/lang/en/date.php | resources/lang/en/date.php | <?php
return [
'day' => [
'Mon' => 'Monday',
'Tue' => 'Tuesday',
'Wed' => 'Wednesday',
'Thu' => 'Thursday',
'Fri' => 'Friday',
'Sat' => 'Saturday',
'Sun' => 'Sunday',
],
'month' => [
1 => 'January',
2 => 'February',
3 => 'March',
4 => 'April',
5 => 'May',
6 => 'June',
7 => 'July',
8 => 'August',
9 => 'September',
10 => 'October',
11 => 'November',
12 => 'December',
],
'time' => [
'dt-separator' => 'at',
'minute-separator' => 'past',
'minute' => 'minutes',
'second' => 'seconds',
'am' => 'am',
'pm' => 'pm',
],
'dictionary' => [
'second' => 'seconds',
'minute' => 'minutes',
'hour' => 'hours',
'day' => 'days',
'month' => 'months',
'year' => 'years',
'week' => 'weeks',
],
];
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/resources/lang/en/terbilang.php | resources/lang/en/terbilang.php | <?php
return [
'hyphen' => '-',
'conjunction' => ' and ',
'separator' => ', ',
'negative' => 'negative ',
'decimal' => ' point ',
'prefix' => '',
'suffix' => '',
'prenum' => '',
'large-number' => [
'kilo' => 'k',
'million' => 'M',
'billion' => 'B',
'trillion' => 'T',
],
'dictionary' => [
0 => 'zero',
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
7 => 'seven',
8 => 'eight',
9 => 'nine',
10 => 'ten',
11 => 'eleven',
12 => 'twelve',
13 => 'thirteen',
14 => 'fourteen',
15 => 'fifteen',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen',
20 => 'twenty',
30 => 'thirty',
40 => 'fourty',
50 => 'fifty',
60 => 'sixty',
70 => 'seventy',
80 => 'eighty',
90 => 'ninety',
100 => 'hundred',
1000 => 'thousand',
1000000 => 'million',
1000000000 => 'billion',
1000000000000 => 'trillion',
1000000000000000 => 'quadrillion',
1000000000000000000 => 'quintillion',
],
];
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/resources/lang/pt/date.php | resources/lang/pt/date.php | <?php
return [
'day' => [
'Mon' => 'Segunda-feira',
'Tue' => 'Terça-feira',
'Wed' => 'Quarta-feira',
'Thu' => 'Quinta-feira',
'Fri' => 'Sexta-feira',
'Sat' => 'Sábado',
'Sun' => 'Domingo',
],
'month' => [
1 => 'Janeiro',
2 => 'Fevereiro',
3 => 'Março',
4 => 'Abril',
5 => 'Maio',
6 => 'Junho',
7 => 'Julho',
8 => 'Agosto',
9 => 'Setembro',
10 => 'Outubro',
11 => 'Novembro',
12 => 'Dezembro',
],
'time' => [
'dt-separator' => 'em',
'minute-separator' => 'passado',
'minute' => 'minutos',
'second' => 'segundos',
'am' => 'am',
'pm' => 'pm',
],
'dictionary' => [
'second' => 'segundos',
'minute' => 'minutos',
'hour' => 'horas',
'day' => 'dias',
'month' => 'meses',
'year' => 'anos',
'week' => 'semanas',
],
];
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/resources/lang/pt/terbilang.php | resources/lang/pt/terbilang.php | <?php
return [
'hyphen' => '-',
'conjunction' => ' e ',
'separator' => ', ',
'negative' => 'negativo ',
'decimal' => ' ponto ',
'prefix' => '',
'suffix' => '',
'prenum' => '',
'short' => [
'kilo' => 'k',
'million' => 'M',
'billion' => 'B',
'trillion' => 'T',
],
'dictionary' => [
0 => 'zero',
1 => 'um',
2 => 'dois',
3 => 'três',
4 => 'quatro',
5 => 'cinco',
6 => 'seis',
7 => 'sete',
8 => 'oito',
9 => 'nove',
10 => 'dez',
11 => 'onze',
12 => 'doze',
13 => 'treze',
14 => 'quatorze',
15 => 'quinze',
16 => 'dezesseis',
17 => 'dezessete',
18 => 'dezoito',
19 => 'dezenove',
20 => 'vinte',
30 => 'trinta',
40 => 'quarenta',
50 => 'cinquenta',
60 => 'sessenta',
70 => 'setenta',
80 => 'oitenta',
90 => 'noventa',
100 => 'cem',
1000 => 'mil',
1000000 => 'milhão',
1000000000 => 'bilhão',
1000000000000 => 'trilhão',
1000000000000000 => 'quadrilhão',
1000000000000000000 => 'quintilhão',
],
];
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/resources/lang/id/date.php | resources/lang/id/date.php | <?php
return [
'day' => [
'Mon' => 'Senin',
'Tue' => 'Selasa',
'Wed' => 'Rabu',
'Thu' => 'Kamis',
'Fri' => 'Jum\'at',
'Sat' => 'Sabtu',
'Sun' => 'Minggu',
],
'month' => [
1 => 'Januari',
2 => 'Februari',
3 => 'Maret',
4 => 'April',
5 => 'Mei',
6 => 'Juni',
7 => 'Juli',
8 => 'Agustus',
9 => 'September',
10 => 'Oktober',
11 => 'Nopember',
12 => 'Desember',
],
'time' => [
'dt-separator' => 'pukul',
'minute-separator' => 'lewat',
'minute' => 'menit',
'second' => 'detik',
'am' => [ // sort by large clock first
11 => 'siang',
0 => 'pagi',
],
'pm' => [ // sort by large clock first
19 => 'malam',
13 => 'sore',
12 => 'siang',
],
],
'dictionary' => [
'second' => 'detik',
'minute' => 'menit',
'hour' => 'jam',
'day' => 'hari',
'month' => 'bulan',
'year' => 'tahun',
'week' => 'minggu',
],
];
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
riskihajar/terbilang | https://github.com/riskihajar/terbilang/blob/c243473508ad84b7642085169e6fea170e8b09d4/resources/lang/id/terbilang.php | resources/lang/id/terbilang.php | <?php
return [
'hyphen' => ' ',
'conjunction' => ' ',
'separator' => ' ',
'negative' => 'negatif ',
'decimal' => ' titik ',
'prefix' => '',
'suffix' => '',
'prenum' => 'se',
'large-number' => [
'kilo' => 'k',
'million' => 'jt',
'billion' => 'M',
'trillion' => 'T',
],
'dictionary' => [
0 => 'nol',
1 => 'satu',
2 => 'dua',
3 => 'tiga',
4 => 'empat',
5 => 'lima',
6 => 'enam',
7 => 'tujuh',
8 => 'delapan',
9 => 'sembilan',
10 => 'sepuluh',
11 => 'sebelas',
12 => 'dua belas',
13 => 'tiga belas',
14 => 'empat belas',
15 => 'lima belas',
16 => 'enam belas',
17 => 'tujuh belas',
18 => 'delapan belas',
19 => 'sembilan belas',
20 => 'dua puluh',
30 => 'tiga puluh',
40 => 'empat puluh',
50 => 'lima puluh',
60 => 'enam puluh',
70 => 'tujuh puluh',
80 => 'delapan puluh',
90 => 'sembilan puluh',
100 => 'ratus',
1000 => 'ribu',
1000000 => 'juta',
1000000000 => 'miliar',
1000000000000 => 'triliun',
1000000000000000 => 'kuadriliun',
1000000000000000000 => 'kuintiliun',
],
];
| php | MIT | c243473508ad84b7642085169e6fea170e8b09d4 | 2026-01-05T05:20:52.032227Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/.php-cs-fixer.php | .php-cs-fixer.php | <?php
// File used for "php-cs-fixer" - go and change code based on rules
use PhpCsFixer\Config;
use PhpCsFixer\Finder;
$rules = [
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'default' => 'single_space',
'operators' => ['=>' => null]
],
'blank_line_after_namespace' => true,
'blank_line_after_opening_tag' => true,
'blank_line_before_statement' => [
'statements' => ['return']
],
'braces' => true,
'cast_spaces' => true,
'class_attributes_separation' => [
'elements' => ['method']
],
'class_definition' => true,
'concat_space' => [
'spacing' => 'none'
],
'header_comment' => [
'header' => 'header',
],
'align_multiline_comment' => [
'comment_type' => 'all_multiline'
]
'declare_equal_normalize' => true,
'elseif' => true,
'encoding' => true,
'full_opening_tag' => true,
'fully_qualified_strict_types' => true, // added by Shift
'function_declaration' => true,
'function_typehint_space' => true,
'heredoc_to_nowdoc' => true,
'include' => true,
'increment_style' => ['style' => 'post'],
'indentation_type' => true,
'linebreak_after_opening_tag' => true,
'line_ending' => true,
'lowercase_cast' => true,
'lowercase_constants' => true,
'lowercase_keywords' => true,
'lowercase_static_reference' => true, // added from Symfony
'magic_method_casing' => true, // added from Symfony
'magic_constant_casing' => true,
'method_argument_space' => true,
'native_function_casing' => true,
'no_alias_functions' => true,
'no_extra_blank_lines' => [
'tokens' => [
'extra',
'throw',
'use',
'use_trait',
]
],
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_closing_tag' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_mixed_echo_print' => [
'use' => 'echo'
],
'no_multiline_whitespace_around_double_arrow' => true,
'multiline_whitespace_before_semicolons' => [
'strategy' => 'no_multi_line'
],
'no_short_bool_cast' => true,
'no_singleline_whitespace_before_semicolons' => true,
'no_spaces_after_function_name' => true,
'no_spaces_around_offset' => true,
'no_spaces_inside_parenthesis' => true,
'no_trailing_comma_in_list_call' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'no_unneeded_control_parentheses' => true,
'no_unreachable_default_argument_value' => true,
'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'normalize_index_brace' => true,
'not_operator_with_successor_space' => true,
'object_operator_without_whitespace' => true,
'ordered_imports' => ['sortAlgorithm' => 'alpha'],
'phpdoc_indent' => true,
'phpdoc_inline_tag' => true,
'phpdoc_no_access' => true,
'phpdoc_no_package' => true,
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_scalar' => true,
'phpdoc_single_line_var_spacing' => true,
'phpdoc_summary' => true,
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'phpdoc_types' => true,
'phpdoc_var_without_name' => true,
'psr4' => true,
'self_accessor' => true,
'short_scalar_cast' => true,
'simplified_null_return' => false, // disabled by Shift
'single_blank_line_at_eof' => true,
'single_blank_line_before_namespace' => true,
'single_class_element_per_statement' => true,
'single_import_per_statement' => true,
'single_line_after_imports' => true,
'single_line_comment_style' => [
'comment_types' => ['hash']
],
'single_quote' => true,
'space_after_semicolon' => true,
'standardize_not_equals' => true,
'switch_case_semicolon_to_colon' => true,
'switch_case_space' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'visibility_required' => [
'elements' => ['method', 'property']
],
'whitespace_after_comma_in_array' => true,
];
$project_path = __DIR__;
$finder = Finder::create()
->in([
$project_path . '/app',
$project_path . '/config',
$project_path . '/database',
$project_path . '/resources',
$project_path . '/routes',
$project_path . '/tests',
])
->name('*.php')
->notName('*.blade.php')
->ignoreDotFiles(true)
->ignoreVCS(true);
return Config::create()
->setFinder($finder)
->setRules($rules)
->setRiskyAllowed(true)
->setUsingCache(true);
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/server.php | server.php | <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/helpers.php | app/helpers.php | <?php
if (! function_exists('array_merge_when')) {
function array_merge_when(array $base, $merge, $condition = false)
{
if (!$condition) {
return $base;
}
if ($merge instanceof Closure) {
$merge = call_user_func($merge);
}
return array_merge($base, $merge);
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Daybreak.php | app/Daybreak.php | <?php
namespace App;
use App\Providers\Features;
use App\Contracts\AddsAbsences;
use App\Contracts\AddsLocation;
use App\Formatter\DateFormatter;
use App\Contracts\RemovesAbsence;
use App\Contracts\AddsAbsenceType;
use App\Contracts\AddsTargetHours;
use App\Contracts\ApprovesAbsence;
use App\Contracts\DeletesAccounts;
use App\Contracts\RemovesLocation;
use App\Contracts\DeletesLocations;
use App\Contracts\AddsPublicHoliday;
use App\Contracts\AddsTimeTrackings;
use App\Contracts\FiltersEvaluation;
use App\Contracts\RemovesTargetHour;
use App\Contracts\RemovesAbsenceType;
use App\Contracts\UpdatesAbsenceType;
use App\Contracts\AddsLocationMembers;
use App\Contracts\RemovesTimeTracking;
use App\Contracts\UpdatesTimeTracking;
use App\Contracts\RemovesPublicHoliday;
use App\Contracts\UpdatesLocationNames;
use App\Contracts\ImportsPublicHolidays;
use App\Contracts\AddsDefaultRestingTime;
use App\Contracts\InvitesLocationMembers;
use App\Contracts\RemovesLocationMembers;
use App\Contracts\AddsVacationEntitlements;
use App\Contracts\RemovesDefaultRestingTime;
use App\Contracts\UpdatesLocationMembersRole;
use App\Contracts\RemovesVacationEntitlements;
use App\Contracts\TransfersVacationEntitlements;
use App\Contracts\UpdatesEmployeeProfile;
class Daybreak
{
public static $membershipModel = 'App\\Models\\Membership';
public static $locationModel = 'App\\Models\\Location';
public static function membershipModel()
{
return static::$membershipModel;
}
public static function locationModel()
{
return static::$locationModel;
}
/**
* Get a new instance of the location model.
*
* @return mixed
*/
public static function newLocationModel()
{
$model = static::locationModel();
return new $model;
}
/**
* Specify the location model that should be used by Daybreak.
*
* @param string $model
* @return static
*/
public static function useLocationModel(string $model)
{
static::$locationModel = $model;
return new static;
}
public static function inviteLocationMembersUsing(string $class)
{
return app()->singleton(InvitesLocationMembers::class, $class);
}
public static function addLocationMembersUsing(string $class)
{
return app()->singleton(AddsLocationMembers::class, $class);
}
/**
* Register a class / callback that should be used to update location names.
*
* @param string $class
* @return void
*/
public static function updateLocationNamesUsing(string $class)
{
return app()->singleton(UpdatesLocationNames::class, $class);
}
public static function updatesLocationMembersRoleUsing(string $class)
{
return app()->singleton(UpdatesLocationMembersRole::class, $class);
}
public static function removesLocationMembersUsing(string $class)
{
return app()->singleton(RemovesLocationMembers::class, $class);
}
public static function addsTargetHoursUsing(string $class)
{
return app()->singleton(AddsTargetHours::class, $class);
}
public static function addsAbsencesUsing(string $class)
{
return app()->singleton(AddsAbsences::class, $class);
}
public static function formatsDatesUsing(string $class)
{
return app()->singleton(DateFormatter::class, $class);
}
public static function addsTimeTrackingsUsing(string $class)
{
return app()->singleton(AddsTimeTrackings::class, $class);
}
public static function approvesAbsenceUsing(string $class)
{
return app()->singleton(ApprovesAbsence::class, $class);
}
public static function addsPublicHolidayUsing(string $class)
{
return app()->singleton(AddsPublicHoliday::class, $class);
}
public static function removesPublicHolidayUsing(string $class)
{
return app()->singleton(RemovesPublicHoliday::class, $class);
}
public static function filtersEvaluationUsing(string $class)
{
return app()->singleton(FiltersEvaluation::class, $class);
}
public static function removesTimeTrackingUsing(string $class)
{
return app()->singleton(RemovesTimeTracking::class, $class);
}
public static function removesAbsenceUsing(string $class)
{
return app()->singleton(RemovesAbsence::class, $class);
}
public static function removesAbsenceTypeUsing(string $class)
{
return app()->singleton(RemovesAbsenceType::class, $class);
}
public static function addsAbsenceTypeUsing(string $class)
{
return app()->singleton(AddsAbsenceType::class, $class);
}
public static function removesTargetHourUsing(string $class)
{
return app()->singleton(RemovesTargetHour::class, $class);
}
public static function addsVacationEntitlementUsing(string $class)
{
return app()->singleton(AddsVacationEntitlements::class, $class);
}
public static function transfersVacationEntitlementUsing(string $class)
{
return app()->singleton(TransfersVacationEntitlements::class, $class);
}
public static function removesVacationEntitlementUsing(string $class)
{
return app()->singleton(RemovesVacationEntitlements::class, $class);
}
public static function importsPublicHolidaysUsing(string $class)
{
return app()->singleton(ImportsPublicHolidays::class, $class);
}
public static function deletesAccountsUsing(string $class)
{
return app()->singleton(DeletesAccounts::class, $class);
}
public static function deletesLocationsUsing(string $class)
{
return app()->singleton(DeletesLocations::class, $class);
}
public static function removesLocationsUsing(string $class)
{
return app()->singleton(RemovesLocation::class, $class);
}
public static function addsLocationsUsing(string $class)
{
return app()->singleton(AddsLocation::class, $class);
}
public static function updatesTimeTrackingsUsing(string $class)
{
return app()->singleton(UpdatesTimeTracking::class, $class);
}
public static function updatesAbsenceTypeUsing(string $class)
{
return app()->singleton(UpdatesAbsenceType::class, $class);
}
public static function updatesEmployeeProfileUsing(string $class)
{
return app()->singleton(UpdatesEmployeeProfile::class, $class);
}
public static function addsDefaultRestingTimeUsing(string $class)
{
return app()->singleton(AddsDefaultRestingTime::class, $class);
}
public static function removesDefaultRestingTimeUsing(string $class)
{
return app()->singleton(RemovesDefaultRestingTime::class, $class);
}
/**
* Determine if the application has payroll enabled.
*
* @return bool
*/
public static function hasEmployeePayrollFeature()
{
return Features::hasEmployeePayrollFeature();
}
/**
* Determine if the application has payroll enabled.
*
* @return bool
*/
public static function hasProjectBillingFeature()
{
return Features::hasProjectBillingFeature();
}
/**
* Determine if the application has payroll enabled.
*
* @return bool
*/
public static function hasCaldavFeature()
{
return Features::hasCaldavFeature();
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Jobs/ExpireVacationEntitlements.php | app/Jobs/ExpireVacationEntitlements.php | <?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use App\Models\VacationEntitlement;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class ExpireVacationEntitlements implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
VacationEntitlement::shouldExpire()->get()->each->expire();
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Jobs/SendAbsenceApproved.php | app/Jobs/SendAbsenceApproved.php | <?php
namespace App\Jobs;
use App\Models\User;
use App\Models\Absence;
use Illuminate\Bus\Queueable;
use App\Mail\AbsenceStatusApproved;
use Illuminate\Support\Facades\Mail;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SendAbsenceApproved implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $absence;
public function __construct(Absence $absence)
{
$this->absence = $absence;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$users = User::all()->filter
->hasLocationRole($this->absence->location, 'admin')
->merge(collect([$this->absence->employee]));
Mail::to($users)
->send(new AbsenceStatusApproved($this->absence->employee, $this->absence));
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Formatter/GermanDateFormatter.php | app/Formatter/GermanDateFormatter.php | <?php
namespace App\Formatter;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use App\Rules\DateFormatterRule;
use App\Rules\DateTimeFormatterRule;
use Illuminate\Support\Facades\Date;
use Illuminate\Contracts\Validation\Rule;
use Symfony\Component\Routing\Exception\InvalidParameterException;
class GermanDateFormatter implements DateFormatter
{
/**
* Determine if the given value is a standard "DE" date format.
*
* @param string $value
* @return bool
*/
public function isStandardDateFormat($value)
{
return preg_match('/^(\d{1,2}).(\d{1,2}).(\d{4})$/', $value);
}
public function strToDate($value, $endOfDay = false)
{
if ($this->isStandardDateFormat($value)) {
$date = Date::instance(Carbon::createFromFormat('d.m.Y', $value));
if ($endOfDay) {
return $date->endOfDay();
} else {
return $date->startOfDay();
}
} else {
throw new InvalidParameterException($value.' is not a standard date format "d.m.Y"');
}
}
public function formatDateForView($date)
{
return $date->format('d.m.Y');
}
public function formatDateTimeForView($date)
{
return $date->format('d.m.Y H:i');
}
public function generateTimeStr(string $date = null, string $hours = null, string $minutes = null)
{
return $date.' '.str_pad($hours,2,"0",STR_PAD_LEFT).':'.str_pad($minutes,2,"0",STR_PAD_LEFT);
}
public function timeStrToCarbon(string $timeStr) : CarbonImmutable
{
return CarbonImmutable::createFromTimestamp(strtotime($timeStr));
}
public function dateTimeFormatRule() : Rule
{
return new DateTimeFormatterRule();
}
public function dateFormatRule() : Rule
{
return new DateFormatterRule();
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Formatter/DateFormatter.php | app/Formatter/DateFormatter.php | <?php
namespace App\Formatter;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Validation\Rule;
interface DateFormatter
{
/**
* Determine if the given value is a standard date format.
*
* @param string $value
* @return bool
*/
public function isStandardDateFormat($value);
public function strToDate($value, $endOfDay = false);
public function formatDateForView($date);
public function formatDateTimeForView($date);
public function generateTimeStr(string $date = null, string $hours = null, string $minutes = null);
public function timeStrToCarbon(string $timeStr) : CarbonImmutable;
public function dateFormatRule() : Rule;
public function dateTimeFormatRule() : Rule;
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Exceptions/Handler.php | app/Exceptions/Handler.php | <?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
NoCurrentLocationSetForUserException::class
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Exceptions/NoCurrentLocationSetForUserException.php | app/Exceptions/NoCurrentLocationSetForUserException.php | <?php
namespace App\Exceptions;
use Exception;
class NoCurrentLocationSetForUserException extends Exception
{
//
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Kernel.php | app/Http/Kernel.php | <?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\EnsureUserHasCurrentLocation::class
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class
];
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Livewire/AccountNavigationMenu.php | app/Http/Livewire/AccountNavigationMenu.php | <?php
namespace App\Http\Livewire;
use Livewire\Component;
class AccountNavigationMenu extends Component
{
/**
* The component's listeners.
*
* @var array
*/
protected $listeners = [
'refresh-navigation-dropdown' => '$refresh',
];
/**
* Render the component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('account-navigation-menu');
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Livewire/TrimAndNullEmptyStrings.php | app/Http/Livewire/TrimAndNullEmptyStrings.php | <?php
namespace App\Http\Livewire;
trait TrimAndNullEmptyStrings
{
/**
* Check why this is needed with livewire.
* https://github.com/livewire/livewire/issues/823
* Sending empty strings instead of null (dafault laravel) is intended by Livewire.
*
* @param srting $name
* @param mixed $value
* @return void
*/
public function updatedTrimAndNullEmptyStrings($name, $value)
{
if (is_string($value)) {
$value = trim($value);
$value = $value === '' ? null : $value;
data_set($this, $name, $value);
}
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Livewire/Locations/LocationManager.php | app/Http/Livewire/Locations/LocationManager.php | <?php
namespace App\Http\Livewire\Locations;
use App\Daybreak;
use App\Models\User;
use App\Models\Account;
use Livewire\Component;
use App\Contracts\AddsLocation;
use App\Contracts\RemovesLocation;
class LocationManager extends Component
{
/**
* The account instance
*/
public $account;
/**
* The employee instance
*/
public $employee;
/**
* Holds the open/closed state for the modal window
*/
public $addLocation = false;
/**
* Fetch the form state
*/
public $addLocationForm = [
'name' => ''
];
/**
* Indicates if the application is confirming if a public holiday should be removed.
*
* @var bool
*/
public $confirmingLocationRemoval = false;
/**
* The ID of the public holiday being removed.
*
* @var int|null
*/
public $locationIdBeingRemoved = null;
public function confirmLocationRemoval($locationId)
{
$this->confirmingLocationRemoval = true;
$this->locationIdBeingRemoved = $locationId;
}
/**
* Removes a location
*
* @param \App\Contracts\RemovesLocation $remover
* @return void
*/
public function removeLocation(RemovesLocation $remover)
{
$remover->remove(
$this->employee,
$this->locationIdBeingRemoved
);
$this->confirmingLocationRemoval = false;
$this->locationIdBeingRemoved = null;
$this->account = $this->account->fresh();
}
public function mount(Account $account, User $employee)
{
$this->account = $account;
$this->employee = $employee;
}
public function addLocation()
{
$this->addLocation = true;
}
public function cancelAddLocation()
{
$this->addLocation = false;
}
public function enterLocation($locationId)
{
$location = Daybreak::newLocationModel()->findOrFail($locationId);
if (! $this->employee->switchLocation($location)) {
abort(403);
}
return redirect(config('fortify.home'), 303);
}
public function confirmAddLocation(AddsLocation $adder)
{
$this->resetErrorBag();
$adder->add(
$this->account,
$this->employee,
[
'name' => $this->addLocationForm['name'],
'owned_by' => $this->employee->id
]
);
$this->addLocationForm = [
'name' => ''
];
$this->account = $this->account->fresh();
$this->emit('saved');
$this->addLocation = false;
}
public function render()
{
return view('locations.location-manager');
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Livewire/Locations/AbsenceTypesManager.php | app/Http/Livewire/Locations/AbsenceTypesManager.php | <?php
namespace App\Http\Livewire\Locations;
use App\Models\User;
use Livewire\Component;
use App\Models\Location;
use App\Contracts\AddsAbsenceType;
use App\Contracts\RemovesAbsenceType;
use App\Contracts\UpdatesAbsenceType;
class AbsenceTypesManager extends Component
{
public $location;
public $addAbsenceType = false;
public $currentAbsenceType;
public $confirmingAbsenceTypeRemoval = false;
public $absenceTypeIdBeingRemoved = null;
public $addAbsenceTypeForm = [
'title' => '',
'affect_vacation_times' => false,
'affect_evaluations' => false,
'regard_holidays' => true,
'assign_new_users' => true,
'remove_working_sessions_on_confirm' => false,
'evaluation_calculation_setting' => null
];
public $evaluationOptions = [];
public $selectedEmployees = [];
public $employees;
public function manageAbsenceType()
{
// have a look here on why we should convert input values to string
// https://github.com/livewire/livewire/issues/788
$this->selectedEmployees = $this->location->allUsers()
->map(function (User $user) {
return (string) $user->id;
})->toArray();
$this->addAbsenceType = true;
}
public function stopManagingAbsenceType()
{
$this->addAbsenceType = false;
$this->currentAbsenceType = null;
$this->reset(['addAbsenceTypeForm', 'selectedEmployees']);
}
public function updateAbsenceType($absenceTypeId)
{
$this->currentAbsenceType = $this->location->absenceTypeById($absenceTypeId);
$this->addAbsenceTypeForm = $this->currentAbsenceType->toArray();
// have a look here on why we should convert input values to string
// https://github.com/livewire/livewire/issues/788
$this->selectedEmployees = $this->currentAbsenceType->users()->orderBy('users.id','ASC')
->select('users.id')
->get()
->map(function (User $user) {
return (string) $user->id;
})->toArray();
$this->addAbsenceType = true;
}
public function createAbsenceType(AddsAbsenceType $adder)
{
$this->resetErrorBag();
$adder->add(
$this->location,
$this->addAbsenceTypeForm,
$this->selectedEmployees
);
$this->location = $this->location->fresh();
$this->stopManagingAbsenceType();
}
public function confirmUpdateAbsenceType(UpdatesAbsenceType $updater)
{
$this->resetErrorBag();
$updater->update(
$this->currentAbsenceType,
$this->addAbsenceTypeForm,
$this->selectedEmployees
);
$this->location = $this->location->fresh();
$this->stopManagingAbsenceType();
}
public function mount(Location $location)
{
$this->location = $location;
$this->employees = $location->allUsers()->pluck('name','id')->toArray();
$this->evaluationOptions = $this->getDefaultEvaluationOptions();
}
public function toggleVacationContingent()
{
$this->addAbsenceTypeForm['affect_vacation_times'] = $this->addAbsenceTypeForm['affect_vacation_times'] ? false : true;
}
public function toggleAffectsEvaluation()
{
$this->addAbsenceTypeForm['affect_evaluations'] = $this->addAbsenceTypeForm['affect_evaluations'] ? false : true;
if (!$this->addAbsenceTypeForm['affect_evaluations']) {
$this->addAbsenceTypeForm['evaluation_calculation_setting'] = null;
}
}
public function toggleRegardHolidays()
{
$this->addAbsenceTypeForm['regard_holidays'] = $this->addAbsenceTypeForm['regard_holidays'] ? false : true;
}
public function toggleAssignNewUsers()
{
$this->addAbsenceTypeForm['assign_new_users'] = $this->addAbsenceTypeForm['assign_new_users'] ? false : true;
}
public function toggleRemoveWorkingSessionsOnConfirm()
{
$this->addAbsenceTypeForm['remove_working_sessions_on_confirm'] = $this->addAbsenceTypeForm['remove_working_sessions_on_confirm'] ? false : true;
}
public function confirmAbsenceTypeRemoval($absenceTypeId)
{
$this->absenceTypeIdBeingRemoved = $absenceTypeId;
$this->confirmingAbsenceTypeRemoval = true;
}
public function removeAbsenceType(RemovesAbsenceType $remover)
{
$remover->remove($this->location, $this->absenceTypeIdBeingRemoved);
$this->absenceTypeIdBeingRemoved = null;
$this->confirmingAbsenceTypeRemoval = false;
$this->location = $this->location->fresh();
}
public function getDefaultEvaluationOptions()
{
return [
'target_to_zero' => [
'label' => __('Target to zero (to be implemented)'),
'description' => __('The target hours will be set to zero in the evaluation.')
],
'absent_to_target' => [
'label' => __('Absent to target'),
'description' => __('The absence hours will be summed up.')
],
'fixed_value' => [
'label' => __('Fixed value (to be implemented)'),
'description' => __('Caclulate a fixed value.')
],
'custom_value'=> [
'label' => __('Custom value (to be implemented)'),
'description' => __('Employee specific values.')
]
];
}
public function render()
{
return view('livewire.locations.absence-types-manager');
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Livewire/Locations/Calendar.php | app/Http/Livewire/Locations/Calendar.php | <?php
namespace App\Http\Livewire\Locations;
use Carbon\Carbon;
use App\Models\AbsenceIndex;
use App\Models\PublicHoliday;
use Illuminate\Support\Collection;
use Asantibanez\LivewireCalendar\LivewireCalendar;
class Calendar extends LivewireCalendar
{
public $employee;
public function mount(
$initialYear = null,
$initialMonth = null,
$weekStartsAt = null,
$calendarView = null,
$dayView = null,
$eventView = null,
$dayOfWeekView = null,
$dragAndDropClasses = null,
$beforeCalendarView = "calendars.before-calendar-view",
$afterCalendarView = null,
$pollMillis = null,
$pollAction = null,
$dragAndDropEnabled = false,
$dayClickEnabled = false,
$eventClickEnabled = false,
$extras = [],
$employee = null
) {
$this->employee = $employee;
parent::mount(
$initialYear,
$initialMonth,
$weekStartsAt,
$calendarView,
$dayView,
$eventView,
$dayOfWeekView,
$dragAndDropClasses,
$beforeCalendarView,
$afterCalendarView,
$pollMillis,
$pollAction,
$dragAndDropEnabled,
$dayClickEnabled,
$eventClickEnabled,
$extras
);
}
public function events() : Collection
{
$absences = AbsenceIndex::where('location_id', $this->employee->currentLocation->id)
->get()
->map(function (AbsenceIndex $model) {
return [
'id' => $model->id,
'title' => $model->absenceType->title,
'description' => $model->user->name,
'date' => $model->date,
];
});
$holidays = PublicHoliday::where('location_id', $this->employee->currentLocation->id)
->get()
->map(function (PublicHoliday $model) {
return [
'id' => $model->id,
'title' => __("Public Holiday"),
'description' => $model->title,
'date' => $model->day,
];
});
return collect()->merge($absences)->merge($holidays);
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Livewire/Locations/LocationMemberManager.php | app/Http/Livewire/Locations/LocationMemberManager.php | <?php
namespace App\Http\Livewire\Locations;
use Livewire\Component;
use Laravel\Jetstream\Jetstream;
use App\Models\LocationInvitation;
use Illuminate\Support\Facades\Auth;
use App\Contracts\InvitesLocationMembers;
use App\Contracts\RemovesLocationMembers;
use App\Contracts\UpdatesLocationMembersRole;
class LocationMemberManager extends Component
{
/**
* The location instance.
*
* @var mixed
*/
public $location;
/**
* Indicates if a user's role is currently being managed.
*
* @var bool
*/
public $currentlyManagingRole = false;
/**
* The user that is having their role managed.
*
* @var mixed
*/
public $managingRoleFor;
/**
* The current role for the user that is having their role managed.
*
* @var string
*/
public $currentRole;
/**
* Indicates if the application is confirming if a user wishes to leave the current location.
*
* @var bool
*/
public $confirmingLeavingLocation = false;
/**
* Indicates if the application is confirming if a location member should be removed.
*
* @var bool
*/
public $confirmingLocationMemberRemoval = false;
/**
* The ID of the location member being removed.
*
* @var int|null
*/
public $locationMemberIdBeingRemoved = null;
/**
* The "add location member" form state.
*
* @var array
*/
public $addLocationMemberForm = [
'email' => '',
'role' => null,
];
/**
* Mount the component.
*
* @param mixed $location
* @return void
*/
public function mount($location)
{
$this->location = $location;
}
/**
* Invite a new location member to a location.
*
* @param \App\Contracts\InvitesLocationMembers
* @return void
*/
public function addLocationMember(InvitesLocationMembers $inviter)
{
$this->resetErrorBag();
$inviter->invite(
$this->user,
$this->location,
$this->addLocationMemberForm['email'],
$this->addLocationMemberForm['role']
);
$this->addLocationMemberForm = [
'email' => '',
'role' => null,
];
$this->location = $this->location->fresh();
$this->emit('saved');
}
/**
* Cancel a pending team member invitation.
*
* @param int $invitationId
* @return void
*/
public function cancelLocationInvitation($invitationId)
{
if (! empty($invitationId)) {
LocationInvitation::whereKey($invitationId)->delete();
}
$this->location = $this->location->fresh();
}
/**
* Allow the given user's role to be managed.
*
* @param int $userId
* @return void
*/
public function manageRole($userId)
{
$this->currentlyManagingRole = true;
$this->managingRoleFor = Jetstream::findUserByIdOrFail($userId);
$this->currentRole = $this->managingRoleFor->locationRole($this->location)->key;
}
/**
* Save the role for the user being managed.
*
* @param \App\Contracts\UpdatesLocationMembersRole $updater
* @return void
*/
public function updateRole(UpdatesLocationMembersRole $updater)
{
$updater->update(
$this->user,
$this->location,
$this->managingRoleFor->id,
$this->currentRole
);
$this->location = $this->location->fresh();
$this->stopManagingRole();
}
/**
* Stop managing the role of a given user.
*/
public function stopManagingRole()
{
$this->currentlyManagingRole = false;
}
/**
* Remove the currently authenticated user from the location.
*
* @param \App\Contracts\RemoveLocationMember $remover
* @return void
*/
public function leaveLocation(RemovesLocationMembers $remover)
{
$remover->remove(
$this->user,
$this->location,
$this->user
);
$this->confirmingLeavingLocation = false;
$this->location = $this->location->fresh();
return redirect(config('fortify.home'));
}
/**
* Confirm that the given location member should be removed.
*
* @param int $userId
* @return void
*/
public function confirmLocationMemberRemoval($userId)
{
$this->confirmingLocationMemberRemoval = true;
$this->locationMemberIdBeingRemoved = $userId;
}
/**
* Remove a location member from the location.
*
* @param \App\Contracts\RemoveLocationMember $remover
* @return void
*/
public function removeLocationMember(RemovesLocationMembers $remover)
{
$remover->remove(
$this->user,
$this->location,
$user = Jetstream::findUserByIdOrFail($this->locationMemberIdBeingRemoved)
);
$this->confirmingLocationMemberRemoval = false;
$this->locationMemberIdBeingRemoved = null;
$this->location = $this->location->fresh();
}
/**
* Get the current user of the application.
*
* @return mixed
*/
public function getUserProperty()
{
return Auth::user();
}
/**
* Get the available location member roles.
*
* @return array
*/
public function getRolesProperty()
{
return array_values(Jetstream::$roles);
}
public function render()
{
return view('locations.location-member-manager');
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Livewire/Locations/PublicHolidaysManager.php | app/Http/Livewire/Locations/PublicHolidaysManager.php | <?php
namespace App\Http\Livewire\Locations;
use Livewire\Component;
use App\Models\Location;
use Livewire\WithPagination;
use App\Contracts\AddsPublicHoliday;
use App\Contracts\RemovesPublicHoliday;
use App\Contracts\ImportsPublicHolidays;
class PublicHolidaysManager extends Component
{
use WithPagination;
/**
* Indicates if the application is confirming if a public holiday should be removed.
*
* @var bool
*/
public $confirmingPublicHolidayRemoval = false;
/**
* The ID of the public holiday being removed.
*
* @var int|null
*/
public $publicHolidayIdBeingRemoved = null;
public $addPublicHolidayModal = false;
public $importPublicHoliday = false;
public $publicHolidayForm = [
'name' => null,
'date' => null,
'half_day' => false
];
public $importYears;
public $importCountries;
public $countryToBeImported;
public $yearToBeImported;
public $location;
public function mount(Location $location)
{
$this->location = $location;
$yearsRange = range(date('Y',strtotime('+1 year')), date('Y',strtotime('-2 year')));
$this->importYears = array_combine($yearsRange, $yearsRange);
$this->importCountries = collect(config('public_holidays.countries'))->mapWithKeys(
function ($item) {
return [
$item['code'] => $item['title']
];
}
)->all();
}
public function openPublicHolidayModal()
{
$this->addPublicHolidayModal = true;
}
public function closePublicHolidayModal()
{
$this->addPublicHolidayModal = false;
}
public function addPublicHoliday(AddsPublicHoliday $adder)
{
$adder->add($this->location, $this->publicHolidayForm);
$this->location = $this->location->fresh();
$this->emit('savedPublicHoliday');
$this->addPublicHolidayModal = false;
}
public function importPublicHoliday(ImportsPublicHolidays $importer)
{
$this->resetErrorBag();
$importer->import(
$this->location,
$this->yearToBeImported,
$this->countryToBeImported
);
$this->location = $this->location->fresh();
$this->importPublicHoliday = false;
$this->emit('savedPublicHoliday');
}
public function confirmPublicHolidayRemoval($publicHolidayId)
{
$this->confirmingPublicHolidayRemoval = true;
$this->publicHolidayIdBeingRemoved = $publicHolidayId;
}
/**
* Remove a public holiday from the location.
*
* @param \App\Actions\RemovesPublicHoliday $remover
* @return void
*/
public function removePublicHoliday(RemovesPublicHoliday $remover)
{
$remover->remove(
$this->location,
$this->publicHolidayIdBeingRemoved
);
$this->confirmingPublicHolidayRemoval = false;
$this->publicHolidayIdBeingRemoved = null;
$this->location = $this->location->fresh();
}
public function render()
{
return view('livewire.locations.public-holidays-manager', [
'holidays' => $this->location->publicHolidays()->paginate(10)
]);
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
eporsche/daybreak | https://github.com/eporsche/daybreak/blob/622d67f67470933977f13a44b19849ddb1cc0d8c/app/Http/Livewire/Locations/UpdateLocationNameForm.php | app/Http/Livewire/Locations/UpdateLocationNameForm.php | <?php
namespace App\Http\Livewire\Locations;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use App\Contracts\UpdatesLocationNames;
class UpdateLocationNameForm extends Component
{
/**
* The team instance.
*
* @var mixed
*/
public $location;
/**
* The component's state.
*
* @var array
*/
public $state = [];
/**
* Mount the component.
*
* @param mixed $location
* @return void
*/
public function mount($location)
{
$this->location = $location;
$this->state = ['name' => $location->name];
}
/**
* Update the location's name.
*
* @param \App\Contracts\UpdatesLocationNames $updater
* @return void
*/
public function updateLocationName(UpdatesLocationNames $updater)
{
$this->resetErrorBag();
$updater->update($this->user, $this->location, $this->state);
$this->emit('saved');
$this->emit('refresh-navigation-dropdown');
}
/**
* Get the current user of the application.
*
* @return mixed
*/
public function getUserProperty()
{
return Auth::user();
}
/**
* Render the component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('livewire.locations.update-location-name-form');
}
}
| php | MIT | 622d67f67470933977f13a44b19849ddb1cc0d8c | 2026-01-05T05:21:01.959950Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.