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 |
|---|---|---|---|---|---|---|---|---|
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/DependencyInjection/YamlStenopeExtensionTest.php | tests/Unit/DependencyInjection/YamlStenopeExtensionTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class YamlStenopeExtensionTest extends StenopeExtensionTest
{
protected function loadFromFile(ContainerBuilder $container, string $file): void
{
$loader = new YamlFileLoader($container, new FileLocator(self::FIXTURES_PATH . '/yaml'));
$loader->load($file . '.yaml');
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/DependencyInjection/XmlStenopeExtensionTest.php | tests/Unit/DependencyInjection/XmlStenopeExtensionTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
class XmlStenopeExtensionTest extends StenopeExtensionTest
{
protected function loadFromFile(ContainerBuilder $container, string $file): void
{
$loader = new XmlFileLoader($container, new FileLocator(self::FIXTURES_PATH . '/xml'));
$loader->load($file . '.xml');
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/DependencyInjection/StenopeExtensionTest.php | tests/Unit/DependencyInjection/StenopeExtensionTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Stenope\Bundle\Builder;
use Stenope\Bundle\DependencyInjection\StenopeExtension;
use Stenope\Bundle\Processor\AssetsProcessor;
use Stenope\Bundle\Processor\CodeHighlightProcessor;
use Stenope\Bundle\Processor\ExtractTitleFromHtmlContentProcessor;
use Stenope\Bundle\Processor\HtmlAnchorProcessor;
use Stenope\Bundle\Processor\HtmlExternalLinksProcessor;
use Stenope\Bundle\Processor\HtmlIdProcessor;
use Stenope\Bundle\Processor\LastModifiedProcessor;
use Stenope\Bundle\Processor\ResolveContentLinksProcessor;
use Stenope\Bundle\Processor\SlugProcessor;
use Stenope\Bundle\Processor\TableOfContentProcessor;
use Stenope\Bundle\Provider\Factory\LocalFilesystemProviderFactory;
use Stenope\Bundle\Routing\ContentUrlResolver;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
use Symfony\Component\DependencyInjection\Reference;
abstract class StenopeExtensionTest extends TestCase
{
public const FIXTURES_PATH = __DIR__ . '/../../fixtures/Unit/DependencyInjection/StenopeExtension';
public function testDefaults(): void
{
$container = $this->createContainerFromFile('defaults');
self::assertSame('%kernel.project_dir%/build', $container->getDefinition(Builder::class)->getArgument('$buildDir'));
self::assertEquals([
[
'src' => '%kernel.project_dir%/public',
'dest' => '.',
'excludes' => ['*.php'],
'fail_if_missing' => true,
'ignore_dot_files' => true,
],
], $container->getDefinition(Builder::class)->getArgument('$filesToCopy'));
}
public function testDirs(): void
{
$container = $this->createContainerFromFile('dirs');
self::assertSame('PROJECT_DIR/site', $container->getDefinition(Builder::class)->getArgument('$buildDir'));
}
public function testCopy(): void
{
$container = $this->createContainerFromFile('copy');
self::assertEquals([
[
'src' => 'PROJECT_DIR/public/build',
'dest' => 'dist',
'excludes' => ['*.excluded'],
'fail_if_missing' => true,
'ignore_dot_files' => false,
],
[
'src' => 'PROJECT_DIR/public/robots.txt',
'dest' => 'robots.txt',
'excludes' => [],
'fail_if_missing' => true,
'ignore_dot_files' => true,
],
[
'src' => 'PROJECT_DIR/public/missing-file',
'fail_if_missing' => false,
'excludes' => [],
'dest' => 'missing-file',
'ignore_dot_files' => true,
],
], $container->getDefinition(Builder::class)->getArgument('$filesToCopy'));
}
public function testProviders(): void
{
$container = $this->createContainerFromFile('providers');
$filesProviderFactory = $container->getDefinition('stenope.provider.files.Foo\Bar');
self::assertEquals(LocalFilesystemProviderFactory::TYPE, $filesProviderFactory->getArgument('$type'));
self::assertEquals([
'class' => 'Foo\Bar',
'path' => 'PROJECT_DIR/foo/bar',
'depth' => '< 2',
'patterns' => ['*.md', '*.html'],
'excludes' => ['excluded.md'],
], $filesProviderFactory->getArgument('$config'));
$customProviderFactory = $container->getDefinition('stenope.provider.custom.Foo\Custom');
self::assertEquals('custom', $customProviderFactory->getArgument('$type'));
self::assertEquals([
'class' => 'Foo\Custom',
'custom_config_key' => 'custom_value',
'custom_sequence' => ['custom_sequence_value_1', 'custom_sequence_value_2'],
], $customProviderFactory->getArgument('$config'));
}
public function testResolveLinks(): void
{
$container = $this->createContainerFromFile('resolve_links');
$resolver = $container->getDefinition(ContentUrlResolver::class);
self::assertCount(1, $routes = $resolver->getArgument('$routes'));
self::assertInstanceOf(Reference::class, $ref = $routes['Foo\Bar']);
self::assertSame(['foo_bar', 'foo', []], $container->getDefinition($ref)->getArguments());
}
public function testDisabledProcessors(): void
{
$container = $this->createContainerFromFile('disabled_processors');
self::assertCount(0, $container->findTaggedServiceIds('stenope.processor'), 'Default built-in processors are not registered');
}
public function testDefaultProcessors(): void
{
$container = $this->createContainerFromFile('defaults');
self::assertNotCount(0, $container->findTaggedServiceIds('stenope.processor'), 'Default built-in processors are registered');
// SlugProcessor
self::assertSame('slug', $container->getDefinition(SlugProcessor::class)->getArgument('$property'));
// AssetsProcessor
self::assertSame('content', $container->getDefinition(AssetsProcessor::class)->getArgument('$property'));
// ResolveContentLinksProcessor
self::assertSame('content', $container->getDefinition(ResolveContentLinksProcessor::class)->getArgument('$property'));
// HtmlExternalLinksProcessor
self::assertSame('content', $container->getDefinition(HtmlExternalLinksProcessor::class)->getArgument('$property'));
// HtmlAnchorProcessor
$def = $container->getDefinition(HtmlAnchorProcessor::class);
self::assertSame('h1, h2, h3, h4, h5', $def->getArgument('$selector'));
self::assertSame('content', $def->getArgument('$property'));
// ExtractTitleFromHtmlContentProcessor
$def = $container->getDefinition(ExtractTitleFromHtmlContentProcessor::class);
self::assertSame('title', $def->getArgument('$titleProperty'));
self::assertSame('content', $def->getArgument('$contentProperty'));
// HtmlIdProcessor
self::assertSame('content', $container->getDefinition(HtmlIdProcessor::class)->getArgument('$property'));
// CodeHighlightProcessor
self::assertSame('content', $container->getDefinition(CodeHighlightProcessor::class)->getArgument('$property'));
// TableOfContentProcessor
$def = $container->getDefinition(TableOfContentProcessor::class);
self::assertSame('tableOfContent', $def->getArgument('$tableOfContentProperty'));
self::assertSame(2, $def->getArgument('$minDepth'));
self::assertSame(6, $def->getArgument('$maxDepth'));
self::assertSame('content', $def->getArgument('$contentProperty'));
// LastModifiedProcessor
$def = $container->getDefinition(LastModifiedProcessor::class);
self::assertSame('lastModified', $def->getArgument('$property'));
self::assertSame('git', $def->getArgument('$gitLastModified')->getArgument('$gitPath'));
}
/**
* @dataProvider provideProcessorsConfig
*/
public function testProcessorsConfig(string $configName, callable $expectations): void
{
$container = $this->createContainerFromFile("processors/$configName");
$expectations($container);
}
public function provideProcessorsConfig(): iterable
{
yield 'slug disabled' => ['slug_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(SlugProcessor::class));
}];
yield 'slug property' => ['slug_property', function (ContainerBuilder $container): void {
self::assertSame('id', $container->getDefinition(SlugProcessor::class)->getArgument('$property'));
}];
yield 'assets disabled' => ['assets_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(AssetsProcessor::class));
}];
yield 'resolve_content_links disabled' => ['resolve_content_links_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(ResolveContentLinksProcessor::class));
}];
yield 'external_links disabled' => ['external_links_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(HtmlExternalLinksProcessor::class));
}];
yield 'anchors disabled' => ['anchors_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(HtmlAnchorProcessor::class));
}];
yield 'anchors selector' => ['anchors_selector', function (ContainerBuilder $container): void {
self::assertSame('h1, h2, h4', $container->getDefinition(HtmlAnchorProcessor::class)->getArgument('$selector'));
}];
yield 'html_title selector' => ['html_title_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(ExtractTitleFromHtmlContentProcessor::class));
}];
yield 'html_title property' => ['html_title_property', function (ContainerBuilder $container): void {
self::assertSame('documentName', $container->getDefinition(ExtractTitleFromHtmlContentProcessor::class)->getArgument('$titleProperty'));
}];
yield 'html_elements_ids disabled' => ['html_elements_ids_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(HtmlIdProcessor::class));
}];
yield 'code_highlight disabled' => ['code_highlight_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(CodeHighlightProcessor::class));
}];
yield 'toc disabled' => ['toc_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(TableOfContentProcessor::class));
}];
yield 'toc config' => ['toc_config', function (ContainerBuilder $container): void {
self::assertNotNull($def = $container->getDefinition(TableOfContentProcessor::class));
self::assertSame('toc', $def->getArgument('$tableOfContentProperty'));
self::assertSame(1, $def->getArgument('$minDepth'));
self::assertSame(3, $def->getArgument('$maxDepth'));
}];
yield 'last_modified disabled' => ['last_modified_disabled', function (ContainerBuilder $container): void {
self::assertFalse($container->hasDefinition(LastModifiedProcessor::class));
}];
yield 'last_modified config' => ['last_modified_config', function (ContainerBuilder $container): void {
self::assertNotNull($def = $container->getDefinition(LastModifiedProcessor::class));
self::assertSame('updatedAt', $def->getArgument('$property'));
self::assertSame('/usr/bin/git', $def->getArgument('$gitLastModified')->getArgument('$gitPath'));
}];
}
protected function createContainerFromFile(string $file, bool $compile = true): ContainerBuilder
{
$container = $this->createContainer();
$container->registerExtension(new StenopeExtension());
$this->loadFromFile($container, $file);
$container->getCompilerPassConfig()->setOptimizationPasses([]);
$container->getCompilerPassConfig()->setRemovingPasses([]);
$container->getCompilerPassConfig()->setAfterRemovingPasses([]);
if ($compile) {
$container->compile();
}
return $container;
}
abstract protected function loadFromFile(ContainerBuilder $container, string $file);
protected function createContainer(): ContainerBuilder
{
return new ContainerBuilder(new EnvPlaceholderParameterBag([
'kernel.project_dir' => 'PROJECT_DIR',
]));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/HttpKernel/Controller/ArgumentResolver/ContentArgumentResolverTest.php | tests/Unit/HttpKernel/Controller/ArgumentResolver/ContentArgumentResolverTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\HttpKernel\Controller\ArgumentResolver;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Prophecy\Prophecy\ObjectProphecy;
use Stenope\Bundle\Content;
use Stenope\Bundle\ContentManagerInterface;
use Stenope\Bundle\HttpKernel\Controller\ArgumentResolver\ContentArgumentResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
class ContentArgumentResolverTest extends TestCase
{
use ProphecyTrait;
private ContentArgumentResolver $resolver;
/** @var ContentManagerInterface|ObjectProphecy */
private ObjectProphecy $manager;
protected function setUp(): void
{
$this->resolver = new ContentArgumentResolver(
($this->manager = $this->prophesize(ContentManagerInterface::class))->reveal()
);
}
public function provideSupportsData(): iterable
{
yield 'non-nullable, supported content class' => [
'request' => new Request([], [], ['foo' => 'foo-1']),
'argument' => new ArgumentMetadata('foo', 'App\Foo', false, false, null, false),
'expected' => true,
];
yield 'non-nullable, non-supported content class' => [
'request' => new Request([], [], ['bar' => 'bar-1']),
'argument' => new ArgumentMetadata('bar', 'App\Bar', false, false, null, false),
'expected' => false,
];
yield 'nullable, supported content class, but no matching request attribute (or null)' => [
'request' => new Request(),
'argument' => new ArgumentMetadata('foo', 'App\Foo', false, false, null, true),
'expected' => false,
];
yield 'non-nullable, supported content class, and no matching request attribute (or null)' => [
'request' => new Request([], [], ['foo' => 'foo-1']),
'argument' => new ArgumentMetadata('foo', 'App\Foo', false, false, null, false),
'expected' => true,
];
}
/**
* @dataProvider provideSupportsData
*/
public function testResolvesSomething(Request $request, ArgumentMetadata $argument, bool $expected): void
{
if (!interface_exists(ValueResolverInterface::class)) {
$this->markTestSkipped('Symfony <6.2');
}
$this->manager->supports('App\Foo')->willReturn(true);
$this->manager->supports('App\Bar')->willReturn(false);
$this->manager->getContent(Argument::cetera())->willReturn(new Content('foo-1', 'App\Foo', 'Foo 1', 'markdown'));
if ($expected) {
self::assertNotEmpty($this->resolver->resolve($request, $argument));
} else {
self::assertEmpty($this->resolver->resolve($request, $argument));
}
}
public function testResolve(): void
{
if (!interface_exists(ValueResolverInterface::class)) {
$this->markTestSkipped('Symfony <6.2');
}
$this->manager->getContent('App\Foo', 'foo-1')->willReturn($content = new Content('foo-1', 'App\Foo', 'Foo 1', 'markdown'));
$this->manager->supports('App\Foo')->willReturn(true);
$request = new Request([], [], ['foo' => 'foo-1']);
$argument = new ArgumentMetadata('foo', 'App\Foo', false, false, null, false);
self::assertSame([$content], $this->resolver->resolve($request, $argument));
}
/**
* @dataProvider provideSupportsData
*/
public function testSupportsLegacy(Request $request, ArgumentMetadata $argument, bool $expected): void
{
if (interface_exists(ValueResolverInterface::class)) {
$this->markTestSkipped('Deprecated `ArgumentValueResolverInterface`, use `ValueResolverInterface` instead');
}
$this->manager->supports('App\Foo')->willReturn(true);
$this->manager->supports('App\Bar')->willReturn(false);
self::assertSame($expected, $this->resolver->supports($request, $argument));
}
public function testResolveLegacy(): void
{
if (interface_exists(ValueResolverInterface::class)) {
$this->markTestSkipped('Deprecated `ArgumentValueResolverInterface`, use `ValueResolverInterface` instead');
}
$this->manager->getContent('App\Foo', 'foo-1')->willReturn($content = new Content('foo-1', 'App\Foo', 'Foo 1', 'markdown'));
$request = new Request([], [], ['foo' => 'foo-1']);
$argument = new ArgumentMetadata('foo', 'App\Foo', false, false, null, false);
self::assertSame([$content], iterator_to_array($this->resolver->resolve($request, $argument)));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/TableOfContent/CrawlerTableOfContentGeneratorTest.php | tests/Unit/TableOfContent/CrawlerTableOfContentGeneratorTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\TableOfContent;
use PHPUnit\Framework\TestCase;
use Stenope\Bundle\TableOfContent\CrawlerTableOfContentGenerator;
use Stenope\Bundle\TableOfContent\Headline;
use Symfony\Component\DomCrawler\Crawler;
class CrawlerTableOfContentGeneratorTest extends TestCase
{
private CrawlerTableOfContentGenerator $generator;
protected function setUp(): void
{
$this->generator = new CrawlerTableOfContentGenerator();
}
/**
* @dataProvider provideTableOfContents
*/
public function testTableOfContent(string $htmlDom, ?int $fromDepth, ?int $toDepth, array $expectedToc): void
{
$toc = $this->generator->getTableOfContent(new Crawler($htmlDom), $fromDepth, $toDepth);
self::assertJsonStringEqualsJsonString(json_encode($expectedToc), json_encode($toc));
}
public function provideTableOfContents(): iterable
{
$content = <<<HTML
<div class="admonition note">
<h1 id="A">Lorem ipsum</h1>
<h2 id="AA">Suspendisse</h2>
<h3 id="AAA">Dolor</h3>
<h3 id="AAB">Sit amet</h3>
<h4 id="AABA">Consectetur</h4>
<h5 id="AABAA">Nulla faucibus</h5>
<h5 id="AABAB">Vestibulum</h5>
<h6 id="AABABA">Tincidunt</h6>
<h3 id="AAC">Magna non rhoncus</h3>
<h4 id="AACA">Id sapien</h4>
<h3 id="AAD">Sit amet</h3>
<h2 id="AB">Nam sed neque</h2>
<h2 id="AC">Donec laoreet</h2>
<!-- Intentionally "jumoing" one level here -->
<h4 id="ACA">Himenaeos</h4>
<h5 id="ACAA">Suscipit</h5>
<h5 id="ACAB">Pretium</h5>
</div>
HTML;
yield 'basic' => [
$content,
null,
null,
[
new Headline(1, 'A', 'Lorem ipsum', [
new Headline(2, 'AA', 'Suspendisse', [
new Headline(3, 'AAA', 'Dolor'),
new Headline(3, 'AAB', 'Sit amet', [
new Headline(4, 'AABA', 'Consectetur', [
new Headline(5, 'AABAA', 'Nulla faucibus'),
new Headline(5, 'AABAB', 'Vestibulum', [
new Headline(6, 'AABABA', 'Tincidunt'),
]),
]),
]),
new Headline(3, 'AAC', 'Magna non rhoncus', [
new Headline(4, 'AACA', 'Id sapien'),
]),
new Headline(3, 'AAD', 'Sit amet'),
]),
new Headline(2, 'AB', 'Nam sed neque'),
new Headline(2, 'AC', 'Donec laoreet', [
new Headline(4, 'ACA', 'Himenaeos', [
new Headline(5, 'ACAA', 'Suscipit'),
new Headline(5, 'ACAB', 'Pretium'),
]),
]),
]),
],
];
yield 'subset' => [
$content,
2,
3,
[
new Headline(2, 'AA', 'Suspendisse', [
new Headline(3, 'AAA', 'Dolor'),
new Headline(3, 'AAB', 'Sit amet'),
new Headline(3, 'AAC', 'Magna non rhoncus'),
new Headline(3, 'AAD', 'Sit amet'),
]),
new Headline(2, 'AB', 'Nam sed neque'),
new Headline(2, 'AC', 'Donec laoreet'),
],
];
yield 'single level' => [
$content,
2,
2,
[
new Headline(2, 'AA', 'Suspendisse'),
new Headline(2, 'AB', 'Nam sed neque'),
new Headline(2, 'AC', 'Donec laoreet'),
],
];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Provider/LocalFilesystemProviderTest.php | tests/Unit/Provider/LocalFilesystemProviderTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Provider;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;
use Stenope\Bundle\Content;
use Stenope\Bundle\Provider\LocalFilesystemProvider;
use Stenope\Bundle\ReverseContent\Context;
use Stenope\Bundle\ReverseContent\RelativeLinkContext;
use Symfony\Component\VarDumper\Cloner\Stub;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Test\VarDumperTestTrait;
class LocalFilesystemProviderTest extends TestCase
{
use ProphecyTrait;
use VarDumperTestTrait {
setUpVarDumper as setUpVarDumperParent;
}
private const FIXTURES_DIR = FIXTURES_DIR . '/Unit/Provider/LocalFilesystemProvider';
protected function setUpVarDumper(array $casters, ?int $flags = null): void
{
$this->setUpVarDumperParent(
$casters,
$flags ?? CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_TRAILING_COMMA | CliDumper::DUMP_COMMA_SEPARATOR
);
}
public function setUp(): void
{
$this->setUpVarDumper([
\DateTimeInterface::class => static function (\DateTimeInterface $d, array $a, Stub $s) {
$s->class = '📅 DATE';
$s->type = Stub::TYPE_REF;
return $a;
},
]);
}
public function testSupport(): void
{
$provider = new LocalFilesystemProvider('App\Foo', self::FIXTURES_DIR . '/content/foo');
self::assertTrue($provider->supports('App\Foo'));
self::assertFalse($provider->supports('App\Bar'));
}
public function testGetContent(): void
{
$provider = new LocalFilesystemProvider(
'App\Foo',
self::FIXTURES_DIR . '/content/foo',
);
$basePath = realpath(self::FIXTURES_DIR);
$this->assertDumpEquals(<<<DUMP
Stenope\Bundle\Content {
-slug: "foo"
-type: "App\Foo"
-rawContent: """
---\\n
title: Foo\\n
---\\n
\\n
Extend doesn’t silently capture any sinner — but the scholar is what remains.\\n
"""
-format: "markdown"
-lastModified: & 📅 DATE
-createdAt: null
-metadata: [
"path" => "$basePath/content/foo/foo.md",
"provider" => "files",
]
}
DUMP,
$provider->getContent('foo'),
);
self::assertSame('bar/bar', $provider->getContent('bar/bar')->getSlug());
}
/**
* @dataProvider provideListContentsData
*/
public function testListContents(LocalFilesystemProvider $provider, array $expected): void
{
self::assertEqualsCanonicalizing($expected, array_map(
fn (Content $c) => sprintf('%s (%s)', $c->getSlug(), $c->getFormat()),
iterator_to_array($provider->listContents())
));
}
public function testReverse(): void
{
$provider = new LocalFilesystemProvider(
'App\Foo',
$basePath = self::FIXTURES_DIR . '/content/foo',
);
self::assertInstanceOf(Content::class, $resolved = $provider->reverse(new RelativeLinkContext(
[
'path' => "$basePath/bar/baz/baz.md",
'provider' => 'files',
],
'../../foo.md',
)), 'target found');
self::assertSame('foo', $resolved->getSlug());
self::assertNull($provider->reverse(new RelativeLinkContext(
[
'path' => "$basePath/bar/baz/baz.md",
'provider' => 'files',
],
'../non-existing-file.md',
)), 'target not found');
self::assertNull($provider->reverse(new RelativeLinkContext(
[
'path' => "$basePath/bar/baz/baz.md",
'provider' => 'not-files',
],
'../non-existing-file.md',
)), 'current content not provided by a filesystem provider');
self::assertNull($provider->reverse($this->prophesize(Context::class)->reveal()), 'Not a relative link context');
}
public function provideListContentsData(): iterable
{
yield 'default config' => [
new LocalFilesystemProvider(
'App\Foo',
self::FIXTURES_DIR . '/content/foo',
),
[
'foo (markdown)',
'foo2 (markdown)',
'foo3 (html)',
'bar/bar (markdown)',
'bar/bar2 (markdown)',
'bar/baz/baz (markdown)',
],
];
yield 'config with depth' => [
new LocalFilesystemProvider(
'App\Foo',
self::FIXTURES_DIR . '/content/foo',
'< 1',
),
[
'foo (markdown)',
'foo2 (markdown)',
'foo3 (html)',
],
];
yield 'config with exclude & patterns' => [
new LocalFilesystemProvider(
'App\Foo',
self::FIXTURES_DIR . '/content/foo',
null,
['foo2.md', 'bar/*2.md'],
['*.md'],
),
[
'foo (markdown)',
'bar/bar (markdown)',
'bar/baz/baz (markdown)',
],
];
yield 'config excluding dir as glob' => [
new LocalFilesystemProvider(
'App\Foo',
self::FIXTURES_DIR . '/content/excluded_dirs',
null,
['bar/*'],
['*.md'],
),
[
'bar (markdown)',
'foo/bar (markdown)',
'foo/bar/baz (markdown)',
],
];
// This one cannot be resolved until https://github.com/symfony/symfony/issues/28158 is.
// If one really needs to exclude a dir but not subdirs with the same name, they must use the glob pattern
// as in the previous test case sample, despite it may have a big performances impact
// yield 'config excluding explicit dir (not as a glob)' => [
// new LocalFilesystemProvider(
// 'App\Foo',
// self::FIXTURES_DIR . '/content/excluded_dirs',
// null,
// ['bar/'],
// ['*.md'],
// ),
// [
// 'bar (markdown)',
// 'foo/bar (markdown)',
// 'foo/bar/baz (markdown)',
// ],
// ];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Service/AssetsUtilsTest.php | tests/Unit/Service/AssetsUtilsTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Service;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Stenope\Bundle\Service\AssetUtils;
use Symfony\Component\Asset\Packages;
class AssetsUtilsTest extends TestCase
{
use ProphecyTrait;
private AssetUtils $utils;
protected function setUp(): void
{
$packages = $this->prophesize(Packages::class);
$packages->getUrl(Argument::type('string'))->will(function (array $args): string {
[$url] = $args;
return "https://cnd.example.com/$url";
});
$this->utils = new AssetUtils($packages->reveal());
}
/**
* @dataProvider provideGetUrlData
*/
public function testGetUrl(string $url, string $expected): void
{
self::assertSame($expected, $this->utils->getUrl($url));
}
public function provideGetUrlData(): iterable
{
yield ['mailto:foo@exemple.com', 'mailto:foo@exemple.com'];
yield ['tel:+33606060606', 'tel:+33606060606'];
yield ['file:///foo.svg', 'file:///foo.svg'];
yield ['http://example.com/bar', 'http://example.com/bar'];
yield ['//example.com/bar', '//example.com/bar'];
yield ['https://example.com/bar', 'https://example.com/bar'];
yield ['foo.png', 'https://cnd.example.com/foo.png'];
yield ['#an-anchor-to-current-page', '#an-anchor-to-current-page'];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Service/HtmlCrawlerManagerTest.php | tests/Unit/Service/HtmlCrawlerManagerTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Service;
use PHPUnit\Framework\TestCase;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Content;
use Stenope\Bundle\Service\NaiveHtmlCrawlerManager;
use Stenope\Bundle\Service\SharedHtmlCrawlerManager;
class HtmlCrawlerManagerTest extends TestCase
{
/**
* @dataProvider provideNoExtraBodyData
*/
public function testSaveNoExtraBody(
HtmlCrawlerManagerInterface $manager,
string $html,
string $expected
): void {
if ($manager instanceof SharedHtmlCrawlerManager) {
$this->markTestSkipped('SharedHtmlCrawlerManager does nothing on save()');
}
$content = new Content('slug', 'type', $html, 'html');
$data = ['content' => $html];
$manager->get($content, $data, 'content');
$manager->save($content, $data, 'content');
self::assertXmlStringEqualsXmlString(<<<HTML
<html>$expected</html>
HTML,
<<<HTML
<html>{$data['content']}</html>
HTML,
);
}
/**
* @dataProvider provideNoExtraBodyData
*/
public function testSaveAllNoExtraBody(
HtmlCrawlerManagerInterface $manager,
string $html,
string $expected
): void {
$content = new Content('slug', 'type', $html, 'html');
$data = ['content' => $html];
$manager->get($content, $data, 'content');
$manager->saveAll($content, $data);
self::assertXmlStringEqualsXmlString(<<<HTML
<html>$expected</html>
HTML,
<<<HTML
<html>{$data['content']}</html>
HTML,
);
}
public function provideNoExtraBodyData(): iterable
{
$html = <<<HTML
<html>
<head>
<title>My title</title>
</head>
<body>
<h1>My title</h1>
<p>My content</p>
</body>
</html>
HTML;
$expected = <<<HTML
<h1>My title</h1>
<p>My content</p>
HTML;
yield 'with full HTML and naive manager' => [
new NaiveHtmlCrawlerManager(),
$html,
$expected,
];
yield 'with full HTML and shared manager' => [
new SharedHtmlCrawlerManager(),
$html,
$expected,
];
$html = <<<HTML
<h1>My title</h1>
<p>My content</p>
HTML;
yield 'with partial HTML and naive manager' => [
new NaiveHtmlCrawlerManager(),
$html,
$expected,
];
yield 'with partial HTML and shared manager' => [
new SharedHtmlCrawlerManager(),
$html,
$expected,
];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Service/ParsedownTest.php | tests/Unit/Service/ParsedownTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Service;
use PHPUnit\Framework\TestCase;
use Stenope\Bundle\Service\Parsedown;
class ParsedownTest extends TestCase
{
private Parsedown $parser;
protected function setUp(): void
{
$this->parser = new Parsedown();
}
/**
* @dataProvider provideAdmonitions
*/
public function testAdmonitions(string $markdown, string $expectedHtml): void
{
$html = $this->parser->parse($markdown);
self::assertHtmlEquals($expectedHtml, $html);
}
public function provideAdmonitions(): iterable
{
yield 'basic' => [
<<<MARKDOWN
!!! Note
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
MARKDOWN,
<<<HTML
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
</p>
</div>
HTML
];
yield 'basic with markdown inside' => [
<<<MARKDOWN
!!! Note
Going to the `small mind doesn’t facilitate` zen anymore
than emerging *creates* superior _blessing_.
MARKDOWN,
<<<HTML
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>
Going to the <code class="code-inline">small mind doesn’t facilitate</code> zen anymore
than emerging <em>creates</em> superior <em>blessing</em>.
</p>
</div>
HTML
];
yield 'basic with text around' => [
<<<MARKDOWN
Some text before
!!! Note
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
Some text after
MARKDOWN,
<<<HTML
<p>Some text before</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
</p>
</div>
<p>Some text after</p>
HTML
];
yield 'basic (without spacing around)' => [
<<<MARKDOWN
Some text before
!!! Note
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
Some text after
MARKDOWN,
<<<HTML
<p>Some text before</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
</p>
</div>
<p>Some text after</p>
HTML
];
yield 'with explicit title' => [
<<<MARKDOWN
!!! Note "Note title"
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
MARKDOWN,
<<<HTML
<div class="admonition note">
<p class="admonition-title">Note title</p>
<p>
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
</p>
</div>
HTML
];
yield 'with explicit title with markdown inside' => [
<<<MARKDOWN
!!! Note "Note `title`"
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
MARKDOWN,
<<<HTML
<div class="admonition note">
<p class="admonition-title">Note <code class="code-inline">title</code></p>
<p>
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
</p>
</div>
HTML
];
yield 'with no title' => [
<<<MARKDOWN
!!! Note ""
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
MARKDOWN,
<<<HTML
<div class="admonition note">
<p>
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
</p>
</div>
HTML
];
yield 'multiple classes with title' => [
<<<MARKDOWN
!!! Note foo bar "Note title"
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
MARKDOWN,
<<<HTML
<div class="admonition note foo bar">
<p class="admonition-title">Note title</p>
<p>
Going to the small mind doesn’t facilitate zen anymore
than emerging creates superior blessing.
</p>
</div>
HTML
];
}
public static function assertHtmlEquals(string $expected, string $actual, ?string $message = ''): void
{
self::assertXmlStringEqualsXmlString("<root>$expected</root>", "<root>$actual</root>", $message);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Service/Git/LastModifiedFetcherTest.php | tests/Unit/Service/Git/LastModifiedFetcherTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Service\Git;
use PHPUnit\Framework\TestCase;
use Psr\Log\Test\TestLogger;
use Stenope\Bundle\Service\Git\LastModifiedFetcher;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\PhpExecutableFinder;
class LastModifiedFetcherTest extends TestCase
{
private static string $php;
private static string $executable;
public static function setUpBeforeClass(): void
{
self::$php = (new PhpExecutableFinder())->find();
self::$executable = self::$php . ' ' . FIXTURES_DIR . '/Unit/Service/Git/bin/git.php';
}
public function testDisabled(): void
{
$fetcher = new LastModifiedFetcher(null);
$fetcher->reset();
self::assertNull($fetcher->__invoke('some-fake-path'));
}
public function testUnavailable(): void
{
$logger = new TestLogger();
$fetcher = new LastModifiedFetcher('not-valid-path', $logger);
$fetcher->reset();
self::assertNull($fetcher->__invoke('some-fake-path'));
self::assertTrue(
$logger->hasWarningThatContains('Git was not found at path')
|| $logger->hasWarningThatContains('An unexpected error occurred while trying to check the git binary at path')
);
self::assertCount(1, $logger->records);
self::assertNull($fetcher->__invoke('some-fake-path'));
self::assertCount(1, $logger->records, 'Do not attempt to check git availability twice');
}
public function testSuccess(): void
{
$fetcher = new LastModifiedFetcher(self::$executable);
$fetcher->reset();
self::assertInstanceOf(\DateTimeImmutable::class, $date = $fetcher->__invoke('some-fake-path'));
self::assertSame('2021-06-14T10:25:47+02:00', $date->format(\DateTimeImmutable::RFC3339));
}
public function testEmpty(): void
{
$fetcher = new LastModifiedFetcher(self::$executable);
$fetcher->reset();
self::assertNull($fetcher->__invoke('empty'));
}
public function testFailure(): void
{
$fetcher = new LastModifiedFetcher(self::$executable);
$fetcher->reset();
$this->expectException(ProcessFailedException::class);
$fetcher->__invoke('fail');
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/bin/lint.twig.php | bin/lint.twig.php | #!/usr/bin/env php
<?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
require __DIR__ . '/../vendor/autoload.php';
use Symfony\Bridge\Twig\Command\LintCommand;
use Symfony\Component\Console\Application;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
(new Application('twig/lint'))
->add(new LintCommand(new Environment(new FilesystemLoader())))
->getApplication()
->setDefaultCommand('lint:twig', true)
->run();
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/config/processors.php | config/processors.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Psr\Log\LoggerInterface;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\DependencyInjection\tags;
use Stenope\Bundle\Highlighter\Prism;
use Stenope\Bundle\Processor\AssetsProcessor;
use Stenope\Bundle\Processor\CodeHighlightProcessor;
use Stenope\Bundle\Processor\ExtractTitleFromHtmlContentProcessor;
use Stenope\Bundle\Processor\HtmlAnchorProcessor;
use Stenope\Bundle\Processor\HtmlExternalLinksProcessor;
use Stenope\Bundle\Processor\HtmlIdProcessor;
use Stenope\Bundle\Processor\LastModifiedProcessor;
use Stenope\Bundle\Processor\ResolveContentLinksProcessor;
use Stenope\Bundle\Processor\SlugProcessor;
use Stenope\Bundle\Processor\TableOfContentProcessor;
use Stenope\Bundle\Routing\ContentUrlResolver;
use Stenope\Bundle\Service\AssetUtils;
use Stenope\Bundle\Service\Git\LastModifiedFetcher;
use Stenope\Bundle\TableOfContent\CrawlerTableOfContentGenerator;
use Symfony\Component\String\Slugger\SluggerInterface;
require_once __DIR__ . '/tags.php';
return static function (ContainerConfigurator $container): void {
$container->services()->defaults()->tag(tags\content_processor)
->set(LastModifiedProcessor::class)->args([
'$property' => abstract_arg('lastModified property'),
'$gitLastModified' => inline_service(LastModifiedFetcher::class)->args([
'$gitPath' => abstract_arg('git path'),
'$logger' => service(LoggerInterface::class)->nullOnInvalid(),
]),
])
->set(SlugProcessor::class)->args([
'$property' => abstract_arg('slug property'),
])
->set(HtmlIdProcessor::class)
->args([
'$slugger' => service(SluggerInterface::class),
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
'$property' => abstract_arg('content property'),
])
->set(HtmlAnchorProcessor::class)->args([
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
'$property' => abstract_arg('content property'),
'$selector' => abstract_arg('HTML elements selector'),
])
->set(HtmlExternalLinksProcessor::class)->args([
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
'$property' => abstract_arg('content property'),
])
->set(ExtractTitleFromHtmlContentProcessor::class)->args([
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
'$titleProperty' => abstract_arg('title property'),
'$contentProperty' => abstract_arg('content property'),
])
->set(CodeHighlightProcessor::class)->args([
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
'$highlighter' => service(Prism::class),
'$property' => abstract_arg('content property'),
])
->set(ResolveContentLinksProcessor::class)->args([
'$resolver' => service(ContentUrlResolver::class),
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
'$property' => abstract_arg('content property'),
])
->set(AssetsProcessor::class)->args([
'$assetUtils' => service(AssetUtils::class),
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
'$property' => abstract_arg('content property'),
])
->set(TableOfContentProcessor::class)
->args([
'$generator' => service(CrawlerTableOfContentGenerator::class),
'$tableOfContentProperty' => abstract_arg('table of content property'),
'$contentProperty' => abstract_arg('content property'),
'$minDepth' => abstract_arg('min depth'),
'$maxDepth' => abstract_arg('max depth'),
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
])
->tag(tags\content_processor, ['priority' => -100])
;
};
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/config/services.php | config/services.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Psr\Log\LoggerInterface;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Builder;
use Stenope\Bundle\Builder\PageList;
use Stenope\Bundle\Builder\Sitemap;
use Stenope\Bundle\Command\BuildCommand;
use Stenope\Bundle\Command\DebugCommand;
use Stenope\Bundle\ContentManager;
use Stenope\Bundle\ContentManagerInterface;
use Stenope\Bundle\Decoder\HtmlDecoder;
use Stenope\Bundle\Decoder\MarkdownDecoder;
use Stenope\Bundle\DependencyInjection\tags;
use Stenope\Bundle\EventListener\Informator;
use Stenope\Bundle\EventListener\SitemapListener;
use Stenope\Bundle\ExpressionLanguage\ExpressionLanguage;
use Stenope\Bundle\Highlighter\Prism;
use Stenope\Bundle\Highlighter\Pygments;
use Stenope\Bundle\HttpKernel\Controller\ArgumentResolver\ContentArgumentResolver;
use Stenope\Bundle\Provider\Factory\ContentProviderFactory;
use Stenope\Bundle\Provider\Factory\LocalFilesystemProviderFactory;
use Stenope\Bundle\Routing\ContentUrlResolver;
use Stenope\Bundle\Routing\RouteInfoCollection;
use Stenope\Bundle\Routing\UrlGenerator;
use Stenope\Bundle\Serializer\Normalizer\SkippingInstantiatedObjectDenormalizer;
use Stenope\Bundle\Service\AssetUtils;
use Stenope\Bundle\Service\NaiveHtmlCrawlerManager;
use Stenope\Bundle\Service\Parsedown;
use Stenope\Bundle\Service\SharedHtmlCrawlerManager;
use Stenope\Bundle\TableOfContent\CrawlerTableOfContentGenerator;
use Stenope\Bundle\Twig\ContentExtension;
use Stenope\Bundle\Twig\ContentRuntime;
use Symfony\Component\Asset\Packages;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Mime\MimeTypesInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Stopwatch\Stopwatch;
require_once __DIR__ . '/tags.php';
return static function (ContainerConfigurator $container): void {
$container->services()
// Content manager
->set(ContentManager::class)->args([
'$decoder' => service('serializer'),
'$denormalizer' => service('serializer'),
'$crawlers' => service(HtmlCrawlerManagerInterface::class),
'$contentProviders' => tagged_iterator(tags\content_provider),
'$processors' => tagged_iterator(tags\content_processor),
'$propertyAccessor' => service('property_accessor'),
'$expressionLanguage' => service(ExpressionLanguage::class)->nullOnInvalid(),
'$stopwatch' => service('debug.stopwatch')->nullOnInvalid(),
])->call('setContentManager', [service(ContentManagerInterface::class)])
->alias(ContentManagerInterface::class, ContentManager::class)
// Content providers factories
->set(ContentProviderFactory::class)->args(['$factories' => tagged_iterator(tags\content_provider_factory)])
->set(LocalFilesystemProviderFactory::class)->tag(tags\content_provider_factory)
// Debug
->set(DebugCommand::class)->args([
'$manager' => service(ContentManagerInterface::class),
'$stopwatch' => service('stenope.build.stopwatch'),
'$registeredTypes' => 'The known content types, defined by the extension',
])
->tag('console.command', ['command' => 'debug:stenope:content'])
// Expression Language
->set(ExpressionLanguage::class)->args([
'$providers' => tagged_iterator(tags\expression_language_provider),
])
// Build
->set(BuildCommand::class)->args([
'$builder' => service(Builder::class),
'$stopwatch' => service('stenope.build.stopwatch'),
])
->tag('console.command', ['command' => 'stenope:build'])
->set(Builder::class)->args([
'$router' => service('router'),
'$routesInfo' => service(RouteInfoCollection::class),
'$httpKernel' => service('kernel'),
'$templating' => service('twig'),
'$mimeTypes' => service(MimeTypesInterface::class),
'$pageList' => service(PageList::class),
'$sitemap' => service(Sitemap::class),
'$buildDir' => 'The build dir, defined by the extension',
'$filesToCopy' => 'The files to copy after build, defined by the extension',
'$logger' => service(LoggerInterface::class)->nullOnInvalid(),
'$stopwatch' => service('stenope.build.stopwatch'),
])
->set('stenope.build.stopwatch', Stopwatch::class)->args([true])
// Sitemap
->set(PageList::class)
->set(Sitemap::class)
->set(SitemapListener::class)
->args([
'$routesInfo' => service(RouteInfoCollection::class),
'$sitemap' => service(Sitemap::class),
])
->tag('kernel.event_subscriber')
->set(Informator::class)
->args([
'$urlGenerator' => service(UrlGeneratorInterface::class),
'$twig' => service('twig'),
])
->tag('kernel.event_subscriber')
// Markdown and code highlighting
->set(Parsedown::class)
->set(Pygments::class)
->set(Prism::class)->args([
'$executable' => null,
'$stopwatch' => service('debug.stopwatch')->nullOnInvalid(),
'$logger' => service(LoggerInterface::class)->nullOnInvalid(),
])->tag('kernel.event_listener', ['event' => KernelEvents::TERMINATE, 'method' => 'stop'])
// Serializer
->set(SkippingInstantiatedObjectDenormalizer::class)->tag('serializer.normalizer')
// Decoders
->set(MarkdownDecoder::class)
->args(['$parser' => service(Parsedown::class)])
->tag('serializer.encoder')
->set(HtmlDecoder::class)->tag('serializer.encoder')
// Url generator decorator
->set(UrlGenerator::class)
->decorate(UrlGeneratorInterface::class)
->args([
'$routesInfo' => service(RouteInfoCollection::class),
'$urlGenerator' => service(UrlGenerator::class . '.inner'),
'$pageList' => service(PageList::class),
])
->set(RouteInfoCollection::class)->args([
'$router' => service('router'),
])
->set(ContentUrlResolver::class)->args([
'$router' => service('router'),
'$routes' => 'The routes to resolve types, defined by the extension',
])
// Symfony HttpKernel controller argument resolver
->set(ContentArgumentResolver::class)
->args(['$contentManager' => service(ContentManagerInterface::class)])
->tag('controller.argument_value_resolver', [
'priority' => 110, // Prior to RequestAttributeValueResolver to resolve from route attribute
])
// Twig
->set(ContentExtension::class)->tag('twig.extension')
->set(ContentRuntime::class)
->args(['$contentManager' => service(ContentManagerInterface::class)])
->tag('twig.runtime')
// Assets
->set(AssetUtils::class)
->args(['$assets' => service(Packages::class)])
// Table of content
->set(CrawlerTableOfContentGenerator::class)
// HTML Crawler Manager
->set(NaiveHtmlCrawlerManager::class)
->set(SharedHtmlCrawlerManager::class)
->alias(HtmlCrawlerManagerInterface::class, NaiveHtmlCrawlerManager::class);
};
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/config/tags.php | config/tags.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\DependencyInjection\tags;
const content_processor = 'stenope.processor';
const content_provider = 'stenope.content_provider';
const content_provider_factory = 'stenope.content_provider_factory';
const expression_language_provider = 'stenope.expression_language_provider';
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/doc/app/src/Kernel.php | doc/app/src/Kernel.php | <?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/doc/app/src/Processor/DefaultTocProcessor.php | doc/app/src/Processor/DefaultTocProcessor.php | <?php
namespace App\Processor;
use App\Model\Page;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
class DefaultTocProcessor implements ProcessorInterface
{
public function __construct(
private string $tableOfContentProperty = 'tableOfContent'
) {
}
/**
* @param array<string,int> &$data
*/
public function __invoke(array &$data, Content $content): void
{
if (!is_a($content->getType(), Page::class, true)) {
return;
}
if (!isset($data[$this->tableOfContentProperty])) {
// By default, always generate a TOC for pages, with max depth of 3:
$data[$this->tableOfContentProperty] = 3;
}
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/doc/app/src/Model/Page.php | doc/app/src/Model/Page.php | <?php
namespace App\Model;
use Stenope\Bundle\TableOfContent\TableOfContent;
class Page
{
public string $title;
public string $slug;
public string $content;
public ?TableOfContent $tableOfContent = null;
public \DateTimeInterface $created;
public \DateTimeInterface $lastModified;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/doc/app/src/Model/Index.php | doc/app/src/Model/Index.php | <?php
namespace App\Model;
class Index extends Page
{
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/doc/app/src/Controller/DocController.php | doc/app/src/Controller/DocController.php | <?php
namespace App\Controller;
use App\Model\Index;
use App\Model\Page;
use Stenope\Bundle\ContentManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
class DocController extends AbstractController
{
public function __construct(
private ContentManagerInterface $contentManager
) {
}
#[Route('/', name: 'index')]
public function index()
{
$page = $this->contentManager->getContent(Index::class, 'README');
return $this->render('doc/index.html.twig', ['page' => $page]);
}
#[Route('/{page<.+>}', name: 'page')]
public function page(Page $page)
{
return $this->render('doc/page.html.twig', ['page' => $page]);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/doc/app/public/index.php | doc/app/public/index.php | <?php
use App\Kernel;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/doc/app/config/preload.php | doc/app/config/preload.php | <?php
if (file_exists(dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php')) {
require dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php';
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/doc/app/config/bundles.php | doc/app/config/bundles.php | <?php
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Twig\Extra\TwigExtraBundle\TwigExtraBundle::class => ['all' => true],
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\WebpackEncoreBundle\WebpackEncoreBundle::class => ['all' => true],
Stenope\Bundle\StenopeBundle::class => ['all' => true],
];
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
yandex-php/translate-api | https://github.com/yandex-php/translate-api/blob/3a53fc1dab9bf5cb6e7f11b39604d6288f683765/src/Translator.php | src/Translator.php | <?php
namespace Yandex\Translate;
/**
* Translate
* @author Nikita Gusakov <dev@nkt.me>
* @link http://api.yandex.com/translate/doc/dg/reference/translate.xml
*/
class Translator
{
const BASE_URL = 'https://translate.yandex.net/api/v1.5/tr.json/';
const MESSAGE_UNKNOWN_ERROR = 'Unknown error';
const MESSAGE_JSON_ERROR = 'JSON parse error';
const MESSAGE_INVALID_RESPONSE = 'Invalid response from service';
/**
* @var string
*/
protected $key;
/**
* @var resource
*/
protected $handler;
/**
* @link http://api.yandex.com/key/keyslist.xml Get a free API key on this page.
*
* @param string $key The API key
*/
public function __construct($key)
{
$this->key = $key;
$this->handler = curl_init();
curl_setopt($this->handler, CURLOPT_RETURNTRANSFER, true);
}
/**
* Returns a list of translation directions supported by the service.
* @link http://api.yandex.com/translate/doc/dg/reference/getLangs.xml
*
* @param string $culture If set, the service's response will contain a list of language codes
*
* @return array
*/
public function getSupportedLanguages($culture = null)
{
return $this->execute('getLangs', array(
'ui' => $culture
));
}
/**
* Detects the language of the specified text.
* @link http://api.yandex.com/translate/doc/dg/reference/detect.xml
*
* @param string $text The text to detect the language for.
*
* @return string
*/
public function detect($text)
{
$data = $this->execute('detect', array(
'text' => $text
));
return $data['lang'];
}
/**
* Translates the text.
* @link http://api.yandex.com/translate/doc/dg/reference/translate.xml
*
* @param string|array $text The text to be translated.
* @param string $language Translation direction (for example, "en-ru" or "ru").
* @param bool $html Text format, if true - html, otherwise plain.
* @param int $options Translation options.
*
* @return array
*/
public function translate($text, $language, $html = false, $options = 0)
{
$data = $this->execute('translate', array(
'text' => $text,
'lang' => $language,
'format' => $html ? 'html' : 'plain',
'options' => $options
));
// @TODO: handle source language detecting
return new Translation($text, $data['text'], $data['lang']);
}
/**
* @param string $uri
* @param array $parameters
*
* @throws Exception
* @return array
*/
protected function execute($uri, array $parameters)
{
$parameters['key'] = $this->key;
curl_setopt($this->handler, CURLOPT_URL, static::BASE_URL . $uri);
curl_setopt($this->handler, CURLOPT_POST, true);
curl_setopt($this->handler, CURLOPT_POSTFIELDS, http_build_query($parameters));
$remoteResult = curl_exec($this->handler);
if ($remoteResult === false) {
throw new Exception(curl_error($this->handler), curl_errno($this->handler));
}
$result = json_decode($remoteResult, true);
if (!$result) {
$errorMessage = self::MESSAGE_UNKNOWN_ERROR;
if (version_compare(PHP_VERSION, '5.3', '>=')) {
if (json_last_error() !== JSON_ERROR_NONE) {
if (version_compare(PHP_VERSION, '5.5', '>=')) {
$errorMessage = json_last_error_msg();
} else {
$errorMessage = self::MESSAGE_JSON_ERROR;
}
}
}
throw new Exception(sprintf('%s: %s', self::MESSAGE_INVALID_RESPONSE, $errorMessage));
} elseif (isset($result['code']) && $result['code'] > 200) {
throw new Exception($result['message'], $result['code']);
}
return $result;
}
}
| php | MIT | 3a53fc1dab9bf5cb6e7f11b39604d6288f683765 | 2026-01-05T05:19:14.342338Z | false |
yandex-php/translate-api | https://github.com/yandex-php/translate-api/blob/3a53fc1dab9bf5cb6e7f11b39604d6288f683765/src/Translation.php | src/Translation.php | <?php
namespace Yandex\Translate;
/**
* Translation
* @author Nikita Gusakov <dev@nkt.me>
*/
class Translation
{
/**
* @var string|array
*/
protected $source;
/**
* @var string|array
*/
protected $result;
/**
* @var array
*/
protected $language;
/**
* @param string|array $source The source text
* @param string|array $result The translation result
* @param string $language Translation language
*/
public function __construct($source, $result, $language)
{
$this->source = $source;
$this->result = $result;
$this->language = explode('-', $language);
}
/**
* @return string|array The source text
*/
public function getSource()
{
return $this->source;
}
/**
* @return array|string The result text
*/
public function getResult()
{
return $this->result;
}
/**
* @return string The source language.
*/
public function getSourceLanguage()
{
return $this->language[0];
}
/**
* @return string The translation language.
*/
public function getResultLanguage()
{
return $this->language[1];
}
/**
* @return string The translation text.
*/
public function __toString()
{
if (is_array($this->result)) {
return join(' ', $this->result);
}
return (string) $this->result;
}
}
| php | MIT | 3a53fc1dab9bf5cb6e7f11b39604d6288f683765 | 2026-01-05T05:19:14.342338Z | false |
yandex-php/translate-api | https://github.com/yandex-php/translate-api/blob/3a53fc1dab9bf5cb6e7f11b39604d6288f683765/src/Exception.php | src/Exception.php | <?php
namespace Yandex\Translate;
/**
* Exception
* @author Nikita Gusakov <dev@nkt.me>
*/
class Exception extends \Exception
{
}
| php | MIT | 3a53fc1dab9bf5cb6e7f11b39604d6288f683765 | 2026-01-05T05:19:14.342338Z | false |
jakeasmith/commit | https://github.com/jakeasmith/commit/blob/dab3e5de1d2938da2ab2fb37ccf463a7c470fc4d/src/EmojiList.php | src/EmojiList.php | <?php
namespace Smacme\Commit;
class EmojiList
{
/** @var array The available emoji */
private $options = [
'🎨' => 'Improving the format/structure of the code',
'🐎' => 'Improving performance',
'📚' => 'Writing docs',
'🐛' => 'Reporting a bug',
'🚑' => 'Fixing a bug',
'🐧' => 'Fixing something on Linux',
'🍎' => 'Fixing something on Mac OS',
'🏁' => 'Fixing something on Windows',
'📼' => 'Deprecating code',
'🔥' => 'Removing code or files',
'✅' => 'Adding tests',
'💚' => 'Fixing the CI build',
'🔒' => 'Dealing with security',
'⬆️' => 'Upgrading dependencies',
'⬇️' => 'Downgrading dependencies',
'👕' => 'Removing linter/strict/deprecation warnings',
'💄' => 'Improving UI/Cosmetic',
'🚧' => 'WIP(Work In Progress) Commits',
'💎' => 'New Release',
'🔖' => 'Version Tags',
'🎉' => 'Initial Commit',
'🔈' => 'Adding Logging',
'🔇' => 'Reducing Logging',
'✨' => 'Introducing New Features',
'⚡️' => 'Introducing Backward-InCompatible Features',
'💡' => 'New Idea',
'❄️' => 'Changing Configuration',
'🎀' => 'Customer requested application Customization',
'🚀' => 'Anything related to Deployments/DevOps',
'🐬' => 'MySQL Database scripts/schema',
];
public function get()
{
return $this->options;
}
}
| php | MIT | dab3e5de1d2938da2ab2fb37ccf463a7c470fc4d | 2026-01-05T05:19:19.625863Z | false |
jakeasmith/commit | https://github.com/jakeasmith/commit/blob/dab3e5de1d2938da2ab2fb37ccf463a7c470fc4d/src/EmojiUsage.php | src/EmojiUsage.php | <?php
namespace Smacme\Commit;
class EmojiUsage
{
/** @var string The directory used to store emoji usage data */
private $workingDir;
/** @var string Filename to store usage data */
private $usageFilename = '.emoji_usage';
public function __construct($workingDir)
{
$this->workingDir = realpath($workingDir);
}
public function sortByUsage($emojii)
{
uksort($emojii, function ($a, $b) use ($emojii) {
$aCount = $this->getCount($a);
$bCount = $this->getCount($b);
if ($aCount == $bCount) {
return $emojii[$a] > $emojii[$b];
}
return $aCount > $bCount ? -1 : 1;
});
return $emojii;
}
public function useEmojii($emojii)
{
$usage = $this->get();
foreach ($emojii as $emoji) {
if (!array_key_exists($emoji, $usage)) {
$usage[$emoji] = 0;
}
$usage[$emoji]++;
}
$this->save($usage);
}
private function getCount($emoji)
{
$usage = $this->get();
return array_key_exists($emoji, $usage)
? $usage[$emoji]
: 0;
}
private function get()
{
$filename = $this->getFilename();
if (!file_exists($filename)) {
file_put_contents($filename, json_encode([]));
}
return json_decode(file_get_contents($filename), true);
}
private function save($usage)
{
file_put_contents($this->getFilename(), json_encode($usage, JSON_PRETTY_PRINT));
}
private function getFilename()
{
return $this->workingDir . DIRECTORY_SEPARATOR . $this->usageFilename;
}
} | php | MIT | dab3e5de1d2938da2ab2fb37ccf463a7c470fc4d | 2026-01-05T05:19:19.625863Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/preload.php | preload.php | <?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\Boot;
use Config\Paths;
/*
*---------------------------------------------------------------
* Sample file for Preloading
*---------------------------------------------------------------
* See https://www.php.net/manual/en/opcache.preloading.php
*
* How to Use:
* 0. Copy this file to your project root folder.
* 1. Set the $paths property of the preload class below.
* 2. Set opcache.preload in php.ini.
* php.ini:
* opcache.preload=/path/to/preload.php
*/
// Load the paths config file
require __DIR__ . '/app/Config/Paths.php';
// Path to the front controller
define('FCPATH', __DIR__ . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR);
class preload
{
/**
* @var array Paths to preload.
*/
private array $paths = [
[
'include' => __DIR__ . '/vendor/codeigniter4/framework/system', // Change this path if using manual installation
'exclude' => [
// Not needed if you don't use them.
'/system/Database/OCI8/',
'/system/Database/Postgre/',
'/system/Database/SQLite3/',
'/system/Database/SQLSRV/',
// Not needed for web apps.
'/system/Database/Seeder.php',
'/system/Test/',
'/system/CLI/',
'/system/Commands/',
'/system/Publisher/',
'/system/ComposerScripts.php',
// Not Class/Function files.
'/system/Config/Routes.php',
'/system/Language/',
'/system/bootstrap.php',
'/system/util_bootstrap.php',
'/system/rewrite.php',
'/Views/',
// Errors occur.
'/system/ThirdParty/',
],
],
];
public function __construct()
{
$this->loadAutoloader();
}
private function loadAutoloader(): void
{
$paths = new Paths();
require rtrim($paths->systemDirectory, '\\/ ') . DIRECTORY_SEPARATOR . 'Boot.php';
Boot::preload($paths);
}
/**
* Load PHP files.
*/
public function load(): void
{
foreach ($this->paths as $path) {
$directory = new RecursiveDirectoryIterator($path['include']);
$fullTree = new RecursiveIteratorIterator($directory);
$phpFiles = new RegexIterator(
$fullTree,
'/.+((?<!Test)+\.php$)/i',
RecursiveRegexIterator::GET_MATCH,
);
foreach ($phpFiles as $key => $file) {
foreach ($path['exclude'] as $exclude) {
if (str_contains($file[0], $exclude)) {
continue 2;
}
}
require_once $file[0];
echo 'Loaded: ' . $file[0] . "\n";
}
}
}
}
(new preload())->load();
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/freeallusers.php | freeallusers.php | <?php
// Program to reset the Memory variable that
// controls access to Jobe tasks, essentially
// freeing all users. For CLI use only and
// then only in emergencies!
$NUM_USERS = 8; // Adjust as required.
$ACTIVE_USERS = 1; // ID for active-users variable.
try {
$key = ftok('/var/www/html/jobe/public/index.php', 'j');
$sem = sem_get($key);
$gotIt = sem_acquire($sem);
$semisfalse = $sem === false;
echo("semisfalse = $semisfalse, key = $key, gotIt = $gotIt\n");
$shm = shm_attach($key, 10000, 0600);
$active = shm_get_var($shm, $ACTIVE_USERS);
print_r($active);
for ($i=0; $i < $NUM_USERS; $i++) {
$active[$i] = 0;
}
shm_put_var($shm, $ACTIVE_USERS, $active);
} catch (Exception $e) {
echo("Exception: $e\n");
}
shm_detach($shm);
sem_release($sem);
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/checkshmstatus.php | checkshmstatus.php | <?php
// Scripts to report status of the Shared Memory variable that
// controls access to Jobe tasks.
// For CLI use only.
// You may need to change the value of $key if your Jobe installation
// is in a different directory.
try {
$key = ftok('/var/www/html/jobe/public/index.php', 'j');
$sem = sem_get($key);
$gotIt = sem_acquire($sem);
$semisfalse = $sem === false;
echo("semisfalse = $semisfalse, key = $key, gotIt = $gotIt\n");
$shm = shm_attach($key, 10000, 0600);
$active = shm_get_var($shm, 1);
print_r($active);
} catch (Exception $e) {
echo("Exception: $e\n");
}
shm_detach($shm);
sem_release($sem);
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/index.php | index.php | <?php
use CodeIgniter\Boot;
use Config\Paths;
/*
*---------------------------------------------------------------
* CHECK PHP VERSION
*---------------------------------------------------------------
*/
$minPhpVersion = '8.1'; // If you update this, don't forget to update `spark`.
if (version_compare(PHP_VERSION, $minPhpVersion, '<')) {
$message = sprintf(
'Your PHP version must be %s or higher to run CodeIgniter. Current version: %s',
$minPhpVersion,
PHP_VERSION,
);
header('HTTP/1.1 503 Service Unavailable.', true, 503);
echo $message;
exit(1);
}
/*
*---------------------------------------------------------------
* SET THE CURRENT DIRECTORY
*---------------------------------------------------------------
*/
// Path to the front controller (this file)
define('FCPATH', __DIR__ . DIRECTORY_SEPARATOR);
// Ensure the current directory is pointing to the front controller's directory
if (getcwd() . DIRECTORY_SEPARATOR !== FCPATH) {
chdir(FCPATH);
}
/*
*---------------------------------------------------------------
* BOOTSTRAP THE APPLICATION
*---------------------------------------------------------------
* This process sets up the path constants, loads and registers
* our autoloader, along with Composer's, loads our constants
* and fires up an environment-specific bootstrapping.
*/
// LOAD OUR PATHS CONFIG FILE
// This is the line that might need to be changed, depending on your folder structure.
require FCPATH . '../app/Config/Paths.php';
// ^^^ Change this line if you move your application folder
$paths = new Paths();
// LOAD THE FRAMEWORK BOOTSTRAP FILE
require $paths->systemDirectory . '/Boot.php';
exit(Boot::bootWeb($paths));
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/rewrite.php | system/rewrite.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
/*
* CodeIgniter PHP-Development Server Rewrite Rules
*
* This script works with the CLI serve command to help run a seamless
* development server based around PHP's built-in development
* server. This file simply tries to mimic Apache's mod_rewrite
* functionality so the site will operate as normal.
*/
// @codeCoverageIgnoreStart
$uri = urldecode(
parse_url('https://codeigniter.com' . $_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? '',
);
// All request handle by index.php file.
$_SERVER['SCRIPT_NAME'] = '/index.php';
// Full path
$path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . ltrim($uri, '/');
// If $path is an existing file or folder within the public folder
// then let the request handle it like normal.
if ($uri !== '/' && (is_file($path) || is_dir($path))) {
return false;
}
unset($uri, $path);
// Otherwise, we'll load the index file and let
// the framework handle the request from here.
require_once $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'index.php';
// @codeCoverageIgnoreEnd
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/util_bootstrap.php | system/util_bootstrap.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\Boot;
use Config\Paths;
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
/*
* ---------------------------------------------------------------
* DEFINE ENVIRONMENT
* ---------------------------------------------------------------
*
* As this bootstrap file is primarily used by internal scripts
* across the framework and other CodeIgniter projects, we need
* to make sure it recognizes that we're in development.
*/
$_SERVER['CI_ENVIRONMENT'] = 'development';
define('ENVIRONMENT', 'development');
defined('CI_DEBUG') || define('CI_DEBUG', true);
/*
* ---------------------------------------------------------------
* SET UP OUR PATH CONSTANTS
* ---------------------------------------------------------------
*
* The path constants provide convenient access to the folders
* throughout the application. We have to set them up here
* so they are available in the config files that are loaded.
*/
defined('HOMEPATH') || define('HOMEPATH', realpath(rtrim(getcwd(), '\\/ ')) . DIRECTORY_SEPARATOR);
$source = match (true) {
is_dir(HOMEPATH . 'app/') => HOMEPATH,
is_dir('vendor/codeigniter4/framework/') => 'vendor/codeigniter4/framework/',
is_dir('vendor/codeigniter4/codeigniter4/') => 'vendor/codeigniter4/codeigniter4/',
default => throw new RuntimeException('Unable to determine the source directory.'),
};
defined('CONFIGPATH') || define('CONFIGPATH', realpath($source . 'app/Config') . DIRECTORY_SEPARATOR);
defined('PUBLICPATH') || define('PUBLICPATH', realpath($source . 'public') . DIRECTORY_SEPARATOR);
unset($source);
require CONFIGPATH . 'Paths.php';
$paths = new Paths();
defined('CIPATH') || define('CIPATH', realpath($paths->systemDirectory . '/../') . DIRECTORY_SEPARATOR);
defined('FCPATH') || define('FCPATH', PUBLICPATH);
if (is_dir($paths->testsDirectory . '/_support/') && ! defined('SUPPORTPATH')) {
define('SUPPORTPATH', realpath($paths->testsDirectory . '/_support/') . DIRECTORY_SEPARATOR);
}
if (is_dir(HOMEPATH . 'vendor/')) {
define('VENDORPATH', realpath(HOMEPATH . 'vendor/') . DIRECTORY_SEPARATOR);
define('COMPOSER_PATH', (string) realpath(HOMEPATH . 'vendor/autoload.php'));
}
/*
*---------------------------------------------------------------
* BOOTSTRAP THE APPLICATION
*---------------------------------------------------------------
*
* This process sets up the path constants, loads and registers
* our autoloader, along with Composer's, loads our constants
* and fires up an environment-specific bootstrapping.
*/
require $paths->systemDirectory . '/Boot.php';
Boot::bootConsole($paths);
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/ComposerScripts.php | system/ComposerScripts.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
/**
* This class is used by Composer during installs and updates
* to move files to locations within the system folder so that end-users
* do not need to use Composer to install a package, but can simply
* download.
*
* @codeCoverageIgnore
*
* @internal
*/
final class ComposerScripts
{
/**
* Path to the ThirdParty directory.
*/
private static string $path = __DIR__ . '/ThirdParty/';
/**
* Direct dependencies of CodeIgniter to copy
* contents to `system/ThirdParty/`.
*
* @var array<string, array<string, string>>
*/
private static array $dependencies = [
'kint-src' => [
'license' => __DIR__ . '/../vendor/kint-php/kint/LICENSE',
'from' => __DIR__ . '/../vendor/kint-php/kint/src/',
'to' => __DIR__ . '/ThirdParty/Kint/',
],
'kint-resources' => [
'from' => __DIR__ . '/../vendor/kint-php/kint/resources/',
'to' => __DIR__ . '/ThirdParty/Kint/resources/',
],
'escaper' => [
'license' => __DIR__ . '/../vendor/laminas/laminas-escaper/LICENSE.md',
'from' => __DIR__ . '/../vendor/laminas/laminas-escaper/src/',
'to' => __DIR__ . '/ThirdParty/Escaper/',
],
'psr-log' => [
'license' => __DIR__ . '/../vendor/psr/log/LICENSE',
'from' => __DIR__ . '/../vendor/psr/log/src/',
'to' => __DIR__ . '/ThirdParty/PSR/Log/',
],
];
/**
* This static method is called by Composer after every update event,
* i.e., `composer install`, `composer update`, `composer remove`.
*/
public static function postUpdate(): void
{
self::recursiveDelete(self::$path);
foreach (self::$dependencies as $key => $dependency) {
// Kint may be removed.
if (! is_dir($dependency['from']) && str_starts_with($key, 'kint')) {
continue;
}
self::recursiveMirror($dependency['from'], $dependency['to']);
if (isset($dependency['license'])) {
$license = basename($dependency['license']);
copy($dependency['license'], $dependency['to'] . '/' . $license);
}
}
self::copyKintInitFiles();
}
/**
* Recursively remove the contents of the previous `system/ThirdParty`.
*/
private static function recursiveDelete(string $directory): void
{
if (! is_dir($directory)) {
echo sprintf('Cannot recursively delete "%s" as it does not exist.', $directory) . PHP_EOL;
return;
}
/** @var SplFileInfo $file */
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(rtrim($directory, '\\/'), FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST,
) as $file) {
$path = $file->getPathname();
if ($file->isDir()) {
@rmdir($path);
} else {
@unlink($path);
}
}
}
/**
* Recursively copy the files and directories of the origin directory
* into the target directory, i.e. "mirror" its contents.
*/
private static function recursiveMirror(string $originDir, string $targetDir): void
{
$originDir = rtrim($originDir, '\\/');
$targetDir = rtrim($targetDir, '\\/');
if (! is_dir($originDir)) {
echo sprintf('The origin directory "%s" was not found.', $originDir);
exit(1);
}
if (is_dir($targetDir)) {
echo sprintf('The target directory "%s" is existing. Run %s::recursiveDelete(\'%s\') first.', $targetDir, self::class, $targetDir);
exit(1);
}
if (! @mkdir($targetDir, 0755, true)) {
echo sprintf('Cannot create the target directory: "%s"', $targetDir) . PHP_EOL;
exit(1);
}
$dirLen = strlen($originDir);
/** @var SplFileInfo $file */
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($originDir, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
) as $file) {
$origin = $file->getPathname();
$target = $targetDir . substr($origin, $dirLen);
if ($file->isDir()) {
@mkdir($target, 0755);
} else {
@copy($origin, $target);
}
}
}
/**
* Copy Kint's init files into `system/ThirdParty/Kint/`
*/
private static function copyKintInitFiles(): void
{
$originDir = self::$dependencies['kint-src']['from'] . '../';
$targetDir = self::$dependencies['kint-src']['to'];
foreach (['init.php', 'init_helpers.php'] as $kintInit) {
@copy($originDir . $kintInit, $targetDir . $kintInit);
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Common.php | system/Common.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Config\Factories;
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
use CodeIgniter\Cookie\Exceptions\CookieException;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\RuntimeException;
use CodeIgniter\Files\Exceptions\FileNotFoundException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\Exceptions\RedirectException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Language\Language;
use CodeIgniter\Model;
use CodeIgniter\Session\Session;
use CodeIgniter\Test\TestLogger;
use Config\App;
use Config\Database;
use Config\DocTypes;
use Config\Logger;
use Config\Services;
use Config\View;
use Laminas\Escaper\Escaper;
// Services Convenience Functions
if (! function_exists('app_timezone')) {
/**
* Returns the timezone the application has been set to display
* dates in. This might be different than the timezone set
* at the server level, as you often want to stores dates in UTC
* and convert them on the fly for the user.
*/
function app_timezone(): string
{
$config = config(App::class);
return $config->appTimezone;
}
}
if (! function_exists('cache')) {
/**
* A convenience method that provides access to the Cache
* object. If no parameter is provided, will return the object,
* otherwise, will attempt to return the cached value.
*
* Examples:
* cache()->save('foo', 'bar');
* $foo = cache('bar');
*
* @return ($key is null ? CacheInterface : mixed)
*/
function cache(?string $key = null)
{
$cache = service('cache');
// No params - return cache object
if ($key === null) {
return $cache;
}
// Still here? Retrieve the value.
return $cache->get($key);
}
}
if (! function_exists('clean_path')) {
/**
* A convenience method to clean paths for
* a nicer looking output. Useful for exception
* handling, error logging, etc.
*/
function clean_path(string $path): string
{
// Resolve relative paths
try {
$path = realpath($path) ?: $path;
} catch (ErrorException|ValueError) {
$path = 'error file path: ' . urlencode($path);
}
return match (true) {
str_starts_with($path, APPPATH) => 'APPPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(APPPATH)),
str_starts_with($path, SYSTEMPATH) => 'SYSTEMPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(SYSTEMPATH)),
str_starts_with($path, FCPATH) => 'FCPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(FCPATH)),
defined('VENDORPATH') && str_starts_with($path, VENDORPATH) => 'VENDORPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(VENDORPATH)),
str_starts_with($path, ROOTPATH) => 'ROOTPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(ROOTPATH)),
default => $path,
};
}
}
if (! function_exists('command')) {
/**
* Runs a single command.
* Input expected in a single string as would
* be used on the command line itself:
*
* > command('migrate:create SomeMigration');
*
* @return false|string
*/
function command(string $command)
{
$regexString = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
$regexQuoted = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
$args = [];
$length = strlen($command);
$cursor = 0;
/**
* Adopted from Symfony's `StringInput::tokenize()` with few changes.
*
* @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Input/StringInput.php
*/
while ($cursor < $length) {
if (preg_match('/\s+/A', $command, $match, 0, $cursor)) {
// nothing to do
} elseif (preg_match('/' . $regexQuoted . '/A', $command, $match, 0, $cursor)) {
$args[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
} elseif (preg_match('/' . $regexString . '/A', $command, $match, 0, $cursor)) {
$args[] = stripcslashes($match[1]);
} else {
// @codeCoverageIgnoreStart
throw new InvalidArgumentException(sprintf(
'Unable to parse input near "... %s ...".',
substr($command, $cursor, 10),
));
// @codeCoverageIgnoreEnd
}
$cursor += strlen($match[0]);
}
/** @var array<int|string, string|null> */
$params = [];
$command = array_shift($args);
$optionValue = false;
foreach ($args as $i => $arg) {
if (mb_strpos($arg, '-') !== 0) {
if ($optionValue) {
// if this was an option value, it was already
// included in the previous iteration
$optionValue = false;
} else {
// add to segments if not starting with '-'
// and not an option value
$params[] = $arg;
}
continue;
}
$arg = ltrim($arg, '-');
$value = null;
if (isset($args[$i + 1]) && mb_strpos($args[$i + 1], '-') !== 0) {
$value = $args[$i + 1];
$optionValue = true;
}
$params[$arg] = $value;
}
ob_start();
service('commands')->run($command, $params);
return ob_get_clean();
}
}
if (! function_exists('config')) {
/**
* More simple way of getting config instances from Factories
*
* @template ConfigTemplate of BaseConfig
*
* @param class-string<ConfigTemplate>|string $name
*
* @return ($name is class-string<ConfigTemplate> ? ConfigTemplate : object|null)
*/
function config(string $name, bool $getShared = true)
{
if ($getShared) {
return Factories::get('config', $name);
}
return Factories::config($name, ['getShared' => $getShared]);
}
}
if (! function_exists('cookie')) {
/**
* Simpler way to create a new Cookie instance.
*
* @param string $name Name of the cookie
* @param string $value Value of the cookie
* @param array $options Array of options to be passed to the cookie
*
* @throws CookieException
*/
function cookie(string $name, string $value = '', array $options = []): Cookie
{
return new Cookie($name, $value, $options);
}
}
if (! function_exists('cookies')) {
/**
* Fetches the global `CookieStore` instance held by `Response`.
*
* @param list<Cookie> $cookies If `getGlobal` is false, this is passed to CookieStore's constructor
* @param bool $getGlobal If false, creates a new instance of CookieStore
*/
function cookies(array $cookies = [], bool $getGlobal = true): CookieStore
{
if ($getGlobal) {
return service('response')->getCookieStore();
}
return new CookieStore($cookies);
}
}
if (! function_exists('csrf_token')) {
/**
* Returns the CSRF token name.
* Can be used in Views when building hidden inputs manually,
* or used in javascript vars when using APIs.
*/
function csrf_token(): string
{
return service('security')->getTokenName();
}
}
if (! function_exists('csrf_header')) {
/**
* Returns the CSRF header name.
* Can be used in Views by adding it to the meta tag
* or used in javascript to define a header name when using APIs.
*/
function csrf_header(): string
{
return service('security')->getHeaderName();
}
}
if (! function_exists('csrf_hash')) {
/**
* Returns the current hash value for the CSRF protection.
* Can be used in Views when building hidden inputs manually,
* or used in javascript vars for API usage.
*/
function csrf_hash(): string
{
return service('security')->getHash();
}
}
if (! function_exists('csrf_field')) {
/**
* Generates a hidden input field for use within manually generated forms.
*
* @param non-empty-string|null $id
*/
function csrf_field(?string $id = null): string
{
return '<input type="hidden"' . ($id !== null ? ' id="' . esc($id, 'attr') . '"' : '') . ' name="' . csrf_token() . '" value="' . csrf_hash() . '"' . _solidus() . '>';
}
}
if (! function_exists('csrf_meta')) {
/**
* Generates a meta tag for use within javascript calls.
*
* @param non-empty-string|null $id
*/
function csrf_meta(?string $id = null): string
{
return '<meta' . ($id !== null ? ' id="' . esc($id, 'attr') . '"' : '') . ' name="' . csrf_header() . '" content="' . csrf_hash() . '"' . _solidus() . '>';
}
}
if (! function_exists('csp_style_nonce')) {
/**
* Generates a nonce attribute for style tag.
*/
function csp_style_nonce(): string
{
$csp = service('csp');
if (! $csp->enabled()) {
return '';
}
return 'nonce="' . $csp->getStyleNonce() . '"';
}
}
if (! function_exists('csp_script_nonce')) {
/**
* Generates a nonce attribute for script tag.
*/
function csp_script_nonce(): string
{
$csp = service('csp');
if (! $csp->enabled()) {
return '';
}
return 'nonce="' . $csp->getScriptNonce() . '"';
}
}
if (! function_exists('db_connect')) {
/**
* Grabs a database connection and returns it to the user.
*
* This is a convenience wrapper for \Config\Database::connect()
* and supports the same parameters. Namely:
*
* When passing in $db, you may pass any of the following to connect:
* - group name
* - existing connection instance
* - array of database configuration values
*
* If $getShared === false then a new connection instance will be provided,
* otherwise it will all calls will return the same instance.
*
* @param array|ConnectionInterface|string|null $db
*
* @return BaseConnection
*/
function db_connect($db = null, bool $getShared = true)
{
return Database::connect($db, $getShared);
}
}
if (! function_exists('env')) {
/**
* Allows user to retrieve values from the environment
* variables that have been set. Especially useful for
* retrieving values set from the .env file for
* use in config files.
*
* @param array<int|string, mixed>|bool|float|int|object|string|null $default
*
* @return array<int|string, mixed>|bool|float|int|object|string|null
*/
function env(string $key, $default = null)
{
$value = $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key);
// Not found? Return the default value
if ($value === false) {
return $default;
}
// Handle any boolean values
return match (strtolower($value)) {
'true' => true,
'false' => false,
'empty' => '',
'null' => null,
default => $value,
};
}
}
if (! function_exists('esc')) {
/**
* Performs simple auto-escaping of data for security reasons.
* Might consider making this more complex at a later date.
*
* If $data is a string, then it simply escapes and returns it.
* If $data is an array, then it loops over it, escaping each
* 'value' of the key/value pairs.
*
* @param array|string $data
* @param 'attr'|'css'|'html'|'js'|'raw'|'url' $context
* @param string|null $encoding Current encoding for escaping.
* If not UTF-8, we convert strings from this encoding
* pre-escaping and back to this encoding post-escaping.
*
* @return array|string
*
* @throws InvalidArgumentException
*/
function esc($data, string $context = 'html', ?string $encoding = null)
{
$context = strtolower($context);
// Provide a way to NOT escape data since
// this could be called automatically by
// the View library.
if ($context === 'raw') {
return $data;
}
if (is_array($data)) {
foreach ($data as &$value) {
$value = esc($value, $context);
}
}
if (is_string($data)) {
if (! in_array($context, ['html', 'js', 'css', 'url', 'attr'], true)) {
throw new InvalidArgumentException('Invalid escape context provided.');
}
$method = $context === 'attr' ? 'escapeHtmlAttr' : 'escape' . ucfirst($context);
static $escaper;
if (! $escaper) {
$escaper = new Escaper($encoding);
}
if ($encoding !== null && $escaper->getEncoding() !== $encoding) {
$escaper = new Escaper($encoding);
}
$data = $escaper->{$method}($data);
}
return $data;
}
}
if (! function_exists('force_https')) {
/**
* Used to force a page to be accessed in via HTTPS.
* Uses a standard redirect, plus will set the HSTS header
* for modern browsers that support, which gives best
* protection against man-in-the-middle attacks.
*
* @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
*
* @param int $duration How long should the SSL header be set for? (in seconds)
* Defaults to 1 year.
*
* @throws HTTPException
* @throws RedirectException
*/
function force_https(
int $duration = 31_536_000,
?RequestInterface $request = null,
?ResponseInterface $response = null,
): void {
$request ??= service('request');
if (! $request instanceof IncomingRequest) {
return;
}
$response ??= service('response');
if ((ENVIRONMENT !== 'testing' && (is_cli() || $request->isSecure()))
|| $request->getServer('HTTPS') === 'test'
) {
return; // @codeCoverageIgnore
}
// If the session status is active, we should regenerate
// the session ID for safety sake.
if (ENVIRONMENT !== 'testing' && session_status() === PHP_SESSION_ACTIVE) {
service('session')->regenerate(); // @codeCoverageIgnore
}
$uri = $request->getUri()->withScheme('https');
// Set an HSTS header
$response->setHeader('Strict-Transport-Security', 'max-age=' . $duration)
->redirect((string) $uri)
->setStatusCode(307)
->setBody('')
->getCookieStore()
->clear();
throw new RedirectException($response);
}
}
if (! function_exists('function_usable')) {
/**
* Function usable
*
* Executes a function_exists() check, and if the Suhosin PHP
* extension is loaded - checks whether the function that is
* checked might be disabled in there as well.
*
* This is useful as function_exists() will return FALSE for
* functions disabled via the *disable_functions* php.ini
* setting, but not for *suhosin.executor.func.blacklist* and
* *suhosin.executor.disable_eval*. These settings will just
* terminate script execution if a disabled function is executed.
*
* The above described behavior turned out to be a bug in Suhosin,
* but even though a fix was committed for 0.9.34 on 2012-02-12,
* that version is yet to be released. This function will therefore
* be just temporary, but would probably be kept for a few years.
*
* @see http://www.hardened-php.net/suhosin/
*
* @param string $functionName Function to check for
*
* @return bool TRUE if the function exists and is safe to call,
* FALSE otherwise.
*
* @codeCoverageIgnore This is too exotic
*/
function function_usable(string $functionName): bool
{
static $_suhosin_func_blacklist;
if (function_exists($functionName)) {
if (! isset($_suhosin_func_blacklist)) {
$_suhosin_func_blacklist = extension_loaded('suhosin') ? explode(',', trim(ini_get('suhosin.executor.func.blacklist'))) : [];
}
return ! in_array($functionName, $_suhosin_func_blacklist, true);
}
return false;
}
}
if (! function_exists('helper')) {
/**
* Loads a helper file into memory. Supports namespaced helpers,
* both in and out of the 'Helpers' directory of a namespaced directory.
*
* Will load ALL helpers of the matching name, in the following order:
* 1. app/Helpers
* 2. {namespace}/Helpers
* 3. system/Helpers
*
* @param array|string $filenames
*
* @throws FileNotFoundException
*/
function helper($filenames): void
{
static $loaded = [];
$loader = service('locator');
if (! is_array($filenames)) {
$filenames = [$filenames];
}
// Store a list of all files to include...
$includes = [];
foreach ($filenames as $filename) {
// Store our system and application helper
// versions so that we can control the load ordering.
$systemHelper = '';
$appHelper = '';
$localIncludes = [];
if (! str_contains($filename, '_helper')) {
$filename .= '_helper';
}
// Check if this helper has already been loaded
if (in_array($filename, $loaded, true)) {
continue;
}
// If the file is namespaced, we'll just grab that
// file and not search for any others
if (str_contains($filename, '\\')) {
$path = $loader->locateFile($filename, 'Helpers');
if ($path === false) {
throw FileNotFoundException::forFileNotFound($filename);
}
$includes[] = $path;
$loaded[] = $filename;
} else {
// No namespaces, so search in all available locations
$paths = $loader->search('Helpers/' . $filename);
foreach ($paths as $path) {
if (str_starts_with($path, APPPATH . 'Helpers' . DIRECTORY_SEPARATOR)) {
$appHelper = $path;
} elseif (str_starts_with($path, SYSTEMPATH . 'Helpers' . DIRECTORY_SEPARATOR)) {
$systemHelper = $path;
} else {
$localIncludes[] = $path;
$loaded[] = $filename;
}
}
// App-level helpers should override all others
if ($appHelper !== '') {
$includes[] = $appHelper;
$loaded[] = $filename;
}
// All namespaced files get added in next
$includes = [...$includes, ...$localIncludes];
// And the system default one should be added in last.
if ($systemHelper !== '') {
$includes[] = $systemHelper;
$loaded[] = $filename;
}
}
}
// Now actually include all of the files
foreach ($includes as $path) {
include_once $path;
}
}
}
if (! function_exists('is_cli')) {
/**
* Check if PHP was invoked from the command line.
*
* @codeCoverageIgnore Cannot be tested fully as PHPUnit always run in php-cli
*/
function is_cli(): bool
{
if (in_array(PHP_SAPI, ['cli', 'phpdbg'], true)) {
return true;
}
// PHP_SAPI could be 'cgi-fcgi', 'fpm-fcgi'.
// See https://github.com/codeigniter4/CodeIgniter4/pull/5393
return ! isset($_SERVER['REMOTE_ADDR']) && ! isset($_SERVER['REQUEST_METHOD']);
}
}
if (! function_exists('is_really_writable')) {
/**
* Tests for file writability
*
* is_writable() returns TRUE on Windows servers when you really can't write to
* the file, based on the read-only attribute. is_writable() is also unreliable
* on Unix servers if safe_mode is on.
*
* @see https://bugs.php.net/bug.php?id=54709
*
* @throws Exception
*
* @codeCoverageIgnore Not practical to test, as travis runs on linux
*/
function is_really_writable(string $file): bool
{
// If we're on a Unix server we call is_writable
if (! is_windows()) {
return is_writable($file);
}
/* For Windows servers and safe_mode "on" installations we'll actually
* write a file then read it. Bah...
*/
if (is_dir($file)) {
$file = rtrim($file, '/') . '/' . bin2hex(random_bytes(16));
if (($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
@chmod($file, 0777);
@unlink($file);
return true;
}
if (! is_file($file) || ($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
return true;
}
}
if (! function_exists('is_windows')) {
/**
* Detect if platform is running in Windows.
*/
function is_windows(?bool $mock = null): bool
{
static $mocked;
if (func_num_args() === 1) {
$mocked = $mock;
}
return $mocked ?? DIRECTORY_SEPARATOR === '\\';
}
}
if (! function_exists('lang')) {
/**
* A convenience method to translate a string or array of them and format
* the result with the intl extension's MessageFormatter.
*
* @return list<string>|string
*/
function lang(string $line, array $args = [], ?string $locale = null)
{
/** @var Language $language */
$language = service('language');
// Get active locale
$activeLocale = $language->getLocale();
if ((string) $locale !== '' && $locale !== $activeLocale) {
$language->setLocale($locale);
}
$lines = $language->getLine($line, $args);
if ((string) $locale !== '' && $locale !== $activeLocale) {
// Reset to active locale
$language->setLocale($activeLocale);
}
return $lines;
}
}
if (! function_exists('log_message')) {
/**
* A convenience/compatibility method for logging events through
* the Log system.
*
* Allowed log levels are:
* - emergency
* - alert
* - critical
* - error
* - warning
* - notice
* - info
* - debug
*/
function log_message(string $level, string $message, array $context = []): void
{
// When running tests, we want to always ensure that the
// TestLogger is running, which provides utilities for
// for asserting that logs were called in the test code.
if (ENVIRONMENT === 'testing') {
$logger = new TestLogger(new Logger());
$logger->log($level, $message, $context);
return;
}
service('logger')->log($level, $message, $context); // @codeCoverageIgnore
}
}
if (! function_exists('model')) {
/**
* More simple way of getting model instances from Factories
*
* @template ModelTemplate of Model
*
* @param class-string<ModelTemplate>|string $name
*
* @return ($name is class-string<ModelTemplate> ? ModelTemplate : object|null)
*/
function model(string $name, bool $getShared = true, ?ConnectionInterface &$conn = null)
{
return Factories::models($name, ['getShared' => $getShared], $conn);
}
}
if (! function_exists('old')) {
/**
* Provides access to "old input" that was set in the session
* during a redirect()->withInput().
*
* @param string|null $default
* @param 'attr'|'css'|'html'|'js'|'raw'|'url'|false $escape
*
* @return array|string|null
*/
function old(string $key, $default = null, $escape = 'html')
{
// Ensure the session is loaded
if (session_status() === PHP_SESSION_NONE && ENVIRONMENT !== 'testing') {
session(); // @codeCoverageIgnore
}
$request = service('request');
$value = $request->getOldInput($key);
// Return the default value if nothing
// found in the old input.
if ($value === null) {
return $default;
}
return $escape === false ? $value : esc($value, $escape);
}
}
if (! function_exists('redirect')) {
/**
* Convenience method that works with the current global $request and
* $router instances to redirect using named/reverse-routed routes
* to determine the URL to go to.
*
* If more control is needed, you must use $response->redirect explicitly.
*
* @param non-empty-string|null $route Route name or Controller::method
*/
function redirect(?string $route = null): RedirectResponse
{
$response = service('redirectresponse');
if ((string) $route !== '') {
return $response->route($route);
}
return $response;
}
}
if (! function_exists('_solidus')) {
/**
* Generates the solidus character (`/`) depending on the HTML5 compatibility flag in `Config\DocTypes`
*
* @param DocTypes|null $docTypesConfig New config. For testing purpose only.
*
* @internal
*/
function _solidus(?DocTypes $docTypesConfig = null): string
{
static $docTypes = null;
if ($docTypesConfig instanceof DocTypes) {
$docTypes = $docTypesConfig;
}
$docTypes ??= new DocTypes();
if ($docTypes->html5 ?? false) {
return '';
}
return ' /';
}
}
if (! function_exists('remove_invisible_characters')) {
/**
* Remove Invisible Characters
*
* This prevents sandwiching null characters
* between ascii characters, like Java\0script.
*/
function remove_invisible_characters(string $str, bool $urlEncoded = true): string
{
$nonDisplayables = [];
// every control character except newline (dec 10),
// carriage return (dec 13) and horizontal tab (dec 09)
if ($urlEncoded) {
$nonDisplayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$nonDisplayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
}
$nonDisplayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
do {
$str = preg_replace($nonDisplayables, '', $str, -1, $count);
} while ($count);
return $str;
}
}
if (! function_exists('request')) {
/**
* Returns the shared Request.
*
* @return CLIRequest|IncomingRequest
*/
function request()
{
return service('request');
}
}
if (! function_exists('response')) {
/**
* Returns the shared Response.
*/
function response(): ResponseInterface
{
return service('response');
}
}
if (! function_exists('route_to')) {
/**
* Given a route name or controller/method string and any params,
* will attempt to build the relative URL to the
* matching route.
*
* NOTE: This requires the controller/method to
* have a route defined in the routes Config file.
*
* @param string $method Route name or Controller::method
* @param int|string ...$params One or more parameters to be passed to the route.
* The last parameter allows you to set the locale.
*
* @return false|string The route (URI path relative to baseURL) or false if not found.
*/
function route_to(string $method, ...$params)
{
return service('routes')->reverseRoute($method, ...$params);
}
}
if (! function_exists('session')) {
/**
* A convenience method for accessing the session instance,
* or an item that has been set in the session.
*
* Examples:
* session()->set('foo', 'bar');
* $foo = session('bar');
*
* @return ($val is null ? Session : mixed)
*/
function session(?string $val = null)
{
$session = service('session');
// Returning a single item?
if (is_string($val)) {
return $session->get($val);
}
return $session;
}
}
if (! function_exists('service')) {
/**
* Allows cleaner access to the Services Config file.
* Always returns a SHARED instance of the class, so
* calling the function multiple times should always
* return the same instance.
*
* These are equal:
* - $timer = service('timer')
* - $timer = \CodeIgniter\Config\Services::timer();
*
* @param array|bool|float|int|object|string|null ...$params
*/
function service(string $name, ...$params): ?object
{
if ($params === []) {
return Services::get($name);
}
return Services::$name(...$params);
}
}
if (! function_exists('single_service')) {
/**
* Always returns a new instance of the class.
*
* @param array|bool|float|int|object|string|null ...$params
*/
function single_service(string $name, ...$params): ?object
{
$service = Services::serviceExists($name);
if ($service === null) {
// The service is not defined anywhere so just return.
return null;
}
$method = new ReflectionMethod($service, $name);
$count = $method->getNumberOfParameters();
$mParam = $method->getParameters();
if ($count === 1) {
// This service needs only one argument, which is the shared
// instance flag, so let's wrap up and pass false here.
return $service::$name(false);
}
// Fill in the params with the defaults, but stop before the last
for ($startIndex = count($params); $startIndex <= $count - 2; $startIndex++) {
$params[$startIndex] = $mParam[$startIndex]->getDefaultValue();
}
// Ensure the last argument will not create a shared instance
$params[$count - 1] = false;
return $service::$name(...$params);
}
}
if (! function_exists('slash_item')) {
// Unlike CI3, this function is placed here because
// it's not a config, or part of a config.
/**
* Fetch a config file item with slash appended (if not empty)
*
* @param string $item Config item name
*
* @return string|null The configuration item or NULL if
* the item doesn't exist
*/
function slash_item(string $item): ?string
{
$config = config(App::class);
if (! property_exists($config, $item)) {
return null;
}
$configItem = $config->{$item};
if (! is_scalar($configItem)) {
throw new RuntimeException(sprintf(
'Cannot convert "%s::$%s" of type "%s" to type "string".',
App::class,
$item,
gettype($configItem),
));
}
$configItem = trim((string) $configItem);
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Controller.php | system/Controller.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\Exceptions\RedirectException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Exceptions\ValidationException;
use CodeIgniter\Validation\ValidationInterface;
use Config\Validation;
use Psr\Log\LoggerInterface;
/**
* Class Controller
*
* @see \CodeIgniter\ControllerTest
*/
class Controller
{
/**
* Helpers that will be automatically loaded on class instantiation.
*
* @var list<string>
*/
protected $helpers = [];
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* Instance of the main response object.
*
* @var ResponseInterface
*/
protected $response;
/**
* Instance of logger to use.
*
* @var LoggerInterface
*/
protected $logger;
/**
* Should enforce HTTPS access for all methods in this controller.
*
* @var int Number of seconds to set HSTS header
*/
protected $forceHTTPS = 0;
/**
* Once validation has been run, will hold the Validation instance.
*
* @var ValidationInterface|null
*/
protected $validator;
/**
* Constructor.
*
* @return void
*
* @throws HTTPException|RedirectException
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->request = $request;
$this->response = $response;
$this->logger = $logger;
if ($this->forceHTTPS > 0) {
$this->forceHTTPS($this->forceHTTPS);
}
// Autoload helper files.
helper($this->helpers);
}
/**
* A convenience method to use when you need to ensure that a single
* method is reached only via HTTPS. If it isn't, then a redirect
* will happen back to this method and HSTS header will be sent
* to have modern browsers transform requests automatically.
*
* @param int $duration The number of seconds this link should be
* considered secure for. Only with HSTS header.
* Default value is 1 year.
*
* @return void
*
* @throws HTTPException|RedirectException
*/
protected function forceHTTPS(int $duration = 31_536_000)
{
force_https($duration, $this->request, $this->response);
}
/**
* How long to cache the current page for.
*
* @params int $time time to live in seconds.
*
* @return void
*/
protected function cachePage(int $time)
{
service('responsecache')->setTtl($time);
}
/**
* A shortcut to performing validation on Request data.
*
* @param array|string $rules
* @param array $messages An array of custom error messages
*/
protected function validate($rules, array $messages = []): bool
{
$this->setValidator($rules, $messages);
return $this->validator->withRequest($this->request)->run();
}
/**
* A shortcut to performing validation on any input data.
*
* @param array $data The data to validate
* @param array|string $rules
* @param array $messages An array of custom error messages
* @param string|null $dbGroup The database group to use
*/
protected function validateData(array $data, $rules, array $messages = [], ?string $dbGroup = null): bool
{
$this->setValidator($rules, $messages);
return $this->validator->run($data, null, $dbGroup);
}
/**
* @param array|string $rules
*/
private function setValidator($rules, array $messages): void
{
$this->validator = service('validation');
// If you replace the $rules array with the name of the group
if (is_string($rules)) {
$validation = config(Validation::class);
// If the rule wasn't found in the \Config\Validation, we
// should throw an exception so the developer can find it.
if (! isset($validation->{$rules})) {
throw ValidationException::forRuleNotFound($rules);
}
// If no error message is defined, use the error message in the Config\Validation file
if ($messages === []) {
$errorName = $rules . '_errors';
$messages = $validation->{$errorName} ?? [];
}
$rules = $validation->{$rules};
}
$this->validator->setRules($rules, $messages);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Superglobals.php | system/Superglobals.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
/**
* Superglobals manipulation.
*
* @internal
* @see \CodeIgniter\SuperglobalsTest
*/
final class Superglobals
{
private array $server;
private array $get;
public function __construct(?array $server = null, ?array $get = null)
{
$this->server = $server ?? $_SERVER;
$this->get = $get ?? $_GET;
}
public function server(string $key): ?string
{
return $this->server[$key] ?? null;
}
public function setServer(string $key, string $value): void
{
$this->server[$key] = $value;
$_SERVER[$key] = $value;
}
/**
* @return array|string|null
*/
public function get(string $key)
{
return $this->get[$key] ?? null;
}
public function setGet(string $key, string $value): void
{
$this->get[$key] = $value;
$_GET[$key] = $value;
}
public function setGetArray(array $array): void
{
$this->get = $array;
$_GET = $array;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/CodeIgniter.php | system/CodeIgniter.php | <?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use Closure;
use CodeIgniter\Cache\ResponseCache;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\Exceptions\LogicException;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Filters\Filters;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\Exceptions\RedirectException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Method;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\ResponsableInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\URI;
use CodeIgniter\Router\RouteCollectionInterface;
use CodeIgniter\Router\Router;
use Config\App;
use Config\Cache;
use Config\Feature;
use Config\Kint as KintConfig;
use Config\Services;
use Exception;
use Kint;
use Kint\Renderer\CliRenderer;
use Kint\Renderer\RichRenderer;
use Locale;
use Throwable;
/**
* This class is the core of the framework, and will analyse the
* request, route it to a controller, and send back the response.
* Of course, there are variations to that flow, but this is the brains.
*
* @see \CodeIgniter\CodeIgniterTest
*/
class CodeIgniter
{
/**
* The current version of CodeIgniter Framework
*/
public const CI_VERSION = '4.6.3';
/**
* App startup time.
*
* @var float|null
*/
protected $startTime;
/**
* Total app execution time
*
* @var float
*/
protected $totalTime;
/**
* Main application configuration
*
* @var App
*/
protected $config;
/**
* Timer instance.
*
* @var Timer
*/
protected $benchmark;
/**
* Current request.
*
* @var CLIRequest|IncomingRequest|null
*/
protected $request;
/**
* Current response.
*
* @var ResponseInterface
*/
protected $response;
/**
* Router to use.
*
* @var Router
*/
protected $router;
/**
* Controller to use.
*
* @var (Closure(mixed...): ResponseInterface|string)|string|null
*/
protected $controller;
/**
* Controller method to invoke.
*
* @var string
*/
protected $method;
/**
* Output handler to use.
*
* @var string
*/
protected $output;
/**
* Cache expiration time
*
* @var int seconds
*
* @deprecated 4.4.0 Moved to ResponseCache::$ttl. No longer used.
*/
protected static $cacheTTL = 0;
/**
* Context
* web: Invoked by HTTP request
* php-cli: Invoked by CLI via `php public/index.php`
*
* @var 'php-cli'|'web'|null
*/
protected ?string $context = null;
/**
* Whether to enable Control Filters.
*/
protected bool $enableFilters = true;
/**
* Whether to return Response object or send response.
*
* @deprecated 4.4.0 No longer used.
*/
protected bool $returnResponse = false;
/**
* Application output buffering level
*/
protected int $bufferLevel;
/**
* Web Page Caching
*/
protected ResponseCache $pageCache;
/**
* Constructor.
*/
public function __construct(App $config)
{
$this->startTime = microtime(true);
$this->config = $config;
$this->pageCache = Services::responsecache();
}
/**
* Handles some basic app and environment setup.
*
* @return void
*/
public function initialize()
{
// Set default locale on the server
Locale::setDefault($this->config->defaultLocale ?? 'en');
// Set default timezone on the server
date_default_timezone_set($this->config->appTimezone ?? 'UTC');
}
/**
* Checks system for missing required PHP extensions.
*
* @return void
*
* @throws FrameworkException
*
* @codeCoverageIgnore
*
* @deprecated 4.5.0 Moved to system/bootstrap.php.
*/
protected function resolvePlatformExtensions()
{
$requiredExtensions = [
'intl',
'json',
'mbstring',
];
$missingExtensions = [];
foreach ($requiredExtensions as $extension) {
if (! extension_loaded($extension)) {
$missingExtensions[] = $extension;
}
}
if ($missingExtensions !== []) {
throw FrameworkException::forMissingExtension(implode(', ', $missingExtensions));
}
}
/**
* Initializes Kint
*
* @return void
*
* @deprecated 4.5.0 Moved to Autoloader.
*/
protected function initializeKint()
{
if (CI_DEBUG) {
$this->autoloadKint();
$this->configureKint();
} elseif (class_exists(Kint::class)) {
// In case that Kint is already loaded via Composer.
Kint::$enabled_mode = false;
// @codeCoverageIgnore
}
helper('kint');
}
/**
* @deprecated 4.5.0 Moved to Autoloader.
*/
private function autoloadKint(): void
{
// If we have KINT_DIR it means it's already loaded via composer
if (! defined('KINT_DIR')) {
spl_autoload_register(function ($class): void {
$class = explode('\\', $class);
if (array_shift($class) !== 'Kint') {
return;
}
$file = SYSTEMPATH . 'ThirdParty/Kint/' . implode('/', $class) . '.php';
if (is_file($file)) {
require_once $file;
}
});
require_once SYSTEMPATH . 'ThirdParty/Kint/init.php';
}
}
/**
* @deprecated 4.5.0 Moved to Autoloader.
*/
private function configureKint(): void
{
$config = new KintConfig();
Kint::$depth_limit = $config->maxDepth;
Kint::$display_called_from = $config->displayCalledFrom;
Kint::$expanded = $config->expanded;
if (isset($config->plugins) && is_array($config->plugins)) {
Kint::$plugins = $config->plugins;
}
$csp = Services::csp();
if ($csp->enabled()) {
RichRenderer::$js_nonce = $csp->getScriptNonce();
RichRenderer::$css_nonce = $csp->getStyleNonce();
}
RichRenderer::$theme = $config->richTheme;
RichRenderer::$folder = $config->richFolder;
if (isset($config->richObjectPlugins) && is_array($config->richObjectPlugins)) {
RichRenderer::$value_plugins = $config->richObjectPlugins;
}
if (isset($config->richTabPlugins) && is_array($config->richTabPlugins)) {
RichRenderer::$tab_plugins = $config->richTabPlugins;
}
CliRenderer::$cli_colors = $config->cliColors;
CliRenderer::$force_utf8 = $config->cliForceUTF8;
CliRenderer::$detect_width = $config->cliDetectWidth;
CliRenderer::$min_terminal_width = $config->cliMinWidth;
}
/**
* Launch the application!
*
* This is "the loop" if you will. The main entry point into the script
* that gets the required class instances, fires off the filters,
* tries to route the response, loads the controller and generally
* makes all the pieces work together.
*
* @param bool $returnResponse Used for testing purposes only.
*
* @return ResponseInterface|null
*/
public function run(?RouteCollectionInterface $routes = null, bool $returnResponse = false)
{
if ($this->context === null) {
throw new LogicException(
'Context must be set before run() is called. If you are upgrading from 4.1.x, '
. 'you need to merge `public/index.php` and `spark` file from `vendor/codeigniter4/framework`.',
);
}
$this->pageCache->setTtl(0);
$this->bufferLevel = ob_get_level();
$this->startBenchmark();
$this->getRequestObject();
$this->getResponseObject();
Events::trigger('pre_system');
$this->benchmark->stop('bootstrap');
$this->benchmark->start('required_before_filters');
// Start up the filters
$filters = Services::filters();
// Run required before filters
$possibleResponse = $this->runRequiredBeforeFilters($filters);
// If a ResponseInterface instance is returned then send it back to the client and stop
if ($possibleResponse instanceof ResponseInterface) {
$this->response = $possibleResponse;
} else {
try {
$this->response = $this->handleRequest($routes, config(Cache::class), $returnResponse);
} catch (ResponsableInterface $e) {
$this->outputBufferingEnd();
$this->response = $e->getResponse();
} catch (PageNotFoundException $e) {
$this->response = $this->display404errors($e);
} catch (Throwable $e) {
$this->outputBufferingEnd();
throw $e;
}
}
$this->runRequiredAfterFilters($filters);
// Is there a post-system event?
Events::trigger('post_system');
if ($returnResponse) {
return $this->response;
}
$this->sendResponse();
return null;
}
/**
* Run required before filters.
*/
private function runRequiredBeforeFilters(Filters $filters): ?ResponseInterface
{
$possibleResponse = $filters->runRequired('before');
$this->benchmark->stop('required_before_filters');
// If a ResponseInterface instance is returned then send it back to the client and stop
if ($possibleResponse instanceof ResponseInterface) {
return $possibleResponse;
}
return null;
}
/**
* Run required after filters.
*/
private function runRequiredAfterFilters(Filters $filters): void
{
$filters->setResponse($this->response);
// Run required after filters
$this->benchmark->start('required_after_filters');
$response = $filters->runRequired('after');
$this->benchmark->stop('required_after_filters');
if ($response instanceof ResponseInterface) {
$this->response = $response;
}
}
/**
* Invoked via php-cli command?
*/
private function isPhpCli(): bool
{
return $this->context === 'php-cli';
}
/**
* Web access?
*/
private function isWeb(): bool
{
return $this->context === 'web';
}
/**
* Disables Controller Filters.
*/
public function disableFilters(): void
{
$this->enableFilters = false;
}
/**
* Handles the main request logic and fires the controller.
*
* @return ResponseInterface
*
* @throws PageNotFoundException
* @throws RedirectException
*
* @deprecated $returnResponse is deprecated.
*/
protected function handleRequest(?RouteCollectionInterface $routes, Cache $cacheConfig, bool $returnResponse = false)
{
if ($this->request instanceof IncomingRequest && $this->request->getMethod() === 'CLI') {
return $this->response->setStatusCode(405)->setBody('Method Not Allowed');
}
$routeFilters = $this->tryToRouteIt($routes);
// $uri is URL-encoded.
$uri = $this->request->getPath();
if ($this->enableFilters) {
/** @var Filters $filters */
$filters = service('filters');
// If any filters were specified within the routes file,
// we need to ensure it's active for the current request
if ($routeFilters !== null) {
$filters->enableFilters($routeFilters, 'before');
$oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false;
if (! $oldFilterOrder) {
$routeFilters = array_reverse($routeFilters);
}
$filters->enableFilters($routeFilters, 'after');
}
// Run "before" filters
$this->benchmark->start('before_filters');
$possibleResponse = $filters->run($uri, 'before');
$this->benchmark->stop('before_filters');
// If a ResponseInterface instance is returned then send it back to the client and stop
if ($possibleResponse instanceof ResponseInterface) {
$this->outputBufferingEnd();
return $possibleResponse;
}
if ($possibleResponse instanceof IncomingRequest || $possibleResponse instanceof CLIRequest) {
$this->request = $possibleResponse;
}
}
$returned = $this->startController();
// Closure controller has run in startController().
if (! is_callable($this->controller)) {
$controller = $this->createController();
if (! method_exists($controller, '_remap') && ! is_callable([$controller, $this->method], false)) {
throw PageNotFoundException::forMethodNotFound($this->method);
}
// Is there a "post_controller_constructor" event?
Events::trigger('post_controller_constructor');
$returned = $this->runController($controller);
} else {
$this->benchmark->stop('controller_constructor');
$this->benchmark->stop('controller');
}
// If $returned is a string, then the controller output something,
// probably a view, instead of echoing it directly. Send it along
// so it can be used with the output.
$this->gatherOutput($cacheConfig, $returned);
if ($this->enableFilters) {
/** @var Filters $filters */
$filters = service('filters');
$filters->setResponse($this->response);
// Run "after" filters
$this->benchmark->start('after_filters');
$response = $filters->run($uri, 'after');
$this->benchmark->stop('after_filters');
if ($response instanceof ResponseInterface) {
$this->response = $response;
}
}
// Skip unnecessary processing for special Responses.
if (
! $this->response instanceof DownloadResponse
&& ! $this->response instanceof RedirectResponse
) {
// Save our current URI as the previous URI in the session
// for safer, more accurate use with `previous_url()` helper function.
$this->storePreviousURL(current_url(true));
}
unset($uri);
return $this->response;
}
/**
* You can load different configurations depending on your
* current environment. Setting the environment also influences
* things like logging and error reporting.
*
* This can be set to anything, but default usage is:
*
* development
* testing
* production
*
* @codeCoverageIgnore
*
* @return void
*
* @deprecated 4.4.0 No longer used. Moved to index.php and spark.
*/
protected function detectEnvironment()
{
// Make sure ENVIRONMENT isn't already set by other means.
if (! defined('ENVIRONMENT')) {
define('ENVIRONMENT', env('CI_ENVIRONMENT', 'production'));
}
}
/**
* Load any custom boot files based upon the current environment.
*
* If no boot file exists, we shouldn't continue because something
* is wrong. At the very least, they should have error reporting setup.
*
* @return void
*
* @deprecated 4.5.0 Moved to system/bootstrap.php.
*/
protected function bootstrapEnvironment()
{
if (is_file(APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php')) {
require_once APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php';
} else {
// @codeCoverageIgnoreStart
header('HTTP/1.1 503 Service Unavailable.', true, 503);
echo 'The application environment is not set correctly.';
exit(EXIT_ERROR); // EXIT_ERROR
// @codeCoverageIgnoreEnd
}
}
/**
* Start the Benchmark
*
* The timer is used to display total script execution both in the
* debug toolbar, and potentially on the displayed page.
*
* @return void
*/
protected function startBenchmark()
{
if ($this->startTime === null) {
$this->startTime = microtime(true);
}
$this->benchmark = Services::timer();
$this->benchmark->start('total_execution', $this->startTime);
$this->benchmark->start('bootstrap');
}
/**
* Sets a Request object to be used for this request.
* Used when running certain tests.
*
* @param CLIRequest|IncomingRequest $request
*
* @return $this
*
* @internal Used for testing purposes only.
* @testTag
*/
public function setRequest($request)
{
$this->request = $request;
return $this;
}
/**
* Get our Request object, (either IncomingRequest or CLIRequest).
*
* @return void
*/
protected function getRequestObject()
{
if ($this->request instanceof Request) {
$this->spoofRequestMethod();
return;
}
if ($this->isPhpCli()) {
Services::createRequest($this->config, true);
} else {
Services::createRequest($this->config);
}
$this->request = service('request');
$this->spoofRequestMethod();
}
/**
* Get our Response object, and set some default values, including
* the HTTP protocol version and a default successful response.
*
* @return void
*/
protected function getResponseObject()
{
$this->response = Services::response($this->config);
if ($this->isWeb()) {
$this->response->setProtocolVersion($this->request->getProtocolVersion());
}
// Assume success until proven otherwise.
$this->response->setStatusCode(200);
}
/**
* Force Secure Site Access? If the config value 'forceGlobalSecureRequests'
* is true, will enforce that all requests to this site are made through
* HTTPS. Will redirect the user to the current page with HTTPS, as well
* as set the HTTP Strict Transport Security header for those browsers
* that support it.
*
* @param int $duration How long the Strict Transport Security
* should be enforced for this URL.
*
* @return void
*
* @deprecated 4.5.0 No longer used. Moved to ForceHTTPS filter.
*/
protected function forceSecureAccess($duration = 31_536_000)
{
if ($this->config->forceGlobalSecureRequests !== true) {
return;
}
force_https($duration, $this->request, $this->response);
}
/**
* Determines if a response has been cached for the given URI.
*
* @return false|ResponseInterface
*
* @throws Exception
*
* @deprecated 4.5.0 PageCache required filter is used. No longer used.
* @deprecated 4.4.2 The parameter $config is deprecated. No longer used.
*/
public function displayCache(Cache $config)
{
$cachedResponse = $this->pageCache->get($this->request, $this->response);
if ($cachedResponse instanceof ResponseInterface) {
$this->response = $cachedResponse;
$this->totalTime = $this->benchmark->getElapsedTime('total_execution');
$output = $this->displayPerformanceMetrics($cachedResponse->getBody());
$this->response->setBody($output);
return $this->response;
}
return false;
}
/**
* Tells the app that the final output should be cached.
*
* @deprecated 4.4.0 Moved to ResponseCache::setTtl(). No longer used.
*
* @return void
*/
public static function cache(int $time)
{
static::$cacheTTL = $time;
}
/**
* Caches the full response from the current request. Used for
* full-page caching for very high performance.
*
* @return bool
*
* @deprecated 4.4.0 No longer used.
*/
public function cachePage(Cache $config)
{
$headers = [];
foreach ($this->response->headers() as $header) {
$headers[$header->getName()] = $header->getValueLine();
}
return cache()->save($this->generateCacheName($config), serialize(['headers' => $headers, 'output' => $this->output]), static::$cacheTTL);
}
/**
* Returns an array with our basic performance stats collected.
*/
public function getPerformanceStats(): array
{
// After filter debug toolbar requires 'total_execution'.
$this->totalTime = $this->benchmark->getElapsedTime('total_execution');
return [
'startTime' => $this->startTime,
'totalTime' => $this->totalTime,
];
}
/**
* Generates the cache name to use for our full-page caching.
*
* @deprecated 4.4.0 No longer used.
*/
protected function generateCacheName(Cache $config): string
{
if ($this->request instanceof CLIRequest) {
return md5($this->request->getPath());
}
$uri = clone $this->request->getUri();
$query = $config->cacheQueryString
? $uri->getQuery(is_array($config->cacheQueryString) ? ['only' => $config->cacheQueryString] : [])
: '';
return md5((string) $uri->setFragment('')->setQuery($query));
}
/**
* Replaces the elapsed_time and memory_usage tag.
*
* @deprecated 4.5.0 PerformanceMetrics required filter is used. No longer used.
*/
public function displayPerformanceMetrics(string $output): string
{
return str_replace(
['{elapsed_time}', '{memory_usage}'],
[(string) $this->totalTime, number_format(memory_get_peak_usage() / 1024 / 1024, 3)],
$output,
);
}
/**
* Try to Route It - As it sounds like, works with the router to
* match a route against the current URI. If the route is a
* "redirect route", will also handle the redirect.
*
* @param RouteCollectionInterface|null $routes A collection interface to use in place
* of the config file.
*
* @return list<string>|string|null Route filters, that is, the filters specified in the routes file
*
* @throws RedirectException
*/
protected function tryToRouteIt(?RouteCollectionInterface $routes = null)
{
$this->benchmark->start('routing');
if (! $routes instanceof RouteCollectionInterface) {
$routes = service('routes')->loadRoutes();
}
// $routes is defined in Config/Routes.php
$this->router = Services::router($routes, $this->request);
// $uri is URL-encoded.
$uri = $this->request->getPath();
$this->outputBufferingStart();
$this->controller = $this->router->handle($uri);
$this->method = $this->router->methodName();
// If a {locale} segment was matched in the final route,
// then we need to set the correct locale on our Request.
if ($this->router->hasLocale()) {
$this->request->setLocale($this->router->getLocale());
}
$this->benchmark->stop('routing');
return $this->router->getFilters();
}
/**
* Determines the path to use for us to try to route to, based
* on the CLI/IncomingRequest path.
*
* @return string
*
* @deprecated 4.5.0 No longer used.
*/
protected function determinePath()
{
return $this->request->getPath();
}
/**
* Now that everything has been setup, this method attempts to run the
* controller method and make the script go. If it's not able to, will
* show the appropriate Page Not Found error.
*
* @return ResponseInterface|string|null
*/
protected function startController()
{
$this->benchmark->start('controller');
$this->benchmark->start('controller_constructor');
// Is it routed to a Closure?
if (is_object($this->controller) && ($this->controller::class === 'Closure')) {
$controller = $this->controller;
return $controller(...$this->router->params());
}
// No controller specified - we don't know what to do now.
if (! isset($this->controller)) {
throw PageNotFoundException::forEmptyController();
}
// Try to autoload the class
if (
! class_exists($this->controller, true)
|| ($this->method[0] === '_' && $this->method !== '__invoke')
) {
throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
}
return null;
}
/**
* Instantiates the controller class.
*
* @return Controller
*/
protected function createController()
{
assert(is_string($this->controller));
$class = new $this->controller();
$class->initController($this->request, $this->response, Services::logger());
$this->benchmark->stop('controller_constructor');
return $class;
}
/**
* Runs the controller, allowing for _remap methods to function.
*
* CI4 supports three types of requests:
* 1. Web: URI segments become parameters, sent to Controllers via Routes,
* output controlled by Headers to browser
* 2. PHP CLI: accessed by CLI via php public/index.php, arguments become URI segments,
* sent to Controllers via Routes, output varies
*
* @param Controller $class
*
* @return false|ResponseInterface|string|void
*/
protected function runController($class)
{
// This is a Web request or PHP CLI request
$params = $this->router->params();
// The controller method param types may not be string.
// So cannot set `declare(strict_types=1)` in this file.
$output = method_exists($class, '_remap')
? $class->_remap($this->method, ...$params)
: $class->{$this->method}(...$params);
$this->benchmark->stop('controller');
return $output;
}
/**
* Displays a 404 Page Not Found error. If set, will try to
* call the 404Override controller/method that was set in routing config.
*
* @return ResponseInterface|void
*/
protected function display404errors(PageNotFoundException $e)
{
$this->response->setStatusCode($e->getCode());
// Is there a 404 Override available?
$override = $this->router->get404Override();
if ($override !== null) {
$returned = null;
if ($override instanceof Closure) {
echo $override($e->getMessage());
} elseif (is_array($override)) {
$this->benchmark->start('controller');
$this->benchmark->start('controller_constructor');
$this->controller = $override[0];
$this->method = $override[1];
$controller = $this->createController();
$returned = $controller->{$this->method}($e->getMessage());
$this->benchmark->stop('controller');
}
unset($override);
$cacheConfig = config(Cache::class);
$this->gatherOutput($cacheConfig, $returned);
return $this->response;
}
$this->outputBufferingEnd();
// Throws new PageNotFoundException and remove exception message on production.
throw PageNotFoundException::forPageNotFound(
(ENVIRONMENT !== 'production' || ! $this->isWeb()) ? $e->getMessage() : null,
);
}
/**
* Gathers the script output from the buffer, replaces some execution
* time tag in the output and displays the debug toolbar, if required.
*
* @param Cache|null $cacheConfig Deprecated. No longer used.
* @param ResponseInterface|string|null $returned
*
* @deprecated $cacheConfig is deprecated.
*
* @return void
*/
protected function gatherOutput(?Cache $cacheConfig = null, $returned = null)
{
$this->output = $this->outputBufferingEnd();
if ($returned instanceof DownloadResponse) {
$this->response = $returned;
return;
}
// If the controller returned a response object,
// we need to grab the body from it so it can
// be added to anything else that might have been
// echoed already.
// We also need to save the instance locally
// so that any status code changes, etc, take place.
if ($returned instanceof ResponseInterface) {
$this->response = $returned;
$returned = $returned->getBody();
}
if (is_string($returned)) {
$this->output .= $returned;
}
$this->response->setBody($this->output);
}
/**
* If we have a session object to use, store the current URI
* as the previous URI. This is called just prior to sending the
* response to the client, and will make it available next request.
*
* This helps provider safer, more reliable previous_url() detection.
*
* @param string|URI $uri
*
* @return void
*/
public function storePreviousURL($uri)
{
// Ignore CLI requests
if (! $this->isWeb()) {
return;
}
// Ignore AJAX requests
if (method_exists($this->request, 'isAJAX') && $this->request->isAJAX()) {
return;
}
// Ignore unroutable responses
if ($this->response instanceof DownloadResponse || $this->response instanceof RedirectResponse) {
return;
}
// Ignore non-HTML responses
if (! str_contains($this->response->getHeaderLine('Content-Type'), 'text/html')) {
return;
}
// This is mainly needed during testing...
if (is_string($uri)) {
$uri = new URI($uri);
}
if (isset($_SESSION)) {
session()->set('_ci_previous_url', URI::createURIString(
$uri->getScheme(),
$uri->getAuthority(),
$uri->getPath(),
$uri->getQuery(),
$uri->getFragment(),
));
}
}
/**
* Modifies the Request Object to use a different method if a POST
* variable called _method is found.
*
* @return void
*/
public function spoofRequestMethod()
{
// Only works with POSTED forms
if ($this->request->getMethod() !== Method::POST) {
return;
}
$method = $this->request->getPost('_method');
if ($method === null) {
return;
}
// Only allows PUT, PATCH, DELETE
if (in_array($method, [Method::PUT, Method::PATCH, Method::DELETE], true)) {
$this->request = $this->request->setMethod($method);
}
}
/**
* Sends the output of this request back to the client.
* This is what they've been waiting for!
*
* @return void
*/
protected function sendResponse()
{
$this->response->send();
}
/**
* Exits the application, setting the exit code for CLI-based applications
* that might be watching.
*
* Made into a separate method so that it can be mocked during testing
* without actually stopping script execution.
*
* @param int $code
*
* @deprecated 4.4.0 No longer Used. Moved to index.php.
*
* @return void
*/
protected function callExit($code)
{
exit($code); // @codeCoverageIgnore
}
/**
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/BaseModel.php | system/BaseModel.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use Closure;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Exceptions\DataException;
use CodeIgniter\Database\Query;
use CodeIgniter\DataConverter\DataConverter;
use CodeIgniter\Entity\Entity;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\ModelException;
use CodeIgniter\I18n\Time;
use CodeIgniter\Pager\Pager;
use CodeIgniter\Validation\ValidationInterface;
use Config\Feature;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;
use stdClass;
/**
* The BaseModel class provides a number of convenient features that
* makes working with a databases less painful. Extending this class
* provide means of implementing various database systems
*
* It will:
* - simplifies pagination
* - allow specifying the return type (array, object, etc) with each call
* - automatically set and update timestamps
* - handle soft deletes
* - ensure validation is run against objects when saving items
* - process various callbacks
* - allow intermingling calls to the db connection
*
* @phpstan-type row_array array<int|string, float|int|null|object|string|bool>
* @phpstan-type event_data_beforeinsert array{data: row_array}
* @phpstan-type event_data_afterinsert array{id: int|string, data: row_array, result: bool}
* @phpstan-type event_data_beforefind array{id?: int|string, method: string, singleton: bool, limit?: int, offset?: int}
* @phpstan-type event_data_afterfind array{id: int|string|null|list<int|string>, data: row_array|list<row_array>|object|null, method: string, singleton: bool}
* @phpstan-type event_data_beforeupdate array{id: null|list<int|string>, data: row_array}
* @phpstan-type event_data_afterupdate array{id: null|list<int|string>, data: row_array|object, result: bool}
* @phpstan-type event_data_beforedelete array{id: null|list<int|string>, purge: bool}
* @phpstan-type event_data_afterdelete array{id: null|list<int|string>, data: null, purge: bool, result: bool}
*/
abstract class BaseModel
{
/**
* Pager instance.
* Populated after calling $this->paginate()
*
* @var Pager
*/
public $pager;
/**
* Database Connection
*
* @var BaseConnection
*/
protected $db;
/**
* Last insert ID
*
* @var int|string
*/
protected $insertID = 0;
/**
* The Database connection group that
* should be instantiated.
*
* @var non-empty-string|null
*/
protected $DBGroup;
/**
* The format that the results should be returned as.
* Will be overridden if the as* methods are used.
*
* @var string
*/
protected $returnType = 'array';
/**
* Used by asArray() and asObject() to provide
* temporary overrides of model default.
*
* @var 'array'|'object'|class-string
*/
protected $tempReturnType;
/**
* Array of column names and the type of value to cast.
*
* @var array<string, string> [column => type]
*/
protected array $casts = [];
/**
* Custom convert handlers.
*
* @var array<string, class-string> [type => classname]
*/
protected array $castHandlers = [];
protected ?DataConverter $converter = null;
/**
* Determines whether the model should protect field names during
* mass assignment operations such as insert() and update().
*
* When set to true, only the fields explicitly defined in the $allowedFields
* property will be allowed for mass assignment. This helps prevent
* unintended modification of database fields and improves security
* by avoiding mass assignment vulnerabilities.
*
* @var bool
*/
protected $protectFields = true;
/**
* An array of field names that are allowed
* to be set by the user in inserts/updates.
*
* @var list<string>
*/
protected $allowedFields = [];
/**
* If true, will set created_at, and updated_at
* values during insert and update routines.
*
* @var bool
*/
protected $useTimestamps = false;
/**
* The type of column that created_at and updated_at
* are expected to.
*
* Allowed: 'datetime', 'date', 'int'
*
* @var string
*/
protected $dateFormat = 'datetime';
/**
* The column used for insert timestamps
*
* @var string
*/
protected $createdField = 'created_at';
/**
* The column used for update timestamps
*
* @var string
*/
protected $updatedField = 'updated_at';
/**
* If this model should use "softDeletes" and
* simply set a date when rows are deleted, or
* do hard deletes.
*
* @var bool
*/
protected $useSoftDeletes = false;
/**
* Used by withDeleted to override the
* model's softDelete setting.
*
* @var bool
*/
protected $tempUseSoftDeletes;
/**
* The column used to save soft delete state
*
* @var string
*/
protected $deletedField = 'deleted_at';
/**
* Whether to allow inserting empty data.
*/
protected bool $allowEmptyInserts = false;
/**
* Whether to update Entity's only changed data.
*/
protected bool $updateOnlyChanged = true;
/**
* Rules used to validate data in insert(), update(), and save() methods.
*
* The array must match the format of data passed to the Validation
* library.
*
* @see https://codeigniter4.github.io/userguide/models/model.html#setting-validation-rules
*
* @var array<string, array<string, array<string, string>|string>|string>|string
*/
protected $validationRules = [];
/**
* Contains any custom error messages to be
* used during data validation.
*
* @var array<string, array<string, string>>
*/
protected $validationMessages = [];
/**
* Skip the model's validation. Used in conjunction with skipValidation()
* to skip data validation for any future calls.
*
* @var bool
*/
protected $skipValidation = false;
/**
* Whether rules should be removed that do not exist
* in the passed data. Used in updates.
*
* @var bool
*/
protected $cleanValidationRules = true;
/**
* Our validator instance.
*
* @var ValidationInterface|null
*/
protected $validation;
/*
* Callbacks.
*
* Each array should contain the method names (within the model)
* that should be called when those events are triggered.
*
* "Update" and "delete" methods are passed the same items that
* are given to their respective method.
*
* "Find" methods receive the ID searched for (if present), and
* 'afterFind' additionally receives the results that were found.
*/
/**
* Whether to trigger the defined callbacks
*
* @var bool
*/
protected $allowCallbacks = true;
/**
* Used by allowCallbacks() to override the
* model's allowCallbacks setting.
*
* @var bool
*/
protected $tempAllowCallbacks;
/**
* Callbacks for beforeInsert
*
* @var list<string>
*/
protected $beforeInsert = [];
/**
* Callbacks for afterInsert
*
* @var list<string>
*/
protected $afterInsert = [];
/**
* Callbacks for beforeUpdate
*
* @var list<string>
*/
protected $beforeUpdate = [];
/**
* Callbacks for afterUpdate
*
* @var list<string>
*/
protected $afterUpdate = [];
/**
* Callbacks for beforeInsertBatch
*
* @var list<string>
*/
protected $beforeInsertBatch = [];
/**
* Callbacks for afterInsertBatch
*
* @var list<string>
*/
protected $afterInsertBatch = [];
/**
* Callbacks for beforeUpdateBatch
*
* @var list<string>
*/
protected $beforeUpdateBatch = [];
/**
* Callbacks for afterUpdateBatch
*
* @var list<string>
*/
protected $afterUpdateBatch = [];
/**
* Callbacks for beforeFind
*
* @var list<string>
*/
protected $beforeFind = [];
/**
* Callbacks for afterFind
*
* @var list<string>
*/
protected $afterFind = [];
/**
* Callbacks for beforeDelete
*
* @var list<string>
*/
protected $beforeDelete = [];
/**
* Callbacks for afterDelete
*
* @var list<string>
*/
protected $afterDelete = [];
public function __construct(?ValidationInterface $validation = null)
{
$this->tempReturnType = $this->returnType;
$this->tempUseSoftDeletes = $this->useSoftDeletes;
$this->tempAllowCallbacks = $this->allowCallbacks;
$this->validation = $validation;
$this->initialize();
$this->createDataConverter();
}
/**
* Creates DataConverter instance.
*/
protected function createDataConverter(): void
{
if ($this->useCasts()) {
$this->converter = new DataConverter(
$this->casts,
$this->castHandlers,
$this->db,
);
}
}
/**
* Are casts used?
*/
protected function useCasts(): bool
{
return $this->casts !== [];
}
/**
* Initializes the instance with any additional steps.
* Optionally implemented by child classes.
*
* @return void
*/
protected function initialize()
{
}
/**
* Fetches the row of database.
* This method works only with dbCalls.
*
* @param bool $singleton Single or multiple results
* @param array|int|string|null $id One primary key or an array of primary keys
*
* @return array|object|null The resulting row of data, or null.
*/
abstract protected function doFind(bool $singleton, $id = null);
/**
* Fetches the column of database.
* This method works only with dbCalls.
*
* @param string $columnName Column Name
*
* @return array|null The resulting row of data, or null if no data found.
*
* @throws DataException
*/
abstract protected function doFindColumn(string $columnName);
/**
* Fetches all results, while optionally limiting them.
* This method works only with dbCalls.
*
* @param int|null $limit Limit
* @param int $offset Offset
*
* @return array
*/
abstract protected function doFindAll(?int $limit = null, int $offset = 0);
/**
* Returns the first row of the result set.
* This method works only with dbCalls.
*
* @return array|object|null
*/
abstract protected function doFirst();
/**
* Inserts data into the current database.
* This method works only with dbCalls.
*
* @param array $row Row data
* @phpstan-param row_array $row
*
* @return bool
*/
abstract protected function doInsert(array $row);
/**
* Compiles batch insert and runs the queries, validating each row prior.
* This method works only with dbCalls.
*
* @param array|null $set An associative array of insert values
* @param bool|null $escape Whether to escape values
* @param int $batchSize The size of the batch to run
* @param bool $testing True means only number of records is returned, false will execute the query
*
* @return bool|int Number of rows inserted or FALSE on failure
*/
abstract protected function doInsertBatch(?array $set = null, ?bool $escape = null, int $batchSize = 100, bool $testing = false);
/**
* Updates a single record in the database.
* This method works only with dbCalls.
*
* @param array|int|string|null $id ID
* @param array|null $row Row data
* @phpstan-param row_array|null $row
*/
abstract protected function doUpdate($id = null, $row = null): bool;
/**
* Compiles an update and runs the query.
* This method works only with dbCalls.
*
* @param array|null $set An associative array of update values
* @param string|null $index The where key
* @param int $batchSize The size of the batch to run
* @param bool $returnSQL True means SQL is returned, false will execute the query
*
* @return false|int|list<string> Number of rows affected or FALSE on failure, SQL array when testMode
*
* @throws DatabaseException
*/
abstract protected function doUpdateBatch(?array $set = null, ?string $index = null, int $batchSize = 100, bool $returnSQL = false);
/**
* Deletes a single record from the database where $id matches.
* This method works only with dbCalls.
*
* @param array|int|string|null $id The rows primary key(s)
* @param bool $purge Allows overriding the soft deletes setting.
*
* @return bool|string
*
* @throws DatabaseException
*/
abstract protected function doDelete($id = null, bool $purge = false);
/**
* Permanently deletes all rows that have been marked as deleted.
* through soft deletes (deleted = 1).
* This method works only with dbCalls.
*
* @return bool|string Returns a string if in test mode.
*/
abstract protected function doPurgeDeleted();
/**
* Works with the find* methods to return only the rows that
* have been deleted.
* This method works only with dbCalls.
*
* @return void
*/
abstract protected function doOnlyDeleted();
/**
* Compiles a replace and runs the query.
* This method works only with dbCalls.
*
* @param row_array|null $row Row data
* @param bool $returnSQL Set to true to return Query String
*
* @return BaseResult|false|Query|string
*/
abstract protected function doReplace(?array $row = null, bool $returnSQL = false);
/**
* Grabs the last error(s) that occurred from the Database connection.
* This method works only with dbCalls.
*
* @return array<string, string>
*/
abstract protected function doErrors();
/**
* Public getter to return the id value using the idValue() method.
* For example with SQL this will return $data->$this->primaryKey.
*
* @param object|row_array $row Row data
*
* @return array|int|string|null
*/
abstract public function getIdValue($row);
/**
* Override countAllResults to account for soft deleted accounts.
* This method works only with dbCalls.
*
* @param bool $reset Reset
* @param bool $test Test
*
* @return int|string
*/
abstract public function countAllResults(bool $reset = true, bool $test = false);
/**
* Loops over records in batches, allowing you to operate on them.
* This method works only with dbCalls.
*
* @param int $size Size
* @param Closure(array<string, string>|object): mixed $userFunc Callback Function
*
* @return void
*
* @throws DataException
*/
abstract public function chunk(int $size, Closure $userFunc);
/**
* Fetches the row of database.
*
* @param array|int|string|null $id One primary key or an array of primary keys
*
* @return array|object|null The resulting row of data, or null.
* @phpstan-return ($id is int|string ? row_array|object|null : list<row_array|object>)
*/
public function find($id = null)
{
$singleton = is_numeric($id) || is_string($id);
if ($this->tempAllowCallbacks) {
// Call the before event and check for a return
$eventData = $this->trigger('beforeFind', [
'id' => $id,
'method' => 'find',
'singleton' => $singleton,
]);
if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
return $eventData['data'];
}
}
$eventData = [
'id' => $id,
'data' => $this->doFind($singleton, $id),
'method' => 'find',
'singleton' => $singleton,
];
if ($this->tempAllowCallbacks) {
$eventData = $this->trigger('afterFind', $eventData);
}
$this->tempReturnType = $this->returnType;
$this->tempUseSoftDeletes = $this->useSoftDeletes;
$this->tempAllowCallbacks = $this->allowCallbacks;
return $eventData['data'];
}
/**
* Fetches the column of database.
*
* @param string $columnName Column Name
*
* @return array|null The resulting row of data, or null if no data found.
*
* @throws DataException
*/
public function findColumn(string $columnName)
{
if (str_contains($columnName, ',')) {
throw DataException::forFindColumnHaveMultipleColumns();
}
$resultSet = $this->doFindColumn($columnName);
return $resultSet !== null ? array_column($resultSet, $columnName) : null;
}
/**
* Fetches all results, while optionally limiting them.
*
* @param int $limit Limit
* @param int $offset Offset
*
* @return array
*/
public function findAll(?int $limit = null, int $offset = 0)
{
$limitZeroAsAll = config(Feature::class)->limitZeroAsAll ?? true;
if ($limitZeroAsAll) {
$limit ??= 0;
}
if ($this->tempAllowCallbacks) {
// Call the before event and check for a return
$eventData = $this->trigger('beforeFind', [
'method' => 'findAll',
'limit' => $limit,
'offset' => $offset,
'singleton' => false,
]);
if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
return $eventData['data'];
}
}
$eventData = [
'data' => $this->doFindAll($limit, $offset),
'limit' => $limit,
'offset' => $offset,
'method' => 'findAll',
'singleton' => false,
];
if ($this->tempAllowCallbacks) {
$eventData = $this->trigger('afterFind', $eventData);
}
$this->tempReturnType = $this->returnType;
$this->tempUseSoftDeletes = $this->useSoftDeletes;
$this->tempAllowCallbacks = $this->allowCallbacks;
return $eventData['data'];
}
/**
* Returns the first row of the result set.
*
* @return array|object|null
*/
public function first()
{
if ($this->tempAllowCallbacks) {
// Call the before event and check for a return
$eventData = $this->trigger('beforeFind', [
'method' => 'first',
'singleton' => true,
]);
if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
return $eventData['data'];
}
}
$eventData = [
'data' => $this->doFirst(),
'method' => 'first',
'singleton' => true,
];
if ($this->tempAllowCallbacks) {
$eventData = $this->trigger('afterFind', $eventData);
}
$this->tempReturnType = $this->returnType;
$this->tempUseSoftDeletes = $this->useSoftDeletes;
$this->tempAllowCallbacks = $this->allowCallbacks;
return $eventData['data'];
}
/**
* A convenience method that will attempt to determine whether the
* data should be inserted or updated. Will work with either
* an array or object. When using with custom class objects,
* you must ensure that the class will provide access to the class
* variables, even if through a magic method.
*
* @param object|row_array $row Row data
*
* @throws ReflectionException
*/
public function save($row): bool
{
if ((array) $row === []) {
return true;
}
if ($this->shouldUpdate($row)) {
$response = $this->update($this->getIdValue($row), $row);
} else {
$response = $this->insert($row, false);
if ($response !== false) {
$response = true;
}
}
return $response;
}
/**
* This method is called on save to determine if entry have to be updated.
* If this method returns false insert operation will be executed
*
* @param array|object $row Row data
* @phpstan-param row_array|object $row
*/
protected function shouldUpdate($row): bool
{
$id = $this->getIdValue($row);
return ! ($id === null || $id === [] || $id === '');
}
/**
* Returns last insert ID or 0.
*
* @return int|string
*/
public function getInsertID()
{
return is_numeric($this->insertID) ? (int) $this->insertID : $this->insertID;
}
/**
* Inserts data into the database. If an object is provided,
* it will attempt to convert it to an array.
*
* @param object|row_array|null $row Row data
* @param bool $returnID Whether insert ID should be returned or not.
*
* @return ($returnID is true ? false|int|string : bool)
*
* @throws ReflectionException
*/
public function insert($row = null, bool $returnID = true)
{
$this->insertID = 0;
// Set $cleanValidationRules to false temporary.
$cleanValidationRules = $this->cleanValidationRules;
$this->cleanValidationRules = false;
$row = $this->transformDataToArray($row, 'insert');
// Validate data before saving.
if (! $this->skipValidation && ! $this->validate($row)) {
// Restore $cleanValidationRules
$this->cleanValidationRules = $cleanValidationRules;
return false;
}
// Restore $cleanValidationRules
$this->cleanValidationRules = $cleanValidationRules;
// Must be called first, so we don't
// strip out created_at values.
$row = $this->doProtectFieldsForInsert($row);
// doProtectFields() can further remove elements from
// $row, so we need to check for empty dataset again
if (! $this->allowEmptyInserts && $row === []) {
throw DataException::forEmptyDataset('insert');
}
// Set created_at and updated_at with same time
$date = $this->setDate();
$row = $this->setCreatedField($row, $date);
$row = $this->setUpdatedField($row, $date);
$eventData = ['data' => $row];
if ($this->tempAllowCallbacks) {
$eventData = $this->trigger('beforeInsert', $eventData);
}
$result = $this->doInsert($eventData['data']);
$eventData = [
'id' => $this->insertID,
'data' => $eventData['data'],
'result' => $result,
];
if ($this->tempAllowCallbacks) {
// Trigger afterInsert events with the inserted data and new ID
$this->trigger('afterInsert', $eventData);
}
$this->tempAllowCallbacks = $this->allowCallbacks;
// If insertion failed, get out of here
if (! $result) {
return $result;
}
// otherwise return the insertID, if requested.
return $returnID ? $this->insertID : $result;
}
/**
* Set datetime to created field.
*
* @param row_array $row
* @param int|string $date timestamp or datetime string
*/
protected function setCreatedField(array $row, $date): array
{
if ($this->useTimestamps && $this->createdField !== '' && ! array_key_exists($this->createdField, $row)) {
$row[$this->createdField] = $date;
}
return $row;
}
/**
* Set datetime to updated field.
*
* @param row_array $row
* @param int|string $date timestamp or datetime string
*/
protected function setUpdatedField(array $row, $date): array
{
if ($this->useTimestamps && $this->updatedField !== '' && ! array_key_exists($this->updatedField, $row)) {
$row[$this->updatedField] = $date;
}
return $row;
}
/**
* Compiles batch insert runs the queries, validating each row prior.
*
* @param list<object|row_array>|null $set an associative array of insert values
* @param bool|null $escape Whether to escape values
* @param int $batchSize The size of the batch to run
* @param bool $testing True means only number of records is returned, false will execute the query
*
* @return bool|int Number of rows inserted or FALSE on failure
*
* @throws ReflectionException
*/
public function insertBatch(?array $set = null, ?bool $escape = null, int $batchSize = 100, bool $testing = false)
{
// Set $cleanValidationRules to false temporary.
$cleanValidationRules = $this->cleanValidationRules;
$this->cleanValidationRules = false;
if (is_array($set)) {
foreach ($set as &$row) {
// If $row is using a custom class with public or protected
// properties representing the collection elements, we need to grab
// them as an array.
if (is_object($row) && ! $row instanceof stdClass) {
$row = $this->objectToArray($row, false, true);
}
// If it's still a stdClass, go ahead and convert to
// an array so doProtectFields and other model methods
// don't have to do special checks.
if (is_object($row)) {
$row = (array) $row;
}
// Convert any Time instances to appropriate $dateFormat
$row = $this->timeToString($row);
// Validate every row.
if (! $this->skipValidation && ! $this->validate($row)) {
// Restore $cleanValidationRules
$this->cleanValidationRules = $cleanValidationRules;
return false;
}
// Must be called first so we don't
// strip out created_at values.
$row = $this->doProtectFieldsForInsert($row);
// Set created_at and updated_at with same time
$date = $this->setDate();
$row = $this->setCreatedField($row, $date);
$row = $this->setUpdatedField($row, $date);
}
}
// Restore $cleanValidationRules
$this->cleanValidationRules = $cleanValidationRules;
$eventData = ['data' => $set];
if ($this->tempAllowCallbacks) {
$eventData = $this->trigger('beforeInsertBatch', $eventData);
}
$result = $this->doInsertBatch($eventData['data'], $escape, $batchSize, $testing);
$eventData = [
'data' => $eventData['data'],
'result' => $result,
];
if ($this->tempAllowCallbacks) {
// Trigger afterInsert events with the inserted data and new ID
$this->trigger('afterInsertBatch', $eventData);
}
$this->tempAllowCallbacks = $this->allowCallbacks;
return $result;
}
/**
* Updates a single record in the database. If an object is provided,
* it will attempt to convert it into an array.
*
* @param array|int|string|null $id
* @param array|object|null $row Row data
* @phpstan-param row_array|object|null $row
*
* @throws ReflectionException
*/
public function update($id = null, $row = null): bool
{
if (is_bool($id)) {
throw new InvalidArgumentException('update(): argument #1 ($id) should not be boolean.');
}
if (is_numeric($id) || is_string($id)) {
$id = [$id];
}
$row = $this->transformDataToArray($row, 'update');
// Validate data before saving.
if (! $this->skipValidation && ! $this->validate($row)) {
return false;
}
// Must be called first, so we don't
// strip out updated_at values.
$row = $this->doProtectFields($row);
// doProtectFields() can further remove elements from
// $row, so we need to check for empty dataset again
if ($row === []) {
throw DataException::forEmptyDataset('update');
}
$row = $this->setUpdatedField($row, $this->setDate());
$eventData = [
'id' => $id,
'data' => $row,
];
if ($this->tempAllowCallbacks) {
$eventData = $this->trigger('beforeUpdate', $eventData);
}
$eventData = [
'id' => $id,
'data' => $eventData['data'],
'result' => $this->doUpdate($id, $eventData['data']),
];
if ($this->tempAllowCallbacks) {
$this->trigger('afterUpdate', $eventData);
}
$this->tempAllowCallbacks = $this->allowCallbacks;
return $eventData['result'];
}
/**
* Compiles an update and runs the query.
*
* @param list<object|row_array>|null $set an associative array of insert values
* @param string|null $index The where key
* @param int $batchSize The size of the batch to run
* @param bool $returnSQL True means SQL is returned, false will execute the query
*
* @return false|int|list<string> Number of rows affected or FALSE on failure, SQL array when testMode
*
* @throws DatabaseException
* @throws ReflectionException
*/
public function updateBatch(?array $set = null, ?string $index = null, int $batchSize = 100, bool $returnSQL = false)
{
if (is_array($set)) {
foreach ($set as &$row) {
// If $row is using a custom class with public or protected
// properties representing the collection elements, we need to grab
// them as an array.
if (is_object($row) && ! $row instanceof stdClass) {
// For updates the index field is needed even if it is not changed.
// So set $onlyChanged to false.
$row = $this->objectToArray($row, false, true);
}
// If it's still a stdClass, go ahead and convert to
// an array so doProtectFields and other model methods
// don't have to do special checks.
if (is_object($row)) {
$row = (array) $row;
}
// Validate data before saving.
if (! $this->skipValidation && ! $this->validate($row)) {
return false;
}
// Save updateIndex for later
$updateIndex = $row[$index] ?? null;
if ($updateIndex === null) {
throw new InvalidArgumentException(
'The index ("' . $index . '") for updateBatch() is missing in the data: '
. json_encode($row),
);
}
// Must be called first so we don't
// strip out updated_at values.
$row = $this->doProtectFields($row);
// Restore updateIndex value in case it was wiped out
$row[$index] = $updateIndex;
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/bootstrap.php | system/bootstrap.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
/**
* ---------------------------------------------------------------
* This file cannot be used. The code has moved to Boot.php.
* ---------------------------------------------------------------
*/
use CodeIgniter\Exceptions\FrameworkException;
use Config\Autoload;
use Config\Modules;
use Config\Paths;
use Config\Services;
header('HTTP/1.1 503 Service Unavailable.', true, 503);
$message = 'This "system/bootstrap.php" is no longer used. If you are seeing this error message,
the upgrade is not complete. Please refer to the upgrade guide and complete the upgrade.
See https://codeigniter4.github.io/userguide/installation/upgrade_450.html' . PHP_EOL;
echo $message;
/*
* ---------------------------------------------------------------
* SETUP OUR PATH CONSTANTS
* ---------------------------------------------------------------
*
* The path constants provide convenient access to the folders
* throughout the application. We have to setup them up here
* so they are available in the config files that are loaded.
*/
/** @var Paths $paths */
// The path to the application directory.
if (! defined('APPPATH')) {
define('APPPATH', realpath(rtrim($paths->appDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
}
// The path to the project root directory. Just above APPPATH.
if (! defined('ROOTPATH')) {
define('ROOTPATH', realpath(APPPATH . '../') . DIRECTORY_SEPARATOR);
}
// The path to the system directory.
if (! defined('SYSTEMPATH')) {
define('SYSTEMPATH', realpath(rtrim($paths->systemDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
}
// The path to the writable directory.
if (! defined('WRITEPATH')) {
define('WRITEPATH', realpath(rtrim($paths->writableDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
}
// The path to the tests directory
if (! defined('TESTPATH')) {
define('TESTPATH', realpath(rtrim($paths->testsDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
}
/*
* ---------------------------------------------------------------
* GRAB OUR CONSTANTS
* ---------------------------------------------------------------
*/
if (! defined('APP_NAMESPACE')) {
require_once APPPATH . 'Config/Constants.php';
}
/*
* ---------------------------------------------------------------
* LOAD COMMON FUNCTIONS
* ---------------------------------------------------------------
*/
// Require app/Common.php file if exists.
if (is_file(APPPATH . 'Common.php')) {
require_once APPPATH . 'Common.php';
}
// Require system/Common.php
require_once SYSTEMPATH . 'Common.php';
/*
* ---------------------------------------------------------------
* LOAD OUR AUTOLOADER
* ---------------------------------------------------------------
*
* The autoloader allows all of the pieces to work together in the
* framework. We have to load it here, though, so that the config
* files can use the path constants.
*/
if (! class_exists(Autoload::class, false)) {
require_once SYSTEMPATH . 'Config/AutoloadConfig.php';
require_once APPPATH . 'Config/Autoload.php';
require_once SYSTEMPATH . 'Modules/Modules.php';
require_once APPPATH . 'Config/Modules.php';
}
require_once SYSTEMPATH . 'Autoloader/Autoloader.php';
require_once SYSTEMPATH . 'Config/BaseService.php';
require_once SYSTEMPATH . 'Config/Services.php';
require_once APPPATH . 'Config/Services.php';
// Initialize and register the loader with the SPL autoloader stack.
Services::autoloader()->initialize(new Autoload(), new Modules())->register();
Services::autoloader()->loadHelpers();
/*
* ---------------------------------------------------------------
* SET EXCEPTION AND ERROR HANDLERS
* ---------------------------------------------------------------
*/
Services::exceptions()->initialize();
/*
* ---------------------------------------------------------------
* CHECK SYSTEM FOR MISSING REQUIRED PHP EXTENSIONS
* ---------------------------------------------------------------
*/
// Run this check for manual installations
if (! is_file(COMPOSER_PATH)) {
$missingExtensions = [];
foreach ([
'intl',
'json',
'mbstring',
] as $extension) {
if (! extension_loaded($extension)) {
$missingExtensions[] = $extension;
}
}
if ($missingExtensions !== []) {
throw FrameworkException::forMissingExtension(implode(', ', $missingExtensions));
}
unset($missingExtensions);
}
/*
* ---------------------------------------------------------------
* INITIALIZE KINT
* ---------------------------------------------------------------
*/
Services::autoloader()->initializeKint(CI_DEBUG);
exit(1);
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Model.php | system/Model.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use Closure;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Exceptions\DataException;
use CodeIgniter\Database\Query;
use CodeIgniter\Entity\Entity;
use CodeIgniter\Exceptions\BadMethodCallException;
use CodeIgniter\Exceptions\ModelException;
use CodeIgniter\Validation\ValidationInterface;
use Config\Database;
use Config\Feature;
use ReflectionException;
use stdClass;
/**
* The Model class extends BaseModel and provides additional
* convenient features that makes working with a SQL database
* table less painful.
*
* It will:
* - automatically connect to database
* - allow intermingling calls to the builder
* - removes the need to use Result object directly in most cases
*
* @property-read BaseConnection $db
*
* @method $this groupBy($by, ?bool $escape = null)
* @method $this groupEnd()
* @method $this groupStart()
* @method $this having($key, $value = null, ?bool $escape = null)
* @method $this havingGroupEnd()
* @method $this havingGroupStart()
* @method $this havingIn(?string $key = null, $values = null, ?bool $escape = null)
* @method $this havingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
* @method $this havingNotIn(?string $key = null, $values = null, ?bool $escape = null)
* @method $this join(string $table, string $cond, string $type = '', ?bool $escape = null)
* @method $this like($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
* @method $this limit(?int $value = null, ?int $offset = 0)
* @method $this notGroupStart()
* @method $this notHavingGroupStart()
* @method $this notHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
* @method $this notLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
* @method $this offset(int $offset)
* @method $this orderBy(string $orderBy, string $direction = '', ?bool $escape = null)
* @method $this orGroupStart()
* @method $this orHaving($key, $value = null, ?bool $escape = null)
* @method $this orHavingGroupStart()
* @method $this orHavingIn(?string $key = null, $values = null, ?bool $escape = null)
* @method $this orHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
* @method $this orHavingNotIn(?string $key = null, $values = null, ?bool $escape = null)
* @method $this orLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
* @method $this orNotGroupStart()
* @method $this orNotHavingGroupStart()
* @method $this orNotHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
* @method $this orNotLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
* @method $this orWhere($key, $value = null, ?bool $escape = null)
* @method $this orWhereIn(?string $key = null, $values = null, ?bool $escape = null)
* @method $this orWhereNotIn(?string $key = null, $values = null, ?bool $escape = null)
* @method $this select($select = '*', ?bool $escape = null)
* @method $this selectAvg(string $select = '', string $alias = '')
* @method $this selectCount(string $select = '', string $alias = '')
* @method $this selectMax(string $select = '', string $alias = '')
* @method $this selectMin(string $select = '', string $alias = '')
* @method $this selectSum(string $select = '', string $alias = '')
* @method $this when($condition, callable $callback, ?callable $defaultCallback = null)
* @method $this whenNot($condition, callable $callback, ?callable $defaultCallback = null)
* @method $this where($key, $value = null, ?bool $escape = null)
* @method $this whereIn(?string $key = null, $values = null, ?bool $escape = null)
* @method $this whereNotIn(?string $key = null, $values = null, ?bool $escape = null)
*
* @phpstan-import-type row_array from BaseModel
*/
class Model extends BaseModel
{
/**
* Name of database table
*
* @var string
*/
protected $table;
/**
* The table's primary key.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
/**
* Query Builder object
*
* @var BaseBuilder|null
*/
protected $builder;
/**
* Holds information passed in via 'set'
* so that we can capture it (not the builder)
* and ensure it gets validated first.
*
* @var array{escape: array, data: array}|array{}
* @phpstan-var array{escape: array<int|string, bool|null>, data: row_array}|array{}
*/
protected $tempData = [];
/**
* Escape array that maps usage of escape
* flag for every parameter.
*
* @var array
*/
protected $escape = [];
/**
* Builder method names that should not be used in the Model.
*
* @var list<string> method name
*/
private array $builderMethodsNotAvailable = [
'getCompiledInsert',
'getCompiledSelect',
'getCompiledUpdate',
];
public function __construct(?ConnectionInterface $db = null, ?ValidationInterface $validation = null)
{
/**
* @var BaseConnection|null $db
*/
$db ??= Database::connect($this->DBGroup);
$this->db = $db;
parent::__construct($validation);
}
/**
* Specify the table associated with a model
*
* @param string $table Table
*
* @return $this
*/
public function setTable(string $table)
{
$this->table = $table;
return $this;
}
/**
* Fetches the row(s) of database from $this->table with a primary key
* matching $id.
* This method works only with dbCalls.
*
* @param bool $singleton Single or multiple results
* @param array|int|string|null $id One primary key or an array of primary keys
*
* @return array|object|null The resulting row of data, or null.
* @phpstan-return ($singleton is true ? row_array|null|object : list<row_array|object>)
*/
protected function doFind(bool $singleton, $id = null)
{
$builder = $this->builder();
$useCast = $this->useCasts();
if ($useCast) {
$returnType = $this->tempReturnType;
$this->asArray();
}
if ($this->tempUseSoftDeletes) {
$builder->where($this->table . '.' . $this->deletedField, null);
}
$row = null;
$rows = [];
if (is_array($id)) {
$rows = $builder->whereIn($this->table . '.' . $this->primaryKey, $id)
->get()
->getResult($this->tempReturnType);
} elseif ($singleton) {
$row = $builder->where($this->table . '.' . $this->primaryKey, $id)
->get()
->getFirstRow($this->tempReturnType);
} else {
$rows = $builder->get()->getResult($this->tempReturnType);
}
if ($useCast) {
$this->tempReturnType = $returnType;
if ($singleton) {
if ($row === null) {
return null;
}
return $this->convertToReturnType($row, $returnType);
}
foreach ($rows as $i => $row) {
$rows[$i] = $this->convertToReturnType($row, $returnType);
}
return $rows;
}
if ($singleton) {
return $row;
}
return $rows;
}
/**
* Fetches the column of database from $this->table.
* This method works only with dbCalls.
*
* @param string $columnName Column Name
*
* @return array|null The resulting row of data, or null if no data found.
* @phpstan-return list<row_array>|null
*/
protected function doFindColumn(string $columnName)
{
return $this->select($columnName)->asArray()->find();
}
/**
* Works with the current Query Builder instance to return
* all results, while optionally limiting them.
* This method works only with dbCalls.
*
* @param int|null $limit Limit
* @param int $offset Offset
*
* @return array
* @phpstan-return list<row_array|object>
*/
protected function doFindAll(?int $limit = null, int $offset = 0)
{
$limitZeroAsAll = config(Feature::class)->limitZeroAsAll ?? true;
if ($limitZeroAsAll) {
$limit ??= 0;
}
$builder = $this->builder();
$useCast = $this->useCasts();
if ($useCast) {
$returnType = $this->tempReturnType;
$this->asArray();
}
if ($this->tempUseSoftDeletes) {
$builder->where($this->table . '.' . $this->deletedField, null);
}
$results = $builder->limit($limit, $offset)
->get()
->getResult($this->tempReturnType);
if ($useCast) {
foreach ($results as $i => $row) {
$results[$i] = $this->convertToReturnType($row, $returnType);
}
$this->tempReturnType = $returnType;
}
return $results;
}
/**
* Returns the first row of the result set. Will take any previous
* Query Builder calls into account when determining the result set.
* This method works only with dbCalls.
*
* @return array|object|null
* @phpstan-return row_array|object|null
*/
protected function doFirst()
{
$builder = $this->builder();
$useCast = $this->useCasts();
if ($useCast) {
$returnType = $this->tempReturnType;
$this->asArray();
}
if ($this->tempUseSoftDeletes) {
$builder->where($this->table . '.' . $this->deletedField, null);
} elseif ($this->useSoftDeletes && ($builder->QBGroupBy === []) && $this->primaryKey !== '') {
$builder->groupBy($this->table . '.' . $this->primaryKey);
}
// Some databases, like PostgreSQL, need order
// information to consistently return correct results.
if ($builder->QBGroupBy !== [] && ($builder->QBOrderBy === []) && $this->primaryKey !== '') {
$builder->orderBy($this->table . '.' . $this->primaryKey, 'asc');
}
$row = $builder->limit(1, 0)->get()->getFirstRow($this->tempReturnType);
if ($useCast && $row !== null) {
$row = $this->convertToReturnType($row, $returnType);
$this->tempReturnType = $returnType;
}
return $row;
}
/**
* Inserts data into the current table.
* This method works only with dbCalls.
*
* @param array $row Row data
* @phpstan-param row_array $row
*
* @return bool
*/
protected function doInsert(array $row)
{
$escape = $this->escape;
$this->escape = [];
// Require non-empty primaryKey when
// not using auto-increment feature
if (! $this->useAutoIncrement && ! isset($row[$this->primaryKey])) {
throw DataException::forEmptyPrimaryKey('insert');
}
$builder = $this->builder();
// Must use the set() method to ensure to set the correct escape flag
foreach ($row as $key => $val) {
$builder->set($key, $val, $escape[$key] ?? null);
}
if ($this->allowEmptyInserts && $row === []) {
$table = $this->db->protectIdentifiers($this->table, true, null, false);
if ($this->db->getPlatform() === 'MySQLi') {
$sql = 'INSERT INTO ' . $table . ' VALUES ()';
} elseif ($this->db->getPlatform() === 'OCI8') {
$allFields = $this->db->protectIdentifiers(
array_map(
static fn ($row) => $row->name,
$this->db->getFieldData($this->table),
),
false,
true,
);
$sql = sprintf(
'INSERT INTO %s (%s) VALUES (%s)',
$table,
implode(',', $allFields),
substr(str_repeat(',DEFAULT', count($allFields)), 1),
);
} else {
$sql = 'INSERT INTO ' . $table . ' DEFAULT VALUES';
}
$result = $this->db->query($sql);
} else {
$result = $builder->insert();
}
// If insertion succeeded then save the insert ID
if ($result) {
$this->insertID = ! $this->useAutoIncrement ? $row[$this->primaryKey] : $this->db->insertID();
}
return $result;
}
/**
* Compiles batch insert strings and runs the queries, validating each row prior.
* This method works only with dbCalls.
*
* @param array|null $set An associative array of insert values
* @param bool|null $escape Whether to escape values
* @param int $batchSize The size of the batch to run
* @param bool $testing True means only number of records is returned, false will execute the query
*
* @return bool|int Number of rows inserted or FALSE on failure
*/
protected function doInsertBatch(?array $set = null, ?bool $escape = null, int $batchSize = 100, bool $testing = false)
{
if (is_array($set)) {
foreach ($set as $row) {
// Require non-empty primaryKey when
// not using auto-increment feature
if (! $this->useAutoIncrement && ! isset($row[$this->primaryKey])) {
throw DataException::forEmptyPrimaryKey('insertBatch');
}
}
}
return $this->builder()->testMode($testing)->insertBatch($set, $escape, $batchSize);
}
/**
* Updates a single record in $this->table.
* This method works only with dbCalls.
*
* @param array|int|string|null $id
* @param array|null $row Row data
* @phpstan-param row_array|null $row
*/
protected function doUpdate($id = null, $row = null): bool
{
$escape = $this->escape;
$this->escape = [];
$builder = $this->builder();
if (! in_array($id, [null, '', 0, '0', []], true)) {
$builder = $builder->whereIn($this->table . '.' . $this->primaryKey, $id);
}
// Must use the set() method to ensure to set the correct escape flag
foreach ($row as $key => $val) {
$builder->set($key, $val, $escape[$key] ?? null);
}
if ($builder->getCompiledQBWhere() === []) {
throw new DatabaseException(
'Updates are not allowed unless they contain a "where" or "like" clause.',
);
}
return $builder->update();
}
/**
* Compiles an update string and runs the query
* This method works only with dbCalls.
*
* @param array|null $set An associative array of update values
* @param string|null $index The where key
* @param int $batchSize The size of the batch to run
* @param bool $returnSQL True means SQL is returned, false will execute the query
*
* @return false|int|list<string> Number of rows affected or FALSE on failure, SQL array when testMode
*
* @throws DatabaseException
*/
protected function doUpdateBatch(?array $set = null, ?string $index = null, int $batchSize = 100, bool $returnSQL = false)
{
return $this->builder()->testMode($returnSQL)->updateBatch($set, $index, $batchSize);
}
/**
* Deletes a single record from $this->table where $id matches
* the table's primaryKey
* This method works only with dbCalls.
*
* @param array|int|string|null $id The rows primary key(s)
* @param bool $purge Allows overriding the soft deletes setting.
*
* @return bool|string SQL string when testMode
*
* @throws DatabaseException
*/
protected function doDelete($id = null, bool $purge = false)
{
$set = [];
$builder = $this->builder();
if (! in_array($id, [null, '', 0, '0', []], true)) {
$builder = $builder->whereIn($this->primaryKey, $id);
}
if ($this->useSoftDeletes && ! $purge) {
if ($builder->getCompiledQBWhere() === []) {
throw new DatabaseException(
'Deletes are not allowed unless they contain a "where" or "like" clause.',
);
}
$builder->where($this->deletedField);
$set[$this->deletedField] = $this->setDate();
if ($this->useTimestamps && $this->updatedField !== '') {
$set[$this->updatedField] = $this->setDate();
}
return $builder->update($set);
}
return $builder->delete();
}
/**
* Permanently deletes all rows that have been marked as deleted
* through soft deletes (deleted = 1)
* This method works only with dbCalls.
*
* @return bool|string Returns a SQL string if in test mode.
*/
protected function doPurgeDeleted()
{
return $this->builder()
->where($this->table . '.' . $this->deletedField . ' IS NOT NULL')
->delete();
}
/**
* Works with the find* methods to return only the rows that
* have been deleted.
* This method works only with dbCalls.
*
* @return void
*/
protected function doOnlyDeleted()
{
$this->builder()->where($this->table . '.' . $this->deletedField . ' IS NOT NULL');
}
/**
* Compiles a replace into string and runs the query
* This method works only with dbCalls.
*
* @param row_array|null $row Data
* @param bool $returnSQL Set to true to return Query String
*
* @return BaseResult|false|Query|string
*/
protected function doReplace(?array $row = null, bool $returnSQL = false)
{
return $this->builder()->testMode($returnSQL)->replace($row);
}
/**
* Grabs the last error(s) that occurred from the Database connection.
* The return array should be in the following format:
* ['source' => 'message']
* This method works only with dbCalls.
*
* @return array<string, string>
*/
protected function doErrors()
{
// $error is always ['code' => string|int, 'message' => string]
$error = $this->db->error();
if ((int) $error['code'] === 0) {
return [];
}
return [$this->db::class => $error['message']];
}
/**
* Returns the id value for the data array or object
*
* @param array|object $row Row data
* @phpstan-param row_array|object $row
*
* @return array|int|string|null
*/
public function getIdValue($row)
{
if (is_object($row)) {
// Get the raw or mapped primary key value of the Entity.
if ($row instanceof Entity && $row->{$this->primaryKey} !== null) {
$cast = $row->cast();
// Disable Entity casting, because raw primary key value is needed for database.
$row->cast(false);
$primaryKey = $row->{$this->primaryKey};
// Restore Entity casting setting.
$row->cast($cast);
return $primaryKey;
}
if (! $row instanceof Entity && isset($row->{$this->primaryKey})) {
return $row->{$this->primaryKey};
}
}
if (is_array($row) && isset($row[$this->primaryKey])) {
return $row[$this->primaryKey];
}
return null;
}
/**
* Loops over records in batches, allowing you to operate on them.
* Works with $this->builder to get the Compiled select to
* determine the rows to operate on.
* This method works only with dbCalls.
*/
public function chunk(int $size, Closure $userFunc)
{
$total = $this->builder()->countAllResults(false);
$offset = 0;
while ($offset <= $total) {
$builder = clone $this->builder();
$rows = $builder->get($size, $offset);
if (! $rows) {
throw DataException::forEmptyDataset('chunk');
}
$rows = $rows->getResult($this->tempReturnType);
$offset += $size;
if ($rows === []) {
continue;
}
foreach ($rows as $row) {
if ($userFunc($row) === false) {
return;
}
}
}
}
/**
* Override countAllResults to account for soft deleted accounts.
*
* @return int|string
*/
public function countAllResults(bool $reset = true, bool $test = false)
{
if ($this->tempUseSoftDeletes) {
$this->builder()->where($this->table . '.' . $this->deletedField, null);
}
// When $reset === false, the $tempUseSoftDeletes will be
// dependent on $useSoftDeletes value because we don't
// want to add the same "where" condition for the second time
$this->tempUseSoftDeletes = $reset
? $this->useSoftDeletes
: ($this->useSoftDeletes ? false : $this->useSoftDeletes);
return $this->builder()->testMode($test)->countAllResults($reset);
}
/**
* Provides a shared instance of the Query Builder.
*
* @param non-empty-string|null $table
*
* @return BaseBuilder
*
* @throws ModelException
*/
public function builder(?string $table = null)
{
// Check for an existing Builder
if ($this->builder instanceof BaseBuilder) {
// Make sure the requested table matches the builder
if ((string) $table !== '' && $this->builder->getTable() !== $table) {
return $this->db->table($table);
}
return $this->builder;
}
// We're going to force a primary key to exist
// so we don't have overly convoluted code,
// and future features are likely to require them.
if ($this->primaryKey === '') {
throw ModelException::forNoPrimaryKey(static::class);
}
$table = ((string) $table === '') ? $this->table : $table;
// Ensure we have a good db connection
if (! $this->db instanceof BaseConnection) {
$this->db = Database::connect($this->DBGroup);
}
$builder = $this->db->table($table);
// Only consider it "shared" if the table is correct
if ($table === $this->table) {
$this->builder = $builder;
}
return $builder;
}
/**
* Captures the builder's set() method so that we can validate the
* data here. This allows it to be used with any of the other
* builder methods and still get validated data, like replace.
*
* @param array|object|string $key Field name, or an array of field/value pairs, or an object
* @param bool|float|int|object|string|null $value Field value, if $key is a single field
* @param bool|null $escape Whether to escape values
*
* @return $this
*/
public function set($key, $value = '', ?bool $escape = null)
{
if (is_object($key)) {
$key = $key instanceof stdClass ? (array) $key : $this->objectToArray($key);
}
$data = is_array($key) ? $key : [$key => $value];
foreach (array_keys($data) as $k) {
$this->tempData['escape'][$k] = $escape;
}
$this->tempData['data'] = array_merge($this->tempData['data'] ?? [], $data);
return $this;
}
/**
* This method is called on save to determine if entry have to be updated
* If this method return false insert operation will be executed
*
* @param array|object $row Data
*/
protected function shouldUpdate($row): bool
{
if (parent::shouldUpdate($row) === false) {
return false;
}
if ($this->useAutoIncrement === true) {
return true;
}
// When useAutoIncrement feature is disabled, check
// in the database if given record already exists
return $this->where($this->primaryKey, $this->getIdValue($row))->countAllResults() === 1;
}
/**
* Inserts data into the database. If an object is provided,
* it will attempt to convert it to an array.
*
* @param object|row_array|null $row
* @param bool $returnID Whether insert ID should be returned or not.
*
* @return ($returnID is true ? false|int|string : bool)
*
* @throws ReflectionException
*/
public function insert($row = null, bool $returnID = true)
{
if (isset($this->tempData['data'])) {
if ($row === null) {
$row = $this->tempData['data'];
} else {
$row = $this->transformDataToArray($row, 'insert');
$row = array_merge($this->tempData['data'], $row);
}
}
$this->escape = $this->tempData['escape'] ?? [];
$this->tempData = [];
return parent::insert($row, $returnID);
}
/**
* Ensures that only the fields that are allowed to be inserted are in
* the data array.
*
* @used-by insert() to protect against mass assignment vulnerabilities.
* @used-by insertBatch() to protect against mass assignment vulnerabilities.
*
* @param array $row Row data
* @phpstan-param row_array $row
*
* @throws DataException
*/
protected function doProtectFieldsForInsert(array $row): array
{
if (! $this->protectFields) {
return $row;
}
if ($this->allowedFields === []) {
throw DataException::forInvalidAllowedFields(static::class);
}
foreach (array_keys($row) as $key) {
// Do not remove the non-auto-incrementing primary key data.
if ($this->useAutoIncrement === false && $key === $this->primaryKey) {
continue;
}
if (! in_array($key, $this->allowedFields, true)) {
unset($row[$key]);
}
}
return $row;
}
/**
* Updates a single record in the database. If an object is provided,
* it will attempt to convert it into an array.
*
* @param array|int|string|null $id
* @param array|object|null $row
* @phpstan-param row_array|object|null $row
*
* @throws ReflectionException
*/
public function update($id = null, $row = null): bool
{
if (isset($this->tempData['data'])) {
if ($row === null) {
$row = $this->tempData['data'];
} else {
$row = $this->transformDataToArray($row, 'update');
$row = array_merge($this->tempData['data'], $row);
}
}
$this->escape = $this->tempData['escape'] ?? [];
$this->tempData = [];
return parent::update($id, $row);
}
/**
* Takes a class and returns an array of its public and protected
* properties as an array with raw values.
*
* @param object $object Object
* @param bool $recursive If true, inner entities will be cast as array as well
*
* @return array<string, mixed> Array with raw values.
*
* @throws ReflectionException
*/
protected function objectToRawArray($object, bool $onlyChanged = true, bool $recursive = false): array
{
return parent::objectToRawArray($object, $onlyChanged);
}
/**
* Provides/instantiates the builder/db connection and model's table/primary key names and return type.
*
* @param string $name Name
*
* @return array|BaseBuilder|bool|float|int|object|string|null
*/
public function __get(string $name)
{
if (parent::__isset($name)) {
return parent::__get($name);
}
return $this->builder()->{$name} ?? null;
}
/**
* Checks for the existence of properties across this model, builder, and db connection.
*
* @param string $name Name
*/
public function __isset(string $name): bool
{
if (parent::__isset($name)) {
return true;
}
return isset($this->builder()->{$name});
}
/**
* Provides direct access to method in the builder (if available)
* and the database connection.
*
* @return $this|array|BaseBuilder|bool|float|int|object|string|null
*/
public function __call(string $name, array $params)
{
$builder = $this->builder();
$result = null;
if (method_exists($this->db, $name)) {
$result = $this->db->{$name}(...$params);
} elseif (method_exists($builder, $name)) {
$this->checkBuilderMethod($name);
$result = $builder->{$name}(...$params);
} else {
throw new BadMethodCallException('Call to undefined method ' . static::class . '::' . $name);
}
if ($result instanceof BaseBuilder) {
return $this;
}
return $result;
}
/**
* Checks the Builder method name that should not be used in the Model.
*/
private function checkBuilderMethod(string $name): void
{
if (in_array($name, $this->builderMethodsNotAvailable, true)) {
throw ModelException::forMethodNotAvailable(static::class, $name . '()');
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Boot.php | system/Boot.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use CodeIgniter\Cache\FactoriesCache;
use CodeIgniter\CLI\Console;
use CodeIgniter\Config\DotEnv;
use Config\App;
use Config\Autoload;
use Config\Modules;
use Config\Optimize;
use Config\Paths;
use Config\Services;
/**
* Bootstrap for the application
*
* @codeCoverageIgnore
*/
class Boot
{
/**
* Used by `public/index.php`
*
* Context
* web: Invoked by HTTP request
* php-cli: Invoked by CLI via `php public/index.php`
*
* @return int Exit code.
*/
public static function bootWeb(Paths $paths): int
{
static::definePathConstants($paths);
if (! defined('APP_NAMESPACE')) {
static::loadConstants();
}
static::checkMissingExtensions();
static::loadDotEnv($paths);
static::defineEnvironment();
static::loadEnvironmentBootstrap($paths);
static::loadCommonFunctions();
static::loadAutoloader();
static::setExceptionHandler();
static::initializeKint();
$configCacheEnabled = class_exists(Optimize::class)
&& (new Optimize())->configCacheEnabled;
if ($configCacheEnabled) {
$factoriesCache = static::loadConfigCache();
}
static::autoloadHelpers();
$app = static::initializeCodeIgniter();
static::runCodeIgniter($app);
if ($configCacheEnabled) {
static::saveConfigCache($factoriesCache);
}
// Exits the application, setting the exit code for CLI-based
// applications that might be watching.
return EXIT_SUCCESS;
}
/**
* Used by command line scripts other than
* * `spark`
* * `php-cli`
* * `phpunit`
*
* @used-by `system/util_bootstrap.php`
*/
public static function bootConsole(Paths $paths): void
{
static::definePathConstants($paths);
static::loadConstants();
static::checkMissingExtensions();
static::loadDotEnv($paths);
static::loadEnvironmentBootstrap($paths);
static::loadCommonFunctions();
static::loadAutoloader();
static::setExceptionHandler();
static::initializeKint();
static::autoloadHelpers();
// We need to force the request to be a CLIRequest since we're in console
Services::createRequest(new App(), true);
service('routes')->loadRoutes();
}
/**
* Used by `spark`
*
* @return int Exit code.
*/
public static function bootSpark(Paths $paths): int
{
static::definePathConstants($paths);
if (! defined('APP_NAMESPACE')) {
static::loadConstants();
}
static::checkMissingExtensions();
static::loadDotEnv($paths);
static::defineEnvironment();
static::loadEnvironmentBootstrap($paths);
static::loadCommonFunctions();
static::loadAutoloader();
static::setExceptionHandler();
static::initializeKint();
static::autoloadHelpers();
static::initializeCodeIgniter();
$console = static::initializeConsole();
return static::runCommand($console);
}
/**
* Used by `system/Test/bootstrap.php`
*/
public static function bootTest(Paths $paths): void
{
static::loadConstants();
static::checkMissingExtensions();
static::loadDotEnv($paths);
static::loadEnvironmentBootstrap($paths, false);
static::loadCommonFunctions();
static::loadAutoloader();
static::setExceptionHandler();
static::initializeKint();
static::autoloadHelpers();
}
/**
* Used by `preload.php`
*/
public static function preload(Paths $paths): void
{
static::definePathConstants($paths);
static::loadConstants();
static::defineEnvironment();
static::loadEnvironmentBootstrap($paths, false);
static::loadAutoloader();
}
/**
* Load environment settings from .env files into $_SERVER and $_ENV
*/
protected static function loadDotEnv(Paths $paths): void
{
require_once $paths->systemDirectory . '/Config/DotEnv.php';
(new DotEnv($paths->appDirectory . '/../'))->load();
}
protected static function defineEnvironment(): void
{
if (! defined('ENVIRONMENT')) {
// @phpstan-ignore-next-line
$env = $_ENV['CI_ENVIRONMENT'] ?? $_SERVER['CI_ENVIRONMENT']
?? getenv('CI_ENVIRONMENT')
?: 'production';
define('ENVIRONMENT', $env);
}
}
protected static function loadEnvironmentBootstrap(Paths $paths, bool $exit = true): void
{
if (is_file($paths->appDirectory . '/Config/Boot/' . ENVIRONMENT . '.php')) {
require_once $paths->appDirectory . '/Config/Boot/' . ENVIRONMENT . '.php';
return;
}
if ($exit) {
header('HTTP/1.1 503 Service Unavailable.', true, 503);
echo 'The application environment is not set correctly.';
exit(EXIT_ERROR);
}
}
/**
* The path constants provide convenient access to the folders throughout
* the application. We have to set them up here, so they are available in
* the config files that are loaded.
*/
protected static function definePathConstants(Paths $paths): void
{
// The path to the application directory.
if (! defined('APPPATH')) {
define('APPPATH', realpath(rtrim($paths->appDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
}
// The path to the project root directory. Just above APPPATH.
if (! defined('ROOTPATH')) {
define('ROOTPATH', realpath(APPPATH . '../') . DIRECTORY_SEPARATOR);
}
// The path to the system directory.
if (! defined('SYSTEMPATH')) {
define('SYSTEMPATH', realpath(rtrim($paths->systemDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
}
// The path to the writable directory.
if (! defined('WRITEPATH')) {
$writePath = realpath(rtrim($paths->writableDirectory, '\\/ '));
if ($writePath === false) {
header('HTTP/1.1 503 Service Unavailable.', true, 503);
echo 'The WRITEPATH is not set correctly.';
// EXIT_ERROR is not yet defined
exit(1);
}
define('WRITEPATH', $writePath . DIRECTORY_SEPARATOR);
}
// The path to the tests directory
if (! defined('TESTPATH')) {
define('TESTPATH', realpath(rtrim($paths->testsDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
}
}
protected static function loadConstants(): void
{
require_once APPPATH . 'Config/Constants.php';
}
protected static function loadCommonFunctions(): void
{
// Require app/Common.php file if exists.
if (is_file(APPPATH . 'Common.php')) {
require_once APPPATH . 'Common.php';
}
// Require system/Common.php
require_once SYSTEMPATH . 'Common.php';
}
/**
* The autoloader allows all the pieces to work together in the framework.
* We have to load it here, though, so that the config files can use the
* path constants.
*/
protected static function loadAutoloader(): void
{
if (! class_exists(Autoload::class, false)) {
require_once SYSTEMPATH . 'Config/AutoloadConfig.php';
require_once APPPATH . 'Config/Autoload.php';
require_once SYSTEMPATH . 'Modules/Modules.php';
require_once APPPATH . 'Config/Modules.php';
}
require_once SYSTEMPATH . 'Autoloader/Autoloader.php';
require_once SYSTEMPATH . 'Config/BaseService.php';
require_once SYSTEMPATH . 'Config/Services.php';
require_once APPPATH . 'Config/Services.php';
// Initialize and register the loader with the SPL autoloader stack.
Services::autoloader()->initialize(new Autoload(), new Modules())->register();
}
protected static function autoloadHelpers(): void
{
service('autoloader')->loadHelpers();
}
protected static function setExceptionHandler(): void
{
service('exceptions')->initialize();
}
protected static function checkMissingExtensions(): void
{
if (is_file(COMPOSER_PATH)) {
return;
}
// Run this check for manual installations
$missingExtensions = [];
foreach ([
'intl',
'json',
'mbstring',
] as $extension) {
if (! extension_loaded($extension)) {
$missingExtensions[] = $extension;
}
}
if ($missingExtensions === []) {
return;
}
$message = sprintf(
'The framework needs the following extension(s) installed and loaded: %s.',
implode(', ', $missingExtensions),
);
header('HTTP/1.1 503 Service Unavailable.', true, 503);
echo $message;
exit(EXIT_ERROR);
}
protected static function initializeKint(): void
{
service('autoloader')->initializeKint(CI_DEBUG);
}
protected static function loadConfigCache(): FactoriesCache
{
$factoriesCache = new FactoriesCache();
$factoriesCache->load('config');
return $factoriesCache;
}
/**
* The CodeIgniter class contains the core functionality to make
* the application run, and does all the dirty work to get
* the pieces all working together.
*/
protected static function initializeCodeIgniter(): CodeIgniter
{
$app = service('codeigniter');
$app->initialize();
$context = is_cli() ? 'php-cli' : 'web';
$app->setContext($context);
return $app;
}
/**
* Now that everything is set up, it's time to actually fire
* up the engines and make this app do its thang.
*/
protected static function runCodeIgniter(CodeIgniter $app): void
{
$app->run();
}
protected static function saveConfigCache(FactoriesCache $factoriesCache): void
{
$factoriesCache->save('config');
}
protected static function initializeConsole(): Console
{
$console = new Console();
// Show basic information before we do anything else.
if (is_int($suppress = array_search('--no-header', $_SERVER['argv'], true))) {
unset($_SERVER['argv'][$suppress]);
$suppress = true;
}
$console->showHeader($suppress);
return $console;
}
protected static function runCommand(Console $console): int
{
$exit = $console->run();
return is_int($exit) ? $exit : EXIT_SUCCESS;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Files/FileCollection.php | system/Files/FileCollection.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Files;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Files\Exceptions\FileException;
use CodeIgniter\Files\Exceptions\FileNotFoundException;
use Countable;
use Generator;
use IteratorAggregate;
/**
* File Collection Class
*
* Representation for a group of files, with utilities for locating,
* filtering, and ordering them.
*
* @template-implements IteratorAggregate<int, File>
* @see \CodeIgniter\Files\FileCollectionTest
*/
class FileCollection implements Countable, IteratorAggregate
{
/**
* The current list of file paths.
*
* @var list<string>
*/
protected $files = [];
// --------------------------------------------------------------------
// Support Methods
// --------------------------------------------------------------------
/**
* Resolves a full path and verifies it is an actual directory.
*
* @throws FileException
*/
final protected static function resolveDirectory(string $directory): string
{
if (! is_dir($directory = set_realpath($directory))) {
$caller = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1];
throw FileException::forExpectedDirectory($caller['function']);
}
return $directory;
}
/**
* Resolves a full path and verifies it is an actual file.
*
* @throws FileException
*/
final protected static function resolveFile(string $file): string
{
if (! is_file($file = set_realpath($file))) {
$caller = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1];
throw FileException::forExpectedFile($caller['function']);
}
return $file;
}
/**
* Removes files that are not part of the given directory (recursive).
*
* @param list<string> $files
*
* @return list<string>
*/
final protected static function filterFiles(array $files, string $directory): array
{
$directory = self::resolveDirectory($directory);
return array_filter($files, static fn (string $value): bool => str_starts_with($value, $directory));
}
/**
* Returns any files whose `basename` matches the given pattern.
*
* @param list<string> $files
* @param string $pattern Regex or pseudo-regex string
*
* @return list<string>
*/
final protected static function matchFiles(array $files, string $pattern): array
{
// Convert pseudo-regex into their true form
if (@preg_match($pattern, '') === false) {
$pattern = str_replace(
['#', '.', '*', '?'],
['\#', '\.', '.*', '.'],
$pattern,
);
$pattern = "#\\A{$pattern}\\z#";
}
return array_filter($files, static fn ($value): bool => (bool) preg_match($pattern, basename($value)));
}
// --------------------------------------------------------------------
// Class Core
// --------------------------------------------------------------------
/**
* Loads the Filesystem helper and adds any initial files.
*
* @param list<string> $files
*/
public function __construct(array $files = [])
{
helper(['filesystem']);
$this->add($files)->define();
}
/**
* Applies any initial inputs after the constructor.
* This method is a stub to be implemented by child classes.
*/
protected function define(): void
{
}
/**
* Optimizes and returns the current file list.
*
* @return list<string>
*/
public function get(): array
{
$this->files = array_unique($this->files);
sort($this->files, SORT_STRING);
return $this->files;
}
/**
* Sets the file list directly, files are still subject to verification.
* This works as a "reset" method with [].
*
* @param list<string> $files The new file list to use
*
* @return $this
*/
public function set(array $files)
{
$this->files = [];
return $this->addFiles($files);
}
/**
* Adds an array/single file or directory to the list.
*
* @param list<string>|string $paths
*
* @return $this
*/
public function add($paths, bool $recursive = true)
{
$paths = (array) $paths;
foreach ($paths as $path) {
if (! is_string($path)) {
throw new InvalidArgumentException('FileCollection paths must be strings.');
}
try {
// Test for a directory
self::resolveDirectory($path);
} catch (FileException) {
$this->addFile($path);
continue;
}
$this->addDirectory($path, $recursive);
}
return $this;
}
// --------------------------------------------------------------------
// File Handling
// --------------------------------------------------------------------
/**
* Verifies and adds files to the list.
*
* @param list<string> $files
*
* @return $this
*/
public function addFiles(array $files)
{
foreach ($files as $file) {
$this->addFile($file);
}
return $this;
}
/**
* Verifies and adds a single file to the file list.
*
* @return $this
*/
public function addFile(string $file)
{
$this->files[] = self::resolveFile($file);
return $this;
}
/**
* Removes files from the list.
*
* @param list<string> $files
*
* @return $this
*/
public function removeFiles(array $files)
{
$this->files = array_diff($this->files, $files);
return $this;
}
/**
* Removes a single file from the list.
*
* @return $this
*/
public function removeFile(string $file)
{
return $this->removeFiles([$file]);
}
// --------------------------------------------------------------------
// Directory Handling
// --------------------------------------------------------------------
/**
* Verifies and adds files from each
* directory to the list.
*
* @param list<string> $directories
*
* @return $this
*/
public function addDirectories(array $directories, bool $recursive = false)
{
foreach ($directories as $directory) {
$this->addDirectory($directory, $recursive);
}
return $this;
}
/**
* Verifies and adds all files from a directory.
*
* @return $this
*/
public function addDirectory(string $directory, bool $recursive = false)
{
$directory = self::resolveDirectory($directory);
// Map the directory to depth 2 to so directories become arrays
foreach (directory_map($directory, 2, true) as $key => $path) {
if (is_string($path)) {
$this->addFile($directory . $path);
} elseif ($recursive && is_array($path)) {
$this->addDirectory($directory . $key, true);
}
}
return $this;
}
// --------------------------------------------------------------------
// Filtering
// --------------------------------------------------------------------
/**
* Removes any files from the list that match the supplied pattern
* (within the optional scope).
*
* @param string $pattern Regex or pseudo-regex string
* @param string|null $scope The directory to limit the scope
*
* @return $this
*/
public function removePattern(string $pattern, ?string $scope = null)
{
if ($pattern === '') {
return $this;
}
// Start with all files or those in scope
$files = $scope === null ? $this->files : self::filterFiles($this->files, $scope);
// Remove any files that match the pattern
return $this->removeFiles(self::matchFiles($files, $pattern));
}
/**
* Keeps only the files from the list that match
* (within the optional scope).
*
* @param string $pattern Regex or pseudo-regex string
* @param string|null $scope A directory to limit the scope
*
* @return $this
*/
public function retainPattern(string $pattern, ?string $scope = null)
{
if ($pattern === '') {
return $this;
}
// Start with all files or those in scope
$files = $scope === null ? $this->files : self::filterFiles($this->files, $scope);
// Matches the pattern within the scoped files and remove their inverse.
return $this->removeFiles(array_diff($files, self::matchFiles($files, $pattern)));
}
/**
* Keeps only the files from the list that match multiple patterns
* (within the optional scope).
*
* @param list<string> $patterns Array of regex or pseudo-regex strings
* @param string|null $scope A directory to limit the scope
*
* @return $this
*/
public function retainMultiplePatterns(array $patterns, ?string $scope = null)
{
if ($patterns === []) {
return $this;
}
if (count($patterns) === 1 && $patterns[0] === '') {
return $this;
}
// Start with all files or those in scope
$files = $scope === null ? $this->files : self::filterFiles($this->files, $scope);
// Add files to retain to array
$filesToRetain = [];
foreach ($patterns as $pattern) {
if ($pattern === '') {
continue;
}
// Matches the pattern within the scoped files
$filesToRetain = array_merge($filesToRetain, self::matchFiles($files, $pattern));
}
// Remove the inverse of files to retain
return $this->removeFiles(array_diff($files, $filesToRetain));
}
// --------------------------------------------------------------------
// Interface Methods
// --------------------------------------------------------------------
/**
* Returns the current number of files in the collection.
* Fulfills Countable.
*/
public function count(): int
{
return count($this->files);
}
/**
* Yields as an Iterator for the current files.
* Fulfills IteratorAggregate.
*
* @return Generator<File>
*
* @throws FileNotFoundException
*/
public function getIterator(): Generator
{
foreach ($this->get() as $file) {
yield new File($file, true);
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Files/File.php | system/Files/File.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Files;
use CodeIgniter\Files\Exceptions\FileException;
use CodeIgniter\Files\Exceptions\FileNotFoundException;
use CodeIgniter\I18n\Time;
use Config\Mimes;
use ReturnTypeWillChange;
use SplFileInfo;
/**
* Wrapper for PHP's built-in SplFileInfo, with goodies.
*
* @see \CodeIgniter\Files\FileTest
*/
class File extends SplFileInfo
{
/**
* The files size in bytes
*
* @var int
*/
protected $size;
/**
* @var string|null
*/
protected $originalMimeType;
/**
* Run our SplFileInfo constructor with an optional verification
* that the path is really a file.
*
* @throws FileNotFoundException
*/
public function __construct(string $path, bool $checkFile = false)
{
if ($checkFile && ! is_file($path)) {
throw FileNotFoundException::forFileNotFound($path);
}
parent::__construct($path);
}
/**
* Retrieve the file size.
*
* Implementations SHOULD return the value stored in the "size" key of
* the file in the $_FILES array if available, as PHP calculates this based
* on the actual size transmitted. A RuntimeException will be thrown if the file
* does not exist or an error occurs.
*
* @return false|int The file size in bytes, or false on failure
*/
#[ReturnTypeWillChange]
public function getSize()
{
return $this->size ?? ($this->size = parent::getSize());
}
/**
* Retrieve the file size by unit, calculated in IEC standards with 1024 as base value.
*
* @param positive-int $precision
*/
public function getSizeByBinaryUnit(FileSizeUnit $unit = FileSizeUnit::B, int $precision = 3): int|string
{
return $this->getSizeByUnitInternal(1024, $unit, $precision);
}
/**
* Retrieve the file size by unit, calculated in metric standards with 1000 as base value.
*
* @param positive-int $precision
*/
public function getSizeByMetricUnit(FileSizeUnit $unit = FileSizeUnit::B, int $precision = 3): int|string
{
return $this->getSizeByUnitInternal(1000, $unit, $precision);
}
/**
* Retrieve the file size by unit.
*
* @deprecated 4.6.0 Use getSizeByBinaryUnit() or getSizeByMetricUnit() instead
*
* @return false|int|string
*/
public function getSizeByUnit(string $unit = 'b')
{
return match (strtolower($unit)) {
'kb' => $this->getSizeByBinaryUnit(FileSizeUnit::KB),
'mb' => $this->getSizeByBinaryUnit(FileSizeUnit::MB),
default => $this->getSize(),
};
}
/**
* Attempts to determine the file extension based on the trusted
* getType() method. If the mime type is unknown, will return null.
*/
public function guessExtension(): ?string
{
// naively get the path extension using pathinfo
$pathinfo = pathinfo($this->getRealPath() ?: $this->__toString()) + ['extension' => ''];
$proposedExtension = $pathinfo['extension'];
return Mimes::guessExtensionFromType($this->getMimeType(), $proposedExtension);
}
/**
* Retrieve the media type of the file. SHOULD not use information from
* the $_FILES array, but should use other methods to more accurately
* determine the type of file, like finfo, or mime_content_type().
*
* @return string The media type we determined it to be.
*/
public function getMimeType(): string
{
if (! function_exists('finfo_open')) {
return $this->originalMimeType ?? 'application/octet-stream'; // @codeCoverageIgnore
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $this->getRealPath() ?: $this->__toString());
finfo_close($finfo);
return $mimeType;
}
/**
* Generates a random names based on a simple hash and the time, with
* the correct file extension attached.
*/
public function getRandomName(): string
{
$extension = $this->getExtension();
$extension = empty($extension) ? '' : '.' . $extension;
return Time::now()->getTimestamp() . '_' . bin2hex(random_bytes(10)) . $extension;
}
/**
* Moves a file to a new location.
*
* @return File
*/
public function move(string $targetPath, ?string $name = null, bool $overwrite = false)
{
$targetPath = rtrim($targetPath, '/') . '/';
$name ??= $this->getBasename();
$destination = $overwrite ? $targetPath . $name : $this->getDestination($targetPath . $name);
$oldName = $this->getRealPath() ?: $this->__toString();
if (! @rename($oldName, $destination)) {
$error = error_get_last();
throw FileException::forUnableToMove($this->getBasename(), $targetPath, strip_tags($error['message']));
}
@chmod($destination, 0777 & ~umask());
return new self($destination);
}
/**
* Returns the destination path for the move operation where overwriting is not expected.
*
* First, it checks whether the delimiter is present in the filename, if it is, then it checks whether the
* last element is an integer as there may be cases that the delimiter may be present in the filename.
* For the all other cases, it appends an integer starting from zero before the file's extension.
*/
public function getDestination(string $destination, string $delimiter = '_', int $i = 0): string
{
if ($delimiter === '') {
$delimiter = '_';
}
while (is_file($destination)) {
$info = pathinfo($destination);
$extension = isset($info['extension']) ? '.' . $info['extension'] : '';
if (str_contains($info['filename'], $delimiter)) {
$parts = explode($delimiter, $info['filename']);
if (is_numeric(end($parts))) {
$i = end($parts);
array_pop($parts);
$parts[] = ++$i;
$destination = $info['dirname'] . DIRECTORY_SEPARATOR . implode($delimiter, $parts) . $extension;
} else {
$destination = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . $delimiter . ++$i . $extension;
}
} else {
$destination = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . $delimiter . ++$i . $extension;
}
}
return $destination;
}
private function getSizeByUnitInternal(int $fileSizeBase, FileSizeUnit $unit, int $precision): int|string
{
$exponent = $unit->value;
$divider = $fileSizeBase ** $exponent;
$size = $this->getSize() / $divider;
if ($unit !== FileSizeUnit::B) {
$size = number_format($size, $precision);
}
return $size;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Files/FileSizeUnit.php | system/Files/FileSizeUnit.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Files;
use CodeIgniter\Exceptions\InvalidArgumentException;
enum FileSizeUnit: int
{
case B = 0;
case KB = 1;
case MB = 2;
case GB = 3;
case TB = 4;
/**
* Allows the creation of a FileSizeUnit from Strings like "kb" or "mb"
*
* @throws InvalidArgumentException
*/
public static function fromString(string $unit): self
{
return match (strtolower($unit)) {
'b' => self::B,
'kb' => self::KB,
'mb' => self::MB,
'gb' => self::GB,
'tb' => self::TB,
default => throw new InvalidArgumentException("Invalid unit: {$unit}"),
};
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Files/Exceptions/FileException.php | system/Files/Exceptions/FileException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Files\Exceptions;
use CodeIgniter\Exceptions\DebugTraceableTrait;
use CodeIgniter\Exceptions\RuntimeException;
class FileException extends RuntimeException implements ExceptionInterface
{
use DebugTraceableTrait;
/**
* @return static
*/
public static function forUnableToMove(?string $from = null, ?string $to = null, ?string $error = null)
{
return new static(lang('Files.cannotMove', [$from, $to, $error]));
}
/**
* Throws when an item is expected to be a directory but is not or is missing.
*
* @param string $caller The method causing the exception
*
* @return static
*/
public static function forExpectedDirectory(string $caller)
{
return new static(lang('Files.expectedDirectory', [$caller]));
}
/**
* Throws when an item is expected to be a file but is not or is missing.
*
* @param string $caller The method causing the exception
*
* @return static
*/
public static function forExpectedFile(string $caller)
{
return new static(lang('Files.expectedFile', [$caller]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Files/Exceptions/FileNotFoundException.php | system/Files/Exceptions/FileNotFoundException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Files\Exceptions;
use CodeIgniter\Exceptions\DebugTraceableTrait;
use CodeIgniter\Exceptions\RuntimeException;
class FileNotFoundException extends RuntimeException implements ExceptionInterface
{
use DebugTraceableTrait;
/**
* @return static
*/
public static function forFileNotFound(string $path)
{
return new static(lang('Files.fileNotFound', [$path]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Files/Exceptions/ExceptionInterface.php | system/Files/Exceptions/ExceptionInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Files\Exceptions;
/**
* Provides a domain-level interface for broad capture
* of all Files-related exceptions.
*
* catch (\CodeIgniter\Files\Exceptions\ExceptionInterface) { ... }
*/
interface ExceptionInterface extends \CodeIgniter\Exceptions\ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Email/Email.php | system/Email/Email.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Email;
use CodeIgniter\Events\Events;
use CodeIgniter\I18n\Time;
use Config\Mimes;
use ErrorException;
/**
* CodeIgniter Email Class
*
* Permits email to be sent using Mail, Sendmail, or SMTP.
*
* @see \CodeIgniter\Email\EmailTest
*/
class Email
{
/**
* Properties from the last successful send.
*
* @var array|null
*/
public $archive;
/**
* Properties to be added to the next archive.
*
* @var array
*/
protected $tmpArchive = [];
/**
* @var string
*/
public $fromEmail;
/**
* @var string
*/
public $fromName;
/**
* Used as the User-Agent and X-Mailer headers' value.
*
* @var string
*/
public $userAgent = 'CodeIgniter';
/**
* Path to the Sendmail binary.
*
* @var string
*/
public $mailPath = '/usr/sbin/sendmail';
/**
* Which method to use for sending e-mails.
*
* @var 'mail'|'sendmail'|'smtp'
*/
public $protocol = 'mail';
/**
* STMP Server Hostname
*
* @var string
*/
public $SMTPHost = '';
/**
* SMTP Username
*
* @var string
*/
public $SMTPUser = '';
/**
* SMTP Password
*
* @var string
*/
public $SMTPPass = '';
/**
* SMTP Server port
*
* @var int
*/
public $SMTPPort = 25;
/**
* SMTP connection timeout in seconds
*
* @var int
*/
public $SMTPTimeout = 5;
/**
* SMTP persistent connection
*
* @var bool
*/
public $SMTPKeepAlive = false;
/**
* SMTP Encryption
*
* * `tls` - will issue a STARTTLS command to the server
* * `ssl` - means implicit SSL
* * `''` - for connection on port 465
*
* @var ''|'ssl'|'tls'
*/
public $SMTPCrypto = '';
/**
* Whether to apply word-wrapping to the message body.
*
* @var bool
*/
public $wordWrap = true;
/**
* Number of characters to wrap at.
*
* @see Email::$wordWrap
*
* @var int
*/
public $wrapChars = 76;
/**
* Message format.
*
* @var 'html'|'text'
*/
public $mailType = 'text';
/**
* Character set (default: utf-8)
*
* @var string
*/
public $charset = 'UTF-8';
/**
* Alternative message (for HTML messages only)
*
* @var string
*/
public $altMessage = '';
/**
* Whether to validate e-mail addresses.
*
* @var bool
*/
public $validate = true;
/**
* X-Priority header value.
*
* @var int<1, 5>
*/
public $priority = 3;
/**
* Newline character sequence.
* Use "\r\n" to comply with RFC 822.
*
* @see http://www.ietf.org/rfc/rfc822.txt
*
* @var "\r\n"|"n"
*/
public $newline = "\r\n";
/**
* CRLF character sequence
*
* RFC 2045 specifies that for 'quoted-printable' encoding,
* "\r\n" must be used. However, it appears that some servers
* (even on the receiving end) don't handle it properly and
* switching to "\n", while improper, is the only solution
* that seems to work for all environments.
*
* @see http://www.ietf.org/rfc/rfc822.txt
*
* @var "\r\n"|"n"
*/
public $CRLF = "\r\n";
/**
* Whether to use Delivery Status Notification.
*
* @var bool
*/
public $DSN = false;
/**
* Whether to send multipart alternatives.
* Yahoo! doesn't seem to like these.
*
* @var bool
*/
public $sendMultipart = true;
/**
* Whether to send messages to BCC recipients in batches.
*
* @var bool
*/
public $BCCBatchMode = false;
/**
* BCC Batch max number size.
*
* @see Email::$BCCBatchMode
*
* @var int|string
*/
public $BCCBatchSize = 200;
/**
* Subject header
*
* @var string
*/
protected $subject = '';
/**
* Message body
*
* @var string
*/
protected $body = '';
/**
* Final message body to be sent.
*
* @var string
*/
protected $finalBody = '';
/**
* Final headers to send
*
* @var string
*/
protected $headerStr = '';
/**
* SMTP Connection socket placeholder
*
* @var false|resource|null
*/
protected $SMTPConnect;
/**
* Mail encoding
*
* @var '7bit'|'8bit'
*/
protected $encoding = '8bit';
/**
* Whether to perform SMTP authentication
*
* @var bool
*/
protected $SMTPAuth = false;
/**
* Whether to send a Reply-To header
*
* @var bool
*/
protected $replyToFlag = false;
/**
* Debug messages
*
* @see Email::printDebugger()
*
* @var array
*/
protected $debugMessage = [];
/**
* Raw debug messages
*
* @var list<string>
*/
private array $debugMessageRaw = [];
/**
* Recipients
*
* @var array|string
*/
protected $recipients = [];
/**
* CC Recipients
*
* @var array
*/
protected $CCArray = [];
/**
* BCC Recipients
*
* @var array
*/
protected $BCCArray = [];
/**
* Message headers
*
* @var array
*/
protected $headers = [];
/**
* Attachment data
*
* @var array
*/
protected $attachments = [];
/**
* Valid $protocol values
*
* @see Email::$protocol
*
* @var list<string>
*/
protected $protocols = [
'mail',
'sendmail',
'smtp',
];
/**
* Character sets valid for 7-bit encoding,
* excluding language suffix.
*
* @var list<string>
*/
protected $baseCharsets = [
'us-ascii',
'iso-2022-',
];
/**
* Bit depths
*
* Valid mail encodings
*
* @see Email::$encoding
*
* @var list<string>
*/
protected $bitDepths = [
'7bit',
'8bit',
];
/**
* $priority translations
*
* Actual values to send with the X-Priority header
*
* @var array<int, string>
*/
protected $priorities = [
1 => '1 (Highest)',
2 => '2 (High)',
3 => '3 (Normal)',
4 => '4 (Low)',
5 => '5 (Lowest)',
];
/**
* mbstring.func_overload flag
*
* @var bool|null
*/
protected static $func_overload;
/**
* @param array|\Config\Email|null $config
*/
public function __construct($config = null)
{
$this->initialize($config);
if (! isset(static::$func_overload)) {
static::$func_overload = extension_loaded('mbstring') && ini_get('mbstring.func_overload');
}
}
/**
* Initialize preferences
*
* @param array|\Config\Email|null $config
*
* @return $this
*/
public function initialize($config)
{
$this->clear();
if ($config instanceof \Config\Email) {
$config = get_object_vars($config);
}
foreach (array_keys(get_class_vars(static::class)) as $key) {
if (property_exists($this, $key) && isset($config[$key])) {
$method = 'set' . ucfirst($key);
if (method_exists($this, $method)) {
$this->{$method}($config[$key]);
} else {
$this->{$key} = $config[$key];
}
}
}
$this->charset = strtoupper($this->charset);
$this->SMTPAuth = isset($this->SMTPUser[0], $this->SMTPPass[0]);
return $this;
}
/**
* @param bool $clearAttachments
*
* @return $this
*/
public function clear($clearAttachments = false)
{
$this->subject = '';
$this->body = '';
$this->finalBody = '';
$this->headerStr = '';
$this->replyToFlag = false;
$this->recipients = [];
$this->CCArray = [];
$this->BCCArray = [];
$this->headers = [];
$this->debugMessage = [];
$this->debugMessageRaw = [];
$this->setHeader('Date', $this->setDate());
if ($clearAttachments) {
$this->attachments = [];
}
return $this;
}
/**
* @param string $from
* @param string $name
* @param string|null $returnPath
*
* @return $this
*/
public function setFrom($from, $name = '', $returnPath = null)
{
if (preg_match('/\<(.*)\>/', $from, $match) === 1) {
$from = $match[1];
}
if ($this->validate) {
$this->validateEmail($this->stringToArray($from));
if ($returnPath !== null) {
$this->validateEmail($this->stringToArray($returnPath));
}
}
$this->tmpArchive['fromEmail'] = $from;
$this->tmpArchive['fromName'] = $name;
if ($name !== '') {
// only use Q encoding if there are characters that would require it
if (preg_match('/[\200-\377]/', $name) !== 1) {
$name = '"' . addcslashes($name, "\0..\37\177'\"\\") . '"';
} else {
$name = $this->prepQEncoding($name);
}
}
$this->setHeader('From', $name . ' <' . $from . '>');
$returnPath ??= $from;
$this->setHeader('Return-Path', '<' . $returnPath . '>');
$this->tmpArchive['returnPath'] = $returnPath;
return $this;
}
/**
* @param string $replyto
* @param string $name
*
* @return $this
*/
public function setReplyTo($replyto, $name = '')
{
if (preg_match('/\<(.*)\>/', $replyto, $match) === 1) {
$replyto = $match[1];
}
if ($this->validate) {
$this->validateEmail($this->stringToArray($replyto));
}
if ($name !== '') {
$this->tmpArchive['replyName'] = $name;
// only use Q encoding if there are characters that would require it
if (preg_match('/[\200-\377]/', $name) !== 1) {
$name = '"' . addcslashes($name, "\0..\37\177'\"\\") . '"';
} else {
$name = $this->prepQEncoding($name);
}
}
$this->setHeader('Reply-To', $name . ' <' . $replyto . '>');
$this->replyToFlag = true;
$this->tmpArchive['replyTo'] = $replyto;
return $this;
}
/**
* @param array|string $to
*
* @return $this
*/
public function setTo($to)
{
$to = $this->stringToArray($to);
$to = $this->cleanEmail($to);
if ($this->validate) {
$this->validateEmail($to);
}
if ($this->getProtocol() !== 'mail') {
$this->setHeader('To', implode(', ', $to));
}
$this->recipients = $to;
return $this;
}
/**
* @param string $cc
*
* @return $this
*/
public function setCC($cc)
{
$cc = $this->cleanEmail($this->stringToArray($cc));
if ($this->validate) {
$this->validateEmail($cc);
}
$this->setHeader('Cc', implode(', ', $cc));
if ($this->getProtocol() === 'smtp') {
$this->CCArray = $cc;
}
$this->tmpArchive['CCArray'] = $cc;
return $this;
}
/**
* @param string $bcc
* @param string $limit
*
* @return $this
*/
public function setBCC($bcc, $limit = '')
{
if ($limit !== '' && is_numeric($limit)) {
$this->BCCBatchMode = true;
$this->BCCBatchSize = $limit;
}
$bcc = $this->cleanEmail($this->stringToArray($bcc));
if ($this->validate) {
$this->validateEmail($bcc);
}
if ($this->getProtocol() === 'smtp' || ($this->BCCBatchMode && count($bcc) > $this->BCCBatchSize)) {
$this->BCCArray = $bcc;
} else {
$this->setHeader('Bcc', implode(', ', $bcc));
$this->tmpArchive['BCCArray'] = $bcc;
}
return $this;
}
/**
* @param string $subject
*
* @return $this
*/
public function setSubject($subject)
{
$this->tmpArchive['subject'] = $subject;
$subject = $this->prepQEncoding($subject);
$this->setHeader('Subject', $subject);
return $this;
}
/**
* @param string $body
*
* @return $this
*/
public function setMessage($body)
{
$this->body = rtrim(str_replace("\r", '', $body));
return $this;
}
/**
* @param string $file Can be local path, URL or buffered content
* @param string $disposition 'attachment'
* @param string|null $newname
* @param string $mime
*
* @return bool|Email
*/
public function attach($file, $disposition = '', $newname = null, $mime = '')
{
if ($mime === '') {
if (! str_contains($file, '://') && ! is_file($file)) {
$this->setErrorMessage(lang('Email.attachmentMissing', [$file]));
return false;
}
if (! $fp = @fopen($file, 'rb')) {
$this->setErrorMessage(lang('Email.attachmentUnreadable', [$file]));
return false;
}
$fileContent = stream_get_contents($fp);
$mime = $this->mimeTypes(pathinfo($file, PATHINFO_EXTENSION));
fclose($fp);
} else {
$fileContent = &$file; // buffered file
}
// declare names on their own, to make phpcbf happy
$namesAttached = [$file, $newname];
$this->attachments[] = [
'name' => $namesAttached,
'disposition' => empty($disposition) ? 'attachment' : $disposition,
// Can also be 'inline' Not sure if it matters
'type' => $mime,
'content' => chunk_split(base64_encode($fileContent)),
'multipart' => 'mixed',
];
return $this;
}
/**
* Set and return attachment Content-ID
* Useful for attached inline pictures
*
* @param string $filename
*
* @return bool|string
*/
public function setAttachmentCID($filename)
{
foreach ($this->attachments as $i => $attachment) {
// For file path.
if ($attachment['name'][0] === $filename) {
$this->attachments[$i]['multipart'] = 'related';
$this->attachments[$i]['cid'] = uniqid(basename($attachment['name'][0]) . '@', true);
return $this->attachments[$i]['cid'];
}
// For buffer string.
if ($attachment['name'][1] === $filename) {
$this->attachments[$i]['multipart'] = 'related';
$this->attachments[$i]['cid'] = uniqid(basename($attachment['name'][1]) . '@', true);
return $this->attachments[$i]['cid'];
}
}
return false;
}
/**
* @param string $header
* @param string $value
*
* @return $this
*/
public function setHeader($header, $value)
{
$this->headers[$header] = str_replace(["\n", "\r"], '', $value);
return $this;
}
/**
* @param list<string>|string $email
*
* @return list<string>
*/
protected function stringToArray($email)
{
if (! is_array($email)) {
return str_contains($email, ',')
? preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY)
: (array) trim($email);
}
return $email;
}
/**
* @param string $str
*
* @return $this
*/
public function setAltMessage($str)
{
$this->altMessage = (string) $str;
return $this;
}
/**
* @param string $type
*
* @return $this
*/
public function setMailType($type = 'text')
{
$this->mailType = $type === 'html' ? 'html' : 'text';
return $this;
}
/**
* @param bool $wordWrap
*
* @return $this
*/
public function setWordWrap($wordWrap = true)
{
$this->wordWrap = (bool) $wordWrap;
return $this;
}
/**
* @param string $protocol
*
* @return $this
*/
public function setProtocol($protocol = 'mail')
{
$this->protocol = in_array($protocol, $this->protocols, true) ? strtolower($protocol) : 'mail';
return $this;
}
/**
* @param int $n
*
* @return $this
*/
public function setPriority($n = 3)
{
$this->priority = preg_match('/^[1-5]$/', (string) $n) ? (int) $n : 3;
return $this;
}
/**
* @param string $newline
*
* @return $this
*/
public function setNewline($newline = "\n")
{
$this->newline = in_array($newline, ["\n", "\r\n", "\r"], true) ? $newline : "\n";
return $this;
}
/**
* @param string $CRLF
*
* @return $this
*/
public function setCRLF($CRLF = "\n")
{
$this->CRLF = ! in_array($CRLF, ["\n", "\r\n", "\r"], true) ? "\n" : $CRLF;
return $this;
}
/**
* @return string
*/
protected function getMessageID()
{
$from = str_replace(['>', '<'], '', $this->headers['Return-Path']);
return '<' . uniqid('', true) . strstr($from, '@') . '>';
}
/**
* @return string
*/
protected function getProtocol()
{
$this->protocol = strtolower($this->protocol);
if (! in_array($this->protocol, $this->protocols, true)) {
$this->protocol = 'mail';
}
return $this->protocol;
}
/**
* @return string
*/
protected function getEncoding()
{
if (! in_array($this->encoding, $this->bitDepths, true)) {
$this->encoding = '8bit';
}
foreach ($this->baseCharsets as $charset) {
if (str_starts_with($this->charset, $charset)) {
$this->encoding = '7bit';
break;
}
}
return $this->encoding;
}
/**
* @return string
*/
protected function getContentType()
{
if ($this->mailType === 'html') {
return $this->attachments === [] ? 'html' : 'html-attach';
}
if ($this->mailType === 'text' && $this->attachments !== []) {
return 'plain-attach';
}
return 'plain';
}
/**
* Set RFC 822 Date
*
* @return string
*/
protected function setDate()
{
$timezone = date('Z');
$operator = ($timezone[0] === '-') ? '-' : '+';
$timezone = abs((int) $timezone);
$timezone = floor($timezone / 3600) * 100 + ($timezone % 3600) / 60;
return sprintf('%s %s%04d', date('D, j M Y H:i:s'), $operator, $timezone);
}
/**
* @return string
*/
protected function getMimeMessage()
{
return 'This is a multi-part message in MIME format.' . $this->newline . 'Your email application may not support this format.';
}
/**
* @param array|string $email
*
* @return bool
*/
public function validateEmail($email)
{
if (! is_array($email)) {
$this->setErrorMessage(lang('Email.mustBeArray'));
return false;
}
foreach ($email as $val) {
if (! $this->isValidEmail($val)) {
$this->setErrorMessage(lang('Email.invalidAddress', [$val]));
return false;
}
}
return true;
}
/**
* @param string $email
*
* @return bool
*/
public function isValidEmail($email)
{
if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46') && $atpos = strpos($email, '@')) {
$email = static::substr($email, 0, ++$atpos)
. idn_to_ascii(static::substr($email, $atpos), 0, INTL_IDNA_VARIANT_UTS46);
}
return (bool) filter_var($email, FILTER_VALIDATE_EMAIL);
}
/**
* @param array|string $email
*
* @return array|string
*/
public function cleanEmail($email)
{
if (! is_array($email)) {
return preg_match('/\<(.*)\>/', $email, $match) ? $match[1] : $email;
}
$cleanEmail = [];
foreach ($email as $addy) {
$cleanEmail[] = preg_match('/\<(.*)\>/', $addy, $match) ? $match[1] : $addy;
}
return $cleanEmail;
}
/**
* Build alternative plain text message
*
* Provides the raw message for use in plain-text headers of
* HTML-formatted emails.
*
* If the user hasn't specified his own alternative message
* it creates one by stripping the HTML
*
* @return string
*/
protected function getAltMessage()
{
if ($this->altMessage !== '') {
return $this->wordWrap ? $this->wordWrap($this->altMessage, 76) : $this->altMessage;
}
$body = preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->body, $match) ? $match[1] : $this->body;
$body = str_replace("\t", '', preg_replace('#<!--(.*)--\>#', '', trim(strip_tags($body))));
for ($i = 20; $i >= 3; $i--) {
$body = str_replace(str_repeat("\n", $i), "\n\n", $body);
}
$body = preg_replace('| +|', ' ', $body);
return $this->wordWrap ? $this->wordWrap($body, 76) : $body;
}
/**
* @param string $str
* @param int|null $charlim Line-length limit
*
* @return string
*/
public function wordWrap($str, $charlim = null)
{
$charlim ??= 0;
if ($charlim === 0) {
$charlim = $this->wrapChars === 0 ? 76 : $this->wrapChars;
}
if (str_contains($str, "\r")) {
$str = str_replace(["\r\n", "\r"], "\n", $str);
}
$str = preg_replace('| +\n|', "\n", $str);
$unwrap = [];
if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches) >= 1) {
for ($i = 0, $c = count($matches[0]); $i < $c; $i++) {
$unwrap[] = $matches[1][$i];
$str = str_replace($matches[0][$i], '{{unwrapped' . $i . '}}', $str);
}
}
// Use PHP's native function to do the initial wordwrap.
// We set the cut flag to FALSE so that any individual words that are
// too long get left alone. In the next step we'll deal with them.
$str = wordwrap($str, $charlim, "\n", false);
// Split the string into individual lines of text and cycle through them
$output = '';
foreach (explode("\n", $str) as $line) {
if (static::strlen($line) <= $charlim) {
$output .= $line . $this->newline;
continue;
}
$temp = '';
do {
if (preg_match('!\[url.+\]|://|www\.!', $line)) {
break;
}
$temp .= static::substr($line, 0, $charlim - 1);
$line = static::substr($line, $charlim - 1);
} while (static::strlen($line) > $charlim);
if ($temp !== '') {
$output .= $temp . $this->newline;
}
$output .= $line . $this->newline;
}
foreach ($unwrap as $key => $val) {
$output = str_replace('{{unwrapped' . $key . '}}', $val, $output);
}
return $output;
}
/**
* Build final headers
*
* @return void
*/
protected function buildHeaders()
{
$this->setHeader('User-Agent', $this->userAgent);
$this->setHeader('X-Sender', $this->cleanEmail($this->headers['From']));
$this->setHeader('X-Mailer', $this->userAgent);
$this->setHeader('X-Priority', $this->priorities[$this->priority]);
$this->setHeader('Message-ID', $this->getMessageID());
$this->setHeader('Mime-Version', '1.0');
}
/**
* Write Headers as a string
*
* @return void
*/
protected function writeHeaders()
{
if ($this->protocol === 'mail' && isset($this->headers['Subject'])) {
$this->subject = $this->headers['Subject'];
unset($this->headers['Subject']);
}
reset($this->headers);
$this->headerStr = '';
foreach ($this->headers as $key => $val) {
$val = trim($val);
if ($val !== '') {
$this->headerStr .= $key . ': ' . $val . $this->newline;
}
}
if ($this->getProtocol() === 'mail') {
$this->headerStr = rtrim($this->headerStr);
}
}
/**
* Build Final Body and attachments
*
* @return void
*/
protected function buildMessage()
{
if ($this->wordWrap === true && $this->mailType !== 'html') {
$this->body = $this->wordWrap($this->body);
}
$this->writeHeaders();
$hdr = ($this->getProtocol() === 'mail') ? $this->newline : '';
$body = '';
switch ($this->getContentType()) {
case 'plain':
$hdr .= 'Content-Type: text/plain; charset='
. $this->charset
. $this->newline
. 'Content-Transfer-Encoding: '
. $this->getEncoding();
if ($this->getProtocol() === 'mail') {
$this->headerStr .= $hdr;
$this->finalBody = $this->body;
} else {
$this->finalBody = $hdr . $this->newline . $this->newline . $this->body;
}
return;
case 'html':
$boundary = uniqid('B_ALT_', true);
if ($this->sendMultipart === false) {
$hdr .= 'Content-Type: text/html; charset='
. $this->charset . $this->newline
. 'Content-Transfer-Encoding: quoted-printable';
} else {
$hdr .= 'Content-Type: multipart/alternative; boundary="' . $boundary . '"';
$body .= $this->getMimeMessage() . $this->newline . $this->newline
. '--' . $boundary . $this->newline
. 'Content-Type: text/plain; charset=' . $this->charset . $this->newline
. 'Content-Transfer-Encoding: ' . $this->getEncoding() . $this->newline . $this->newline
. $this->getAltMessage() . $this->newline . $this->newline
. '--' . $boundary . $this->newline
. 'Content-Type: text/html; charset=' . $this->charset . $this->newline
. 'Content-Transfer-Encoding: quoted-printable' . $this->newline . $this->newline;
}
$this->finalBody = $body . $this->prepQuotedPrintable($this->body) . $this->newline . $this->newline;
if ($this->getProtocol() === 'mail') {
$this->headerStr .= $hdr;
} else {
$this->finalBody = $hdr . $this->newline . $this->newline . $this->finalBody;
}
if ($this->sendMultipart !== false) {
$this->finalBody .= '--' . $boundary . '--';
}
return;
case 'plain-attach':
$boundary = uniqid('B_ATC_', true);
$hdr .= 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
if ($this->getProtocol() === 'mail') {
$this->headerStr .= $hdr;
}
$body .= $this->getMimeMessage() . $this->newline
. $this->newline
. '--' . $boundary . $this->newline
. 'Content-Type: text/plain; charset=' . $this->charset . $this->newline
. 'Content-Transfer-Encoding: ' . $this->getEncoding() . $this->newline
. $this->newline
. $this->body . $this->newline . $this->newline;
$this->appendAttachments($body, $boundary);
break;
case 'html-attach':
$altBoundary = uniqid('B_ALT_', true);
$lastBoundary = null;
if ($this->attachmentsHaveMultipart('mixed')) {
$atcBoundary = uniqid('B_ATC_', true);
$hdr .= 'Content-Type: multipart/mixed; boundary="' . $atcBoundary . '"';
$lastBoundary = $atcBoundary;
}
if ($this->attachmentsHaveMultipart('related')) {
$relBoundary = uniqid('B_REL_', true);
$relBoundaryHeader = 'Content-Type: multipart/related; boundary="' . $relBoundary . '"';
if (isset($lastBoundary)) {
$body .= '--' . $lastBoundary . $this->newline . $relBoundaryHeader;
} else {
$hdr .= $relBoundaryHeader;
}
$lastBoundary = $relBoundary;
}
if ($this->getProtocol() === 'mail') {
$this->headerStr .= $hdr;
}
if (static::strlen($body) > 0) {
$body .= $this->newline . $this->newline;
}
$body .= $this->getMimeMessage() . $this->newline . $this->newline
. '--' . $lastBoundary . $this->newline
. 'Content-Type: multipart/alternative; boundary="' . $altBoundary . '"' . $this->newline . $this->newline
. '--' . $altBoundary . $this->newline
. 'Content-Type: text/plain; charset=' . $this->charset . $this->newline
. 'Content-Transfer-Encoding: ' . $this->getEncoding() . $this->newline . $this->newline
. $this->getAltMessage() . $this->newline . $this->newline
. '--' . $altBoundary . $this->newline
. 'Content-Type: text/html; charset=' . $this->charset . $this->newline
. 'Content-Transfer-Encoding: quoted-printable' . $this->newline . $this->newline
. $this->prepQuotedPrintable($this->body) . $this->newline . $this->newline
. '--' . $altBoundary . '--' . $this->newline . $this->newline;
if (isset($relBoundary)) {
$body .= $this->newline . $this->newline;
$this->appendAttachments($body, $relBoundary, 'related');
}
// multipart/mixed attachments
if (isset($atcBoundary)) {
$body .= $this->newline . $this->newline;
$this->appendAttachments($body, $atcBoundary, 'mixed');
}
break;
}
$this->finalBody = ($this->getProtocol() === 'mail') ? $body : $hdr . $this->newline . $this->newline . $body;
}
/**
* @param string $type
*
* @return bool
*/
protected function attachmentsHaveMultipart($type)
{
foreach ($this->attachments as $attachment) {
if ($attachment['multipart'] === $type) {
return true;
}
}
return false;
}
/**
* @param string $body Message body to append to
* @param string $boundary Multipart boundary
* @param string|null $multipart When provided, only attachments of this type will be processed
*
* @return void
*/
protected function appendAttachments(&$body, $boundary, $multipart = null)
{
foreach ($this->attachments as $attachment) {
if (isset($multipart) && $attachment['multipart'] !== $multipart) {
continue;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Exceptions.php | system/Debug/Exceptions.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Exceptions\HasExitCodeInterface;
use CodeIgniter\Exceptions\HTTPExceptionInterface;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Exceptions as ExceptionsConfig;
use Config\Paths;
use ErrorException;
use Psr\Log\LogLevel;
use Throwable;
/**
* Exceptions manager
*
* @see \CodeIgniter\Debug\ExceptionsTest
*/
class Exceptions
{
use ResponseTrait;
/**
* Nesting level of the output buffering mechanism
*
* @var int
*
* @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler.
*/
public $ob_level;
/**
* The path to the directory containing the
* cli and html error view directories.
*
* @var string
*
* @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler.
*/
protected $viewPath;
/**
* Config for debug exceptions.
*
* @var ExceptionsConfig
*/
protected $config;
/**
* The request.
*
* @var RequestInterface|null
*/
protected $request;
/**
* The outgoing response.
*
* @var ResponseInterface
*/
protected $response;
private ?Throwable $exceptionCaughtByExceptionHandler = null;
public function __construct(ExceptionsConfig $config)
{
// For backward compatibility
$this->ob_level = ob_get_level();
$this->viewPath = rtrim($config->errorViewPath, '\\/ ') . DIRECTORY_SEPARATOR;
$this->config = $config;
// workaround for upgraded users
// This causes "Deprecated: Creation of dynamic property" in PHP 8.2.
// @TODO remove this after dropping PHP 8.1 support.
if (! isset($this->config->sensitiveDataInTrace)) {
$this->config->sensitiveDataInTrace = [];
}
if (! isset($this->config->logDeprecations, $this->config->deprecationLogLevel)) {
$this->config->logDeprecations = false;
$this->config->deprecationLogLevel = LogLevel::WARNING;
}
}
/**
* Responsible for registering the error, exception and shutdown
* handling of our application.
*
* @codeCoverageIgnore
*
* @return void
*/
public function initialize()
{
set_exception_handler($this->exceptionHandler(...));
set_error_handler($this->errorHandler(...));
register_shutdown_function([$this, 'shutdownHandler']);
}
/**
* Catches any uncaught errors and exceptions, including most Fatal errors
* (Yay PHP7!). Will log the error, display it if display_errors is on,
* and fire an event that allows custom actions to be taken at this point.
*
* @return void
*/
public function exceptionHandler(Throwable $exception)
{
$this->exceptionCaughtByExceptionHandler = $exception;
[$statusCode, $exitCode] = $this->determineCodes($exception);
$this->request = service('request');
if ($this->config->log === true && ! in_array($statusCode, $this->config->ignoreCodes, true)) {
$uri = $this->request->getPath() === '' ? '/' : $this->request->getPath();
$routeInfo = '[Method: ' . $this->request->getMethod() . ', Route: ' . $uri . ']';
log_message('critical', $exception::class . ": {message}\n{routeInfo}\nin {exFile} on line {exLine}.\n{trace}", [
'message' => $exception->getMessage(),
'routeInfo' => $routeInfo,
'exFile' => clean_path($exception->getFile()), // {file} refers to THIS file
'exLine' => $exception->getLine(), // {line} refers to THIS line
'trace' => self::renderBacktrace($exception->getTrace()),
]);
// Get the first exception.
$last = $exception;
while ($prevException = $last->getPrevious()) {
$last = $prevException;
log_message('critical', '[Caused by] ' . $prevException::class . ": {message}\nin {exFile} on line {exLine}.\n{trace}", [
'message' => $prevException->getMessage(),
'exFile' => clean_path($prevException->getFile()), // {file} refers to THIS file
'exLine' => $prevException->getLine(), // {line} refers to THIS line
'trace' => self::renderBacktrace($prevException->getTrace()),
]);
}
}
$this->response = service('response');
if (method_exists($this->config, 'handler')) {
// Use new ExceptionHandler
$handler = $this->config->handler($statusCode, $exception);
$handler->handle(
$exception,
$this->request,
$this->response,
$statusCode,
$exitCode,
);
return;
}
// For backward compatibility
if (! is_cli()) {
try {
$this->response->setStatusCode($statusCode);
} catch (HTTPException) {
// Workaround for invalid HTTP status code.
$statusCode = 500;
$this->response->setStatusCode($statusCode);
}
if (! headers_sent()) {
header(sprintf('HTTP/%s %s %s', $this->request->getProtocolVersion(), $this->response->getStatusCode(), $this->response->getReasonPhrase()), true, $statusCode);
}
if (! str_contains($this->request->getHeaderLine('accept'), 'text/html')) {
$this->respond(ENVIRONMENT === 'development' ? $this->collectVars($exception, $statusCode) : '', $statusCode)->send();
exit($exitCode);
}
}
$this->render($exception, $statusCode);
exit($exitCode);
}
/**
* The callback to be registered to `set_error_handler()`.
*
* @return bool
*
* @throws ErrorException
*
* @codeCoverageIgnore
*/
public function errorHandler(int $severity, string $message, ?string $file = null, ?int $line = null)
{
if ($this->isDeprecationError($severity)) {
if ($this->isSessionSidDeprecationError($message, $file, $line)) {
return true;
}
if ($this->isImplicitNullableDeprecationError($message, $file, $line)) {
return true;
}
if (! $this->config->logDeprecations || (bool) env('CODEIGNITER_SCREAM_DEPRECATIONS')) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return $this->handleDeprecationError($message, $file, $line);
}
if ((error_reporting() & $severity) !== 0) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false; // return false to propagate the error to PHP standard error handler
}
/**
* Handles session.sid_length and session.sid_bits_per_character deprecations
* in PHP 8.4.
*/
private function isSessionSidDeprecationError(string $message, ?string $file = null, ?int $line = null): bool
{
if (
PHP_VERSION_ID >= 80400
&& str_contains($message, 'session.sid_')
) {
log_message(
LogLevel::WARNING,
'[DEPRECATED] {message} in {errFile} on line {errLine}.',
[
'message' => $message,
'errFile' => clean_path($file ?? ''),
'errLine' => $line ?? 0,
],
);
return true;
}
return false;
}
/**
* Workaround to implicit nullable deprecation errors in PHP 8.4.
*
* "Implicitly marking parameter $xxx as nullable is deprecated,
* the explicit nullable type must be used instead"
*
* @TODO remove this before v4.6.0 release
*/
private function isImplicitNullableDeprecationError(string $message, ?string $file = null, ?int $line = null): bool
{
if (
PHP_VERSION_ID >= 80400
&& str_contains($message, 'the explicit nullable type must be used instead')
// Only Kint and Faker, which cause this error, are logged.
&& (str_starts_with($message, 'Kint\\') || str_starts_with($message, 'Faker\\'))
) {
log_message(
LogLevel::WARNING,
'[DEPRECATED] {message} in {errFile} on line {errLine}.',
[
'message' => $message,
'errFile' => clean_path($file ?? ''),
'errLine' => $line ?? 0,
],
);
return true;
}
return false;
}
/**
* Checks to see if any errors have happened during shutdown that
* need to be caught and handle them.
*
* @codeCoverageIgnore
*
* @return void
*/
public function shutdownHandler()
{
$error = error_get_last();
if ($error === null) {
return;
}
['type' => $type, 'message' => $message, 'file' => $file, 'line' => $line] = $error;
if ($this->exceptionCaughtByExceptionHandler instanceof Throwable) {
$message .= "\n【Previous Exception】\n"
. $this->exceptionCaughtByExceptionHandler::class . "\n"
. $this->exceptionCaughtByExceptionHandler->getMessage() . "\n"
. $this->exceptionCaughtByExceptionHandler->getTraceAsString();
}
if (in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE], true)) {
$this->exceptionHandler(new ErrorException($message, 0, $type, $file, $line));
}
}
/**
* Determines the view to display based on the exception thrown,
* whether an HTTP or CLI request, etc.
*
* @return string The path and filename of the view file to use
*
* @deprecated 4.4.0 No longer used. Moved to ExceptionHandler.
*/
protected function determineView(Throwable $exception, string $templatePath): string
{
// Production environments should have a custom exception file.
$view = 'production.php';
$templatePath = rtrim($templatePath, '\\/ ') . DIRECTORY_SEPARATOR;
if (
in_array(
strtolower(ini_get('display_errors')),
['1', 'true', 'on', 'yes'],
true,
)
) {
$view = 'error_exception.php';
}
// 404 Errors
if ($exception instanceof PageNotFoundException) {
return 'error_404.php';
}
// Allow for custom views based upon the status code
if (is_file($templatePath . 'error_' . $exception->getCode() . '.php')) {
return 'error_' . $exception->getCode() . '.php';
}
return $view;
}
/**
* Given an exception and status code will display the error to the client.
*
* @return void
*
* @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler.
*/
protected function render(Throwable $exception, int $statusCode)
{
// Determine possible directories of error views
$path = $this->viewPath;
$altPath = rtrim((new Paths())->viewDirectory, '\\/ ') . DIRECTORY_SEPARATOR . 'errors' . DIRECTORY_SEPARATOR;
$path .= (is_cli() ? 'cli' : 'html') . DIRECTORY_SEPARATOR;
$altPath .= (is_cli() ? 'cli' : 'html') . DIRECTORY_SEPARATOR;
// Determine the views
$view = $this->determineView($exception, $path);
$altView = $this->determineView($exception, $altPath);
// Check if the view exists
if (is_file($path . $view)) {
$viewFile = $path . $view;
} elseif (is_file($altPath . $altView)) {
$viewFile = $altPath . $altView;
}
if (! isset($viewFile)) {
echo 'The error view files were not found. Cannot render exception trace.';
exit(1);
}
echo (function () use ($exception, $statusCode, $viewFile): string {
$vars = $this->collectVars($exception, $statusCode);
extract($vars, EXTR_SKIP);
ob_start();
include $viewFile;
return ob_get_clean();
})();
}
/**
* Gathers the variables that will be made available to the view.
*
* @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler.
*/
protected function collectVars(Throwable $exception, int $statusCode): array
{
// Get the first exception.
$firstException = $exception;
while ($prevException = $firstException->getPrevious()) {
$firstException = $prevException;
}
$trace = $firstException->getTrace();
if ($this->config->sensitiveDataInTrace !== []) {
$trace = $this->maskSensitiveData($trace, $this->config->sensitiveDataInTrace);
}
return [
'title' => $exception::class,
'type' => $exception::class,
'code' => $statusCode,
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $trace,
];
}
/**
* Mask sensitive data in the trace.
*
* @param array $trace
*
* @return array
*
* @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler.
*/
protected function maskSensitiveData($trace, array $keysToMask, string $path = '')
{
foreach ($trace as $i => $line) {
$trace[$i]['args'] = $this->maskData($line['args'], $keysToMask);
}
return $trace;
}
/**
* @param array|object $args
*
* @return array|object
*
* @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler.
*/
private function maskData($args, array $keysToMask, string $path = '')
{
foreach ($keysToMask as $keyToMask) {
$explode = explode('/', $keyToMask);
$index = end($explode);
if (str_starts_with(strrev($path . '/' . $index), strrev($keyToMask))) {
if (is_array($args) && array_key_exists($index, $args)) {
$args[$index] = '******************';
} elseif (
is_object($args) && property_exists($args, $index)
&& isset($args->{$index}) && is_scalar($args->{$index})
) {
$args->{$index} = '******************';
}
}
}
if (is_array($args)) {
foreach ($args as $pathKey => $subarray) {
$args[$pathKey] = $this->maskData($subarray, $keysToMask, $path . '/' . $pathKey);
}
} elseif (is_object($args)) {
foreach ($args as $pathKey => $subarray) {
$args->{$pathKey} = $this->maskData($subarray, $keysToMask, $path . '/' . $pathKey);
}
}
return $args;
}
/**
* Determines the HTTP status code and the exit status code for this request.
*/
protected function determineCodes(Throwable $exception): array
{
$statusCode = 500;
$exitStatus = EXIT_ERROR;
if ($exception instanceof HTTPExceptionInterface) {
$statusCode = $exception->getCode();
}
if ($exception instanceof HasExitCodeInterface) {
$exitStatus = $exception->getExitCode();
}
return [$statusCode, $exitStatus];
}
private function isDeprecationError(int $error): bool
{
$deprecations = E_DEPRECATED | E_USER_DEPRECATED;
return ($error & $deprecations) !== 0;
}
/**
* @return true
*/
private function handleDeprecationError(string $message, ?string $file = null, ?int $line = null): bool
{
// Remove the trace of the error handler.
$trace = array_slice(debug_backtrace(), 2);
log_message(
$this->config->deprecationLogLevel,
"[DEPRECATED] {message} in {errFile} on line {errLine}.\n{trace}",
[
'message' => $message,
'errFile' => clean_path($file ?? ''),
'errLine' => $line ?? 0,
'trace' => self::renderBacktrace($trace),
],
);
return true;
}
// --------------------------------------------------------------------
// Display Methods
// --------------------------------------------------------------------
/**
* This makes nicer looking paths for the error output.
*
* @deprecated Use dedicated `clean_path()` function.
*/
public static function cleanPath(string $file): string
{
return match (true) {
str_starts_with($file, APPPATH) => 'APPPATH' . DIRECTORY_SEPARATOR . substr($file, strlen(APPPATH)),
str_starts_with($file, SYSTEMPATH) => 'SYSTEMPATH' . DIRECTORY_SEPARATOR . substr($file, strlen(SYSTEMPATH)),
str_starts_with($file, FCPATH) => 'FCPATH' . DIRECTORY_SEPARATOR . substr($file, strlen(FCPATH)),
defined('VENDORPATH') && str_starts_with($file, VENDORPATH) => 'VENDORPATH' . DIRECTORY_SEPARATOR . substr($file, strlen(VENDORPATH)),
default => $file,
};
}
/**
* Describes memory usage in real-world units. Intended for use
* with memory_get_usage, etc.
*
* @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler.
*/
public static function describeMemory(int $bytes): string
{
if ($bytes < 1024) {
return $bytes . 'B';
}
if ($bytes < 1_048_576) {
return round($bytes / 1024, 2) . 'KB';
}
return round($bytes / 1_048_576, 2) . 'MB';
}
/**
* Creates a syntax-highlighted version of a PHP file.
*
* @return bool|string
*
* @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler.
*/
public static function highlightFile(string $file, int $lineNumber, int $lines = 15)
{
if ($file === '' || ! is_readable($file)) {
return false;
}
// Set our highlight colors:
if (function_exists('ini_set')) {
ini_set('highlight.comment', '#767a7e; font-style: italic');
ini_set('highlight.default', '#c7c7c7');
ini_set('highlight.html', '#06B');
ini_set('highlight.keyword', '#f1ce61;');
ini_set('highlight.string', '#869d6a');
}
try {
$source = file_get_contents($file);
} catch (Throwable) {
return false;
}
$source = str_replace(["\r\n", "\r"], "\n", $source);
$source = explode("\n", highlight_string($source, true));
$source = str_replace('<br />', "\n", $source[1]);
$source = explode("\n", str_replace("\r\n", "\n", $source));
// Get just the part to show
$start = max($lineNumber - (int) round($lines / 2), 0);
// Get just the lines we need to display, while keeping line numbers...
$source = array_splice($source, $start, $lines, true);
// Used to format the line number in the source
$format = '% ' . strlen((string) ($start + $lines)) . 'd';
$out = '';
// Because the highlighting may have an uneven number
// of open and close span tags on one line, we need
// to ensure we can close them all to get the lines
// showing correctly.
$spans = 1;
foreach ($source as $n => $row) {
$spans += substr_count($row, '<span') - substr_count($row, '</span');
$row = str_replace(["\r", "\n"], ['', ''], $row);
if (($n + $start + 1) === $lineNumber) {
preg_match_all('#<[^>]+>#', $row, $tags);
$out .= sprintf(
"<span class='line highlight'><span class='number'>{$format}</span> %s\n</span>%s",
$n + $start + 1,
strip_tags($row),
implode('', $tags[0]),
);
} else {
$out .= sprintf('<span class="line"><span class="number">' . $format . '</span> %s', $n + $start + 1, $row) . "\n";
}
}
if ($spans > 0) {
$out .= str_repeat('</span>', $spans);
}
return '<pre><code>' . $out . '</code></pre>';
}
private static function renderBacktrace(array $backtrace): string
{
$backtraces = [];
foreach ($backtrace as $index => $trace) {
$frame = $trace + ['file' => '[internal function]', 'line' => '', 'class' => '', 'type' => '', 'args' => []];
if ($frame['file'] !== '[internal function]') {
$frame['file'] = sprintf('%s(%s)', $frame['file'], $frame['line']);
}
unset($frame['line']);
$idx = $index;
$idx = str_pad((string) ++$idx, 2, ' ', STR_PAD_LEFT);
$args = implode(', ', array_map(static fn ($value): string => match (true) {
is_object($value) => sprintf('Object(%s)', $value::class),
is_array($value) => $value !== [] ? '[...]' : '[]',
$value === null => 'null',
is_resource($value) => sprintf('resource (%s)', get_resource_type($value)),
default => var_export($value, true),
}, $frame['args']));
$backtraces[] = sprintf(
'%s %s: %s%s%s(%s)',
$idx,
clean_path($frame['file']),
$frame['class'],
$frame['type'],
$frame['function'],
$args,
);
}
return implode("\n", $backtraces);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/ExceptionHandlerInterface.php | system/Debug/ExceptionHandlerInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Throwable;
interface ExceptionHandlerInterface
{
/**
* Determines the correct way to display the error.
*/
public function handle(
Throwable $exception,
RequestInterface $request,
ResponseInterface $response,
int $statusCode,
int $exitCode,
): void;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/ExceptionHandler.php | system/Debug/ExceptionHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Paths;
use Throwable;
/**
* @see \CodeIgniter\Debug\ExceptionHandlerTest
*/
final class ExceptionHandler extends BaseExceptionHandler implements ExceptionHandlerInterface
{
use ResponseTrait;
/**
* ResponseTrait needs this.
*/
private ?RequestInterface $request = null;
/**
* ResponseTrait needs this.
*/
private ?ResponseInterface $response = null;
/**
* Determines the correct way to display the error.
*/
public function handle(
Throwable $exception,
RequestInterface $request,
ResponseInterface $response,
int $statusCode,
int $exitCode,
): void {
// ResponseTrait needs these properties.
$this->request = $request;
$this->response = $response;
if ($request instanceof IncomingRequest) {
try {
$response->setStatusCode($statusCode);
} catch (HTTPException) {
// Workaround for invalid HTTP status code.
$statusCode = 500;
$response->setStatusCode($statusCode);
}
if (! headers_sent()) {
header(
sprintf(
'HTTP/%s %s %s',
$request->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase(),
),
true,
$statusCode,
);
}
// Handles non-HTML requests.
if (! str_contains($request->getHeaderLine('accept'), 'text/html')) {
// If display_errors is enabled, shows the error details.
$data = $this->isDisplayErrorsEnabled()
? $this->collectVars($exception, $statusCode)
: '';
$this->respond($data, $statusCode)->send();
if (ENVIRONMENT !== 'testing') {
// @codeCoverageIgnoreStart
exit($exitCode);
// @codeCoverageIgnoreEnd
}
return;
}
}
// Determine possible directories of error views
$addPath = ($request instanceof IncomingRequest ? 'html' : 'cli') . DIRECTORY_SEPARATOR;
$path = $this->viewPath . $addPath;
$altPath = rtrim((new Paths())->viewDirectory, '\\/ ')
. DIRECTORY_SEPARATOR . 'errors' . DIRECTORY_SEPARATOR . $addPath;
// Determine the views
$view = $this->determineView($exception, $path, $statusCode);
$altView = $this->determineView($exception, $altPath, $statusCode);
// Check if the view exists
$viewFile = null;
if (is_file($path . $view)) {
$viewFile = $path . $view;
} elseif (is_file($altPath . $altView)) {
$viewFile = $altPath . $altView;
}
// Displays the HTML or CLI error code.
$this->render($exception, $statusCode, $viewFile);
if (ENVIRONMENT !== 'testing') {
// @codeCoverageIgnoreStart
exit($exitCode);
// @codeCoverageIgnoreEnd
}
}
/**
* Determines the view to display based on the exception thrown, HTTP status
* code, whether an HTTP or CLI request, etc.
*
* @return string The filename of the view file to use
*/
protected function determineView(
Throwable $exception,
string $templatePath,
int $statusCode = 500,
): string {
// Production environments should have a custom exception file.
$view = 'production.php';
if ($this->isDisplayErrorsEnabled()) {
// If display_errors is enabled, shows the error details.
$view = 'error_exception.php';
}
// 404 Errors
if ($exception instanceof PageNotFoundException) {
return 'error_404.php';
}
$templatePath = rtrim($templatePath, '\\/ ') . DIRECTORY_SEPARATOR;
// Allow for custom views based upon the status code
if (is_file($templatePath . 'error_' . $statusCode . '.php')) {
return 'error_' . $statusCode . '.php';
}
return $view;
}
private function isDisplayErrorsEnabled(): bool
{
return in_array(
strtolower(ini_get('display_errors')),
['1', 'true', 'on', 'yes'],
true,
);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Timer.php | system/Debug/Timer.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\Exceptions\RuntimeException;
/**
* Class Timer
*
* Provides a simple way to measure the amount of time
* that elapses between two points.
*
* @see \CodeIgniter\Debug\TimerTest
*/
class Timer
{
/**
* List of all timers.
*
* @var array
*/
protected $timers = [];
/**
* Starts a timer running.
*
* Multiple calls can be made to this method so that several
* execution points can be measured.
*
* @param string $name The name of this timer.
* @param float|null $time Allows user to provide time.
*
* @return Timer
*/
public function start(string $name, ?float $time = null)
{
$this->timers[strtolower($name)] = [
'start' => ! empty($time) ? $time : microtime(true),
'end' => null,
];
return $this;
}
/**
* Stops a running timer.
*
* If the timer is not stopped before the timers() method is called,
* it will be automatically stopped at that point.
*
* @param string $name The name of this timer.
*
* @return Timer
*/
public function stop(string $name)
{
$name = strtolower($name);
if (empty($this->timers[$name])) {
throw new RuntimeException('Cannot stop timer: invalid name given.');
}
$this->timers[$name]['end'] = microtime(true);
return $this;
}
/**
* Returns the duration of a recorded timer.
*
* @param string $name The name of the timer.
* @param int $decimals Number of decimal places.
*
* @return float|null Returns null if timer does not exist by that name.
* Returns a float representing the number of
* seconds elapsed while that timer was running.
*/
public function getElapsedTime(string $name, int $decimals = 4)
{
$name = strtolower($name);
if (empty($this->timers[$name])) {
return null;
}
$timer = $this->timers[$name];
if (empty($timer['end'])) {
$timer['end'] = microtime(true);
}
return (float) number_format($timer['end'] - $timer['start'], $decimals, '.', '');
}
/**
* Returns the array of timers, with the duration pre-calculated for you.
*
* @param int $decimals Number of decimal places
*/
public function getTimers(int $decimals = 4): array
{
$timers = $this->timers;
foreach ($timers as &$timer) {
if (empty($timer['end'])) {
$timer['end'] = microtime(true);
}
$timer['duration'] = (float) number_format($timer['end'] - $timer['start'], $decimals);
}
return $timers;
}
/**
* Checks whether or not a timer with the specified name exists.
*/
public function has(string $name): bool
{
return array_key_exists(strtolower($name), $this->timers);
}
/**
* Executes callable and measures its time.
* Returns its return value if any.
*
* @param string $name The name of the timer
* @param callable(): mixed $callable callable to be executed
*
* @return mixed
*/
public function record(string $name, callable $callable)
{
$this->start($name);
$returnValue = $callable();
$this->stop($name);
return $returnValue;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar.php | system/Debug/Toolbar.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\CodeIgniter;
use CodeIgniter\Debug\Toolbar\Collectors\BaseCollector;
use CodeIgniter\Debug\Toolbar\Collectors\Config;
use CodeIgniter\Debug\Toolbar\Collectors\History;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\Header;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\I18n\Time;
use Config\Toolbar as ToolbarConfig;
use Kint\Kint;
/**
* Displays a toolbar with bits of stats to aid a developer in debugging.
*
* Inspiration: http://prophiler.fabfuel.de
*/
class Toolbar
{
/**
* Toolbar configuration settings.
*
* @var ToolbarConfig
*/
protected $config;
/**
* Collectors to be used and displayed.
*
* @var list<BaseCollector>
*/
protected $collectors = [];
public function __construct(ToolbarConfig $config)
{
$this->config = $config;
foreach ($config->collectors as $collector) {
if (! class_exists($collector)) {
log_message(
'critical',
'Toolbar collector does not exist (' . $collector . ').'
. ' Please check $collectors in the app/Config/Toolbar.php file.',
);
continue;
}
$this->collectors[] = new $collector();
}
}
/**
* Returns all the data required by Debug Bar
*
* @param float $startTime App start time
* @param IncomingRequest $request
*
* @return string JSON encoded data
*/
public function run(float $startTime, float $totalTime, RequestInterface $request, ResponseInterface $response): string
{
$data = [];
// Data items used within the view.
$data['url'] = current_url();
$data['method'] = $request->getMethod();
$data['isAJAX'] = $request->isAJAX();
$data['startTime'] = $startTime;
$data['totalTime'] = $totalTime * 1000;
$data['totalMemory'] = number_format(memory_get_peak_usage() / 1024 / 1024, 3);
$data['segmentDuration'] = $this->roundTo($data['totalTime'] / 7);
$data['segmentCount'] = (int) ceil($data['totalTime'] / $data['segmentDuration']);
$data['CI_VERSION'] = CodeIgniter::CI_VERSION;
$data['collectors'] = [];
foreach ($this->collectors as $collector) {
$data['collectors'][] = $collector->getAsArray();
}
foreach ($this->collectVarData() as $heading => $items) {
$varData = [];
if (is_array($items)) {
foreach ($items as $key => $value) {
if (is_string($value)) {
$varData[esc($key)] = esc($value);
} else {
$oldKintMode = Kint::$mode_default;
$oldKintCalledFrom = Kint::$display_called_from;
Kint::$mode_default = Kint::MODE_RICH;
Kint::$display_called_from = false;
$kint = @Kint::dump($value);
$kint = substr($kint, strpos($kint, '</style>') + 8);
Kint::$mode_default = $oldKintMode;
Kint::$display_called_from = $oldKintCalledFrom;
$varData[esc($key)] = $kint;
}
}
}
$data['vars']['varData'][esc($heading)] = $varData;
}
if (isset($_SESSION)) {
foreach ($_SESSION as $key => $value) {
// Replace the binary data with string to avoid json_encode failure.
if (is_string($value) && preg_match('~[^\x20-\x7E\t\r\n]~', $value)) {
$value = 'binary data';
}
$data['vars']['session'][esc($key)] = is_string($value) ? esc($value) : '<pre>' . esc(print_r($value, true)) . '</pre>';
}
}
foreach ($request->getGet() as $name => $value) {
$data['vars']['get'][esc($name)] = is_array($value) ? '<pre>' . esc(print_r($value, true)) . '</pre>' : esc($value);
}
foreach ($request->getPost() as $name => $value) {
$data['vars']['post'][esc($name)] = is_array($value) ? '<pre>' . esc(print_r($value, true)) . '</pre>' : esc($value);
}
foreach ($request->headers() as $name => $value) {
if ($value instanceof Header) {
$data['vars']['headers'][esc($name)] = esc($value->getValueLine());
} else {
foreach ($value as $i => $header) {
$index = $i + 1;
$data['vars']['headers'][esc($name)] ??= '';
$data['vars']['headers'][esc($name)] .= ' (' . $index . ') '
. esc($header->getValueLine());
}
}
}
foreach ($request->getCookie() as $name => $value) {
$data['vars']['cookies'][esc($name)] = esc($value);
}
$data['vars']['request'] = ($request->isSecure() ? 'HTTPS' : 'HTTP') . '/' . $request->getProtocolVersion();
$data['vars']['response'] = [
'statusCode' => $response->getStatusCode(),
'reason' => esc($response->getReasonPhrase()),
'contentType' => esc($response->getHeaderLine('content-type')),
'headers' => [],
];
foreach ($response->headers() as $name => $value) {
if ($value instanceof Header) {
$data['vars']['response']['headers'][esc($name)] = esc($value->getValueLine());
} else {
foreach ($value as $i => $header) {
$index = $i + 1;
$data['vars']['response']['headers'][esc($name)] ??= '';
$data['vars']['response']['headers'][esc($name)] .= ' (' . $index . ') '
. esc($header->getValueLine());
}
}
}
$data['config'] = Config::display();
$response->getCSP()->addImageSrc('data:');
return json_encode($data);
}
/**
* Called within the view to display the timeline itself.
*/
protected function renderTimeline(array $collectors, float $startTime, int $segmentCount, int $segmentDuration, array &$styles): string
{
$rows = $this->collectTimelineData($collectors);
$styleCount = 0;
// Use recursive render function
return $this->renderTimelineRecursive($rows, $startTime, $segmentCount, $segmentDuration, $styles, $styleCount);
}
/**
* Recursively renders timeline elements and their children.
*/
protected function renderTimelineRecursive(array $rows, float $startTime, int $segmentCount, int $segmentDuration, array &$styles, int &$styleCount, int $level = 0, bool $isChild = false): string
{
$displayTime = $segmentCount * $segmentDuration;
$output = '';
foreach ($rows as $row) {
$hasChildren = isset($row['children']) && ! empty($row['children']);
$isQuery = isset($row['query']) && ! empty($row['query']);
// Open controller timeline by default
$open = $row['name'] === 'Controller';
if ($hasChildren || $isQuery) {
$output .= '<tr class="timeline-parent' . ($open ? ' timeline-parent-open' : '') . '" id="timeline-' . $styleCount . '_parent" data-toggle="childrows" data-child="timeline-' . $styleCount . '">';
} else {
$output .= '<tr>';
}
$output .= '<td class="' . ($isChild ? 'debug-bar-width30' : '') . ' debug-bar-level-' . $level . '" >' . ($hasChildren || $isQuery ? '<nav></nav>' : '') . $row['name'] . '</td>';
$output .= '<td class="' . ($isChild ? 'debug-bar-width10' : '') . '">' . $row['component'] . '</td>';
$output .= '<td class="' . ($isChild ? 'debug-bar-width10 ' : '') . 'debug-bar-alignRight">' . number_format($row['duration'] * 1000, 2) . ' ms</td>';
$output .= "<td class='debug-bar-noverflow' colspan='{$segmentCount}'>";
$offset = ((((float) $row['start'] - $startTime) * 1000) / $displayTime) * 100;
$length = (((float) $row['duration'] * 1000) / $displayTime) * 100;
$styles['debug-bar-timeline-' . $styleCount] = "left: {$offset}%; width: {$length}%;";
$output .= "<span class='timer debug-bar-timeline-{$styleCount}' title='" . number_format($length, 2) . "%'></span>";
$output .= '</td>';
$output .= '</tr>';
$styleCount++;
// Add children if any
if ($hasChildren || $isQuery) {
$output .= '<tr class="child-row ' . ($open ? '' : ' debug-bar-ndisplay') . '" id="timeline-' . ($styleCount - 1) . '_children" >';
$output .= '<td colspan="' . ($segmentCount + 3) . '" class="child-container">';
$output .= '<table class="timeline">';
$output .= '<tbody>';
if ($isQuery) {
// Output query string if query
$output .= '<tr>';
$output .= '<td class="query-container debug-bar-level-' . ($level + 1) . '" >' . $row['query'] . '</td>';
$output .= '</tr>';
} else {
// Recursively render children
$output .= $this->renderTimelineRecursive($row['children'], $startTime, $segmentCount, $segmentDuration, $styles, $styleCount, $level + 1, true);
}
$output .= '</tbody>';
$output .= '</table>';
$output .= '</td>';
$output .= '</tr>';
}
}
return $output;
}
/**
* Returns a sorted array of timeline data arrays from the collectors.
*
* @param array $collectors
*/
protected function collectTimelineData($collectors): array
{
$data = [];
// Collect it
foreach ($collectors as $collector) {
if (! $collector['hasTimelineData']) {
continue;
}
$data = array_merge($data, $collector['timelineData']);
}
// Sort it
$sortArray = [
array_column($data, 'start'), SORT_NUMERIC, SORT_ASC,
array_column($data, 'duration'), SORT_NUMERIC, SORT_DESC,
&$data,
];
array_multisort(...$sortArray);
// Add end time to each element
array_walk($data, static function (&$row): void {
$row['end'] = $row['start'] + $row['duration'];
});
// Group it
$data = $this->structureTimelineData($data);
return $data;
}
/**
* Arranges the already sorted timeline data into a parent => child structure.
*/
protected function structureTimelineData(array $elements): array
{
// We define ourselves as the first element of the array
$element = array_shift($elements);
// If we have children behind us, collect and attach them to us
while ($elements !== [] && $elements[array_key_first($elements)]['end'] <= $element['end']) {
$element['children'][] = array_shift($elements);
}
// Make sure our children know whether they have children, too
if (isset($element['children'])) {
$element['children'] = $this->structureTimelineData($element['children']);
}
// If we have no younger siblings, we can return
if ($elements === []) {
return [$element];
}
// Make sure our younger siblings know their relatives, too
return array_merge([$element], $this->structureTimelineData($elements));
}
/**
* Returns an array of data from all of the modules
* that should be displayed in the 'Vars' tab.
*/
protected function collectVarData(): array
{
if (! ($this->config->collectVarData ?? true)) {
return [];
}
$data = [];
foreach ($this->collectors as $collector) {
if (! $collector->hasVarData()) {
continue;
}
$data = array_merge($data, $collector->getVarData());
}
return $data;
}
/**
* Rounds a number to the nearest incremental value.
*/
protected function roundTo(float $number, int $increments = 5): float
{
$increments = 1 / $increments;
return ceil($number * $increments) / $increments;
}
/**
* Prepare for debugging.
*
* @return void
*/
public function prepare(?RequestInterface $request = null, ?ResponseInterface $response = null)
{
/**
* @var IncomingRequest|null $request
*/
if (CI_DEBUG && ! is_cli()) {
$app = service('codeigniter');
$request ??= service('request');
/** @var ResponseInterface $response */
$response ??= service('response');
// Disable the toolbar for downloads
if ($response instanceof DownloadResponse) {
return;
}
$toolbar = service('toolbar', config(ToolbarConfig::class));
$stats = $app->getPerformanceStats();
$data = $toolbar->run(
$stats['startTime'],
$stats['totalTime'],
$request,
$response,
);
helper('filesystem');
// Updated to microtime() so we can get history
$time = sprintf('%.6f', Time::now()->format('U.u'));
if (! is_dir(WRITEPATH . 'debugbar')) {
mkdir(WRITEPATH . 'debugbar', 0777);
}
write_file(WRITEPATH . 'debugbar/debugbar_' . $time . '.json', $data, 'w+');
$format = $response->getHeaderLine('content-type');
// Non-HTML formats should not include the debugbar
// then we send headers saying where to find the debug data
// for this response
if ($request->isAJAX() || ! str_contains($format, 'html')) {
$response->setHeader('Debugbar-Time', "{$time}")
->setHeader('Debugbar-Link', site_url("?debugbar_time={$time}"));
return;
}
$oldKintMode = Kint::$mode_default;
Kint::$mode_default = Kint::MODE_RICH;
$kintScript = @Kint::dump('');
Kint::$mode_default = $oldKintMode;
$kintScript = substr($kintScript, 0, strpos($kintScript, '</style>') + 8);
$kintScript = ($kintScript === '0') ? '' : $kintScript;
$script = PHP_EOL
. '<script ' . csp_script_nonce() . ' id="debugbar_loader" '
. 'data-time="' . $time . '" '
. 'src="' . site_url() . '?debugbar"></script>'
. '<script ' . csp_script_nonce() . ' id="debugbar_dynamic_script"></script>'
. '<style ' . csp_style_nonce() . ' id="debugbar_dynamic_style"></style>'
. $kintScript
. PHP_EOL;
if (str_contains((string) $response->getBody(), '<head>')) {
$response->setBody(
preg_replace(
'/<head>/',
'<head>' . $script,
$response->getBody(),
1,
),
);
return;
}
$response->appendBody($script);
}
}
/**
* Inject debug toolbar into the response.
*
* @codeCoverageIgnore
*
* @return void
*/
public function respond()
{
if (ENVIRONMENT === 'testing') {
return;
}
$request = service('request');
// If the request contains '?debugbar then we're
// simply returning the loading script
if ($request->getGet('debugbar') !== null) {
header('Content-Type: application/javascript');
ob_start();
include $this->config->viewsPath . 'toolbarloader.js';
$output = ob_get_clean();
$output = str_replace('{url}', rtrim(site_url(), '/'), $output);
echo $output;
exit;
}
// Otherwise, if it includes ?debugbar_time, then
// we should return the entire debugbar.
if ($request->getGet('debugbar_time')) {
helper('security');
// Negotiate the content-type to format the output
$format = $request->negotiate('media', ['text/html', 'application/json', 'application/xml']);
$format = explode('/', $format)[1];
$filename = sanitize_filename('debugbar_' . $request->getGet('debugbar_time'));
$filename = WRITEPATH . 'debugbar/' . $filename . '.json';
if (is_file($filename)) {
// Show the toolbar if it exists
echo $this->format(file_get_contents($filename), $format);
exit;
}
// Filename not found
http_response_code(404);
exit; // Exit here is needed to avoid loading the index page
}
}
/**
* Format output
*/
protected function format(string $data, string $format = 'html'): string
{
$data = json_decode($data, true);
if (preg_match('/\d+\.\d{6}/s', (string) service('request')->getGet('debugbar_time'), $debugbarTime)) {
$history = new History();
$history->setFiles(
$debugbarTime[0],
$this->config->maxHistory,
);
$data['collectors'][] = $history->getAsArray();
}
$output = '';
switch ($format) {
case 'html':
$data['styles'] = [];
extract($data);
$parser = service('parser', $this->config->viewsPath, null, false);
ob_start();
include $this->config->viewsPath . 'toolbar.tpl.php';
$output = ob_get_clean();
break;
case 'json':
$formatter = new JSONFormatter();
$output = $formatter->format($data);
break;
case 'xml':
$formatter = new XMLFormatter();
$output = $formatter->format($data);
break;
}
return $output;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/BaseExceptionHandler.php | system/Debug/BaseExceptionHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Exceptions as ExceptionsConfig;
use Throwable;
/**
* Provides common functions for exception handlers,
* especially around displaying the output.
*/
abstract class BaseExceptionHandler
{
/**
* Config for debug exceptions.
*/
protected ExceptionsConfig $config;
/**
* Nesting level of the output buffering mechanism
*/
protected int $obLevel;
/**
* The path to the directory containing the
* cli and html error view directories.
*/
protected ?string $viewPath = null;
public function __construct(ExceptionsConfig $config)
{
$this->config = $config;
$this->obLevel = ob_get_level();
if ($this->viewPath === null) {
$this->viewPath = rtrim($this->config->errorViewPath, '\\/ ') . DIRECTORY_SEPARATOR;
}
}
/**
* The main entry point into the handler.
*
* @return void
*/
abstract public function handle(
Throwable $exception,
RequestInterface $request,
ResponseInterface $response,
int $statusCode,
int $exitCode,
);
/**
* Gathers the variables that will be made available to the view.
*/
protected function collectVars(Throwable $exception, int $statusCode): array
{
// Get the first exception.
$firstException = $exception;
while ($prevException = $firstException->getPrevious()) {
$firstException = $prevException;
}
$trace = $firstException->getTrace();
if ($this->config->sensitiveDataInTrace !== []) {
$trace = $this->maskSensitiveData($trace, $this->config->sensitiveDataInTrace);
}
return [
'title' => $exception::class,
'type' => $exception::class,
'code' => $statusCode,
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $trace,
];
}
/**
* Mask sensitive data in the trace.
*/
protected function maskSensitiveData(array $trace, array $keysToMask, string $path = ''): array
{
foreach ($trace as $i => $line) {
$trace[$i]['args'] = $this->maskData($line['args'], $keysToMask);
}
return $trace;
}
/**
* @param array|object $args
*
* @return array|object
*/
private function maskData($args, array $keysToMask, string $path = '')
{
foreach ($keysToMask as $keyToMask) {
$explode = explode('/', $keyToMask);
$index = end($explode);
if (str_starts_with(strrev($path . '/' . $index), strrev($keyToMask))) {
if (is_array($args) && array_key_exists($index, $args)) {
$args[$index] = '******************';
} elseif (
is_object($args) && property_exists($args, $index)
&& isset($args->{$index}) && is_scalar($args->{$index})
) {
$args->{$index} = '******************';
}
}
}
if (is_array($args)) {
foreach ($args as $pathKey => $subarray) {
$args[$pathKey] = $this->maskData($subarray, $keysToMask, $path . '/' . $pathKey);
}
} elseif (is_object($args)) {
foreach ($args as $pathKey => $subarray) {
$args->{$pathKey} = $this->maskData($subarray, $keysToMask, $path . '/' . $pathKey);
}
}
return $args;
}
/**
* Describes memory usage in real-world units. Intended for use
* with memory_get_usage, etc.
*
* @used-by app/Views/errors/html/error_exception.php
*/
protected static function describeMemory(int $bytes): string
{
helper('number');
return number_to_size($bytes, 2);
}
/**
* Creates a syntax-highlighted version of a PHP file.
*
* @used-by app/Views/errors/html/error_exception.php
*
* @return bool|string
*/
protected static function highlightFile(string $file, int $lineNumber, int $lines = 15)
{
if ($file === '' || ! is_readable($file)) {
return false;
}
// Set our highlight colors:
if (function_exists('ini_set')) {
ini_set('highlight.comment', '#767a7e; font-style: italic');
ini_set('highlight.default', '#c7c7c7');
ini_set('highlight.html', '#06B');
ini_set('highlight.keyword', '#f1ce61;');
ini_set('highlight.string', '#869d6a');
}
try {
$source = file_get_contents($file);
} catch (Throwable) {
return false;
}
$source = str_replace(["\r\n", "\r"], "\n", $source);
$source = explode("\n", highlight_string($source, true));
if (PHP_VERSION_ID < 80300) {
$source = str_replace('<br />', "\n", $source[1]);
$source = explode("\n", str_replace("\r\n", "\n", $source));
} else {
// We have to remove these tags since we're preparing the result
// ourselves and these tags are added manually at the end.
$source = str_replace(['<pre><code>', '</code></pre>'], '', $source);
}
// Get just the part to show
$start = max($lineNumber - (int) round($lines / 2), 0);
// Get just the lines we need to display, while keeping line numbers...
$source = array_splice($source, $start, $lines, true);
// Used to format the line number in the source
$format = '% ' . strlen((string) ($start + $lines)) . 'd';
$out = '';
// Because the highlighting may have an uneven number
// of open and close span tags on one line, we need
// to ensure we can close them all to get the lines
// showing correctly.
$spans = 0;
foreach ($source as $n => $row) {
$spans += substr_count($row, '<span') - substr_count($row, '</span');
$row = str_replace(["\r", "\n"], ['', ''], $row);
if (($n + $start + 1) === $lineNumber) {
preg_match_all('#<[^>]+>#', $row, $tags);
$out .= sprintf(
"<span class='line highlight'><span class='number'>{$format}</span> %s\n</span>%s",
$n + $start + 1,
strip_tags($row),
implode('', $tags[0]),
);
} else {
$out .= sprintf('<span class="line"><span class="number">' . $format . '</span> %s', $n + $start + 1, $row) . "\n";
// We're closing only one span tag we added manually line before,
// so we have to increment $spans count to close this tag later.
$spans++;
}
}
if ($spans > 0) {
$out .= str_repeat('</span>', $spans);
}
return '<pre><code>' . $out . '</code></pre>';
}
/**
* Given an exception and status code will display the error to the client.
*
* @param string|null $viewFile
*/
protected function render(Throwable $exception, int $statusCode, $viewFile = null): void
{
if ($viewFile === null) {
echo 'The error view file was not specified. Cannot display error view.';
exit(1);
}
if (! is_file($viewFile)) {
echo 'The error view file "' . $viewFile . '" was not found. Cannot display error view.';
exit(1);
}
echo (function () use ($exception, $statusCode, $viewFile): string {
$vars = $this->collectVars($exception, $statusCode);
extract($vars, EXTR_SKIP);
// CLI error views output to STDERR/STDOUT, so ob_start() does not work.
ob_start();
include $viewFile;
return ob_get_clean();
})();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Iterator.php | system/Debug/Iterator.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use Closure;
/**
* Iterator for debugging.
*/
class Iterator
{
/**
* Stores the tests that we are to run.
*
* @var array
*/
protected $tests = [];
/**
* Stores the results of each of the tests.
*
* @var array
*/
protected $results = [];
/**
* Adds a test to run.
*
* Tests are simply closures that the user can define any sequence of
* things to happen during the test.
*
* @param Closure(): mixed $closure
*
* @return $this
*/
public function add(string $name, Closure $closure)
{
$name = strtolower($name);
$this->tests[$name] = $closure;
return $this;
}
/**
* Runs through all of the tests that have been added, recording
* time to execute the desired number of iterations, and the approximate
* memory usage used during those iterations.
*
* @return string|null
*/
public function run(int $iterations = 1000, bool $output = true)
{
foreach ($this->tests as $name => $test) {
// clear memory before start
gc_collect_cycles();
$start = microtime(true);
$startMem = $maxMemory = memory_get_usage(true);
for ($i = 0; $i < $iterations; $i++) {
$result = $test();
$maxMemory = max($maxMemory, memory_get_usage(true));
unset($result);
}
$this->results[$name] = [
'time' => microtime(true) - $start,
'memory' => $maxMemory - $startMem,
'n' => $iterations,
];
}
if ($output) {
return $this->getReport();
}
return null;
}
/**
* Get results.
*/
public function getReport(): string
{
if ($this->results === []) {
return 'No results to display.';
}
helper('number');
// Template
$tpl = '<table>
<thead>
<tr>
<td>Test</td>
<td>Time</td>
<td>Memory</td>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>';
$rows = '';
foreach ($this->results as $name => $result) {
$memory = number_to_size($result['memory'], 4);
$rows .= "<tr>
<td>{$name}</td>
<td>" . number_format($result['time'], 4) . "</td>
<td>{$memory}</td>
</tr>";
}
$tpl = str_replace('{rows}', $rows, $tpl);
return $tpl . '<br/>';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/Database.php | system/Debug/Toolbar/Collectors/Database.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
use CodeIgniter\Database\Query;
use CodeIgniter\I18n\Time;
use Config\Toolbar;
/**
* Collector for the Database tab of the Debug Toolbar.
*
* @see \CodeIgniter\Debug\Toolbar\Collectors\DatabaseTest
*/
class Database extends BaseCollector
{
/**
* Whether this collector has timeline data.
*
* @var bool
*/
protected $hasTimeline = true;
/**
* Whether this collector should display its own tab.
*
* @var bool
*/
protected $hasTabContent = true;
/**
* Whether this collector has data for the Vars tab.
*
* @var bool
*/
protected $hasVarData = false;
/**
* The name used to reference this collector in the toolbar.
*
* @var string
*/
protected $title = 'Database';
/**
* Array of database connections.
*
* @var array
*/
protected $connections;
/**
* The query instances that have been collected
* through the DBQuery Event.
*
* @var array
*/
protected static $queries = [];
/**
* Constructor
*/
public function __construct()
{
$this->getConnections();
}
/**
* The static method used during Events to collect
* data.
*
* @internal
*
* @return void
*/
public static function collect(Query $query)
{
$config = config(Toolbar::class);
// Provide default in case it's not set
$max = $config->maxQueries ?: 100;
if (count(static::$queries) < $max) {
$queryString = $query->getQuery();
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
if (! is_cli()) {
// when called in the browser, the first two trace arrays
// are from the DB event trigger, which are unneeded
$backtrace = array_slice($backtrace, 2);
}
static::$queries[] = [
'query' => $query,
'string' => $queryString,
'duplicate' => in_array($queryString, array_column(static::$queries, 'string', null), true),
'trace' => $backtrace,
];
}
}
/**
* Returns timeline data formatted for the toolbar.
*
* @return array The formatted data or an empty array.
*/
protected function formatTimelineData(): array
{
$data = [];
foreach ($this->connections as $alias => $connection) {
// Connection Time
$data[] = [
'name' => 'Connecting to Database: "' . $alias . '"',
'component' => 'Database',
'start' => $connection->getConnectStart(),
'duration' => $connection->getConnectDuration(),
];
}
foreach (static::$queries as $query) {
$data[] = [
'name' => 'Query',
'component' => 'Database',
'start' => $query['query']->getStartTime(true),
'duration' => $query['query']->getDuration(),
'query' => $query['query']->debugToolbarDisplay(),
];
}
return $data;
}
/**
* Returns the data of this collector to be formatted in the toolbar
*/
public function display(): array
{
$data = [];
$data['queries'] = array_map(static function (array $query): array {
$isDuplicate = $query['duplicate'] === true;
$firstNonSystemLine = '';
foreach ($query['trace'] as $index => &$line) {
// simplify file and line
if (isset($line['file'])) {
$line['file'] = clean_path($line['file']) . ':' . $line['line'];
unset($line['line']);
} else {
$line['file'] = '[internal function]';
}
// find the first trace line that does not originate from `system/`
if ($firstNonSystemLine === '' && ! str_contains($line['file'], 'SYSTEMPATH')) {
$firstNonSystemLine = $line['file'];
}
// simplify function call
if (isset($line['class'])) {
$line['function'] = $line['class'] . $line['type'] . $line['function'];
unset($line['class'], $line['type']);
}
if (strrpos($line['function'], '{closure}') === false) {
$line['function'] .= '()';
}
$line['function'] = str_repeat(chr(0xC2) . chr(0xA0), 8) . $line['function'];
// add index numbering padded with nonbreaking space
$indexPadded = str_pad(sprintf('%d', $index + 1), 3, ' ', STR_PAD_LEFT);
$indexPadded = preg_replace('/\s/', chr(0xC2) . chr(0xA0), $indexPadded);
$line['index'] = $indexPadded . str_repeat(chr(0xC2) . chr(0xA0), 4);
}
return [
'hover' => $isDuplicate ? 'This query was called more than once.' : '',
'class' => $isDuplicate ? 'duplicate' : '',
'duration' => ((float) $query['query']->getDuration(5) * 1000) . ' ms',
'sql' => $query['query']->debugToolbarDisplay(),
'trace' => $query['trace'],
'trace-file' => $firstNonSystemLine,
'qid' => md5($query['query'] . Time::now()->format('0.u00 U')),
];
}, static::$queries);
return $data;
}
/**
* Gets the "badge" value for the button.
*/
public function getBadgeValue(): int
{
return count(static::$queries);
}
/**
* Information to be displayed next to the title.
*
* @return string The number of queries (in parentheses) or an empty string.
*/
public function getTitleDetails(): string
{
$this->getConnections();
$queryCount = count(static::$queries);
$uniqueCount = count(array_filter(static::$queries, static fn ($query): bool => $query['duplicate'] === false));
$connectionCount = count($this->connections);
return sprintf(
'(%d total Quer%s, %d %s unique across %d Connection%s)',
$queryCount,
$queryCount > 1 ? 'ies' : 'y',
$uniqueCount,
$uniqueCount > 1 ? 'of them' : '',
$connectionCount,
$connectionCount > 1 ? 's' : '',
);
}
/**
* Does this collector have any data collected?
*/
public function isEmpty(): bool
{
return static::$queries === [];
}
/**
* Display the icon.
*
* Icon from https://icons8.com - 1em package
*/
public function icon(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADMSURBVEhLY6A3YExLSwsA4nIycQDIDIhRWEBqamo/UNF/SjDQjF6ocZgAKPkRiFeEhoYyQ4WIBiA9QAuWAPEHqBAmgLqgHcolGQD1V4DMgHIxwbCxYD+QBqcKINseKo6eWrBioPrtQBq/BcgY5ht0cUIYbBg2AJKkRxCNWkDQgtFUNJwtABr+F6igE8olGQD114HMgHIxAVDyAhA/AlpSA8RYUwoeXAPVex5qHCbIyMgwBCkAuQJIY00huDBUz/mUlBQDqHGjgBjAwAAACexpph6oHSQAAAAASUVORK5CYII=';
}
/**
* Gets the connections from the database config
*/
private function getConnections(): void
{
$this->connections = \Config\Database::getConnections();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/History.php | system/Debug/Toolbar/Collectors/History.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
use DateTime;
/**
* History collector
*
* @see \CodeIgniter\Debug\Toolbar\Collectors\HistoryTest
*/
class History extends BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = false;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = true;
/**
* Whether this collector needs to display
* a label or not.
*
* @var bool
*/
protected $hasLabel = true;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = 'History';
/**
* @var array History files
*/
protected $files = [];
/**
* Specify time limit & file count for debug history.
*
* @param string $current Current history time
* @param int $limit Max history files
*
* @return void
*/
public function setFiles(string $current, int $limit = 20)
{
$filenames = glob(WRITEPATH . 'debugbar/debugbar_*.json');
$files = [];
$counter = 0;
foreach (array_reverse($filenames) as $filename) {
$counter++;
// Oldest files will be deleted
if ($limit >= 0 && $counter > $limit) {
unlink($filename);
continue;
}
// Get the contents of this specific history request
$contents = file_get_contents($filename);
$contents = @json_decode($contents);
if (json_last_error() === JSON_ERROR_NONE) {
preg_match('/debugbar_(.*)\.json$/s', $filename, $time);
$time = sprintf('%.6f', $time[1] ?? 0);
// Debugbar files shown in History Collector
$files[] = [
'time' => $time,
'datetime' => DateTime::createFromFormat('U.u', $time)->format('Y-m-d H:i:s.u'),
'active' => $time === $current,
'status' => $contents->vars->response->statusCode,
'method' => $contents->method,
'url' => $contents->url,
'isAJAX' => $contents->isAJAX ? 'Yes' : 'No',
'contentType' => $contents->vars->response->contentType,
];
}
}
$this->files = $files;
}
/**
* Returns the data of this collector to be formatted in the toolbar
*/
public function display(): array
{
return ['files' => $this->files];
}
/**
* Displays the number of included files as a badge in the tab button.
*/
public function getBadgeValue(): int
{
return count($this->files);
}
/**
* Return true if there are no history files.
*/
public function isEmpty(): bool
{
return $this->files === [];
}
/**
* Display the icon.
*
* Icon from https://icons8.com - 1em package
*/
public function icon(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAJySURBVEhL3ZU7aJNhGIVTpV6i4qCIgkIHxcXLErS4FBwUFNwiCKGhuTYJGaIgnRoo4qRu6iCiiIuIXXTTIkIpuqoFwaGgonUQlC5KafU5ycmNP0lTdPLA4fu+8573/a4/f6hXpFKpwUwmc9fDfweKbk+n07fgEv33TLSbtt/hvwNFT1PsG/zdTE0Gp+GFfD6/2fbVIxqNrqPIRbjg4t/hY8aztcngfDabHXbKyiiXy2vcrcPH8oDCry2FKDrA+Ar6L01E/ypyXzXaARjDGGcoeNxSDZXE0dHRA5VRE5LJ5CFy5jzJuOX2wHRHRnjbklZ6isQ3tIctBaAd4vlK3jLtkOVWqABBXd47jGHLmjTmSScttQV5J+SjfcUweFQEbsjAas5aqoCLXutJl7vtQsAzpRowYqkBinyCC8Vicb2lOih8zoldd0F8RD7qTFiqAnGrAy8stUAvi/hbqDM+YzkAFrLPdR5ZqoLXsd+Bh5YCIH7JniVdquUWxOPxDfboHhrI5XJ7HHhiqQXox+APe/Qk64+gGYVCYZs8cMpSFQj9JOoFzVqqo7k4HIvFYpscCoAjOmLffUsNUGRaQUwDlmofUa34ecsdgXdcXo4wbakBgiUFafXJV8A4DJ/2UrxUKm3E95H8RbjLcgOJRGILhnmCP+FBy5XvwN2uIPcy1AJvWgqC4xm2aU4Xb3lF4I+Tpyf8hRe5w3J7YLymSeA8Z3nSclv4WLRyFdfOjzrUFX0klJUEtZtntCNc+F69cz/FiDzEPtjzmcUMOr83kDQEX6pAJxJfpL3OX22n01YN7SZCoQnaSdoZ+Jz+PZihH3wt/xlCoT9M6nEtmRSPCQAAAABJRU5ErkJggg==';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/Events.php | system/Debug/Toolbar/Collectors/Events.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
/**
* Events collector
*/
class Events extends BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = true;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = true;
/**
* Whether this collector has data that
* should be shown in the Vars tab.
*
* @var bool
*/
protected $hasVarData = false;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = 'Events';
/**
* Child classes should implement this to return the timeline data
* formatted for correct usage.
*/
protected function formatTimelineData(): array
{
$data = [];
$rows = \CodeIgniter\Events\Events::getPerformanceLogs();
foreach ($rows as $info) {
$data[] = [
'name' => 'Event: ' . $info['event'],
'component' => 'Events',
'start' => $info['start'],
'duration' => $info['end'] - $info['start'],
];
}
return $data;
}
/**
* Returns the data of this collector to be formatted in the toolbar
*/
public function display(): array
{
$data = [
'events' => [],
];
foreach (\CodeIgniter\Events\Events::getPerformanceLogs() as $row) {
$key = $row['event'];
if (! array_key_exists($key, $data['events'])) {
$data['events'][$key] = [
'event' => $key,
'duration' => ($row['end'] - $row['start']) * 1000,
'count' => 1,
];
continue;
}
$data['events'][$key]['duration'] += ($row['end'] - $row['start']) * 1000;
$data['events'][$key]['count']++;
}
foreach ($data['events'] as &$row) {
$row['duration'] = number_format($row['duration'], 2);
}
return $data;
}
/**
* Gets the "badge" value for the button.
*/
public function getBadgeValue(): int
{
return count(\CodeIgniter\Events\Events::getPerformanceLogs());
}
/**
* Display the icon.
*
* Icon from https://icons8.com - 1em package
*/
public function icon(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAEASURBVEhL7ZXNDcIwDIVTsRBH1uDQDdquUA6IM1xgCA6MwJUN2hk6AQzAz0vl0ETUxC5VT3zSU5w81/mRMGZysixbFEVR0jSKNt8geQU9aRpFmp/keX6AbjZ5oB74vsaN5lSzA4tLSjpBFxsjeSuRy4d2mDdQTWU7YLbXTNN05mKyovj5KL6B7q3hoy3KwdZxBlT+Ipz+jPHrBqOIynZgcZonoukb/0ckiTHqNvDXtXEAaygRbaB9FvUTjRUHsIYS0QaSp+Dw6wT4hiTmYHOcYZsdLQ2CbXa4ftuuYR4x9vYZgdb4vsFYUdmABMYeukK9/SUme3KMFQ77+Yfzh8eYF8+orDuDWU5LAAAAAElFTkSuQmCC';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/Logs.php | system/Debug/Toolbar/Collectors/Logs.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
/**
* Loags collector
*/
class Logs extends BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = false;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = true;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = 'Logs';
/**
* Our collected data.
*
* @var list<array{level: string, msg: string}>
*/
protected $data;
/**
* Returns the data of this collector to be formatted in the toolbar.
*
* @return array{logs: list<array{level: string, msg: string}>}
*/
public function display(): array
{
return [
'logs' => $this->collectLogs(),
];
}
/**
* Does this collector actually have any data to display?
*/
public function isEmpty(): bool
{
$this->collectLogs();
return $this->data !== [];
}
/**
* Display the icon.
*
* Icon from https://icons8.com - 1em package
*/
public function icon(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACYSURBVEhLYxgFJIHU1FSjtLS0i0D8AYj7gEKMEBkqAaAFF4D4ERCvAFrwH4gDoFIMKSkpFkB+OTEYqgUTACXfA/GqjIwMQyD9H2hRHlQKJFcBEiMGQ7VgAqCBvUgK32dmZspCpagGGNPT0/1BLqeF4bQHQJePpiIwhmrBBEADR1MRfgB0+WgqAmOoFkwANHA0FY0CUgEDAwCQ0PUpNB3kqwAAAABJRU5ErkJggg==';
}
/**
* Ensures the data has been collected.
*
* @return list<array{level: string, msg: string}>
*/
protected function collectLogs()
{
if ($this->data !== []) {
return $this->data;
}
$cache = service('logger')->logCache;
$this->data = $cache ?? [];
return $this->data;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/Config.php | system/Debug/Toolbar/Collectors/Config.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
use CodeIgniter\CodeIgniter;
use Config\App;
/**
* Debug toolbar configuration
*/
class Config
{
/**
* Return toolbar config values as an array.
*/
public static function display(): array
{
$config = config(App::class);
return [
'ciVersion' => CodeIgniter::CI_VERSION,
'phpVersion' => PHP_VERSION,
'phpSAPI' => PHP_SAPI,
'environment' => ENVIRONMENT,
'baseURL' => $config->baseURL,
'timezone' => app_timezone(),
'locale' => service('request')->getLocale(),
'cspEnabled' => $config->CSPEnabled,
];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/Routes.php | system/Debug/Toolbar/Collectors/Routes.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
use CodeIgniter\Router\DefinedRouteCollector;
use ReflectionException;
use ReflectionFunction;
use ReflectionMethod;
/**
* Routes collector
*/
class Routes extends BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = false;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = true;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = 'Routes';
/**
* Returns the data of this collector to be formatted in the toolbar
*
* @return array{
* matchedRoute: list<array{
* directory: string,
* controller: string,
* method: string,
* paramCount: int,
* truePCount: int,
* params: list<array{
* name: string,
* value: mixed
* }>
* }>,
* routes: list<array{
* method: string,
* route: string,
* handler: string
* }>
* }
*
* @throws ReflectionException
*/
public function display(): array
{
$rawRoutes = service('routes', true);
$router = service('router', null, null, true);
// Get our parameters
// Closure routes
if (is_callable($router->controllerName())) {
$method = new ReflectionFunction($router->controllerName());
} else {
try {
$method = new ReflectionMethod($router->controllerName(), $router->methodName());
} catch (ReflectionException) {
try {
// If we're here, the method doesn't exist
// and is likely calculated in _remap.
$method = new ReflectionMethod($router->controllerName(), '_remap');
} catch (ReflectionException) {
// If we're here, page cache is returned. The router is not executed.
return [
'matchedRoute' => [],
'routes' => [],
];
}
}
}
$rawParams = $method->getParameters();
$params = [];
foreach ($rawParams as $key => $param) {
$params[] = [
'name' => '$' . $param->getName() . ' = ',
'value' => $router->params()[$key] ??
' <empty> | default: '
. var_export(
$param->isDefaultValueAvailable() ? $param->getDefaultValue() : null,
true,
),
];
}
$matchedRoute = [
[
'directory' => $router->directory(),
'controller' => $router->controllerName(),
'method' => $router->methodName(),
'paramCount' => count($router->params()),
'truePCount' => count($params),
'params' => $params,
],
];
// Defined Routes
$routes = [];
$definedRouteCollector = new DefinedRouteCollector($rawRoutes);
foreach ($definedRouteCollector->collect() as $route) {
// filter for strings, as callbacks aren't displayable
if ($route['handler'] !== '(Closure)') {
$routes[] = [
'method' => strtoupper($route['method']),
'route' => $route['route'],
'handler' => $route['handler'],
];
}
}
return [
'matchedRoute' => $matchedRoute,
'routes' => $routes,
];
}
/**
* Returns a count of all the routes in the system.
*/
public function getBadgeValue(): int
{
$rawRoutes = service('routes', true);
return count($rawRoutes->getRoutes());
}
/**
* Display the icon.
*
* Icon from https://icons8.com - 1em package
*/
public function icon(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAFDSURBVEhL7ZRNSsNQFIUjVXSiOFEcuQIHDpzpxC0IGYeE/BEInbWlCHEDLsSiuANdhKDjgm6ggtSJ+l25ldrmmTwIgtgDh/t37r1J+16cX0dRFMtpmu5pWAkrvYjjOB7AETzStBFW+inxu3KUJMmhludQpoflS1zXban4LYqiO224h6VLTHr8Z+z8EpIHFF9gG78nDVmW7UgTHKjsCyY98QP+pcq+g8Ku2s8G8X3f3/I8b038WZTp+bO38zxfFd+I6YY6sNUvFlSDk9CRhiAI1jX1I9Cfw7GG1UB8LAuwbU0ZwQnbRDeEN5qqBxZMLtE1ti9LtbREnMIuOXnyIf5rGIb7Wq8HmlZgwYBH7ORTcKH5E4mpjeGt9fBZcHE2GCQ3Vt7oTNPNg+FXLHnSsHkw/FR+Gg2bB8Ptzrst/v6C/wrH+QB+duli6MYJdQAAAABJRU5ErkJggg==';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/BaseCollector.php | system/Debug/Toolbar/Collectors/BaseCollector.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
/**
* Base Toolbar collector
*/
class BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = false;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = false;
/**
* Whether this collector needs to display
* a label or not.
*
* @var bool
*/
protected $hasLabel = false;
/**
* Whether this collector has data that
* should be shown in the Vars tab.
*
* @var bool
*/
protected $hasVarData = false;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = '';
/**
* Gets the Collector's title.
*/
public function getTitle(bool $safe = false): string
{
if ($safe) {
return str_replace(' ', '-', strtolower($this->title));
}
return $this->title;
}
/**
* Returns any information that should be shown next to the title.
*/
public function getTitleDetails(): string
{
return '';
}
/**
* Does this collector need it's own tab?
*/
public function hasTabContent(): bool
{
return (bool) $this->hasTabContent;
}
/**
* Does this collector have a label?
*/
public function hasLabel(): bool
{
return (bool) $this->hasLabel;
}
/**
* Does this collector have information for the timeline?
*/
public function hasTimelineData(): bool
{
return (bool) $this->hasTimeline;
}
/**
* Grabs the data for the timeline, properly formatted,
* or returns an empty array.
*/
public function timelineData(): array
{
if (! $this->hasTimeline) {
return [];
}
return $this->formatTimelineData();
}
/**
* Does this Collector have data that should be shown in the
* 'Vars' tab?
*/
public function hasVarData(): bool
{
return (bool) $this->hasVarData;
}
/**
* Gets a collection of data that should be shown in the 'Vars' tab.
* The format is an array of sections, each with their own array
* of key/value pairs:
*
* $data = [
* 'section 1' => [
* 'foo' => 'bar,
* 'bar' => 'baz'
* ],
* 'section 2' => [
* 'foo' => 'bar,
* 'bar' => 'baz'
* ],
* ];
*
* @return array|null
*/
public function getVarData()
{
return null;
}
/**
* Child classes should implement this to return the timeline data
* formatted for correct usage.
*
* Timeline data should be formatted into arrays that look like:
*
* [
* 'name' => 'Database::Query',
* 'component' => 'Database',
* 'start' => 10 // milliseconds
* 'duration' => 15 // milliseconds
* ]
*/
protected function formatTimelineData(): array
{
return [];
}
/**
* Returns the data of this collector to be formatted in the toolbar
*
* @return array|string
*/
public function display()
{
return [];
}
/**
* This makes nicer looking paths for the error output.
*
* @deprecated Use the dedicated `clean_path()` function.
*/
public function cleanPath(string $file): string
{
return clean_path($file);
}
/**
* Gets the "badge" value for the button.
*
* @return int|null
*/
public function getBadgeValue()
{
return null;
}
/**
* Does this collector have any data collected?
*
* If not, then the toolbar button won't get shown.
*/
public function isEmpty(): bool
{
return false;
}
/**
* Returns the HTML to display the icon. Should either
* be SVG, or a base-64 encoded.
*
* Recommended dimensions are 24px x 24px
*/
public function icon(): string
{
return '';
}
/**
* Return settings as an array.
*/
public function getAsArray(): array
{
return [
'title' => $this->getTitle(),
'titleSafe' => $this->getTitle(true),
'titleDetails' => $this->getTitleDetails(),
'display' => $this->display(),
'badgeValue' => $this->getBadgeValue(),
'isEmpty' => $this->isEmpty(),
'hasTabContent' => $this->hasTabContent(),
'hasLabel' => $this->hasLabel(),
'icon' => $this->icon(),
'hasTimelineData' => $this->hasTimelineData(),
'timelineData' => $this->timelineData(),
];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/Timers.php | system/Debug/Toolbar/Collectors/Timers.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
/**
* Timers collector
*/
class Timers extends BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = true;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = false;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = 'Timers';
/**
* Child classes should implement this to return the timeline data
* formatted for correct usage.
*/
protected function formatTimelineData(): array
{
$data = [];
$benchmark = service('timer', true);
$rows = $benchmark->getTimers(6);
foreach ($rows as $name => $info) {
if ($name === 'total_execution') {
continue;
}
$data[] = [
'name' => ucwords(str_replace('_', ' ', $name)),
'component' => 'Timer',
'start' => $info['start'],
'duration' => $info['end'] - $info['start'],
];
}
return $data;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/Views.php | system/Debug/Toolbar/Collectors/Views.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
use CodeIgniter\View\RendererInterface;
/**
* Views collector
*/
class Views extends BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = true;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = false;
/**
* Whether this collector needs to display
* a label or not.
*
* @var bool
*/
protected $hasLabel = true;
/**
* Whether this collector has data that
* should be shown in the Vars tab.
*
* @var bool
*/
protected $hasVarData = true;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = 'Views';
/**
* Instance of the shared Renderer service
*
* @var RendererInterface|null
*/
protected $viewer;
/**
* Views counter
*
* @var array
*/
protected $views = [];
private function initViewer(): void
{
$this->viewer ??= service('renderer');
}
/**
* Child classes should implement this to return the timeline data
* formatted for correct usage.
*/
protected function formatTimelineData(): array
{
$this->initViewer();
$data = [];
$rows = $this->viewer->getPerformanceData();
foreach ($rows as $info) {
$data[] = [
'name' => 'View: ' . $info['view'],
'component' => 'Views',
'start' => $info['start'],
'duration' => $info['end'] - $info['start'],
];
}
return $data;
}
/**
* Gets a collection of data that should be shown in the 'Vars' tab.
* The format is an array of sections, each with their own array
* of key/value pairs:
*
* $data = [
* 'section 1' => [
* 'foo' => 'bar,
* 'bar' => 'baz'
* ],
* 'section 2' => [
* 'foo' => 'bar,
* 'bar' => 'baz'
* ],
* ];
*/
public function getVarData(): array
{
$this->initViewer();
return [
'View Data' => $this->viewer->getData(),
];
}
/**
* Returns a count of all views.
*/
public function getBadgeValue(): int
{
$this->initViewer();
return count($this->viewer->getPerformanceData());
}
/**
* Display the icon.
*
* Icon from https://icons8.com - 1em package
*/
public function icon(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADeSURBVEhL7ZSxDcIwEEWNYA0YgGmgyAaJLTcUaaBzQQEVjMEabBQxAdw53zTHiThEovGTfnE/9rsoRUxhKLOmaa6Uh7X2+UvguLCzVxN1XW9x4EYHzik033Hp3X0LO+DaQG8MDQcuq6qao4qkHuMgQggLvkPLjqh00ZgFDBacMJYFkuwFlH1mshdkZ5JPJERA9JpI6xNCBESvibQ+IURA9JpI6xNCBESvibQ+IURA9DTsuHTOrVFFxixgB/eUFlU8uKJ0eDBFOu/9EvoeKnlJS2/08Tc8NOwQ8sIfMeYFjqKDjdU2sp4AAAAASUVORK5CYII=';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Collectors/Files.php | system/Debug/Toolbar/Collectors/Files.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
/**
* Files collector
*/
class Files extends BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = false;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = true;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = 'Files';
/**
* Returns any information that should be shown next to the title.
*/
public function getTitleDetails(): string
{
return '( ' . count(get_included_files()) . ' )';
}
/**
* Returns the data of this collector to be formatted in the toolbar
*/
public function display(): array
{
$rawFiles = get_included_files();
$coreFiles = [];
$userFiles = [];
foreach ($rawFiles as $file) {
$path = clean_path($file);
if (str_contains($path, 'SYSTEMPATH')) {
$coreFiles[] = [
'path' => $path,
'name' => basename($file),
];
} else {
$userFiles[] = [
'path' => $path,
'name' => basename($file),
];
}
}
sort($userFiles);
sort($coreFiles);
return [
'coreFiles' => $coreFiles,
'userFiles' => $userFiles,
];
}
/**
* Displays the number of included files as a badge in the tab button.
*/
public function getBadgeValue(): int
{
return count(get_included_files());
}
/**
* Display the icon.
*
* Icon from https://icons8.com - 1em package
*/
public function icon(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGBSURBVEhL7ZQ9S8NQGIVTBQUncfMfCO4uLgoKbuKQOWg+OkXERRE1IAXrIHbVDrqIDuLiJgj+gro7S3dnpfq88b1FMTE3VZx64HBzzvvZWxKnj15QCcPwCD5HUfSWR+JtzgmtsUcQBEva5IIm9SwSu+95CAWbUuy67qBa32ByZEDpIaZYZSZMjjQuPcQUq8yEyYEb8FSerYeQVGbAFzJkX1PyQWLhgCz0BxTCekC1Wp0hsa6yokzhed4oje6Iz6rlJEkyIKfUEFtITVtQdAibn5rMyaYsMS+a5wTv8qeXMhcU16QZbKgl3hbs+L4/pnpdc87MElZgq10p5DxGdq8I7xrvUWUKvG3NbSK7ubngYzdJwSsF7TiOh9VOgfcEz1UayNe3JUPM1RWC5GXYgTfc75B4NBmXJnAtTfpABX0iPvEd9ezALwkplCFXcr9styiNOKc1RRZpaPM9tcqBwlWzGY1qPL9wjqRBgF5BH6j8HWh2S7MHlX8PrmbK+k/8PzjOOzx1D3i1pKTTAAAAAElFTkSuQmCC';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Debug/Toolbar/Views/toolbar.tpl.php | system/Debug/Toolbar/Views/toolbar.tpl.php | <?php declare(strict_types=1);
use CodeIgniter\Debug\Toolbar;
use CodeIgniter\View\Parser;
/**
* @var Toolbar $this
* @var int $totalTime
* @var int $totalMemory
* @var string $url
* @var string $method
* @var bool $isAJAX
* @var int $startTime
* @var int $totalTime
* @var int $totalMemory
* @var float $segmentDuration
* @var int $segmentCount
* @var string $CI_VERSION
* @var array $collectors
* @var array $vars
* @var array $styles
* @var Parser $parser
*/
?>
<style>
<?= preg_replace('#[\r\n\t ]+#', ' ', file_get_contents(__DIR__ . '/toolbar.css')) ?>
</style>
<script id="toolbar_js">
var ciSiteURL = "<?= rtrim(site_url(), '/') ?>"
<?= file_get_contents(__DIR__ . '/toolbar.js') ?>
</script>
<div id="debug-icon" class="debug-bar-ndisplay">
<a id="debug-icon-link">
<svg xmlns="http://www.w3.org/2000/svg" version="1.0" viewBox="0 0 155 200"><defs/><path fill="#dd4814" d="M73.7 3.7c2.2 7.9-.7 18.5-7.8 29-1.8 2.6-10.7 12.2-19.7 21.3-23.9 24-33.6 37.1-40.3 54.4-7.9 20.6-7.8 40.8.5 58.2C12.8 180 27.6 193 42.5 198l6 2-3-2.2c-21-15.2-22.9-38.7-4.8-58.8 2.5-2.7 4.8-5 5.1-5 .4 0 .7 2.7.7 6.1 0 5.7.2 6.2 3.7 9.5 3 2.7 4.6 3.4 7.8 3.4 5.6 0 9.9-2.4 11.6-6.5 2.9-6.9 1.6-12-5-20.5-10.5-13.4-11.7-23.3-4.3-34.7l3.1-4.8.7 4.7c1.3 8.2 5.8 12.9 25 25.8 20.9 14.1 30.6 26.1 32.8 40.5 1.1 7.2-.1 16.1-3.1 21.8-2.7 5.3-11.2 14.3-16.5 17.4-2.4 1.4-4.3 2.6-4.3 2.8 0 .2 2.4-.4 5.3-1.4 24.1-8.3 42.7-27.1 48.2-48.6 1.9-7.6 1.9-20.2-.1-28.5-3.5-15.2-14.6-30.5-29.9-41.2l-7-4.9-.6 3.3c-.8 4.8-2.6 7.6-5.9 9.3-4.5 2.3-10.3 1.9-13.8-1-6.7-5.7-7.8-14.6-3.7-30.5 3-11.6 3.2-20.6.5-29.1C88.3 18 80.6 6.3 74.8 2.2 73.1.9 73 1 73.7 3.7z"/></svg>
</a>
</div>
<div id="debug-bar">
<div class="toolbar">
<span id="toolbar-position">↕</span>
<span id="toolbar-theme">🔅</span>
<span id="hot-reload-btn" class="ci-label">
<a id="debug-hot-reload" title="Toggle Hot Reload">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAABNklEQVR4nN2US04CQRCGv/DaiBxEvYWuBRPDKSCIXsCdcg0ULqTI8xIGN7JwTCU/ScV5tTO64Us6maSq/7+nuqvgkLgHopTl+QAWwBToAg3+wMTzM7YBrihp4jkCToEB8OJyRkCFAB5yDDxVoAd8OpNMOkrcAeMAgz3nzsQ0EqkDayXZqXy5Qugrdy2tGNdKeNWv40xCqGpvJK0YEwXt8ooylMZzUnCh4EkJgzNpmFaMrYLNEgbH0thmGVhSUVrSeE8KLv+7RBMFb0oY3EnDeihGN+WZhmJ7ZlnPtKHB5RvtNwy0d5XWaGgqRmp7a/9QLjRevoDLvOSRM+nnlKumk++0xwZlLhVnEulOhnohTS37vnU1t5M/ho7rPR03/LKW1bxNQep6ETZb5mpGW2/Ak2KpF3oYfAPX9Xpc671kqwAAAABJRU5ErkJggg==" />
</a>
</span>
<span class="ci-label">
<a data-tab="ci-timeline">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAD7SURBVEhLY6ArSEtLK09NTbWHcvGC9PR0BaDaQiAdUl9fzwQVxg+AFvwHamqHcnGCpKQkeaDa9yD1UD09UCn8AKaBWJySkmIApFehi0ONwwRQBceBLurAh4FqFoHUAtkrgPgREN+ByYEw1DhMANVEMIhAYQ5U1wtU/wmILwLZRlAp/IBYC8gGw88CaFj3A/FnIL4ETDXGUCnyANSC/UC6HIpnQMXAqQXIvo0khxNDjcMEQEmU9AzDuNI7Lgw1DhOAJIEuhQcRKMcC+e+QNHdDpcgD6BaAANSSQqBcENFlDi6AzQKqgkFlwWhxjVI8o2OgmkFaXI8CTMDAAAAxd1O4FzLMaAAAAABJRU5ErkJggg==">
<span class="hide-sm"><?= $totalTime ?> ms <?= $totalMemory ?> MB</span>
</a>
</span>
<?php foreach ($collectors as $c) : ?>
<?php if (! $c['isEmpty'] && ($c['hasTabContent'] || $c['hasLabel'])) : ?>
<span class="ci-label">
<a data-tab="ci-<?= $c['titleSafe'] ?>">
<img src="<?= $c['icon'] ?>">
<span class="hide-sm">
<?= $c['title'] ?>
<?php if ($c['badgeValue'] !== null) : ?>
<span class="badge"><?= $c['badgeValue'] ?></span>
<?php endif ?>
</span>
</a>
</span>
<?php endif ?>
<?php endforeach ?>
<span class="ci-label">
<a data-tab="ci-vars">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACLSURBVEhLYxgFJIHU1NSraWlp/6H4T0pKSjRUijoAyXAwBlrYDpViAFpmARQrJwZDtWACoCROC4D8CnR5XBiqBRMADfyNprgRKkUdAApzoCUdUNwE5MtApYYIALp6NBWBMVQLJgAaOJqK8AOgq+mSio6DggjEBtLUT0UwQ5HZIADkj6aiUTAggIEBANAEDa/lkCRlAAAAAElFTkSuQmCC">
<span class="hide-sm">Vars</span>
</a>
</span>
<h1>
<span class="ci-label">
<a data-tab="ci-config">
<svg xmlns="http://www.w3.org/2000/svg" version="1.0" viewBox="0 0 155 200"><defs/><path fill="#dd4814" d="M73.7 3.7c2.2 7.9-.7 18.5-7.8 29-1.8 2.6-10.7 12.2-19.7 21.3-23.9 24-33.6 37.1-40.3 54.4-7.9 20.6-7.8 40.8.5 58.2C12.8 180 27.6 193 42.5 198l6 2-3-2.2c-21-15.2-22.9-38.7-4.8-58.8 2.5-2.7 4.8-5 5.1-5 .4 0 .7 2.7.7 6.1 0 5.7.2 6.2 3.7 9.5 3 2.7 4.6 3.4 7.8 3.4 5.6 0 9.9-2.4 11.6-6.5 2.9-6.9 1.6-12-5-20.5-10.5-13.4-11.7-23.3-4.3-34.7l3.1-4.8.7 4.7c1.3 8.2 5.8 12.9 25 25.8 20.9 14.1 30.6 26.1 32.8 40.5 1.1 7.2-.1 16.1-3.1 21.8-2.7 5.3-11.2 14.3-16.5 17.4-2.4 1.4-4.3 2.6-4.3 2.8 0 .2 2.4-.4 5.3-1.4 24.1-8.3 42.7-27.1 48.2-48.6 1.9-7.6 1.9-20.2-.1-28.5-3.5-15.2-14.6-30.5-29.9-41.2l-7-4.9-.6 3.3c-.8 4.8-2.6 7.6-5.9 9.3-4.5 2.3-10.3 1.9-13.8-1-6.7-5.7-7.8-14.6-3.7-30.5 3-11.6 3.2-20.6.5-29.1C88.3 18 80.6 6.3 74.8 2.2 73.1.9 73 1 73.7 3.7z"/></svg>
<?= $CI_VERSION ?>
</a>
</span>
</h1>
<!-- Open/Close Toggle -->
<a id="debug-bar-link" role="button" title="Open/Close">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAEPSURBVEhL7ZVLDoJAEEThRuoGDwSEG+jCuFU34s3AK3APP1VDDSGMqI1xx0s6M/2rnlHEaMZElmWrPM+vsDvsYbQ7+us0TReSC2EBrEHxCevRYuppYLXkQpC8sVCuGfTvqSE3hFdFwUGuGfRvqSE35NUAfKZrbQNQm2jrMA+gOK+M+FmhDsRL5voHMA8gFGecq0JOXLWlQg7E7AMIxZnjOiZOEJ82gFCcedUE4gS56QP8yf8ywItz7e+RituKlkkDBoIOH4Nd4HZD4NsGYJ/Abn1xEVOcuZ8f0zc/tHiYmzTAwscBvDIK/veyQ9K/rnewjdF26q0kF1IUxZIFPAVW98x/a+qp8L2M/+HMhETRE6S8TxpZ7KGXAAAAAElFTkSuQmCC">
</a>
</div>
<!-- Timeline -->
<div id="ci-timeline" class="tab">
<table class="timeline">
<thead>
<tr>
<th class="debug-bar-width30">NAME</th>
<th class="debug-bar-width10">COMPONENT</th>
<th class="debug-bar-width10">DURATION</th>
<?php for ($i = 0; $i < $segmentCount; $i++) : ?>
<th><?= $i * $segmentDuration ?> ms</th>
<?php endfor ?>
</tr>
</thead>
<tbody>
<?= $this->renderTimeline($collectors, $startTime, $segmentCount, $segmentDuration, $styles) ?>
</tbody>
</table>
</div>
<!-- Collector-provided Tabs -->
<?php foreach ($collectors as $c) : ?>
<?php if (! $c['isEmpty']) : ?>
<?php if ($c['hasTabContent']) : ?>
<div id="ci-<?= $c['titleSafe'] ?>" class="tab">
<h2><?= $c['title'] ?> <span><?= $c['titleDetails'] ?></span></h2>
<?= is_string($c['display']) ? $c['display'] : $parser->setData($c['display'])->render("_{$c['titleSafe']}.tpl") ?>
</div>
<?php endif ?>
<?php endif ?>
<?php endforeach ?>
<!-- In & Out -->
<div id="ci-vars" class="tab">
<!-- VarData from Collectors -->
<?php if (isset($vars['varData'])) : ?>
<?php foreach ($vars['varData'] as $heading => $items) : ?>
<a class="debug-bar-vars" data-toggle="datatable" data-table="<?= strtolower(str_replace(' ', '-', $heading)) ?>">
<h2><?= $heading ?></h2>
</a>
<?php if (is_array($items)) : ?>
<table id="<?= strtolower(str_replace(' ', '-', $heading . '_table')) ?>">
<tbody>
<?php foreach ($items as $key => $value) : ?>
<tr>
<td><?= $key ?></td>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php else: ?>
<p class="muted">No data to display.</p>
<?php endif ?>
<?php endforeach ?>
<?php endif ?>
<!-- Session -->
<a class="debug-bar-vars" data-toggle="datatable" data-table="session">
<h2>Session User Data</h2>
</a>
<?php if (isset($vars['session'])) : ?>
<?php if (! empty($vars['session'])) : ?>
<table id="session_table">
<tbody>
<?php foreach ($vars['session'] as $key => $value) : ?>
<tr>
<td><?= $key ?></td>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php else : ?>
<p class="muted">No data to display.</p>
<?php endif ?>
<?php else : ?>
<p class="muted">Session doesn't seem to be active.</p>
<?php endif ?>
<h2>Request <span>( <?= $vars['request'] ?> )</span></h2>
<?php if (isset($vars['get']) && $get = $vars['get']) : ?>
<a class="debug-bar-vars" data-toggle="datatable" data-table="get">
<h3>$_GET</h3>
</a>
<table id="get_table">
<tbody>
<?php foreach ($get as $name => $value) : ?>
<tr>
<td><?= $name ?></td>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif ?>
<?php if (isset($vars['post']) && $post = $vars['post']) : ?>
<a class="debug-bar-vars" data-toggle="datatable" data-table="post">
<h3>$_POST</h3>
</a>
<table id="post_table">
<tbody>
<?php foreach ($post as $name => $value) : ?>
<tr>
<td><?= $name ?></td>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif ?>
<?php if (isset($vars['headers']) && $headers = $vars['headers']) : ?>
<a class="debug-bar-vars" data-toggle="datatable" data-table="request_headers">
<h3>Headers</h3>
</a>
<table id="request_headers_table">
<tbody>
<?php foreach ($headers as $header => $value) : ?>
<tr>
<td><?= $header ?></td>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif ?>
<?php if (isset($vars['cookies']) && $cookies = $vars['cookies']) : ?>
<a class="debug-bar-vars" data-toggle="datatable" data-table="cookie">
<h3>Cookies</h3>
</a>
<table id="cookie_table">
<tbody>
<?php foreach ($cookies as $name => $value) : ?>
<tr>
<td><?= $name ?></td>
<td><?= is_array($value) ? print_r($value, true) : $value ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif ?>
<h2>Response
<span>( <?= $vars['response']['statusCode'] . ' - ' . $vars['response']['reason'] ?> )</span>
</h2>
<?php if (isset($vars['response']['headers']) && $headers = $vars['response']['headers']) : ?>
<a class="debug-bar-vars" data-toggle="datatable" data-table="response_headers">
<h3>Headers</h3>
</a>
<table id="response_headers_table">
<tbody>
<?php foreach ($headers as $header => $value) : ?>
<tr>
<td><?= $header ?></td>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif ?>
</div>
<!-- Config Values -->
<div id="ci-config" class="tab">
<h2>System Configuration</h2>
<?= $parser->setData($config)->render('_config.tpl') ?>
</div>
</div>
<style>
<?php foreach ($styles as $name => $style): ?>
<?= sprintf(".%s { %s }\n", $name, $style) ?>
<?php endforeach ?>
</style>
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataConverter/DataConverter.php | system/DataConverter/DataConverter.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\DataConverter;
use Closure;
use CodeIgniter\DataCaster\DataCaster;
use CodeIgniter\Entity\Entity;
/**
* PHP data <==> DataSource data converter
*
* @template TEntity of object
*
* @see \CodeIgniter\DataConverter\DataConverterTest
*/
final class DataConverter
{
/**
* The data caster.
*/
private readonly DataCaster $dataCaster;
/**
* @param array<string, class-string> $castHandlers Custom convert handlers
*
* @internal
*/
public function __construct(
/**
* Type definitions.
*
* @var array<string, string> [column => type]
*/
private readonly array $types,
array $castHandlers = [],
/**
* Helper object.
*/
private readonly ?object $helper = null,
/**
* Static reconstruct method name or closure to reconstruct an object.
* Used by reconstruct().
*
* @var (Closure(array<string, mixed>): TEntity)|string|null
*/
private readonly Closure|string|null $reconstructor = 'reconstruct',
/**
* Extract method name or closure to extract data from an object.
* Used by extract().
*
* @var (Closure(TEntity, bool, bool): array<string, mixed>)|string|null
*/
private readonly Closure|string|null $extractor = null,
) {
$this->dataCaster = new DataCaster($castHandlers, $types, $this->helper);
}
/**
* Converts data from DataSource to PHP array with specified type values.
*
* @param array<string, mixed> $data DataSource data
*
* @internal
*/
public function fromDataSource(array $data): array
{
foreach (array_keys($this->types) as $field) {
if (array_key_exists($field, $data)) {
$data[$field] = $this->dataCaster->castAs($data[$field], $field, 'get');
}
}
return $data;
}
/**
* Converts PHP array to data for DataSource field types.
*
* @param array<string, mixed> $phpData PHP data
*
* @internal
*/
public function toDataSource(array $phpData): array
{
foreach (array_keys($this->types) as $field) {
if (array_key_exists($field, $phpData)) {
$phpData[$field] = $this->dataCaster->castAs($phpData[$field], $field, 'set');
}
}
return $phpData;
}
/**
* Takes database data array and creates a specified type object.
*
* @param class-string<TEntity> $classname
* @param array<string, mixed> $row Raw data from database
*
* @return TEntity
*
* @internal
*/
public function reconstruct(string $classname, array $row): object
{
$phpData = $this->fromDataSource($row);
// Use static reconstruct method.
if (is_string($this->reconstructor) && method_exists($classname, $this->reconstructor)) {
$method = $this->reconstructor;
return $classname::$method($phpData);
}
// Use closure to reconstruct.
if ($this->reconstructor instanceof Closure) {
$closure = $this->reconstructor;
return $closure($phpData);
}
$classObj = new $classname();
if ($classObj instanceof Entity) {
$classObj->injectRawData($phpData);
$classObj->syncOriginal();
return $classObj;
}
$classSet = Closure::bind(function ($key, $value): void {
$this->{$key} = $value;
}, $classObj, $classname);
foreach ($phpData as $key => $value) {
$classSet($key, $value);
}
return $classObj;
}
/**
* Takes an object and extract properties as an array.
*
* @param bool $onlyChanged Only for CodeIgniter's Entity. If true, only returns
* values that have changed since object creation.
* @param bool $recursive Only for CodeIgniter's Entity. If true, inner
* entities will be cast as array as well.
*
* @return array<string, mixed>
*
* @internal
*/
public function extract(object $object, bool $onlyChanged = false, bool $recursive = false): array
{
// Use extractor method.
if (is_string($this->extractor) && method_exists($object, $this->extractor)) {
$method = $this->extractor;
$row = $object->{$method}($onlyChanged, $recursive);
return $this->toDataSource($row);
}
// Use closure to extract.
if ($this->extractor instanceof Closure) {
$closure = $this->extractor;
$row = $closure($object, $onlyChanged, $recursive);
return $this->toDataSource($row);
}
if ($object instanceof Entity) {
$row = $object->toRawArray($onlyChanged, $recursive);
return $this->toDataSource($row);
}
$array = (array) $object;
$row = [];
foreach ($array as $key => $value) {
$key = preg_replace('/\000.*\000/', '', $key);
$row[$key] = $value;
}
return $this->toDataSource($row);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/CriticalError.php | system/Exceptions/CriticalError.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Error: Critical conditions, like component unavailable, etc.
*/
class CriticalError extends RuntimeException
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/TestException.php | system/Exceptions/TestException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Exception thrown when there is an error with the test code.
*/
class TestException extends LogicException
{
use DebugTraceableTrait;
/**
* @return static
*/
public static function forInvalidMockClass(string $name)
{
return new static(lang('Test.invalidMockClass', [$name]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/PageNotFoundException.php | system/Exceptions/PageNotFoundException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
class PageNotFoundException extends RuntimeException implements HTTPExceptionInterface
{
use DebugTraceableTrait;
/**
* HTTP status code
*
* @var int
*/
protected $code = 404;
/**
* @return static
*/
public static function forPageNotFound(?string $message = null)
{
return new static($message ?? self::lang('HTTP.pageNotFound'));
}
/**
* @return static
*/
public static function forEmptyController()
{
return new static(self::lang('HTTP.emptyController'));
}
/**
* @return static
*/
public static function forControllerNotFound(string $controller, string $method)
{
return new static(self::lang('HTTP.controllerNotFound', [$controller, $method]));
}
/**
* @return static
*/
public static function forMethodNotFound(string $method)
{
return new static(self::lang('HTTP.methodNotFound', [$method]));
}
/**
* @return static
*/
public static function forLocaleNotSupported(string $locale)
{
return new static(self::lang('HTTP.localeNotSupported', [$locale]));
}
/**
* Get translated system message
*
* Use a non-shared Language instance in the Services.
* If a shared instance is created, the Language will
* have the current locale, so even if users call
* `$this->request->setLocale()` in the controller afterwards,
* the Language locale will not be changed.
*/
private static function lang(string $line, array $args = []): string
{
$lang = service('language', null, false);
return $lang->getLine($line, $args);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/BadFunctionCallException.php | system/Exceptions/BadFunctionCallException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Exception thrown if a function is called in the wrong way, or the function
* does not exist.
*/
class BadFunctionCallException extends \BadFunctionCallException implements ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/HasExitCodeInterface.php | system/Exceptions/HasExitCodeInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Interface for Exceptions that has exception code as exit code.
*/
interface HasExitCodeInterface extends ExceptionInterface
{
/**
* Returns exit status code.
*/
public function getExitCode(): int;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/ExceptionInterface.php | system/Exceptions/ExceptionInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Provides a domain-level interface for broad capture
* of all framework-related exceptions.
*
* catch (\CodeIgniter\Exceptions\ExceptionInterface) { ... }
*/
interface ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/ModelException.php | system/Exceptions/ModelException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Model Exceptions.
*/
class ModelException extends FrameworkException
{
/**
* @return static
*/
public static function forNoPrimaryKey(string $modelName)
{
return new static(lang('Database.noPrimaryKey', [$modelName]));
}
/**
* @return static
*/
public static function forNoDateFormat(string $modelName)
{
return new static(lang('Database.noDateFormat', [$modelName]));
}
/**
* @return static
*/
public static function forMethodNotAvailable(string $modelName, string $methodName)
{
return new static(lang('Database.methodNotAvailable', [$modelName, $methodName]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/FrameworkException.php | system/Exceptions/FrameworkException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Class FrameworkException
*
* A collection of exceptions thrown by the framework
* that can only be determined at run time.
*/
class FrameworkException extends RuntimeException
{
use DebugTraceableTrait;
/**
* @return static
*/
public static function forEnabledZlibOutputCompression()
{
return new static(lang('Core.enabledZlibOutputCompression'));
}
/**
* @return static
*/
public static function forInvalidFile(string $path)
{
return new static(lang('Core.invalidFile', [$path]));
}
/**
* @return static
*/
public static function forInvalidDirectory(string $path)
{
return new static(lang('Core.invalidDirectory', [$path]));
}
/**
* @return static
*/
public static function forCopyError(string $path)
{
return new static(lang('Core.copyError', [$path]));
}
/**
* @return static
*
* @deprecated 4.5.0 No longer used.
*/
public static function forMissingExtension(string $extension)
{
if (str_contains($extension, 'intl')) {
// @codeCoverageIgnoreStart
$message = sprintf(
'The framework needs the following extension(s) installed and loaded: %s.',
$extension,
);
// @codeCoverageIgnoreEnd
} else {
$message = lang('Core.missingExtension', [$extension]);
}
return new static($message);
}
/**
* @return static
*/
public static function forNoHandlers(string $class)
{
return new static(lang('Core.noHandlers', [$class]));
}
/**
* @return static
*/
public static function forFabricatorCreateFailed(string $table, string $reason)
{
return new static(lang('Fabricator.createFailed', [$table, $reason]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/ConfigException.php | system/Exceptions/ConfigException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Exception thrown if the value of the Config class is invalid or the type is
* incorrect.
*/
class ConfigException extends RuntimeException implements HasExitCodeInterface
{
use DebugTraceableTrait;
public function getExitCode(): int
{
return EXIT_CONFIG;
}
/**
* @return static
*/
public static function forDisabledMigrations()
{
return new static(lang('Migrations.disabled'));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/LogicException.php | system/Exceptions/LogicException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Exception that represents error in the program logic.
*/
class LogicException extends \LogicException implements ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/RuntimeException.php | system/Exceptions/RuntimeException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Exception thrown if an error which can only be found on runtime occurs.
*/
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/BadMethodCallException.php | system/Exceptions/BadMethodCallException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Exception thrown if a method is called in the wrong way, or the method
* does not exist.
*/
class BadMethodCallException extends \BadMethodCallException implements ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/HTTPExceptionInterface.php | system/Exceptions/HTTPExceptionInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Interface for Exceptions that has exception code as HTTP status code.
*/
interface HTTPExceptionInterface extends ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/InvalidArgumentException.php | system/Exceptions/InvalidArgumentException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Exception thrown if an argument is not of the expected type.
*/
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/DownloadException.php | system/Exceptions/DownloadException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
/**
* Class DownloadException
*/
class DownloadException extends RuntimeException
{
use DebugTraceableTrait;
/**
* @return static
*/
public static function forCannotSetFilePath(string $path)
{
return new static(lang('HTTP.cannotSetFilepath', [$path]));
}
/**
* @return static
*/
public static function forCannotSetBinary()
{
return new static(lang('HTTP.cannotSetBinary'));
}
/**
* @return static
*/
public static function forNotFoundDownloadSource()
{
return new static(lang('HTTP.notFoundDownloadSource'));
}
/**
* @deprecated Since v4.5.6
*
* @return static
*/
public static function forCannotSetCache()
{
return new static(lang('HTTP.cannotSetCache'));
}
/**
* @return static
*/
public static function forCannotSetStatusCode(int $code, string $reason)
{
return new static(lang('HTTP.cannotSetStatusCode', [$code, $reason]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Exceptions/DebugTraceableTrait.php | system/Exceptions/DebugTraceableTrait.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Exceptions;
use Throwable;
/**
* This trait provides framework exceptions the ability to pinpoint
* accurately where the exception was raised rather than instantiated.
*
* This is used primarily for factory-instantiated exceptions.
*/
trait DebugTraceableTrait
{
/**
* Tweaks the exception's constructor to assign the file/line to where
* it is actually raised rather than were it is instantiated.
*/
final public function __construct(string $message = '', int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$trace = $this->getTrace()[0];
if (isset($trace['class']) && $trace['class'] === static::class) {
[
'line' => $this->line,
'file' => $this->file,
] = $trace;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/I18n/Time.php | system/I18n/Time.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\I18n;
use DateTimeImmutable;
use Stringable;
/**
* A localized date/time package inspired
* by Nesbot/Carbon and CakePHP/Chronos.
*
* Requires the intl PHP extension.
*
* @property-read int $age
* @property-read string $day
* @property-read string $dayOfWeek
* @property-read string $dayOfYear
* @property-read bool $dst
* @property-read string $hour
* @property-read bool $local
* @property-read string $minute
* @property-read string $month
* @property-read string $quarter
* @property-read string $second
* @property-read int $timestamp
* @property-read bool $utc
* @property-read string $weekOfMonth
* @property-read string $weekOfYear
* @property-read string $year
*
* @phpstan-consistent-constructor
*
* @see \CodeIgniter\I18n\TimeTest
*/
class Time extends DateTimeImmutable implements Stringable
{
use TimeTrait;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/I18n/TimeTrait.php | system/I18n/TimeTrait.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\I18n;
use CodeIgniter\I18n\Exceptions\I18nException;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use Exception;
use IntlCalendar;
use IntlDateFormatter;
use Locale;
use ReturnTypeWillChange;
/**
* This trait has properties and methods for Time and TimeLegacy.
* When TimeLegacy is removed, this will be in Time.
*/
trait TimeTrait
{
/**
* @var DateTimeZone|string
*/
protected $timezone;
/**
* @var string
*/
protected $locale;
/**
* Format to use when displaying datetime through __toString
*
* @var string
*/
protected $toStringFormat = 'yyyy-MM-dd HH:mm:ss';
/**
* Used to check time string to determine if it is relative time or not....
*
* @var string
*/
protected static $relativePattern = '/this|next|last|tomorrow|yesterday|midnight|today|[+-]|first|last|ago/i';
/**
* @var DateTimeInterface|static|null
*/
protected static $testNow;
// --------------------------------------------------------------------
// Constructors
// --------------------------------------------------------------------
/**
* Time constructor.
*
* @param DateTimeZone|string|null $timezone
*
* @throws Exception
*/
public function __construct(?string $time = null, $timezone = null, ?string $locale = null)
{
$this->locale = $locale !== null && $locale !== '' && $locale !== '0' ? $locale : Locale::getDefault();
$time ??= '';
// If a test instance has been provided, use it instead.
if ($time === '' && static::$testNow instanceof static) {
if ($timezone !== null) {
$testNow = static::$testNow->setTimezone($timezone);
$time = $testNow->format('Y-m-d H:i:s.u');
} else {
$timezone = static::$testNow->getTimezone();
$time = static::$testNow->format('Y-m-d H:i:s.u');
}
}
$timezone = $timezone ?: date_default_timezone_get();
$this->timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
// If the time string was a relative string (i.e. 'next Tuesday')
// then we need to adjust the time going in so that we have a current
// timezone to work with.
if ($time !== '' && static::hasRelativeKeywords($time)) {
$instance = new DateTime('now', $this->timezone);
$instance->modify($time);
$time = $instance->format('Y-m-d H:i:s.u');
}
parent::__construct($time, $this->timezone);
}
/**
* Returns a new Time instance with the timezone set.
*
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
public static function now($timezone = null, ?string $locale = null)
{
return new static(null, $timezone, $locale);
}
/**
* Returns a new Time instance while parsing a datetime string.
*
* Example:
* $time = Time::parse('first day of December 2008');
*
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
public static function parse(string $datetime, $timezone = null, ?string $locale = null)
{
return new static($datetime, $timezone, $locale);
}
/**
* Return a new time with the time set to midnight.
*
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
public static function today($timezone = null, ?string $locale = null)
{
return new static(date('Y-m-d 00:00:00'), $timezone, $locale);
}
/**
* Returns an instance set to midnight yesterday morning.
*
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
public static function yesterday($timezone = null, ?string $locale = null)
{
return new static(date('Y-m-d 00:00:00', strtotime('-1 day')), $timezone, $locale);
}
/**
* Returns an instance set to midnight tomorrow morning.
*
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
public static function tomorrow($timezone = null, ?string $locale = null)
{
return new static(date('Y-m-d 00:00:00', strtotime('+1 day')), $timezone, $locale);
}
/**
* Returns a new instance based on the year, month and day. If any of those three
* are left empty, will default to the current value.
*
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
public static function createFromDate(?int $year = null, ?int $month = null, ?int $day = null, $timezone = null, ?string $locale = null)
{
return static::create($year, $month, $day, null, null, null, $timezone, $locale);
}
/**
* Returns a new instance with the date set to today, and the time set to the values passed in.
*
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
public static function createFromTime(?int $hour = null, ?int $minutes = null, ?int $seconds = null, $timezone = null, ?string $locale = null)
{
return static::create(null, null, null, $hour, $minutes, $seconds, $timezone, $locale);
}
/**
* Returns a new instance with the date time values individually set.
*
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
public static function create(
?int $year = null,
?int $month = null,
?int $day = null,
?int $hour = null,
?int $minutes = null,
?int $seconds = null,
$timezone = null,
?string $locale = null,
) {
$year ??= date('Y');
$month ??= date('m');
$day ??= date('d');
$hour ??= 0;
$minutes ??= 0;
$seconds ??= 0;
return new static(date('Y-m-d H:i:s', strtotime("{$year}-{$month}-{$day} {$hour}:{$minutes}:{$seconds}")), $timezone, $locale);
}
/**
* Provides a replacement for DateTime's own createFromFormat function, that provides
* more flexible timeZone handling
*
* @param string $format
* @param string $datetime
* @param DateTimeZone|string|null $timezone
*
* @return static
*
* @throws Exception
*/
#[ReturnTypeWillChange]
public static function createFromFormat($format, $datetime, $timezone = null)
{
if (! $date = parent::createFromFormat($format, $datetime)) {
throw I18nException::forInvalidFormat($format);
}
return new static($date->format('Y-m-d H:i:s.u'), $timezone);
}
/**
* Returns a new instance with the datetime set based on the provided UNIX timestamp.
*
* @param DateTimeZone|string|null $timezone
*
* @throws Exception
*/
public static function createFromTimestamp(float|int $timestamp, $timezone = null, ?string $locale = null): static
{
$time = new static(sprintf('@%.6f', $timestamp), 'UTC', $locale);
$timezone ??= 'UTC';
return $time->setTimezone($timezone);
}
/**
* Takes an instance of DateTimeInterface and returns an instance of Time with it's same values.
*
* @return static
*
* @throws Exception
*/
public static function createFromInstance(DateTimeInterface $dateTime, ?string $locale = null)
{
$date = $dateTime->format('Y-m-d H:i:s.u');
$timezone = $dateTime->getTimezone();
return new static($date, $timezone, $locale);
}
/**
* Takes an instance of DateTime and returns an instance of Time with it's same values.
*
* @return static
*
* @throws Exception
*
* @deprecated Use createFromInstance() instead
*
* @codeCoverageIgnore
*/
public static function instance(DateTime $dateTime, ?string $locale = null)
{
return static::createFromInstance($dateTime, $locale);
}
/**
* Converts the current instance to a mutable DateTime object.
*
* @return DateTime
*
* @throws Exception
*/
public function toDateTime()
{
return DateTime::createFromFormat(
'Y-m-d H:i:s.u',
$this->format('Y-m-d H:i:s.u'),
$this->getTimezone(),
);
}
// --------------------------------------------------------------------
// For Testing
// --------------------------------------------------------------------
/**
* Creates an instance of Time that will be returned during testing
* when calling 'Time::now()' instead of the current time.
*
* @param DateTimeInterface|self|string|null $datetime
* @param DateTimeZone|string|null $timezone
*
* @return void
*
* @throws Exception
*/
public static function setTestNow($datetime = null, $timezone = null, ?string $locale = null)
{
// Reset the test instance
if ($datetime === null) {
static::$testNow = null;
return;
}
// Convert to a Time instance
if (is_string($datetime)) {
$datetime = new static($datetime, $timezone, $locale);
} elseif ($datetime instanceof DateTimeInterface && ! $datetime instanceof static) {
$datetime = new static($datetime->format('Y-m-d H:i:s.u'), $timezone);
}
static::$testNow = $datetime;
}
/**
* Returns whether we have a testNow instance saved.
*/
public static function hasTestNow(): bool
{
return static::$testNow !== null;
}
// --------------------------------------------------------------------
// Getters
// --------------------------------------------------------------------
/**
* Returns the localized Year
*
* @throws Exception
*/
public function getYear(): string
{
return $this->toLocalizedString('y');
}
/**
* Returns the localized Month
*
* @throws Exception
*/
public function getMonth(): string
{
return $this->toLocalizedString('M');
}
/**
* Return the localized day of the month.
*
* @throws Exception
*/
public function getDay(): string
{
return $this->toLocalizedString('d');
}
/**
* Return the localized hour (in 24-hour format).
*
* @throws Exception
*/
public function getHour(): string
{
return $this->toLocalizedString('H');
}
/**
* Return the localized minutes in the hour.
*
* @throws Exception
*/
public function getMinute(): string
{
return $this->toLocalizedString('m');
}
/**
* Return the localized seconds
*
* @throws Exception
*/
public function getSecond(): string
{
return $this->toLocalizedString('s');
}
/**
* Return the index of the day of the week
*
* @throws Exception
*/
public function getDayOfWeek(): string
{
return $this->toLocalizedString('c');
}
/**
* Return the index of the day of the year
*
* @throws Exception
*/
public function getDayOfYear(): string
{
return $this->toLocalizedString('D');
}
/**
* Return the index of the week in the month
*
* @throws Exception
*/
public function getWeekOfMonth(): string
{
return $this->toLocalizedString('W');
}
/**
* Return the index of the week in the year
*
* @throws Exception
*/
public function getWeekOfYear(): string
{
return $this->toLocalizedString('w');
}
/**
* Returns the age in years from the date and 'now'
*
* @return int
*
* @throws Exception
*/
public function getAge()
{
// future dates have no age
return max(0, $this->difference(static::now())->getYears());
}
/**
* Returns the number of the current quarter for the year.
*
* @throws Exception
*/
public function getQuarter(): string
{
return $this->toLocalizedString('Q');
}
/**
* Are we in daylight savings time currently?
*/
public function getDst(): bool
{
return $this->format('I') === '1'; // 1 if Daylight Saving Time, 0 otherwise.
}
/**
* Returns boolean whether the passed timezone is the same as
* the local timezone.
*/
public function getLocal(): bool
{
$local = date_default_timezone_get();
return $local === $this->timezone->getName();
}
/**
* Returns boolean whether object is in UTC.
*/
public function getUtc(): bool
{
return $this->getOffset() === 0;
}
/**
* Returns the name of the current timezone.
*/
public function getTimezoneName(): string
{
return $this->timezone->getName();
}
// --------------------------------------------------------------------
// Setters
// --------------------------------------------------------------------
/**
* Sets the current year for this instance.
*
* @param int|string $value
*
* @return static
*
* @throws Exception
*/
public function setYear($value)
{
return $this->setValue('year', $value);
}
/**
* Sets the month of the year.
*
* @param int|string $value
*
* @return static
*
* @throws Exception
*/
public function setMonth($value)
{
if (is_numeric($value) && ($value < 1 || $value > 12)) {
throw I18nException::forInvalidMonth((string) $value);
}
if (is_string($value) && ! is_numeric($value)) {
$value = date('m', strtotime("{$value} 1 2017"));
}
return $this->setValue('month', $value);
}
/**
* Sets the day of the month.
*
* @param int|string $value
*
* @return static
*
* @throws Exception
*/
public function setDay($value)
{
if ($value < 1 || $value > 31) {
throw I18nException::forInvalidDay((string) $value);
}
$date = $this->getYear() . '-' . $this->getMonth();
$lastDay = date('t', strtotime($date));
if ($value > $lastDay) {
throw I18nException::forInvalidOverDay($lastDay, (string) $value);
}
return $this->setValue('day', $value);
}
/**
* Sets the hour of the day (24 hour cycle)
*
* @param int|string $value
*
* @return static
*
* @throws Exception
*/
public function setHour($value)
{
if ($value < 0 || $value > 23) {
throw I18nException::forInvalidHour((string) $value);
}
return $this->setValue('hour', $value);
}
/**
* Sets the minute of the hour
*
* @param int|string $value
*
* @return static
*
* @throws Exception
*/
public function setMinute($value)
{
if ($value < 0 || $value > 59) {
throw I18nException::forInvalidMinutes((string) $value);
}
return $this->setValue('minute', $value);
}
/**
* Sets the second of the minute.
*
* @param int|string $value
*
* @return static
*
* @throws Exception
*/
public function setSecond($value)
{
if ($value < 0 || $value > 59) {
throw I18nException::forInvalidSeconds((string) $value);
}
return $this->setValue('second', $value);
}
/**
* Helper method to do the heavy lifting of the 'setX' methods.
*
* @param int $value
*
* @return static
*
* @throws Exception
*/
protected function setValue(string $name, $value)
{
[$year, $month, $day, $hour, $minute, $second] = explode('-', $this->format('Y-n-j-G-i-s'));
${$name} = $value;
return static::create(
(int) $year,
(int) $month,
(int) $day,
(int) $hour,
(int) $minute,
(int) $second,
$this->getTimezoneName(),
$this->locale,
);
}
/**
* Returns a new instance with the revised timezone.
*
* @param DateTimeZone|string $timezone
*
* @return static
*
* @throws Exception
*/
#[ReturnTypeWillChange]
public function setTimezone($timezone)
{
$timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
return static::createFromInstance($this->toDateTime()->setTimezone($timezone), $this->locale);
}
// --------------------------------------------------------------------
// Add/Subtract
// --------------------------------------------------------------------
/**
* Returns a new Time instance with $seconds added to the time.
*
* @return static
*/
public function addSeconds(int $seconds)
{
$time = clone $this;
return $time->add(DateInterval::createFromDateString("{$seconds} seconds"));
}
/**
* Returns a new Time instance with $minutes added to the time.
*
* @return static
*/
public function addMinutes(int $minutes)
{
$time = clone $this;
return $time->add(DateInterval::createFromDateString("{$minutes} minutes"));
}
/**
* Returns a new Time instance with $hours added to the time.
*
* @return static
*/
public function addHours(int $hours)
{
$time = clone $this;
return $time->add(DateInterval::createFromDateString("{$hours} hours"));
}
/**
* Returns a new Time instance with $days added to the time.
*
* @return static
*/
public function addDays(int $days)
{
$time = clone $this;
return $time->add(DateInterval::createFromDateString("{$days} days"));
}
/**
* Returns a new Time instance with $months added to the time.
*
* @return static
*/
public function addMonths(int $months)
{
$time = clone $this;
return $time->add(DateInterval::createFromDateString("{$months} months"));
}
/**
* Returns a new Time instance with $years added to the time.
*
* @return static
*/
public function addYears(int $years)
{
$time = clone $this;
return $time->add(DateInterval::createFromDateString("{$years} years"));
}
/**
* Returns a new Time instance with $seconds subtracted from the time.
*
* @return static
*/
public function subSeconds(int $seconds)
{
$time = clone $this;
return $time->sub(DateInterval::createFromDateString("{$seconds} seconds"));
}
/**
* Returns a new Time instance with $minutes subtracted from the time.
*
* @return static
*/
public function subMinutes(int $minutes)
{
$time = clone $this;
return $time->sub(DateInterval::createFromDateString("{$minutes} minutes"));
}
/**
* Returns a new Time instance with $hours subtracted from the time.
*
* @return static
*/
public function subHours(int $hours)
{
$time = clone $this;
return $time->sub(DateInterval::createFromDateString("{$hours} hours"));
}
/**
* Returns a new Time instance with $days subtracted from the time.
*
* @return static
*/
public function subDays(int $days)
{
$time = clone $this;
return $time->sub(DateInterval::createFromDateString("{$days} days"));
}
/**
* Returns a new Time instance with $months subtracted from the time.
*
* @return static
*/
public function subMonths(int $months)
{
$time = clone $this;
return $time->sub(DateInterval::createFromDateString("{$months} months"));
}
/**
* Returns a new Time instance with $hours subtracted from the time.
*
* @return static
*/
public function subYears(int $years)
{
$time = clone $this;
return $time->sub(DateInterval::createFromDateString("{$years} years"));
}
// --------------------------------------------------------------------
// Formatters
// --------------------------------------------------------------------
/**
* Returns the localized value of the date in the format 'Y-m-d H:i:s'
*
* @return false|string
*
* @throws Exception
*/
public function toDateTimeString()
{
return $this->toLocalizedString('yyyy-MM-dd HH:mm:ss');
}
/**
* Returns a localized version of the date in Y-m-d format.
*
* @return string
*
* @throws Exception
*/
public function toDateString()
{
return $this->toLocalizedString('yyyy-MM-dd');
}
/**
* Returns a localized version of the date in nicer date format:
*
* i.e. Apr 1, 2017
*
* @return string
*
* @throws Exception
*/
public function toFormattedDateString()
{
return $this->toLocalizedString('MMM d, yyyy');
}
/**
* Returns a localized version of the time in nicer date format:
*
* i.e. 13:20:33
*
* @return string
*
* @throws Exception
*/
public function toTimeString()
{
return $this->toLocalizedString('HH:mm:ss');
}
/**
* Returns the localized value of this instance in $format.
*
* @return false|string
*
* @throws Exception
*/
public function toLocalizedString(?string $format = null)
{
$format ??= $this->toStringFormat;
return IntlDateFormatter::formatObject($this->toDateTime(), $format, $this->locale);
}
// --------------------------------------------------------------------
// Comparison
// --------------------------------------------------------------------
/**
* Determines if the datetime passed in is equal to the current instance.
* Equal in this case means that they represent the same moment in time,
* and are not required to be in the same timezone, as both times are
* converted to UTC and compared that way.
*
* @param DateTimeInterface|self|string $testTime
*
* @throws Exception
*/
public function equals($testTime, ?string $timezone = null): bool
{
$testTime = $this->getUTCObject($testTime, $timezone);
$ourTime = $this->toDateTime()
->setTimezone(new DateTimeZone('UTC'))
->format('Y-m-d H:i:s.u');
return $testTime->format('Y-m-d H:i:s.u') === $ourTime;
}
/**
* Ensures that the times are identical, taking timezone into account.
*
* @param DateTimeInterface|self|string $testTime
*
* @throws Exception
*/
public function sameAs($testTime, ?string $timezone = null): bool
{
if ($testTime instanceof DateTimeInterface) {
$testTime = $testTime->format('Y-m-d H:i:s.u O');
} elseif (is_string($testTime)) {
$timezone = $timezone !== null && $timezone !== '' && $timezone !== '0' ? $timezone : $this->timezone;
$timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
$testTime = new DateTime($testTime, $timezone);
$testTime = $testTime->format('Y-m-d H:i:s.u O');
}
$ourTime = $this->format('Y-m-d H:i:s.u O');
return $testTime === $ourTime;
}
/**
* Determines if the current instance's time is before $testTime,
* after converting to UTC.
*
* @param DateTimeInterface|self|string $testTime
*
* @throws Exception
*/
public function isBefore($testTime, ?string $timezone = null): bool
{
$testTime = $this->getUTCObject($testTime, $timezone);
$testTimestamp = $testTime->getTimestamp();
$ourTimestamp = $this->getTimestamp();
if ($ourTimestamp === $testTimestamp) {
return $this->format('u') < $testTime->format('u');
}
return $ourTimestamp < $testTimestamp;
}
/**
* Determines if the current instance's time is after $testTime,
* after converting in UTC.
*
* @param DateTimeInterface|self|string $testTime
*
* @throws Exception
*/
public function isAfter($testTime, ?string $timezone = null): bool
{
$testTime = $this->getUTCObject($testTime, $timezone);
$testTimestamp = $testTime->getTimestamp();
$ourTimestamp = $this->getTimestamp();
if ($ourTimestamp === $testTimestamp) {
return $this->format('u') > $testTime->format('u');
}
return $ourTimestamp > $testTimestamp;
}
// --------------------------------------------------------------------
// Differences
// --------------------------------------------------------------------
/**
* Returns a text string that is easily readable that describes
* how long ago, or how long from now, a date is, like:
*
* - 3 weeks ago
* - in 4 days
* - 6 hours ago
*
* @return string
*
* @throws Exception
*/
public function humanize()
{
$now = IntlCalendar::fromDateTime(self::now($this->timezone)->toDateTime());
$time = $this->getCalendar()->getTime();
$years = $now->fieldDifference($time, IntlCalendar::FIELD_YEAR);
$months = $now->fieldDifference($time, IntlCalendar::FIELD_MONTH);
$days = $now->fieldDifference($time, IntlCalendar::FIELD_DAY_OF_YEAR);
$hours = $now->fieldDifference($time, IntlCalendar::FIELD_HOUR_OF_DAY);
$minutes = $now->fieldDifference($time, IntlCalendar::FIELD_MINUTE);
$phrase = null;
if ($years !== 0) {
$phrase = lang('Time.years', [abs($years)]);
$before = $years < 0;
} elseif ($months !== 0) {
$phrase = lang('Time.months', [abs($months)]);
$before = $months < 0;
} elseif ($days !== 0 && (abs($days) >= 7)) {
$weeks = ceil($days / 7);
$phrase = lang('Time.weeks', [abs($weeks)]);
$before = $days < 0;
} elseif ($days !== 0) {
$before = $days < 0;
// Yesterday/Tomorrow special cases
if (abs($days) === 1) {
return $before ? lang('Time.yesterday') : lang('Time.tomorrow');
}
$phrase = lang('Time.days', [abs($days)]);
} elseif ($hours !== 0) {
$phrase = lang('Time.hours', [abs($hours)]);
$before = $hours < 0;
} elseif ($minutes !== 0) {
$phrase = lang('Time.minutes', [abs($minutes)]);
$before = $minutes < 0;
} else {
return lang('Time.now');
}
return $before ? lang('Time.ago', [$phrase]) : lang('Time.inFuture', [$phrase]);
}
/**
* @param DateTimeInterface|self|string $testTime
*
* @return TimeDifference
*
* @throws Exception
*/
public function difference($testTime, ?string $timezone = null)
{
if (is_string($testTime)) {
$timezone = ($timezone !== null) ? new DateTimeZone($timezone) : $this->timezone;
$testTime = new DateTime($testTime, $timezone);
} elseif ($testTime instanceof static) {
$testTime = $testTime->toDateTime();
}
assert($testTime instanceof DateTime);
if ($this->timezone->getOffset($this) !== $testTime->getTimezone()->getOffset($this)) {
$testTime = $this->getUTCObject($testTime, $timezone);
$ourTime = $this->getUTCObject($this);
} else {
$ourTime = $this->toDateTime();
}
return new TimeDifference($ourTime, $testTime);
}
// --------------------------------------------------------------------
// Utilities
// --------------------------------------------------------------------
/**
* Returns a Time instance with the timezone converted to UTC.
*
* @param DateTimeInterface|self|string $time
*
* @return DateTime|static
*
* @throws Exception
*/
public function getUTCObject($time, ?string $timezone = null)
{
if ($time instanceof static) {
$time = $time->toDateTime();
} elseif (is_string($time)) {
$timezone = $timezone !== null && $timezone !== '' && $timezone !== '0' ? $timezone : $this->timezone;
$timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
$time = new DateTime($time, $timezone);
}
if ($time instanceof DateTime || $time instanceof DateTimeImmutable) {
$time = $time->setTimezone(new DateTimeZone('UTC'));
}
return $time;
}
/**
* Returns the IntlCalendar object used for this object,
* taking into account the locale, date, etc.
*
* Primarily used internally to provide the difference and comparison functions,
* but available for public consumption if they need it.
*
* @return IntlCalendar
*
* @throws Exception
*/
public function getCalendar()
{
return IntlCalendar::fromDateTime($this->toDateTime());
}
/**
* Check a time string to see if it includes a relative date (like 'next Tuesday').
*/
protected static function hasRelativeKeywords(string $time): bool
{
// skip common format with a '-' in it
if (preg_match('/\d{4}-\d{1,2}-\d{1,2}/', $time) !== 1) {
return preg_match(static::$relativePattern, $time) > 0;
}
return false;
}
/**
* Outputs a short format version of the datetime.
* The output is NOT localized intentionally.
*/
public function __toString(): string
{
return $this->format('Y-m-d H:i:s');
}
/**
* Allow for property-type access to any getX method...
*
* Note that we cannot use this for any of our setX methods,
* as they return new Time objects, but the __set ignores
* return values.
* See http://php.net/manual/en/language.oop5.overloading.php
*
* @param string $name
*
* @return array|bool|DateTimeInterface|DateTimeZone|int|IntlCalendar|self|string|null
*/
public function __get($name)
{
$method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->{$method}();
}
return null;
}
/**
* Allow for property-type checking to any getX method...
*
* @param string $name
*/
public function __isset($name): bool
{
$method = 'get' . ucfirst($name);
return method_exists($this, $method);
}
/**
* This is called when we unserialize the Time object.
*/
public function __wakeup(): void
{
/**
* Prior to unserialization, this is a string.
*
* @var string $timezone
*/
$timezone = $this->timezone;
$this->timezone = new DateTimeZone($timezone);
// @phpstan-ignore-next-line `$this->date` is a special property for PHP internal use.
parent::__construct($this->date, $this->timezone);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/I18n/TimeLegacy.php | system/I18n/TimeLegacy.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\I18n;
use DateTime;
use Exception;
use ReturnTypeWillChange;
/**
* Legacy Time class.
*
* This class is only for backward compatibility. Do not use.
* This is not immutable! Some methods are immutable,
* but some methods can alter the state.
*
* @property int $age read-only
* @property string $day read-only
* @property string $dayOfWeek read-only
* @property string $dayOfYear read-only
* @property bool $dst read-only
* @property string $hour read-only
* @property bool $local read-only
* @property string $minute read-only
* @property string $month read-only
* @property string $quarter read-only
* @property string $second read-only
* @property int $timestamp read-only
* @property bool $utc read-only
* @property string $weekOfMonth read-only
* @property string $weekOfYear read-only
* @property string $year read-only
*
* @phpstan-consistent-constructor
*
* @deprecated Use Time instead.
* @see \CodeIgniter\I18n\TimeLegacyTest
*/
class TimeLegacy extends DateTime
{
use TimeTrait;
/**
* Returns a new instance with the date set to the new timestamp.
*
* @param int $timestamp
*
* @return static
*
* @throws Exception
*/
#[ReturnTypeWillChange]
public function setTimestamp($timestamp)
{
$time = date('Y-m-d H:i:s', $timestamp);
return static::parse($time, $this->timezone, $this->locale);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/I18n/TimeDifference.php | system/I18n/TimeDifference.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\I18n;
use DateTime;
use IntlCalendar;
/**
* @property-read float|int $days
* @property-read float|int $hours
* @property-read float|int $minutes
* @property-read float|int $months
* @property-read int $seconds
* @property-read float|int $weeks
* @property-read float|int $years
*
* @see \CodeIgniter\I18n\TimeDifferenceTest
*/
class TimeDifference
{
/**
* The timestamp of the "current" time.
*
* @var IntlCalendar
*/
protected $currentTime;
/**
* The timestamp to compare the current time to.
*
* @var float
*/
protected $testTime;
/**
* Eras.
*
* @var float
*/
protected $eras = 0;
/**
* Years.
*
* @var float
*/
protected $years = 0;
/**
* Months.
*
* @var float
*/
protected $months = 0;
/**
* Weeks.
*
* @var int
*/
protected $weeks = 0;
/**
* Days.
*
* @var int
*/
protected $days = 0;
/**
* Hours.
*
* @var int
*/
protected $hours = 0;
/**
* Minutes.
*
* @var int
*/
protected $minutes = 0;
/**
* Seconds.
*
* @var int
*/
protected $seconds = 0;
/**
* Difference in seconds.
*
* @var int
*/
protected $difference;
/**
* Note: both parameters are required to be in the same timezone. No timezone
* shifting is done internally.
*/
public function __construct(DateTime $currentTime, DateTime $testTime)
{
$this->difference = $currentTime->getTimestamp() - $testTime->getTimestamp();
$current = IntlCalendar::fromDateTime($currentTime);
$time = IntlCalendar::fromDateTime($testTime)->getTime();
$this->currentTime = $current;
$this->testTime = $time;
}
/**
* Returns the number of years of difference between the two.
*
* @return float|int
*/
public function getYears(bool $raw = false)
{
if ($raw) {
return $this->difference / YEAR;
}
$time = clone $this->currentTime;
return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_YEAR);
}
/**
* Returns the number of months difference between the two dates.
*
* @return float|int
*/
public function getMonths(bool $raw = false)
{
if ($raw) {
return $this->difference / MONTH;
}
$time = clone $this->currentTime;
return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_MONTH);
}
/**
* Returns the number of weeks difference between the two dates.
*
* @return float|int
*/
public function getWeeks(bool $raw = false)
{
if ($raw) {
return $this->difference / WEEK;
}
$time = clone $this->currentTime;
return (int) ($time->fieldDifference($this->testTime, IntlCalendar::FIELD_DAY_OF_YEAR) / 7);
}
/**
* Returns the number of days difference between the two dates.
*
* @return float|int
*/
public function getDays(bool $raw = false)
{
if ($raw) {
return $this->difference / DAY;
}
$time = clone $this->currentTime;
return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_DAY_OF_YEAR);
}
/**
* Returns the number of hours difference between the two dates.
*
* @return float|int
*/
public function getHours(bool $raw = false)
{
if ($raw) {
return $this->difference / HOUR;
}
$time = clone $this->currentTime;
return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_HOUR_OF_DAY);
}
/**
* Returns the number of minutes difference between the two dates.
*
* @return float|int
*/
public function getMinutes(bool $raw = false)
{
if ($raw) {
return $this->difference / MINUTE;
}
$time = clone $this->currentTime;
return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_MINUTE);
}
/**
* Returns the number of seconds difference between the two dates.
*
* @return int
*/
public function getSeconds(bool $raw = false)
{
if ($raw) {
return $this->difference;
}
$time = clone $this->currentTime;
return $time->fieldDifference($this->testTime, IntlCalendar::FIELD_SECOND);
}
/**
* Convert the time to human readable format
*/
public function humanize(?string $locale = null): string
{
$current = clone $this->currentTime;
$years = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_YEAR);
$months = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_MONTH);
$days = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_DAY_OF_YEAR);
$hours = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_HOUR_OF_DAY);
$minutes = $current->fieldDifference($this->testTime, IntlCalendar::FIELD_MINUTE);
$phrase = null;
if ($years !== 0) {
$phrase = lang('Time.years', [abs($years)], $locale);
$before = $years < 0;
} elseif ($months !== 0) {
$phrase = lang('Time.months', [abs($months)], $locale);
$before = $months < 0;
} elseif ($days !== 0 && (abs($days) >= 7)) {
$weeks = ceil($days / 7);
$phrase = lang('Time.weeks', [abs($weeks)], $locale);
$before = $days < 0;
} elseif ($days !== 0) {
$phrase = lang('Time.days', [abs($days)], $locale);
$before = $days < 0;
} elseif ($hours !== 0) {
$phrase = lang('Time.hours', [abs($hours)], $locale);
$before = $hours < 0;
} elseif ($minutes !== 0) {
$phrase = lang('Time.minutes', [abs($minutes)], $locale);
$before = $minutes < 0;
} else {
return lang('Time.now', [], $locale);
}
return $before
? lang('Time.ago', [$phrase], $locale)
: lang('Time.inFuture', [$phrase], $locale);
}
/**
* Allow property-like access to our calculated values.
*
* @param string $name
*
* @return float|int|null
*/
public function __get($name)
{
$name = ucfirst(strtolower($name));
$method = "get{$name}";
if (method_exists($this, $method)) {
return $this->{$method}();
}
return null;
}
/**
* Allow property-like checking for our calculated values.
*
* @param string $name
*
* @return bool
*/
public function __isset($name)
{
$name = ucfirst(strtolower($name));
$method = "get{$name}";
return method_exists($this, $method);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/I18n/Exceptions/I18nException.php | system/I18n/Exceptions/I18nException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\I18n\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
/**
* I18nException
*/
class I18nException extends FrameworkException
{
/**
* Thrown when createFromFormat fails to receive a valid
* DateTime back from DateTime::createFromFormat.
*
* @return static
*/
public static function forInvalidFormat(string $format)
{
return new static(lang('Time.invalidFormat', [$format]));
}
/**
* Thrown when the numeric representation of the month falls
* outside the range of allowed months.
*
* @return static
*/
public static function forInvalidMonth(string $month)
{
return new static(lang('Time.invalidMonth', [$month]));
}
/**
* Thrown when the supplied day falls outside the range
* of allowed days.
*
* @return static
*/
public static function forInvalidDay(string $day)
{
return new static(lang('Time.invalidDay', [$day]));
}
/**
* Thrown when the day provided falls outside the allowed
* last day for the given month.
*
* @return static
*/
public static function forInvalidOverDay(string $lastDay, string $day)
{
return new static(lang('Time.invalidOverDay', [$lastDay, $day]));
}
/**
* Thrown when the supplied hour falls outside the
* range of allowed hours.
*
* @return static
*/
public static function forInvalidHour(string $hour)
{
return new static(lang('Time.invalidHour', [$hour]));
}
/**
* Thrown when the supplied minutes falls outside the
* range of allowed minutes.
*
* @return static
*/
public static function forInvalidMinutes(string $minutes)
{
return new static(lang('Time.invalidMinutes', [$minutes]));
}
/**
* Thrown when the supplied seconds falls outside the
* range of allowed seconds.
*
* @return static
*/
public static function forInvalidSeconds(string $seconds)
{
return new static(lang('Time.invalidSeconds', [$seconds]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/html_helper.php | system/Helpers/html_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\Files\Exceptions\FileNotFoundException;
use Config\DocTypes;
use Config\Mimes;
// CodeIgniter HTML Helpers
if (! function_exists('ul')) {
/**
* Unordered List
*
* Generates an HTML unordered list from a single or
* multidimensional array.
*
* @param array $list List entries
* @param array|object|string $attributes HTML attributes string, array, object
*/
function ul(array $list, $attributes = ''): string
{
return _list('ul', $list, $attributes);
}
}
if (! function_exists('ol')) {
/**
* Ordered List
*
* Generates an HTML ordered list from a single or multidimensional array.
*
* @param array $list List entries
* @param array|object|string $attributes HTML attributes string, array, object
*/
function ol(array $list, $attributes = ''): string
{
return _list('ol', $list, $attributes);
}
}
if (! function_exists('_list')) {
/**
* Generates the list
*
* Generates an HTML ordered list from a single or multidimensional array.
*
* @param array $list List entries
* @param array|object|string $attributes HTML attributes string, array, object
*/
function _list(string $type = 'ul', $list = [], $attributes = '', int $depth = 0): string
{
// Set the indentation based on the depth
$out = str_repeat(' ', $depth)
// Write the opening list tag
. '<' . $type . stringify_attributes($attributes) . ">\n";
// Cycle through the list elements. If an array is
// encountered we will recursively call _list()
foreach ($list as $key => $val) {
$out .= str_repeat(' ', $depth + 2) . '<li>';
if (! is_array($val)) {
$out .= $val;
} else {
$out .= $key
. "\n"
. _list($type, $val, '', $depth + 4)
. str_repeat(' ', $depth + 2);
}
$out .= "</li>\n";
}
// Set the indentation for the closing tag and apply it
return $out . str_repeat(' ', $depth) . '</' . $type . ">\n";
}
}
if (! function_exists('img')) {
/**
* Image
*
* Generates an image element
*
* @param array|string $src Image source URI, or array of attributes and values
* @param bool $indexPage Should `Config\App::$indexPage` be added to the source path
* @param array|object|string $attributes Additional HTML attributes
*/
function img($src = '', bool $indexPage = false, $attributes = ''): string
{
if (! is_array($src)) {
$src = ['src' => $src];
}
if (! isset($src['src'])) {
$src['src'] = $attributes['src'] ?? '';
}
if (! isset($src['alt'])) {
$src['alt'] = $attributes['alt'] ?? '';
}
$img = '<img';
// Check for a relative URI
if (preg_match('#^([a-z]+:)?//#i', $src['src']) !== 1 && ! str_starts_with($src['src'], 'data:')) {
if ($indexPage) {
$img .= ' src="' . site_url($src['src']) . '"';
} else {
$img .= ' src="' . slash_item('baseURL') . $src['src'] . '"';
}
unset($src['src']);
}
// Append any other values
foreach ($src as $key => $value) {
$img .= ' ' . $key . '="' . $value . '"';
}
// Prevent passing completed values to stringify_attributes
if (is_array($attributes)) {
unset($attributes['alt'], $attributes['src']);
}
return $img . stringify_attributes($attributes) . _solidus() . '>';
}
}
if (! function_exists('img_data')) {
/**
* Image (data)
*
* Generates a src-ready string from an image using the "data:" protocol
*
* @param string $path Image source path
* @param string|null $mime MIME type to use, or null to guess
*/
function img_data(string $path, ?string $mime = null): string
{
if (! is_file($path) || ! is_readable($path)) {
throw FileNotFoundException::forFileNotFound($path);
}
// Read in file binary data
$handle = fopen($path, 'rb');
$data = fread($handle, filesize($path));
fclose($handle);
// Encode as base64
$data = base64_encode($data);
// Figure out the type (Hail Mary to JPEG)
$mime ??= Mimes::guessTypeFromExtension(pathinfo($path, PATHINFO_EXTENSION)) ?? 'image/jpg';
return 'data:' . $mime . ';base64,' . $data;
}
}
if (! function_exists('doctype')) {
/**
* Doctype
*
* Generates a page document type declaration
*
* Examples of valid options: html5, xhtml-11, xhtml-strict, xhtml-trans,
* xhtml-frame, html4-strict, html4-trans, and html4-frame.
* All values are saved in the doctypes config file.
*
* @param string $type The doctype to be generated
*/
function doctype(string $type = 'html5'): string
{
$config = new DocTypes();
$doctypes = $config->list;
return $doctypes[$type] ?? '';
}
}
if (! function_exists('script_tag')) {
/**
* Script
*
* Generates link to a JS file
*
* @param array|string $src Script source or an array of attributes
* @param bool $indexPage Should `Config\App::$indexPage` be added to the JS path
*/
function script_tag($src = '', bool $indexPage = false): string
{
$cspNonce = csp_script_nonce();
$cspNonce = $cspNonce !== '' ? ' ' . $cspNonce : $cspNonce;
$script = '<script' . $cspNonce . ' ';
if (! is_array($src)) {
$src = ['src' => $src];
}
foreach ($src as $k => $v) {
if ($k === 'src' && preg_match('#^([a-z]+:)?//#i', $v) !== 1) {
if ($indexPage) {
$script .= 'src="' . site_url($v) . '" ';
} else {
$script .= 'src="' . slash_item('baseURL') . $v . '" ';
}
} else {
// for attributes without values, like async or defer, use NULL.
$script .= $k . (null === $v ? ' ' : '="' . $v . '" ');
}
}
return rtrim($script) . '></script>';
}
}
if (! function_exists('link_tag')) {
/**
* Link
*
* Generates link tag
*
* @param array<string, bool|string>|string $href Stylesheet href or an array
* @param bool $indexPage Should `Config\App::$indexPage` be added to the CSS path.
*/
function link_tag(
$href = '',
string $rel = 'stylesheet',
string $type = 'text/css',
string $title = '',
string $media = '',
bool $indexPage = false,
string $hreflang = '',
): string {
$attributes = [];
// extract fields if needed
if (is_array($href)) {
$rel = $href['rel'] ?? $rel;
$type = $href['type'] ?? $type;
$title = $href['title'] ?? $title;
$media = $href['media'] ?? $media;
$hreflang = $href['hreflang'] ?? '';
$indexPage = $href['indexPage'] ?? $indexPage;
$href = $href['href'] ?? '';
}
if (preg_match('#^([a-z]+:)?//#i', $href) !== 1) {
$attributes['href'] = $indexPage ? site_url($href) : slash_item('baseURL') . $href;
} else {
$attributes['href'] = $href;
}
if ($hreflang !== '') {
$attributes['hreflang'] = $hreflang;
}
$attributes['rel'] = $rel;
if ($type !== '' && $rel !== 'canonical' && $hreflang === '' && ! ($rel === 'alternate' && $media !== '')) {
$attributes['type'] = $type;
}
if ($media !== '') {
$attributes['media'] = $media;
}
if ($title !== '') {
$attributes['title'] = $title;
}
return '<link' . stringify_attributes($attributes) . _solidus() . '>';
}
}
if (! function_exists('video')) {
/**
* Video
*
* Generates a video element to embed videos. The video element can
* contain one or more video sources
*
* @param array|string $src Either a source string or an array of sources
* @param string $unsupportedMessage The message to display if the media tag is not supported by the browser
* @param string $attributes HTML attributes
* @param bool $indexPage Should `Config\App::$indexPage` be added to the source path
*/
function video($src, string $unsupportedMessage = '', string $attributes = '', array $tracks = [], bool $indexPage = false): string
{
if (is_array($src)) {
return _media('video', $src, $unsupportedMessage, $attributes, $tracks);
}
$video = '<video';
if (_has_protocol($src)) {
$video .= ' src="' . $src . '"';
} elseif ($indexPage) {
$video .= ' src="' . site_url($src) . '"';
} else {
$video .= ' src="' . slash_item('baseURL') . $src . '"';
}
if ($attributes !== '') {
$video .= ' ' . $attributes;
}
$video .= ">\n";
foreach ($tracks as $track) {
$video .= _space_indent() . $track . "\n";
}
if ($unsupportedMessage !== '') {
$video .= _space_indent()
. $unsupportedMessage
. "\n";
}
return $video . "</video>\n";
}
}
if (! function_exists('audio')) {
/**
* Audio
*
* Generates an audio element to embed sounds
*
* @param array|string $src Either a source string or an array of sources
* @param string $unsupportedMessage The message to display if the media tag is not supported by the browser.
* @param string $attributes HTML attributes
* @param bool $indexPage Should `Config\App::$indexPage` be added to the source path
*/
function audio($src, string $unsupportedMessage = '', string $attributes = '', array $tracks = [], bool $indexPage = false): string
{
if (is_array($src)) {
return _media('audio', $src, $unsupportedMessage, $attributes, $tracks);
}
$audio = '<audio';
if (_has_protocol($src)) {
$audio .= ' src="' . $src . '"';
} elseif ($indexPage) {
$audio .= ' src="' . site_url($src) . '"';
} else {
$audio .= ' src="' . slash_item('baseURL') . $src . '"';
}
if ($attributes !== '') {
$audio .= ' ' . $attributes;
}
$audio .= '>';
foreach ($tracks as $track) {
$audio .= "\n" . _space_indent() . $track;
}
if ($unsupportedMessage !== '') {
$audio .= "\n" . _space_indent() . $unsupportedMessage . "\n";
}
return $audio . "</audio>\n";
}
}
if (! function_exists('_media')) {
/**
* Generate media based tag
*
* @param string $unsupportedMessage The message to display if the media tag is not supported by the browser.
*/
function _media(string $name, array $types = [], string $unsupportedMessage = '', string $attributes = '', array $tracks = []): string
{
$media = '<' . $name;
if ($attributes === '') {
$media .= '>';
} else {
$media .= ' ' . $attributes . '>';
}
$media .= "\n";
foreach ($types as $option) {
$media .= _space_indent() . $option . "\n";
}
foreach ($tracks as $track) {
$media .= _space_indent() . $track . "\n";
}
if ($unsupportedMessage !== '') {
$media .= _space_indent() . $unsupportedMessage . "\n";
}
return $media . ('</' . $name . ">\n");
}
}
if (! function_exists('source')) {
/**
* Source
*
* Generates a source element that specifies multiple media resources
* for either audio or video element
*
* @param string $src The path of the media resource
* @param string $type The MIME-type of the resource with optional codecs parameters
* @param string $attributes HTML attributes
* @param bool $indexPage Should `Config\App::$indexPage` be added to the source path
*/
function source(string $src, string $type = 'unknown', string $attributes = '', bool $indexPage = false): string
{
if (! _has_protocol($src)) {
$src = $indexPage ? site_url($src) : slash_item('baseURL') . $src;
}
$source = '<source src="' . $src
. '" type="' . $type . '"';
if ($attributes !== '') {
$source .= ' ' . $attributes;
}
return $source . _solidus() . '>';
}
}
if (! function_exists('track')) {
/**
* Track
*
* Generates a track element to specify timed tracks. The tracks are
* formatted in WebVTT format.
*
* @param string $src The path of the .VTT file
* @param string $kind How the text track is meant to be used
* @param string $srcLanguage Language of the track text data
* @param string $label A user-readable title of the text track
*/
function track(string $src, string $kind, string $srcLanguage, string $label): string
{
return '<track src="' . $src
. '" kind="' . $kind
. '" srclang="' . $srcLanguage
. '" label="' . $label
. '"' . _solidus() . '>';
}
}
if (! function_exists('object')) {
/**
* Object
*
* Generates an object element that represents the media
* as either image or a resource plugin such as audio, video,
* Java applets, ActiveX, PDF and Flash
*
* @param string $data A resource URL
* @param string $type Content-type of the resource
* @param string $attributes HTML attributes
* @param bool $indexPage Should `Config\App::$indexPage` be added to the data path
*/
function object(string $data, string $type = 'unknown', string $attributes = '', array $params = [], bool $indexPage = false): string
{
if (! _has_protocol($data)) {
$data = $indexPage ? site_url($data) : slash_item('baseURL') . $data;
}
$object = '<object data="' . $data . '" '
. $attributes . '>';
if ($params !== []) {
$object .= "\n";
}
foreach ($params as $param) {
$object .= _space_indent() . $param . "\n";
}
return $object . "</object>\n";
}
}
if (! function_exists('param')) {
/**
* Param
*
* Generates a param element that defines parameters
* for the object element.
*
* @param string $name The name of the parameter
* @param string $value The value of the parameter
* @param string $type The MIME-type
* @param string $attributes HTML attributes
*/
function param(string $name, string $value, string $type = 'ref', string $attributes = ''): string
{
return '<param name="' . $name
. '" type="' . $type
. '" value="' . $value
. '" ' . $attributes . _solidus() . '>';
}
}
if (! function_exists('embed')) {
/**
* Embed
*
* Generates an embed element
*
* @param string $src The path of the resource to embed
* @param string $type MIME-type
* @param string $attributes HTML attributes
* @param bool $indexPage Should `Config\App::$indexPage` be added to the source path
*/
function embed(string $src, string $type = 'unknown', string $attributes = '', bool $indexPage = false): string
{
if (! _has_protocol($src)) {
$src = $indexPage ? site_url($src) : slash_item('baseURL') . $src;
}
return '<embed src="' . $src
. '" type="' . $type . '" '
. $attributes . _solidus() . ">\n";
}
}
if (! function_exists('_has_protocol')) {
/**
* Test the protocol of a URI.
*
* @return false|int
*/
function _has_protocol(string $url)
{
return preg_match('#^([a-z]+:)?//#i', $url);
}
}
if (! function_exists('_space_indent')) {
/**
* Provide space indenting.
*/
function _space_indent(int $depth = 2): string
{
return str_repeat(' ', $depth);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/url_helper.php | system/Helpers/url_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\SiteURI;
use CodeIgniter\HTTP\URI;
use CodeIgniter\Router\Exceptions\RouterException;
use Config\App;
// CodeIgniter URL Helpers
if (! function_exists('site_url')) {
/**
* Returns a site URL as defined by the App config.
*
* @param array|string $relativePath URI string or array of URI segments.
* @param string|null $scheme URI scheme. E.g., http, ftp. If empty
* string '' is set, a protocol-relative
* link is returned.
* @param App|null $config Alternate configuration to use.
*/
function site_url($relativePath = '', ?string $scheme = null, ?App $config = null): string
{
$currentURI = service('request')->getUri();
assert($currentURI instanceof SiteURI);
return $currentURI->siteUrl($relativePath, $scheme, $config);
}
}
if (! function_exists('base_url')) {
/**
* Returns the base URL as defined by the App config.
* Base URLs are trimmed site URLs without the index page.
*
* @param array|string $relativePath URI string or array of URI segments.
* @param string|null $scheme URI scheme. E.g., http, ftp. If empty
* string '' is set, a protocol-relative
* link is returned.
*/
function base_url($relativePath = '', ?string $scheme = null): string
{
$currentURI = service('request')->getUri();
assert($currentURI instanceof SiteURI);
return $currentURI->baseUrl($relativePath, $scheme);
}
}
if (! function_exists('current_url')) {
/**
* Returns the current full URL based on the Config\App settings and IncomingRequest.
*
* @param bool $returnObject True to return an object instead of a string
* @param IncomingRequest|null $request A request to use when retrieving the path
*
* @return string|URI When returning string, the query and fragment parts are removed.
* When returning URI, the query and fragment parts are preserved.
*/
function current_url(bool $returnObject = false, ?IncomingRequest $request = null)
{
$request ??= service('request');
/** @var CLIRequest|IncomingRequest $request */
$uri = $request->getUri();
return $returnObject ? $uri : URI::createURIString($uri->getScheme(), $uri->getAuthority(), $uri->getPath());
}
}
if (! function_exists('previous_url')) {
/**
* Returns the previous URL the current visitor was on. For security reasons
* we first check in a saved session variable, if it exists, and use that.
* If that's not available, however, we'll use a sanitized url from $_SERVER['HTTP_REFERER']
* which can be set by the user so is untrusted and not set by certain browsers/servers.
*
* @return string|URI
*/
function previous_url(bool $returnObject = false)
{
// Grab from the session first, if we have it,
// since it's more reliable and safer.
if (isset($_SESSION)) {
$referer = session('_ci_previous_url');
}
// Otherwise, grab a sanitized version from $_SERVER.
$referer ??= request()->getServer('HTTP_REFERER', FILTER_SANITIZE_URL) ?? site_url('/');
return $returnObject ? new URI($referer) : $referer;
}
}
if (! function_exists('uri_string')) {
/**
* URL String
*
* Returns the path part (relative to baseURL) of the current URL
*/
function uri_string(): string
{
// The value of service('request')->getUri()->getPath() returns
// full URI path.
$uri = service('request')->getUri();
$path = $uri instanceof SiteURI ? $uri->getRoutePath() : $uri->getPath();
return ltrim($path, '/');
}
}
if (! function_exists('index_page')) {
/**
* Index page
*
* Returns the "index_page" from your config file
*
* @param App|null $altConfig Alternate configuration to use
*/
function index_page(?App $altConfig = null): string
{
// use alternate config if provided, else default one
$config = $altConfig ?? config(App::class);
return $config->indexPage;
}
}
if (! function_exists('anchor')) {
/**
* Anchor Link
*
* Creates an anchor based on the local URL.
*
* @param array|string $uri URI string or array of URI segments
* @param string $title The link title
* @param array|object|string $attributes Any attributes
* @param App|null $altConfig Alternate configuration to use
*/
function anchor($uri = '', string $title = '', $attributes = '', ?App $altConfig = null): string
{
// use alternate config if provided, else default one
$config = $altConfig ?? config(App::class);
$siteUrl = is_array($uri) ? site_url($uri, null, $config) : (preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config));
// eliminate trailing slash
$siteUrl = rtrim($siteUrl, '/');
if ($title === '') {
$title = $siteUrl;
}
if ($attributes !== '') {
$attributes = stringify_attributes($attributes);
}
return '<a href="' . $siteUrl . '"' . $attributes . '>' . $title . '</a>';
}
}
if (! function_exists('anchor_popup')) {
/**
* Anchor Link - Pop-up version
*
* Creates an anchor based on the local URL. The link
* opens a new window based on the attributes specified.
*
* @param string $uri the URL
* @param string $title the link title
* @param array|false|object|string $attributes any attributes
* @param App|null $altConfig Alternate configuration to use
*/
function anchor_popup($uri = '', string $title = '', $attributes = false, ?App $altConfig = null): string
{
// use alternate config if provided, else default one
$config = $altConfig ?? config(App::class);
$siteUrl = preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config);
$siteUrl = rtrim($siteUrl, '/');
if ($title === '') {
$title = $siteUrl;
}
if ($attributes === false) {
return '<a href="' . $siteUrl . '" onclick="window.open(\'' . $siteUrl . "', '_blank'); return false;\">" . $title . '</a>';
}
if (! is_array($attributes)) {
$attributes = [$attributes];
// Ref: http://www.w3schools.com/jsref/met_win_open.asp
$windowName = '_blank';
} elseif (! empty($attributes['window_name'])) {
$windowName = $attributes['window_name'];
unset($attributes['window_name']);
} else {
$windowName = '_blank';
}
$atts = [];
foreach (['width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'menubar' => 'no', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0'] as $key => $val) {
$atts[$key] = $attributes[$key] ?? $val;
unset($attributes[$key]);
}
$attributes = stringify_attributes($attributes);
return '<a href="' . $siteUrl
. '" onclick="window.open(\'' . $siteUrl . "', '" . $windowName . "', '" . stringify_attributes($atts, true) . "'); return false;\""
. $attributes . '>' . $title . '</a>';
}
}
if (! function_exists('mailto')) {
/**
* Mailto Link
*
* @param string $email the email address
* @param string $title the link title
* @param array|object|string $attributes any attributes
*/
function mailto(string $email, string $title = '', $attributes = ''): string
{
if (trim($title) === '') {
$title = $email;
}
return '<a href="mailto:' . $email . '"' . stringify_attributes($attributes) . '>' . $title . '</a>';
}
}
if (! function_exists('safe_mailto')) {
/**
* Encoded Mailto Link
*
* Create a spam-protected mailto link written in Javascript
*
* @param string $email the email address
* @param string $title the link title
* @param array|object|string $attributes any attributes
*/
function safe_mailto(string $email, string $title = '', $attributes = ''): string
{
$count = 0;
if (trim($title) === '') {
$title = $email;
}
$x = str_split('<a href="mailto:', 1);
for ($i = 0, $l = strlen($email); $i < $l; $i++) {
$x[] = '|' . ord($email[$i]);
}
$x[] = '"';
if ($attributes !== '') {
if (is_array($attributes)) {
foreach ($attributes as $key => $val) {
$x[] = ' ' . $key . '="';
for ($i = 0, $l = strlen($val); $i < $l; $i++) {
$x[] = '|' . ord($val[$i]);
}
$x[] = '"';
}
} else {
for ($i = 0, $l = mb_strlen($attributes); $i < $l; $i++) {
$x[] = mb_substr($attributes, $i, 1);
}
}
}
$x[] = '>';
$temp = [];
for ($i = 0, $l = strlen($title); $i < $l; $i++) {
$ordinal = ord($title[$i]);
if ($ordinal < 128) {
$x[] = '|' . $ordinal;
} else {
if ($temp === []) {
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) === $count) {
$number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64);
$x[] = '|' . $number;
$count = 1;
$temp = [];
}
}
}
$x[] = '<';
$x[] = '/';
$x[] = 'a';
$x[] = '>';
$x = array_reverse($x);
// improve obfuscation by eliminating newlines & whitespace
$cspNonce = csp_script_nonce();
$cspNonce = $cspNonce !== '' ? ' ' . $cspNonce : $cspNonce;
$output = '<script' . $cspNonce . '>'
. 'var l=new Array();';
foreach ($x as $i => $value) {
$output .= 'l[' . $i . "] = '" . $value . "';";
}
return $output . ('for (var i = l.length-1; i >= 0; i=i-1) {'
. "if (l[i].substring(0, 1) === '|') document.write(\"&#\"+unescape(l[i].substring(1))+\";\");"
. 'else document.write(unescape(l[i]));'
. '}'
. '</script>');
}
}
if (! function_exists('auto_link')) {
/**
* Auto-linker
*
* Automatically links URL and Email addresses.
* Note: There's a bit of extra code here to deal with
* URLs or emails that end in a period. We'll strip these
* off and add them after the link.
*
* @param string $str the string
* @param string $type the type: email, url, or both
* @param bool $popup whether to create pop-up links
*/
function auto_link(string $str, string $type = 'both', bool $popup = false): string
{
// Find and replace any URLs.
if (
$type !== 'email'
&& preg_match_all(
'#([a-z][a-z0-9+\-.]*://|www\.)[a-z0-9]+(-+[a-z0-9]+)*(\.[a-z0-9]+(-+[a-z0-9]+)*)+(/([^\s()<>;]+\w)?/?)?#i',
$str,
$matches,
PREG_OFFSET_CAPTURE | PREG_SET_ORDER,
) >= 1
) {
// Set our target HTML if using popup links.
$target = ($popup) ? ' target="_blank"' : '';
// We process the links in reverse order (last -> first) so that
// the returned string offsets from preg_match_all() are not
// moved as we add more HTML.
foreach (array_reverse($matches) as $match) {
// $match[0] is the matched string/link
// $match[1] is either a protocol prefix or 'www.'
//
// With PREG_OFFSET_CAPTURE, both of the above is an array,
// where the actual value is held in [0] and its offset at the [1] index.
$a = '<a href="' . (strpos($match[1][0], '/') ? '' : 'http://') . $match[0][0] . '"' . $target . '>' . $match[0][0] . '</a>';
$str = substr_replace($str, $a, $match[0][1], strlen($match[0][0]));
}
}
// Find and replace any emails.
if (
$type !== 'url'
&& preg_match_all(
'#([\w\.\-\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i',
$str,
$matches,
PREG_OFFSET_CAPTURE,
) >= 1
) {
foreach (array_reverse($matches[0]) as $match) {
if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== false) {
$str = substr_replace($str, safe_mailto($match[0]), $match[1], strlen($match[0]));
}
}
}
return $str;
}
}
if (! function_exists('prep_url')) {
/**
* Prep URL - Simply adds the http:// or https:// part if no scheme is included.
*
* Formerly used URI, but that does not play nicely with URIs missing
* the scheme.
*
* @param string $str the URL
* @param bool $secure set true if you want to force https://
*/
function prep_url(string $str = '', bool $secure = false): string
{
if (in_array($str, ['http://', 'https://', '//', ''], true)) {
return '';
}
if (parse_url($str, PHP_URL_SCHEME) === null) {
$str = 'http://' . ltrim($str, '/');
}
// force replace http:// with https://
if ($secure) {
$str = preg_replace('/^(?:http):/i', 'https:', $str);
}
return $str;
}
}
if (! function_exists('url_title')) {
/**
* Create URL Title
*
* Takes a "title" string as input and creates a
* human-friendly URL string with a "separator" string
* as the word separator.
*
* @param string $str Input string
* @param string $separator Word separator (usually '-' or '_')
* @param bool $lowercase Whether to transform the output string to lowercase
*/
function url_title(string $str, string $separator = '-', bool $lowercase = false): string
{
$qSeparator = preg_quote($separator, '#');
$trans = [
'&.+?;' => '',
'[^\w\d\pL\pM _-]' => '',
'\s+' => $separator,
'(' . $qSeparator . ')+' => $separator,
];
$str = strip_tags($str);
foreach ($trans as $key => $val) {
$str = preg_replace('#' . $key . '#iu', $val, $str);
}
if ($lowercase) {
$str = mb_strtolower($str);
}
return trim(trim($str, $separator));
}
}
if (! function_exists('mb_url_title')) {
/**
* Create URL Title that takes into account accented characters
*
* Takes a "title" string as input and creates a
* human-friendly URL string with a "separator" string
* as the word separator.
*
* @param string $str Input string
* @param string $separator Word separator (usually '-' or '_')
* @param bool $lowercase Whether to transform the output string to lowercase
*/
function mb_url_title(string $str, string $separator = '-', bool $lowercase = false): string
{
helper('text');
return url_title(convert_accented_characters($str), $separator, $lowercase);
}
}
if (! function_exists('url_to')) {
/**
* Get the full, absolute URL to a route name or controller method
* (with additional arguments)
*
* NOTE: This requires the controller/method to
* have a route defined in the routes Config file.
*
* @param string $controller Route name or Controller::method
* @param int|string ...$args One or more parameters to be passed to the route.
* The last parameter allows you to set the locale.
*
* @throws RouterException
*/
function url_to(string $controller, ...$args): string
{
if (! $route = route_to($controller, ...$args)) {
$explode = explode('::', $controller);
if (isset($explode[1])) {
throw RouterException::forControllerNotFound($explode[0], $explode[1]);
}
throw RouterException::forInvalidRoute($controller);
}
return site_url($route);
}
}
if (! function_exists('url_is')) {
/**
* Determines if current url path contains
* the given path. It may contain a wildcard (*)
* which will allow any valid character.
*
* Example:
* if (url_is('admin*')) ...
*/
function url_is(string $path): bool
{
// Setup our regex to allow wildcards
$path = '/' . trim(str_replace('*', '(\S)*', $path), '/ ');
$currentPath = '/' . trim(uri_string(), '/ ');
return (bool) preg_match("|^{$path}$|", $currentPath, $matches);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/form_helper.php | system/Helpers/form_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\Validation\Exceptions\ValidationException;
use Config\App;
use Config\Validation;
// CodeIgniter Form Helpers
if (! function_exists('form_open')) {
/**
* Form Declaration
*
* Creates the opening portion of the form.
*
* @param string $action the URI segments of the form destination
* @param array|string $attributes a key/value pair of attributes, or string representation
* @param array $hidden a key/value pair hidden data
*/
function form_open(string $action = '', $attributes = [], array $hidden = []): string
{
// If no action is provided then set to the current url
if ($action === '') {
$action = (string) current_url(true);
} // If an action is not a full URL then turn it into one
elseif (! str_contains($action, '://')) {
// If an action has {locale}
if (str_contains($action, '{locale}')) {
$action = str_replace('{locale}', service('request')->getLocale(), $action);
}
$action = site_url($action);
}
if (is_array($attributes) && array_key_exists('csrf_id', $attributes)) {
$csrfId = $attributes['csrf_id'];
unset($attributes['csrf_id']);
}
$attributes = stringify_attributes($attributes);
if (! str_contains(strtolower($attributes), 'method=')) {
$attributes .= ' method="post"';
}
if (! str_contains(strtolower($attributes), 'accept-charset=')) {
$config = config(App::class);
$attributes .= ' accept-charset="' . strtolower($config->charset) . '"';
}
$form = '<form action="' . $action . '"' . $attributes . ">\n";
// Add CSRF field if enabled, but leave it out for GET requests and requests to external websites
$before = service('filters')->getFilters()['before'];
if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && str_contains($action, base_url()) && ! str_contains(strtolower($form), strtolower('method="get"'))) {
$form .= csrf_field($csrfId ?? null);
}
foreach ($hidden as $name => $value) {
$form .= form_hidden($name, $value);
}
return $form;
}
}
if (! function_exists('form_open_multipart')) {
/**
* Form Declaration - Multipart type
*
* Creates the opening portion of the form, but with "multipart/form-data".
*
* @param string $action The URI segments of the form destination
* @param array|string $attributes A key/value pair of attributes, or the same as a string
* @param array $hidden A key/value pair hidden data
*/
function form_open_multipart(string $action = '', $attributes = [], array $hidden = []): string
{
if (is_string($attributes)) {
$attributes .= ' enctype="' . esc('multipart/form-data') . '"';
} else {
$attributes['enctype'] = 'multipart/form-data';
}
return form_open($action, $attributes, $hidden);
}
}
if (! function_exists('form_hidden')) {
/**
* Hidden Input Field
*
* Generates hidden fields. You can pass a simple key/value string or
* an associative array with multiple values.
*
* @param array|string $name Field name or associative array to create multiple fields
* @param array|string $value Field value
*/
function form_hidden($name, $value = '', bool $recursing = false): string
{
static $form;
if ($recursing === false) {
$form = "\n";
}
if (is_array($name)) {
foreach ($name as $key => $val) {
form_hidden($key, $val, true);
}
return $form;
}
if (! is_array($value)) {
$form .= form_input($name, $value, '', 'hidden');
} else {
foreach ($value as $k => $v) {
$k = is_int($k) ? '' : $k;
form_hidden($name . '[' . $k . ']', $v, true);
}
}
return $form;
}
}
if (! function_exists('form_input')) {
/**
* Text Input Field. If 'type' is passed in the $type field, it will be
* used as the input type, for making 'email', 'phone', etc input fields.
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_input($data = '', string $value = '', $extra = '', string $type = 'text'): string
{
$defaults = [
'type' => $type,
'name' => is_array($data) ? '' : $data,
'value' => $value,
];
return '<input ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . _solidus() . ">\n";
}
}
if (! function_exists('form_password')) {
/**
* Password Field
*
* Identical to the input function but adds the "password" type
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_password($data = '', string $value = '', $extra = ''): string
{
if (! is_array($data)) {
$data = ['name' => $data];
}
$data['type'] = 'password';
return form_input($data, $value, $extra);
}
}
if (! function_exists('form_upload')) {
/**
* Upload Field
*
* Identical to the input function but adds the "file" type
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_upload($data = '', string $value = '', $extra = ''): string
{
$defaults = [
'type' => 'file',
'name' => '',
];
if (! is_array($data)) {
$data = ['name' => $data];
}
$data['type'] = 'file';
return '<input ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . _solidus() . ">\n";
}
}
if (! function_exists('form_textarea')) {
/**
* Textarea field
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_textarea($data = '', string $value = '', $extra = ''): string
{
$defaults = [
'name' => is_array($data) ? '' : $data,
'cols' => '40',
'rows' => '10',
];
if (! is_array($data) || ! isset($data['value'])) {
$val = $value;
} else {
$val = $data['value'];
unset($data['value']); // textareas don't use the value attribute
}
// Unsets default rows and cols if defined in extra field as array or string.
if ((is_array($extra) && array_key_exists('rows', $extra)) || (is_string($extra) && str_contains(strtolower(preg_replace('/\s+/', '', $extra)), 'rows='))) {
unset($defaults['rows']);
}
if ((is_array($extra) && array_key_exists('cols', $extra)) || (is_string($extra) && str_contains(strtolower(preg_replace('/\s+/', '', $extra)), 'cols='))) {
unset($defaults['cols']);
}
return '<textarea ' . rtrim(parse_form_attributes($data, $defaults)) . stringify_attributes($extra) . '>'
. htmlspecialchars($val)
. "</textarea>\n";
}
}
if (! function_exists('form_multiselect')) {
/**
* Multi-select menu
*
* @param array|string $name
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_multiselect($name = '', array $options = [], array $selected = [], $extra = ''): string
{
$extra = stringify_attributes($extra);
if (! str_contains(strtolower($extra), strtolower('multiple'))) {
$extra .= ' multiple="multiple"';
}
return form_dropdown($name, $options, $selected, $extra);
}
}
if (! function_exists('form_dropdown')) {
/**
* Drop-down Menu
*
* @param array|string $data
* @param array|string $options
* @param array|string $selected
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): string
{
$defaults = [];
if (is_array($data)) {
if (isset($data['selected'])) {
$selected = $data['selected'];
unset($data['selected']); // select tags don't have a selected attribute
}
if (isset($data['options'])) {
$options = $data['options'];
unset($data['options']); // select tags don't use an options attribute
}
} else {
$defaults = ['name' => $data];
}
if (! is_array($selected)) {
$selected = [$selected];
}
if (! is_array($options)) {
$options = [$options];
}
// If no selected state was submitted we will attempt to set it automatically
if ($selected === []) {
if (is_array($data)) {
if (isset($data['name'], $_POST[$data['name']])) {
$selected = [$_POST[$data['name']]];
}
} elseif (isset($_POST[$data])) {
$selected = [$_POST[$data]];
}
}
// Standardize selected as strings, like the option keys will be
foreach ($selected as $key => $item) {
$selected[$key] = (string) $item;
}
$extra = stringify_attributes($extra);
$multiple = (count($selected) > 1 && ! str_contains(strtolower($extra), 'multiple')) ? ' multiple="multiple"' : '';
$form = '<select ' . rtrim(parse_form_attributes($data, $defaults)) . $extra . $multiple . ">\n";
foreach ($options as $key => $val) {
// Keys should always be strings for strict comparison
$key = (string) $key;
if (is_array($val)) {
if ($val === []) {
continue;
}
$form .= '<optgroup label="' . $key . "\">\n";
foreach ($val as $optgroupKey => $optgroupVal) {
// Keys should always be strings for strict comparison
$optgroupKey = (string) $optgroupKey;
$sel = in_array($optgroupKey, $selected, true) ? ' selected="selected"' : '';
$form .= '<option value="' . htmlspecialchars($optgroupKey) . '"' . $sel . '>' . $optgroupVal . "</option>\n";
}
$form .= "</optgroup>\n";
} else {
$form .= '<option value="' . htmlspecialchars($key) . '"'
. (in_array($key, $selected, true) ? ' selected="selected"' : '') . '>'
. $val . "</option>\n";
}
}
return $form . "</select>\n";
}
}
if (! function_exists('form_checkbox')) {
/**
* Checkbox Field
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_checkbox($data = '', string $value = '', bool $checked = false, $extra = ''): string
{
$defaults = [
'type' => 'checkbox',
'name' => (! is_array($data) ? $data : ''),
'value' => $value,
];
if (is_array($data) && array_key_exists('checked', $data)) {
$checked = $data['checked'];
if ($checked === false) {
unset($data['checked']);
} else {
$data['checked'] = 'checked';
}
}
if ($checked === true) {
$defaults['checked'] = 'checked';
}
return '<input ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . _solidus() . ">\n";
}
}
if (! function_exists('form_radio')) {
/**
* Radio Button
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_radio($data = '', string $value = '', bool $checked = false, $extra = ''): string
{
if (! is_array($data)) {
$data = ['name' => $data];
}
$data['type'] = 'radio';
return form_checkbox($data, $value, $checked, $extra);
}
}
if (! function_exists('form_submit')) {
/**
* Submit Button
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_submit($data = '', string $value = '', $extra = ''): string
{
return form_input($data, $value, $extra, 'submit');
}
}
if (! function_exists('form_reset')) {
/**
* Reset Button
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_reset($data = '', string $value = '', $extra = ''): string
{
return form_input($data, $value, $extra, 'reset');
}
}
if (! function_exists('form_button')) {
/**
* Form Button
*
* @param array|string $data
* @param array|object|string $extra string, array, object that can be cast to array
*/
function form_button($data = '', string $content = '', $extra = ''): string
{
$defaults = [
'name' => is_array($data) ? '' : $data,
'type' => 'button',
];
if (is_array($data) && isset($data['content'])) {
$content = $data['content'];
unset($data['content']); // content is not an attribute
}
return '<button ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . '>'
. $content
. "</button>\n";
}
}
if (! function_exists('form_label')) {
/**
* Form Label Tag
*
* @param string $labelText The text to appear onscreen
* @param string $id The id the label applies to
* @param array $attributes Additional attributes
*/
function form_label(string $labelText = '', string $id = '', array $attributes = []): string
{
$label = '<label';
if ($id !== '') {
$label .= ' for="' . $id . '"';
}
foreach ($attributes as $key => $val) {
$label .= ' ' . $key . '="' . $val . '"';
}
return $label . '>' . $labelText . '</label>';
}
}
if (! function_exists('form_datalist')) {
/**
* Datalist
*
* The <datalist> element specifies a list of pre-defined options for an <input> element.
* Users will see a drop-down list of pre-defined options as they input data.
* The list attribute of the <input> element, must refer to the id attribute of the <datalist> element.
*/
function form_datalist(string $name, string $value, array $options): string
{
$data = [
'type' => 'text',
'name' => $name,
'list' => $name . '_list',
'value' => $value,
];
$out = form_input($data) . "\n";
$out .= "<datalist id='" . $name . "_list'>";
foreach ($options as $option) {
$out .= "<option value='{$option}'>\n";
}
return $out . ("</datalist>\n");
}
}
if (! function_exists('form_fieldset')) {
/**
* Fieldset Tag
*
* Used to produce <fieldset><legend>text</legend>. To close fieldset
* use form_fieldset_close()
*
* @param string $legendText The legend text
* @param array $attributes Additional attributes
*/
function form_fieldset(string $legendText = '', array $attributes = []): string
{
$fieldset = '<fieldset' . stringify_attributes($attributes) . ">\n";
if ($legendText !== '') {
return $fieldset . '<legend>' . $legendText . "</legend>\n";
}
return $fieldset;
}
}
if (! function_exists('form_fieldset_close')) {
/**
* Fieldset Close Tag
*/
function form_fieldset_close(string $extra = ''): string
{
return '</fieldset>' . $extra;
}
}
if (! function_exists('form_close')) {
/**
* Form Close Tag
*/
function form_close(string $extra = ''): string
{
return '</form>' . $extra;
}
}
if (! function_exists('set_value')) {
/**
* Form Value
*
* Grabs a value from the POST array for the specified field so you can
* re-populate an input field or textarea
*
* @param string $field Field name
* @param list<string>|string $default Default value
* @param bool $htmlEscape Whether to escape HTML special characters or not
*
* @return list<string>|string
*/
function set_value(string $field, $default = '', bool $htmlEscape = true)
{
$request = service('request');
// Try any old input data we may have first
$value = $request->getOldInput($field);
if ($value === null) {
$value = $request->getPost($field) ?? $default;
}
return ($htmlEscape) ? esc($value) : $value;
}
}
if (! function_exists('set_select')) {
/**
* Set Select
*
* Let's you set the selected value of a <select> menu via data in the POST array.
*/
function set_select(string $field, string $value = '', bool $default = false): string
{
$request = service('request');
// Try any old input data we may have first
$input = $request->getOldInput($field);
if ($input === null) {
$input = $request->getPost($field);
}
if ($input === null) {
return $default ? ' selected="selected"' : '';
}
if (is_array($input)) {
// Note: in_array('', array(0)) returns TRUE, do not use it
foreach ($input as &$v) {
if ($value === $v) {
return ' selected="selected"';
}
}
return '';
}
return ($input === $value) ? ' selected="selected"' : '';
}
}
if (! function_exists('set_checkbox')) {
/**
* Set Checkbox
*
* Let's you set the selected value of a checkbox via the value in the POST array.
*/
function set_checkbox(string $field, string $value = '', bool $default = false): string
{
$request = service('request');
// Try any old input data we may have first
$input = $request->getOldInput($field);
if ($input === null) {
$input = $request->getPost($field);
}
if (is_array($input)) {
// Note: in_array('', array(0)) returns TRUE, do not use it
foreach ($input as &$v) {
if ($value === $v) {
return ' checked="checked"';
}
}
return '';
}
$session = service('session');
$hasOldInput = $session->has('_ci_old_input');
// Unchecked checkbox and radio inputs are not even submitted by browsers ...
if ((string) $input === '0' || ! empty($request->getPost()) || $hasOldInput) {
return ($input === $value) ? ' checked="checked"' : '';
}
return $default ? ' checked="checked"' : '';
}
}
if (! function_exists('set_radio')) {
/**
* Set Radio
*
* Let's you set the selected value of a radio field via info in the POST array.
*/
function set_radio(string $field, string $value = '', bool $default = false): string
{
$request = service('request');
// Try any old input data we may have first
$oldInput = $request->getOldInput($field);
$postInput = $request->getPost($field);
$input = $oldInput ?? $postInput ?? $default;
if (is_array($input)) {
// Note: in_array('', array(0)) returns TRUE, do not use it
foreach ($input as $v) {
if ($value === $v) {
return ' checked="checked"';
}
}
return '';
}
// Unchecked checkbox and radio inputs are not even submitted by browsers ...
if ($oldInput !== null || $postInput !== null) {
return ((string) $input === $value) ? ' checked="checked"' : '';
}
return $default ? ' checked="checked"' : '';
}
}
if (! function_exists('validation_errors')) {
/**
* Returns the validation errors.
*
* First, checks the validation errors that are stored in the session.
* To store the errors in the session, you need to use `withInput()` with `redirect()`.
*
* The returned array should be in the following format:
* [
* 'field1' => 'error message',
* 'field2' => 'error message',
* ]
*
* @return array<string, string>
*/
function validation_errors()
{
$errors = session('_ci_validation_errors');
// Check the session to see if any were
// passed along from a redirect withErrors() request.
if ($errors !== null && (ENVIRONMENT === 'testing' || ! is_cli())) {
return $errors;
}
$validation = service('validation');
return $validation->getErrors();
}
}
if (! function_exists('validation_list_errors')) {
/**
* Returns the rendered HTML of the validation errors.
*
* See Validation::listErrors()
*/
function validation_list_errors(string $template = 'list'): string
{
$config = config(Validation::class);
$view = service('renderer');
if (! array_key_exists($template, $config->templates)) {
throw ValidationException::forInvalidTemplate($template);
}
return $view->setVar('errors', validation_errors())
->render($config->templates[$template]);
}
}
if (! function_exists('validation_show_error')) {
/**
* Returns a single error for the specified field in formatted HTML.
*
* See Validation::showError()
*/
function validation_show_error(string $field, string $template = 'single'): string
{
$config = config(Validation::class);
$view = service('renderer');
$errors = array_filter(validation_errors(), static fn ($key): bool => preg_match(
'/^' . str_replace(['\.\*', '\*\.'], ['\..+', '.+\.'], preg_quote($field, '/')) . '$/',
$key,
) === 1, ARRAY_FILTER_USE_KEY);
if ($errors === []) {
return '';
}
if (! array_key_exists($template, $config->templates)) {
throw ValidationException::forInvalidTemplate($template);
}
return $view->setVar('error', implode("\n", $errors))
->render($config->templates[$template]);
}
}
if (! function_exists('parse_form_attributes')) {
/**
* Parse the form attributes
*
* Helper function used by some of the form helpers
*
* @internal
*
* @param array|string $attributes List of attributes
* @param array $default Default values
*/
function parse_form_attributes($attributes, array $default): string
{
if (is_array($attributes)) {
foreach (array_keys($default) as $key) {
if (isset($attributes[$key])) {
$default[$key] = $attributes[$key];
unset($attributes[$key]);
}
}
if ($attributes !== []) {
$default = array_merge($default, $attributes);
}
}
$att = '';
foreach ($default as $key => $val) {
if (! is_bool($val)) {
if ($key === 'value') {
$val = esc($val);
} elseif ($key === 'name' && $default['name'] === '') {
continue;
}
$att .= $key . '="' . $val . '"' . ($key === array_key_last($default) ? '' : ' ');
} else {
$att .= $key . ' ';
}
}
return $att;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/inflector_helper.php | system/Helpers/inflector_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
// CodeIgniter Inflector Helpers
if (! function_exists('singular')) {
/**
* Singular
*
* Takes a plural word and makes it singular
*
* @param string $string Input string
*/
function singular(string $string): string
{
$result = $string;
if (! is_pluralizable($result)) {
return $result;
}
// Arranged in order.
$singularRules = [
'/(matr)ices$/' => '\1ix',
'/(vert|ind)ices$/' => '\1ex',
'/^(ox)en/' => '\1',
'/(alias)es$/' => '\1',
'/([octop|vir])i$/' => '\1us',
'/(cris|ax|test)es$/' => '\1is',
'/(shoe)s$/' => '\1',
'/(o)es$/' => '\1',
'/(bus|campus)es$/' => '\1',
'/([m|l])ice$/' => '\1ouse',
'/(x|ch|ss|sh)es$/' => '\1',
'/(m)ovies$/' => '\1\2ovie',
'/(s)eries$/' => '\1\2eries',
'/([^aeiouy]|qu)ies$/' => '\1y',
'/([lr])ves$/' => '\1f',
'/(tive)s$/' => '\1',
'/(hive)s$/' => '\1',
'/([^f])ves$/' => '\1fe',
'/(^analy)ses$/' => '\1sis',
'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis',
'/([ti])a$/' => '\1um',
'/(p)eople$/' => '\1\2erson',
'/(m)en$/' => '\1an',
'/(s)tatuses$/' => '\1\2tatus',
'/(c)hildren$/' => '\1\2hild',
'/(n)ews$/' => '\1\2ews',
'/(quiz)zes$/' => '\1',
'/([^us])s$/' => '\1',
];
foreach ($singularRules as $rule => $replacement) {
if (preg_match($rule, $result)) {
$result = preg_replace($rule, $replacement, $result);
break;
}
}
return $result;
}
}
if (! function_exists('plural')) {
/**
* Plural
*
* Takes a singular word and makes it plural
*
* @param string $string Input string
*/
function plural(string $string): string
{
$result = $string;
if (! is_pluralizable($result)) {
return $result;
}
$pluralRules = [
'/(quiz)$/' => '\1zes', // quizzes
'/^(ox)$/' => '\1\2en', // ox
'/([m|l])ouse$/' => '\1ice', // mouse, louse
'/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index
'/(x|ch|ss|sh)$/' => '\1es', // search, switch, fix, box, process, address
'/([^aeiouy]|qu)y$/' => '\1ies', // query, ability, agency
'/(hive)$/' => '\1s', // archive, hive
'/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife
'/sis$/' => 'ses', // basis, diagnosis
'/([ti])um$/' => '\1a', // datum, medium
'/(p)erson$/' => '\1eople', // person, salesperson
'/(m)an$/' => '\1en', // man, woman, spokesman
'/(c)hild$/' => '\1hildren', // child
'/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato
'/(bu|campu)s$/' => '\1\2ses', // bus, campus
'/(alias|status|virus)$/' => '\1es', // alias
'/(octop)us$/' => '\1i', // octopus
'/(ax|cris|test)is$/' => '\1es', // axis, crisis
'/s$/' => 's', // no change (compatibility)
'/$/' => 's',
];
foreach ($pluralRules as $rule => $replacement) {
if (preg_match($rule, $result)) {
$result = preg_replace($rule, $replacement, $result);
break;
}
}
return $result;
}
}
if (! function_exists('counted')) {
/**
* Counted
*
* Takes a number and a word to return the plural or not
* E.g. 0 cats, 1 cat, 2 cats, ...
*
* @param int $count Number of items
* @param string $string Input string
*/
function counted(int $count, string $string): string
{
$result = "{$count} ";
return $result . ($count === 1 ? singular($string) : plural($string));
}
}
if (! function_exists('camelize')) {
/**
* Camelize
*
* Takes multiple words separated by spaces or
* underscores and converts them to camel case.
*
* @param string $string Input string
*/
function camelize(string $string): string
{
return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[\s_]+/', ' ', $string))));
}
}
if (! function_exists('pascalize')) {
/**
* Pascalize
*
* Takes multiple words separated by spaces or
* underscores and converts them to Pascal case,
* which is camel case with an uppercase first letter.
*
* @param string $string Input string
*/
function pascalize(string $string): string
{
return ucfirst(camelize($string));
}
}
if (! function_exists('underscore')) {
/**
* Underscore
*
* Takes multiple words separated by spaces and underscores them
*
* @param string $string Input string
*/
function underscore(string $string): string
{
$replacement = trim($string);
return preg_replace('/[\s]+/', '_', $replacement);
}
}
if (! function_exists('decamelize')) {
/**
* Decamelize
*
* Takes multiple words separated by camel case and
* underscores them.
*
* @param string $string Input string
*/
function decamelize(string $string): string
{
return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', trim($string)));
}
}
if (! function_exists('humanize')) {
/**
* Humanize
*
* Takes multiple words separated by the separator,
* camelizes and changes them to spaces
*
* @param string $string Input string
* @param string $separator Input separator
*/
function humanize(string $string, string $separator = '_'): string
{
$replacement = trim($string);
return ucwords(preg_replace('/[' . $separator . ']+/', ' ', $replacement));
}
}
if (! function_exists('is_pluralizable')) {
/**
* Checks if the given word has a plural version.
*
* @param string $word Word to check
*/
function is_pluralizable(string $word): bool
{
$uncountables = in_array(
strtolower($word),
[
'advice',
'bravery',
'butter',
'chaos',
'clarity',
'coal',
'courage',
'cowardice',
'curiosity',
'education',
'equipment',
'evidence',
'fish',
'fun',
'furniture',
'greed',
'help',
'homework',
'honesty',
'information',
'insurance',
'jewelry',
'knowledge',
'livestock',
'love',
'luck',
'marketing',
'meta',
'money',
'mud',
'news',
'patriotism',
'racism',
'rice',
'satisfaction',
'scenery',
'series',
'sexism',
'silence',
'species',
'spelling',
'sugar',
'water',
'weather',
'wisdom',
'work',
],
true,
);
return ! $uncountables;
}
}
if (! function_exists('dasherize')) {
/**
* Replaces underscores with dashes in the string.
*
* @param string $string Input string
*/
function dasherize(string $string): string
{
return str_replace('_', '-', $string);
}
}
if (! function_exists('ordinal')) {
/**
* Returns the suffix that should be added to a
* number to denote the position in an ordered
* sequence such as 1st, 2nd, 3rd, 4th.
*
* @param int $integer The integer to determine the suffix
*/
function ordinal(int $integer): string
{
$suffixes = [
'th',
'st',
'nd',
'rd',
'th',
'th',
'th',
'th',
'th',
'th',
];
return $integer % 100 >= 11 && $integer % 100 <= 13 ? 'th' : $suffixes[$integer % 10];
}
}
if (! function_exists('ordinalize')) {
/**
* Turns a number into an ordinal string used
* to denote the position in an ordered sequence
* such as 1st, 2nd, 3rd, 4th.
*
* @param int $integer The integer to ordinalize
*/
function ordinalize(int $integer): string
{
return $integer . ordinal($integer);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/kint_helper.php | system/Helpers/kint_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
// This helper is autoloaded by CodeIgniter.
if (! function_exists('dd')) {
if (class_exists(Kint::class)) {
/**
* Prints a Kint debug report and exits.
*
* @param array $vars
*
* @return never
*
* @codeCoverageIgnore Can't be tested ... exits
*/
function dd(...$vars): void
{
// @codeCoverageIgnoreStart
Kint::$aliases[] = 'dd';
Kint::dump(...$vars);
exit;
// @codeCoverageIgnoreEnd
}
} else {
// In case that Kint is not loaded.
/**
* dd function
*
* @param array $vars
*
* @return int
*/
function dd(...$vars)
{
return 0;
}
}
}
if (! function_exists('d') && ! class_exists(Kint::class)) {
// In case that Kint is not loaded.
/**
* d function
*
* @param array $vars
*
* @return int
*/
function d(...$vars)
{
return 0;
}
}
if (! function_exists('trace')) {
if (class_exists(Kint::class)) {
/**
* Provides a backtrace to the current execution point, from Kint.
*/
/**
* trace function
*/
function trace(): void
{
Kint::$aliases[] = 'trace';
Kint::trace();
}
} else {
// In case that Kint is not loaded.
/**
* trace function
*
* @return int
*/
function trace()
{
return 0;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/security_helper.php | system/Helpers/security_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
// CodeIgniter Security Helpers
if (! function_exists('sanitize_filename')) {
/**
* Sanitize Filename
*
* Tries to sanitize filenames in order to prevent directory traversal attempts
* and other security threats, which is particularly useful for files that
* were supplied via user input.
*
* If it is acceptable for the user input to include relative paths,
* e.g. file/in/some/approved/folder.txt, you can set the second optional
* parameter, $relativePath to TRUE.
*
* @param string $filename Input file name
* @param bool $relativePath Whether to preserve paths
*/
function sanitize_filename(string $filename, bool $relativePath = false): string
{
// List of sanitized filename strings
$bad = [
'../',
'<!--',
'-->',
'<',
'>',
"'",
'"',
'&',
'$',
'#',
'{',
'}',
'[',
']',
'=',
';',
'?',
'%20',
'%22',
'%3c',
'%253c',
'%3e',
'%0e',
'%28',
'%29',
'%2528',
'%26',
'%24',
'%3f',
'%3b',
'%3d',
];
if (! $relativePath) {
$bad[] = './';
$bad[] = '/';
}
$filename = remove_invisible_characters($filename, false);
do {
$old = $filename;
$filename = str_replace($bad, '', $filename);
} while ($old !== $filename);
return stripslashes($filename);
}
}
if (! function_exists('strip_image_tags')) {
/**
* Strip Image Tags
*/
function strip_image_tags(string $str): string
{
return preg_replace(
[
'#<img[\s/]+.*?src\s*=\s*(["\'])([^\\1]+?)\\1.*?\>#i',
'#<img[\s/]+.*?src\s*=\s*?(([^\s"\'=<>`]+)).*?\>#i',
],
'\\2',
$str,
);
}
}
if (! function_exists('encode_php_tags')) {
/**
* Convert PHP tags to entities
*/
function encode_php_tags(string $str): string
{
return str_replace(['<?', '?>'], ['<?', '?>'], $str);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/array_helper.php | system/Helpers/array_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\Helpers\Array\ArrayHelper;
// CodeIgniter Array Helpers
if (! function_exists('dot_array_search')) {
/**
* Searches an array through dot syntax. Supports
* wildcard searches, like foo.*.bar
*
* @return array|bool|int|object|string|null
*/
function dot_array_search(string $index, array $array)
{
return ArrayHelper::dotSearch($index, $array);
}
}
if (! function_exists('array_deep_search')) {
/**
* Returns the value of an element at a key in an array of uncertain depth.
*
* @param int|string $key
*
* @return array|bool|float|int|object|string|null
*/
function array_deep_search($key, array $array)
{
if (isset($array[$key])) {
return $array[$key];
}
foreach ($array as $value) {
if (is_array($value) && ($result = array_deep_search($key, $value))) {
return $result;
}
}
return null;
}
}
if (! function_exists('array_sort_by_multiple_keys')) {
/**
* Sorts a multidimensional array by its elements values. The array
* columns to be used for sorting are passed as an associative
* array of key names and sorting flags.
*
* Both arrays of objects and arrays of array can be sorted.
*
* Example:
* array_sort_by_multiple_keys($players, [
* 'team.hierarchy' => SORT_ASC,
* 'position' => SORT_ASC,
* 'name' => SORT_STRING,
* ]);
*
* The '.' dot operator in the column name indicates a deeper array or
* object level. In principle, any number of sublevels could be used,
* as long as the level and column exist in every array element.
*
* For information on multi-level array sorting, refer to Example #3 here:
* https://www.php.net/manual/de/function.array-multisort.php
*
* @param array $array the reference of the array to be sorted
* @param array $sortColumns an associative array of columns to sort
* after and their sorting flags
*/
function array_sort_by_multiple_keys(array &$array, array $sortColumns): bool
{
// Check if there really are columns to sort after
if ($sortColumns === [] || $array === []) {
return false;
}
// Group sorting indexes and data
$tempArray = [];
foreach ($sortColumns as $key => $sortFlag) {
// Get sorting values
$carry = $array;
// The '.' operator separates nested elements
foreach (explode('.', $key) as $keySegment) {
// Loop elements if they are objects
if (is_object(reset($carry))) {
// Extract the object attribute
foreach ($carry as $index => $object) {
$carry[$index] = $object->{$keySegment};
}
continue;
}
// Extract the target column if elements are arrays
$carry = array_column($carry, $keySegment);
}
// Store the collected sorting parameters
$tempArray[] = $carry;
$tempArray[] = $sortFlag;
}
// Append the array as reference
$tempArray[] = &$array;
// Pass sorting arrays and flags as an argument list.
return array_multisort(...$tempArray);
}
}
if (! function_exists('array_flatten_with_dots')) {
/**
* Flatten a multidimensional array using dots as separators.
*
* @param iterable $array The multi-dimensional array
* @param string $id Something to initially prepend to the flattened keys
*
* @return array The flattened array
*/
function array_flatten_with_dots(iterable $array, string $id = ''): array
{
$flattened = [];
foreach ($array as $key => $value) {
$newKey = $id . $key;
if (is_array($value) && $value !== []) {
$flattened = array_merge($flattened, array_flatten_with_dots($value, $newKey . '.'));
} else {
$flattened[$newKey] = $value;
}
}
return $flattened;
}
}
if (! function_exists('array_group_by')) {
/**
* Groups all rows by their index values. Result's depth equals number of indexes
*
* @param array $array Data array (i.e. from query result)
* @param array $indexes Indexes to group by. Dot syntax used. Returns $array if empty
* @param bool $includeEmpty If true, null and '' are also added as valid keys to group
*
* @return array Result array where rows are grouped together by indexes values.
*/
function array_group_by(array $array, array $indexes, bool $includeEmpty = false): array
{
return ArrayHelper::groupBy($array, $indexes, $includeEmpty);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/text_helper.php | system/Helpers/text_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\Exceptions\InvalidArgumentException;
use Config\ForeignCharacters;
// CodeIgniter Text Helpers
if (! function_exists('word_limiter')) {
/**
* Word Limiter
*
* Limits a string to X number of words.
*
* @param string $endChar the end character. Usually an ellipsis
*/
function word_limiter(string $str, int $limit = 100, string $endChar = '…'): string
{
if (trim($str) === '') {
return $str;
}
preg_match('/^\s*+(?:\S++\s*+){1,' . $limit . '}/', $str, $matches);
if (strlen($str) === strlen($matches[0])) {
$endChar = '';
}
return rtrim($matches[0]) . $endChar;
}
}
if (! function_exists('character_limiter')) {
/**
* Character Limiter
*
* Limits the string based on the character count. Preserves complete words
* so the character count may not be exactly as specified.
*
* @param string $endChar the end character. Usually an ellipsis
*/
function character_limiter(string $string, int $limit = 500, string $endChar = '…'): string
{
if (mb_strlen($string) < $limit) {
return $string;
}
// a bit complicated, but faster than preg_replace with \s+
$string = preg_replace('/ {2,}/', ' ', str_replace(["\r", "\n", "\t", "\x0B", "\x0C"], ' ', $string));
$stringLength = mb_strlen($string);
if ($stringLength <= $limit) {
return $string;
}
$output = '';
$outputLength = 0;
$words = explode(' ', trim($string));
foreach ($words as $word) {
$output .= $word . ' ';
$outputLength = mb_strlen($output);
if ($outputLength >= $limit) {
$output = trim($output);
break;
}
}
return ($outputLength === $stringLength) ? $output : $output . $endChar;
}
}
if (! function_exists('ascii_to_entities')) {
/**
* High ASCII to Entities
*
* Converts high ASCII text and MS Word special characters to character entities
*/
function ascii_to_entities(string $str): string
{
$out = '';
for ($i = 0, $s = strlen($str) - 1, $count = 1, $temp = []; $i <= $s; $i++) {
$ordinal = ord($str[$i]);
if ($ordinal < 128) {
/*
If the $temp array has a value but we have moved on, then it seems only
fair that we output that entity and restart $temp before continuing.
*/
if (count($temp) === 1) {
$out .= '&#' . array_shift($temp) . ';';
$count = 1;
}
$out .= $str[$i];
} else {
if ($temp === []) {
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) === $count) {
$number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64);
$out .= '&#' . $number . ';';
$count = 1;
$temp = [];
}
// If this is the last iteration, just output whatever we have
elseif ($i === $s) {
$out .= '&#' . implode(';', $temp) . ';';
}
}
}
return $out;
}
}
if (! function_exists('entities_to_ascii')) {
/**
* Entities to ASCII
*
* Converts character entities back to ASCII
*/
function entities_to_ascii(string $str, bool $all = true): string
{
if (preg_match_all('/\&#(\d+)\;/', $str, $matches) >= 1) {
for ($i = 0, $s = count($matches[0]); $i < $s; $i++) {
$digits = (int) $matches[1][$i];
$out = '';
if ($digits < 128) {
$out .= chr($digits);
} elseif ($digits < 2048) {
$out .= chr(192 + (($digits - ($digits % 64)) / 64)) . chr(128 + ($digits % 64));
} else {
$out .= chr(224 + (($digits - ($digits % 4096)) / 4096))
. chr(128 + ((($digits % 4096) - ($digits % 64)) / 64))
. chr(128 + ($digits % 64));
}
$str = str_replace($matches[0][$i], $out, $str);
}
}
if ($all) {
return str_replace(
['&', '<', '>', '"', ''', '-'],
['&', '<', '>', '"', "'", '-'],
$str,
);
}
return $str;
}
}
if (! function_exists('word_censor')) {
/**
* Word Censoring Function
*
* Supply a string and an array of disallowed words and any
* matched words will be converted to #### or to the replacement
* word you've submitted.
*
* @param string $str the text string
* @param array $censored the array of censored words
* @param string $replacement the optional replacement value
*/
function word_censor(string $str, array $censored, string $replacement = ''): string
{
if ($censored === []) {
return $str;
}
$str = ' ' . $str . ' ';
// \w, \b and a few others do not match on a unicode character
// set for performance reasons. As a result words like über
// will not match on a word boundary. Instead, we'll assume that
// a bad word will be bookended by any of these characters.
$delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
foreach ($censored as $badword) {
$badword = str_replace('\*', '\w*?', preg_quote($badword, '/'));
if ($replacement !== '') {
$str = preg_replace(
"/({$delim})(" . $badword . ")({$delim})/i",
"\\1{$replacement}\\3",
$str,
);
} elseif (preg_match_all("/{$delim}(" . $badword . "){$delim}/i", $str, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE) >= 1) {
$matches = $matches[1];
for ($i = count($matches) - 1; $i >= 0; $i--) {
$length = strlen($matches[$i][0]);
$str = substr_replace(
$str,
str_repeat('#', $length),
$matches[$i][1],
$length,
);
}
}
}
return trim($str);
}
}
if (! function_exists('highlight_code')) {
/**
* Code Highlighter
*
* Colorizes code strings
*
* @param string $str the text string
*/
function highlight_code(string $str): string
{
/* The highlight string function encodes and highlights
* brackets so we need them to start raw.
*
* Also replace any existing PHP tags to temporary markers
* so they don't accidentally break the string out of PHP,
* and thus, thwart the highlighting.
*/
$str = str_replace(
['<', '>', '<?', '?>', '<%', '%>', '\\', '</script>'],
['<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'],
$str,
);
// The highlight_string function requires that the text be surrounded
// by PHP tags, which we will remove later
$str = highlight_string('<?php ' . $str . ' ?>', true);
// Remove our artificially added PHP, and the syntax highlighting that came with it
$str = preg_replace(
[
'/<span style="color: #([A-Z0-9]+)"><\?php( | )/i',
'/(<span style="color: #[A-Z0-9]+">.*?)\?><\/span>\n<\/span>\n<\/code>/is',
'/<span style="color: #[A-Z0-9]+"\><\/span>/i',
],
[
'<span style="color: #$1">',
"$1</span>\n</span>\n</code>",
'',
],
$str,
);
// Replace our markers back to PHP tags.
return str_replace(
[
'phptagopen',
'phptagclose',
'asptagopen',
'asptagclose',
'backslashtmp',
'scriptclose',
],
[
'<?',
'?>',
'<%',
'%>',
'\\',
'</script>',
],
$str,
);
}
}
if (! function_exists('highlight_phrase')) {
/**
* Phrase Highlighter
*
* Highlights a phrase within a text string
*
* @param string $str the text string
* @param string $phrase the phrase you'd like to highlight
* @param string $tagOpen the opening tag to precede the phrase with
* @param string $tagClose the closing tag to end the phrase with
*/
function highlight_phrase(string $str, string $phrase, string $tagOpen = '<mark>', string $tagClose = '</mark>'): string
{
return ($str !== '' && $phrase !== '') ? preg_replace('/(' . preg_quote($phrase, '/') . ')/i', $tagOpen . '\\1' . $tagClose, $str) : $str;
}
}
if (! function_exists('convert_accented_characters')) {
/**
* Convert Accented Foreign Characters to ASCII
*
* @param string $str Input string
*/
function convert_accented_characters(string $str): string
{
static $arrayFrom, $arrayTo;
if (! is_array($arrayFrom)) {
$config = new ForeignCharacters();
if ($config->characterList === [] || ! is_array($config->characterList)) {
$arrayFrom = [];
$arrayTo = [];
return $str;
}
$arrayFrom = array_keys($config->characterList);
$arrayTo = array_values($config->characterList);
unset($config);
}
return preg_replace($arrayFrom, $arrayTo, $str);
}
}
if (! function_exists('word_wrap')) {
/**
* Word Wrap
*
* Wraps text at the specified character. Maintains the integrity of words.
* Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
* will URLs.
*
* @param string $str the text string
* @param int $charlim = 76 the number of characters to wrap at
*/
function word_wrap(string $str, int $charlim = 76): string
{
// Reduce multiple spaces
$str = preg_replace('| +|', ' ', $str);
// Standardize newlines
if (str_contains($str, "\r")) {
$str = str_replace(["\r\n", "\r"], "\n", $str);
}
// If the current word is surrounded by {unwrap} tags we'll
// strip the entire chunk and replace it with a marker.
$unwrap = [];
if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches) >= 1) {
for ($i = 0, $c = count($matches[0]); $i < $c; $i++) {
$unwrap[] = $matches[1][$i];
$str = str_replace($matches[0][$i], '{{unwrapped' . $i . '}}', $str);
}
}
// Use PHP's native function to do the initial wordwrap.
// We set the cut flag to FALSE so that any individual words that are
// too long get left alone. In the next step we'll deal with them.
$str = wordwrap($str, $charlim, "\n", false);
// Split the string into individual lines of text and cycle through them
$output = '';
foreach (explode("\n", $str) as $line) {
// Is the line within the allowed character count?
// If so we'll join it to the output and continue
if (mb_strlen($line) <= $charlim) {
$output .= $line . "\n";
continue;
}
$temp = '';
while (mb_strlen($line) > $charlim) {
// If the over-length word is a URL we won't wrap it
if (preg_match('!\[url.+\]|://|www\.!', $line)) {
break;
}
// Trim the word down
$temp .= mb_substr($line, 0, $charlim - 1);
$line = mb_substr($line, $charlim - 1);
}
// If $temp contains data it means we had to split up an over-length
// word into smaller chunks so we'll add it back to our current line
if ($temp !== '') {
$output .= $temp . "\n" . $line . "\n";
} else {
$output .= $line . "\n";
}
}
// Put our markers back
foreach ($unwrap as $key => $val) {
$output = str_replace('{{unwrapped' . $key . '}}', $val, $output);
}
// remove any trailing newline
return rtrim($output);
}
}
if (! function_exists('ellipsize')) {
/**
* Ellipsize String
*
* This function will strip tags from a string, split it at its max_length and ellipsize
*
* @param string $str String to ellipsize
* @param int $maxLength Max length of string
* @param float|int $position int (1|0) or float, .5, .2, etc for position to split
* @param string $ellipsis ellipsis ; Default '...'
*
* @return string Ellipsized string
*/
function ellipsize(string $str, int $maxLength, $position = 1, string $ellipsis = '…'): string
{
// Strip tags
$str = trim(strip_tags($str));
// Is the string long enough to ellipsize?
if (mb_strlen($str) <= $maxLength) {
return $str;
}
$beg = mb_substr($str, 0, (int) floor($maxLength * $position));
$position = ($position > 1) ? 1 : $position;
if ($position === 1) {
$end = mb_substr($str, 0, -($maxLength - mb_strlen($beg)));
} else {
$end = mb_substr($str, -($maxLength - mb_strlen($beg)));
}
return $beg . $ellipsis . $end;
}
}
if (! function_exists('strip_slashes')) {
/**
* Strip Slashes
*
* Removes slashes contained in a string or in an array
*
* @param array|string $str string or array
*
* @return array|string string or array
*/
function strip_slashes($str)
{
if (! is_array($str)) {
return stripslashes($str);
}
foreach ($str as $key => $val) {
$str[$key] = strip_slashes($val);
}
return $str;
}
}
if (! function_exists('strip_quotes')) {
/**
* Strip Quotes
*
* Removes single and double quotes from a string
*/
function strip_quotes(string $str): string
{
return str_replace(['"', "'"], '', $str);
}
}
if (! function_exists('quotes_to_entities')) {
/**
* Quotes to Entities
*
* Converts single and double quotes to entities
*/
function quotes_to_entities(string $str): string
{
return str_replace(["\\'", '"', "'", '"'], [''', '"', ''', '"'], $str);
}
}
if (! function_exists('reduce_double_slashes')) {
/**
* Reduce Double Slashes
*
* Converts double slashes in a string to a single slash,
* except those found in http://
*
* http://www.some-site.com//index.php
*
* becomes:
*
* http://www.some-site.com/index.php
*/
function reduce_double_slashes(string $str): string
{
return preg_replace('#(^|[^:])//+#', '\\1/', $str);
}
}
if (! function_exists('reduce_multiples')) {
/**
* Reduce Multiples
*
* Reduces multiple instances of a particular character. Example:
*
* Fred, Bill,, Joe, Jimmy
*
* becomes:
*
* Fred, Bill, Joe, Jimmy
*
* @param string $character the character you wish to reduce
* @param bool $trim TRUE/FALSE - whether to trim the character from the beginning/end
*/
function reduce_multiples(string $str, string $character = ',', bool $trim = false): string
{
$pattern = '#' . preg_quote($character, '#') . '{2,}#';
$str = preg_replace($pattern, $character, $str);
return $trim ? trim($str, $character) : $str;
}
}
if (! function_exists('random_string')) {
/**
* Create a Random String
*
* Useful for generating passwords or hashes.
*
* @param string $type Type of random string. basic, alpha, alnum, numeric, nozero, md5, sha1, and crypto
* @param int $len Number of characters
*
* @deprecated The type 'basic', 'md5', and 'sha1' are deprecated. They are not cryptographically secure.
*/
function random_string(string $type = 'alnum', int $len = 8): string
{
switch ($type) {
case 'alnum':
case 'nozero':
case 'alpha':
switch ($type) {
case 'alpha':
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'alnum':
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'nozero':
$pool = '123456789';
break;
}
return _from_random($len, $pool);
case 'numeric':
$max = 10 ** $len - 1;
$rand = random_int(0, $max);
return sprintf('%0' . $len . 'd', $rand);
case 'md5':
return md5(uniqid((string) mt_rand(), true));
case 'sha1':
return sha1(uniqid((string) mt_rand(), true));
case 'crypto':
if ($len % 2 !== 0) {
throw new InvalidArgumentException(
'You must set an even number to the second parameter when you use `crypto`.',
);
}
return bin2hex(random_bytes($len / 2));
}
// 'basic' type treated as default
return (string) mt_rand();
}
}
if (! function_exists('_from_random')) {
/**
* The following function was derived from code of Symfony (v6.2.7 - 2023-02-28)
* https://github.com/symfony/symfony/blob/80cac46a31d4561804c17d101591a4f59e6db3a2/src/Symfony/Component/String/ByteString.php#L45
* Code subject to the MIT license (https://github.com/symfony/symfony/blob/v6.2.7/LICENSE).
* Copyright (c) 2004-present Fabien Potencier
*
* The following method was derived from code of the Hack Standard Library (v4.40 - 2020-05-03)
* https://github.com/hhvm/hsl/blob/80a42c02f036f72a42f0415e80d6b847f4bf62d5/src/random/private.php#L16
* Code subject to the MIT license (https://github.com/hhvm/hsl/blob/master/LICENSE).
* Copyright (c) 2004-2020, Facebook, Inc. (https://www.facebook.com/)
*
* @internal Outside the framework this should not be used directly.
*/
function _from_random(int $length, string $pool): string
{
if ($length <= 0) {
throw new InvalidArgumentException(
sprintf('A strictly positive length is expected, "%d" given.', $length),
);
}
$poolSize = \strlen($pool);
$bits = (int) ceil(log($poolSize, 2.0));
if ($bits <= 0 || $bits > 56) {
throw new InvalidArgumentException(
'The length of the alphabet must in the [2^1, 2^56] range.',
);
}
$string = '';
while ($length > 0) {
$urandomLength = (int) ceil(2 * $length * $bits / 8.0);
$data = random_bytes($urandomLength);
$unpackedData = 0;
$unpackedBits = 0;
for ($i = 0; $i < $urandomLength && $length > 0; $i++) {
// Unpack 8 bits
$unpackedData = ($unpackedData << 8) | \ord($data[$i]);
$unpackedBits += 8;
// While we have enough bits to select a character from the alphabet, keep
// consuming the random data
for (; $unpackedBits >= $bits && $length > 0; $unpackedBits -= $bits) {
$index = ($unpackedData & ((1 << $bits) - 1));
$unpackedData >>= $bits;
// Unfortunately, the alphabet size is not necessarily a power of two.
// Worst case, it is 2^k + 1, which means we need (k+1) bits and we
// have around a 50% chance of missing as k gets larger
if ($index < $poolSize) {
$string .= $pool[$index];
$length--;
}
}
}
}
return $string;
}
}
if (! function_exists('increment_string')) {
/**
* Add's _1 to a string or increment the ending number to allow _2, _3, etc
*
* @param string $str Required
* @param string $separator What should the duplicate number be appended with
* @param int $first Which number should be used for the first dupe increment
*/
function increment_string(string $str, string $separator = '_', int $first = 1): string
{
preg_match('/(.+)' . preg_quote($separator, '/') . '([0-9]+)$/', $str, $match);
return isset($match[2]) ? $match[1] . $separator . ((int) $match[2] + 1) : $str . $separator . $first;
}
}
if (! function_exists('alternator')) {
/**
* Alternator
*
* Allows strings to be alternated. See docs...
*
* @param string ...$args (as many parameters as needed)
*/
function alternator(...$args): string
{
static $i;
if (func_num_args() === 0) {
$i = 0;
return '';
}
return $args[($i++ % count($args))];
}
}
if (! function_exists('excerpt')) {
/**
* Excerpt.
*
* Allows to extract a piece of text surrounding a word or phrase.
*
* @param string $text String to search the phrase
* @param string $phrase Phrase that will be searched for.
* @param int $radius The amount of characters returned around the phrase.
* @param string $ellipsis Ending that will be appended
*
* If no $phrase is passed, will generate an excerpt of $radius characters
* from the beginning of $text.
*/
function excerpt(string $text, ?string $phrase = null, int $radius = 100, string $ellipsis = '...'): string
{
if (isset($phrase)) {
$phrasePosition = mb_stripos($text, $phrase);
$phraseLength = mb_strlen($phrase);
} else {
$phrasePosition = $radius / 2;
$phraseLength = 1;
}
$beforeWords = explode(' ', mb_substr($text, 0, $phrasePosition));
$afterWords = explode(' ', mb_substr($text, $phrasePosition + $phraseLength));
$firstPartOutput = ' ';
$endPartOutput = ' ';
$count = 0;
foreach (array_reverse($beforeWords) as $beforeWord) {
$beforeWordLength = mb_strlen($beforeWord);
if (($beforeWordLength + $count + 1) < $radius) {
$firstPartOutput = ' ' . $beforeWord . $firstPartOutput;
}
$count = ++$count + $beforeWordLength;
}
$count = 0;
foreach ($afterWords as $afterWord) {
$afterWordLength = mb_strlen($afterWord);
if (($afterWordLength + $count + 1) < $radius) {
$endPartOutput .= $afterWord . ' ';
}
$count = ++$count + $afterWordLength;
}
$ellPre = $phrase !== null ? $ellipsis : '';
return str_replace(' ', ' ', $ellPre . $firstPartOutput . $phrase . $endPartOutput . $ellipsis);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/test_helper.php | system/Helpers/test_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\Exceptions\TestException;
use CodeIgniter\Model;
use CodeIgniter\Test\Fabricator;
use Config\Services;
// CodeIgniter Test Helpers
if (! function_exists('fake')) {
/**
* Creates a single item using Fabricator.
*
* @param Model|object|string $model Instance or name of the model
* @param array|null $overrides Overriding data to pass to Fabricator::setOverrides()
* @param bool $persist
*
* @return array|object
*/
function fake($model, ?array $overrides = null, $persist = true)
{
$fabricator = new Fabricator($model);
if ($overrides !== null) {
$fabricator->setOverrides($overrides);
}
if ($persist) {
return $fabricator->create();
}
return $fabricator->make();
}
}
if (! function_exists('mock')) {
/**
* Used within our test suite to mock certain system tools.
*
* @param string $className Fully qualified class name
*
* @return object
*/
function mock(string $className)
{
$mockClass = $className::$mockClass;
$mockService = $className::$mockServiceName ?? '';
if (empty($mockClass) || ! class_exists($mockClass)) {
throw TestException::forInvalidMockClass($mockClass);
}
$mock = new $mockClass();
if (! empty($mockService)) {
Services::injectMock($mockService, $mock);
}
return $mock;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/xml_helper.php | system/Helpers/xml_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
// CodeIgniter XML Helpers
if (! function_exists('xml_convert')) {
/**
* Convert Reserved XML characters to Entities
*/
function xml_convert(string $str, bool $protectAll = false): string
{
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// ampersands won't get messed up
$str = preg_replace('/&#(\d+);/', $temp . '\\1;', $str);
if ($protectAll) {
$str = preg_replace('/&(\w+);/', $temp . '\\1;', $str);
}
$original = [
'&',
'<',
'>',
'"',
"'",
'-',
];
$replacement = [
'&',
'<',
'>',
'"',
''',
'-',
];
$str = str_replace($original, $replacement, $str);
// Decode the temp markers back to entities
$str = preg_replace('/' . $temp . '(\d+);/', '&#\\1;', $str);
if ($protectAll) {
return preg_replace('/' . $temp . '(\w+);/', '&\\1;', $str);
}
return $str;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Helpers/date_helper.php | system/Helpers/date_helper.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use CodeIgniter\I18n\Time;
// CodeIgniter Date Helpers
if (! function_exists('now')) {
/**
* Get "now" time
*
* Returns Time::now()->getTimestamp() based on the timezone parameter or on the
* app_timezone() setting
*
* @param non-empty-string|null $timezone
*
* @throws Exception
*/
function now(?string $timezone = null): int
{
$timezone = ($timezone === null || $timezone === '') ? app_timezone() : $timezone;
if ($timezone === 'local' || $timezone === date_default_timezone_get()) {
return Time::now()->getTimestamp();
}
$time = Time::now($timezone);
sscanf(
$time->format('j-n-Y G:i:s'),
'%d-%d-%d %d:%d:%d',
$day,
$month,
$year,
$hour,
$minute,
$second,
);
return mktime($hour, $minute, $second, $month, $day, $year);
}
}
if (! function_exists('timezone_select')) {
/**
* Generates a select field of all available timezones
*
* Returns a string with the formatted HTML
*
* @param string $class Optional class to apply to the select field
* @param string $default Default value for initial selection
* @param int $what One of the DateTimeZone class constants (for listIdentifiers)
* @param string $country A two-letter ISO 3166-1 compatible country code (for listIdentifiers)
*
* @throws Exception
*/
function timezone_select(string $class = '', string $default = '', int $what = DateTimeZone::ALL, ?string $country = null): string
{
$timezones = DateTimeZone::listIdentifiers($what, $country);
$buffer = "<select name='timezone' class='{$class}'>\n";
foreach ($timezones as $timezone) {
$selected = ($timezone === $default) ? 'selected' : '';
$buffer .= "<option value='{$timezone}' {$selected}>{$timezone}</option>\n";
}
return $buffer . ("</select>\n");
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.