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
Rct567/DomQuery
https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/tests/Rct567/DomQuery/Tests/DomQueryTest.php
tests/Rct567/DomQuery/Tests/DomQueryTest.php
<?php namespace Rct567\DomQuery\Tests; use Rct567\DomQuery\DomQuery; use Rct567\DomQuery\DomQueryNodes; class DomQueryTest extends \PHPUnit\Framework\TestCase { /* * Test filters, first and last (with method and pseudo selector) */ public function testFirstAndLastFilters() { $html = '<div id="main" class="root"> <div class="level-a" id="first-child-a">first-child-a</div> <div class="level-a" id="second-child-a"> <p>Hai</p> <div class="level-b"></div> <div class="level-b"></div> <div class="level-b"> <div class="level-c"></div> </div> </div> <div class="level-a" id="last-child-a">last-child-a</div> </div>'; $dom = new DomQuery($html); $this->assertEquals('main', $dom->find('div')->first()->getAttribute('id')); $this->assertEquals('main', $dom->children()->first()->getAttribute('id')); // first and last method, check id $this->assertEquals('first-child-a', $dom->find('.root div')->first()->attr('id')); $this->assertEquals('last-child-a', $dom->find('.root div')->last()->attr('id')); // first and last via pseudo selector, check id $this->assertEquals('first-child-a', $dom->find('.root div:first')->attr('id')); // id of first div inside .root $this->assertEquals('last-child-a', $dom->find('.root div:last')->attr('id')); // id of last div inside .root // first and last via get method, check id $this->assertEquals('first-child-a', $dom->find('.root div')->get(0)->textContent); $this->assertEquals('last-child-a', $dom->find('.root div')->get(-1)->textContent); } /* * Test basic usage examples from readme */ public function testBasicUsageReadmeExamples() { $dom = new DomQuery('<div><h1 class="title">Hello</h1></div>'); $this->assertEquals('Hello', $dom->find('div')->text()); $this->assertEquals('<div><h1 class="title">Hello</h1></div>', $dom->find('div')->prop('outerHTML')); $this->assertEquals('<h1 class="title">Hello</h1>', $dom->find('div')->html()); $this->assertEquals('title', $dom->find('div > h1')->class); $this->assertEquals('title', $dom->find('div > h1')->attr('class')); $this->assertEquals('h1', $dom->find('div > h1')->prop('tagName')); $this->assertEquals('h1', $dom->find('div')->children('h1')->prop('tagName')); $this->assertEquals('<h1 class="title">Hello</h1>', (string) $dom->find('div > h1')); $this->assertEquals('h1', $dom->find('div')->children('h1')->prop('tagName')); $this->assertCount(2, $dom->find('div, h1')); } /* * Test simple links lookup */ public function testGetLink() { $dom = new DomQuery; $dom->loadContent('<!DOCTYPE html> <html> <head></head> <body> <p><a href="test.html"></a></p> <a href="test2.html">X</a> </body> </html>'); $this->assertEquals('html', $dom->nodeName); $link_found = $dom->find('p > a[href^="test"]'); $this->assertCount(1, $link_found, 'finding link'); // 1 link is inside p $this->assertEquals(1, $link_found->length, 'finding link'); $this->assertTrue(isset($link_found->href), 'finding link'); $this->assertEquals('test.html', $link_found->href, 'finding link'); $this->assertEquals('test.html', $link_found->attr('href'), 'finding link'); $this->assertEquals('a', $link_found->nodeName); $this->assertEquals('a', $link_found->prop('tagName')); $this->assertInstanceOf(DomQuery::class, $link_found); $this->assertInstanceOf(DomQuery::class, $link_found[0]); $link_found = $dom->find('body > a'); $this->assertCount(1, $link_found, 'finding link'); $this->assertEquals('X', $link_found->text()); } /* * Test loading utf8 html */ public function testLoadingUf8AndGettingSameContent() { $html = '<div><h1>Iñtërnâtiônàlizætiøn</h1></div><a>k</a>'; $dom = new DomQuery($html); $this->assertEquals($html, (string) $dom); // same result $this->assertEquals('<h1>Iñtërnâtiônàlizætiøn</h1>', (string) $dom->find('h1')); // same header $this->assertEquals('Iñtërnâtiônàlizætiøn', $dom->find('h1')->text()); // same text $this->assertEquals('Iñtërnâtiônàlizætiøn', $dom->text()); } /* * Test loading utf8 html with irrelevant pi in content */ public function testLoadingUf8AndGettingSameContentWithPiInContent() { $html = '<div><h1>Iñtërnâtiônàlizætiøn</h1></div><a>k</a><?xml version="1.0" encoding="iso-8859-1"?>'; $dom = new DomQuery($html); $this->assertEquals($html, (string) $dom); // same result $this->assertEquals('<h1>Iñtërnâtiônàlizætiøn</h1>', (string) $dom->find('h1')); // same header } /* * Test loading utf8 content with leading pi */ public function testLoadingUf8AndGettingSameContentWithLeadingPi() { $html = '<?xml version="1.0" encoding="UTF-8"?><div><h1>Iñtërnâtiônàlizætiøn</h1></div>'; $dom = new DomQuery($html); $this->assertTrue($dom->xml_mode); $this->assertEquals($html, (string) $dom); // same result $this->assertEquals('<h1>Iñtërnâtiônàlizætiøn</h1>', (string) $dom->find('h1')); // same header $dom->xml_mode = false; $this->assertEquals('<div><h1>Iñtërnâtiônàlizætiøn</h1></div>', (string) $dom); // without pi } /* * Test loading html with new lines */ public function testLoadingWithNewLines() { $dom = new DomQuery("<div>\n<h1>X</h1>\n</div>"); $this->assertEquals("<div>\n<h1>X</h1>\n</div>", (string) $dom); } /* * Test preserve attribute without value */ public function testPreserverAttributeWithoutValue() { $dom = new DomQuery('<div selected>a</div>'); $this->assertEquals('<div selected>a</div>', (string) $dom); } /* * Test change attribute without value in xml write mode */ public function testChangeAttributeWithoutValueInXmlWriteMode() { $dom = new DomQuery('<div selected>a</div>'); $dom->xml_mode = true; $this->assertEquals("<div selected=\"selected\">a</div>", (string) $dom); } /* * Test change attribute without value in xml read+write mode */ public function testChangeAttributeWithoutValueInXmlReadWriteModeWithDeclaration() { $dom = new DomQuery("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n\n<div selected>a</div>"); $this->assertEquals("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n\n<div>a</div>", (string) $dom); } /* * Test instance without nodes */ public function testDomQueryNoDocument() { $dom = new DomQuery; $this->assertCount(0, $dom); $this->assertFalse(isset($dom[0])); $this->assertCount(0, $dom->find('*')); $this->assertCount(0, $dom->children()); $this->assertNull($dom->get(0)); $this->assertInstanceOf(DomQuery::class, $dom[0]); $this->assertInstanceOf(DomQuery::class, $dom->children('a')->first('b')->last('c')->find('d')); $this->assertInstanceOf(DomQuery::class, $dom->parent('a')->next('b')->prev('c')); $this->assertInstanceOf(DomQuery::class, $dom->not('a')->filter('b')); $this->assertNull($dom->getDocument()); $this->assertNull($dom->getXpathQuery()); $this->assertNull($dom->getCssQuery()); $this->assertNull($dom->getDomXpath()); $num = 0; foreach ($dom as $node) { $num++; } $this->assertEquals(0, $num); } /* * Test constructor with selector and html context */ public function testConstructorWithSelectorAndHtmlContext() { $dom = new DomQuery('div', '<div>X</div><p>Nope</p>'); $this->assertEquals('<div>X</div>', (string) $dom); } /* * Test constructor with selector and self as context */ public function testConstructorWithSelectorAndSelfContext() { $dom = new DomQuery('div', new DomQuery('<div>X</div><p>Nope</p>')); $this->assertEquals('<div>X</div>', (string) $dom); } /* * Test to array and array as constructor argument */ public function testConstructorWithNodesArray() { $nodes_array = DomQuery::create('<div>X</div><p>Nope</p>')->toArray(); $this->assertContainsOnlyInstancesOf(\DOMNode::class, $nodes_array); $this->assertCount(2, $nodes_array); $this->assertEquals('<div>X</div><p>Nope</p>', (string) DomQuery::create($nodes_array)); } /* * Test constructor exception by giving unknown object argument */ public function testConstructorUnknownObjectArgument() { $this->expectException(\InvalidArgumentException::class); $dom = new DomQuery(new \stdClass); } /* * Test constructor exception by giving unknown argument */ public function testConstructorUnknownArgument() { $this->expectException(\InvalidArgumentException::class); $dom = new DomQuery(null); } /* * Test constructor exception by giving double document */ public function testConstructorDoubleDocument() { $this->expectException(\Exception::class); $dom = new DomQuery(new \DOMDocument(), new \DOMDocument()); } /* * Test constructor exception caused by giving empty node list */ public function testConstructorEmptyNodeList() { $this->expectException(\Exception::class); $empty_node_list = (new \DOMDocument())->getElementsByTagName('nope'); $dom = new DomQuery($empty_node_list); } /* * Test exception caused by array access with invalid offset key */ public function testArrayAccessGetWithInvalidOffsetKey() { $this->expectException(\BadMethodCallException::class); $dom = (new DomQuery())['invalid']; } /* * Test exception caused by array access set value */ public function testArrayAccessSet() { $this->expectException(\BadMethodCallException::class); $dom = new DomQuery(); $dom['invalid'] = null; } /* * Test exception caused by array access unset */ public function testArrayAccessUnset() { $this->expectException(\BadMethodCallException::class); $dom = new DomQuery(); unset($dom['invalid']); } /* * Test exception caused by non existing method call */ public function testNonExistingMethodCall() { $this->expectException(\Exception::class); $dom = (new DomQuery('<div>'))->nope(); } /* * Test invalid xpath expression */ public function testInvalidXpath() { $this->expectException(\Exception::class); $dom = new DomQuery('<div>'); $dom->xpathQuery("\n[]"); } /* * Test making xpath relative method */ public function testXpathMakeQueryRelative() { $reflectedClass = new \ReflectionClass(DomQueryNodes::class); $method = $reflectedClass->getMethod('xpathMakeQueryRelative'); $method->setAccessible(true); $xpath_to_relative = array( '/a' => './a', '//a' => './/a', '//a[attr ]' => './/a[attr ]', '//a|/a' => '(.//a|./a)', '//*|./a[attr]' => '(.//*|./a[attr])', '//a/b' => './/a/b', '//a/b|//a/b' => '(.//a/b|.//a/b)', '//a[descendant::b]' => './/a[descendant::b]', '/a[descendant::b]' => './a[descendant::b]', '//p/a[child::a]|//p/a[child::a]' => '(.//p/a[child::a]|.//p/a[child::a])', '(//*)[1]' => '(.//*)[1]', '/html/body//div|//p' => '(./html/body//div|.//p)', '(/a|//b)[@class="test"]/c' => '((./a|.//b)[@class="test"]/c)', '//*[@class="my\.class"]|/b[@class="my\.cla-ss"]' => '(.//*[@class="my\.class"]|./b[@class="my\.cla-ss"])' ); foreach ($xpath_to_relative as $xpath => $expected_xpath) { $result = $method->invokeArgs(null, [$xpath]); $this->assertEquals($expected_xpath, $result); } $xpath_unchanged = array( '[/a]', 'bbb[/a]bbb', './a', './/a', './/a[|]/a', './/p/a', 'aaaa[bbb//bbb]aaaaaa', 'aaaa[bbb/bbb]aaaaaa', 'aaaa[/bbb|/bbb]aaaaaa' ); foreach ($xpath_unchanged as $xpath) { $result = $method->invokeArgs(null, [$xpath]); $this->assertEquals($xpath, $result); } } }
php
MIT
4bc72c3da2e82eb7c08fa30582f71e91843423df
2026-01-05T05:09:18.310463Z
false
Rct567/DomQuery
https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/tests/Rct567/DomQuery/Tests/DomQueryMiscellaneousElementMethodTest.php
tests/Rct567/DomQuery/Tests/DomQueryMiscellaneousElementMethodTest.php
<?php namespace Rct567\DomQuery\Tests; use Rct567\DomQuery\DomQuery; class DomQueryMiscellaneousElementMethodTest extends \PHPUnit\Framework\TestCase { /* * Test get data */ public function testGetData() { $dom = new DomQuery('<div data-role="page"></div>'); $this->assertEquals('page', $dom->data('role')); $this->assertNull($dom->data('nope')); $this->assertEquals((object) array('role' => 'page'), $dom->data()); } /* * Test get object data */ public function testGetObjectData() { $dom = new DomQuery('<div data-options=\'{"name":"John"}\'></div>'); $this->assertEquals((object) array('name' => 'John'), $dom->data('options')); $this->assertEquals((object) array('options' => (object) array('name' => 'John')), $dom->data()); } /* * Test set string as data, surviving wrap */ public function testSetStringData() { $dom = new DomQuery('<div> <a data-role=""></a> </div>'); $dom->find('a')->data('role', 'page'); $this->assertEquals('page', $dom->find('a')->data('role')); $dom->find('a')->wrap('<div>'); $this->assertEquals('page', $dom->find('a')->data('role')); $this->assertEquals((object) array('role' => 'page'), $dom->find('a')->data()); } /* * Test set instance as data, surviving wrap */ public function testSetInstanceData() { $dom = new DomQuery('<div> <a data-role=""></a> </div>'); $dom->find('a')->data('role', $this); $this->assertEquals($this, $dom->find('a')->data('role')); $dom->find('a')->wrap('<div>'); $this->assertEquals($this, $dom->find('a')->data('role')); } /* * Test remove data */ public function testRemoveData() { $dom = new DomQuery('<div> <a></a> </div>'); $dom->find('a')->data('role', 'page'); $dom->find('a')->data('other', 'still-there'); $this->assertEquals('page', $dom->find('a')->data('role')); $this->assertEquals('still-there', $dom->find('a')->data('other')); $dom->find('a')->removeData('role'); $this->assertEquals(null, $dom->find('a')->data('role')); $this->assertEquals('still-there', $dom->find('a')->data('other')); } /* * Test remove all data */ public function testRemoveAllData() { $dom = new DomQuery('<div> <a data-stay="x"></a> </div>'); $dom->find('a')->data('role', 'page'); $dom->find('a')->data('other', 'also-gone'); $this->assertEquals('page', $dom->find('a')->data('role')); $dom->find('a')->removeData(); $this->assertEquals(null, $dom->find('a')->data('role')); $this->assertEquals(null, $dom->find('a')->data('other')); $this->assertEquals('<div> <a data-stay="x"></a> </div>', (string) $dom); } /* * Test get index of position in dom */ public function testIndex() { $dom = new DomQuery('<div> <a class="a">1</a><a class="b">2</a><a class="c">3</a><a class="d">4</a> </div>'); $this->assertEquals(-1, $dom->find('nope')->index()); $this->assertEquals(0, $dom->find('div')->index()); $this->assertEquals(0, $dom->find('.a')->index()); $this->assertEquals(3, $dom->find('.d')->index()); } /* * Test get index of position in result that matches selector */ public function testIndexWithSelector() { $dom = new DomQuery('<div> <a class="a">1</a><a class="b">2</a><a class="c">3</a><a class="d">4</a> </div>'); $this->assertEquals(-1, $dom->find('a')->index('.nope')); $this->assertEquals(0, $dom->find('a')->index('.a')); $this->assertEquals(1, $dom->find('a')->index($dom->find('.b'))); $this->assertEquals(2, $dom->find('a')->index($dom->find('a')->get(2))); $this->assertEquals(3, $dom->find('a')->index('.d')); } /* * Test each iteration */ public function testEachIteration() { $dom = new DomQuery('<p> <a>1</a> <a>2</a> <span></span> </p>'); $result = array(); $dom->find('a')->each(function ($elm, $i) use (&$result) { $result[$i] = $elm; }); $this->assertCount(2, $result); $this->assertInstanceOf(\DOMNode::class, $result[0]); } /* * Test clone */ public function testClone() { $dom = new DomQuery('<div><p>My words</p></div>'); $elm = $dom->find('p'); $cloned_elm = $elm->clone(); $this->assertEquals('<p>My words</p>', (string) $elm); $this->assertEquals('<p>My words</p>', (string) $cloned_elm); $this->assertFalse($elm->get(0)->isSameNode($cloned_elm->get(0))); $dom_clone = $dom->clone(); $this->assertEquals('<div><p>My words</p></div>', $dom_clone); $this->assertEquals('<p>My words</p>', $dom_clone->find('p')->first()); $this->assertTrue($dom_clone->find('p')->first()->is('p')); } }
php
MIT
4bc72c3da2e82eb7c08fa30582f71e91843423df
2026-01-05T05:09:18.310463Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/autoload.php
autoload.php
<?php spl_autoload_register(function ($class) { // the package namespace $ns = 'Aura\Auth'; // what prefixes should be recognized? $prefixes = array( "{$ns}\_Config\\" => array( __DIR__ . '/config', ), "{$ns}\\" => array( __DIR__ . '/src', __DIR__ . '/tests', ), ); // go through the prefixes foreach ($prefixes as $prefix => $dirs) { // does the requested class match the namespace prefix? $prefix_len = strlen($prefix); if (substr($class, 0, $prefix_len) !== $prefix) { continue; } // strip the prefix off the class $class = substr($class, $prefix_len); // a partial filename $part = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php'; // go through the directories to find classes foreach ($dirs as $dir) { $dir = str_replace('/', DIRECTORY_SEPARATOR, $dir); $file = $dir . DIRECTORY_SEPARATOR . $part; if (is_readable($file)) { require $file; return; } } } });
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/phpunit.php
phpunit.php
<?php error_reporting(E_ALL); $autoloader = __DIR__ . '/vendor/autoload.php'; if (! file_exists($autoloader)) { echo "Composer autoloader not found: $autoloader" . PHP_EOL; echo "Please issue 'composer install' and try again." . PHP_EOL; exit(1); } require $autoloader;
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/AuthFactory.php
src/AuthFactory.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth; use Aura\Auth\Adapter; use Aura\Auth\Service; use Aura\Auth\Session; use Aura\Auth\Session\SessionInterface; use Aura\Auth\Session\SegmentInterface; use Aura\Auth\Verifier; use Aura\Auth\Adapter\AdapterInterface; use PDO; /** * * Factory for Auth package objects. * * @package Aura.Auth * */ class AuthFactory { /** * * A session manager. * * @var SessionInterface * */ protected $session; /** * * A session segment. * * @var SegmentInterface * */ protected $segment; /** * * Constructor. * * @param array $cookie A copy of $_COOKIES. * * @param SessionInterface $session A session manager. * * @param SegmentInterface $segment A session segment. * */ public function __construct( array $cookie, SessionInterface $session = null, SegmentInterface $segment = null ) { $this->session = $session; if (! $this->session) { $this->session = new Session\Session($cookie); } $this->segment = $segment; if (! $this->segment) { $this->segment = new Session\Segment; } } /** * * Returns a new authentication tracker. * * @return Auth * */ public function newInstance() { return new Auth($this->segment); } /** * * Returns a new login service instance. * * @param AdapterInterface $adapter The adapter to use with the service. * * @return Service\LoginService * */ public function newLoginService(AdapterInterface $adapter = null) { return new Service\LoginService( $this->fixAdapter($adapter), $this->session ); } /** * * Returns a new logout service instance. * * @param AdapterInterface $adapter The adapter to use with the service. * * @return Service\LogoutService * */ public function newLogoutService(AdapterInterface $adapter = null) { return new Service\LogoutService( $this->fixAdapter($adapter), $this->session ); } /** * * Returns a new "resume session" service. * * @param AdapterInterface $adapter The adapter to use with the service, and * with the underlying logout service. * * @param int $idle_ttl The session idle time in seconds. * * @param int $expire_ttl The session expire time in seconds. * * @return Service\ResumeService * */ public function newResumeService( AdapterInterface $adapter = null, $idle_ttl = 3600, // 1 hour $expire_ttl = 86400 // 24 hours ) { $adapter = $this->fixAdapter($adapter); $timer = new Session\Timer( ini_get('session.gc_maxlifetime'), ini_get('session.cookie_lifetime'), $idle_ttl, $expire_ttl ); $logout_service = new Service\LogoutService( $adapter, $this->session ); return new Service\ResumeService( $adapter, $this->session, $timer, $logout_service ); } /** * * Make sure we have an Adapter instance, even if only a NullAdapter. * * @param Adapterinterface $adapter Check to make sure this is an Adapter * instance. * * @return AdapterInterface * */ protected function fixAdapter(AdapterInterface $adapter = null) { if ($adapter === null) { $adapter = new Adapter\NullAdapter; } return $adapter; } /** * * Returns a new PDO adapter. * * @param PDO $pdo A PDO connection. * * @param mixed $verifier_spec Specification to pick a verifier: if an * object, assume a VerifierInterface; otherwise, assume a PASSWORD_* * constant for a PasswordVerifier. * * @param array $cols Select these columns. * * @param string $from Select from this table (and joins). * * @param string $where WHERE conditions for the select. * * @return Adapter\PdoAdapter * */ public function newPdoAdapter( PDO $pdo, $verifier_spec, array $cols, $from, $where = null ) { if (is_object($verifier_spec)) { $verifier = $verifier_spec; } else { $verifier = new Verifier\PasswordVerifier($verifier_spec); } return new Adapter\PdoAdapter( $pdo, $verifier, $cols, $from, $where ); } /** * * Returns a new HtpasswdAdapter. * * @param string $file Path to the htpasswd file. * * @return Adapter\HtpasswdAdapter * */ public function newHtpasswdAdapter($file) { $verifier = new Verifier\HtpasswdVerifier; return new Adapter\HtpasswdAdapter( $file, $verifier ); } /** * * Returns a new ImapAdapter. * * @param string $mailbox An imap_open() mailbox string. * * @param int $options Options for the imap_open() call. * * @param int $retries Try to connect this many times. * * @param array $params Set these params after opening the connection. * * @return Adapter\ImapAdapter * */ public function newImapAdapter( $mailbox, $options = 0, $retries = 1, array $params = null ) { return new Adapter\ImapAdapter( new Phpfunc, $mailbox, $options, $retries, $params ); } /** * * Returns a new LdapAdapter. * * @param string $server An LDAP server string. * * @param string $dnformat A distinguished name format string for looking up * the username. * * @param array $options Use these connection options. * * @return Adapter\LdapAdapter * */ public function newLdapAdapter( $server, $dnformat, array $options = array() ) { return new Adapter\LdapAdapter( new Phpfunc, $server, $dnformat, $options ); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Auth.php
src/Auth.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth; use Aura\Auth\Session\SegmentInterface; use Aura\Auth\Session\SessionInterface; use Aura\Auth\Session\Timer; /** * * The current user (authenticated or otherwise). * * @package Aura.Auth * */ class Auth { /** * * Session data. * * @var SegmentInterface * */ protected $segment; /** * * Constructor. * * @param SegmentInterface $segment A session data store. * */ public function __construct(SegmentInterface $segment) { $this->segment = $segment; } /** * * Sets the authentication values. * * @param string $status The authentication status. * * @param int $first_active First active at this Unix time. * * @param int $last_active Last active at this Unix time. * * @param string $username The username. * * @param array $userdata Arbitrary user data. * * @return null * * @see Status for constants and their values. * */ public function set( $status, $first_active, $last_active, $username, array $userdata ) { $this->setStatus($status); $this->setFirstActive($first_active); $this->setLastActive($last_active); $this->setUserName($username); $this->setUserData($userdata); } /** * * Is the user authenticated? * * @return bool * */ public function isValid() { return $this->getStatus() == Status::VALID; } /** * * Is the user anonymous? * * @return bool * */ public function isAnon() { return $this->getStatus() == Status::ANON; } /** * * Has the user been idle for too long? * * @return bool * */ public function isIdle() { return $this->getStatus() == Status::IDLE; } /** * * Has the authentication time expired? * * @return bool * */ public function isExpired() { return $this->getStatus() == Status::EXPIRED; } /** * * Sets the current authentication status. * * @param string $status The authentication status. * * @return null * */ public function setStatus($status) { $this->segment->set('status', $status); } /** * * Gets the current authentication status. * * @return string * */ public function getStatus() { return $this->segment->get('status', Status::ANON); } /** * * Sets the initial authentication time. * * @param int $first_active The initial authentication Unix time. * * @return null * */ public function setFirstActive($first_active) { $this->segment->set('first_active', $first_active); } /** * * Gets the initial authentication time. * * @return int * */ public function getFirstActive() { return $this->segment->get('first_active'); } /** * * Sets the last active time. * * @param int $last_active The last active Unix time. * * @return null * */ public function setLastActive($last_active) { $this->segment->set('last_active', $last_active); } /** * * Gets the last active time. * * @return int * */ public function getLastActive() { return $this->segment->get('last_active'); } /** * * Sets the current user name. * * @param string $username The username. * * @return null * */ public function setUserName($username) { $this->segment->set('username', $username); } /** * * Gets the current user name. * * @return string * */ public function getUserName() { return $this->segment->get('username'); } /** * * Sets the current user data. * * @param array $userdata The user data. * * @return null * */ public function setUserData(array $userdata) { $this->segment->set('userdata', $userdata); } /** * * Gets the current user data. * * @return array * */ public function getUserData() { return $this->segment->get('userdata', array()); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception.php
src/Exception.php
<?php /** * * This file is part of the Aura project for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth; /** * * Base exception class. * * @package Aura.Auth * */ class Exception extends \Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Status.php
src/Status.php
<?php /** * * This file is part of the Aura project for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth; /** * * Constants for authentication statuses. * * @package Aura.Auth * */ class Status { /** * * The user is anonymous/unauthenticated. * * @const string * */ const ANON = 'ANON'; /** * * The max time for authentication has expired. * * @const string * */ const EXPIRED = 'EXPIRED'; /** * * The authenticated user has been idle for too long. * * @const string * */ const IDLE = 'IDLE'; /** * * The user is authenticated and has not idled or expired. * * @const string * */ const VALID = 'VALID'; }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Phpfunc.php
src/Phpfunc.php
<?php /** * * This file is part of the Aura project for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth; /** * * Proxy for the ease of testing PHP functions. * * http://mikenaberezny.com/2007/08/01/wrapping-php-functions-for-testability/ * * @package Aura.Auth * */ class Phpfunc { /** * * Magic call for PHP functions. * * @param string $method The PHP function to call. * * @param array $params Params to pass to the function. * * @return mixed * */ public function __call($method, $params) { return call_user_func_array($method, $params); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Verifier/PasswordVerifier.php
src/Verifier/PasswordVerifier.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Verifier; /** * * Htaccess password Verifier * * @package Aura.Auth * */ class PasswordVerifier implements VerifierInterface { /** * * The hashing algorithm to use. * * @var string|int * */ protected $algo; /** * * Constructor. * * @param string|int $algo The hashing algorithm to use. * */ public function __construct($algo) { $this->algo = $algo; } /** * * Verifies a password against a hash. * * @param string $plaintext Plaintext password. * * @param string $hashvalue The comparison hash. * * @param array $extra Optional array if used by verify * * @return bool * */ public function verify($plaintext, $hashvalue, array $extra = array()) { if (is_string($this->algo) && $this->algo !== PASSWORD_BCRYPT) { return hash($this->algo, $plaintext) === $hashvalue; } else { return password_verify($plaintext, $hashvalue); } } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Verifier/VerifierInterface.php
src/Verifier/VerifierInterface.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Verifier; /** * * Password Verifier * * @package Aura.Auth * */ interface VerifierInterface { /** * * Verify that a plaintext password matches a hashed one. * * @param string $plaintext Plaintext password. * * @param string $hashvalue Hashed password. * * @param array $extra Optional array of data. * * @return bool * */ public function verify($plaintext, $hashvalue, array $extra = array()); }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Verifier/HtpasswdVerifier.php
src/Verifier/HtpasswdVerifier.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Verifier; /** * * Verfies passwords from htpasswd files; supports APR1/MD5, DES, SHA1, and * Bcrypt. * * The APR1/MD5 implementation was originally written by Mike Wallner * <mike@php.net>; any flaws are the fault of Paul M. Jones * <pmjones88@gmail.com>. * * @package Aura.Auth * */ class HtpasswdVerifier implements VerifierInterface { /** * * Verifies a plaintext password against a hash. * * @param string $plaintext Plaintext password. * * @param string $hashvalue Comparison hash. * * @param array $extra Optional array if used by verify. * * @return bool * */ public function verify($plaintext, $hashvalue, array $extra = array()) { $hashvalue = trim($hashvalue); if (substr($hashvalue, 0, 4) == '$2y$') { return password_verify($plaintext, $hashvalue); } if (substr($hashvalue, 0, 5) == '{SHA}') { return $this->sha($plaintext, $hashvalue); } if (substr($hashvalue, 0, 6) == '$apr1$') { return $this->apr1($plaintext, $hashvalue); } return $this->des($plaintext, $hashvalue); } /** * * Verify using SHA1 hashing. * * @param string $plaintext Plaintext password. * * @param string $hashvalue Comparison hash. * * @return bool * */ protected function sha($plaintext, $hashvalue) { $hex = sha1($plaintext, true); $computed_hash = '{SHA}' . base64_encode($hex); return $computed_hash === $hashvalue; } /** * * Verify using APR compatible MD5 hashing. * * @param string $plaintext Plaintext password. * * @param string $hashvalue Comparison hash. * * @return bool * */ protected function apr1($plaintext, $hashvalue) { $salt = preg_replace('/^\$apr1\$([^$]+)\$.*/', '\\1', $hashvalue); $context = $this->computeContext($plaintext, $salt); $binary = $this->computeBinary($plaintext, $salt, $context); $p = $this->computeP($binary); $computed_hash = '$apr1$' . $salt . '$' . $p . $this->convert64(ord($binary[11]), 3); return $computed_hash === $hashvalue; } /** * * Compute the context. * * @param string $plaintext Plaintext password. * * @param string $salt The salt. * * @return string * */ protected function computeContext($plaintext, $salt) { $length = strlen($plaintext); $hash = hash('md5', $plaintext . $salt . $plaintext, true); $context = $plaintext . '$apr1$' . $salt; for ($i = $length; $i > 0; $i -= 16) { $context .= substr($hash, 0, min(16, $i)); } for ($i = $length; $i > 0; $i >>= 1) { $context .= ($i & 1) ? chr(0) : $plaintext[0]; } return $context; } /** * * Compute the binary. * * @param string $plaintext Plaintext password. * * @param string $salt The salt. * * @param string $context The context. * * @return string * */ protected function computeBinary($plaintext, $salt, $context) { $binary = hash('md5', $context, true); for ($i = 0; $i < 1000; $i++) { $new = ($i & 1) ? $plaintext : $binary; if ($i % 3) { $new .= $salt; } if ($i % 7) { $new .= $plaintext; } $new .= ($i & 1) ? $binary : $plaintext; $binary = hash('md5', $new, true); } return $binary; } /** * * Compute the P value for a binary. * * @param string $binary The binary. * * @return string * */ protected function computeP($binary) { $p = array(); for ($i = 0; $i < 5; $i++) { $k = $i + 6; $j = $i + 12; if ($j == 16) { $j = 5; } $p[] = $this->convert64( (ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5 ); } return implode($p); } /** * * Convert to allowed 64 characters for encryption. * * @param string $value The value to convert. * * @param int $count The number of characters. * * @return string The converted value. * */ protected function convert64($value, $count) { $charset = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; $result = ''; while (--$count) { $result .= $charset[$value & 0x3f]; $value >>= 6; } return $result; } /** * * Verify using DES hashing. * * Note that crypt() will only check up to the first 8 * characters of a password; chars after 8 are ignored. This * means that if the real password is "atecharsnine", the * word "atechars" would be valid. This is bad. As a * workaround, if the password provided by the user is * longer than 8 characters, this method will *not* verify * it. * * @param string $plaintext Plaintext password. * * @param string $hashvalue Comparison hash. * * @return bool * */ protected function des($plaintext, $hashvalue) { if (strlen($plaintext) > 8) { return false; } $computed_hash = crypt($plaintext, $hashvalue); return $computed_hash === $hashvalue; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/BindFailed.php
src/Exception/BindFailed.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Binding to a network service (LDAP etc) failed. * * @package Aura.Auth * */ class BindFailed extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/UsernameNotFound.php
src/Exception/UsernameNotFound.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Username not found. * * @package Aura.Auth * */ class UsernameNotFound extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/PasswordMissing.php
src/Exception/PasswordMissing.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Missing password. * * @package Aura.Auth * */ class PasswordMissing extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/UsernameMissing.php
src/Exception/UsernameMissing.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Missing username. * * @package Aura.Auth * */ class UsernameMissing extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/PasswordIncorrect.php
src/Exception/PasswordIncorrect.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * PasswordIncorrect. * * @package Aura.Auth * */ class PasswordIncorrect extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/FileNotFound.php
src/Exception/FileNotFound.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * File does not exists * * @package Aura.Auth * */ class FileNotFound extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/AlgorithmNotAvailable.php
src/Exception/AlgorithmNotAvailable.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Algorithm not available or unknown * * @package Aura.Auth * */ class AlgorithmNotAvailable extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/FileNotReadable.php
src/Exception/FileNotReadable.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * File is not readable * * @package Aura.Auth * */ class FileNotReadable extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/UsernameColumnNotSpecified.php
src/Exception/UsernameColumnNotSpecified.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Username column not specified. * * @package Aura.Auth * */ class UsernameColumnNotSpecified extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/MultipleMatches.php
src/Exception/MultipleMatches.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Found multiple matches for the credentials. * * @package Aura.Auth * */ class MultipleMatches extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/PasswordColumnNotSpecified.php
src/Exception/PasswordColumnNotSpecified.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Password column not specified. * * @package Aura.Auth * */ class PasswordColumnNotSpecified extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Exception/ConnectionFailed.php
src/Exception/ConnectionFailed.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Exception; use Aura\Auth\Exception; /** * * Connection to a network service (IMAP/LDAP/etc) failed. * * @package Aura.Auth * */ class ConnectionFailed extends Exception { }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Adapter/HtpasswdAdapter.php
src/Adapter/HtpasswdAdapter.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Adapter; use Aura\Auth\Exception; use Aura\Auth\Verifier\VerifierInterface; /** * * Authenticate against a file generated by htpassword. * * Format for each line is "username:hashedpassword\n"; * * Automatically checks against DES, SHA, and apr1-MD5. * * SECURITY NOTE: Default DES encryption will only check up to the first * 8 characters of a password; chars after 8 are ignored. This means * that if the real password is "atechars", the word "atecharsnine" would * be valid. This is bad. As a workaround, if the password provided by * the user is longer than 8 characters, and DES encryption is being * used, this class will *not* validate it. * * @package Aura.Auth * */ class HtpasswdAdapter extends AbstractAdapter { /** * * The httpasswd credential file. * * @var string * */ protected $file; /** * * A verifier for passwords. * * @var VerifierInterface * */ protected $verifier; /** * * Constructor. * * @param string $file The htpasswd file path. * * @param VerifierInterface $verifier * * @return null */ public function __construct($file, VerifierInterface $verifier) { $this->file = $file; $this->verifier = $verifier; } /** * * Return object of type VerifierInterface * * @return VerifierInterface * */ public function getVerifier() { return $this->verifier; } /** * * Verifies a set of credentials. * * @param array $input An array with keys 'username' and 'password'. * * @return array An array of login data. * */ public function login(array $input) { $this->checkInput($input); $username = $input['username']; $password = $input['password']; $hashvalue = $this->fetchHashedPassword($username); $this->verify($password, $hashvalue); return array($username, array()); } /** * * Reads the hashed password for a username from the htpasswd file. * * @param string $username The username to find in the htpasswd file. * * @return string * * @throws Exception\UsernameNotFound when the username is not found in the * htpasswd file. * */ protected function fetchHashedPassword($username) { // force the full, real path to the file $real = realpath($this->file); if (! $real) { throw new Exception\FileNotReadable($this->file); } // find the user's line in the file $fp = fopen($real, 'r'); $len = strlen($username) + 1; $hashvalue = false; while ($line = fgets($fp)) { if (substr($line, 0, $len) == "{$username}:") { // found the line, leave the loop $tmp = explode(':', trim($line)); $hashvalue = $tmp[1]; break; } } // close the file fclose($fp); // did we find the encrypted password for the username? if ($hashvalue) { return $hashvalue; } throw new Exception\UsernameNotFound; } /** * * Verifies the input password against the hashed password. * * @param string $password The input password. * * @param string $hashvalue The hashed password in htpasswd. * * @return null * * @throws Exception\PasswordIncorrect on failed verification. * */ protected function verify($password, $hashvalue) { if (! $this->verifier->verify($password, $hashvalue)) { throw new Exception\PasswordIncorrect; } } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Adapter/ImapAdapter.php
src/Adapter/ImapAdapter.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Adapter; use Aura\Auth\Exception; use Aura\Auth\Phpfunc; /** * * Authenticate against an IMAP, POP3, or NNTP server. * * @package Aura.Auth * */ class ImapAdapter extends AbstractAdapter { /** * * An imap_open() mailbox string; e.g., "{mail.example.com:143/imap/secure}" * or "{mail.example.com:110/pop3/secure}". * * @var string * */ protected $mailbox; /** * * Options for the imap_open() call. * * @var int * */ protected $options = 0; /** * * Try to connect this many times. * * @var int * */ protected $retries = 1; /** * * Params for the imap_open() call. * * @var array|null * */ protected $params; /** * * An object to intercept PHP calls. * * @var Phpfunc * */ protected $phpfunc; /** * * Constructor. * * @param Phpfunc $phpfunc An object to intercept PHP calls. * * @param string $mailbox The imap_open() mailbox string. * * @param int $options Options for the imap_open() call. * * @param int $retries Try connecting this many times. * * @param array $params Params for the imap_open() call. * */ public function __construct( Phpfunc $phpfunc, $mailbox, $options = 0, $retries = 1, array $params = null ) { $this->phpfunc = $phpfunc; $this->mailbox = $mailbox; $this->options = $options; $this->retries = $retries; $this->params = $params; } /** * * Verifies a set of credentials. * * @param array $input An array of credential data, including any data to * bind to the query. * * @return array An array of login data. * * @throws Exception\ConnectionFailed when the IMAP connection fails. * */ public function login(array $input) { $this->checkInput($input); $username = $input['username']; $password = $input['password']; $conn = $this->phpfunc->imap_open( $this->mailbox, $username, $password, $this->options, $this->retries, $this->params ); if (! $conn) { throw new Exception\ConnectionFailed($this->mailbox); } $this->phpfunc->imap_close($conn); return array($username, array()); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Adapter/NullAdapter.php
src/Adapter/NullAdapter.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Adapter; /** * * NullAdapter * * @package Aura.Auth * */ class NullAdapter extends AbstractAdapter { /** * * login * * @param array $input * * @return array * */ public function login(array $input) { return array(null, null); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Adapter/AdapterInterface.php
src/Adapter/AdapterInterface.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Adapter; use Aura\Auth\Auth; use Aura\Auth\Status; /** * * Abstract Authentication Storage. * * @package Aura.Auth * */ interface AdapterInterface { /** * * Verifies a set of credentials against a storage backend. * * @param array $input Credential input. * * @return array An array of login data on success. * */ public function login(array $input); /** * * Handle logout logic against the storage backend. * * @param Auth $auth The authentication object to be logged out. * * @param string $status The new authentication status after logout. * * @return null * * @see Status * */ public function logout(Auth $auth, $status = Status::ANON); /** * * Handle a resumed session against the storage backend. * * @param Auth $auth The authentication object to be resumed. * * @return null * */ public function resume(Auth $auth); }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Adapter/AbstractAdapter.php
src/Adapter/AbstractAdapter.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Adapter; use Aura\Auth\Exception; use Aura\Auth\Status; use Aura\Auth\Auth; /** * * Authentication adapter * * @package Aura.Auth * */ abstract class AbstractAdapter implements AdapterInterface { /** * * Verifies a set of credentials against a storage backend. * * @param array $input Credential input. * * @return array An array of login data on success. * */ abstract public function login(array $input); /** * * Handle logout logic against the storage backend. * * @param Auth $auth The authentication obbject to be logged out. * * @param string $status The new authentication status after logout. * * @return null * * @see Status * */ public function logout(Auth $auth, $status = Status::ANON) { // do nothing } /** * * Handle a resumed session against the storage backend. * * @param Auth $auth The authentication object to be resumed. * * @return null * */ public function resume(Auth $auth) { // do nothing } /** * * Check the credential input for completeness. * * @param array $input * * @return bool * */ protected function checkInput($input) { if (empty($input['username'])) { throw new Exception\UsernameMissing; } if (empty($input['password'])) { throw new Exception\PasswordMissing; } } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Adapter/LdapAdapter.php
src/Adapter/LdapAdapter.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Adapter; use Aura\Auth\Exception; use Aura\Auth\Phpfunc; /** * * Authenticate against an LDAP server. * * @package Aura.Auth * */ class LdapAdapter extends AbstractAdapter { /** * * An LDAP server connection string. * * @var string * */ protected $server; /** * * An sprintf() format string for the LDAP query. * * @var string * */ protected $dnformat = null; /** * * Set these options after the LDAP connection. * * @var array * */ protected $options = array(); /** * * An object to intercept PHP calls. * * @var Phpfunc * */ protected $phpfunc; /** * * Constructor. * * @param Phpfunc $phpfunc An object to intercept PHP calls. * * @param string $server An LDAP server connection string. * * @param string $dnformat An sprintf() format string for the LDAP query. * * @param array $options Set these options after the LDAP connection. * */ public function __construct( Phpfunc $phpfunc, $server, $dnformat, array $options = array() ) { $this->phpfunc = $phpfunc; $this->server = $server; $this->dnformat = $dnformat; $this->options = $options; } /** * * Verifies a set of credentials. * * @param array $input The 'username' and 'password' to verify. * * @return mixed An array of verified user information, or boolean false * if verification failed. * */ public function login(array $input) { $this->checkInput($input); $username = $input['username']; $password = $input['password']; $conn = $this->connect(); $this->bind($conn, $username, $password); return array($username, array()); } /** * * Connects to the LDAP server and sets options. * * @return resource The LDAP connection. * * @throws Exception\ConnectionFailed when the connection fails. * */ protected function connect() { $conn = $this->phpfunc->ldap_connect($this->server); if (! $conn) { throw new Exception\ConnectionFailed($this->server); } foreach ($this->options as $opt => $val) { $this->phpfunc->ldap_set_option($conn, $opt, $val); } return $conn; } /** * * Binds to the LDAP server with username and password. * * @param resource $conn The LDAP connection. * * @param string $username The input username. * * @param string $password The input password. * * @throws Exception\BindFailed when the username/password fails. * */ protected function bind($conn, $username, $password) { $username = $this->escape($username); $bind_rdn = sprintf($this->dnformat, $username); $bound = $this->phpfunc->ldap_bind($conn, $bind_rdn, $password); if (! $bound) { $error = $this->phpfunc->ldap_errno($conn) . ': ' . $this->phpfunc->ldap_error($conn); $this->phpfunc->ldap_unbind($conn); throw new Exception\BindFailed($error); } $this->phpfunc->ldap_unbind($conn); } /** * * Escapes input values for LDAP string. * * Per <http://projects.webappsec.org/w/page/13246947/LDAP%20Injection> * and <https://www.owasp.org/index.php/Preventing_LDAP_Injection_in_Java>. * * @param string $str The string to be escaped. * * @return string The escaped string. * */ protected function escape($str) { return strtr($str, array( '\\' => '\\\\', '&' => '\\&', '!' => '\\!', '|' => '\\|', '=' => '\\=', '<' => '\\<', '>' => '\\>', ',' => '\\,', '+' => '\\+', '-' => '\\-', '"' => '\\"', "'" => "\\'", ';' => '\\;', )); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Adapter/PdoAdapter.php
src/Adapter/PdoAdapter.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Adapter; use PDO; use Aura\Auth\Verifier\VerifierInterface; use Aura\Auth\Exception; /** * * Authenticate against an SQL database table via PDO. * * @package Aura.Auth * */ class PdoAdapter extends AbstractAdapter { /** * * A PDO connection object. * * @var PDO * */ protected $pdo; /** * * Columns to be selected. * * @param array * */ protected $cols = array(); /** * * Select FROM this table; add JOIN specifications here as needed. * * @var string * */ protected $from; /** * * Added WHERE conditions for the select. * * @var string * */ protected $where; /** * * A verifier for passwords. * * @var VerifierInterface * */ protected $verifier; /** * * Constructor * * @param \PDO $pdo A PDO connection. * * @param VerifierInterface $verifier A password verifier. * * @param array $cols The columns to be selected. * * @param string $from The table (and joins) to select from. * * @param string $where The where clause to use. * */ public function __construct( PDO $pdo, VerifierInterface $verifier, array $cols, $from, $where = null ) { $this->pdo = $pdo; $this->verifier = $verifier; $this->setCols($cols); $this->from = $from; $this->where = $where; } /** * * Set the $cols property. * * @param array $cols The columns to select. * * @return null * * @throws Exception\UsernameColumnNotSpecified * * @throws Exception\PasswordColumnNotSpecified * */ protected function setCols($cols) { if (! isset($cols[0]) || trim($cols[0] == '')) { throw new Exception\UsernameColumnNotSpecified; } if (! isset($cols[1]) || trim($cols[1] == '')) { throw new Exception\PasswordColumnNotSpecified; } $this->cols = $cols; } /** * * Returns the password verifier. * * @return VerifierInterface * */ public function getVerifier() { return $this->verifier; } /** * * Verifies the username/password credentials. * * @param array $input An array of credential data, including any data to * bind to the query. * * @return array An array of login data. * */ public function login(array $input) { $this->checkInput($input); $data = $this->fetchRow($input); $this->verify($input, $data); $name = $data['username']; unset($data['username']); unset($data['password']); return array($name, $data); } /** * * Fetches a single matching row from the database. * * @param array $input The user input. * * @return array The found row. * * @throws Exception\UsernameNotFound when no row is found. * * @throws Exception\MultipleMatches where more than one row is found. * */ protected function fetchRow($input) { $stm = $this->buildSelect(); $rows = $this->fetchRows($stm, $input); if (count($rows) < 1) { throw new Exception\UsernameNotFound; } if (count($rows) > 1) { throw new Exception\MultipleMatches; } return $rows[0]; } /** * * Fetches all matching rows from the database. * * @param string $stm The SQL statement to execute. * * @param array $bind Values to bind to the query. * * @return array * */ protected function fetchRows($stm, $bind) { $sth = $this->pdo->prepare($stm); unset($bind['password']); $sth->execute($bind); return $sth->fetchAll(PDO::FETCH_ASSOC); } /** * * Builds the SQL statement for finding the user data. * * @return string * */ protected function buildSelect() { $cols = $this->buildSelectCols(); $from = $this->buildSelectFrom(); $where = $this->buildSelectWhere(); return "SELECT {$cols} FROM {$from} WHERE {$where}"; } /** * * Builds the SELECT column list. * * @return string * */ protected function buildSelectCols() { $cols = $this->cols; $cols[0] .= ' AS username'; $cols[1] .= ' AS password'; return implode(', ', $cols); } /** * * Builds the FROM clause. * * @return string * */ protected function buildSelectFrom() { return $this->from; } /** * * Builds the WHERE clause. * * @return string * */ protected function buildSelectWhere() { $where = $this->cols[0] . " = :username"; if ($this->where) { $where .= " AND ({$this->where})"; } return $where; } /** * * Verifies the password. * * @param array $input The user input array. * * @param array $data The data from the database. * * @return bool * * @throws Exception\PasswordIncorrect * */ protected function verify($input, $data) { $verified = $this->verifier->verify( $input['password'], $data['password'], $data ); if (! $verified) { throw new Exception\PasswordIncorrect; } return true; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Session/SegmentInterface.php
src/Session/SegmentInterface.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Session; /** * * Interface for segment of the $_SESSION array. * * @package Aura.Auth * */ interface SegmentInterface { /** * * Gets a value from the segment. * * @param mixed $key A key for the segment value. * * @param mixed $alt Return this value if the segment key does not exist. * * @return mixed * */ public function get($key, $alt = null); /** * * Sets a value in the segment. * * @param mixed $key The key in the segment. * * @param mixed $val The value to set. * */ public function set($key, $val); }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Session/Segment.php
src/Session/Segment.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Session; /** * * A $_SESSION segment; it attaches to $_SESSION lazily (i.e., only after a * session becomes available.) * * @package Aura.Auth * */ class Segment implements SegmentInterface { /** * * The name of the $_SESSION segment, typically a class name. * * @var string * */ protected $name; /** * * Constructor. * * @param string $name The name of the $_SESSION segment. * */ public function __construct($name = 'Aura\Auth\Auth') { $this->name = $name; } /** * * Gets a value from the segment. * * @param mixed $key A key for the segment value. * * @param mixed $alt Return this value if the segment key does not exist. * * @return mixed * */ public function get($key, $alt = null) { if (isset($_SESSION[$this->name][$key])) { return $_SESSION[$this->name][$key]; } return $alt; } /** * * Sets a value in the segment. * * @param mixed $key The key in the segment. * * @param mixed $val The value to set. * */ public function set($key, $val) { if (! isset($_SESSION)) { return; } $_SESSION[$this->name][$key] = $val; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Session/NullSession.php
src/Session/NullSession.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Session; /** * * Session manager. * * @package Aura.Auth * */ class NullSession implements SessionInterface { /** * * Start Session * * @return bool * */ public function start() { return true; } /** * * Resume previous session * * @return bool * */ public function resume() { return false; } /** * * Re generate session id * * @return mixed * */ public function regenerateId() { return true; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Session/NullSegment.php
src/Session/NullSegment.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Session; /** * * A $this->data segment; it attaches to $this->data lazily (i.e., only after a * session becomes available.) * * @package Aura.Auth * */ class NullSegment implements SegmentInterface { /** * * The segment data. * * @var array * */ protected $data = array(); /** * * Gets a value from the segment. * * @param mixed $key A key for the segment value. * * @param mixed $alt Return this value if the segment key does not exist. * * @return mixed * */ public function get($key, $alt = null) { if (isset($this->data[$key])) { return $this->data[$key]; } return $alt; } /** * * Sets a value in the segment. * * @param mixed $key The key in the segment. * * @param mixed $val The value to set. * */ public function set($key, $val) { $this->data[$key] = $val; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Session/SessionInterface.php
src/Session/SessionInterface.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Session; /** * * Interface for a session manager. * * @package Aura.Auth * */ interface SessionInterface { /** * * Starts a session. * */ public function start(); /** * * Resumes a previously-existing session. * */ public function resume(); /** * * Regenerates the session ID. * */ public function regenerateId(); }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Session/Timer.php
src/Session/Timer.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Session; use Aura\Auth\Exception; use Aura\Auth\Status; /** * * Timer * * @package Aura.Auth * */ class Timer { /** * ini_gc_maxlifetime * * @var int * @access protected */ protected $ini_gc_maxlifetime; /** * ini_cookie_lifetime * * @var int * @access protected */ protected $ini_cookie_lifetime; /** * * Maximum idle time in seconds; zero is forever. * * @var int * */ protected $idle_ttl = 3600; // 1 hour /** * * Maximum authentication lifetime in seconds; zero is forever. * * @var int * */ protected $expire_ttl = 86400; // 24 hours /** * * Constructor. * * @param int $ini_gc_maxlifetime * * @param int $ini_cookie_lifetime * * @param int $idle_ttl The maximum idle time in seconds. * * @param int $expire_ttl The maximum authentication time in seconds. * */ public function __construct( $ini_gc_maxlifetime = 86401, // 24 hours plus 1 second $ini_cookie_lifetime = 0, $idle_ttl = 3600, // 1 hour $expire_ttl = 86400 // 24 hours ) { $this->ini_gc_maxlifetime = $ini_gc_maxlifetime; $this->ini_cookie_lifetime = $ini_cookie_lifetime; $this->setIdleTtl($idle_ttl); $this->setExpireTtl($expire_ttl); } /** * * Sets the maximum idle time. * * @param int $idle_ttl The maximum idle time in seconds. * * @throws Exception when the session garbage collection max lifetime is * less than the idle time. * * @return null * */ public function setIdleTtl($idle_ttl) { if ($this->ini_gc_maxlifetime < $idle_ttl) { throw new Exception("session.gc_maxlifetime {$this->ini_gc_maxlifetime} less than idle time $idle_ttl"); } $this->idle_ttl = $idle_ttl; } /** * * Returns the maximum idle time. * * @return int * */ public function getIdleTtl() { return $this->idle_ttl; } /** * * Sets the maximum authentication lifetime. * * @param int $expire_ttl The maximum authentication lifetime in seconds. * * @throws Exception when the session cookie lifetime is less than the * authentication lifetime. * * @return null * */ public function setExpireTtl($expire_ttl) { $bad = $this->ini_cookie_lifetime > 0 && $this->ini_cookie_lifetime < $expire_ttl; if ($bad) { throw new Exception('session.cookie_lifetime less than expire time'); } $this->expire_ttl = $expire_ttl; } /** * * Returns the maximum authentication lifetime. * * @return int * */ public function getExpireTtl() { return $this->expire_ttl; } /** * * Has the authentication time expired? * * @param int $first_active * * @return bool * */ public function hasExpired($first_active) { return $this->expire_ttl <= 0 || ($first_active + $this->getExpireTtl()) < time(); } /** * * Has the idle time been exceeded? * * @param int $last_active * * @return bool * */ public function hasIdled($last_active) { return $this->idle_ttl <= 0 || ($last_active + $this->getIdleTtl()) < time(); } /** * * Get Timeout Status * * @param int $first_active * * @param int $last_active * * @return string * */ public function getTimeoutStatus($first_active, $last_active) { if ($this->hasExpired($first_active)) { return Status::EXPIRED; } if ($this->hasIdled($last_active)) { return Status::IDLE; } } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Session/Session.php
src/Session/Session.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Session; /** * * Session manager. * * @package Aura.Auth * */ class Session implements SessionInterface { /** * * A copy of the $_COOKIE array. * * @var array * */ protected $cookie; /** * * Constructor. * * @param array $cookie A copy of the $_COOKIE array. * */ public function __construct(array $cookie) { $this->cookie = $cookie; } /** * * Starts a session. * * @return bool * */ public function start() { return session_start(); } /** * * Resumes a previously-started session. * * @return bool * */ public function resume() { if (session_id() !== '') { return true; } if (isset($this->cookie[session_name()])) { return $this->start(); } return false; } /** * * Regenerates a session ID. * * @return mixed * */ public function regenerateId() { return session_regenerate_id(true); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Service/LoginService.php
src/Service/LoginService.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Service; use Aura\Auth\Adapter\AdapterInterface; use Aura\Auth\Session\SessionInterface; use Aura\Auth\Status; use Aura\Auth\Auth; /** * * Login handler * * @package Aura.Auth * */ class LoginService { /** * * Adapter of Adapterinterface * * @var mixed * */ protected $adapter; /** * * session * * @var SessionInterface * */ protected $session; /** * * Constructor. * * @param AdapterInterface $adapter A credential-storage adapter. * * @param SessionInterface $session A session manager. * */ public function __construct( AdapterInterface $adapter, SessionInterface $session ) { $this->adapter = $adapter; $this->session = $session; } /** * * Logs the user in via the credential adapter. * * @param Auth $auth The authentication tracking object. * * @param array $input The credential input. * * @return null * */ public function login(Auth $auth, array $input) { list($name, $data) = $this->adapter->login($input); $this->forceLogin($auth, $name, $data); } /** * * Forces a successful login. * * @param Auth $auth The authentication tracking object. * * @param string $name The authenticated user name. * * @param string $data Additional arbitrary user data. * * @param string $status The new authentication status. * * @return string|false The authentication status on success, or boolean * false on failure. * */ public function forceLogin( Auth $auth, $name, array $data = array(), $status = Status::VALID ) { $started = $this->session->resume() || $this->session->start(); if (! $started) { return false; } $this->session->regenerateId(); $auth->set( $status, time(), time(), $name, $data ); return $status; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Service/LogoutService.php
src/Service/LogoutService.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Service; use Aura\Auth\Adapter\AdapterInterface; use Aura\Auth\Session\SessionInterface; use Aura\Auth\Status; use Aura\Auth\Auth; /** * * Logout handler. * * @package Aura.Auth * */ class LogoutService { /** * * A credential storage adapter. * * @var AdapterInterface * */ protected $adapter; /** * * A session manager. * * @var SessionInterface * */ protected $session; /** * * Constructor. * * @param AdapterInterface $adapter A credential storage adapter. * * @param SessionInterface $session A session manager. * */ public function __construct( AdapterInterface $adapter, SessionInterface $session ) { $this->adapter = $adapter; $this->session = $session; } /** * * Log the user out via the adapter. * * @param Auth $auth An authentication tracker. * * @param string $status The status after logout. * * @return null * */ public function logout(Auth $auth, $status = Status::ANON) { $this->adapter->logout($auth, $status); $this->forceLogout($auth, $status); } /** * * Forces a successful logout. * * @param Auth $auth An authentication tracker. * * @param string $status The status after logout. * * @return string The new authentication status. * */ public function forceLogout(Auth $auth, $status = Status::ANON) { $this->session->regenerateId(); $auth->set( $status, null, null, null, array() ); return $status; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/src/Service/ResumeService.php
src/Service/ResumeService.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\Service; use Aura\Auth\Auth; use Aura\Auth\Adapter\AdapterInterface; use Aura\Auth\Session\SessionInterface; use Aura\Auth\Session\Timer; /** * * Resume handler. * * @package Aura.Auth * */ class ResumeService { /** * * A credential storage adapter. * * @var AdapterInterface * */ protected $adapter; /** * * A session manager. * * @var SessionInterface * */ protected $session; /** * * A session timer. * * @var Timer * */ protected $timer; /** * * The logout handler to use if the session has timed out. * * @var LogoutService * */ protected $logout_service; /** * * Constructor. * * @param AdapterInterface $adapter A credential storage adapter. * * @param SessionInterface $session A session manager. * * @param Timer $timer A session timer. * * @param LogoutService $logout_service The logout handler to use if the * session has timed out. * */ public function __construct( AdapterInterface $adapter, SessionInterface $session, Timer $timer, LogoutService $logout_service ) { $this->adapter = $adapter; $this->session = $session; $this->timer = $timer; $this->logout_service = $logout_service; } /** * * Resumes any previous session, logging out the user as idled or * expired if needed. * * @param Auth $auth An authentication tracker. * * @return null * */ public function resume(Auth $auth) { $this->session->resume(); if (! $this->timedOut($auth)) { $auth->setLastActive(time()); $this->adapter->resume($auth); } } /** * * Sets the user timeout status, and logs out if expired. * * @param Auth $auth An authentication tracker. * * @return bool * */ protected function timedOut(Auth $auth) { if ($auth->isAnon()) { return false; } $timeout_status = $this->timer->getTimeoutStatus( $auth->getFirstActive(), $auth->getLastActive() ); if ($timeout_status) { $auth->setStatus($timeout_status); $this->logout_service->logout($auth, $timeout_status); return true; } return false; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/PhpfuncTest.php
tests/PhpfuncTest.php
<?php namespace Aura\Auth; class PhpfuncTest extends \PHPUnit\Framework\TestCase { protected $phpfunc; protected function setUp() : void { $this->phpfunc = new Phpfunc; } public function testInstance() { $this->assertEquals( str_replace('Hello', 'Hi', 'Hello Aura'), $this->phpfunc->str_replace('Hello', 'Hi', 'Hello Aura') ); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/FakePdo.php
tests/FakePdo.php
<?php namespace Aura\Auth; use PDO; class FakePdo extends PDO { public function __construct() { // do nothing } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/AuthFactoryTest.php
tests/AuthFactoryTest.php
<?php namespace Aura\Auth; use PDO; use Aura\Auth\Session\Session; use Aura\Auth\Session\Segment; use Aura\Auth\Verifier\FakeVerifier; class AuthFactoryTest extends \PHPUnit\Framework\TestCase { protected $factory; protected function setUp() : void { $this->factory = new AuthFactory($_COOKIE); } public function testNewAuth() { $auth = $this->factory->newInstance(array()); $this->assertInstanceOf('Aura\Auth\Auth', $auth); } public function testNewAuthWithSessionAndSegment() { $auth = $this->factory->newInstance(array(), new Session(array()), new Segment); $this->assertInstanceOf('Aura\Auth\Auth', $auth); } public function testNewPdoAdapter_passwordVerifier() { if (false === extension_loaded('pdo_sqlite')) { $this->markTestSkipped("Cannot test this adapter with pdo_sqlite extension disabled."); } $pdo = new PDO('sqlite::memory:'); $adapter = $this->factory->newPdoAdapter( $pdo, 1, array('username', 'password'), 'accounts' ); $this->assertInstanceOf('Aura\Auth\Adapter\PdoAdapter', $adapter); $verifier = $adapter->getVerifier(); $this->assertInstanceOf('Aura\Auth\Verifier\PasswordVerifier',$verifier); } public function testNewPdoAdapter_customVerifier() { if (false === extension_loaded('pdo_sqlite')) { $this->markTestSkipped("Cannot test this adapter with pdo_sqlite extension disabled."); } $pdo = new PDO('sqlite::memory:'); $adapter = $this->factory->newPdoAdapter( $pdo, new FakeVerifier, array('username', 'password'), 'accounts' ); $this->assertInstanceOf('Aura\Auth\Adapter\PdoAdapter', $adapter); $verifier = $adapter->getVerifier(); $this->assertInstanceOf('Aura\Auth\Verifier\FakeVerifier', $verifier); } public function testNewHtpasswdAdapter() { $file = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'fake.htpasswd'; $adapter = $this->factory->newHtpasswdAdapter($file); $this->assertInstanceOf('Aura\Auth\Adapter\HtpasswdAdapter', $adapter); $verifier = $adapter->getVerifier(); $this->assertInstanceOf('Aura\Auth\Verifier\HtpasswdVerifier', $verifier); } public function testNewImapAdapter() { $adapter = $this->factory->newImapAdapter('imap.example.com', '{mbox}'); $this->assertInstanceOf('Aura\Auth\Adapter\ImapAdapter', $adapter); } public function testNewLdapAdapter() { $adapter = $this->factory->newLdapAdapter('ldap.example.com', 'ou=Org'); $this->assertInstanceOf('Aura\Auth\Adapter\LdapAdapter', $adapter); } public function testNewLoginService() { $service = $this->factory->newLoginService(); $this->assertInstanceOf('Aura\Auth\Service\LoginService', $service); } public function testNewLogoutService() { $service = $this->factory->newLogoutService(); $this->assertInstanceOf('Aura\Auth\Service\LogoutService', $service); } public function testNewResumeService() { $service = $this->factory->newResumeService(); $this->assertInstanceOf('Aura\Auth\Service\ResumeService', $service); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/AuthTest.php
tests/AuthTest.php
<?php namespace Aura\Auth; use Aura\Auth\Session\FakeSegment; use Aura\Auth\Status; class AuthTest extends \PHPUnit\Framework\TestCase { protected $auth; protected $segment; protected function setUp() : void { $this->segment = new FakeSegment; $this->auth = new Auth($this->segment); } public function test() { $now = time(); $this->auth->set( Status::VALID, $now, $now, 'boshag', array('foo' => 'bar') ); $this->assertSame(Status::VALID, $this->auth->getStatus()); $this->assertSame($now, $this->auth->getFirstActive()); $this->assertSame($now, $this->auth->getLastActive()); $this->assertSame('boshag', $this->auth->getUserName()); $this->assertSame(array('foo' => 'bar'), $this->auth->getUserData()); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Verifier/HtpasswdVerifierTest.php
tests/Verifier/HtpasswdVerifierTest.php
<?php namespace Aura\Auth\Verifier; class HtpasswdVerifierTest extends \PHPUnit\Framework\TestCase { public function setUp() : void { $this->verifier = new HtpasswdVerifier; } public function testDes() { $hashvalue = 'ngPfeOKlo3uIs'; $this->assertTrue($this->verifier->verify('12345678', $hashvalue)); $this->assertFalse($this->verifier->verify('wrong', $hashvalue)); $this->assertFalse($this->verifier->verify('1234567890', $hashvalue)); } public function testSha() { $hashvalue = '{SHA}MCdMR5A70brHYzu/CXQxSeurgF8='; $this->assertTrue($this->verifier->verify('passwd', $hashvalue)); $this->assertFalse($this->verifier->verify('wrong', $hashvalue)); } public function testApr() { $hashvalue = '$apr1$c4b0dz9t$FRDSRse3FWsZidoPAx9g0.'; $this->assertTrue($this->verifier->verify('tkirah', $hashvalue)); $this->assertFalse($this->verifier->verify('wrong', $hashvalue)); } public function testBcrypt() { if (! function_exists('password_verify')) { $this->markTestSkipped("password_hash functionality not available. Install ircmaxell/password-compat for 5.3+"); } $hashvalue = '$2y$05$VBdzN9btLNhVZi1tyl8nOeNiQcafX.A8pR/HJT57XHKK2lGmPpaDW'; $this->assertTrue($this->verifier->verify('1234567890', $hashvalue)); $this->assertFalse($this->verifier->verify('wrong', $hashvalue)); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Verifier/PasswordVerifierTest.php
tests/Verifier/PasswordVerifierTest.php
<?php namespace Aura\Auth\Verifier; class PasswordVerifierTest extends \PHPUnit\Framework\TestCase { public function testBcrypt() { if (! defined('PASSWORD_BCRYPT')) { $this->markTestSkipped("password_hash functionality not available. Install ircmaxell/password-compat for 5.3+"); } $verifier = new PasswordVerifier(PASSWORD_BCRYPT); $plaintext = 'password'; $hashvalue = password_hash($plaintext, PASSWORD_BCRYPT); $this->assertTrue($verifier->verify($plaintext, $hashvalue)); $this->assertFalse($verifier->verify('wrong', $hashvalue)); } public function testHash() { $verifier = new PasswordVerifier('md5'); $plaintext = 'password'; $hashvalue = hash('md5', $plaintext); $this->assertTrue($verifier->verify($plaintext, $hashvalue)); $this->assertFalse($verifier->verify('wrong', $hashvalue)); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Verifier/FakeVerifier.php
tests/Verifier/FakeVerifier.php
<?php namespace Aura\Auth\Verifier; class FakeVerifier implements VerifierInterface { public function verify($plaintext, $hashvalue, array $extra = array()) { throw new \Exception('should not be calling this'); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Adapter/LdapAdapterTest.php
tests/Adapter/LdapAdapterTest.php
<?php namespace Aura\Auth\Adapter; use Aura\Auth\Phpfunc; class LdapAdapterTest extends \PHPUnit\Framework\TestCase { protected $adapter; protected $phpfunc; protected function setUp() : void { $this->phpfunc = $this->getMockBuilder('Aura\Auth\Phpfunc') ->setMethods(array( 'ldap_connect', 'ldap_bind', 'ldap_unbind', 'ldap_set_option', 'ldap_errno', 'ldap_error' )) ->getMock(); $this->adapter = new LdapAdapter( $this->phpfunc, 'ldaps://ldap.example.com:636', 'ou=Foo,dc=Bar,cn=users,uid=%s', array('LDAP_OPTION_KEY', 'LDAP_OPTION_VALUE') ); } public function testInstance() { $this->assertInstanceOf( 'Aura\Auth\Adapter\LdapAdapter', $this->adapter ); } public function testLogin() { $this->phpfunc->expects($this->once()) ->method('ldap_connect') ->with('ldaps://ldap.example.com:636') ->will($this->returnValue(true)); $this->phpfunc->expects($this->any()) ->method('ldap_set_option') ->will($this->returnValue(true)); $this->phpfunc->expects($this->once()) ->method('ldap_bind') ->with( true, 'ou=Foo,dc=Bar,cn=users,uid=someusername', 'secretpassword' ) ->will($this->returnValue(true)); $this->phpfunc->expects($this->once()) ->method('ldap_unbind') ->will($this->returnValue(true)); $actual = $this->adapter->login(array( 'username' => 'someusername', 'password' => 'secretpassword' )); $this->assertEquals( array('someusername', array()), $actual ); } public function testLogin_connectionFailed() { $input = array( 'username' => 'someusername', 'password' => 'secretpassword' ); $this->phpfunc->expects($this->once()) ->method('ldap_connect') ->with('ldaps://ldap.example.com:636') ->will($this->returnValue(false)); $this->expectException('Aura\Auth\Exception\ConnectionFailed'); $this->adapter->login($input); } public function testLogin_bindFailed() { $this->phpfunc->expects($this->once()) ->method('ldap_connect') ->with('ldaps://ldap.example.com:636') ->will($this->returnValue(true)); $this->phpfunc->expects($this->any()) ->method('ldap_set_option') ->will($this->returnValue(true)); $this->phpfunc->expects($this->once()) ->method('ldap_bind') ->will($this->returnValue(false)); $this->phpfunc->expects($this->once()) ->method('ldap_errno') ->will($this->returnValue(1)); $this->phpfunc->expects($this->once()) ->method('ldap_error') ->will($this->returnValue('Operations Error')); $this->phpfunc->expects($this->once()) ->method('ldap_unbind') ->will($this->returnValue(true)); $this->expectException('Aura\Auth\Exception\BindFailed'); $this->adapter->login(array( 'username' => 'someusername', 'password' => 'secretpassword' )); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Adapter/PdoAdapterTest.php
tests/Adapter/PdoAdapterTest.php
<?php namespace Aura\Auth\Adapter; use PDO; use Aura\Auth\Verifier\PasswordVerifier; class PdoAdapterTest extends \PHPUnit\Framework\TestCase { protected $adapter; protected $pdo; protected function setUp() : void { if (false === extension_loaded('pdo_sqlite')) { $this->markTestSkipped("Cannot test this adapter with pdo_sqlite extension disabled."); } $this->pdo = new PDO('sqlite::memory:'); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->buildTable(); $this->setAdapter(); } protected function setAdapter($where = null) { $this->adapter = new PdoAdapter( $this->pdo, new PasswordVerifier('md5'), array('username', 'password', 'active'), 'accounts', $where ); } protected function buildTable() { $stm = "CREATE TABLE accounts ( username VARCHAR(255), password VARCHAR(255), active VARCHAR(255) )"; $this->pdo->query($stm); $rows = array( array( 'username' => 'boshag', 'password' => hash('md5', '123456'), 'active' => 'y', ), array( 'username' => 'repeat', 'password' => hash('md5', '234567'), 'active' => 'y', ), array( 'username' => 'repeat', 'password' => hash('md5', '234567'), 'active' => 'n', ), ); $stm = "INSERT INTO accounts (username, password, active) VALUES (:username, :password, :active)"; $sth = $this->pdo->prepare($stm); foreach ($rows as $row) { $sth->execute($row); } } public function test_usernameColumnNotSpecified() { $this->expectException('Aura\Auth\Exception\UsernameColumnNotSpecified'); $this->adapter = new PdoAdapter( $this->pdo, new PasswordVerifier('md5'), array(), 'accounts' ); } public function test_passwordColumnNotSpecified() { $this->expectException('Aura\Auth\Exception\PasswordColumnNotSpecified'); $this->adapter = new PdoAdapter( $this->pdo, new PasswordVerifier('md5'), array('username'), 'accounts' ); } public function testLogin() { list($name, $data) = $this->adapter->login(array( 'username' => 'boshag', 'password' => '123456', )); $this->assertSame('boshag', $name); $this->assertSame(array('active' => 'y'), $data); } public function testLogin_usernameMissing() { $this->expectException('Aura\Auth\Exception\UsernameMissing'); $this->adapter->login(array()); } public function testLogin_passwordMissing() { $this->expectException('Aura\Auth\Exception\PasswordMissing'); $this->adapter->login(array( 'username' => 'boshag', )); } public function testLogin_usernameNotFound() { $this->expectException('Aura\Auth\Exception\UsernameNotFound'); $this->adapter->login(array( 'username' => 'missing', 'password' => '------', )); } public function testLogin_passwordIncorrect() { $this->expectException('Aura\Auth\Exception\PasswordIncorrect'); $this->adapter->login(array( 'username' => 'boshag', 'password' => '------', )); } public function testLogin_multipleMatches() { $this->expectException('Aura\Auth\Exception\MultipleMatches'); $this->adapter->login(array( 'username' => 'repeat', 'password' => '234567', )); } public function testLogin_where() { $this->setAdapter("active = :active"); list($name, $data) = $this->adapter->login(array( 'username' => 'repeat', 'password' => '234567', 'active' => 'y', )); $this->assertSame('repeat', $name); $this->assertSame(array('active' => 'y'), $data); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Adapter/ImapAdapterTest.php
tests/Adapter/ImapAdapterTest.php
<?php namespace Aura\Auth\Adapter; use Aura\Auth\Phpfunc; class ImapAdapterTest extends \PHPUnit\Framework\TestCase { protected $phpfunc; protected $adapter; protected function setUp() : void { $this->phpfunc = $this->getMockBuilder('Aura\Auth\Phpfunc') ->setMethods(array( 'imap_open', 'imap_close', )) ->getMock(); $this->adapter = new ImapAdapter( $this->phpfunc, '{mailbox.example.com:143/imap/secure}' ); } public function testInstance() { $this->assertInstanceOf( 'Aura\Auth\Adapter\ImapAdapter', $this->adapter ); } public function testLogin() { $this->phpfunc->expects($this->once()) ->method('imap_open') ->with( '{mailbox.example.com:143/imap/secure}', 'someusername', 'secretpassword', 0, 1, null ) ->will($this->returnValue(true)); $actual = $this->adapter->login(array( 'username' => 'someusername', 'password' => 'secretpassword' )); $expect = array('someusername', array()); $this->assertSame($expect, $actual); } public function testLogin_connectionFailed() { $this->phpfunc->expects($this->once()) ->method('imap_open') ->with('{mailbox.example.com:143/imap/secure}') ->will($this->returnValue(false)); $this->expectException('Aura\Auth\Exception\ConnectionFailed'); $this->adapter->login(array( 'username' => 'someusername', 'password' => 'secretpassword' )); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Adapter/FakeAdapter.php
tests/Adapter/FakeAdapter.php
<?php namespace Aura\Auth\Adapter; use Aura\Auth\Auth; use Aura\Auth\Exception; class FakeAdapter extends AbstractAdapter { protected $accounts = array(); public function __construct(array $accounts = array()) { $this->accounts = $accounts; } public function login(array $input) { return array($input['username'], array()); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Adapter/HtpasswdAdapterTest.php
tests/Adapter/HtpasswdAdapterTest.php
<?php namespace Aura\Auth\Adapter; use Aura\Auth\Verifier\HtpasswdVerifier; class HtpasswdAdapterTest extends \PHPUnit\Framework\TestCase { protected $adapter; protected function setUp() : void { $file = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'fake.htpasswd'; $this->setAdapter($file); } protected function setAdapter($file) { $this->adapter = new HtpasswdAdapter($file, new HtpasswdVerifier); } public function testLogin_fileNotReadable() { $this->setAdapter('no-such-file'); $this->expectException('Aura\Auth\Exception\FileNotReadable'); $this->adapter->login(array( 'username' => 'boshag', 'password' => '123456', )); } public function testLogin_success() { list($name, $data) = $this->adapter->login(array( 'username' => 'boshag', 'password' => '123456', )); $this->assertSame('boshag', $name); $this->assertSame(array(), $data); } public function testLogin_usernameMissing() { $this->expectException('Aura\Auth\Exception\UsernameMissing'); $this->adapter->login(array()); } public function testLogin_passwordMissing() { $this->expectException('Aura\Auth\Exception\PasswordMissing'); $this->adapter->login(array( 'username' => 'boshag', )); } public function testLogin_usernameNotFound() { $this->expectException('Aura\Auth\Exception\UsernameNotFound'); $this->adapter->login(array( 'username' => 'nouser', 'password' => 'nopass', )); } public function testLogin_passwordIncorrect() { $this->expectException('Aura\Auth\Exception\PasswordIncorrect'); $this->adapter->login(array( 'username' => 'boshag', 'password' => '------', )); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Adapter/NullAdapterTest.php
tests/Adapter/NullAdapterTest.php
<?php namespace Aura\Auth\Adapter; class NullAdapterTest extends \PHPUnit\Framework\TestCase { protected $adapter; protected function setUp() : void { $this->adapter = new NullAdapter; } public function testLogin() { list($name, $data) = $this->adapter->login(array()); $this->assertNull($name); $this->assertNull($data); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Session/FakeSession.php
tests/Session/FakeSession.php
<?php namespace Aura\Auth\Session; class FakeSession implements SessionInterface { public $started = false; public $resumed = false; public $session_id = 1; public $allow_start = true; public $allow_resume = true; public function start() { $this->started = $this->allow_start; return $this->started; } public function resume() { $this->resumed = $this->allow_resume; return $this->resumed; } public function regenerateId() { $this->session_id ++; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Session/SessionTest.php
tests/Session/SessionTest.php
<?php namespace Aura\Auth\Session; /** * @runTestsInSeparateProcesses */ class SessionTest extends \PHPUnit\Framework\TestCase { protected function setUp() : void { $this->setSession(); } protected function setSession(array $cookie = array()) { $this->session = new Session($cookie); } public function testStart() { // no session yet $this->assertTrue(session_id() === ''); // start once $this->session->start(); $id = session_id(); $this->assertTrue(session_id() !== ''); } public function testResume() { // fake a previous session cookie $this->setSession(array(session_name() => true)); // no session yet $this->assertTrue(session_id() === ''); // resume the pre-existing session $this->assertTrue($this->session->resume()); // now we have a session $this->assertTrue(session_id() !== ''); // try again after the session is already started $this->assertTrue($this->session->resume()); } public function testResume_nonePrevious() { // no previous session cookie $cookie = array(); $this->session = new Session($cookie); // no session yet $this->assertTrue(session_id() === ''); // no pre-existing session to resume $this->assertFalse($this->session->resume()); // still no session $this->assertTrue(session_id() === ''); } public function testRegenerateId() { $cookie = array(); $this->session = new Session($cookie); $this->session->start(); $old_id = session_id(); $this->assertTrue(session_id() !== ''); $this->session->regenerateId(); $new_id = session_id(); $this->assertTrue($old_id !== $new_id); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Session/TimerTest.php
tests/Session/TimerTest.php
<?php namespace Aura\Auth\Session; use Aura\Auth\Status; class TimerTest extends \PHPUnit\Framework\TestCase { protected $timer; protected function setUp() : void { $this->timer = new Timer(3600, 86400); } public function testHasExpired() { $this->assertFalse($this->timer->hasExpired(time())); $this->assertTrue($this->timer->hasExpired(time() - 86401)); } public function testHasIdled() { $this->assertFalse($this->timer->hasIdled(time())); $this->assertTrue($this->timer->hasIdled(time() - 3601)); } public function testGetTimeoutStatus() { $actual = $this->timer->getTimeoutStatus( time() - 86401, time() ); $this->assertSame(Status::EXPIRED, $actual); $actual = $this->timer->getTimeoutStatus( time() - 3602, time() - 3601 ); $this->assertSame(Status::IDLE, $actual); $this->assertNull($this->timer->getTimeoutStatus( time(), time() )); } public function testSetIdleTtl_bad() { $this->expectException('Aura\Auth\Exception'); $this->timer->setIdleTtl(3601); } public function testSetExpireTtl_bad() { $this->expectException('Aura\Auth\Exception'); $this->timer->setExpireTtl(86401); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Session/NullSessionTest.php
tests/Session/NullSessionTest.php
<?php namespace Aura\Auth\Session; class NullSessionTest extends \PHPUnit\Framework\TestCase { protected $session; protected function setUp() : void { $this->session = new NullSession; } public function testStart() { $this->assertTrue(session_id() === ''); $this->assertTrue($this->session->start()); $this->assertTrue(session_id() === ''); } public function testResume() { $this->assertTrue(session_id() === ''); $this->assertFalse($this->session->resume()); $this->assertTrue(session_id() === ''); } public function testRegenerateId() { $this->assertTrue(session_id() === ''); $this->assertTrue($this->session->regenerateId()); $this->assertTrue(session_id() === ''); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Session/FakeSegment.php
tests/Session/FakeSegment.php
<?php namespace Aura\Auth\Session; class FakeSegment implements SegmentInterface { public function get($key, $alt = null) { if (isset($this->$key)) { return $this->$key; } return $alt; } public function set($key, $val) { $this->$key = $val; } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Session/SegmentTest.php
tests/Session/SegmentTest.php
<?php namespace Aura\Auth\Session; class SegmentTest extends \PHPUnit\Framework\TestCase { protected $segment; public function setUp() : void { $this->segment = new Segment(__CLASS__); } public function testWithoutSession() { $this->segment->set('foo', 'bar'); $this->assertNull($this->segment->get('foo')); } /** * @runInSeparateProcess */ public function testWithSession() { session_start(); $this->assertNull($this->segment->get('foo')); $this->segment->set('foo', 'bar'); $this->assertSame('bar', $this->segment->get('foo')); $this->assertSame('bar', $_SESSION[__CLASS__]['foo']); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Session/NullSegmentTest.php
tests/Session/NullSegmentTest.php
<?php namespace Aura\Auth\Session; class NullSegmentTest extends \PHPUnit\Framework\TestCase { protected $segment; public function setUp() : void { $this->segment = new NullSegment; } public function test() { $this->assertNull($this->segment->get('foo')); $this->segment->set('foo', 'bar'); $this->assertSame('bar', $this->segment->get('foo')); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Service/LogoutServiceTest.php
tests/Service/LogoutServiceTest.php
<?php namespace Aura\Auth\Service; use Aura\Auth\Adapter\FakeAdapter; use Aura\Auth\Session\FakeSession; use Aura\Auth\Session\FakeSegment; use Aura\Auth\Session\Timer; use Aura\Auth\Auth; use Aura\Auth\Status; class LogoutServiceTest extends \PHPUnit\Framework\TestCase { protected $session; protected $segment; protected $adapter; protected $auth; protected $login_service; protected $logout_service; protected function setUp() : void { $this->segment = new FakeSegment; $this->session = new FakeSession; $this->adapter = new FakeAdapter; $this->auth = new Auth($this->segment); $this->login_service = new LoginService( $this->adapter, $this->session ); $this->logout_service = new LogoutService( $this->adapter, $this->session ); } public function testLogout() { $this->login_service->forceLogin($this->auth, 'boshag'); $this->assertTrue($this->auth->isValid()); $this->logout_service->logout($this->auth); $this->assertTrue($this->auth->isAnon()); } public function testForceLogout() { $result = $this->login_service->forceLogin( $this->auth, 'boshag', array('foo' => 'bar') ); $this->assertSame(Status::VALID, $result); $this->assertTrue($this->auth->isValid()); $result = $this->logout_service->forceLogout($this->auth); $this->assertSame(Status::ANON, $result); $this->assertSame(Status::ANON, $this->auth->getStatus()); $this->assertNull($this->auth->getUserName()); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Service/ResumeServiceTest.php
tests/Service/ResumeServiceTest.php
<?php namespace Aura\Auth\Service; use Aura\Auth\Adapter\FakeAdapter; use Aura\Auth\Session\FakeSession; use Aura\Auth\Session\FakeSegment; use Aura\Auth\Session\Timer; use Aura\Auth\Auth; use Aura\Auth\Status; class ResumeServiceTest extends \PHPUnit\Framework\TestCase { protected $segment; protected $adapter; protected $session; protected $timer; protected $auth; protected $login_service; protected $logout_service; protected $resume_service; protected function setUp() : void { $this->segment = new FakeSegment; $this->session = new FakeSession; $this->adapter = new FakeAdapter; $this->timer = new Timer(3600, 86400); $this->auth = new Auth($this->segment); $this->login_service = new LoginService( $this->adapter, $this->session ); $this->logout_service = new LogoutService( $this->adapter, $this->session ); $this->resume_service = new ResumeService( $this->adapter, $this->session, $this->timer, $this->logout_service ); } public function testResume() { $this->assertTrue($this->auth->isAnon()); $this->login_service->forceLogin($this->auth, 'boshag'); $this->assertTrue($this->auth->isValid()); $this->auth->setLastActive(time() - 100); $this->resume_service->resume($this->auth); $this->assertTrue($this->auth->isValid()); $this->assertSame(time(), $this->auth->getLastActive()); } public function testResume_cannotResume() { $this->session->allow_resume = false; $this->assertTrue($this->auth->isAnon()); $this->resume_service->resume($this->auth); $this->assertTrue($this->auth->isAnon()); } public function testResume_logoutIdle() { $this->assertTrue($this->auth->isAnon()); $this->login_service->forceLogin($this->auth, 'boshag'); $this->assertTrue($this->auth->isValid()); $this->auth->setLastActive(time() - 3601); $this->resume_service->resume($this->auth); $this->assertTrue($this->auth->isIdle()); $this->assertNull($this->auth->getUserName()); } public function testResume_logoutExpired() { $this->assertTrue($this->auth->isAnon()); $this->login_service->forceLogin($this->auth, 'boshag'); $this->assertTrue($this->auth->isValid()); $this->auth->setFirstActive(time() - 86401); $this->resume_service->resume($this->auth); $this->assertTrue($this->auth->isExpired()); $this->assertNull($this->auth->getUserName()); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/tests/Service/LoginServiceTest.php
tests/Service/LoginServiceTest.php
<?php namespace Aura\Auth\Service; use Aura\Auth\Adapter\FakeAdapter; use Aura\Auth\Session\FakeSession; use Aura\Auth\Session\FakeSegment; use Aura\Auth\Session\Timer; use Aura\Auth\Auth; use Aura\Auth\Status; class LoginServiceTest extends \PHPUnit\Framework\TestCase { protected $segment; protected $session; protected $adapter; protected $auth; protected $login_service; protected function setUp() : void { $this->segment = new FakeSegment; $this->session = new FakeSession; $this->adapter = new FakeAdapter; $this->auth = new Auth($this->segment); $this->login_service = new LoginService( $this->adapter, $this->session ); } public function testLogin() { $this->assertTrue($this->auth->isAnon()); $this->login_service->login( $this->auth, array('username' => 'boshag') ); $this->assertTrue($this->auth->isValid()); $this->assertSame('boshag', $this->auth->getUserName()); } public function testForceLogin() { $this->assertTrue($this->auth->isAnon()); $result = $this->login_service->forceLogin( $this->auth, 'boshag', array('foo' => 'bar') ); $this->assertSame(Status::VALID, $result); $this->assertSame(Status::VALID, $this->auth->getStatus()); $this->assertSame('boshag', $this->auth->getUserName()); $this->assertSame(array('foo' => 'bar'), $this->auth->getUserData()); } public function testForceLogin_cannotResumeOrStart() { $this->session->allow_resume = false; $this->session->allow_start = false; $this->assertTrue($this->auth->isAnon()); $result = $this->login_service->forceLogin( $this->auth, 'boshag', array('foo' => 'bar') ); $this->assertFalse($result); $this->assertTrue($this->auth->isAnon()); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
auraphp/Aura.Auth
https://github.com/auraphp/Aura.Auth/blob/c88b713960c3a9f4449d264bd3de440719c086e9/config/Common.php
config/Common.php
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\Auth\_Config; use Aura\Di\Config; use Aura\Di\Container; /** * * Common configuration. * * @package Aura.Auth * */ class Common extends Config { public function define(Container $di): void { /** * Services */ $di->set('aura/auth:auth', $di->lazyNew('Aura\Auth\Auth')); $di->set('aura/auth:login_service', $di->lazyNew('Aura\Auth\Service\LoginService')); $di->set('aura/auth:logout_service', $di->lazyNew('Aura\Auth\Service\LogoutService')); $di->set('aura/auth:resume_service', $di->lazyNew('Aura\Auth\Service\ResumeService')); $di->set('aura/auth:session', $di->lazyNew('Aura\Auth\Session\Session')); $di->set('aura/auth:adapter', $di->lazyNew('Aura\Auth\Adapter\NullAdapter')); /** * Aura\Auth\Adapter\HtpasswdAdapter */ $di->params['Aura\Auth\Adapter\HtpasswdAdapter'] = array( 'verifier' => $di->lazyNew('Aura\Auth\Verifier\HtpasswdVerifier'), ); /** * Aura\Auth\Adapter\ImapAdapter */ $di->params['Aura\Auth\Adapter\ImapAdapter'] = array( 'phpfunc' => $di->lazyNew('Aura\Auth\Phpfunc'), ); /** * Aura\Auth\Adapter\LdapAdapter */ $di->params['Aura\Auth\Adapter\LdapAdapter'] = array( 'phpfunc' => $di->lazyNew('Aura\Auth\Phpfunc'), ); /** * Aura\Auth\Adapter\PdoAdapter */ $di->params['Aura\Auth\Adapter\PdoAdapter'] = array( 'verifier' => $di->lazyNew('Aura\Auth\Verifier\PasswordVerifier'), 'from' => 'users', 'cols' => array('username', 'password'), ); /** * Aura\Auth\Auth */ $di->params['Aura\Auth\Auth'] = array( 'segment' => $di->lazyNew('Aura\Auth\Session\Segment') ); /** * Aura\Auth\Service\LoginService */ $di->params['Aura\Auth\Service\LoginService'] = array( 'adapter' => $di->lazyGet('aura/auth:adapter'), 'session' => $di->lazyGet('aura/auth:session') ); /** * Aura\Auth\Service\LogoutService */ $di->params['Aura\Auth\Service\LogoutService'] = array( 'adapter' => $di->lazyGet('aura/auth:adapter'), 'session' => $di->lazyGet('aura/auth:session') ); /** * Aura\Auth\Service\ResumeService */ $di->params['Aura\Auth\Service\ResumeService'] = array( 'adapter' => $di->lazyGet('aura/auth:adapter'), 'session' => $di->lazyGet('aura/auth:session'), 'timer' => $di->lazyNew('Aura\Auth\Session\Timer'), 'logout_service' => $di->lazyGet('aura/auth:logout_service'), ); /** * Aura\Auth\Session\Timer */ $di->params['Aura\Auth\Session\Timer'] = array( 'ini_gc_maxlifetime' => ini_get('session.gc_maxlifetime'), 'ini_cookie_lifetime' => ini_get('session.cookie_lifetime'), 'idle_ttl' => 3600, // 1 hour 'expire_ttl' => 86400, // 24 hours ); /** * Aura\Auth\Session\Session */ $di->params['Aura\Auth\Session\Session'] = array( 'cookie' => $_COOKIE, ); /** * Aura\Auth\Verifier\PasswordVerifier */ $di->params['Aura\Auth\Verifier\PasswordVerifier'] = array( 'algo' => 'NO_ALGO_SPECIFIED', ); } }
php
BSD-2-Clause
c88b713960c3a9f4449d264bd3de440719c086e9
2026-01-05T05:09:30.862573Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Consumer.php
src/Consumer.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * Consumer's pull messages out of the queue and execute them. * * @since 2.0 * @api */ interface Consumer { const EXIT_SUCCESS = 0; const EXIT_ERROR = 2; /** * Run the consumer for a given queue. This will block. * * @param $queueName The queue from which the jobs will be consumed. * @param $lifecycle The message lifecycle to apply to the running consumer. * @return int The exit code to be used for the consumer. */ public function run(string $queueName, ?MessageLifecycle $lifecycle=null) : int; /** * Consume a single job from the given queue. This will block until the * job is competed then return. Implementations of this method MUST be * safe to run in a loop. * * @param string $queueName The queue from which jobs will be consumed. * @param $lifecycle The message lifecycle to apply to any job run. * @throws Exception\MustStop if the executor or handler throws a must * stop execption indicating a graceful stop is necessary * @throws Exception\DriverError|Exception if anything goes wrong with the * underlying driver itself. * @return boolean|null True if the a job was execute successfully. Null if * no job was executed. See the logs. */ public function once(string $queueName, ?MessageLifecycle $lifecycle=null) : ?bool; /** * Gracefully stop the consumer with the given exit code. * * @param int $code The exit code passed to `exit`. If null `EXIT_SUCCESS` is used. * @return void */ public function stop(?int $code=null) : void; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/AbstractConsumer.php
src/AbstractConsumer.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; /** * ABC for consumers, provides `run` and `stop` along with their default * implementations to make it easier to decorate consumers to add extra stuff. * * @since 3.0 */ abstract class AbstractConsumer implements Consumer { use MessageNames; /** * @var LoggerInterface */ private $logger; /** * @var boolean */ private $running = false; /** * @var int */ private $exitCode = self::EXIT_SUCCESS; /** * @var bool */ private $hasPcntl = null; public function __construct(?LoggerInterface $logger=null) { $this->logger = $logger; } /** * {@inheritdoc} */ public function run(string $queueName, ?MessageLifecycle $lifecycle=null) : int { $lifecycle = $lifecycle ?? new Lifecycle\NullLifecycle(); $this->running = true; while ($this->running) { $this->maybeCallSignalHandlers(); try { $this->once($queueName, $lifecycle); } catch (Exception\MustStop $e) { $this->getLogger()->warning('Caught a must stop exception, exiting: {msg}', [ 'msg' => $e->getMessage(), 'exception' => $e, ]); $this->stop($e->getCode()); } catch (\Throwable $e) { // likely means means something went wrong with the driver $this->logFatalAndStop($e); } } return $this->exitCode; } /** * {@inheritdoc} */ public function stop(?int $code=null) : void { $this->running = false; $this->exitCode = null === $code ? self::EXIT_SUCCESS : $code; } protected function getLogger() { if (!$this->logger) { $this->logger = new NullLogger(); } return $this->logger; } protected function logFatalAndStop(\Throwable $exception) { $this->getLogger()->emergency('Caught an unexpected {cls} exception, exiting: {msg}', [ 'cls' => get_class($exception), 'msg' => $exception->getMessage(), 'exception' => $exception, ]); $this->stop(self::EXIT_ERROR); } protected function maybeCallSignalHandlers() { if (null === $this->hasPcntl) { $this->hasPcntl = function_exists('pcntl_signal_dispatch'); } return $this->hasPcntl ? pcntl_signal_dispatch() : false; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/DefaultProducer.php
src/DefaultProducer.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * The default implementation of the producer. Uses a router to look up * where the message should go then adds it to the queue. * * @since 2015-06-09 */ final class DefaultProducer implements Producer { use MessageNames; /** * @var Driver */ private $driver; /** * @var Router */ private $router; public function __construct(Driver $driver, Router $router) { $this->driver = $driver; $this->router = $router; } /** * {@inheritdoc} */ public function send(object $messageOrEnvelope) : void { $message = $messageOrEnvelope instanceof Envelope ? $messageOrEnvelope->unwrap() : $messageOrEnvelope; $queueName = $this->router->queueFor($message); if (!$queueName) { throw new Exception\QueueNotFound(sprintf( 'Could not find a queue for "%s"', self::nameOf($message) )); } $this->driver->enqueue($queueName, $messageOrEnvelope); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/RetrySpec.php
src/RetrySpec.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * Some queue implementations use retry strategies to determine whether or * not a given message should be retried after failure. * * @since 2.0 * @api */ interface RetrySpec { /** * Given an envelop check whether or not it can be retried. * * @param $env The envelop to check * @return boolean True if the message should be retried. */ public function canRetry(Envelope $env) : bool; /** * Get the number of seconds before an envelop can be retried. * * @since 5.0.0 */ public function retryDelay(Envelope $env): int; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/QueueException.php
src/QueueException.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * A marker interface for all exceptions throw by this library. * * @since 2.0 */ interface QueueException { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/MessageNames.php
src/MessageNames.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; trait MessageNames { protected static function nameOf(object $message) : string { if ($message instanceof Message) { return $message->getName(); } return get_class($message); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/DefaultConsumer.php
src/DefaultConsumer.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use GuzzleHttp\Promises\PromiseInterface; use Psr\Log\LoggerInterface; /** * A default implementation of `Consumer`. Runs jobs via a MessageHandler. * * @since 2.0 * @api */ class DefaultConsumer extends AbstractConsumer { /** * @var Driver */ private $driver; /** * @var MessageHandler */ private $handler; /** * @var RetrySpec */ private $retries; /** * @var array */ private $handlerOptions = []; /** * The promise that's currently being handled by a consumer. * * @var PromiseInterface|null */ private $currentPromise = null; public function __construct( Driver $driver, MessageHandler $handler, ?RetrySpec $retries=null, ?LoggerInterface $logger=null ) { parent::__construct($logger); $this->driver = $driver; $this->handler = $handler; $this->retries = $retries ?: new Retry\LimitedSpec(); } /** * {@inheritdoc} */ public function once(string $queueName, ?MessageLifecycle $lifecycle=null) : ?bool { $envelope = $this->driver->dequeue($queueName); if (!$envelope) { return null; } $lifecycle = $lifecycle ?? new Lifecycle\NullLifecycle(); $message = $envelope->unwrap(); $lifecycle->starting($message, $this); list($succeeded, $willRetry) = $this->doOnce($queueName, $envelope); $lifecycle->completed($message, $this); if ($succeeded) { $lifecycle->succeeded($message, $this); } elseif ($willRetry) { $lifecycle->retrying($message, $this); } else { $lifecycle->failed($message, $this); } return $succeeded; } /** * {@inheritdoc} */ public function stop(?int $code=null) : void { if ($this->currentPromise) { $this->currentPromise->cancel(); } parent::stop($code); } /** * Do the actual work for processing a single message. * * @param $queueName The queue to which the message belongs * @param $envelope The envelope containing the message to process * @return An array if [$messageSucceeded, $willRetry] */ protected function doOnce(string $queueName, Envelope $envelope) : array { $result = false; $message = $envelope->unwrap(); $this->getLogger()->debug('Handling message {msg}', ['msg' => self::nameOf($message)]); try { $result = $this->handleMessage($message); } catch (Exception\MustStop $e) { $this->driver->ack($queueName, $envelope); throw $e; } catch (Exception\ShouldReleaseMessage $e) { $this->driver->release($queueName, $envelope); $this->getLogger()->debug('Releasing message {msg} due to {cls} exception: {err}', [ 'msg' => self::nameOf($message), 'cls' => get_class($e), 'err' => $e->getMessage(), 'exception' => $e, ]); return [$result, true]; } catch (\Exception $e) { // any other exception is simply logged. We and marked as failed // below. We only log here because we can't make guarantees about // the implementation of the handler and whether or not it actually // throws exceptions on failure (see PcntlForkingHandler). $this->getLogger()->critical('Unexpected {cls} exception handling {name} message: {msg}', [ 'cls' => get_class($e), 'name' => self::nameOf($message), 'msg' => $e->getMessage(), 'exception' => $e, ]); $result = false; } $this->getLogger()->debug('Handled message {msg}', ['msg' => self::nameOf($message)]); if ($result) { $willRetry = false; $this->driver->ack($queueName, $envelope); $this->getLogger()->debug('Acknowledged message {msg}', ['msg' => self::nameOf($message)]); } else { $willRetry = $this->failed($queueName, $envelope); $this->getLogger()->debug('Failed message {msg}', ['msg' => self::nameOf($message)]); } return [$result, $willRetry]; } /** * Fail the message. This will retry it if possible. * * @param $queueName the queue from which the message originated * @param $env The envelope containing the message * @return bool True if the message will be retried. */ protected function failed(string $queueName, Envelope $env) : bool { $retry = $this->retries->canRetry($env); if ($retry) { $delay = $this->retries->retryDelay($env); $this->getDriver()->retry($queueName, $env->retry($delay)); } else { $this->getDriver()->fail($queueName, $env); } return $retry; } protected function handleMessage(object $message) { try { $this->currentPromise = $this->getHandler()->handle( $message, $this->getHandlerOptions() ); return $this->currentPromise->wait(); } finally { $this->currentPromise = null; } } protected function getHandler() { return $this->handler; } protected function getDriver() { return $this->driver; } /** * Replace all the handler options. * * @param $newOptions The options to set * @return void */ protected function setHandlerOptions(array $newOptions) { $this->handlerOptions = $newOptions; } protected function getHandlerOptions() { return $this->handlerOptions; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/MessageLifecycle.php
src/MessageLifecycle.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * Provides a way to hook into the life of a message as it moves through * a consumer. * * This provides a way to extend the lifecycle of a message without tying you * to a specific thing (like an event library, etc). * * @since 4.0 */ interface MessageLifecycle { /** * Called when a message starts its processing in the consumer. * * @param $message The message that's starting * @param $consumer The consumer that's doing the work * @return void */ public function starting(object $message, Consumer $consumer) : void; /** * Called when a message completes regardless of whether it was successful. * * @param $message The message that completed * @param $consumer The consumer that did the work * @return void */ public function completed(object $message, Consumer $consumer) : void; /** * Called when a message failed and is retrying. * * No details about the error are provided because the consumer may not even * have them. * * @param $message The message that errored and is retrying * @param $consumer The consumer that did the work * @return void */ public function retrying(object $message, Consumer $consumer) : void; /** * Called when a message failed. * * No details about the error are provided here because consumers, specifically * the default consumer implementation may not have those details. For instance, * if a handler forks the child process will not pass any exception info up * to the parent. It's up to your handlers to deal with logging and accountability. * * @param $message The message that errored * @param $consumer The consumer that did the work * @return void */ public function failed(object $message, Consumer $consumer) : void; /** * Called when message processing was successful. * * @param $message The message that errored * @param $consumer The consumer that did the work * @return void */ public function succeeded(object $message, Consumer $consumer) : void; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Envelope.php
src/Envelope.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * Envelopes wrap up messages and retry counts. End users never see Envelope * implementations. * * Envelope implementations are closely tied to their drivers. * * @since 2.0 */ interface Envelope { const NO_DELAY = 0; /** * Get the number of times the message has been attempted. * * @return int */ public function attempts() : int; /** * Get the number of seconds which the message should be delayed. * * @return int */ public function delay() : int; /** * Get the wrapped message. * * @return object the actual message */ public function unwrap() : object; /** * Returns a new envelop with all the same attributes but an incremented * attempt count. * * @param $delay The amount number of seconds the message should be delayed before retrying * @return Envelop */ public function retry(int $delay=0) : Envelope; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Router.php
src/Router.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * Routers map messages to Queue names. * * @since 2.0 * @api */ interface Router { /** * Look up the queue for a message. * * @param $message The message to look up. * @return string|null The queue name if found or `null` otherwise. */ public function queueFor(object $message) : ?string; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/MessageHandler.php
src/MessageHandler.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use GuzzleHttp\Promise\PromiseInterface; /** * Something that can process a message. * * @since 3.0 */ interface MessageHandler { /** * Handle a message. What that means depends on the implementation, but it * probably means interact with the user's system based on the given message. * * @param $message That message to process. * @param array $options A freeform set of options that may be passed from the * consumer. * @return a promise object that resolves to `true` if the the handler was successful. * or false if the handler failed. Since handlers may process messages * outside the current thread, we're limited to a boolean here. */ public function handle(object $message, array $options=[]) : PromiseInterface; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Producer.php
src/Producer.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * Producers push messages into the queue. * * @since 2.0 * @api */ interface Producer { /** * Send a new message into the queue. * * @param $messageOrEnvelope The message to send * @throws Exception\DriverError if something goes wrong with the * queue backend. * @throws Exception\QueueNotFound if the router fails to find a queue. * @return void */ public function send(object $messageOrEnvelope) : void; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/DefaultEnvelope.php
src/DefaultEnvelope.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use PMG\Queue\Exception\InvalidArgumentException as InvalidArg; /** * Default implementation of the `Envelop` with no extras. * * @since 2.0 */ class DefaultEnvelope implements Envelope { /** * @var object */ protected $message; /** * @var int */ protected $attempts; /** * @var int */ private $delay; public function __construct(object $message, int $attempts=0, int $delay=Envelope::NO_DELAY) { InvalidArg::assert($attempts >= 0, '$attempts must be >= 0'); $this->message = $message; $this->attempts = $attempts; $this->setDelay($delay); } /** * {@inheritdoc} */ public function attempts() : int { return $this->attempts; } /** * {@inheritdoc} */ public function delay() : int { return $this->delay; } /** * {@inheritdoc} */ public function unwrap() : object { return $this->message; } /** * {@inheritdoc} */ public function retry(int $delay=0) : Envelope { $new = clone $this; $new->attempts++; $new->setDelay($delay); return $new; } protected function setDelay(int $delay) : void { InvalidArg::assert($delay >= 0, '$delay must be >= 0'); $this->delay = $delay; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Message.php
src/Message.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * A marker interface for messages. * * @since 2.0 */ interface Message { /** * Get the name of the message. This is used for routing things to queues. * * @return string */ public function getName() : string; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/SimpleMessage.php
src/SimpleMessage.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * A message that returns the name given to it. * * @since 2.0 */ final class SimpleMessage implements Message { private $name; private $payload; public function __construct(string $name, $payload=null) { $this->name = $name; $this->payload = $payload; } /** * {@inheritdoc} */ public function getName() : string { return $this->name; } /** * {@inheritdoc} */ public function getPayload() { return $this->payload; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Driver.php
src/Driver.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * Defines a driver backend for persistant queues. * * Drivers make no promises or guarantees about ordering of messages. Some drivers * will be LIFO others will be FIFO and some have no ordering. Don't build systems * that depend on those charactertistics. * * Additionally, drivers know nothing about configuring a backend. If special steps * are required to create a queue, those should be done elsewhere. * * @since 2.0 * @api */ interface Driver { /** * Add a new message to the queue. * * @param string $queueName The name of the queue to put the message in. * @param $message The message to add. * @throws Exception\DriverError when something goes wrong * @return Envelope An envelop representing the message in the queue. */ public function enqueue(string $queueName, object $message) : Envelope; /** * Pull a message out of the queue. * * @param string $queueName The queue from which to pull messages. * @throws Exception\DriverError when something goes wrong * @return Envelope|null An envelope if a message is found, null otherwise */ public function dequeue(string $queueName) : ?Envelope; /** * Acknowledge a message as complete. * * @param string $queueName The queue from which the message came * @param $envelope The message envelop -- should be the same instance * returned by `dequeue` * @throws Exception\DriverError when something goes wrong * @return void */ public function ack(string $queueName, Envelope $envelope) : void; /** * Retry a job -- put it back in the queue for retrying. * * @param string $queueName The queue from whcih the message came * @param $envelope The message envelope -- should be the same instance * returned from `dequeue` * @throws Exception\DriverError when something goes wrong * @return Envelope The envelope that was retried. This can be the same * envelope passed in or a new one depending on the drivers needs. */ public function retry(string $queueName, Envelope $envelope) : Envelope; /** * Fail a job -- this called when no more retries can be attempted. * * @param string $queueName The queue from whcih the message came * @param $envelope The message envelope -- should be the same instance * returned from `dequeue` * @throws Exception\DriverError when something goes wrong * @return void */ public function fail(string $queueName, Envelope $envelope) : void; /** * Release a message back to a ready state. This is used by the consumer * when it skips the retry system. This may happen if the consumer receives * a signal and has to exit early. * * @param $queueName The queue from which the message came * @param $envelope The message to release, should be the same instance * returned from `dequeue` * @throws Exception\DriverError if something goes wrong * @return void */ public function release(string $queueName, Envelope $envelope) : void; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Otel/PmgQueueInstrumentation.php
src/Otel/PmgQueueInstrumentation.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Otel; use function OpenTelemetry\Instrumentation\hook; use OpenTelemetry\API\Instrumentation\CachedInstrumentation; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\SpanBuilderInterface; use OpenTelemetry\API\Trace\SpanKind; use OpenTelemetry\API\Trace\StatusCode; use OpenTelemetry\Context\Context; use OpenTelemetry\SemConv\TraceAttributes; use PMG\Queue\Consumer; use PMG\Queue\Driver; use PMG\Queue\Envelope; final class PmgQueueInstrumentation { public const NAME = 'pmg-queue'; public const INSTRUMENTATION_NAME = 'com.pmg.opentelemetry.'.self::NAME; // these two are in semconv, but have not yet maded it to the PHP SDK // type is generic and defined in semconv where name is system specific public const OPERATION_TYPE = 'messaging.operation.type'; public const OPERATION_NAME = 'messaging.operation.name'; public static bool $registered = false; public static function register(): bool { if (self::$registered) { return false; } if (!extension_loaded('opentelemetry')) { return false; } self::$registered = true; $instrumentation = new CachedInstrumentation(self::INSTRUMENTATION_NAME); hook( Consumer::class, 'once', pre: static function ( Consumer $consumer, array $params, string $class, string $function, ?string $filename, ?int $lineno, ) use ($instrumentation): array { $queueName = $params[0]; assert(is_string($queueName)); $builder = $instrumentation ->tracer() ->spanBuilder($queueName.' receive') ->setSpanKind(SpanKind::KIND_CONSUMER) ->setAttribute(TraceAttributes::CODE_FUNCTION, $function) ->setAttribute(TraceAttributes::CODE_NAMESPACE, $class) ->setAttribute(TraceAttributes::CODE_FILEPATH, $filename) ->setAttribute(TraceAttributes::CODE_LINENO, $lineno) ->setAttribute(TraceAttributes::MESSAGING_DESTINATION_NAME, $queueName) ->setAttribute(self::OPERATION_TYPE, 'receive') // generic ->setAttribute(self::OPERATION_NAME, 'once') // system specific ; $parent = Context::getCurrent(); $span = $builder ->setParent($parent) ->startSpan(); $context = $span->storeInContext($parent); Context::storage()->attach($context); return $params; }, post: static function ( Consumer $consumer, array $params, mixed $result, ?\Throwable $exception ): void { $scope = Context::storage()->scope(); if (null === $scope) { return; } $queueName = $params[0]; assert(is_string($queueName)); $scope->detach(); $span = Span::fromContext($scope->context()); if (null !== $exception) { $span->recordException($exception, [ TraceAttributes::EXCEPTION_ESCAPED => true, ]); $span->setStatus(StatusCode::STATUS_ERROR, $exception->getMessage()); } elseif ($result === false) { $span->setStatus(StatusCode::STATUS_ERROR, 'Message was not handled successfully'); } elseif ($result === null) { $span->updateName($queueName.' empty-receive'); } $span->end(); } ); hook( Driver::class, 'enqueue', pre: static function ( Driver $bus, array $params, string $class, string $function, ?string $filename, ?int $lineno, ) use ($instrumentation): array { $queueName = $params[0]; assert(is_string($queueName)); $message = $params[1]; assert(is_object($message)); $builder = $instrumentation ->tracer() ->spanBuilder($queueName.' publish') ->setSpanKind(SpanKind::KIND_PRODUCER) ->setAttribute(TraceAttributes::CODE_FUNCTION, $function) ->setAttribute(TraceAttributes::CODE_NAMESPACE, $class) ->setAttribute(TraceAttributes::CODE_FILEPATH, $filename) ->setAttribute(TraceAttributes::CODE_LINENO, $lineno) ->setAttribute(TraceAttributes::MESSAGING_DESTINATION_NAME, $queueName) ->setAttribute(self::OPERATION_TYPE, 'publish') ->setAttribute(self::OPERATION_NAME, 'enqueue') ; $parent = Context::getCurrent(); $span = $builder ->setParent($parent) ->startSpan(); $context = $span->storeInContext($parent); Context::storage()->attach($context); return $params; }, post: static function ( Driver $driver, array $params, ?Envelope $envelope, ?\Throwable $exception ): void { $scope = Context::storage()->scope(); if (null === $scope) { return; } $scope->detach(); $span = Span::fromContext($scope->context()); if (null !== $exception) { $span->recordException($exception, [ TraceAttributes::EXCEPTION_ESCAPED => true, ]); $span->setStatus(StatusCode::STATUS_ERROR, $exception->getMessage()); } $span->end(); } ); return self::$registered; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Otel/_register.php
src/Otel/_register.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ use PMG\Queue\Otel\PmgQueueInstrumentation; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\Context\Context; use OpenTelemetry\SemConv\TraceAttributes; use OpenTelemetry\SDK\Sdk; // look for deps and if we have them all we'll load the instrumentation. if ( !extension_loaded('opentelemetry') || !class_exists(Span::class) || !class_exists(Context::class) || !interface_exists(TraceAttributes::class) ) { return; } // allow disabling instrumentation via the SDK's supported environment variables if (class_exists(Sdk::class) && Sdk::isInstrumentationDisabled(PmgQueueInstrumentation::NAME)) { return; } PmgQueueInstrumentation::register();
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Driver/AbstractPersistanceDriver.php
src/Driver/AbstractPersistanceDriver.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Driver; use PMG\Queue\Envelope; use PMG\Queue\DefaultEnvelope; use PMG\Queue\Serializer\Serializer; use PMG\Queue\Serializer\NativeSerializer; /** * Base class for drivers that deal with persistent backends. This provides * some utilities for serialization. * * @since 2.0 */ abstract class AbstractPersistanceDriver implements \PMG\Queue\Driver { /** * @var Serializer */ private $serializer; public function __construct(Serializer $serializer) { $this->serializer = $serializer; } /** * Returns a set of allowed classes for the serializer. This may not be used: * it depends on what serializer the end user decided on. The idea here * is that the envelope class names remain opaque to the user (because they * should not care about them: envelopes are internal to drivers and the queue * only). * * Example (with `NativeSerializer` and `PheanstalkDriver`): * * $serializer = new NativeSerializer(array_merge([ * SomeMessage::class, * ], PheanstalkDriver::allowedClasses())); * * @return string[] */ public static function allowedClasses() { return [ DefaultEnvelope::class, ]; } protected function serialize(Envelope $env) { return $this->ensureSerializer()->serialize($env); } protected function unserialize($data) { return $this->ensureSerializer()->unserialize($data); } protected function ensureSerializer() { if (!$this->serializer) { throw new \RuntimeException(sprintf( '%s does not have a serializer set, did you forget to call parent::__construct($serializer) in its constructor?', get_class($this) )); } return $this->serializer; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Driver/MemoryDriver.php
src/Driver/MemoryDriver.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Driver; use SplQueue; use PMG\Queue\Envelope; use PMG\Queue\Message; use PMG\Queue\DefaultEnvelope; /** * A driver that keeps jobs in memory. * * @since 2.0 */ final class MemoryDriver implements \PMG\Queue\Driver { /** * @var SplQueue[] */ private $queues = []; /** * {@inheritdoc} */ public function enqueue(string $queueName, object $message) : Envelope { $envelope = $message instanceof Envelope ? $message : new DefaultEnvelope($message); $this->enqueueEnvelope($queueName, $envelope); return $envelope; } /** * {@inheritdoc} */ public function dequeue(string $queueName) : ?Envelope { try{ return $this->getQueue($queueName)->dequeue(); } catch (\RuntimeException $e) { return null; } } /** * {@inheritdoc} */ public function ack(string $queueName, Envelope $envelope) : void { // noop } /** * {@inheritdoc} */ public function retry(string $queueName, Envelope $envelope) : Envelope { $this->enqueueEnvelope($queueName, $envelope); return $envelope; } /** * {@inheritdoc} */ public function fail(string $queueName, Envelope $envelope) : void { // noop } /** * {@inheritdoc} */ public function release(string $queueName, Envelope $envelope) : void { $this->enqueueEnvelope($queueName, $envelope); } private function enqueueEnvelope(string $queueName, Envelope $envelope) : void { $this->getQueue($queueName)->enqueue($envelope); } private function getQueue(string $queueName) : SplQueue { if (!isset($this->queues[$queueName])) { $this->queues[$queueName] = new SplQueue(); } return $this->queues[$queueName]; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Signer/HmacSha256.php
src/Signer/HmacSha256.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Signer; use PMG\Queue\Exception\InvalidArgumentException; /** * Uses hash_hmac and sha256 to sign/validate messages. * * @since 4.0 */ final class HmacSha256 implements Signer { const ALGO = 'sha256'; /** * @var string */ private $key; /** * Constructor. * * @param $key The key with which messages will be signed. */ public function __construct(string $key) { InvalidArgumentException::assertNotEmpty($key, '$key cannot be empty!'); $this->key = $key; } /** * {@inheritdoc} */ public function sign(string $message) : string { return hash_hmac(self::ALGO, $message, $this->key, false); } /** * {@inheritdoc} */ public function verify(string $mac, string $message) : bool { return hash_equals($this->sign($message), $mac); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Signer/SodiumCryptoAuth.php
src/Signer/SodiumCryptoAuth.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Signer; use PMG\Queue\Exception\InvalidArgumentException; final class SodiumCryptoAuth implements Signer { /** * @var string */ private $key; /** * Constructor. This tries to sign a dummy message immediately to validate * that the key okay for libsodium. * * @param $key The key with which messages will be signed. */ public function __construct(string $key) { // @codeCoverageIgnoreStart if (!function_exists('sodium_crypto_auth')) { throw new \RuntimeException(sprintf( 'sodium_* functions are not available, cannot use %s', __CLASS__ )); } // @codeCoverageIgnoreEnd InvalidArgumentException::assertNotEmpty($key, '$key cannot be empty!'); $this->key = $key; try { $this->sign('test message, please ignore'); } catch (\Throwable $e) { throw new InvalidArgumentException($e->getMessage(), 0, $e); } } /** * {@inheritdoc} */ public function sign(string $message) : string { return sodium_crypto_auth($message, $this->key); } /** * {@inheritdoc} */ public function verify(string $mac, string $message) : bool { return sodium_crypto_auth_verify($mac, $message, $this->key); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Signer/Signer.php
src/Signer/Signer.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Signer; /** * Sign or verify messages. This is used in conjuction with `NativeSerializer` * for the most part. * * @since 4.0 */ interface Signer { /** * Sign a message. * * @param $message The message to signe * @return a MAC that can be be associated with the message however the * caller sees fit. */ public function sign(string $message) : string; /** * Verify the message signature. * * @param $signed The signed message * @return True if the message signature is valid. */ public function verify(string $mac, string $message) : bool; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Lifecycle/NullLifecycle.php
src/Lifecycle/NullLifecycle.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Lifecycle; use PMG\Queue\Consumer; use PMG\Queue\MessageLifecycle; /** * A `MessageLifecycle` implementation that does nothing. * * This is also useful to extend in your own implementation if you only care * about certain events. * * @since 4.0 */ class NullLifecycle implements MessageLifecycle { /** * {@inheritdoc} */ public function starting(object $message, Consumer $consumer) : void { // noop } /** * {@inheritdoc} */ public function completed(object $message, Consumer $consumer) : void { // noop } /** * {@inheritdoc} */ public function retrying(object $message, Consumer $consumer) : void { // noop } /** * {@inheritdoc} */ public function failed(object $message, Consumer $consumer) : void { // noop } /** * {@inheritdoc} */ public function succeeded(object $message, Consumer $consumer) : void { // noop } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Lifecycle/DelegatingLifecycle.php
src/Lifecycle/DelegatingLifecycle.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Lifecycle; use PMG\Queue\Consumer; use PMG\Queue\MessageLifecycle; /** * A `MessageLifecycle` implementation that delegates to other lifecycles. * * @since 4.2 */ final class DelegatingLifecycle implements MessageLifecycle, \Countable { /** * @var MessageLifecycle[] */ private $lifecycles; public function __construct(MessageLifecycle ...$lifecycles) { $this->lifecycles = $lifecycles; } public static function fromIterable(iterable $lifecycles) : self { return new self(...$lifecycles); } /** * {@inheritdoc} */ public function starting(object $message, Consumer $consumer) : void { $this->apply(function (MessageLifecycle $ml) use ($message, $consumer) { $ml->starting($message, $consumer); }); } /** * {@inheritdoc} */ public function completed(object $message, Consumer $consumer) : void { $this->apply(function (MessageLifecycle $ml) use ($message, $consumer) { $ml->completed($message, $consumer); }); } /** * {@inheritdoc} */ public function retrying(object $message, Consumer $consumer) : void { $this->apply(function (MessageLifecycle $ml) use ($message, $consumer) { $ml->retrying($message, $consumer); }); } /** * {@inheritdoc} */ public function failed(object $message, Consumer $consumer) : void { $this->apply(function (MessageLifecycle $ml) use ($message, $consumer) { $ml->failed($message, $consumer); }); } /** * {@inheritdoc} */ public function succeeded(object $message, Consumer $consumer) : void { $this->apply(function (MessageLifecycle $ml) use ($message, $consumer) { $ml->succeeded($message, $consumer); }); } /** * {@inheritdoc} */ public function count() : int { return count($this->lifecycles); } private function apply(callable $fn) : void { foreach ($this->lifecycles as $lifecycle) { $fn($lifecycle); } } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Lifecycle/MappingLifecycle.php
src/Lifecycle/MappingLifecycle.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Lifecycle; use PMG\Queue\Consumer; use PMG\Queue\MessageLifecycle; use PMG\Queue\MessageNames; use PMG\Queue\Exception\InvalidArgumentException; /** * A `MessageLifecycle` implementation that applies other lifecycles based on * a apping and the incoming message name. * * @since 4.2 */ final class MappingLifecycle implements MessageLifecycle { use MessageNames; /** * A mapping of message names to lifecycles. [$messageName => $lifecycle] * * @var array|ArrayAccess */ private $mapping; /** * @var MessageLifecycle */ private $fallback; /** * @param array|ArrayAccess $mapping the message mapping * @param $fallback The message lifecycle to which unmatches messages will be applied * @throws InvalidArgumentException if $mapping is a bad type */ public function __construct($mapping, ?MessageLifecycle $fallback=null) { if (!is_array($mapping) && !$mapping instanceof \ArrayAccess) { throw new InvalidArgumentException(sprintf( '$mapping must be an array or ArrayAccess implementation, got "%s"', is_object($mapping) ? get_class($mapping) : gettype($mapping) )); } $this->mapping = $mapping; $this->fallback = $fallback ?? new NullLifecycle(); } /** * {@inheritdoc} */ public function starting(object $message, Consumer $consumer) : void { $this->lifecycleFor($message)->starting($message, $consumer); } /** * {@inheritdoc} */ public function completed(object $message, Consumer $consumer) : void { $this->lifecycleFor($message)->completed($message, $consumer); } /** * {@inheritdoc} */ public function retrying(object $message, Consumer $consumer) : void { $this->lifecycleFor($message)->retrying($message, $consumer); } /** * {@inheritdoc} */ public function failed(object $message, Consumer $consumer) : void { $this->lifecycleFor($message)->failed($message, $consumer); } /** * {@inheritdoc} */ public function succeeded(object $message, Consumer $consumer) : void { $this->lifecycleFor($message)->succeeded($message, $consumer); } /** * Check whether or not the message has a lifecycle. * * @param $messageName the message name to check * @return true if a message lifecycle exists for the message */ public function has(string $messageName) : bool { return isset($this->mapping[$messageName]); } private function lifecycleFor(object $message) : MessageLifecycle { $name = self::nameOf($message); return $this->has($name) ? $this->mapping[$name] : $this->fallback; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Serializer/NativeSerializer.php
src/Serializer/NativeSerializer.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Serializer; use PMG\Queue\Envelope; use PMG\Queue\Exception\InvalidSignature; use PMG\Queue\Exception\MissingSignature; use PMG\Queue\Exception\NotAnEnvelope; use PMG\Queue\Exception\SerializationError; use PMG\Queue\Signer\Signer; use PMG\Queue\Signer\HmacSha256; /** * A serializer implemtnation that uses PHP's native serialize and unserialize. * * @since 2.0 */ final class NativeSerializer implements Serializer { /** * Only applicable to PHP 7+. This is a set of allowed classes passed * to the second argument of `unserialize`. * * @var string[] */ private $allowedClasses; /** * @var Signer */ private $signer; public function __construct(Signer $signer, ?array $allowedClasses=null) { $this->signer = $signer; $this->allowedClasses = $allowedClasses; } public static function fromSigningKey(string $key, ?array $allowedClasses=null) { return new self(new HmacSha256($key), $allowedClasses); } /** * {@inheritdoc} */ public function serialize(Envelope $env) { $str = base64_encode(serialize($env)); return sprintf('%s|%s', $this->signer->sign($str), $str); } /** * {@inheritdoc} */ public function unserialize($message) { $env = $this->verifySignature($message); $m = $this->doUnserialize(base64_decode($env)); if (!$m instanceof Envelope) { throw new NotAnEnvelope(sprintf( 'Expected an instance of "%s" got "%s"', Envelope::class, is_object($m) ? get_class($m) : gettype($m) )); } return $m; } private function verifySignature(string $message) : string { if (substr_count($message, '|') !== 1) { throw new MissingSignature('Data to unserialize does not have a signature'); } list($sig, $env) = explode('|', $message, 2); if (!$this->signer->verify($sig, $env)) { throw new InvalidSignature('Invalid Message Signature'); } return $env; } /** * Small wrapper around `unserialize` so we can pass in `$allowedClasses` * if the PHP verison 7+ * * @param string $str the string to unserialize * @return object|false */ private function doUnserialize($str) { $m = $this->allowedClasses ? @unserialize($str, [ 'allowed_classes' => $this->allowedClasses, ]) : @unserialize($str); if (false === $m) { $err = error_get_last(); throw new SerializationError(sprintf( 'Error unserializing message: %s', $err && isset($err['message']) ? $err['message'] : 'unknown error' )); } return $m; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Serializer/Serializer.php
src/Serializer/Serializer.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Serializer; use PMG\Queue\Envelope; use PMG\Queue\Exception\SerializationError; /** * Serializer's turn messages into strings that can be sent into Queues and * deserialize stringy messages from queues back into objects. * * @since 2.0 */ interface Serializer { /** * Serialize a message into a string for sending into a queue. * * @param $env The message envelope to serialize * @throws SerializationError if the message cannot be serialized * @return string A base 64 encoded string of the serialized envelope */ public function serialize(Envelope $env); /** * Deserialize a string form the queue into a message object. * * @param string $message a base 64 encoded string of the serialed envelope * @throws SerializationError if something goes wrong during unserialization. * @return Envelope */ public function unserialize($message); }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Router/SimpleRouter.php
src/Router/SimpleRouter.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Router; use PMG\Queue\Router; /** * A router that always returns the same queue name for every message. * * @since 2.0 */ final class SimpleRouter implements Router { /** * @var string */ private $queueName; public function __construct($queueName) { $this->queueName = $queueName; } /** * {@inheritdoc} */ public function queueFor(object $message) : ?string { return $this->queueName; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Router/FallbackRouter.php
src/Router/FallbackRouter.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Router; use PMG\Queue\Router; /** * A decorator that wraps another router and returns a fallback queue * name if one isn't found. * * @since 2.0 */ final class FallbackRouter implements \PMG\Queue\Router { /** * @var Router */ private $wrapped; /** * @var string */ private $fallbackQueue; public function __construct(Router $wrapped, $fallbackQueue) { $this->wrapped = $wrapped; $this->fallbackQueue = $fallbackQueue; } /** * {@inheritdoc} */ public function queueFor(object $message) : ?string { return $this->wrapped->queueFor($message) ?: $this->fallbackQueue; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Router/MappingRouter.php
src/Router/MappingRouter.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Router; use PMG\Queue\MessageNames; use PMG\Queue\Router; use PMG\Queue\Exception\InvalidArgumentException; /** * A router implementation that maps message names to queue names via * an array or `ArrayAccess` implementation. * * @since 2.0 */ final class MappingRouter implements Router { use MessageNames; /** * The map of class name => queue name values. * * @var array */ private $map; public function __construct($map) { if (!is_array($map) && !$map instanceof \ArrayAccess) { throw new InvalidArgumentException(sprintf( '%s expects $map must be an array or implementation of ArrayAccess, got "%s"', __METHOD__, is_object($map) ? get_class($map) : gettype($map) )); } $this->map = $map; } /** * {@inheritdoc} */ public function queueFor(object $message) : ?string { $name = self::nameOf($message); return isset($this->map[$name]) ? $this->map[$name] : null; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Retry/LimitedSpec.php
src/Retry/LimitedSpec.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Retry; use PMG\Queue\Envelope; use PMG\Queue\RetrySpec; use PMG\Queue\Exception\InvalidArgumentException; /** * Retry a message a limited number of times. * * @since 2.0 */ final class LimitedSpec implements RetrySpec { const DEFAULT_ATTEMPTS = 5; private $maxAttempts; private $retryDelay; public function __construct(?int $maxAttempts=null, int $retryDelay=0) { if (null !== $maxAttempts && $maxAttempts < 1) { throw new InvalidArgumentException(sprintf( '$maxAttempts must be a positive integer, got "%s"', $maxAttempts )); } if ($retryDelay < 0) { throw new InvalidArgumentException(sprintf( '$retryDelay must be a positive integer, got "%s"', $retryDelay )); } $this->maxAttempts = $maxAttempts ?: self::DEFAULT_ATTEMPTS; $this->retryDelay = $retryDelay; } /** * {@inheritdoc} */ public function canRetry(Envelope $env) : bool { return $env->attempts() < $this->maxAttempts; } /** * {@inheritdoc} */ public function retryDelay(Envelope $env): int { return $this->retryDelay; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Retry/NeverSpec.php
src/Retry/NeverSpec.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Retry; use PMG\Queue\Envelope; use PMG\Queue\RetrySpec; /** * Never retry a message. * * @since 2.0 */ final class NeverSpec implements RetrySpec { /** * {@inheritdoc} */ public function canRetry(Envelope $env) : bool { return false; } public function retryDelay(Envelope $env): int { return 0; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Handler/PcntlForkingHandler.php
src/Handler/PcntlForkingHandler.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Handler; use GuzzleHttp\Promise\Promise; use GuzzleHttp\Promise\PromiseInterface; use PMG\Queue\Message; use PMG\Queue\MessageHandler; use PMG\Queue\Exception\CouldNotFork; use PMG\Queue\Exception\ForkedProcessCancelled; use PMG\Queue\Exception\ForkedProcessFailed; use PMG\Queue\Handler\Pcntl\Pcntl; /** * A message handler decorator that forks a child process to handle the message. * * Use with caution, and be aware that forking will mess with things like open * connections and resources (sockets, files, etc). Best bet is to wrap this * around a `CallableHandler` and bootstrap your entire application for each * message handled. Or implement your own `MessageHandler` that bootstraps the * entire application each time. * * @since 3.0 */ final class PcntlForkingHandler implements MessageHandler { private MessageHandler $wrapped; private Pcntl $pcntl; public function __construct(MessageHandler $wrapped, ?Pcntl $pcntl=null) { $this->wrapped = $wrapped; $this->pcntl = $pcntl ?: new Pcntl(); } /** * {@inheritdoc} * This does not really deal with or log exceptions. It just swallows them * and makes sure that the child process exits with an error (1). Should * you want to do any specialized logging, that should happen in the wrapped * `MessageHandler`. Just be sure to return `false` (the job failed) so it * can be retried. */ public function handle(object $message, array $options=[]) : PromiseInterface { // this is outside the promise so both the cancel and wait // callbacks have access to the child's PID $child = $this->fork(); if (0 === $child) { try { $result = $this->wrapped->handle($message, $options)->wait(); } finally { $this->pcntl->quit(isset($result) && $result); } } $promise = new Promise(function () use (&$promise, $child) { $result = $this->pcntl->wait($child); // this happens when the promise is cancelled. We don't want to // to try and change the promise to resolved if that happens. if ($promise->getState() !== PromiseInterface::PENDING) { return; } if ($result->successful()) { $promise->resolve(true); } else { $promise->reject(ForkedProcessFailed::withExitCode($result->getExitCode())); } }, function () use (&$promise, $child) { $this->pcntl->signal($child, SIGTERM); $promise->reject(new ForkedProcessCancelled()); }); return $promise; } private function fork() { $child = $this->pcntl->fork(); if (-1 === $child) { throw CouldNotFork::fromLastError(); } return $child; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Handler/CallableHandler.php
src/Handler/CallableHandler.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Handler; use GuzzleHttp\Promise\Promise; use GuzzleHttp\Promise\PromiseInterface; use PMG\Queue\Message; use PMG\Queue\MessageHandler; /** * A message handler that invokes a callable with the message. The callback should * return a boolean value indicating whether the message succeeded. * * @since 3.0 */ final class CallableHandler implements MessageHandler { /** * The message callback. * * @var callable */ private $callback; public function __construct(callable $callback) { $this->callback = $callback; } /** * {@inheritdoc} * This *always* resolves with the values from the callback. If the callback * throws something that will result in a rejected promise. */ public function handle(object $message, array $options=[]) : PromiseInterface { $promise = new Promise(function () use (&$promise, $message, $options) { $promise->resolve(call_user_func( $this->callback, $message, $options )); }); return $promise; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false