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
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/KeepAliveTest.php
test/Header/KeepAliveTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\KeepAlive; class KeepAliveTest extends TestCase { public function testKeepAliveFromStringCreatesValidKeepAliveHeader() { $keepAliveHeader = KeepAlive::fromString('Keep-Alive: xxx'); $this->assertInstanceOf(HeaderInterface::class, $keepAliveHeader); $this->assertInstanceOf(KeepAlive::class, $keepAliveHeader); } public function testKeepAliveGetFieldNameReturnsHeaderName() { $keepAliveHeader = new KeepAlive(); $this->assertEquals('Keep-Alive', $keepAliveHeader->getFieldName()); } public function testKeepAliveGetFieldValueReturnsProperValue() { $this->markTestIncomplete('KeepAlive needs to be completed'); $keepAliveHeader = new KeepAlive(); $this->assertEquals('xxx', $keepAliveHeader->getFieldValue()); } public function testKeepAliveToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('KeepAlive needs to be completed'); $keepAliveHeader = new KeepAlive(); // @todo set some values, then test output $this->assertEmpty('Keep-Alive: xxx', $keepAliveHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); KeepAlive::fromString("Keep-Alive: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new KeepAlive("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/HeaderValueTest.php
test/Header/HeaderValueTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderValue; class HeaderValueTest extends TestCase { /** * Data for filter value */ public function getFilterValues() { return [ ["This is a\n test", 'This is a test'], ["This is a\r test", 'This is a test'], ["This is a\n\r test", 'This is a test'], ["This is a\r\n test", 'This is a test'], ["This is a \r\ntest", 'This is a test'], ["This is a \r\n\n test", 'This is a test'], ["This is a\n\n test", 'This is a test'], ["This is a\r\r test", 'This is a test'], ["This is a \r\r\n test", 'This is a test'], ["This is a \r\n\r\ntest", 'This is a test'], ["This is a \r\n\n\r\n test", 'This is a test'], ]; } /** * @group ZF2015-04 * * @dataProvider getFilterValues * * @param string $value * @param string $expected */ public function testFiltersValuesPerRfc7230($value, $expected) { $this->assertEquals($expected, HeaderValue::filter($value)); } public function validateValues() { return [ ["This is a\n test", 'assertFalse'], ["This is a\r test", 'assertFalse'], ["This is a\n\r test", 'assertFalse'], ["This is a\r\n test", 'assertFalse'], ["This is a \r\ntest", 'assertFalse'], ["This is a \r\n\n test", 'assertFalse'], ["This is a\n\n test", 'assertFalse'], ["This is a\r\r test", 'assertFalse'], ["This is a \r\r\n test", 'assertFalse'], ["This is a \r\n\r\ntest", 'assertFalse'], ["This is a \r\n\n\r\n test", 'assertFalse'], ]; } /** * @group ZF2015-04 * * @dataProvider validateValues * * @param string $value * @param string $assertion */ public function testValidatesValuesPerRfc7230($value, $assertion) { $this->{$assertion}(HeaderValue::isValid($value)); } public function assertValues() { return [ ["This is a\n test"], ["This is a\r test"], ["This is a\n\r test"], ["This is a \r\ntest"], ["This is a \r\n\n test"], ["This is a\n\n test"], ["This is a\r\r test"], ["This is a \r\r\n test"], ["This is a \r\n\r\ntest"], ["This is a \r\n\n\r\n test"], ]; } /** * @group ZF2015-04 * * @dataProvider assertValues * * @param string $value */ public function testAssertValidRaisesExceptionForInvalidValue($value) { $this->expectException(InvalidArgumentException::class); HeaderValue::assertValid($value); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/TrailerTest.php
test/Header/TrailerTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\Trailer; class TrailerTest extends TestCase { public function testTrailerFromStringCreatesValidTrailerHeader() { $trailerHeader = Trailer::fromString('Trailer: xxx'); $this->assertInstanceOf(HeaderInterface::class, $trailerHeader); $this->assertInstanceOf(Trailer::class, $trailerHeader); } public function testTrailerGetFieldNameReturnsHeaderName() { $trailerHeader = new Trailer(); $this->assertEquals('Trailer', $trailerHeader->getFieldName()); } public function testTrailerGetFieldValueReturnsProperValue() { $this->markTestIncomplete('Trailer needs to be completed'); $trailerHeader = new Trailer(); $this->assertEquals('xxx', $trailerHeader->getFieldValue()); } public function testTrailerToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('Trailer needs to be completed'); $trailerHeader = new Trailer(); // @todo set some values, then test output $this->assertEmpty('Trailer: xxx', $trailerHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); Trailer::fromString("Trailer: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new Trailer("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/RefererTest.php
test/Header/RefererTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\GenericHeader; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\Referer; use Zend\Http\Headers; use Zend\Uri\Http; use Zend\Uri\Uri; class RefererTest extends TestCase { public function testRefererFromStringCreatesValidLocationHeader() { $refererHeader = Referer::fromString('Referer: http://www.example.com/'); $this->assertInstanceOf(HeaderInterface::class, $refererHeader); $this->assertInstanceOf(Referer::class, $refererHeader); } public function testRefererGetFieldValueReturnsProperValue() { $refererHeader = new Referer(); $refererHeader->setUri('http://www.example.com/'); $this->assertEquals('http://www.example.com/', $refererHeader->getFieldValue()); $refererHeader->setUri('/path'); $this->assertEquals('/path', $refererHeader->getFieldValue()); } public function testRefererToStringReturnsHeaderFormattedString() { $refererHeader = new Referer(); $refererHeader->setUri('http://www.example.com/path?query'); $this->assertEquals('Referer: http://www.example.com/path?query', $refererHeader->toString()); } /** Implementation specific tests here */ public function testRefererCanSetAndAccessAbsoluteUri() { $refererHeader = Referer::fromString('Referer: http://www.example.com/path'); $uri = $refererHeader->uri(); $this->assertInstanceOf(Http::class, $uri); $this->assertTrue($uri->isAbsolute()); $this->assertEquals('http://www.example.com/path', $refererHeader->getUri()); } public function testRefererCanSetAndAccessRelativeUri() { $refererHeader = Referer::fromString('Referer: /path/to'); $uri = $refererHeader->uri(); $this->assertInstanceOf(Uri::class, $uri); $this->assertFalse($uri->isAbsolute()); $this->assertEquals('/path/to', $refererHeader->getUri()); } public function testRefererDoesNotHaveUriFragment() { $refererHeader = new Referer(); $refererHeader->setUri('http://www.example.com/path?query#fragment'); $this->assertEquals('Referer: http://www.example.com/path?query', $refererHeader->toString()); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testCRLFAttack() { $this->expectException(InvalidArgumentException::class); Referer::fromString("Referer: http://www.example.com/\r\n\r\nevilContent"); } public function testInvalidUriShouldWrapException() { $headerString = "Referer: unknown-scheme://test"; $headers = Headers::fromString($headerString); $result = $headers->get('Referer'); $this->assertInstanceOf(GenericHeader::class, $result); $this->assertNotInstanceOf(Referer::class, $result); $this->assertEquals('unknown-scheme://test', $result->getFieldValue()); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ServerTest.php
test/Header/ServerTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\Server; class ServerTest extends TestCase { public function testServerFromStringCreatesValidServerHeader() { $serverHeader = Server::fromString('Server: xxx'); $this->assertInstanceOf(HeaderInterface::class, $serverHeader); $this->assertInstanceOf(Server::class, $serverHeader); } public function testServerGetFieldNameReturnsHeaderName() { $serverHeader = new Server(); $this->assertEquals('Server', $serverHeader->getFieldName()); } public function testServerGetFieldValueReturnsProperValue() { $this->markTestIncomplete('Server needs to be completed'); $serverHeader = new Server(); $this->assertEquals('xxx', $serverHeader->getFieldValue()); } public function testServerToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('Server needs to be completed'); $serverHeader = new Server(); // @todo set some values, then test output $this->assertEmpty('Server: xxx', $serverHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); Server::fromString("Server: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new Server("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/TransferEncodingTest.php
test/Header/TransferEncodingTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\TransferEncoding; class TransferEncodingTest extends TestCase { public function testTransferEncodingFromStringCreatesValidTransferEncodingHeader() { $transferEncodingHeader = TransferEncoding::fromString('Transfer-Encoding: xxx'); $this->assertInstanceOf(HeaderInterface::class, $transferEncodingHeader); $this->assertInstanceOf(TransferEncoding::class, $transferEncodingHeader); } public function testTransferEncodingGetFieldNameReturnsHeaderName() { $transferEncodingHeader = new TransferEncoding(); $this->assertEquals('Transfer-Encoding', $transferEncodingHeader->getFieldName()); } public function testTransferEncodingGetFieldValueReturnsProperValue() { $this->markTestIncomplete('TransferEncoding needs to be completed'); $transferEncodingHeader = new TransferEncoding(); $this->assertEquals('xxx', $transferEncodingHeader->getFieldValue()); } public function testTransferEncodingToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('TransferEncoding needs to be completed'); $transferEncodingHeader = new TransferEncoding(); // @todo set some values, then test output $this->assertEmpty('Transfer-Encoding: xxx', $transferEncodingHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); TransferEncoding::fromString("Transfer-Encoding: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new TransferEncoding("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ExpiresTest.php
test/Header/ExpiresTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\Expires; use Zend\Http\Header\HeaderInterface; class ExpiresTest extends TestCase { public function testExpiresFromStringCreatesValidExpiresHeader() { $expiresHeader = Expires::fromString('Expires: Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertInstanceOf(HeaderInterface::class, $expiresHeader); $this->assertInstanceOf(Expires::class, $expiresHeader); } public function testExpiresGetFieldNameReturnsHeaderName() { $expiresHeader = new Expires(); $this->assertEquals('Expires', $expiresHeader->getFieldName()); } public function testExpiresGetFieldValueReturnsProperValue() { $expiresHeader = new Expires(); $expiresHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $expiresHeader->getFieldValue()); } public function testExpiresToStringReturnsHeaderFormattedString() { $expiresHeader = new Expires(); $expiresHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertEquals('Expires: Sun, 06 Nov 1994 08:49:37 GMT', $expiresHeader->toString()); } /** * Implementation specific tests are covered by DateTest * @see ZendTest\Http\Header\DateTest */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); Expires::fromString("Expires: Sun, 06 Nov 1994 08:49:37 GMT\r\n\r\nevilContent"); } public function testExpiresSetToZero() { $expires = Expires::fromString('Expires: 0'); $this->assertEquals('Expires: Thu, 01 Jan 1970 00:00:00 GMT', $expires->toString()); $expires = new Expires(); $expires->setDate('0'); $this->assertEquals('Expires: Thu, 01 Jan 1970 00:00:00 GMT', $expires->toString()); $expires = new Expires(); $expires->setDate(0); $this->assertEquals('Expires: Thu, 01 Jan 1970 00:00:00 GMT', $expires->toString()); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/UpgradeTest.php
test/Header/UpgradeTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\Upgrade; class UpgradeTest extends TestCase { public function testUpgradeFromStringCreatesValidUpgradeHeader() { $upgradeHeader = Upgrade::fromString('Upgrade: xxx'); $this->assertInstanceOf(HeaderInterface::class, $upgradeHeader); $this->assertInstanceOf(Upgrade::class, $upgradeHeader); } public function testUpgradeGetFieldNameReturnsHeaderName() { $upgradeHeader = new Upgrade(); $this->assertEquals('Upgrade', $upgradeHeader->getFieldName()); } public function testUpgradeGetFieldValueReturnsProperValue() { $this->markTestIncomplete('Upgrade needs to be completed'); $upgradeHeader = new Upgrade(); $this->assertEquals('xxx', $upgradeHeader->getFieldValue()); } public function testUpgradeToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('Upgrade needs to be completed'); $upgradeHeader = new Upgrade(); // @todo set some values, then test output $this->assertEmpty('Upgrade: xxx', $upgradeHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); Upgrade::fromString("Upgrade: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new Upgrade("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AuthorizationTest.php
test/Header/AuthorizationTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Authorization; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; class AuthorizationTest extends TestCase { public function testAuthorizationFromStringCreatesValidAuthorizationHeader() { $authorizationHeader = Authorization::fromString('Authorization: xxx'); $this->assertInstanceOf(HeaderInterface::class, $authorizationHeader); $this->assertInstanceOf(Authorization::class, $authorizationHeader); } public function testAuthorizationGetFieldNameReturnsHeaderName() { $authorizationHeader = new Authorization(); $this->assertEquals('Authorization', $authorizationHeader->getFieldName()); } public function testAuthorizationGetFieldValueReturnsProperValue() { $authorizationHeader = new Authorization('xxx'); $this->assertEquals('xxx', $authorizationHeader->getFieldValue()); } public function testAuthorizationToStringReturnsHeaderFormattedString() { $authorizationHeader = new Authorization('xxx'); $this->assertEquals('Authorization: xxx', $authorizationHeader->toString()); $authorizationHeader = Authorization::fromString('Authorization: xxx2'); $this->assertEquals('Authorization: xxx2', $authorizationHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); $header = Authorization::fromString("Authorization: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new Authorization("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ProxyAuthorizationTest.php
test/Header/ProxyAuthorizationTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\ProxyAuthorization; class ProxyAuthorizationTest extends TestCase { public function testProxyAuthorizationFromStringCreatesValidProxyAuthorizationHeader() { $proxyAuthorizationHeader = ProxyAuthorization::fromString('Proxy-Authorization: xxx'); $this->assertInstanceOf(HeaderInterface::class, $proxyAuthorizationHeader); $this->assertInstanceOf(ProxyAuthorization::class, $proxyAuthorizationHeader); } public function testProxyAuthorizationGetFieldNameReturnsHeaderName() { $proxyAuthorizationHeader = new ProxyAuthorization(); $this->assertEquals('Proxy-Authorization', $proxyAuthorizationHeader->getFieldName()); } public function testProxyAuthorizationGetFieldValueReturnsProperValue() { $this->markTestIncomplete('ProxyAuthorization needs to be completed'); $proxyAuthorizationHeader = new ProxyAuthorization(); $this->assertEquals('xxx', $proxyAuthorizationHeader->getFieldValue()); } public function testProxyAuthorizationToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('ProxyAuthorization needs to be completed'); $proxyAuthorizationHeader = new ProxyAuthorization(); // @todo set some values, then test output $this->assertEmpty('Proxy-Authorization: xxx', $proxyAuthorizationHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); ProxyAuthorization::fromString("Proxy-Authorization: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new ProxyAuthorization("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/IfUnmodifiedSinceTest.php
test/Header/IfUnmodifiedSinceTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\IfUnmodifiedSince; class IfUnmodifiedSinceTest extends TestCase { public function testIfUnmodifiedSinceFromStringCreatesValidIfUnmodifiedSinceHeader() { $ifUnmodifiedSinceHeader = IfUnmodifiedSince::fromString('If-Unmodified-Since: Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertInstanceOf(HeaderInterface::class, $ifUnmodifiedSinceHeader); $this->assertInstanceOf(IfUnmodifiedSince::class, $ifUnmodifiedSinceHeader); } public function testIfUnmodifiedSinceGetFieldNameReturnsHeaderName() { $ifUnmodifiedSinceHeader = new IfUnmodifiedSince(); $this->assertEquals('If-Unmodified-Since', $ifUnmodifiedSinceHeader->getFieldName()); } public function testIfUnmodifiedSinceGetFieldValueReturnsProperValue() { $ifUnmodifiedSinceHeader = new IfUnmodifiedSince(); $ifUnmodifiedSinceHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $ifUnmodifiedSinceHeader->getFieldValue()); } public function testIfUnmodifiedSinceToStringReturnsHeaderFormattedString() { $ifUnmodifiedSinceHeader = new IfUnmodifiedSince(); $ifUnmodifiedSinceHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertEquals('If-Unmodified-Since: Sun, 06 Nov 1994 08:49:37 GMT', $ifUnmodifiedSinceHeader->toString()); } /** * Implementation specific tests are covered by DateTest * @see ZendTest\Http\Header\DateTest */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testCRLFAttack() { $this->expectException(InvalidArgumentException::class); IfUnmodifiedSince::fromString( "If-Unmodified-Since: Sun, 06 Nov 1994 08:49:37 GMT\r\n\r\nevilContent" ); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentTransferEncodingTest.php
test/Header/ContentTransferEncodingTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\ContentTransferEncoding; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; class ContentTransferEncodingTest extends TestCase { public function testContentTransferEncodingFromStringCreatesValidContentTransferEncodingHeader() { $contentTransferEncodingHeader = ContentTransferEncoding::fromString('Content-Transfer-Encoding: xxx'); $this->assertInstanceOf(HeaderInterface::class, $contentTransferEncodingHeader); $this->assertInstanceOf(ContentTransferEncoding::class, $contentTransferEncodingHeader); } public function testContentTransferEncodingGetFieldNameReturnsHeaderName() { $contentTransferEncodingHeader = new ContentTransferEncoding(); $this->assertEquals('Content-Transfer-Encoding', $contentTransferEncodingHeader->getFieldName()); } public function testContentTransferEncodingGetFieldValueReturnsProperValue() { $this->markTestIncomplete('ContentTransferEncoding needs to be completed'); $contentTransferEncodingHeader = new ContentTransferEncoding(); $this->assertEquals('xxx', $contentTransferEncodingHeader->getFieldValue()); } public function testContentTransferEncodingToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('ContentTransferEncoding needs to be completed'); $contentTransferEncodingHeader = new ContentTransferEncoding(); // @todo set some values, then test output $this->assertEmpty('Content-Transfer-Encoding: xxx', $contentTransferEncodingHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); ContentTransferEncoding::fromString("Content-Transfer-Encoding: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new ContentTransferEncoding("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ViaTest.php
test/Header/ViaTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\Via; class ViaTest extends TestCase { public function testViaFromStringCreatesValidViaHeader() { $viaHeader = Via::fromString('Via: xxx'); $this->assertInstanceOf(HeaderInterface::class, $viaHeader); $this->assertInstanceOf(Via::class, $viaHeader); } public function testViaGetFieldNameReturnsHeaderName() { $viaHeader = new Via(); $this->assertEquals('Via', $viaHeader->getFieldName()); } public function testViaGetFieldValueReturnsProperValue() { $this->markTestIncomplete('Via needs to be completed'); $viaHeader = new Via(); $this->assertEquals('xxx', $viaHeader->getFieldValue()); } public function testViaToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('Via needs to be completed'); $viaHeader = new Via(); // @todo set some values, then test output $this->assertEmpty('Via: xxx', $viaHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); Via::fromString("Via: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new Via("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/MaxForwardsTest.php
test/Header/MaxForwardsTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\MaxForwards; class MaxForwardsTest extends TestCase { public function testMaxForwardsFromStringCreatesValidMaxForwardsHeader() { $maxForwardsHeader = MaxForwards::fromString('Max-Forwards: xxx'); $this->assertInstanceOf(HeaderInterface::class, $maxForwardsHeader); $this->assertInstanceOf(MaxForwards::class, $maxForwardsHeader); } public function testMaxForwardsGetFieldNameReturnsHeaderName() { $maxForwardsHeader = new MaxForwards(); $this->assertEquals('Max-Forwards', $maxForwardsHeader->getFieldName()); } public function testMaxForwardsGetFieldValueReturnsProperValue() { $this->markTestIncomplete('MaxForwards needs to be completed'); $maxForwardsHeader = new MaxForwards(); $this->assertEquals('xxx', $maxForwardsHeader->getFieldValue()); } public function testMaxForwardsToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('MaxForwards needs to be completed'); $maxForwardsHeader = new MaxForwards(); // @todo set some values, then test output $this->assertEmpty('Max-Forwards: xxx', $maxForwardsHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); MaxForwards::fromString("Max-Forwards: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructorValue() { $this->expectException(InvalidArgumentException::class); new MaxForwards("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/VaryTest.php
test/Header/VaryTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\Vary; class VaryTest extends TestCase { public function testVaryFromStringCreatesValidVaryHeader() { $varyHeader = Vary::fromString('Vary: xxx'); $this->assertInstanceOf(HeaderInterface::class, $varyHeader); $this->assertInstanceOf(Vary::class, $varyHeader); } public function testVaryGetFieldNameReturnsHeaderName() { $varyHeader = new Vary(); $this->assertEquals('Vary', $varyHeader->getFieldName()); } public function testVaryGetFieldValueReturnsProperValue() { $this->markTestIncomplete('Vary needs to be completed'); $varyHeader = new Vary(); $this->assertEquals('xxx', $varyHeader->getFieldValue()); } public function testVaryToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('Vary needs to be completed'); $varyHeader = new Vary(); // @todo set some values, then test output $this->assertEmpty('Vary: xxx', $varyHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); Vary::fromString("Vary: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new Vary("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentLanguageTest.php
test/Header/ContentLanguageTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\ContentLanguage; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; class ContentLanguageTest extends TestCase { public function testContentLanguageFromStringCreatesValidContentLanguageHeader() { $contentLanguageHeader = ContentLanguage::fromString('Content-Language: xxx'); $this->assertInstanceOf(HeaderInterface::class, $contentLanguageHeader); $this->assertInstanceOf(ContentLanguage::class, $contentLanguageHeader); } public function testContentLanguageGetFieldNameReturnsHeaderName() { $contentLanguageHeader = new ContentLanguage(); $this->assertEquals('Content-Language', $contentLanguageHeader->getFieldName()); } public function testContentLanguageGetFieldValueReturnsProperValue() { $this->markTestIncomplete('ContentLanguage needs to be completed'); $contentLanguageHeader = new ContentLanguage(); $this->assertEquals('xxx', $contentLanguageHeader->getFieldValue()); } public function testContentLanguageToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('ContentLanguage needs to be completed'); $contentLanguageHeader = new ContentLanguage(); // @todo set some values, then test output $this->assertEmpty('Content-Language: xxx', $contentLanguageHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); ContentLanguage::fromString("Content-Language: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new ContentLanguage("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/CacheControlTest.php
test/Header/CacheControlTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\CacheControl; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; class CacheControlTest extends TestCase { public function testCacheControlFromStringCreatesValidCacheControlHeader() { $cacheControlHeader = CacheControl::fromString('Cache-Control: xxx'); $this->assertInstanceOf(HeaderInterface::class, $cacheControlHeader); $this->assertInstanceOf(CacheControl::class, $cacheControlHeader); } public function testCacheControlGetFieldNameReturnsHeaderName() { $cacheControlHeader = new CacheControl(); $this->assertEquals('Cache-Control', $cacheControlHeader->getFieldName()); } public function testCacheControlGetFieldValueReturnsProperValue() { $this->markTestIncomplete('CacheControl needs to be completed'); $cacheControlHeader = new CacheControl(); $this->assertEquals('xxx', $cacheControlHeader->getFieldValue()); } public function testCacheControlToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('CacheControl needs to be completed'); $cacheControlHeader = new CacheControl(); // @todo set some values, then test output $this->assertEmpty('Cache-Control: xxx', $cacheControlHeader->toString()); } /** Implementation specific tests here */ public function testCacheControlIsEmpty() { $cacheControlHeader = new CacheControl(); $this->assertTrue($cacheControlHeader->isEmpty()); $cacheControlHeader->addDirective('xxx'); $this->assertFalse($cacheControlHeader->isEmpty()); $cacheControlHeader->removeDirective('xxx'); $this->assertTrue($cacheControlHeader->isEmpty()); } public function testCacheControlAddHasGetRemove() { $cacheControlHeader = new CacheControl(); $cacheControlHeader->addDirective('xxx'); $this->assertTrue($cacheControlHeader->hasDirective('xxx')); $this->assertTrue($cacheControlHeader->getDirective('xxx')); $cacheControlHeader->removeDirective('xxx'); $this->assertFalse($cacheControlHeader->hasDirective('xxx')); $this->assertNull($cacheControlHeader->getDirective('xxx')); $cacheControlHeader->addDirective('xxx', 'foo'); $this->assertTrue($cacheControlHeader->hasDirective('xxx')); $this->assertEquals('foo', $cacheControlHeader->getDirective('xxx')); $cacheControlHeader->removeDirective('xxx'); $this->assertFalse($cacheControlHeader->hasDirective('xxx')); $this->assertNull($cacheControlHeader->getDirective('xxx')); } public function testCacheControlGetFieldValue() { $cacheControlHeader = new CacheControl(); $this->assertEmpty($cacheControlHeader->getFieldValue()); $cacheControlHeader->addDirective('xxx'); $this->assertEquals('xxx', $cacheControlHeader->getFieldValue()); $cacheControlHeader->addDirective('aaa'); $this->assertEquals('aaa, xxx', $cacheControlHeader->getFieldValue()); $cacheControlHeader->addDirective('yyy', 'foo'); $this->assertEquals('aaa, xxx, yyy=foo', $cacheControlHeader->getFieldValue()); $cacheControlHeader->addDirective('zzz', 'bar, baz'); $this->assertEquals('aaa, xxx, yyy=foo, zzz="bar, baz"', $cacheControlHeader->getFieldValue()); } public function testCacheControlParse() { $cacheControlHeader = CacheControl::fromString('Cache-Control: a, b=foo, c="bar, baz"'); $this->assertTrue($cacheControlHeader->hasDirective('a')); $this->assertTrue($cacheControlHeader->getDirective('a')); $this->assertTrue($cacheControlHeader->hasDirective('b')); $this->assertEquals('foo', $cacheControlHeader->getDirective('b')); $this->assertTrue($cacheControlHeader->hasDirective('c')); $this->assertEquals('bar, baz', $cacheControlHeader->getDirective('c')); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); CacheControl::fromString("Cache-Control: xxx\r\n\r\n"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testProtectsFromCRLFAttackViaSetters() { $header = new CacheControl(); $this->expectException(InvalidArgumentException::class); $header->addDirective("\rsome\r\ninvalid\nkey", "\ra\r\nCRLF\ninjection"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/GenericHeaderTest.php
test/Header/GenericHeaderTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\GenericHeader; class GenericHeaderTest extends TestCase { /** * @dataProvider validFieldNameChars * * @param string $name */ public function testValidFieldName($name) { try { new GenericHeader($name); } catch (InvalidArgumentException $e) { $this->assertEquals( $e->getMessage(), 'Header name must be a valid RFC 7230 (section 3.2) field-name.' ); $this->fail('Allowed char rejected: ' . ord($name)); // For easy debug } } /** * @dataProvider invalidFieldNameChars * * @param string $name */ public function testInvalidFieldName($name) { try { new GenericHeader($name); $this->fail('Invalid char allowed: ' . ord($name)); // For easy debug } catch (InvalidArgumentException $e) { $this->assertEquals( $e->getMessage(), 'Header name must be a valid RFC 7230 (section 3.2) field-name.' ); } } /** * @group 7295 */ public function testDoesNotReplaceUnderscoresWithDashes() { $header = new GenericHeader('X_Foo_Bar'); $this->assertEquals('X_Foo_Bar', $header->getFieldName()); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); GenericHeader::fromString("X_Foo_Bar: Bar\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); new GenericHeader('X_Foo_Bar', "Bar\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testProtectsFromCRLFAttackViaSetFieldName() { $header = new GenericHeader(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('valid'); $header->setFieldName("\rX-\r\nFoo-\nBar"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testProtectsFromCRLFAttackViaSetFieldValue() { $header = new GenericHeader(); $this->expectException(InvalidArgumentException::class); $header->setFieldValue("\rSome\r\nCLRF\nAttack"); } /** * Valid field name characters. * * @return string[] */ public function validFieldNameChars() { return [ ['!'], ['#'], ['$'], ['%'], ['&'], ["'"], ['*'], ['+'], ['-'], ['.'], ['0'], // Begin numeric range ['9'], // End numeric range ['A'], // Begin upper range ['Z'], // End upper range ['^'], ['_'], ['`'], ['a'], // Begin lower range ['z'], // End lower range ['|'], ['~'], ]; } /** * Invalid field name characters. * * @return string[] */ public function invalidFieldNameChars() { return [ ["\x00"], // Min CTL invalid character range. ["\x1F"], // Max CTL invalid character range. ['('], [')'], ['<'], ['>'], ['@'], [','], [';'], [':'], ['\\'], ['"'], ['/'], ['['], [']'], ['?'], ['='], ['{'], ['}'], [' '], ["\t"], ["\x7F"], // DEL CTL invalid character. ]; } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
zendframework/zend-http
https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/WWWAuthenticateTest.php
test/Header/WWWAuthenticateTest.php
<?php /** * @see https://github.com/zendframework/zend-http for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License */ namespace ZendTest\Http\Header; use PHPUnit\Framework\TestCase; use Zend\Http\Header\Exception\InvalidArgumentException; use Zend\Http\Header\HeaderInterface; use Zend\Http\Header\WWWAuthenticate; class WWWAuthenticateTest extends TestCase { public function testWWWAuthenticateFromStringCreatesValidWWWAuthenticateHeader() { $wWWAuthenticateHeader = WWWAuthenticate::fromString('WWW-Authenticate: xxx'); $this->assertInstanceOf(HeaderInterface::class, $wWWAuthenticateHeader); $this->assertInstanceOf(WWWAuthenticate::class, $wWWAuthenticateHeader); } public function testWWWAuthenticateGetFieldNameReturnsHeaderName() { $wWWAuthenticateHeader = new WWWAuthenticate(); $this->assertEquals('WWW-Authenticate', $wWWAuthenticateHeader->getFieldName()); } public function testWWWAuthenticateGetFieldValueReturnsProperValue() { $this->markTestIncomplete('WWWAuthenticate needs to be completed'); $wWWAuthenticateHeader = new WWWAuthenticate(); $this->assertEquals('xxx', $wWWAuthenticateHeader->getFieldValue()); } public function testWWWAuthenticateToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('WWWAuthenticate needs to be completed'); $wWWAuthenticateHeader = new WWWAuthenticate(); // @todo set some values, then test output $this->assertEmpty('WWW-Authenticate: xxx', $wWWAuthenticateHeader->toString()); } /** Implementation specific tests here */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaFromString() { $this->expectException(InvalidArgumentException::class); $header = WWWAuthenticate::fromString("WWW-Authenticate: xxx\r\n\r\nevilContent"); } /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 */ public function testPreventsCRLFAttackViaConstructor() { $this->expectException(InvalidArgumentException::class); $header = new WWWAuthenticate("xxx\r\n\r\nevilContent"); } }
php
BSD-3-Clause
ac4ffd09d509b2c5c0285178c4f7de740f05c3d9
2026-01-05T05:18:13.309357Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/FrontMatter.php
src/FrontMatter.php
<?php namespace Livewire\Blaze; use Livewire\Blaze\Events\ComponentFolded; class FrontMatter { public function compileFromEvents(array $events): string { $frontmatter = ''; foreach ($events as $event) { if (! ($event instanceof ComponentFolded)) { throw new \Exception('Event is not a ComponentFolded event'); } $frontmatter .= "<?php # [BlazeFolded]:{". $event->name ."}:{". $event->path ."}:{".$event->filemtime."} ?>\n"; } return $frontmatter; } public function sourceContainsExpiredFoldedDependencies(string $source): bool { $foldedComponents = $this->parseFromTemplate($source); if (empty($foldedComponents)) { return false; } foreach ($foldedComponents as $match) { $componentPath = $match[2]; $storedFilemtime = (int) $match[3]; if (! file_exists($componentPath)) { return true; } $currentFilemtime = filemtime($componentPath); if ($currentFilemtime > $storedFilemtime) { return true; } } return false; } public function parseFromTemplate(string $template): array { preg_match_all('/<'.'?php # \[BlazeFolded\]:\{([^}]+)\}:\{([^}]+)\}:\{([^}]+)\} \?>/', $template, $matches, PREG_SET_ORDER); return $matches; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/BlazeManager.php
src/BlazeManager.php
<?php namespace Livewire\Blaze; use Livewire\Blaze\Events\ComponentFolded; use Livewire\Blaze\Nodes\ComponentNode; use Livewire\Blaze\Tokenizer\Tokenizer; use Illuminate\Support\Facades\Event; use Livewire\Blaze\Memoizer\Memoizer; use Livewire\Blaze\Walker\Walker; use Livewire\Blaze\Parser\Parser; use Livewire\Blaze\Folder\Folder; class BlazeManager { protected $foldedEvents = []; protected $enabled = true; protected $debug = false; protected $expiredMemo = []; public function __construct( protected Tokenizer $tokenizer, protected Parser $parser, protected Walker $walker, protected Folder $folder, protected Memoizer $memoizer, ) { Event::listen(ComponentFolded::class, function (ComponentFolded $event) { $this->foldedEvents[] = $event; }); } public function flushFoldedEvents() { return tap($this->foldedEvents, function ($events) { $this->foldedEvents = []; return $events; }); } public function collectAndAppendFrontMatter($template, $callback) { $this->flushFoldedEvents(); $output = $callback($template); $frontmatter = (new FrontMatter)->compileFromEvents( $this->flushFoldedEvents() ); return $frontmatter . $output; } public function viewContainsExpiredFrontMatter($view): bool { $path = $view->getPath(); if (isset($this->expiredMemo[$path])) { return $this->expiredMemo[$path]; } $compiler = $view->getEngine()->getCompiler(); $compiled = $compiler->getCompiledPath($path); $expired = $compiler->isExpired($path); $isExpired = false; if (! $expired) { $contents = file_get_contents($compiled); $isExpired = (new FrontMatter)->sourceContainsExpiredFoldedDependencies($contents); } $this->expiredMemo[$path] = $isExpired; return $isExpired; } public function compile(string $template): string { // Protect verbatim blocks before tokenization $template = (new BladeService)->preStoreVerbatimBlocks($template); $tokens = $this->tokenizer->tokenize($template); $ast = $this->parser->parse($tokens); $dataStack = []; $ast = $this->walker->walk( nodes: $ast, preCallback: function ($node) use (&$dataStack) { if ($node instanceof ComponentNode) { $node->setParentsAttributes($dataStack); } if (($node instanceof ComponentNode) && !empty($node->children)) { array_push($dataStack, $node->attributes); } return $node; }, postCallback: function ($node) use (&$dataStack) { if (($node instanceof ComponentNode) && !empty($node->children)) { array_pop($dataStack); } return $this->memoizer->memoize($this->folder->fold($node)); }, ); $output = $this->render($ast); (new BladeService)->deleteTemporaryCacheDirectory(); return $output; } public function render(array $nodes): string { return implode('', array_map(fn ($n) => $n->render(), $nodes)); } public function isEnabled() { return $this->enabled; } public function isDisabled() { return ! $this->enabled; } public function enable() { $this->enabled = true; } public function disable() { $this->enabled = false; } public function debug() { $this->debug = true; } public function isDebugging() { return $this->debug; } public function tokenizer(): Tokenizer { return $this->tokenizer; } public function parser(): Parser { return $this->parser; } public function folder(): Folder { return $this->folder; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Unblaze.php
src/Unblaze.php
<?php namespace Livewire\Blaze; use Illuminate\Support\Arr; class Unblaze { static $unblazeScopes = []; static $unblazeReplacements = []; public static function storeScope($token, $scope = []) { static::$unblazeScopes[$token] = $scope; } public static function hasUnblaze(string $template): bool { return str_contains($template, '@unblaze'); } public static function processUnblazeDirectives(string $template) { $compiler = static::getHackedBladeCompiler(); $expressionsByToken = []; $compiler->directive('unblaze', function ($expression) use (&$expressionsByToken) { $token = str()->random(10); $expressionsByToken[$token] = $expression; return '[STARTUNBLAZE:'.$token.']'; }); $compiler->directive('endunblaze', function () { return '[ENDUNBLAZE]'; }); $result = $compiler->compileStatementsMadePublic($template); $result = preg_replace_callback('/(\[STARTUNBLAZE:([0-9a-zA-Z]+)\])(.*?)(\[ENDUNBLAZE\])/s', function ($matches) use (&$expressionsByToken) { $token = $matches[2]; $expression = $expressionsByToken[$token]; $innerContent = $matches[3]; static::$unblazeReplacements[$token] = $innerContent; return '' . '[STARTCOMPILEDUNBLAZE:'.$token.']' . '<'.'?php \Livewire\Blaze\Unblaze::storeScope("'.$token.'", '.$expression.') ?>' . '[ENDCOMPILEDUNBLAZE]'; }, $result); return $result; } public static function replaceUnblazePrecompiledDirectives(string $template) { if (str_contains($template, '[STARTCOMPILEDUNBLAZE')) { $template = preg_replace_callback('/(\[STARTCOMPILEDUNBLAZE:([0-9a-zA-Z]+)\])(.*?)(\[ENDCOMPILEDUNBLAZE\])/s', function ($matches) use (&$expressionsByToken) { $token = $matches[2]; $innerContent = static::$unblazeReplacements[$token]; $scope = static::$unblazeScopes[$token]; $runtimeScopeString = var_export($scope, true); return '' . '<'.'?php if (isset($scope)) $__scope = $scope; ?>' . '<'.'?php $scope = '.$runtimeScopeString.'; ?>' . $innerContent . '<'.'?php if (isset($__scope)) { $scope = $__scope; unset($__scope); } ?>'; }, $template); } return $template; } public static function getHackedBladeCompiler() { $instance = new class ( app('files'), storage_path('framework/views'), ) extends \Illuminate\View\Compilers\BladeCompiler { /** * Make this method public... */ public function compileStatementsMadePublic($template) { return $this->compileStatements($template); } /** * Tweak this method to only process custom directives so we * can restrict rendering solely to @island related directives... */ protected function compileStatement($match) { if (str_contains($match[1], '@')) { $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1]; } elseif (isset($this->customDirectives[$match[1]])) { $match[0] = $this->callCustomDirective($match[1], Arr::get($match, 3)); } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) { // Don't process through built-in directive methods... // $match[0] = $this->$method(Arr::get($match, 3)); // Just return the original match... return $match[0]; } else { return $match[0]; } return isset($match[3]) ? $match[0] : $match[0].$match[2]; } }; return $instance; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/BladeService.php
src/BladeService.php
<?php namespace Livewire\Blaze; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\File; use Livewire\Blaze\Unblaze; use ReflectionClass; class BladeService { public function getTemporaryCachePath(): string { return storage_path('framework/views/blaze'); } public function isolatedRender(string $template): string { $compiler = app('blade.compiler'); $temporaryCachePath = $this->getTemporaryCachePath(); File::ensureDirectoryExists($temporaryCachePath); $factory = app('view'); [$factory, $restoreFactory] = $this->freezeObjectProperties($factory, [ 'componentStack' => [], 'componentData' => [], 'currentComponentData' => [], 'slots' => [], 'slotStack' => [], 'renderCount' => 0, ]); [$compiler, $restore] = $this->freezeObjectProperties($compiler, [ 'cachePath' => $temporaryCachePath, 'rawBlocks', 'prepareStringsForCompilationUsing' => [ function ($input) { if (Unblaze::hasUnblaze($input)) { $input = Unblaze::processUnblazeDirectives($input); } return $input; } ], 'path' => null, ]); try { // As we are rendering a string, Blade will generate a view for the string in the cache directory // and it doesn't use the `cachePath` property. Instead it uses the config `view.compiled` path // to store the view. Hence why our `temporaryCachePath` won't clean this file up. To remove // the file, we can pass `deleteCachedView: true` to the render method... $result = $compiler->render($template, deleteCachedView: true); $result = Unblaze::replaceUnblazePrecompiledDirectives($result); } finally { $restore(); $restoreFactory(); } return $result; } public function deleteTemporaryCacheDirectory() { File::deleteDirectory($this->getTemporaryCachePath()); } public function containsLaravelExceptionView(string $input): bool { return str_contains($input, 'laravel-exceptions'); } public function earliestPreCompilationHook(callable $callback) { app()->booted(function () use ($callback) { app('blade.compiler')->prepareStringsForCompilationUsing(function ($input) use ($callback) { $output = $callback($input); return $output; }); }); } public function preStoreVerbatimBlocks(string $input): string { $compiler = app('blade.compiler'); $reflection = new \ReflectionClass($compiler); $storeVerbatimBlocks = $reflection->getMethod('storeVerbatimBlocks'); $storeVerbatimBlocks->setAccessible(true); return $storeVerbatimBlocks->invoke($compiler, $input); } public function restoreVerbatimBlocks(string $input): string { $compiler = app('blade.compiler'); $reflection = new \ReflectionClass($compiler); $restoreRawBlocks = $reflection->getMethod('restoreRawBlocks'); $restoreRawBlocks->setAccessible(true); return $restoreRawBlocks->invoke($compiler, $input); } public function viewCacheInvalidationHook(callable $callback) { Event::listen('composing:*', function ($event, $params) use ($callback) { $view = $params[0]; if (! $view instanceof \Illuminate\View\View) { return; } $invalidate = fn () => app('blade.compiler')->compile($view->getPath()); $callback($view, $invalidate); }); } public function componentNameToPath($name): string { $compiler = app('blade.compiler'); $viewFinder = app('view.finder'); $reflection = new \ReflectionClass($compiler); $pathsProperty = $reflection->getProperty('anonymousComponentPaths'); $pathsProperty->setAccessible(true); $paths = $pathsProperty->getValue($compiler) ?? []; // Handle namespaced components... if (str_contains($name, '::')) { [$namespace, $componentName] = explode('::', $name, 2); $componentPath = str_replace('.', '/', $componentName); // Look for namespaced anonymous component... foreach ($paths as $pathData) { if (isset($pathData['prefix']) && $pathData['prefix'] === $namespace) { $basePath = rtrim($pathData['path'], '/'); // Try direct component file first (e.g., pages::auth.login -> auth/login.blade.php)... $fullPath = $basePath . '/' . $componentPath . '.blade.php'; if (file_exists($fullPath)) { return $fullPath; } // Try index.blade.php (e.g., pages::auth -> auth/index.blade.php)... $indexPath = $basePath . '/' . $componentPath . '/index.blade.php'; if (file_exists($indexPath)) { return $indexPath; } // Try same-name file (e.g., pages::auth -> auth/auth.blade.php)... $lastSegment = basename($componentPath); $sameNamePath = $basePath . '/' . $componentPath . '/' . $lastSegment . '.blade.php'; if (file_exists($sameNamePath)) { return $sameNamePath; } } } // Fallback to regular namespaced view lookup... try { return $viewFinder->find(str_replace('::', '::components.', $name)); } catch (\Exception $e) { return ''; } } // For regular anonymous components, check the registered paths... $componentPath = str_replace('.', '/', $name); // Check each registered anonymous component path (without prefix)... foreach ($paths as $pathData) { // Only check paths without a prefix for regular anonymous components... if (!isset($pathData['prefix']) || $pathData['prefix'] === null) { $registeredPath = $pathData['path'] ?? $pathData; if (is_string($registeredPath)) { $basePath = rtrim($registeredPath, '/'); // Try direct component file first (e.g., form.input -> form/input.blade.php)... $fullPath = $basePath . '/' . $componentPath . '.blade.php'; if (file_exists($fullPath)) { return $fullPath; } // Try index.blade.php (e.g., form -> form/index.blade.php)... $indexPath = $basePath . '/' . $componentPath . '/index.blade.php'; if (file_exists($indexPath)) { return $indexPath; } // Try same-name file (e.g., card -> card/card.blade.php)... $lastSegment = basename($componentPath); $sameNamePath = $basePath . '/' . $componentPath . '/' . $lastSegment . '.blade.php'; if (file_exists($sameNamePath)) { return $sameNamePath; } } } } // Fallback to standard components namespace... try { return $viewFinder->find("components.{$name}"); } catch (\Exception $e) { return ''; } } protected function freezeObjectProperties(object $object, array $properties) { $reflection = new ReflectionClass($object); $frozen = []; foreach ($properties as $key => $value) { $name = is_numeric($key) ? $value : $key; $property = $reflection->getProperty($name); $property->setAccessible(true); $frozen[$name] = $property->getValue($object); if (! is_numeric($key)) { $property->setValue($object, $value); } } return [ $object, function () use ($reflection, $object, $frozen) { foreach ($frozen as $name => $value) { $property = $reflection->getProperty($name); $property->setAccessible(true); $property->setValue($object, $value); } }, ]; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Blaze.php
src/Blaze.php
<?php namespace Livewire\Blaze; use Illuminate\Support\Facades\Facade; /** * @method static string collectAndAppendFrontMatter(string $template, callable $callback) * @method static bool viewContainsExpiredFrontMatter(\Illuminate\View\View $view) * @method static string compile(string $template) * @method static string render(array $nodes) * @method static void enable() * @method static void disable() * @method static bool isEnabled() * @method static bool isDisabled() * @method static \Livewire\Blaze\Tokenizer\Tokenizer tokenizer() * @method static \Livewire\Blaze\Parser\Parser parser() * @method static \Livewire\Blaze\Folder\Folder folder() * @method static array flushFoldedEvents() * @see \Livewire\Blaze\BlazeManager */ class Blaze extends Facade { public static function getFacadeAccessor() { return 'blaze'; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/BlazeServiceProvider.php
src/BlazeServiceProvider.php
<?php namespace Livewire\Blaze; use Livewire\Blaze\Walker\Walker; use Livewire\Blaze\Tokenizer\Tokenizer; use Livewire\Blaze\Parser\Parser; use Livewire\Blaze\Memoizer\Memoizer; use Livewire\Blaze\Folder\Folder; use Livewire\Blaze\Directive\BlazeDirective; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Blade; class BlazeServiceProvider extends ServiceProvider { public function register(): void { $this->registerBlazeManager(); $this->registerBlazeDirectiveFallbacks(); $this->registerBladeMacros(); $this->interceptBladeCompilation(); $this->interceptViewCacheInvalidation(); } protected function registerBlazeManager(): void { $bladeService = new BladeService; $this->app->singleton(BlazeManager::class, fn () => new BlazeManager( new Tokenizer, new Parser, new Walker, new Folder( renderBlade: fn ($blade) => $bladeService->isolatedRender($blade), renderNodes: fn ($nodes) => implode('', array_map(fn ($n) => $n->render(), $nodes)), componentNameToPath: fn ($name) => $bladeService->componentNameToPath($name), ), new Memoizer( componentNameToPath: fn ($name) => $bladeService->componentNameToPath($name), ), )); $this->app->alias(BlazeManager::class, Blaze::class); $this->app->bind('blaze', fn ($app) => $app->make(BlazeManager::class)); } protected function registerBlazeDirectiveFallbacks(): void { Blade::directive('unblaze', function ($expression) { return '' . '<'.'?php $__getScope = fn($scope = []) => $scope; ?>' . '<'.'?php if (isset($scope)) $__scope = $scope; ?>' . '<'.'?php $scope = $__getScope('.$expression.'); ?>'; }); Blade::directive('endunblaze', function () { return '<'.'?php if (isset($__scope)) { $scope = $__scope; unset($__scope); } ?>'; }); BlazeDirective::registerFallback(); } protected function registerBladeMacros(): void { $this->app->make('view')->macro('pushConsumableComponentData', function ($data) { $this->componentStack[] = new \Illuminate\Support\HtmlString(''); $this->componentData[$this->currentComponent()] = $data; }); $this->app->make('view')->macro('popConsumableComponentData', function () { array_pop($this->componentStack); }); } protected function interceptBladeCompilation(): void { $blaze = app(BlazeManager::class); (new BladeService)->earliestPreCompilationHook(function ($input) use ($blaze) { if ($blaze->isDisabled()) return $input; if ((new BladeService)->containsLaravelExceptionView($input)) return $input; return $blaze->collectAndAppendFrontMatter($input, function ($input) use ($blaze) { return $blaze->compile($input); }); }); } protected function interceptViewCacheInvalidation(): void { $blaze = app(BlazeManager::class); (new BladeService)->viewCacheInvalidationHook(function ($view, $invalidate) use ($blaze) { if ($blaze->isDisabled()) return; if ($blaze->viewContainsExpiredFrontMatter($view)) { $invalidate(); } }); } public function boot(): void { // Bootstrap services } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Exceptions/InvalidBlazeFoldUsageException.php
src/Exceptions/InvalidBlazeFoldUsageException.php
<?php namespace Livewire\Blaze\Exceptions; class InvalidBlazeFoldUsageException extends \Exception { protected string $componentPath; protected string $problematicPattern; protected function __construct(string $componentPath, string $problematicPattern, string $reason) { $this->componentPath = $componentPath; $this->problematicPattern = $problematicPattern; $message = "Invalid @blaze fold usage in component '{$componentPath}': {$reason}"; parent::__construct($message); } public function getComponentPath(): string { return $this->componentPath; } public function getProblematicPattern(): string { return $this->problematicPattern; } public static function forAware(string $componentPath): self { return new self( $componentPath, '@aware', 'Components with @aware should not use @blaze fold as they depend on parent component state' ); } public static function forErrors(string $componentPath): self { return new self( $componentPath, '\\$errors', 'Components accessing $errors should not use @blaze fold as errors are request-specific' ); } public static function forSession(string $componentPath): self { return new self( $componentPath, 'session\\(', 'Components using session() should not use @blaze fold as session data can change' ); } public static function forError(string $componentPath): self { return new self( $componentPath, '@error\\(', 'Components with @error directives should not use @blaze fold as errors are request-specific' ); } public static function forCsrf(string $componentPath): self { return new self( $componentPath, '@csrf', 'Components with @csrf should not use @blaze fold as CSRF tokens are request-specific' ); } public static function forAuth(string $componentPath): self { return new self( $componentPath, 'auth\\(\\)', 'Components using auth() should not use @blaze fold as authentication state can change' ); } public static function forRequest(string $componentPath): self { return new self( $componentPath, 'request\\(\\)', 'Components using request() should not use @blaze fold as request data varies' ); } public static function forOld(string $componentPath): self { return new self( $componentPath, 'old\\(', 'Components using old() should not use @blaze fold as old input is request-specific' ); } public static function forOnce(string $componentPath): self { return new self( $componentPath, '@once', 'Components with @once should not use @blaze fold as @once maintains runtime state' ); } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Exceptions/LeftoverPlaceholdersException.php
src/Exceptions/LeftoverPlaceholdersException.php
<?php namespace Livewire\Blaze\Exceptions; class LeftoverPlaceholdersException extends \RuntimeException { public function __construct( protected string $componentName, protected string $leftoverSummary, protected ?string $renderedSnippet = null ) { parent::__construct( "Leftover Blaze placeholders detected after folding component '{$componentName}': {$leftoverSummary}" ); } public function getComponentName(): string { return $this->componentName; } public function getLeftoverSummary(): string { return $this->leftoverSummary; } public function getRenderedSnippet(): ?string { return $this->renderedSnippet; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Support/AttributeParser.php
src/Support/AttributeParser.php
<?php namespace Livewire\Blaze\Support; class AttributeParser { public function parseAndReplaceDynamics( string $attributesString, array &$attributePlaceholders, array &$attributeNameToPlaceholder ): string { // Early exit unless bound syntax or echo present (support start or whitespace before colon)... $hasBound = (bool) preg_match('/(^|\s):[A-Za-z$]/', $attributesString); if (! $hasBound && strpos($attributesString, '{{') === false) { return $attributesString; } // :name="..." $attributesString = preg_replace_callback('/(?<!\S)(\s*):([A-Za-z0-9_:-]+)\s*=\s*"([^"]*)"/', function ($matches) use (&$attributePlaceholders, &$attributeNameToPlaceholder) { $whitespace = $matches[1]; $attributeName = $matches[2]; $attributeValue = $matches[3]; $placeholder = 'ATTR_PLACEHOLDER_' . count($attributePlaceholders); $attributePlaceholders[$placeholder] = '{{ ' . $attributeValue . ' }}'; $attributeNameToPlaceholder[$attributeName] = $placeholder; return $whitespace . $attributeName . '="' . $placeholder . '"'; }, $attributesString); // Short :$var $attributesString = preg_replace_callback('/(\s*):\$([a-zA-Z0-9_]+)/', function ($matches) use (&$attributePlaceholders, &$attributeNameToPlaceholder) { $whitespace = $matches[1]; $variableName = $matches[2]; $placeholder = 'ATTR_PLACEHOLDER_' . count($attributePlaceholders); $attributePlaceholders[$placeholder] = '{{ $' . $variableName . ' }}'; $attributeNameToPlaceholder[$variableName] = $placeholder; return $whitespace . $variableName . '="' . $placeholder . '"'; }, $attributesString); // Echoes inside quoted attribute values: foo {{ $bar }} $attributesString = preg_replace_callback('/(\s*[a-zA-Z0-9_-]+\s*=\s*")([^\"]*)(\{\{[^}]+\}\})([^\"]*)(")/', function ($matches) use (&$attributePlaceholders) { $before = $matches[1] . $matches[2]; $echo = $matches[3]; $after = $matches[4] . $matches[5]; $placeholder = 'ATTR_PLACEHOLDER_' . count($attributePlaceholders); $attributePlaceholders[$placeholder] = $echo; return $before . $placeholder . $after; }, $attributesString); return $attributesString; } /** * Parse an attribute string into an array of attributes. * * For example, the string: * `foo="bar" :name="$name" :$baz searchable` * * will be parsed into the array: * [ * 'foo' => [ * 'isDynamic' => false, * 'value' => 'bar', * 'original' => 'foo="bar"', * ], * 'name' => [ * 'isDynamic' => true, * 'value' => '$name', * 'original' => ':name="$name"', * ], * 'baz' => [ * 'isDynamic' => true, * 'value' => '$baz', * 'original' => ':$baz', * ], * 'searchable' => [ * 'isDynamic' => false, * 'value' => true, * 'original' => 'searchable', * ], * ] */ public function parseAttributeStringToArray(string $attributesString): array { $attributes = []; // Handle :name="..." syntax preg_match_all('/(?:^|\s):([A-Za-z0-9_:-]+)\s*=\s*"([^"]*)"/', $attributesString, $matches, PREG_SET_ORDER); foreach ($matches as $m) { $attributeName = str($m[1])->camel()->toString(); if (isset($attributes[$attributeName])) continue; $attributes[$attributeName] = [ 'isDynamic' => true, 'value' => $m[2], 'original' => trim($m[0]), ]; } // Handle short :$var syntax (expands to :var="$var") preg_match_all('/(?:^|\s):\$([A-Za-z0-9_:-]+)(?=\s|$)/', $attributesString, $matches, PREG_SET_ORDER); foreach ($matches as $m) { $raw = $m[1]; $attributeName = str($raw)->camel()->toString(); if (isset($attributes[$attributeName])) continue; $attributes[$attributeName] = [ 'isDynamic' => true, 'value' => '$' . $raw, 'original' => trim($m[0]), ]; } // Handle regular name="value" syntax preg_match_all('/(?:^|\s)(?!:)([A-Za-z0-9_:-]+)\s*=\s*"([^"]*)"/', $attributesString, $matches, PREG_SET_ORDER); foreach ($matches as $m) { $attributeName = str($m[1])->camel()->toString(); if (isset($attributes[$attributeName])) continue; $attributes[$attributeName] = [ 'isDynamic' => false, 'value' => $m[2], 'original' => trim($m[0]), ]; } // Handle boolean attributes (single words without values) preg_match_all('/(?:^|\s)([A-Za-z0-9_:-]+)(?=\s|$)/', $attributesString, $matches, PREG_SET_ORDER); foreach ($matches as $m) { $attributeName = str($m[1])->camel()->toString(); if (isset($attributes[$attributeName])) continue; $attributes[$attributeName] = [ 'isDynamic' => false, 'value' => true, 'original' => trim($m[0]), ]; } return $attributes; } /** * Parse an array of attributes into an attributes string. * * For example, the array: * [ * 'foo' => [ * 'isDynamic' => false, * 'value' => 'bar', * 'original' => 'foo="bar"', * ], * 'name' => [ * 'isDynamic' => true, * 'value' => '$name', * 'original' => ':name="$name"', * ], * 'baz' => [ * 'isDynamic' => true, * 'value' => '$baz', * 'original' => ':$baz', * ], * 'searchable' => [ * 'isDynamic' => false, * 'value' => true, * 'original' => 'searchable', * ], * ] * * will be parsed into the string: * `foo="bar" :name="$name" :$baz searchable` */ public function parseAttributesArrayToPropString(array $attributes): string { $attributesString = ''; foreach ($attributes as $attributeName => $attributeValue) { $attributesString .= $attributeValue['original'] . ' '; } return trim($attributesString); } /** * * Parse an array of attributes into a runtime array string. * * For example, the array: * [ * 'foo' => [ * 'isDynamic' => false, * 'value' => 'bar', * 'original' => 'foo="bar"', * ], * 'name' => [ * 'isDynamic' => true, * 'value' => '$name', * 'original' => ':name="$name"', * ], * 'baz' => [ * 'isDynamic' => true, * 'value' => '$baz', * 'original' => ':$baz', * ], * 'searchable' => [ * 'isDynamic' => false, * 'value' => true, * 'original' => 'searchable', * ], * ] * * will be parsed into the string: * `['foo' => 'bar', 'name' => $name, 'baz' => $baz, 'searchable' => true]` */ public function parseAttributesArrayToRuntimeArrayString(array $attributes): string { $arrayParts = []; foreach ($attributes as $attributeName => $attributeData) { if ($attributeData['isDynamic']) { $arrayParts[] = "'" . addslashes($attributeName) . "' => " . $attributeData['value']; continue; } $value = $attributeData['value']; // Handle different value types if (is_bool($value)) { $valueString = $value ? 'true' : 'false'; } elseif (is_string($value)) { $valueString = "'" . addslashes($value) . "'"; } elseif (is_null($value)) { $valueString = 'null'; } else { $valueString = (string) $value; } $arrayParts[] = "'" . addslashes($attributeName) . "' => " . $valueString; } return '[' . implode(', ', $arrayParts) . ']'; } /** * Parse PHP array string syntax (typically used in `@aware` or `@props` directives) into a PHP array. * * For example, the string: * `['foo', 'bar' => 'baz']` * * will be parsed into the array: * [ * 'foo', * 'bar' => 'baz', * ] */ public function parseArrayStringIntoArray(string $arrayString): array { // Remove any leading/trailing whitespace and newlines $arrayString = trim($arrayString); // Remove square brackets if present if (str_starts_with($arrayString, '[') && str_ends_with($arrayString, ']')) { $arrayString = substr($arrayString, 1, -1); } // Split by comma, but be careful about commas inside quotes $items = []; $current = ''; $inQuotes = false; $quoteChar = ''; for ($i = 0; $i < strlen($arrayString); $i++) { $char = $arrayString[$i]; if (($char === '"' || $char === "'") && !$inQuotes) { $inQuotes = true; $quoteChar = $char; $current .= $char; } elseif ($char === $quoteChar && $inQuotes) { $inQuotes = false; $quoteChar = ''; $current .= $char; } elseif ($char === ',' && !$inQuotes) { $items[] = trim($current); $current = ''; } else { $current .= $char; } } if (!empty(trim($current))) { $items[] = trim($current); } $array = []; foreach ($items as $item) { $item = trim($item); if (empty($item)) continue; // Check if it's a key-value pair (contains =>) if (strpos($item, '=>') !== false) { $parts = explode('=>', $item, 2); $key = trim(trim($parts[0]), "'\""); $value = trim(trim($parts[1]), "'\""); // Convert null string to actual null if ($value === 'null') { $value = null; } $array[$key] = $value; } else { // It's just a key $key = trim(trim($item), "'\""); $array[] = $key; } } return $array; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Memoizer/Memo.php
src/Memoizer/Memo.php
<?php namespace Livewire\Blaze\Memoizer; class Memo { protected static $memo = []; public static function clear(): void { self::$memo = []; } public static function key(string $name, $params = []): string { ksort($params); $params = json_encode($params); return 'blaze_memoized_' . $name . ':' . $params; } public static function has(string $key): bool { return isset(self::$memo[$key]); } public static function get(string $key): mixed { return self::$memo[$key]; } public static function put(string $key, mixed $value): void { self::$memo[$key] = $value; } public static function forget(string $key): void { unset(self::$memo[$key]); } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Memoizer/Memoizer.php
src/Memoizer/Memoizer.php
<?php namespace Livewire\Blaze\Memoizer; use Livewire\Blaze\Nodes\ComponentNode; use Livewire\Blaze\Nodes\TextNode; use Livewire\Blaze\Nodes\Node; use Livewire\Blaze\Directive\BlazeDirective; class Memoizer { protected $componentNameToPath; public function __construct(callable $componentNameToPath) { $this->componentNameToPath = $componentNameToPath; } public function isMemoizable(Node $node): bool { if (! $node instanceof ComponentNode) { return false; } try { $componentPath = ($this->componentNameToPath)($node->name); if (empty($componentPath) || ! file_exists($componentPath)) { return false; } $source = file_get_contents($componentPath); $directiveParameters = BlazeDirective::getParameters($source); if (is_null($directiveParameters)) { return false; } // Default to true if memo parameter is not specified return $directiveParameters['memo'] ?? true; } catch (\Exception $e) { return false; } } public function memoize(Node $node): Node { if (! $node instanceof ComponentNode) { return $node; } if (! $node->selfClosing) { return $node; } if (! $this->isMemoizable($node)) { return $node; } $name = $node->name; $attributes = $node->getAttributesAsRuntimeArrayString(); $output = '<' . '?php $blaze_memoized_key = \Livewire\Blaze\Memoizer\Memo::key("' . $name . '", ' . $attributes . '); ?>'; $output .= '<' . '?php if (! \Livewire\Blaze\Memoizer\Memo::has($blaze_memoized_key)) : ?>'; $output .= '<' . '?php ob_start(); ?>'; $output .= $node->render(); $output .= '<' . '?php \Livewire\Blaze\Memoizer\Memo::put($blaze_memoized_key, ob_get_clean()); ?>'; $output .= '<' . '?php endif; ?>'; $output .= '<' . '?php echo \Livewire\Blaze\Memoizer\Memo::get($blaze_memoized_key); ?>'; return new TextNode($output); } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Nodes/SlotNode.php
src/Nodes/SlotNode.php
<?php namespace Livewire\Blaze\Nodes; class SlotNode extends Node { public function __construct( public string $name, public string $attributes = '', public string $slotStyle = 'standard', public array $children = [], public string $prefix = 'x-slot', public bool $closeHasName = false, ) {} public function getType(): string { return 'slot'; } public function toArray(): array { return [ 'type' => $this->getType(), 'name' => $this->name, 'attributes' => $this->attributes, 'slot_style' => $this->slotStyle, 'prefix' => $this->prefix, 'close_has_name' => $this->closeHasName, 'children' => array_map(fn($child) => $child instanceof Node ? $child->toArray() : $child, $this->children), ]; } public function render(): string { if ($this->slotStyle === 'short') { $output = "<{$this->prefix}:{$this->name}"; if (! empty($this->attributes)) { $output .= " {$this->attributes}"; } $output .= '>'; foreach ($this->children as $child) { $output .= $child instanceof Node ? $child->render() : (string) $child; } // Short syntax may close with </prefix> or </prefix:name>... $output .= $this->closeHasName ? "</{$this->prefix}:{$this->name}>" : "</{$this->prefix}>"; return $output; } $output = "<{$this->prefix}"; if (! empty($this->name)) { $output .= ' name="' . $this->name . '"'; } if (! empty($this->attributes)) { $output .= " {$this->attributes}"; } $output .= '>'; foreach ($this->children as $child) { $output .= $child instanceof Node ? $child->render() : (string) $child; } $output .= "</{$this->prefix}>"; return $output; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Nodes/Node.php
src/Nodes/Node.php
<?php namespace Livewire\Blaze\Nodes; abstract class Node { abstract public function getType(): string; abstract public function toArray(): array; abstract public function render(): string; }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Nodes/TextNode.php
src/Nodes/TextNode.php
<?php namespace Livewire\Blaze\Nodes; class TextNode extends Node { public function __construct( public string $content, ) {} public function getType(): string { return 'text'; } public function toArray(): array { return [ 'type' => $this->getType(), 'content' => $this->content, ]; } public function render(): string { return $this->content; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Nodes/ComponentNode.php
src/Nodes/ComponentNode.php
<?php namespace Livewire\Blaze\Nodes; use Livewire\Blaze\Support\AttributeParser; use Livewire\Blaze\Nodes\SlotNode; use Livewire\Blaze\Nodes\TextNode; class ComponentNode extends Node { public function __construct( public string $name, public string $prefix, public string $attributes = '', public array $children = [], public bool $selfClosing = false, public array $parentsAttributes = [], ) {} public function getType(): string { return 'component'; } public function setParentsAttributes(array $parentsAttributes): void { $this->parentsAttributes = $parentsAttributes; } public function toArray(): array { $array = [ 'type' => $this->getType(), 'name' => $this->name, 'prefix' => $this->prefix, 'attributes' => $this->attributes, 'children' => array_map(fn($child) => $child instanceof Node ? $child->toArray() : $child, $this->children), 'self_closing' => $this->selfClosing, 'parents_attributes' => $this->parentsAttributes, ]; return $array; } public function render(): string { $name = $this->stripNamespaceFromName($this->name, $this->prefix); $output = "<{$this->prefix}{$name}"; if (!empty($this->attributes)) { $output .= " {$this->attributes}"; } if ($this->selfClosing) { return $output . ' />'; } $output .= '>'; foreach ($this->children as $child) { $output .= $child instanceof Node ? $child->render() : (string) $child; } $output .= "</{$this->prefix}{$name}>"; return $output; } public function getAttributesAsRuntimeArrayString(): string { $attributeParser = new AttributeParser(); $attributesArray = $attributeParser->parseAttributeStringToArray($this->attributes); return $attributeParser->parseAttributesArrayToRuntimeArrayString($attributesArray); } public function replaceDynamicPortionsWithPlaceholders(callable $renderNodes): array { $attributePlaceholders = []; $attributeNameToPlaceholder = []; $processedAttributes = (new AttributeParser())->parseAndReplaceDynamics( $this->attributes, $attributePlaceholders, $attributeNameToPlaceholder ); // Map attribute name => original dynamic content (if dynamic) $attributeNameToOriginal = []; foreach ($attributeNameToPlaceholder as $name => $placeholder) { if (isset($attributePlaceholders[$placeholder])) { $attributeNameToOriginal[$name] = $attributePlaceholders[$placeholder]; } } $processedNode = new self( name: $this->name, prefix: $this->prefix, attributes: $processedAttributes, children: [], selfClosing: $this->selfClosing, ); $slotPlaceholders = []; $defaultSlotChildren = []; $namedSlotNames = []; foreach ($this->children as $child) { if ($child instanceof SlotNode) { $slotName = $child->name; if (!empty($slotName) && $slotName !== 'slot') { $slotContent = $renderNodes($child->children); $slotPlaceholders['NAMED_SLOT_' . $slotName] = $slotContent; $namedSlotNames[] = $slotName; } else { foreach ($child->children as $grandChild) { $defaultSlotChildren[] = $grandChild; } } } else { $defaultSlotChildren[] = $child; } } // Emit real <x-slot> placeholder nodes for named slots and separate with zero-output PHP... $count = count($namedSlotNames); foreach ($namedSlotNames as $index => $name) { if ($index > 0) { $processedNode->children[] = new TextNode('<?php /*blaze_sep*/ ?>'); } $processedNode->children[] = new SlotNode( name: $name, attributes: '', slotStyle: 'standard', children: [new TextNode('NAMED_SLOT_' . $name)], prefix: 'x-slot', ); } $defaultPlaceholder = null; if (!empty($defaultSlotChildren)) { if ($count > 0) { // Separate last named slot from default content with zero-output PHP... $processedNode->children[] = new TextNode('<?php /*blaze_sep*/ ?>'); } $defaultPlaceholder = 'SLOT_PLACEHOLDER_' . count($slotPlaceholders); $renderedDefault = $renderNodes($defaultSlotChildren); $slotPlaceholders[$defaultPlaceholder] = ($count > 0) ? trim($renderedDefault) : $renderedDefault; $processedNode->children[] = new TextNode($defaultPlaceholder); } else { $processedNode->children[] = new TextNode(''); } $restore = function (string $renderedHtml) use ($slotPlaceholders, $attributePlaceholders, $defaultPlaceholder): string { // Replace slot placeholders first... foreach ($slotPlaceholders as $placeholder => $content) { if ($placeholder === $defaultPlaceholder) { // Trim whitespace immediately around the default placeholder position... $pattern = '/\s*' . preg_quote($placeholder, '/') . '\s*/'; $renderedHtml = preg_replace($pattern, $content, $renderedHtml); } else { $renderedHtml = str_replace($placeholder, $content, $renderedHtml); } } // Restore attribute placeholders... foreach ($attributePlaceholders as $placeholder => $original) { $renderedHtml = str_replace($placeholder, $original, $renderedHtml); } return $renderedHtml; }; return [$processedNode, $slotPlaceholders, $restore, $attributeNameToPlaceholder, $attributeNameToOriginal, $this->attributes]; } public function mergeAwareAttributes(array $awareAttributes): void { $attributeParser = new AttributeParser(); // Attributes are a string of attributes in the format: // `name1="value1" name2="value2" name3="value3"` // So we need to convert that attributes string to an array of attributes with the format: // [ // 'name' => [ // 'isDynamic' => true, // 'value' => '$name', // 'original' => ':name="$name"', // ], // ] $attributes = $attributeParser->parseAttributeStringToArray($this->attributes); $parentsAttributes = []; // Parents attributes are an array of attributes strings in the same format // as above so we also need to convert them to an array of attributes... foreach ($this->parentsAttributes as $parentAttributes) { $parentsAttributes[] = $attributeParser->parseAttributeStringToArray($parentAttributes); } // Now we can take the aware attributes and merge them with the components attributes... foreach ($awareAttributes as $key => $value) { // As `$awareAttributes` is an array of attributes, which can either have just // a value, which is the attribute name, or a key-value pair, which is the // attribute name and a default value... if (is_int($key)) { $attributeName = $value; $attributeValue = null; $defaultValue = null; } else { $attributeName = $key; $attributeValue = $value; $defaultValue = [ 'isDynamic' => false, 'value' => $attributeValue, 'original' => $attributeName . '="' . $attributeValue . '"', ]; } if (isset($attributes[$attributeName])) { continue; } // Loop through the parents attributes in reverse order so that the last parent // attribute that matches the attribute name is used... foreach (array_reverse($parentsAttributes) as $parsedParentAttributes) { // If an attribute is found, then use it and stop searching... if (isset($parsedParentAttributes[$attributeName])) { $attributes[$attributeName] = $parsedParentAttributes[$attributeName]; break; } } // If the attribute is not set then fall back to using the aware value. // We need to add it in the same format as the other attributes... if (! isset($attributes[$attributeName]) && $defaultValue !== null) { $attributes[$attributeName] = $defaultValue; } } // Convert the parsed attributes back to a string with the original format: // `name1="value1" name2="value2" name3="value3"` $this->attributes = $attributeParser->parseAttributesArrayToPropString($attributes); } protected function stripNamespaceFromName(string $name, string $prefix): string { $prefixes = [ 'flux:' => [ 'namespace' => 'flux::' ], 'x:' => [ 'namespace' => '' ], 'x-' => [ 'namespace' => '' ], ]; if (isset($prefixes[$prefix])) { $namespace = $prefixes[$prefix]['namespace']; if (!empty($namespace) && str_starts_with($name, $namespace)) { return substr($name, strlen($namespace)); } } return $name; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Parser/Parser.php
src/Parser/Parser.php
<?php namespace Livewire\Blaze\Parser; use Livewire\Blaze\Tokenizer\Tokens\TagSelfCloseToken; use Livewire\Blaze\Tokenizer\Tokens\SlotCloseToken; use Livewire\Blaze\Tokenizer\Tokens\TagCloseToken; use Livewire\Blaze\Tokenizer\Tokens\SlotOpenToken; use Livewire\Blaze\Tokenizer\Tokens\TagOpenToken; use Livewire\Blaze\Tokenizer\Tokens\TextToken; use Livewire\Blaze\Nodes\ComponentNode; use Livewire\Blaze\Nodes\TextNode; use Livewire\Blaze\Nodes\SlotNode; class Parser { public function parse(array $tokens): array { $stack = new ParseStack(); foreach ($tokens as $token) { match(get_class($token)) { TagOpenToken::class => $this->handleTagOpen($token, $stack), TagSelfCloseToken::class => $this->handleTagSelfClose($token, $stack), TagCloseToken::class => $this->handleTagClose($token, $stack), SlotOpenToken::class => $this->handleSlotOpen($token, $stack), SlotCloseToken::class => $this->handleSlotClose($token, $stack), TextToken::class => $this->handleText($token, $stack), default => throw new \RuntimeException('Unknown token type: ' . get_class($token)) }; } return $stack->getAst(); } protected function handleTagOpen(TagOpenToken $token, ParseStack $stack): void { $node = new ComponentNode( name: $token->namespace . $token->name, prefix: $token->prefix, attributes: $token->attributes, children: [], selfClosing: false ); $stack->pushContainer($node); } protected function handleTagSelfClose(TagSelfCloseToken $token, ParseStack $stack): void { $node = new ComponentNode( name: $token->namespace . $token->name, prefix: $token->prefix, attributes: $token->attributes, children: [], selfClosing: true ); $stack->addToRoot($node); } protected function handleTagClose(TagCloseToken $token, ParseStack $stack): void { $stack->popContainer(); } protected function handleSlotOpen(SlotOpenToken $token, ParseStack $stack): void { $node = new SlotNode( name: $token->name ?? '', attributes: $token->attributes, slotStyle: $token->slotStyle, children: [], prefix: $token->prefix, closeHasName: false, ); $stack->pushContainer($node); } protected function handleSlotClose(SlotCloseToken $token, ParseStack $stack): void { $closed = $stack->popContainer(); if ($closed instanceof SlotNode && $closed->slotStyle === 'short') { // If tokenizer captured a :name on the close tag, mark it if (! empty($token->name)) { $closed->closeHasName = true; } } } protected function handleText(TextToken $token, ParseStack $stack): void { // Always preserve text content, including whitespace... $node = new TextNode(content: $token->content); $stack->addToRoot($node); } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Parser/ParseStack.php
src/Parser/ParseStack.php
<?php namespace Livewire\Blaze\Parser; use Livewire\Blaze\Nodes\ComponentNode; use Livewire\Blaze\Nodes\SlotNode; use Livewire\Blaze\Nodes\Node; class ParseStack { protected array $stack = []; protected array $ast = []; public function addToRoot(Node $node): void { if (empty($this->stack)) { $this->ast[] = $node; } else { $current = $this->getCurrentContainer(); if ($current instanceof ComponentNode || $current instanceof SlotNode) { $current->children[] = $node; } else { // Fallback: if current container cannot accept children, append to root... $this->ast[] = $node; } } } public function pushContainer(Node $container): void { $this->addToRoot($container); $this->stack[] = $container; } public function popContainer(): ?Node { if (! empty($this->stack)) { return array_pop($this->stack); } return null; } public function getCurrentContainer(): ?Node { return empty($this->stack) ? null : end($this->stack); } public function getAst(): array { return $this->ast; } public function isEmpty(): bool { return empty($this->stack); } public function depth(): int { return count($this->stack); } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/State.php
src/Tokenizer/State.php
<?php namespace Livewire\Blaze\Tokenizer; enum State: string { case TEXT = 'TEXT'; case TAG_OPEN = 'TAG_OPEN'; case TAG_NAME = 'TAG_NAME'; case ATTRIBUTE_NAME = 'ATTRIBUTE_NAME'; case ATTRIBUTE_VALUE = 'ATTRIBUTE_VALUE'; case SLOT = 'SLOT'; case SLOT_NAME = 'SLOT_NAME'; case TAG_CLOSE = 'TAG_CLOSE'; case SLOT_CLOSE = 'SLOT_CLOSE'; case SHORT_SLOT = 'SHORT_SLOT'; }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/Tokenizer.php
src/Tokenizer/Tokenizer.php
<?php namespace Livewire\Blaze\Tokenizer; use Livewire\Blaze\Tokenizer\Tokens\TagSelfCloseToken; use Livewire\Blaze\Tokenizer\Tokens\SlotCloseToken; use Livewire\Blaze\Tokenizer\Tokens\SlotOpenToken; use Livewire\Blaze\Tokenizer\Tokens\TagCloseToken; use Livewire\Blaze\Tokenizer\Tokens\TagOpenToken; use Livewire\Blaze\Tokenizer\Tokens\TextToken; use Livewire\Blaze\Tokenizer\Tokens\Token; class Tokenizer { protected array $prefixes = [ 'flux:' => [ 'namespace' => 'flux::', 'slot' => 'x-slot', ], 'x:' => [ 'namespace' => '', 'slot' => 'x-slot', ], 'x-' => [ 'namespace' => '', 'slot' => 'x-slot', ], ]; protected string $content = ''; protected int $position = 0; protected int $length = 0; protected array $tokens = []; protected string $buffer = ''; protected ?Token $currentToken = null; protected array $tagStack = []; protected string $currentPrefix = ''; protected string $currentSlotPrefix = ''; public function tokenize(string $content): array { $this->resetTokenizer($content); $state = State::TEXT; while (!$this->isAtEnd()) { $state = match($state) { State::TEXT => $this->handleTextState(), State::TAG_OPEN => $this->handleTagOpenState(), State::TAG_CLOSE => $this->handleTagCloseState(), State::ATTRIBUTE_NAME => $this->handleAttributeState(), State::SLOT => $this->handleSlotState(), State::SLOT_CLOSE => $this->handleSlotCloseState(), State::SHORT_SLOT => $this->handleShortSlotState(), default => throw new \RuntimeException("Unknown state: $state"), }; } $this->flushBuffer(); return $this->tokens; } protected function resetTokenizer(string $content): void { $this->content = $content; $this->position = 0; $this->length = strlen($content); $this->tokens = []; $this->buffer = ''; $this->currentToken = null; $this->tagStack = []; $this->currentPrefix = ''; $this->currentSlotPrefix = ''; } protected function handleTextState(): State { $char = $this->current(); // Check for slot tags first... if ($char === '<') { if ($slotInfo = $this->matchSlotOpen()) { $this->flushBuffer(); $this->currentSlotPrefix = $slotInfo['prefix']; if ($slotInfo['isShort']) { $this->currentToken = new SlotOpenToken(slotStyle: 'short', prefix: $slotInfo['prefix']); $this->advance(strlen('<' . $slotInfo['prefix'] . ':')); return State::SHORT_SLOT; } else { $this->currentToken = new SlotOpenToken(slotStyle: 'standard', prefix: $slotInfo['prefix']); $this->advance(strlen('<' . $slotInfo['prefix'])); return State::SLOT; } } if ($slotInfo = $this->matchSlotClose()) { $this->flushBuffer(); $this->currentToken = new SlotCloseToken(); $this->currentSlotPrefix = $slotInfo['prefix']; $this->advance(strlen('</' . $slotInfo['prefix'])); return State::SLOT_CLOSE; } if ($prefixInfo = $this->matchComponentOpen()) { $this->flushBuffer(); $this->currentPrefix = $prefixInfo['prefix']; $this->currentToken = new TagOpenToken( name: '', prefix: $prefixInfo['prefix'], namespace: $prefixInfo['namespace'] ); $this->advance(strlen('<' . $prefixInfo['prefix'])); return State::TAG_OPEN; } if ($this->peek(1) === '/' && ($prefixInfo = $this->matchComponentClose())) { $this->flushBuffer(); $this->currentPrefix = $prefixInfo['prefix']; $this->currentToken = new TagCloseToken( name: '', prefix: $prefixInfo['prefix'], namespace: $prefixInfo['namespace'] ); $this->advance(strlen('</' . $prefixInfo['prefix'])); return State::TAG_CLOSE; } } // Regular text... $this->buffer .= $char; $this->advance(); return State::TEXT; } protected function handleTagOpenState(): State { if ($name = $this->matchTagName()) { $this->currentToken->name = $name; $this->tagStack[] = $name; $this->advance(strlen($name)); return State::ATTRIBUTE_NAME; } $this->advance(); return State::TAG_OPEN; } protected function handleTagCloseState(): State { if ($name = $this->matchTagName()) { $this->currentToken->name = $name; array_pop($this->tagStack); $this->advance(strlen($name)); if ($this->current() === '>') { $this->tokens[] = $this->currentToken; $this->advance(); return State::TEXT; } } $this->advance(); return State::TAG_CLOSE; } protected function handleAttributeState(): State { $char = $this->current(); // Skip whitespace... if ($char === ' ') { $this->advance(); return State::ATTRIBUTE_NAME; } // End of tag... if ($char === '>') { $this->tokens[] = $this->currentToken; $this->advance(); return State::TEXT; } // Self-closing tag... if ($char === '/' && $this->peek() === '>') { $this->currentToken = new TagSelfCloseToken( name: $this->currentToken->name, prefix: $this->currentToken->prefix, namespace: $this->currentToken->namespace, attributes: $this->currentToken->attributes ); array_pop($this->tagStack); $this->tokens[] = $this->currentToken; $this->advance(2); return State::TEXT; } $attributes = $this->collectAttributes(); if ($attributes !== null) { $this->currentToken->attributes = $attributes; } return State::ATTRIBUTE_NAME; } protected function handleSlotState(): State { $char = $this->current(); if ($char === ' ') { $this->advance(); return State::SLOT; } // Check for name attribute if ($this->match('/^name="([^"]+)"/')) { $matches = []; preg_match('/^name="([^"]+)"/', $this->remaining(), $matches); $this->currentToken->name = $matches[1]; $this->advance(strlen($matches[0])); return State::ATTRIBUTE_NAME; } if ($char === '>') { $this->tokens[] = $this->currentToken; $this->advance(); return State::TEXT; } $this->advance(); return State::SLOT; } protected function handleSlotCloseState(): State { // Check for slot:name pattern... if ($this->match('/^:[a-zA-Z0-9-]+/')) { $matches = []; preg_match('/^:[a-zA-Z0-9-]+/', $this->remaining(), $matches); $this->currentToken->name = substr($matches[0], 1); $this->advance(strlen($matches[0])); } if ($this->current() === '>') { $this->tokens[] = $this->currentToken; $this->advance(); return State::TEXT; } $this->advance(); return State::SLOT_CLOSE; } protected function handleShortSlotState(): State { if ($name = $this->matchSlotName()) { $this->currentToken->name = $name; $this->advance(strlen($name)); // Collect attributes until >... $attrBuffer = ''; while (! $this->isAtEnd() && $this->current() !== '>') { $attrBuffer .= $this->current(); $this->advance(); } if (trim($attrBuffer) !== '') { $this->currentToken->attributes = trim($attrBuffer); } if ($this->current() === '>') { $this->tokens[] = $this->currentToken; $this->advance(); return State::TEXT; } } $this->advance(); return State::SHORT_SLOT; } protected function collectAttributes(): ?string { $attrString = ''; $inSingleQuote = false; $inDoubleQuote = false; $braceCount = 0; $bracketCount = 0; $parenCount = 0; while (!$this->isAtEnd()) { $char = $this->current(); $prevChar = $this->position > 0 ? $this->content[$this->position - 1] : ''; // Track quote state... if ($char === '"' && !$inSingleQuote && $prevChar !== '\\') { $inDoubleQuote = !$inDoubleQuote; } elseif ($char === "'" && !$inDoubleQuote && $prevChar !== '\\') { $inSingleQuote = !$inSingleQuote; } // Track nesting only outside quotes... if (!$inSingleQuote && !$inDoubleQuote) { match($char) { '{' => $braceCount++, '}' => $braceCount--, '[' => $bracketCount++, ']' => $bracketCount--, '(' => $parenCount++, ')' => $parenCount--, default => null }; } // Check for end of attributes... if (($char === '>' || ($char === '/' && $this->peek() === '>')) && !$inSingleQuote && !$inDoubleQuote && $braceCount === 0 && $bracketCount === 0 && $parenCount === 0) { break; } $attrString .= $char; $this->advance(); } return trim($attrString) !== '' ? trim($attrString) : null; } protected function matchSlotOpen(): ?array { foreach ($this->prefixes as $prefix => $config) { $slotPrefix = $config['slot']; // Check for short slot syntax... if ($this->matchesAt('<' . $slotPrefix . ':')) { return ['prefix' => $slotPrefix, 'isShort' => true]; } // Check for standard slot syntax... if ($this->matchesAt('<' . $slotPrefix)) { $nextChar = $this->peek(strlen('<' . $slotPrefix)); if ($nextChar !== ':') { return ['prefix' => $slotPrefix, 'isShort' => false]; } } } return null; } protected function matchSlotClose(): ?array { foreach ($this->prefixes as $prefix => $config) { $slotPrefix = $config['slot']; if ($this->matchesAt('</' . $slotPrefix)) { return ['prefix' => $slotPrefix]; } } return null; } protected function matchComponentOpen(): ?array { foreach ($this->prefixes as $prefix => $config) { if ($this->matchesAt('<' . $prefix)) { return [ 'prefix' => $prefix, 'namespace' => $config['namespace'] ?? '' ]; } } return null; } protected function matchComponentClose(): ?array { foreach ($this->prefixes as $prefix => $config) { if ($this->matchesAt('</' . $prefix)) { return [ 'prefix' => $prefix, 'namespace' => $config['namespace'] ?? '' ]; } } return null; } protected function matchTagName(): ?string { if (preg_match('/^[a-zA-Z0-9-\.:]+/', $this->remaining(), $matches)) { return $matches[0]; } return null; } protected function matchSlotName(): ?string { if (preg_match('/^[a-zA-Z0-9-]+/', $this->remaining(), $matches)) { return $matches[0]; } return null; } protected function match(string $pattern): bool { return preg_match($pattern, $this->remaining()) === 1; } protected function matchesAt(string $string): bool { return substr($this->content, $this->position, strlen($string)) === $string; } protected function current(): string { return $this->isAtEnd() ? '' : $this->content[$this->position]; } protected function peek(int $offset = 1): string { $pos = $this->position + $offset; return $pos >= $this->length ? '' : $this->content[$pos]; } protected function remaining(): string { return substr($this->content, $this->position); } protected function advance(int $count = 1): void { $this->position += $count; } protected function isAtEnd(): bool { return $this->position >= $this->length; } protected function flushBuffer(): void { if ($this->buffer !== '') { $this->tokens[] = new TextToken($this->buffer); $this->buffer = ''; } } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/Tokens/Token.php
src/Tokenizer/Tokens/Token.php
<?php namespace Livewire\Blaze\Tokenizer\Tokens; abstract class Token { abstract public function getType(): string; abstract public function toArray(): array; }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/Tokens/TagOpenToken.php
src/Tokenizer/Tokens/TagOpenToken.php
<?php namespace Livewire\Blaze\Tokenizer\Tokens; class TagOpenToken extends Token { public function __construct( public string $name, public string $prefix, public string $namespace = '', public string $attributes = '', ) {} public function getType(): string { return 'tag_open'; } public function toArray(): array { return [ 'type' => $this->getType(), 'name' => $this->name, 'prefix' => $this->prefix, 'namespace' => $this->namespace, 'attributes' => $this->attributes, ]; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/Tokens/TagSelfCloseToken.php
src/Tokenizer/Tokens/TagSelfCloseToken.php
<?php namespace Livewire\Blaze\Tokenizer\Tokens; class TagSelfCloseToken extends Token { public function __construct( public string $name, public string $prefix, public string $namespace = '', public string $attributes = '', ) {} public function getType(): string { return 'tag_self_close'; } public function toArray(): array { return [ 'type' => $this->getType(), 'name' => $this->name, 'prefix' => $this->prefix, 'namespace' => $this->namespace, 'attributes' => $this->attributes, ]; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/Tokens/SlotCloseToken.php
src/Tokenizer/Tokens/SlotCloseToken.php
<?php namespace Livewire\Blaze\Tokenizer\Tokens; class SlotCloseToken extends Token { public function __construct( public ?string $name = null, public string $prefix = 'x-', ) {} public function getType(): string { return 'slot_close'; } public function toArray(): array { return [ 'type' => $this->getType(), 'name' => $this->name, ]; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/Tokens/TagCloseToken.php
src/Tokenizer/Tokens/TagCloseToken.php
<?php namespace Livewire\Blaze\Tokenizer\Tokens; class TagCloseToken extends Token { public function __construct( public string $name, public string $prefix, public string $namespace = '', ) {} public function getType(): string { return 'tag_close'; } public function toArray(): array { return [ 'type' => $this->getType(), 'name' => $this->name, 'prefix' => $this->prefix, 'namespace' => $this->namespace, ]; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/Tokens/TextToken.php
src/Tokenizer/Tokens/TextToken.php
<?php namespace Livewire\Blaze\Tokenizer\Tokens; class TextToken extends Token { public function __construct( public string $content, ) {} public function getType(): string { return 'text'; } public function toArray(): array { return [ 'type' => $this->getType(), 'content' => $this->content, ]; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Tokenizer/Tokens/SlotOpenToken.php
src/Tokenizer/Tokens/SlotOpenToken.php
<?php namespace Livewire\Blaze\Tokenizer\Tokens; class SlotOpenToken extends Token { public function __construct( public ?string $name = null, public string $attributes = '', public string $slotStyle = 'standard', public string $prefix = 'x-', ) {} public function getType(): string { return 'slot_open'; } public function toArray(): array { return [ 'type' => $this->getType(), 'name' => $this->name, 'attributes' => $this->attributes, 'slot_style' => $this->slotStyle, ]; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Walker/Walker.php
src/Walker/Walker.php
<?php namespace Livewire\Blaze\Walker; use Livewire\Blaze\Nodes\ComponentNode; use Livewire\Blaze\Nodes\SlotNode; class Walker { public function walk(array $nodes, callable $preCallback, callable $postCallback): array { $result = []; foreach ($nodes as $node) { $processed = $preCallback($node); if (($node instanceof ComponentNode || $node instanceof SlotNode) && !empty($node->children)) { $node->children = $this->walk($node->children, $preCallback, $postCallback); } $processed = $postCallback($node); $result[] = $processed ?? $node; } return $result; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Directive/BlazeDirective.php
src/Directive/BlazeDirective.php
<?php namespace Livewire\Blaze\Directive; use Illuminate\Support\Facades\Blade; class BlazeDirective { public static function registerFallback(): void { Blade::directive('blaze', fn () => ''); } public static function getParameters(string $source): ?array { // If there is no @blaze directive, return null if (! preg_match('/^\s*(?:\/\*.*?\*\/\s*)*@blaze(?:\s*\(([^)]+)\))?/s', $source, $matches)) { return null; } // If there are no parameters, return an empty array if (empty($matches[1])) { return []; } return self::parseParameters($matches[1]); } /** * Parse directive parameters * * For example, the string: * "fold: false" * * will be parsed into the array: * [ * 'fold' => false, * ] */ protected static function parseParameters(string $paramString): array { $params = []; // Simple parameter parsing for key:value pairs if (preg_match_all('/(\w+)\s*:\s*(\w+)/', $paramString, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $key = $match[1]; $value = $match[2]; // Convert string boolean values if (in_array(strtolower($value), ['true', 'false'])) { $params[$key] = strtolower($value) === 'true'; } else { $params[$key] = $value; } } } return $params; } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Folder/Folder.php
src/Folder/Folder.php
<?php namespace Livewire\Blaze\Folder; use Livewire\Blaze\Exceptions\LeftoverPlaceholdersException; use Livewire\Blaze\Exceptions\InvalidBlazeFoldUsageException; use Livewire\Blaze\Support\AttributeParser; use Livewire\Blaze\Events\ComponentFolded; use Livewire\Blaze\Nodes\ComponentNode; use Illuminate\Support\Facades\Event; use Livewire\Blaze\Nodes\TextNode; use Livewire\Blaze\Nodes\SlotNode; use Livewire\Blaze\Nodes\Node; use Livewire\Blaze\Directive\BlazeDirective; class Folder { protected $renderBlade; protected $renderNodes; protected $componentNameToPath; public function __construct(callable $renderBlade, callable $renderNodes, callable $componentNameToPath) { $this->renderBlade = $renderBlade; $this->renderNodes = $renderNodes; $this->componentNameToPath = $componentNameToPath; } public function isFoldable(Node $node): bool { if (! $node instanceof ComponentNode) { return false; } try { $componentPath = ($this->componentNameToPath)($node->name); if (empty($componentPath) || !file_exists($componentPath)) { return false; } $source = file_get_contents($componentPath); $directiveParameters = BlazeDirective::getParameters($source); if (is_null($directiveParameters)) { return false; } // Default to true if fold parameter is not specified return $directiveParameters['fold'] ?? true; } catch (\Exception $e) { return false; } } public function fold(Node $node): Node { if (! $node instanceof ComponentNode) { return $node; } if (! $this->isFoldable($node)) { return $node; } /** @var ComponentNode $component */ $component = $node; try { $componentPath = ($this->componentNameToPath)($component->name); if (file_exists($componentPath)) { $source = file_get_contents($componentPath); $this->validateFoldableComponent($source, $componentPath); $directiveParameters = BlazeDirective::getParameters($source); // Default to true if aware parameter is not specified if ($directiveParameters['aware'] ?? true) { $awareAttributes = $this->getAwareDirectiveAttributes($source); if (! empty($awareAttributes)) { $component->mergeAwareAttributes($awareAttributes); } } } [$processedNode, $slotPlaceholders, $restore, $attributeNameToPlaceholder, $attributeNameToOriginal, $rawAttributes] = $component->replaceDynamicPortionsWithPlaceholders( renderNodes: fn (array $nodes) => ($this->renderNodes)($nodes) ); $usageBlade = ($this->renderNodes)([$processedNode]); $renderedHtml = ($this->renderBlade)($usageBlade); $finalHtml = $restore($renderedHtml); $shouldInjectAwareMacros = $this->hasAwareDescendant($component); if ($shouldInjectAwareMacros) { $dataArrayLiteral = $this->buildRuntimeDataArray($attributeNameToOriginal, $rawAttributes); if ($dataArrayLiteral !== '[]') { $finalHtml = '<?php $__env->pushConsumableComponentData(' . $dataArrayLiteral . '); ?>' . $finalHtml . '<?php $__env->popConsumableComponentData(); ?>'; } } if ($this->containsLeftoverPlaceholders($finalHtml)) { $summary = $this->summarizeLeftoverPlaceholders($finalHtml); throw new LeftoverPlaceholdersException($component->name, $summary, substr($finalHtml, 0, 2000)); } Event::dispatch(new ComponentFolded( name: $component->name, path: $componentPath, filemtime: filemtime($componentPath) )); return new TextNode($finalHtml); } catch (InvalidBlazeFoldUsageException $e) { throw $e; } catch (\Exception $e) { if (app('blaze')->isDebugging()) { throw $e; } return $component; } } protected function validateFoldableComponent(string $source, string $componentPath): void { // Strip out @unblaze blocks before validation since they can contain dynamic content $sourceWithoutUnblaze = $this->stripUnblazeBlocks($source); $problematicPatterns = [ '@once' => 'forOnce', '\\$errors' => 'forErrors', 'session\\(' => 'forSession', '@error\\(' => 'forError', '@csrf' => 'forCsrf', 'auth\\(\\)' => 'forAuth', 'request\\(\\)' => 'forRequest', 'old\\(' => 'forOld', ]; foreach ($problematicPatterns as $pattern => $factoryMethod) { if (preg_match('/' . $pattern . '/', $sourceWithoutUnblaze)) { throw InvalidBlazeFoldUsageException::{$factoryMethod}($componentPath); } } } protected function stripUnblazeBlocks(string $source): string { // Remove content between @unblaze and @endunblaze (including the directives themselves) return preg_replace('/@unblaze.*?@endunblaze/s', '', $source); } protected function buildRuntimeDataArray(array $attributeNameToOriginal, string $rawAttributes): string { $pairs = []; // Dynamic attributes -> original expressions... foreach ($attributeNameToOriginal as $name => $original) { $key = $this->toCamelCase($name); if (preg_match('/\{\{\s*\$([a-zA-Z0-9_]+)\s*\}\}/', $original, $m)) { $pairs[$key] = '$' . $m[1]; } else { $pairs[$key] = var_export($original, true); } } // Static attributes from the original attribute string... if (! empty($rawAttributes)) { if (preg_match_all('/\b([a-zA-Z0-9_-]+)="([^"]*)"/', $rawAttributes, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $name = $m[1]; $value = $m[2]; $key = $this->toCamelCase($name); if (! isset($pairs[$key])) { $pairs[$key] = var_export($value, true); } } } } if (empty($pairs)) return '[]'; $parts = []; foreach ($pairs as $name => $expr) { $parts[] = var_export($name, true) . ' => ' . $expr; } return '[' . implode(', ', $parts) . ']'; } protected function getAwareDirectiveAttributes(string $source): array { preg_match('/@aware\(\[(.*?)\]\)/s', $source, $matches); if (empty($matches[1])) { return []; } $attributeParser = new AttributeParser(); return $attributeParser->parseArrayStringIntoArray($matches[1]); } protected function hasAwareDescendant(Node $node): bool { $children = []; if ($node instanceof ComponentNode || $node instanceof SlotNode) { $children = $node->children; } foreach ($children as $child) { if ($child instanceof ComponentNode) { $path = ($this->componentNameToPath)($child->name); if ($path && file_exists($path)) { $source = file_get_contents($path); if (preg_match('/@aware/', $source)) { return true; } } if ($this->hasAwareDescendant($child)) { return true; } } elseif ($child instanceof SlotNode) { if ($this->hasAwareDescendant($child)) { return true; } } } return false; } protected function toCamelCase(string $name): string { $name = str_replace(['-', '_'], ' ', $name); $name = ucwords($name); $name = str_replace(' ', '', $name); return lcfirst($name); } protected function containsLeftoverPlaceholders(string $html): bool { return (bool) preg_match('/\b(SLOT_PLACEHOLDER_\d+|ATTR_PLACEHOLDER_\d+|NAMED_SLOT_[A-Za-z0-9_-]+)\b/', $html); } protected function summarizeLeftoverPlaceholders(string $html): string { preg_match_all('/\b(SLOT_PLACEHOLDER_\d+|ATTR_PLACEHOLDER_\d+|NAMED_SLOT_[A-Za-z0-9_-]+)\b/', $html, $matches); $counts = array_count_values($matches[1] ?? []); $parts = []; foreach ($counts as $placeholder => $count) { $parts[] = $placeholder . ' x' . $count; } return implode(', ', $parts); } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/src/Events/ComponentFolded.php
src/Events/ComponentFolded.php
<?php namespace Livewire\Blaze\Events; class ComponentFolded { public function __construct( public string $name, public string $path, public int $filemtime ) {} }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/BenchmarkTest.php
tests/BenchmarkTest.php
<?php use Illuminate\Support\Facades\View; beforeEach(function () { // Register anonymous components used by the benchmark app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); }); function render($viewFile, $enabled = false) { clearCache(); // Warm up the compiler/cache... View::file($viewFile)->render(); // Run the benchmark... $iterations = 1; // single run of a 25k loop inside the view $start = microtime(true); for ($i = 0; $i < $iterations; $i++) { View::file($viewFile)->render(); } $duration = (microtime(true) - $start) * 1000; // ms return $duration; } function clearCache() { $files = glob(__DIR__ . '/../vendor/orchestra/testbench-core/laravel/storage/framework/views/*'); foreach ($files as $file) { if (!str_ends_with($file, '.gitignore')) { if (is_dir($file)) { rmdir($file); } else { unlink($file); } } } } it('can run performance benchmarks', function () { app('blaze')->enable(); $viewFile = __DIR__ . '/fixtures/benchmark/simple-button-in-loop.blade.php'; $duration = render($viewFile, enabled: false); fwrite(STDOUT, "Blaze enabled - render 25k component loop: " . number_format($duration, 2) . " ms\n"); app('blaze')->disable(); $viewFile = __DIR__ . '/fixtures/benchmark/simple-button-in-loop.blade.php'; $duration = render($viewFile, enabled: false); fwrite(STDOUT, "Blaze disabled - render 25k component loop: " . number_format($duration, 2) . " ms\n"); app('blaze')->enable(); $viewFile = __DIR__ . '/fixtures/benchmark/no-fold-button-in-loop.blade.php'; $duration = render($viewFile, enabled: false); fwrite(STDOUT, "Blaze enabled but no folding - render 25k component loop: " . number_format($duration, 2) . " ms\n"); expect(true)->toBeTrue(); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/BlazeTest.php
tests/BlazeTest.php
<?php use Illuminate\Support\Facades\View; describe('blaze integration', function () { beforeEach(function () { // Configure Blade to find our test components and views app('blade.compiler')->anonymousComponentNamespace('', 'x'); app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); // Add view path for our test pages View::addLocation(__DIR__ . '/fixtures/pages'); }); it('renders foldable components as optimized html through blade facade', function () { // This is still outside-in - we're using Laravel's Blade facade, not calling Blaze directly $template = ' <div class="page"> <h1>Integration Test</h1> <x-button>Save Changes</x-button> <x-card> <x-alert message="Success!" /> </x-card> </div>'; $rendered = \Illuminate\Support\Facades\Blade::render($template); // Foldable components should be folded to optimized HTML expect($rendered)->toContain('<button type="button">Save Changes</button>'); expect($rendered)->toContain('<div class="card">'); expect($rendered)->toContain('<div class="alert">Success!</div>'); expect($rendered)->not->toContain('<x-button>'); expect($rendered)->not->toContain('<x-card>'); expect($rendered)->not->toContain('<x-alert'); // Should contain the page structure expect($rendered)->toContain('<div class="page">'); expect($rendered)->toContain('<h1>Integration Test</h1>'); }); it('leaves unfoldable components unchanged through blade facade', function () { $template = '<div><x-unfoldable-button>Test Button</x-unfoldable-button></div>'; $rendered = \Illuminate\Support\Facades\Blade::render($template); // Unfoldable component should render normally (not folded) expect($rendered)->toContain('<button type="button">Test Button</button>'); expect($rendered)->not->toContain('<x-unfoldable-button>'); // Just verify it renders normally }); it('throws exception for components with invalid foldable usage', function () { expect(fn() => \Illuminate\Support\Facades\Blade::render('<x-invalid-foldable.errors>Test</x-invalid-foldable.errors>')) ->toThrow(\Livewire\Blaze\Exceptions\InvalidBlazeFoldUsageException::class); }); it('preserves slot content when folding components', function () { $template = '<x-card><h2>Dynamic Title</h2><p>Dynamic content with <em>emphasis</em></p></x-card>'; $rendered = \Illuminate\Support\Facades\Blade::render($template); // Should preserve all slot content in folded output expect($rendered)->toContain('<h2>Dynamic Title</h2>'); expect($rendered)->toContain('<p>Dynamic content with <em>emphasis</em></p>'); expect($rendered)->toContain('<div class="card">'); expect($rendered)->not->toContain('<x-card>'); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/CacheInvalidationTest.php
tests/CacheInvalidationTest.php
<?php describe('cache invalidation', function () { beforeEach(function () { app('blade.compiler')->anonymousComponentNamespace('', 'x'); app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); }); function compileWithFrontmatter(string $input): string { return app('blaze')->collectAndAppendFrontMatter($input, function($template) { return app('blaze')->compile($template); }); } it('embeds folded component metadata as frontmatter', function () { $input = '<x-button>Save</x-button>'; $output = compileWithFrontmatter($input); // Check that frontmatter exists with component metadata expect($output)->toContain('<'.'?php # [BlazeFolded]:'); expect($output)->toContain('{'.__DIR__ . '/fixtures/components/button.blade.php}'); expect($output)->toContain('{button}'); }); it('dispatches ComponentFolded events during compilation', function () { \Illuminate\Support\Facades\Event::fake([\Livewire\Blaze\Events\ComponentFolded::class]); $input = '<x-button>Save</x-button>'; app('blaze')->compile($input); \Illuminate\Support\Facades\Event::assertDispatched(\Livewire\Blaze\Events\ComponentFolded::class, function($event) { return $event->name === 'button' && str_contains($event->path, 'button.blade.php') && is_int($event->filemtime); }); }); it('parses frontmatter correctly', function () { $frontMatter = new \Livewire\Blaze\FrontMatter(); // First, let's see what the actual frontmatter looks like $input = '<x-button>Save</x-button>'; $output = compileWithFrontmatter($input); // Debug: show what the actual output looks like // echo "Actual output: " . $output . "\n"; $parsed = $frontMatter->parseFromTemplate($output); expect($parsed)->toHaveCount(1); }); it('detects expired folded dependencies', function () { $frontMatter = new \Livewire\Blaze\FrontMatter(); // Get the actual generated frontmatter format first $input = '<x-button>Save</x-button>'; $actualOutput = compileWithFrontmatter($input); // Now test with current filemtime (not expired) expect($frontMatter->sourceContainsExpiredFoldedDependencies($actualOutput))->toBeFalse(); // Test with old filemtime by manually creating expired data $buttonPath = __DIR__ . '/fixtures/components/button.blade.php'; $currentFilemtime = filemtime($buttonPath); $oldFilemtime = $currentFilemtime - 3600; // 1 hour ago // Create expired frontmatter manually $expiredFrontmatter = "<?php # [BlazeFolded]:{button}:{{$buttonPath}}:{{$oldFilemtime}} ?>\n"; $expiredOutput = $expiredFrontmatter . "<button type=\"button\">Save</button>"; // Check parsing $parsed = $frontMatter->parseFromTemplate($expiredOutput); expect($parsed)->toHaveCount(1); expect((int)$parsed[0][3])->toBeLessThan($currentFilemtime); // old filemtime should be less than current expect($frontMatter->sourceContainsExpiredFoldedDependencies($expiredOutput))->toBeTrue(); // Test with non-existent file (expired) $missingOutput = str_replace($buttonPath, '/path/that/does/not/exist.blade.php', $actualOutput); expect($frontMatter->sourceContainsExpiredFoldedDependencies($missingOutput))->toBeTrue(); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/LookupTest.php
tests/LookupTest.php
<?php use Livewire\Blaze\BladeService; describe('lookup component paths', function () { beforeEach(function () { app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/pages', 'pages'); }); it('anonymous component', function () { $path = (new BladeService)->componentNameToPath('button'); expect($path)->toBe(__DIR__ . '/fixtures/components/button.blade.php'); }); it('namespaced anonymous component', function () { $path = (new BladeService)->componentNameToPath('pages::dashboard'); expect($path)->toBe(__DIR__ . '/fixtures/pages/dashboard.blade.php'); }); it('sub-component', function () { $path = (new BladeService)->componentNameToPath('form.input'); expect($path)->toBe(__DIR__ . '/fixtures/components/form/input.blade.php'); }); it('nested sub-component', function () { $path = (new BladeService)->componentNameToPath('form.fields.text'); expect($path)->toBe(__DIR__ . '/fixtures/components/form/fields/text.blade.php'); }); it('root component with index file', function () { $path = (new BladeService)->componentNameToPath('form'); expect($path)->toBe(__DIR__ . '/fixtures/components/form/index.blade.php'); }); it('root component with same-name file', function () { $path = (new BladeService)->componentNameToPath('panel'); expect($path)->toBe(__DIR__ . '/fixtures/components/panel/panel.blade.php'); }); it('namespaced sub-component', function () { $path = (new BladeService)->componentNameToPath('pages::auth.login'); expect($path)->toBe(__DIR__ . '/fixtures/pages/auth/login.blade.php'); }); it('namespaced root component', function () { $path = (new BladeService)->componentNameToPath('pages::auth'); expect($path)->toBe(__DIR__ . '/fixtures/pages/auth/index.blade.php'); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/MemoizeTest.php
tests/MemoizeTest.php
<?php use Illuminate\Support\Facades\Artisan; describe('memoization', function () { beforeEach(function () { // Configure Blade to find our test components and views app('blade.compiler')->anonymousComponentNamespace('', 'x'); app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); // call artisan view:clear: Artisan::call('view:clear'); }); it('can memoize an unfoldable component', function () { $template = '<x-memoize />'; $renderedA = app('blade.compiler')->render($template); $renderedB = app('blade.compiler')->render($template); expect($renderedA)->toContain('<div>'); expect($renderedA)->toBe($renderedB); }); it('can memoize based on static attributes', function () { $renderedA = app('blade.compiler')->render('<x-memoize foo="bar" />'); $renderedB = app('blade.compiler')->render('<x-memoize foo="bar" />'); expect($renderedA)->toContain('<div>'); expect($renderedA)->toBe($renderedB); $renderedA = app('blade.compiler')->render('<x-memoize foo="bar" />'); $renderedB = app('blade.compiler')->render('<x-memoize foo="baz" />'); expect($renderedA)->toContain('<div>'); expect($renderedA)->not->toBe($renderedB); }); it('memoization only works on self-closing components', function () { $renderedA = app('blade.compiler')->render('<x-memoize foo="bar"></x-memoize>'); $renderedB = app('blade.compiler')->render('<x-memoize foo="bar"></x-memoize>'); expect($renderedA)->toContain('<div>'); expect($renderedA)->not->toBe($renderedB); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/Pest.php
tests/Pest.php
<?php use Livewire\Blaze\Tests\TestCase; uses(TestCase::class)->in(__DIR__);
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/TestCase.php
tests/TestCase.php
<?php namespace Livewire\Blaze\Tests; use Livewire\Blaze\BlazeServiceProvider; use Orchestra\Testbench\TestCase as Orchestra; class TestCase extends Orchestra { protected function setUp(): void { parent::setUp(); } protected function getPackageProviders($app) { return [ BlazeServiceProvider::class, ]; } protected function getEnvironmentSetUp($app) { // Setup default configuration $app['config']->set('view.paths', [ __DIR__ . '/fixtures/views', ]); $app['config']->set('view.compiled', sys_get_temp_dir() . '/views'); } }
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/ExcerciseTest.php
tests/ExcerciseTest.php
<?php describe('exercise without folding', function () { function compileBlade(string $input): string { $tokens = app('blaze')->tokenizer()->tokenize($input); $ast = app('blaze')->parser()->parse($tokens); $output = implode('', array_map(fn ($n) => $n->render(), $ast)); return $output; } it('simple component with static attributes', function () { $input = '<x-button size="lg" color="blue">Click Me</x-button>'; expect(compileBlade($input))->toBe($input); }); it('self-closing components', function () { $input = '<x-icon name="home" size="sm" />'; expect(compileBlade($input))->toBe($input); }); it('nested components', function () { $input = '<x-card><x-button>Save</x-button><x-button>Cancel</x-button></x-card>'; expect(compileBlade($input))->toBe($input); }); it('components with complex nesting and text', function () { $input = '<x-layout title="Dashboard"> <x-header> <x-nav-link href="/home">Home</x-nav-link> <x-nav-link href="/about">About</x-nav-link> </x-header> <main> <h1>Welcome back!</h1> <x-card> <x-card-header>Stats</x-card-header> <x-card-body> <p>Your dashboard content here</p> </x-card-body> </x-card> </main> </x-layout>'; expect(compileBlade($input))->toBe($input); }); it('components with various attribute formats', function () { $input = '<x-button type="submit" disabled class="btn-primary" data-test="login-btn">Login</x-button>'; expect(compileBlade($input))->toBe($input); }); it('components with quoted attributes containing spaces', function () { $input = '<x-alert message="This is a long message with spaces" type="warning" />'; expect(compileBlade($input))->toBe($input); }); it('mixed regular HTML and components', function () { $input = '<div class="container"> <h1>Page Title</h1> <x-alert type="success">Operation completed!</x-alert> <p>Some regular HTML content</p> <x-button onclick="handleClick()">Click me</x-button> </div>'; expect(compileBlade($input))->toBe($input); }); it('flux namespace components', function () { $input = '<flux:button variant="primary">Flux Button</flux:button>'; expect(compileBlade($input))->toBe($input); }); it('flux self-closing components', function () { $input = '<flux:input type="email" placeholder="Enter email" />'; expect(compileBlade($input))->toBe($input); }); it('x: namespace components', function () { $input = '<x:modal title="Confirm Action"> <x:button type="danger">Delete</x:button> <x:button type="secondary">Cancel</x:button> </x:modal>'; expect(compileBlade($input))->toBe($input); }); it('standard slot syntax', function () { $input = '<x-modal><x-slot name="header"> <h2>Modal Title</h2> </x-slot><x-slot name="footer"> <x-button>OK</x-button> </x-slot> <p>Modal content goes here</p> </x-modal>'; expect(compileBlade($input))->toBe($input); }); it('short slot syntax', function () { $input = '<x-card><x-slot:header> <h3>Card Title</h3> </x-slot><x-slot:footer> <small>Footer text</small> </x-slot> <p>Card body content</p> </x-card>'; expect(compileBlade($input))->toBe($input); }); it('mixed slot syntaxes', function () { $input = '<x-layout> <x-slot name="title">Page Title</x-slot> <x-slot:sidebar> <x-nav-item>Home</x-nav-item> <x-nav-item>Settings</x-nav-item> </x-slot:sidebar> <main>Main content</main> </x-layout>'; expect(compileBlade($input))->toBe($input); }); it('slots with attributes', function () { $input = '<x-modal> <x-slot name="header" class="bg-gray-100 p-4"> <h2>Styled Header</h2> </x-slot> <x-slot:actions class="flex gap-2"> <x-button>Save</x-button> <x-button>Cancel</x-button> </x-slot:actions> </x-modal>'; expect(compileBlade($input))->toBe($input); }); it('deeply nested components and slots', function () { $input = '<x-page-layout> <x-slot:header> <x-navigation> <x-nav-group title="Main"> <x-nav-item href="/dashboard">Dashboard</x-nav-item> <x-nav-item href="/users">Users</x-nav-item> </x-nav-group> </x-navigation> </x-slot:header> <x-content-area> <x-card> <x-card-header> <x-heading level="2">User Management</x-heading> </x-card-header> <x-card-body> <x-data-table> <x-slot name="columns"> <x-column>Name</x-column> <x-column>Email</x-column> <x-column>Actions</x-column> </x-slot> <x-row> <x-cell>John Doe</x-cell> <x-cell>john@example.com</x-cell> <x-cell> <x-button size="sm">Edit</x-button> </x-cell> </x-row> </x-data-table> </x-card-body> </x-card> </x-content-area> </x-page-layout>'; expect(compileBlade($input))->toBe($input); }); it('components with complex attribute values', function () { $input = '<x-form method="POST" action="/users/create" :validation-rules="[\'name\' => \'required\', \'email\' => \'required|email\']" class="space-y-4 max-w-md mx-auto" data-turbo="false"> <x-input name="name" placeholder="Enter your name" /> <x-input name="email" type="email" placeholder="Enter your email" /> <x-button type="submit">Create User</x-button> </x-form>'; expect(compileBlade($input))->toBe($input); }); it('empty components', function () { $input = '<x-divider></x-divider>'; expect(compileBlade($input))->toBe($input); }); it('components with only whitespace content', function () { $input = '<x-container> </x-container>'; expect(compileBlade($input))->toBe($input); }); it('special characters in text content', function () { $input = '<x-code-block> if (condition && other_condition) { console.log("Hello & welcome!"); return true; } </x-code-block>'; expect(compileBlade($input))->toBe($input); }); it('components with hyphenated names', function () { $input = '<x-user-profile> <x-avatar-image src="/avatar.jpg" /> <x-user-details> <x-display-name>John Doe</x-display-name> <x-user-email>john@example.com</x-user-email> </x-user-details> </x-user-profile>'; expect(compileBlade($input))->toBe($input); }); it('components with dots in names', function () { $input = '<x-forms.input type="text" name="username" /> <x-forms.select name="country"> <x-forms.option value="us">United States</x-forms.option> <x-forms.option value="ca">Canada</x-forms.option> </x-forms.select>'; expect(compileBlade($input))->toBe($input); }); it('mixed component prefixes in same template', function () { $input = '<x-layout> <flux:header> <x:navigation /> </flux:header> <main> <x-card> <flux:button>Flux Button</flux:button> <x:modal> <x-content>Mixed prefixes work</x-content> </x:modal> </x-card> </main> </x-layout>'; expect(compileBlade($input))->toBe($input); }); it('preserve exact whitespace and formatting', function () { $input = '<x-pre-formatted> This has lots of spaces </x-pre-formatted>'; expect(compileBlade($input))->toBe($input); }); it('attributes with single quotes', function () { $input = "<x-component attr='single quoted value' mixed=\"double quoted\">Content</x-component>"; expect(compileBlade($input))->toBe($input); }); it('attributes with nested quotes', function () { $input = '<x-tooltip message="Click the \'Save\' button to continue">Hover me</x-tooltip>'; expect(compileBlade($input))->toBe($input); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/FoldTest.php
tests/FoldTest.php
<?php describe('fold elligable components', function () { beforeEach(function () { app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); }); function compile(string $input): string { return app('blaze')->compile($input); } it('simple component', function () { $input = '<x-button>Save</x-button>'; $output = '<button type="button">Save</button>'; expect(compile($input))->toBe($output); }); it('strips double quotes from attributes with string literals', function () { $input = '<x-avatar :name="\'Hi\'" :src="\'there\'" />'; expect(compile($input))->not->toContain('src=""'); expect(compile($input))->not->toContain('alt=""'); }); it('strips double quotes from complex dynamic attributes', function () { $input = '<x-avatar :name="$foo->bar" :src="$baz->qux" />'; expect(compile($input))->toContain('src="{{ $baz->qux }}" alt="{{ $foo->bar }}"'); }); it('with static props', function () { $input = '<x-alert message="Success!" />'; $output = '<div class="alert">Success!</div>'; expect(compile($input))->toBe($output); }); it('with static props containing dynamic characters like dollar signs', function () { $input = '<x-button wire:click="$refresh" />'; $output = '<button type="button" wire:click="$refresh"></button>'; expect(compile($input))->toBe($output); }); it('dynamic slot', function () { $input = '<x-button>{{ $name }}</x-button>'; $output = '<button type="button">{{ $name }}</button>'; expect(compile($input))->toBe($output); }); it('dynamic attributes', function () { $input = '<x-button :type="$type">Save</x-button>'; $output = '<button type="{{ $type }}">Save</button>'; expect(compile($input))->toBe($output); }); it('dynamic short attributes', function () { $input = '<x-button :$type>Save</x-button>'; $output = '<button type="{{ $type }}">Save</button>'; expect(compile($input))->toBe($output); }); it('dynamic echo attributes', function () { $input = '<x-button type="foo {{ $type }}">Save</x-button>'; $output = '<button type="foo {{ $type }}">Save</button>'; expect(compile($input))->toBe($output); }); it('dynamic slot with unfoldable component', function () { $input = '<x-button><x-unfoldable-button>{{ $name }}</x-unfoldable-button></x-button>'; $output = '<button type="button"><x-unfoldable-button>{{ $name }}</x-unfoldable-button></button>'; expect(compile($input))->toBe($output); }); it('nested components', function () { $input = <<<'HTML' <x-card> <x-button>Edit</x-button> <x-button>Delete</x-button> </x-card> HTML; $output = <<<HTML <div class="card"> <button type="button">Edit</button> <button type="button">Delete</button> </div> HTML; expect(compile($input))->toBe($output); }); it('deeply nested components', function () { $input = <<<'HTML' <x-card> <x-alert> <x-button>Save</x-button> </x-alert> </x-card> HTML; $output = <<<HTML <div class="card"> <div class="alert"> <button type="button">Save</button> </div> </div> HTML; expect(compile($input))->toBe($output); }); it('self-closing component', function () { $input = '<x-alert message="Success!" />'; $output = '<div class="alert">Success!</div>'; expect(compile($input))->toBe($output); }); it('component without @blaze is not folded', function () { $input = '<x-unfoldable-button>Save</x-unfoldable-button>'; $output = '<x-unfoldable-button>Save</x-unfoldable-button>'; expect(compile($input))->toBe($output); }); it('throws exception for invalid foldable usage with $pattern', function (string $pattern, string $expectedPattern) { $folder = app('blaze')->folder(); $componentNode = new \Livewire\Blaze\Nodes\ComponentNode("invalid-foldable.{$pattern}", 'x', '', [], false); expect(fn() => $folder->fold($componentNode)) ->toThrow(\Livewire\Blaze\Exceptions\InvalidBlazeFoldUsageException::class); try { $folder->fold($componentNode); } catch (\Livewire\Blaze\Exceptions\InvalidBlazeFoldUsageException $e) { expect($e->getMessage())->toContain('Invalid @blaze fold usage'); expect($e->getComponentPath())->toContain("invalid-foldable/{$pattern}.blade.php"); expect($e->getProblematicPattern())->toBe($expectedPattern); } })->with([ ['errors', '\\$errors'], ['session', 'session\\('], ['error', '@error\\('], ['csrf', '@csrf'], ['auth', 'auth\\(\\)'], ['request', 'request\\(\\)'], ['old', 'old\\('], ['once', '@once'], ]); it('named slots', function () { $input = '<x-modal> <x-slot name="header">Modal Title</x-slot> <x-slot name="footer">Footer Content</x-slot> Main content </x-modal>'; $output = '<div class="modal"> <div class="modal-header">Modal Title</div> <div class="modal-body">Main content</div> <div class="modal-footer">Footer Content</div> </div>'; expect(compile($input))->toBe($output); }); it('supports folding aware components with single word attributes', function () { $input = '<x-group variant="primary"><x-foldable-item /></x-group>'; $output = '<div class="group group-primary" data-test="foo"><div class="item item-primary"></div></div>'; expect(compile($input))->toBe($output); }); it('supports folding aware components with hyphenated attributes', function () { $input = '<x-group variant="primary" second-variant="secondary"><x-foldable-item /></x-group>'; $output = '<div class="group group-primary" data-test="foo" data-second-variant="secondary"><div class="item item-primary item-secondary"></div></div>'; expect(compile($input))->toBe($output); }); it('supports folding aware components with two wrapping components both with the same prop the closest one wins', function () { $input = '<x-group variant="primary"><x-group variant="secondary"><x-foldable-item /></x-group></x-group>'; // The foldable-item should render the `secondary` variant because it is the closest one to the foldable-item... $output = '<div class="group group-primary" data-test="foo"><div class="group group-secondary" data-test="foo"><div class="item item-secondary"></div></div></div>'; expect(compile($input))->toBe($output); }); it('supports aware on unfoldable components from folded parent with single word attributes', function () { $input = '<x-group variant="primary"><x-item /></x-group>'; $output = '<div class="group group-primary" data-test="foo"><div class="item item-primary"></div></div>'; $compiled = compile($input); $rendered = \Illuminate\Support\Facades\Blade::render($compiled); expect($rendered)->toBe($output); }); it('supports aware on unfoldable components from folded parent with hyphenated attributes', function () { $input = '<x-group variant="primary" second-variant="secondary"><x-item /></x-group>'; $output = '<div class="group group-primary" data-test="foo" data-second-variant="secondary"><div class="item item-primary item-secondary"></div></div>'; $compiled = compile($input); $rendered = \Illuminate\Support\Facades\Blade::render($compiled); expect($rendered)->toBe($output); }); it('supports aware on unfoldable components from folded parent with dynamic attributes', function () { $input = '<?php $result = "bar"; ?> <x-group variant="primary" :data-test="$result"><x-item /></x-group>'; $output = '<div class="group group-primary" data-test="bar"><div class="item item-primary"></div></div>'; $compiled = compile($input); $rendered = \Illuminate\Support\Facades\Blade::render($compiled); expect($rendered)->toBe($output); }); it('supports verbatim blocks', function () { $input = <<<'BLADE' @verbatim <x-card> <x-button>Save</x-button> </x-card> @endverbatim BLADE; $output = <<<'BLADE' <x-card> <x-button>Save</x-button> </x-card> BLADE; $rendered = \Illuminate\Support\Facades\Blade::render($input); expect($rendered)->toBe($output); }); it('can fold static props that get formatted', function () { $input = '<x-date date="2025-07-11 13:22:41 UTC" />'; $output = '<div>Date is: Fri, Jul 11</div>'; expect(compile($input))->toBe($output); }); it('cant fold dynamic props that get formatted', function () { $input = '<?php $date = "2025-07-11 13:22:41 UTC"; ?> <x-date :date="$date" />'; $output = '<?php $date = "2025-07-11 13:22:41 UTC"; ?> <?php $blaze_memoized_key = \Livewire\Blaze\Memoizer\Memo::key("date", [\'date\' => $date]); ?><?php if (! \Livewire\Blaze\Memoizer\Memo::has($blaze_memoized_key)) : ?><?php ob_start(); ?><x-date :date="$date" /><?php \Livewire\Blaze\Memoizer\Memo::put($blaze_memoized_key, ob_get_clean()); ?><?php endif; ?><?php echo \Livewire\Blaze\Memoizer\Memo::get($blaze_memoized_key); ?>'; expect(compile($input))->toBe($output); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/InfiniteRecursionTest.php
tests/InfiniteRecursionTest.php
<?php describe('infinite recursion bugs', function () { beforeEach(function () { // Configure Blade to find our test components and views app('blade.compiler')->anonymousComponentNamespace('', 'x'); app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); }); it('should handle dynamic attributes without infinite recursion', function () { $template = '<x-button type="submit" class="btn-primary">Submit</x-button>'; // This should complete without hanging or crashing $rendered = \Illuminate\Support\Facades\Blade::render($template); expect($rendered)->toContain('<button'); expect($rendered)->toContain('type="submit"'); expect($rendered)->toContain('class="btn-primary"'); expect($rendered)->toContain('Submit'); expect($rendered)->not->toContain('<x-button'); }); it('should handle nested foldable components without infinite recursion', function () { $template = '<x-card><x-alert message="Nested alert!" /></x-card>'; // This should complete without hanging or crashing $rendered = \Illuminate\Support\Facades\Blade::render($template); expect($rendered)->toContain('<div class="card">'); expect($rendered)->toContain('<div class="alert">'); expect($rendered)->toContain('Nested alert!'); expect($rendered)->not->toContain('<x-card>'); expect($rendered)->not->toContain('<x-alert'); }); it('should handle complex nested structure without infinite recursion', function () { $template = ' <x-card> <x-button type="button">Button 1</x-button> <x-alert message="Alert in card" /> <x-button type="submit" class="secondary">Button 2</x-button> </x-card>'; // This should complete without hanging or crashing $rendered = \Illuminate\Support\Facades\Blade::render($template); expect($rendered)->toContain('<div class="card">'); expect($rendered)->toContain('Button 1'); expect($rendered)->toContain('Button 2'); expect($rendered)->toContain('Alert in card'); expect($rendered)->not->toContain('<x-card>'); expect($rendered)->not->toContain('<x-button'); expect($rendered)->not->toContain('<x-alert'); }); it('should handle multiple levels of nesting without infinite recursion', function () { // Create a more complex nesting scenario $template = ' <div class="wrapper"> <x-card> <h1>Outer Card</h1> <x-card> <h2>Inner Card</h2> <x-button type="button">Nested Button</x-button> <x-alert message="Deeply nested alert" /> </x-card> <x-button type="submit">Outer Button</x-button> </x-card> </div>'; // This should complete without hanging or crashing $rendered = \Illuminate\Support\Facades\Blade::render($template); expect($rendered)->toContain('<div class="wrapper">'); expect($rendered)->toContain('<h1>Outer Card</h1>'); expect($rendered)->toContain('<h2>Inner Card</h2>'); expect($rendered)->toContain('Nested Button'); expect($rendered)->toContain('Deeply nested alert'); expect($rendered)->toContain('Outer Button'); expect($rendered)->not->toContain('<x-card>'); expect($rendered)->not->toContain('<x-button'); expect($rendered)->not->toContain('<x-alert'); }); it('should handle components with variable attributes without infinite recursion', function () { // Test components with dynamic/variable attributes that might trigger edge cases $template = ' <x-button type="submit" class="btn-primary btn-large" data-action="save" aria-label="Save changes"> Save Changes </x-button>'; // This should complete without hanging or crashing $rendered = \Illuminate\Support\Facades\Blade::render($template); expect($rendered)->toContain('<button'); expect($rendered)->toContain('type="submit"'); expect($rendered)->toContain('class="btn-primary btn-large"'); expect($rendered)->toContain('data-action="save"'); expect($rendered)->toContain('aria-label="Save changes"'); expect($rendered)->toContain('Save Changes'); expect($rendered)->not->toContain('<x-button'); }); it('should handle edge case with quotes and special characters', function () { // Test edge case that might trigger recursion issues $template = '<x-button class="btn \'quoted\' &amp; escaped" data-test=\'{"key": "value"}\'>Complex</x-button>'; // This should complete without hanging or crashing $rendered = \Illuminate\Support\Facades\Blade::render($template); expect($rendered)->toContain('<button'); expect($rendered)->toContain('Complex'); expect($rendered)->not->toContain('<x-button'); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/AttributeParserTest.php
tests/AttributeParserTest.php
<?php use Livewire\Blaze\Support\AttributeParser; describe('parse attributes', function () { it('parses and replaces dynamic attributes with name and value syntax', function() { $input = ':name="$foo"'; $output = 'name="ATTR_PLACEHOLDER_0"'; $attributePlaceholders = []; $attributeNameToPlaceholder = []; $result = (new AttributeParser)->parseAndReplaceDynamics($input, $attributePlaceholders, $attributeNameToPlaceholder); expect($result)->toBe($output); expect($attributePlaceholders)->toBe([ 'ATTR_PLACEHOLDER_0' => '{{ $foo }}', ]); expect($attributeNameToPlaceholder)->toBe([ 'name' => 'ATTR_PLACEHOLDER_0', ]); }); it('parses and replaces dynamic attributes with short syntax', function() { $input = ':$name'; $output = 'name="ATTR_PLACEHOLDER_0"'; $attributePlaceholders = []; $attributeNameToPlaceholder = []; $result = (new AttributeParser)->parseAndReplaceDynamics($input, $attributePlaceholders, $attributeNameToPlaceholder); expect($result)->toBe($output); expect($attributePlaceholders)->toBe([ 'ATTR_PLACEHOLDER_0' => '{{ $name }}', ]); expect($attributeNameToPlaceholder)->toBe([ 'name' => 'ATTR_PLACEHOLDER_0', ]); }); it('parses and replaces dynamic attributes echoed within a value', function() { $input = 'name="foo {{ $type }}"'; $output = 'name="foo ATTR_PLACEHOLDER_0"'; $attributePlaceholders = []; $attributeNameToPlaceholder = []; $result = (new AttributeParser)->parseAndReplaceDynamics($input, $attributePlaceholders, $attributeNameToPlaceholder); expect($result)->toBe($output); expect($attributePlaceholders)->toBe([ 'ATTR_PLACEHOLDER_0' => '{{ $type }}', ]); expect($attributeNameToPlaceholder)->toBe([]); }); it('does not parse static attributes with colon in the name when used alone', function() { $input = 'icon:trailing="chevrons-up-down"'; $output = 'icon:trailing="chevrons-up-down"'; $attributePlaceholders = []; $attributeNameToPlaceholder = []; $result = (new AttributeParser)->parseAndReplaceDynamics($input, $attributePlaceholders, $attributeNameToPlaceholder); expect($result)->toBe($output); expect($attributePlaceholders)->toBe([]); expect($attributeNameToPlaceholder)->toBe([]); }); it('does not parse static attributes with colon in the name when used with dynamic attributes', function() { $input = ':name="$foo" icon:trailing="chevrons-up-down"'; $output = 'name="ATTR_PLACEHOLDER_0" icon:trailing="chevrons-up-down"'; $attributePlaceholders = []; $attributeNameToPlaceholder = []; $result = (new AttributeParser)->parseAndReplaceDynamics($input, $attributePlaceholders, $attributeNameToPlaceholder); expect($result)->toBe($output); expect($attributePlaceholders)->toBe([ 'ATTR_PLACEHOLDER_0' => '{{ $foo }}', ]); expect($attributeNameToPlaceholder)->toBe([ 'name' => 'ATTR_PLACEHOLDER_0', ]); }); it('parses static attributes', function () { $input = 'name="Bob" searchable="true"'; $output = [ 'name' => [ 'isDynamic' => false, 'value' => 'Bob', 'original' => 'name="Bob"', ], 'searchable' => [ 'isDynamic' => false, 'value' => 'true', 'original' => 'searchable="true"', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses dynamic attributes', function () { $input = ':name="$name" :searchable="true"'; $output = [ 'name' => [ 'isDynamic' => true, 'value' => '$name', 'original' => ':name="$name"', ], 'searchable' => [ 'isDynamic' => true, 'value' => 'true', 'original' => ':searchable="true"', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses dynamic short attributes', function () { $input = ':$name'; $output = [ 'name' => [ 'isDynamic' => true, 'value' => '$name', 'original' => ':$name', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses boolean attributes', function () { $input = 'searchable'; $output = [ 'searchable' => [ 'isDynamic' => false, 'value' => true, 'original' => 'searchable', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses attributes with echoed values', function () { $input = 'type="{{ $type }}"'; $output = [ 'type' => [ 'isDynamic' => false, 'value' => '{{ $type }}', 'original' => 'type="{{ $type }}"', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses hyphenated static attributes', function () { $input = 'data-test="foo" second-variant="secondary"'; $output = [ 'dataTest' => [ 'isDynamic' => false, 'value' => 'foo', 'original' => 'data-test="foo"', ], 'secondVariant' => [ 'isDynamic' => false, 'value' => 'secondary', 'original' => 'second-variant="secondary"', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses hyphenated dynamic attributes', function () { $input = ':data-test="$test" :second-variant="true"'; $output = [ 'dataTest' => [ 'isDynamic' => true, 'value' => '$test', 'original' => ':data-test="$test"', ], 'secondVariant' => [ 'isDynamic' => true, 'value' => 'true', 'original' => ':second-variant="true"', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses hyphenated short dynamic attributes', function () { $input = ':$data-test'; $output = [ 'dataTest' => [ 'isDynamic' => true, 'value' => '$data-test', 'original' => ':$data-test', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses static attributes which contain colons', function () { $input = 'icon:trailing="chevrons-up-down" wire:sort:item="{{ $id }}"'; $output = [ 'icon:trailing' => [ 'isDynamic' => false, 'value' => 'chevrons-up-down', 'original' => 'icon:trailing="chevrons-up-down"', ], 'wire:sort:item' => [ 'isDynamic' => false, 'value' => '{{ $id }}', 'original' => 'wire:sort:item="{{ $id }}"', ], ]; $attributes = (new AttributeParser())->parseAttributeStringToArray($input); expect($attributes)->toBe($output); }); it('parses an attributes array and converts it to an attributes string', function () { $input = [ 'foo' => [ 'isDynamic' => false, 'value' => 'bar', 'original' => 'foo="bar"', ], 'name' => [ 'isDynamic' => true, 'value' => '$name', 'original' => ':name="$name"', ], 'baz' => [ 'isDynamic' => true, 'value' => '$baz', 'original' => ':$baz', ], 'searchable' => [ 'isDynamic' => false, 'value' => true, 'original' => 'searchable', ], ]; $output = 'foo="bar" :name="$name" :$baz searchable'; $attributes = (new AttributeParser())->parseAttributesArrayToPropString($input); expect($attributes)->toBe($output); }); it('parses an array string and converts it to an array', function () { $input = '[\'variant\', \'secondVariant\' => null]'; $output = [ 'variant', 'secondVariant' => null, ]; $attributes = (new AttributeParser())->parseArrayStringIntoArray($input); expect($attributes)->toBe($output); }); it('parses an array string with multiline formatting and converts it to an array', function () { $input = '[ \'variant\', \'secondVariant\' => null ]'; $output = [ 'variant', 'secondVariant' => null, ]; $attributes = (new AttributeParser())->parseArrayStringIntoArray($input); expect($attributes)->toBe($output); }); it('parses an array string with double quotes and converts it to an array', function () { $input = '["variant", "secondVariant" => null]'; $output = [ 'variant', 'secondVariant' => null, ]; $attributes = (new AttributeParser())->parseArrayStringIntoArray($input); expect($attributes)->toBe($output); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/UnblazeTest.php
tests/UnblazeTest.php
<?php use Illuminate\Support\Facades\View; describe('unblaze directive', function () { beforeEach(function () { // Configure Blade to find our test components app('blade.compiler')->anonymousComponentNamespace('', 'x'); app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); // Add view path for our test pages View::addLocation(__DIR__ . '/fixtures/pages'); }); it('folds component but preserves unblaze block', function () { $input = '<x-with-unblaze />'; $compiled = app('blaze')->compile($input); // The component should be folded expect($compiled)->toContain('<div class="container">'); expect($compiled)->toContain('<h1>Static Header</h1>'); expect($compiled)->toContain('<footer>Static Footer</footer>'); // The unblaze block should be preserved as dynamic content expect($compiled)->toContain('{{ $dynamicValue }}'); expect($compiled)->not->toContain('<x-with-unblaze'); }); it('preserves unblaze content without folding the dynamic parts', function () { $input = '<x-with-unblaze />'; $compiled = app('blaze')->compile($input); // Static parts should be folded expect($compiled)->toContain('Static Header'); expect($compiled)->toContain('Static Footer'); // Dynamic parts inside @unblaze should remain dynamic expect($compiled)->toContain('$dynamicValue'); }); it('handles unblaze with scope parameter', function () { $input = '<?php $message = "Hello World"; ?> <x-with-unblaze-scope :message="$message" />'; $compiled = app('blaze')->compile($input); // The component should be folded expect($compiled)->toContain('<div class="wrapper">'); expect($compiled)->toContain('<h2>Title</h2>'); expect($compiled)->toContain('<p>Static paragraph</p>'); // The scope should be captured and made available expect($compiled)->toContain('$scope'); }); it('encodes scope into compiled view for runtime access', function () { $input = '<?php $message = "Test Message"; ?> <x-with-unblaze-scope :message="$message" />'; $compiled = app('blaze')->compile($input); // Should contain PHP code to set up the scope expect($compiled)->toMatch('/\$scope\s*=\s*array\s*\(/'); // The dynamic content should reference $scope expect($compiled)->toContain('$scope[\'message\']'); }); it('renders unblaze component correctly at runtime', function () { $template = '<?php $message = "Runtime Test"; ?> <x-with-unblaze-scope :message="$message" />'; $rendered = \Illuminate\Support\Facades\Blade::render($template); // Static content should be present expect($rendered)->toContain('<div class="wrapper">'); expect($rendered)->toContain('<h2>Title</h2>'); expect($rendered)->toContain('<p>Static paragraph</p>'); // Dynamic content should be rendered with the scope value // Note: The actual rendering of scope variables happens at runtime expect($rendered)->toContain('class="dynamic"'); }); it('allows punching a hole in static component for dynamic section', function () { $input = <<<'BLADE' <x-card> Static content here @unblaze <span>{{ $dynamicValue }}</span> @endunblaze More static content </x-card> BLADE; $compiled = app('blaze')->compile($input); // Card should be folded expect($compiled)->toContain('<div class="card">'); expect($compiled)->toContain('Static content here'); expect($compiled)->toContain('More static content'); // But dynamic part should be preserved expect($compiled)->toContain('{{ $dynamicValue }}'); expect($compiled)->not->toContain('<x-card>'); }); it('supports multiple unblaze blocks in same component', function () { $template = <<<'BLADE' @blaze <div> <p>Static 1</p> @unblaze <span>{{ $dynamic1 }}</span> @endunblaze <p>Static 2</p> @unblaze <span>{{ $dynamic2 }}</span> @endunblaze <p>Static 3</p> </div> BLADE; $compiled = app('blaze')->compile($template); // All static parts should be folded expect($compiled)->toContain('<p>Static 1</p>'); expect($compiled)->toContain('<p>Static 2</p>'); expect($compiled)->toContain('<p>Static 3</p>'); // Both dynamic parts should be preserved expect($compiled)->toContain('{{ $dynamic1 }}'); expect($compiled)->toContain('{{ $dynamic2 }}'); }); it('handles nested components with unblaze', function () { $input = <<<'BLADE' <x-card> <x-button>Static Button</x-button> @unblaze <x-button>{{ $dynamicLabel }}</x-button> @endunblaze </x-card> BLADE; $compiled = app('blaze')->compile($input); // Outer card and static button should be folded expect($compiled)->toContain('<div class="card">'); expect($compiled)->toContain('Static Button'); // Dynamic button inside unblaze should be preserved expect($compiled)->toContain('{{ $dynamicLabel }}'); }); it('static folded content with random strings stays the same between renders', function () { // First render $render1 = \Illuminate\Support\Facades\Blade::render('<x-random-static />'); // Second render $render2 = \Illuminate\Support\Facades\Blade::render('<x-random-static />'); // The random string should be the same because it was folded at compile time expect($render1)->toBe($render2); // Verify it contains the static structure expect($render1)->toContain('class="static-component"'); expect($render1)->toContain('This should be folded and not change between renders'); }); it('unblazed dynamic content changes between renders while static parts stay the same', function () { // First render with a value $render1 = \Illuminate\Support\Facades\Blade::render('<x-mixed-random />', ['dynamicValue' => 'first-value']); // Second render with a different value $render2 = \Illuminate\Support\Facades\Blade::render('<x-mixed-random />', ['dynamicValue' => 'second-value']); // Extract the static parts (header and footer with random strings) preg_match('/<h1>Static Random: (.+?)<\/h1>/', $render1, $matches1); preg_match('/<h1>Static Random: (.+?)<\/h1>/', $render2, $matches2); $staticRandom1 = $matches1[1] ?? ''; $staticRandom2 = $matches2[1] ?? ''; // The static random strings should be IDENTICAL (folded at compile time) expect($staticRandom1)->toBe($staticRandom2); expect($staticRandom1)->not->toBeEmpty(); // But the dynamic parts should be DIFFERENT expect($render1)->toContain('Dynamic value: first-value'); expect($render2)->toContain('Dynamic value: second-value'); expect($render1)->not->toContain('second-value'); expect($render2)->not->toContain('first-value'); }); it('multiple renders of unblaze component proves folding optimization', function () { // Render the same template multiple times with different dynamic values $renders = []; foreach (['one', 'two', 'three'] as $value) { $renders[] = \Illuminate\Support\Facades\Blade::render( '<x-mixed-random />', ['dynamicValue' => $value] ); } // Extract the static footer random string from each render $staticFooters = []; foreach ($renders as $render) { preg_match('/<footer>Static Footer: (.+?)<\/footer>/', $render, $matches); $staticFooters[] = $matches[1] ?? ''; } // All static random strings should be IDENTICAL (proving they were folded) expect($staticFooters[0])->toBe($staticFooters[1]); expect($staticFooters[1])->toBe($staticFooters[2]); expect($staticFooters[0])->not->toBeEmpty(); // But each render should have its unique dynamic value expect($renders[0])->toContain('Dynamic value: one'); expect($renders[1])->toContain('Dynamic value: two'); expect($renders[2])->toContain('Dynamic value: three'); }); }); describe('unblaze validation', function () { beforeEach(function () { app('blade.compiler')->anonymousComponentNamespace('', 'x'); app('blade.compiler')->anonymousComponentPath(__DIR__ . '/fixtures/components'); }); it('allows $errors inside @unblaze blocks', function () { $input = '<x-with-errors-inside-unblaze />'; // Should not throw an exception $compiled = app('blaze')->compile($input); expect($compiled)->toContain('form-input'); expect($compiled)->toContain('$errors'); }); it('throws exception for $errors outside @unblaze blocks', function () { expect(fn() => app('blaze')->compile('<x-with-errors-outside-unblaze />')) ->toThrow(\Livewire\Blaze\Exceptions\InvalidBlazeFoldUsageException::class); }); it('allows @csrf inside @unblaze blocks', function () { $input = '<x-with-csrf-inside-unblaze />'; // Should not throw an exception $compiled = app('blaze')->compile($input); expect($compiled)->toContain('form-wrapper'); }); it('allows request() inside @unblaze blocks', function () { $input = '<x-with-request-inside-unblaze />'; // Should not throw an exception $compiled = app('blaze')->compile($input); expect($compiled)->toContain('<nav>'); expect($compiled)->toContain('request()'); }); it('still validates problematic patterns in static parts of component', function () { // Create a component with $errors in static part and @unblaze $componentPath = __DIR__ . '/fixtures/components/mixed-errors.blade.php'; file_put_contents($componentPath, '@blaze <div> <p>{{ $errors->count() }}</p> @unblaze <span>{{ $errors->first() }}</span> @endunblaze </div>'); try { expect(fn() => app('blaze')->compile('<x-mixed-errors />')) ->toThrow(\Livewire\Blaze\Exceptions\InvalidBlazeFoldUsageException::class); } finally { unlink($componentPath); } }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/BladeServiceTest.php
tests/BladeServiceTest.php
<?php use Livewire\Blaze\BladeService; describe('componentNameToPath', function () { beforeEach(function () { $basePath = __DIR__ . '/fixtures/components'; app('blade.compiler')->anonymousComponentPath($basePath); app('blade.compiler')->anonymousComponentPath($basePath, 'fixtures'); }); describe('namespaced', function () { it('gets the correct path for namespaced direct component files', function () { $input = 'fixtures::button'; $expected = __DIR__ . '/fixtures/components/button.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('prefers namespaced direct component file over index.blade.php for root components', function () { $input = 'fixtures::card'; $expected = __DIR__ . '/fixtures/components/card.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for namespaced nested components', function () { $input = 'fixtures::form.input'; $expected = __DIR__ . '/fixtures/components/form/input.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for namespaced deeply nested components', function () { $input = 'fixtures::form.fields.text'; $expected = __DIR__ . '/fixtures/components/form/fields/text.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for namespaced root components using index.blade.php', function () { $input = 'fixtures::form'; $expected = __DIR__ . '/fixtures/components/form/index.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for namespaced root components using same-name.blade.php', function () { $input = 'fixtures::panel'; $expected = __DIR__ . '/fixtures/components/panel/panel.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for namespaced nested root components using same-name.blade.php', function () { $input = 'fixtures::kanban.comments'; $expected = __DIR__ . '/fixtures/components/kanban/comments/comments.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('handles non-existent namespaced components gracefully', function () { $input = 'fixtures::nonexistent.component'; expect((new BladeService)->componentNameToPath($input))->toBe(''); }); }); describe('non-namespaced', function () { it('gets the correct path for direct component files', function () { $input = 'button'; $expected = __DIR__ . '/fixtures/components/button.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('prefers direct component file over index.blade.php for root components', function () { $input = 'card'; $expected = __DIR__ . '/fixtures/components/card.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for nested components', function () { $input = 'form.input'; $expected = __DIR__ . '/fixtures/components/form/input.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for deeply nested components', function () { $input = 'form.fields.text'; $expected = __DIR__ . '/fixtures/components/form/fields/text.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for root components using index.blade.php', function () { $input = 'form'; $expected = __DIR__ . '/fixtures/components/form/index.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for root components using same-name.blade.php', function () { $input = 'panel'; $expected = __DIR__ . '/fixtures/components/panel/panel.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('gets the correct path for nested root components using same-name.blade.php', function () { $input = 'kanban.comments'; $expected = __DIR__ . '/fixtures/components/kanban/comments/comments.blade.php'; expect((new BladeService)->componentNameToPath($input))->toBe($expected); }); it('handles non-existent components gracefully', function () { $input = 'nonexistent.component'; expect((new BladeService)->componentNameToPath($input))->toBe(''); }); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/FluxTest.php
tests/FluxTest.php
<?php use Illuminate\Support\Facades\Route; describe('flux component integration', function () { beforeEach(function () { // Manually register Livewire and Flux providers for these tests app()->register(\Livewire\LivewireServiceProvider::class); app()->register(\Flux\FluxServiceProvider::class); }); it('folds flux heading component with static props', function () { $input = '<flux:heading>Hello World</flux:heading>'; $output = app('blaze')->compile($input); // Should be folded to a div (default level) expect($output)->toContain('<div'); expect($output)->toContain('Hello World'); expect($output)->toContain('data-flux-heading'); expect($output)->not->toContain('flux:heading'); }); it('folds link component with dynamic route helper link', function() { Route::get('/dashboard', fn() => 'dashboard')->name('dashboard'); $input = '<flux:link :href="route(\'dashboard\')">Dashboard</flux:link>'; $output = app('blaze')->compile($input); expect($output) ->toContain('<a ') ->toContain(' href="{{ route(\'dashboard\') }}"'); }); });
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/benchmark/no-fold-button-in-loop.blade.php
tests/fixtures/benchmark/no-fold-button-in-loop.blade.php
@for ($i = 0; $i < 25000; $i++) <x-button-no-fold>Hi</x-button-no-fold> @endfor
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/benchmark/simple-button-in-loop.blade.php
tests/fixtures/benchmark/simple-button-in-loop.blade.php
@for ($i = 0; $i < 25000; $i++) <x-button>Hi</x-button> @endfor
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/pages/dashboard.blade.php
tests/fixtures/pages/dashboard.blade.php
@props([]) <div class="dashboard">{{ $slot }}</div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/pages/invalid-foldable-test.blade.php
tests/fixtures/pages/invalid-foldable-test.blade.php
<div class="page"> <h1>Invalid Foldable Test</h1> <!-- This should throw an exception because invalid-foldable has @blaze but uses $errors --> <x-invalid-foldable>This should fail</x-invalid-foldable> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/pages/integration-test.blade.php
tests/fixtures/pages/integration-test.blade.php
<div class="page"> <h1>Integration Test Page</h1> <!-- Foldable component should get folded --> <x-button>Save Changes</x-button> <!-- Non-foldable component should stay as component tag --> <x-unfoldable-button>Cancel</x-unfoldable-button> <!-- Nested foldable components should get folded --> <x-card> <x-alert message="Success!" /> </x-card> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/pages/auth/login.blade.php
tests/fixtures/pages/auth/login.blade.php
@props([]) <div class="login-form">{{ $slot }}</div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/pages/auth/index.blade.php
tests/fixtures/pages/auth/index.blade.php
@props([]) <div class="auth-layout">{{ $slot }}</div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/alert.blade.php
tests/fixtures/components/alert.blade.php
@blaze @props(['message' => null]) <div class="alert">{{ $message ?? $slot }}</div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/unfoldable-button.blade.php
tests/fixtures/components/unfoldable-button.blade.php
@props(['type' => 'button']) <button type="{{ $type }}">{{ $slot }}</button>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/with-errors-inside-unblaze.blade.php
tests/fixtures/components/with-errors-inside-unblaze.blade.php
@blaze <div class="form-input"> <label>Email</label> <input type="email" name="email"> @unblaze @if($errors->has('email')) <span class="error">{{ $errors->first('email') }}</span> @endif @endunblaze </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/with-unblaze.blade.php
tests/fixtures/components/with-unblaze.blade.php
@blaze <div class="container"> <h1>Static Header</h1> @unblaze <p>Dynamic content: {{ $dynamicValue }}</p> @endunblaze <footer>Static Footer</footer> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/card.blade.php
tests/fixtures/components/card.blade.php
@blaze @props([]) <div class="card"> {{ $slot }} </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/button-no-fold.blade.php
tests/fixtures/components/button-no-fold.blade.php
@props(['type' => 'button']) <button {{ $attributes->merge(['type' => $type]) }}>{{ $slot }}</button>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/group.blade.php
tests/fixtures/components/group.blade.php
@blaze @props(['variant' => '', 'dataTest' => 'foo', 'secondVariant' => null]) <div {{ $attributes->merge(['class' => 'group group-'.$variant, 'data-test' => $dataTest]) }}@if($secondVariant) data-second-variant="{{ $secondVariant }}"@endif>{{ $slot }}</div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/date.blade.php
tests/fixtures/components/date.blade.php
@blaze @props(['date']) <div>Date is: {{ (new DateTime($date))->format('D, M d') }}</div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/button.blade.php
tests/fixtures/components/button.blade.php
@blaze @props(['type' => 'button']) <button {{ $attributes->merge(['type' => $type]) }}>{{ $slot }}</button>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/foldable-item.blade.php
tests/fixtures/components/foldable-item.blade.php
@blaze @aware(['variant', 'secondVariant' => null ]) <div class="item item-{{ $variant }}{{ $secondVariant ? ' item-'.$secondVariant : '' }}"></div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/mixed-random.blade.php
tests/fixtures/components/mixed-random.blade.php
@blaze <div class="mixed-component"> <h1>Static Random: {{ \Illuminate\Support\Str::random(20) }}</h1> @unblaze <p class="dynamic">Dynamic value: {{ $dynamicValue ?? 'none' }}</p> @endunblaze <footer>Static Footer: {{ \Illuminate\Support\Str::random(10) }}</footer> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/memoize.blade.php
tests/fixtures/components/memoize.blade.php
@blaze(fold: false) <div>{{ str()->random() }}</div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/item.blade.php
tests/fixtures/components/item.blade.php
@aware(['variant', 'secondVariant' => null ]) <div class="item item-{{ $variant }}{{ $secondVariant ? ' item-'.$secondVariant : '' }}"></div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/modal.blade.php
tests/fixtures/components/modal.blade.php
@blaze @props([ 'header' => '', 'footer' => '', ]) <div class="modal"> <div class="modal-header">{{ $header }}</div> <div class="modal-body">{{ $slot }}</div> <div class="modal-footer">{{ $footer }}</div> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/random-static.blade.php
tests/fixtures/components/random-static.blade.php
@blaze <div class="static-component"> <h1>Random: {{ \Illuminate\Support\Str::random(20) }}</h1> <p>This should be folded and not change between renders</p> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/scoped-dynamic.blade.php
tests/fixtures/components/scoped-dynamic.blade.php
@blaze <div class="scoped-component"> <h1>Static: {{ \Illuminate\Support\Str::random(15) }}</h1> @unblaze(scope: ['value' => $value]) <div class="dynamic-section">Value: {{ $scope['value'] }}</div> @endunblaze <p>Static paragraph: {{ \Illuminate\Support\Str::random(10) }}</p> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/with-unblaze-scope.blade.php
tests/fixtures/components/with-unblaze-scope.blade.php
@blaze <div class="wrapper"> <h2>Title</h2> @unblaze(scope: ['message' => $message]) <div class="dynamic">{{ $scope['message'] }}</div> @endunblaze <p>Static paragraph</p> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/with-request-inside-unblaze.blade.php
tests/fixtures/components/with-request-inside-unblaze.blade.php
@blaze <nav> <a href="/home">Home</a> @unblaze <a href="/about" class="{{ request()->is('about') ? 'active' : '' }}">About</a> @endunblaze </nav>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/with-errors-outside-unblaze.blade.php
tests/fixtures/components/with-errors-outside-unblaze.blade.php
@blaze <div class="form-input"> <label>Email</label> <input type="email" name="email"> @if($errors->has('email')) <span class="error">{{ $errors->first('email') }}</span> @endif </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/avatar.blade.php
tests/fixtures/components/avatar.blade.php
@blaze @props([ 'iconVariant' => 'solid', 'initials' => null, 'tooltip' => null, 'circle' => null, 'color' => null, 'badge' => null, 'name' => null, 'icon' => null, 'size' => 'md', 'src' => null, 'href' => null, 'alt' => null, 'as' => 'div', ]) @php if ($name && ! $initials) { $parts = explode(' ', trim($name)); if (false) { $initials = strtoupper(mb_substr($parts[0], 0, 1)); } else { // Remove empty strings from the array... $parts = collect($parts)->filter()->values()->all(); if (count($parts) > 1) { $initials = strtoupper(mb_substr($parts[0], 0, 1) . mb_substr($parts[1], 0, 1)); } else if (count($parts) === 1) { $initials = strtoupper(mb_substr($parts[0], 0, 1)) . strtolower(mb_substr($parts[0], 1, 1)); } } } if ($name && $tooltip === true) { $tooltip = $name; } $hasTextContent = $icon ?? $initials ?? $slot->isNotEmpty(); // If there's no text content, we'll fallback to using the user icon otherwise there will be an empty white square... if (! $hasTextContent) { $icon = 'user'; $hasTextContent = true; } // Be careful not to change the order of these colors. // They're used in the hash function below and changing them would change actual user avatar colors that they might have grown to identify with. $colors = ['red', 'orange', 'amber', 'yellow', 'lime', 'green', 'emerald', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose']; if ($hasTextContent && $color === 'auto') { $colorSeed = false ?? $name ?? $icon ?? $initials ?? $slot; $hash = crc32((string) $colorSeed); $color = $colors[$hash % count($colors)]; } $classes = ''; $iconClasses = ''; $badgeColor = false ?: (is_object($badge) ? false : null); $badgeCircle = false ?: (is_object($badge) ? false : null); $badgePosition = false ?: (is_object($badge) ? false : null); $badgeVariant = false ?: (is_object($badge) ? false : null); $badgeClasses = ''; $label = $alt ?? $name; @endphp <flux:with-tooltip :$tooltip :$attributes> <flux:button-or-link :attributes="$attributes->class($classes)->merge($circle ? ['data-circle' => 'true'] : [])" :$as :$href data-flux-avatar data-slot="avatar" data-size="{{ $size }}"> <?php if ($src): ?> <img src="{{ $src }}" alt="{{ $alt ?? $name }}" class="rounded-[var(--avatar-radius)]"> <?php elseif ($icon): ?> <flux:icon :name="$icon" :variant="$iconVariant" :class="$iconClasses" /> <?php elseif ($hasTextContent): ?> <span class="select-none">{{ $initials ?? $slot }}</span> <?php endif; ?> <?php if ($badge instanceof \Illuminate\View\ComponentSlot): ?> <div {{ $badge->attributes->class($badgeClasses) }} aria-hidden="true">{{ $badge }}</div> <?php elseif ($badge): ?> <div class="{{ $badgeClasses }}" aria-hidden="true">{{ is_string($badge) ? $badge : '' }}</div> <?php endif; ?> </flux:button-or-link> </flux:with-tooltip>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/with-csrf-inside-unblaze.blade.php
tests/fixtures/components/with-csrf-inside-unblaze.blade.php
@blaze <div class="form-wrapper"> <h2>Form</h2> @unblaze <form method="POST"> @csrf <button>Submit</button> </form> @endunblaze </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/panel/panel.blade.php
tests/fixtures/components/panel/panel.blade.php
@blaze @props([]) <div class="panel"> <div class="panel-header"> {{ $header }} </div> <div class="panel-body"> {{ $slot }} </div> <div class="panel-footer"> {{ $footer }} </div> </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/aware.blade.php
tests/fixtures/components/invalid-foldable/aware.blade.php
@blaze @aware(['variant' => 'default']) <div class="item item-{{ $variant }}"> {{ $slot }} </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/session.blade.php
tests/fixtures/components/invalid-foldable/session.blade.php
@blaze <div class="message"> {{ session('message') }} </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/csrf.blade.php
tests/fixtures/components/invalid-foldable/csrf.blade.php
@blaze <form method="POST"> @csrf {{ $slot }} </form>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/errors.blade.php
tests/fixtures/components/invalid-foldable/errors.blade.php
@blaze <div class="{{ $errors->has('name') ? 'error' : '' }}"> {{ $slot }} </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/auth.blade.php
tests/fixtures/components/invalid-foldable/auth.blade.php
@blaze <div> Welcome, {{ auth()->user()->name }} </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/request.blade.php
tests/fixtures/components/invalid-foldable/request.blade.php
@blaze <div> Current URL: {{ request()->url() }} </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/old.blade.php
tests/fixtures/components/invalid-foldable/old.blade.php
@blaze <input type="text" name="email" value="{{ old('email') }}" />
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false
livewire/blaze
https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/once.blade.php
tests/fixtures/components/invalid-foldable/once.blade.php
@blaze @props(['title']) <div class="test-component"> <h1>{{ $title }}</h1> @once <script>console.log('This should only run once');</script> @endonce </div>
php
MIT
412a05c7b333ee9ce5d8a61a23f80998ece76a9d
2026-01-05T05:18:39.918460Z
false