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 |
|---|---|---|---|---|---|---|---|---|
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/InternalUtilsTest.php | tests/InternalUtilsTest.php | <?php
namespace GuzzleHttp\Test;
use GuzzleHttp\Psr7;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
class InternalUtilsTest extends TestCase
{
public function testCurrentTime()
{
self::assertGreaterThan(0, Utils::currentTime());
}
/**
* @requires extension idn
*/
public function testIdnConvert()
{
$uri = Psr7\Utils::uriFor('https://яндекс.рф/images');
$uri = Utils::idnUriConvert($uri);
self::assertSame('xn--d1acpjx3f.xn--p1ai', $uri->getHost());
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Handler/CurlHandlerTest.php | tests/Handler/CurlHandlerTest.php | <?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\CurlHandler
*/
class CurlHandlerTest extends TestCase
{
protected function getHandler($options = [])
{
return new CurlHandler($options);
}
public function testCreatesCurlErrors()
{
$handler = new CurlHandler();
$request = new Request('GET', 'http://localhost:123');
$this->expectException(ConnectException::class);
$this->expectExceptionMessage('cURL');
$handler($request, ['timeout' => 0.001, 'connect_timeout' => 0.001])->wait();
}
public function testRedactsUserInfoInErrors()
{
$handler = new CurlHandler();
$request = new Request('GET', 'http://my_user:secretPass@localhost:123');
try {
$handler($request, ['timeout' => 0.001, 'connect_timeout' => 0.001])->wait();
$this->fail('Must throw an Exception.');
} catch (\Throwable $e) {
$this->assertStringNotContainsString('secretPass', $e->getMessage());
}
}
public function testReusesHandles()
{
Server::flush();
$response = new Response(200);
Server::enqueue([$response, $response]);
$a = new CurlHandler();
$request = new Request('GET', Server::$url);
self::assertInstanceOf(FulfilledPromise::class, $a($request, []));
self::assertInstanceOf(FulfilledPromise::class, $a($request, []));
}
public function testDoesSleep()
{
$response = new Response(200);
Server::enqueue([$response]);
$a = new CurlHandler();
$request = new Request('GET', Server::$url);
$s = Utils::currentTime();
$a($request, ['delay' => 0.1])->wait();
self::assertGreaterThan(0.0001, Utils::currentTime() - $s);
}
public function testCreatesCurlErrorsWithContext()
{
$handler = new CurlHandler();
$request = new Request('GET', 'http://localhost:123');
$called = false;
$p = $handler($request, ['timeout' => 0.001, 'connect_timeout' => 0.001])
->otherwise(static function (ConnectException $e) use (&$called) {
$called = true;
self::assertArrayHasKey('errno', $e->getHandlerContext());
});
$p->wait();
self::assertTrue($called);
}
public function testUsesContentLengthWhenOverInMemorySize()
{
Server::flush();
Server::enqueue([new Response()]);
$stream = Psr7\Utils::streamFor(\str_repeat('.', 1000000));
$handler = new CurlHandler();
$request = new Request(
'PUT',
Server::$url,
['Content-Length' => 1000000],
$stream
);
$handler($request, [])->wait();
$received = Server::received()[0];
self::assertEquals(1000000, $received->getHeaderLine('Content-Length'));
self::assertFalse($received->hasHeader('Transfer-Encoding'));
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Handler/ProxyTest.php | tests/Handler/ProxyTest.php | <?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Handler\Proxy;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\Proxy
*/
class ProxyTest extends TestCase
{
public function testSendsToNonSync()
{
$a = $b = null;
$m1 = new MockHandler([static function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([static function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapSync($m1, $m2);
$h(new Request('GET', 'http://foo.com'), []);
self::assertNotNull($a);
self::assertNull($b);
}
public function testSendsToSync()
{
$a = $b = null;
$m1 = new MockHandler([static function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([static function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapSync($m1, $m2);
$h(new Request('GET', 'http://foo.com'), [RequestOptions::SYNCHRONOUS => true]);
self::assertNull($a);
self::assertNotNull($b);
}
public function testSendsToStreaming()
{
$a = $b = null;
$m1 = new MockHandler([static function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([static function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapStreaming($m1, $m2);
$h(new Request('GET', 'http://foo.com'), []);
self::assertNotNull($a);
self::assertNull($b);
}
public function testSendsToNonStreaming()
{
$a = $b = null;
$m1 = new MockHandler([static function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([static function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapStreaming($m1, $m2);
$h(new Request('GET', 'http://foo.com'), ['stream' => true]);
self::assertNull($a);
self::assertNotNull($b);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Handler/CurlMultiHandlerTest.php | tests/Handler/CurlMultiHandlerTest.php | <?php
namespace GuzzleHttp\Tests\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\CurlMultiHandler;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Helpers;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
class CurlMultiHandlerTest extends TestCase
{
public function setUp(): void
{
$_SERVER['curl_test'] = true;
unset($_SERVER['_curl_multi']);
}
public function tearDown(): void
{
unset($_SERVER['_curl_multi'], $_SERVER['curl_test']);
}
public function testCanAddCustomCurlOptions()
{
Server::flush();
Server::enqueue([new Response()]);
$a = new CurlMultiHandler(['options' => [
\CURLMOPT_MAXCONNECTS => 5,
]]);
$request = new Request('GET', Server::$url);
$a($request, []);
self::assertEquals(5, $_SERVER['_curl_multi'][\CURLMOPT_MAXCONNECTS]);
}
public function testSendsRequest()
{
Server::enqueue([new Response()]);
$a = new CurlMultiHandler();
$request = new Request('GET', Server::$url);
$response = $a($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testCreatesExceptions()
{
$a = new CurlMultiHandler();
$this->expectException(ConnectException::class);
$this->expectExceptionMessage('cURL error');
$a(new Request('GET', 'http://localhost:123'), [])->wait();
}
public function testCanSetSelectTimeout()
{
$a = new CurlMultiHandler(['select_timeout' => 2]);
self::assertEquals(2, Helpers::readObjectAttribute($a, 'selectTimeout'));
}
public function testCanCancel()
{
Server::flush();
$response = new Response(200);
Server::enqueue(\array_fill_keys(\range(0, 10), $response));
$a = new CurlMultiHandler();
$responses = [];
for ($i = 0; $i < 10; ++$i) {
$response = $a(new Request('GET', Server::$url), []);
$response->cancel();
$responses[] = $response;
}
foreach ($responses as $r) {
self::assertTrue(P\Is::rejected($r));
}
}
public function testCannotCancelFinished()
{
Server::flush();
Server::enqueue([new Response(200)]);
$a = new CurlMultiHandler();
$response = $a(new Request('GET', Server::$url), []);
$response->wait();
$response->cancel();
self::assertTrue(P\Is::fulfilled($response));
}
public function testDelaysConcurrently()
{
Server::flush();
Server::enqueue([new Response()]);
$a = new CurlMultiHandler();
$expected = Utils::currentTime() + (100 / 1000);
$response = $a(new Request('GET', Server::$url), ['delay' => 100]);
$response->wait();
self::assertGreaterThanOrEqual($expected, Utils::currentTime());
}
public function testUsesTimeoutEnvironmentVariables()
{
unset($_SERVER['GUZZLE_CURL_SELECT_TIMEOUT']);
\putenv('GUZZLE_CURL_SELECT_TIMEOUT=');
try {
$a = new CurlMultiHandler();
// Default if no options are given and no environment variable is set
self::assertEquals(1, Helpers::readObjectAttribute($a, 'selectTimeout'));
\putenv('GUZZLE_CURL_SELECT_TIMEOUT=3');
$a = new CurlMultiHandler();
// Handler reads from the environment if no options are given
self::assertEquals(3, Helpers::readObjectAttribute($a, 'selectTimeout'));
} finally {
\putenv('GUZZLE_CURL_SELECT_TIMEOUT=');
}
}
public function throwsWhenAccessingInvalidProperty()
{
$h = new CurlMultiHandler();
$this->expectException(\BadMethodCallException::class);
$h->foo;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Handler/StreamHandlerTest.php | tests/Handler/StreamHandlerTest.php | <?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\StreamHandler;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
/**
* @covers \GuzzleHttp\Handler\StreamHandler
*/
class StreamHandlerTest extends TestCase
{
private function queueRes()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], 'hi there'),
]);
}
public function testReturnsResponseForSuccessfulRequest()
{
$this->queueRes();
$handler = new StreamHandler();
$response = $handler(
new Request('GET', Server::$url, ['Foo' => 'Bar']),
[]
)->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('8', $response->getHeaderLine('Content-Length'));
self::assertSame('hi there', (string) $response->getBody());
$sent = Server::received()[0];
self::assertSame('GET', $sent->getMethod());
self::assertSame('/', $sent->getUri()->getPath());
self::assertSame('127.0.0.1:8126', $sent->getHeaderLine('Host'));
self::assertSame('Bar', $sent->getHeaderLine('foo'));
}
public function testAddsErrorToResponse()
{
$handler = new StreamHandler();
$this->expectException(ConnectException::class);
$handler(
new Request('GET', 'http://localhost:123'),
['timeout' => 0.01]
)->wait();
}
public function testStreamAttributeKeepsStreamOpen()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request(
'PUT',
Server::$url.'foo?baz=bar',
['Foo' => 'Bar'],
'test'
);
$response = $handler($request, ['stream' => true])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('8', $response->getHeaderLine('Content-Length'));
$body = $response->getBody();
$stream = $body->detach();
self::assertIsResource($stream);
self::assertSame('http', \stream_get_meta_data($stream)['wrapper_type']);
self::assertSame('hi there', \stream_get_contents($stream));
\fclose($stream);
$sent = Server::received()[0];
self::assertSame('PUT', $sent->getMethod());
self::assertSame('http://127.0.0.1:8126/foo?baz=bar', (string) $sent->getUri());
self::assertSame('Bar', $sent->getHeaderLine('Foo'));
self::assertSame('test', (string) $sent->getBody());
}
public function testDrainsResponseIntoTempStream()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('php://temp', \stream_get_meta_data($stream)['uri']);
self::assertSame('hi', \fread($stream, 2));
\fclose($stream);
}
public function testDrainsResponseIntoSaveToBody()
{
$r = \fopen('php://temp', 'r+');
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $r])->wait();
$body = $response->getBody()->detach();
self::assertSame('php://temp', \stream_get_meta_data($body)['uri']);
self::assertSame('hi', \fread($body, 2));
self::assertSame(' there', \stream_get_contents($r));
\fclose($r);
}
public function testDrainsResponseIntoSaveToBodyAtPath()
{
$tmpfname = \tempnam(\sys_get_temp_dir(), 'save_to_path');
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $tmpfname])->wait();
$body = $response->getBody();
self::assertSame($tmpfname, $body->getMetadata('uri'));
self::assertSame('hi', $body->read(2));
$body->close();
\unlink($tmpfname);
}
public function testDrainsResponseIntoSaveToBodyAtNonExistentPath()
{
$tmpfname = \tempnam(\sys_get_temp_dir(), 'save_to_path');
\unlink($tmpfname);
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $tmpfname])->wait();
$body = $response->getBody();
self::assertSame($tmpfname, $body->getMetadata('uri'));
self::assertSame('hi', $body->read(2));
$body->close();
\unlink($tmpfname);
}
public function testDrainsResponseAndReadsOnlyContentLengthBytes()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], 'hi there... This has way too much data!'),
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('hi there', \stream_get_contents($stream));
\fclose($stream);
}
public function testDoesNotDrainWhenHeadRequest()
{
Server::flush();
// Say the content-length is 8, but return no response.
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], ''),
]);
$handler = new StreamHandler();
$request = new Request('HEAD', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('', \stream_get_contents($stream));
\fclose($stream);
}
public function testAutomaticallyDecompressGzip()
{
Server::flush();
$content = \gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => \strlen($content),
], $content),
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true])->wait();
self::assertSame('test', (string) $response->getBody());
self::assertFalse($response->hasHeader('content-encoding'));
self::assertTrue(!$response->hasHeader('content-length') || $response->getHeaderLine('content-length') == $response->getBody()->getSize());
}
public function testAutomaticallyDecompressGzipHead()
{
Server::flush();
$content = \gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => \strlen($content),
], $content),
]);
$handler = new StreamHandler();
$request = new Request('HEAD', Server::$url);
$response = $handler($request, ['decode_content' => true])->wait();
// Verify that the content-length matches the encoded size.
self::assertTrue(!$response->hasHeader('content-length') || $response->getHeaderLine('content-length') == \strlen($content));
}
public function testReportsOriginalSizeAndContentEncodingAfterDecoding()
{
Server::flush();
$content = \gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => \strlen($content),
], $content),
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true])->wait();
self::assertSame(
'gzip',
$response->getHeaderLine('x-encoded-content-encoding')
);
self::assertSame(
\strlen($content),
(int) $response->getHeaderLine('x-encoded-content-length')
);
}
public function testDoesNotForceGzipDecode()
{
Server::flush();
$content = \gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => \strlen($content),
], $content),
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => false])->wait();
self::assertSame($content, (string) $response->getBody());
self::assertSame('gzip', $response->getHeaderLine('content-encoding'));
self::assertEquals(\strlen($content), $response->getHeaderLine('content-length'));
}
public function testProtocolVersion()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url, [], null, '1.0');
$handler($request, []);
self::assertSame('1.0', Server::received()[0]->getProtocolVersion());
}
protected function getSendResult(array $opts)
{
$this->queueRes();
$handler = new StreamHandler();
$opts['stream'] = true;
$request = new Request('GET', Server::$url);
return $handler($request, $opts)->wait();
}
public function testAddsProxy()
{
$this->expectException(ConnectException::class);
$this->expectExceptionMessage('Connection refused');
$this->getSendResult(['proxy' => '127.0.0.1:8125']);
}
public function testAddsProxyByProtocol()
{
$url = Server::$url;
$res = $this->getSendResult(['proxy' => ['http' => $url]]);
$opts = \stream_context_get_options($res->getBody()->detach());
foreach ([\PHP_URL_HOST, \PHP_URL_PORT] as $part) {
self::assertSame(parse_url($url, $part), parse_url($opts['http']['proxy'], $part));
}
}
public function testAddsProxyButHonorsNoProxy()
{
$url = Server::$url;
$res = $this->getSendResult(['proxy' => [
'http' => $url,
'no' => ['*'],
]]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertArrayNotHasKey('proxy', $opts['http']);
}
public function testUsesProxy()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', 'http://www.example.com', [], null, '1.0');
$response = $handler($request, [
'proxy' => Server::$url,
])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('8', $response->getHeaderLine('Content-Length'));
self::assertSame('hi there', (string) $response->getBody());
}
public function testAddsTimeout()
{
$res = $this->getSendResult(['stream' => true, 'timeout' => 200]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertEquals(200, $opts['http']['timeout']);
}
public function testVerifiesVerifyIsValidIfPath()
{
$this->expectException(RequestException::class);
$this->expectExceptionMessage('SSL CA bundle not found: /does/not/exist');
$this->getSendResult(['verify' => '/does/not/exist']);
}
public function testVerifyCanBeDisabled()
{
$handler = $this->getSendResult(['verify' => false]);
self::assertInstanceOf(Response::class, $handler);
}
public function testVerifiesCertIfValidPath()
{
$this->expectException(RequestException::class);
$this->expectExceptionMessage('SSL certificate not found: /does/not/exist');
$this->getSendResult(['cert' => '/does/not/exist']);
}
public function testVerifyCanBeSetToPath()
{
$path = Utils::defaultCaBundle();
$res = $this->getSendResult(['verify' => $path]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertTrue($opts['ssl']['verify_peer']);
self::assertTrue($opts['ssl']['verify_peer_name']);
self::assertSame($path, $opts['ssl']['cafile']);
self::assertFileExists($opts['ssl']['cafile']);
}
public function testUsesSystemDefaultBundle()
{
$res = $this->getSendResult(['verify' => true]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertArrayNotHasKey('cafile', $opts['ssl']);
}
public function testEnsuresVerifyOptionIsValid()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid verify request option');
$this->getSendResult(['verify' => 10]);
}
public function testEnsuresCryptoMethodOptionIsValid()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid crypto_method request option: unknown version provided');
$this->getSendResult(['crypto_method' => 123]);
}
public function testSetsCryptoMethodTls10()
{
$res = $this->getSendResult(['crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertSame(\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT, $opts['http']['crypto_method']);
}
public function testSetsCryptoMethodTls11()
{
$res = $this->getSendResult(['crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertSame(\STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT, $opts['http']['crypto_method']);
}
public function testSetsCryptoMethodTls12()
{
$res = $this->getSendResult(['crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertSame(\STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, $opts['http']['crypto_method']);
}
/**
* @requires PHP >=7.4
*/
public function testSetsCryptoMethodTls13()
{
$res = $this->getSendResult(['crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertSame(\STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT, $opts['http']['crypto_method']);
}
public function testCanSetPasswordWhenSettingCert()
{
$path = __FILE__;
$res = $this->getSendResult(['cert' => [$path, 'foo']]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertSame($path, $opts['ssl']['local_cert']);
self::assertSame('foo', $opts['ssl']['passphrase']);
}
public function testDebugAttributeWritesToStream()
{
$this->queueRes();
$f = \fopen('php://temp', 'w+');
$this->getSendResult(['debug' => $f]);
\fseek($f, 0);
$contents = \stream_get_contents($f);
self::assertStringContainsString('<GET http://127.0.0.1:8126/> [CONNECT]', $contents);
self::assertStringContainsString('<GET http://127.0.0.1:8126/> [FILE_SIZE_IS]', $contents);
self::assertStringContainsString('<GET http://127.0.0.1:8126/> [PROGRESS]', $contents);
}
public function testDebugAttributeWritesStreamInfoToBuffer()
{
$called = false;
$this->queueRes();
$buffer = \fopen('php://temp', 'r+');
$this->getSendResult([
'progress' => static function () use (&$called) {
$called = true;
},
'debug' => $buffer,
]);
\fseek($buffer, 0);
$contents = \stream_get_contents($buffer);
self::assertStringContainsString('<GET http://127.0.0.1:8126/> [CONNECT]', $contents);
self::assertStringContainsString('<GET http://127.0.0.1:8126/> [FILE_SIZE_IS] message: "Content-Length: 8"', $contents);
self::assertStringContainsString('<GET http://127.0.0.1:8126/> [PROGRESS] bytes_max: "8"', $contents);
self::assertTrue($called);
}
public function testEmitsProgressInformation()
{
$called = [];
$this->queueRes();
$this->getSendResult([
'progress' => static function (...$args) use (&$called) {
$called[] = $args;
},
]);
self::assertNotEmpty($called);
self::assertEquals(8, $called[0][0]);
self::assertEquals(0, $called[0][1]);
}
public function testEmitsProgressInformationAndDebugInformation()
{
$called = [];
$this->queueRes();
$buffer = \fopen('php://memory', 'w+');
$this->getSendResult([
'debug' => $buffer,
'progress' => static function (...$args) use (&$called) {
$called[] = $args;
},
]);
self::assertNotEmpty($called);
self::assertEquals(8, $called[0][0]);
self::assertEquals(0, $called[0][1]);
\rewind($buffer);
self::assertNotEmpty(\stream_get_contents($buffer));
\fclose($buffer);
}
public function testPerformsShallowMergeOfCustomContextOptions()
{
$res = $this->getSendResult([
'stream_context' => [
'http' => [
'request_fulluri' => true,
'method' => 'HEAD',
],
'socket' => [
'bindto' => '127.0.0.1:0',
],
'ssl' => [
'verify_peer' => false,
],
],
]);
$opts = \stream_context_get_options($res->getBody()->detach());
self::assertSame('HEAD', $opts['http']['method']);
self::assertTrue($opts['http']['request_fulluri']);
self::assertSame('127.0.0.1:0', $opts['socket']['bindto']);
self::assertFalse($opts['ssl']['verify_peer']);
}
public function testEnsuresThatStreamContextIsAnArray()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('stream_context must be an array');
$this->getSendResult(['stream_context' => 'foo']);
}
public function testDoesNotAddContentTypeByDefault()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, ['Content-Length' => 3], 'foo');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals('', $req->getHeaderLine('Content-Type'));
self::assertEquals(3, $req->getHeaderLine('Content-Length'));
}
public function testAddsContentLengthByDefault()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, [], 'foo');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals(3, $req->getHeaderLine('Content-Length'));
}
public function testAddsContentLengthForPUTEvenWhenEmpty()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, [], '');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals(0, $req->getHeaderLine('Content-Length'));
}
public function testAddsContentLengthForPOSTEvenWhenEmpty()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('POST', Server::$url, [], '');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals(0, $req->getHeaderLine('Content-Length'));
}
public function testDontAddContentLengthForGETEvenWhenEmpty()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url, [], '');
$handler($request, []);
$req = Server::received()[0];
self::assertSame('', $req->getHeaderLine('Content-Length'));
}
public function testSupports100Continue()
{
Server::flush();
$response = new Response(200, ['Test' => 'Hello', 'Content-Length' => '4'], 'test');
Server::enqueue([$response]);
$request = new Request('PUT', Server::$url, ['Expect' => '100-Continue'], 'test');
$handler = new StreamHandler();
$response = $handler($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('Hello', $response->getHeaderLine('Test'));
self::assertSame('4', $response->getHeaderLine('Content-Length'));
self::assertSame('test', (string) $response->getBody());
}
public function testDoesSleep()
{
$response = new Response(200);
Server::enqueue([$response]);
$a = new StreamHandler();
$request = new Request('GET', Server::$url);
$s = Utils::currentTime();
$a($request, ['delay' => 0.1])->wait();
self::assertGreaterThan(0.0001, Utils::currentTime() - $s);
}
public function testEnsuresOnHeadersIsCallable()
{
$req = new Request('GET', Server::$url);
$handler = new StreamHandler();
$this->expectException(\InvalidArgumentException::class);
$handler($req, ['on_headers' => 'error!']);
}
public function testRejectsPromiseWhenOnHeadersFails()
{
Server::flush();
Server::enqueue([
new Response(200, ['X-Foo' => 'bar'], 'abc 123'),
]);
$req = new Request('GET', Server::$url);
$handler = new StreamHandler();
$promise = $handler($req, [
'on_headers' => static function () {
throw new \Exception('test');
},
]);
$this->expectException(RequestException::class);
$this->expectExceptionMessage('An error was encountered during the on_headers event');
$promise->wait();
}
public function testSuccessfullyCallsOnHeadersBeforeWritingToSink()
{
Server::flush();
Server::enqueue([
new Response(200, ['X-Foo' => 'bar'], 'abc 123'),
]);
$req = new Request('GET', Server::$url);
$got = null;
$stream = Psr7\Utils::streamFor();
$stream = FnStream::decorate($stream, [
'write' => static function ($data) use ($stream, &$got) {
self::assertNotNull($got);
return $stream->write($data);
},
]);
$handler = new StreamHandler();
$promise = $handler($req, [
'sink' => $stream,
'on_headers' => static function (ResponseInterface $res) use (&$got) {
$got = $res;
self::assertSame('bar', $res->getHeaderLine('X-Foo'));
},
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('bar', $response->getHeaderLine('X-Foo'));
self::assertSame('abc 123', (string) $response->getBody());
}
public function testInvokesOnStatsOnSuccess()
{
Server::flush();
Server::enqueue([new Response(200)]);
$req = new Request('GET', Server::$url);
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'on_stats' => static function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
},
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame(200, $gotStats->getResponse()->getStatusCode());
self::assertSame(
Server::$url,
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
Server::$url,
(string) $gotStats->getRequest()->getUri()
);
self::assertGreaterThan(0, $gotStats->getTransferTime());
}
public function testInvokesOnStatsOnError()
{
$req = new Request('GET', 'http://127.0.0.1:123');
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'connect_timeout' => 0.001,
'timeout' => 0.001,
'on_stats' => static function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
},
]);
$promise->wait(false);
self::assertFalse($gotStats->hasResponse());
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getRequest()->getUri()
);
self::assertIsFloat($gotStats->getTransferTime());
self::assertInstanceOf(
ConnectException::class,
$gotStats->getHandlerErrorData()
);
}
public function testStreamIgnoresZeroTimeout()
{
Server::flush();
Server::enqueue([new Response(200)]);
$req = new Request('GET', Server::$url);
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'connect_timeout' => 10,
'timeout' => 0,
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testDrainsResponseAndReadsAllContentWhenContentLengthIsZero()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => '0',
], 'hi there... This has a lot of data!'),
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('hi there... This has a lot of data!', \stream_get_contents($stream));
\fclose($stream);
}
public function testHonorsReadTimeout()
{
Server::flush();
$handler = new StreamHandler();
$response = $handler(
new Request('GET', Server::$url.'guzzle-server/read-timeout'),
[
RequestOptions::READ_TIMEOUT => 1,
RequestOptions::STREAM => true,
]
)->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
$body = $response->getBody()->detach();
$line = \fgets($body);
self::assertSame("sleeping 60 seconds ...\n", $line);
$line = \fgets($body);
self::assertFalse($line);
self::assertTrue(\stream_get_meta_data($body)['timed_out']);
self::assertFalse(\feof($body));
}
private static function shouldRunOnThisPhpVersion(): bool
{
return (PHP_VERSION_ID >= 80132 && PHP_VERSION_ID < 80200)
|| (PHP_VERSION_ID >= 80228 && PHP_VERSION_ID < 80300)
|| (PHP_VERSION_ID >= 80319 && PHP_VERSION_ID < 80400)
|| PHP_VERSION_ID >= 80405;
}
public function testHandlesGarbageHttpServerGracefullyLegacy()
{
if (self::shouldRunOnThisPhpVersion()) {
$this->markTestSkipped('This test is not relevant for '.PHP_VERSION);
}
$handler = new StreamHandler();
$this->expectException(RequestException::class);
$this->expectExceptionMessage('An error was encountered while creating the response');
$handler(
new Request('GET', Server::$url.'guzzle-server/garbage'),
[
RequestOptions::STREAM => true,
]
)->wait();
}
public function testHandlesGarbageHttpServerGracefully()
{
if (!self::shouldRunOnThisPhpVersion()) {
$this->markTestSkipped('This test is not relevant for '.PHP_VERSION);
}
$handler = new StreamHandler();
$this->expectException(ConnectException::class);
$this->expectExceptionMessage('Connection refused for URI '.Server::$url);
$handler(
new Request('GET', Server::$url.'guzzle-server/garbage'),
[
RequestOptions::STREAM => true,
]
)->wait();
}
public function testHandlesInvalidStatusCodeGracefully()
{
$handler = new StreamHandler();
$this->expectException(RequestException::class);
$this->expectExceptionMessage('An error was encountered while creating the response');
$handler(
new Request('GET', Server::$url.'guzzle-server/bad-status'),
[
RequestOptions::STREAM => true,
]
)->wait();
}
public function testRejectsNonHttpSchemes()
{
$handler = new StreamHandler();
$this->expectException(RequestException::class);
$this->expectExceptionMessage("The scheme 'file' is not supported.");
$handler(
new Request('GET', 'file:///etc/passwd'),
[
RequestOptions::STREAM => true,
]
)->wait();
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Handler/MockHandlerTest.php | tests/Handler/MockHandlerTest.php | <?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Stream;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\MockHandler
*/
class MockHandlerTest extends TestCase
{
public function testReturnsMockResponse()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, []);
self::assertSame($res, $p->wait());
}
public function testIsCountable()
{
$res = new Response();
$mock = new MockHandler([$res, $res]);
self::assertCount(2, $mock);
}
public function testEmptyHandlerIsCountable()
{
self::assertCount(0, new MockHandler());
}
public function testEnsuresEachAppendOnCreationIsValid()
{
$this->expectException(\TypeError::class);
new MockHandler(['a']);
}
public function testEnsuresEachAppendIsValid()
{
$mock = new MockHandler();
$this->expectException(\TypeError::class);
$mock->append(['a']);
}
public function testCanQueueExceptions()
{
$e = new \Exception('a');
$mock = new MockHandler([$e]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, []);
try {
$p->wait();
self::fail();
} catch (\Exception $e2) {
self::assertSame($e, $e2);
}
}
public function testCanGetLastRequestAndOptions()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$mock($request, ['foo' => 'bar']);
self::assertSame($request, $mock->getLastRequest());
self::assertSame(['foo' => 'bar'], $mock->getLastOptions());
}
public function testSinkFilename()
{
$filename = \sys_get_temp_dir().'/mock_test_'.\uniqid();
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $filename]);
$p->wait();
self::assertFileExists($filename);
self::assertStringEqualsFile($filename, 'TEST CONTENT');
\unlink($filename);
}
public function testSinkResource()
{
$file = \tmpfile();
$meta = \stream_get_meta_data($file);
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $file]);
$p->wait();
self::assertFileExists($meta['uri']);
self::assertStringEqualsFile($meta['uri'], 'TEST CONTENT');
}
public function testSinkStream()
{
$stream = new Stream(\tmpfile());
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $stream]);
$p->wait();
self::assertFileExists($stream->getMetadata('uri'));
self::assertStringEqualsFile($stream->getMetadata('uri'), 'TEST CONTENT');
}
public function testCanEnqueueCallables()
{
$r = new Response();
$fn = static function ($req, $o) use ($r) {
return $r;
};
$mock = new MockHandler([$fn]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, ['foo' => 'bar']);
self::assertSame($r, $p->wait());
}
public function testEnsuresOnHeadersIsCallable()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$this->expectException(\InvalidArgumentException::class);
$mock($request, ['on_headers' => 'error!']);
}
public function testRejectsPromiseWhenOnHeadersFails()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$promise = $mock($request, [
'on_headers' => static function () {
throw new \Exception('test');
},
]);
$this->expectException(RequestException::class);
$this->expectExceptionMessage('An error was encountered during the on_headers event');
$promise->wait();
}
public function testInvokesOnFulfilled()
{
$res = new Response();
$mock = new MockHandler([$res], static function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$mock($request, [])->wait();
self::assertSame($res, $c);
}
public function testInvokesOnRejected()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, static function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$mock($request, [])->wait(false);
self::assertSame($e, $c);
}
public function testThrowsWhenNoMoreResponses()
{
$mock = new MockHandler();
$request = new Request('GET', 'http://example.com');
$this->expectException(\OutOfBoundsException::class);
$mock($request, []);
}
public function testCanCreateWithDefaultMiddleware()
{
$r = new Response(500);
$mock = MockHandler::createWithMiddleware([$r]);
$request = new Request('GET', 'http://example.com');
$this->expectException(BadResponseException::class);
$mock($request, ['http_errors' => true])->wait();
}
public function testInvokesOnStatsFunctionForResponse()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
/** @var TransferStats|null $stats */
$stats = null;
$onStats = static function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$p = $mock($request, ['on_stats' => $onStats]);
$p->wait();
self::assertSame($res, $stats->getResponse());
self::assertSame($request, $stats->getRequest());
}
public function testInvokesOnStatsFunctionForError()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, static function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
/** @var TransferStats|null $stats */
$stats = null;
$onStats = static function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$mock($request, ['on_stats' => $onStats])->wait(false);
self::assertSame($e, $stats->getHandlerErrorData());
self::assertNull($stats->getResponse());
self::assertSame($request, $stats->getRequest());
}
public function testTransferTime()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, static function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$stats = null;
$onStats = static function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$mock($request, ['on_stats' => $onStats, 'transfer_time' => 0.4])->wait(false);
self::assertEquals(0.4, $stats->getTransferTime());
}
public function testResetQueue()
{
$mock = new MockHandler([new Response(200), new Response(204)]);
self::assertCount(2, $mock);
$mock->reset();
self::assertEmpty($mock);
$mock->append(new Response(500));
self::assertCount(1, $mock);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Handler/EasyHandleTest.php | tests/Handler/EasyHandleTest.php | <?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler\EasyHandle;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\EasyHandle
*/
class EasyHandleTest extends TestCase
{
public function testEnsuresHandleExists()
{
$easy = new EasyHandle();
unset($easy->handle);
$this->expectException(\BadMethodCallException::class);
$this->expectExceptionMessage('The EasyHandle has been released');
$easy->handle;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Handler/CurlFactoryTest.php | tests/Handler/CurlFactoryTest.php | <?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler;
use GuzzleHttp\Handler\CurlFactory;
use GuzzleHttp\Handler\EasyHandle;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Psr7;
use GuzzleHttp\Tests\Helpers;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
/**
* @covers \GuzzleHttp\Handler\CurlFactory
*/
class CurlFactoryTest extends TestCase
{
public static function setUpBeforeClass(): void
{
$_SERVER['curl_test'] = true;
unset($_SERVER['_curl']);
}
public static function tearDownAfterClass(): void
{
unset($_SERVER['_curl'], $_SERVER['curl_test']);
}
public function testCreatesCurlHandle()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, [
'Foo' => 'Bar',
'Baz' => 'bam',
'Content-Length' => 2,
], 'hi'),
]);
$stream = Psr7\Utils::streamFor();
$request = new Psr7\Request('PUT', Server::$url, [
'Hi' => ' 123',
'Content-Length' => '7',
], 'testing');
$f = new CurlFactory(3);
$result = $f->create($request, ['sink' => $stream]);
try {
self::assertInstanceOf(EasyHandle::class, $result);
if (\PHP_VERSION_ID >= 80000) {
self::assertInstanceOf(\CurlHandle::class, $result->handle);
} else {
self::assertIsResource($result->handle);
}
self::assertIsArray($result->headers);
self::assertSame($stream, $result->sink);
} finally {
if (PHP_VERSION_ID < 80000) {
\curl_close($result->handle);
}
}
self::assertSame('PUT', $_SERVER['_curl'][\CURLOPT_CUSTOMREQUEST]);
self::assertSame(
'http://127.0.0.1:8126/',
$_SERVER['_curl'][\CURLOPT_URL]
);
// Sends via post fields when the request is small enough
self::assertSame('testing', $_SERVER['_curl'][\CURLOPT_POSTFIELDS]);
self::assertEquals(0, $_SERVER['_curl'][\CURLOPT_RETURNTRANSFER]);
self::assertEquals(0, $_SERVER['_curl'][\CURLOPT_HEADER]);
self::assertSame(300, $_SERVER['_curl'][\CURLOPT_CONNECTTIMEOUT]);
self::assertInstanceOf('Closure', $_SERVER['_curl'][\CURLOPT_HEADERFUNCTION]);
if (\defined('CURLOPT_PROTOCOLS')) {
self::assertSame(
\CURLPROTO_HTTP | \CURLPROTO_HTTPS,
$_SERVER['_curl'][\CURLOPT_PROTOCOLS]
);
}
self::assertContains('Expect:', $_SERVER['_curl'][\CURLOPT_HTTPHEADER]);
self::assertContains('Accept:', $_SERVER['_curl'][\CURLOPT_HTTPHEADER]);
self::assertContains('Content-Type:', $_SERVER['_curl'][\CURLOPT_HTTPHEADER]);
self::assertContains('Hi: 123', $_SERVER['_curl'][\CURLOPT_HTTPHEADER]);
self::assertContains('Host: 127.0.0.1:8126', $_SERVER['_curl'][\CURLOPT_HTTPHEADER]);
}
public function testSendsHeadRequests()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$response = $a(new Psr7\Request('HEAD', Server::$url), []);
$response->wait();
self::assertTrue($_SERVER['_curl'][\CURLOPT_NOBODY]);
$checks = [\CURLOPT_READFUNCTION, \CURLOPT_FILE, \CURLOPT_INFILE];
foreach ($checks as $check) {
self::assertArrayNotHasKey($check, $_SERVER['_curl']);
}
self::assertEquals('HEAD', Server::received()[0]->getMethod());
}
public function testCanAddCustomCurlOptions()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$req = new Psr7\Request('GET', Server::$url);
$a($req, ['curl' => [\CURLOPT_LOW_SPEED_LIMIT => 10]]);
self::assertEquals(10, $_SERVER['_curl'][\CURLOPT_LOW_SPEED_LIMIT]);
}
public function testCanChangeCurlOptions()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$req = new Psr7\Request('GET', Server::$url);
$a($req, ['curl' => [\CURLOPT_HTTP_VERSION => \CURL_HTTP_VERSION_1_0]]);
self::assertEquals(\CURL_HTTP_VERSION_1_0, $_SERVER['_curl'][\CURLOPT_HTTP_VERSION]);
}
public function testValidatesVerify()
{
$f = new CurlFactory(3);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('SSL CA bundle not found: /does/not/exist');
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => '/does/not/exist']);
}
public function testCanSetVerifyToFile()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', 'http://foo.com'), ['verify' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][\CURLOPT_CAINFO]);
self::assertEquals(2, $_SERVER['_curl'][\CURLOPT_SSL_VERIFYHOST]);
self::assertTrue($_SERVER['_curl'][\CURLOPT_SSL_VERIFYPEER]);
}
public function testCanSetVerifyToDir()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', 'http://foo.com'), ['verify' => __DIR__]);
self::assertEquals(__DIR__, $_SERVER['_curl'][\CURLOPT_CAPATH]);
self::assertEquals(2, $_SERVER['_curl'][\CURLOPT_SSL_VERIFYHOST]);
self::assertTrue($_SERVER['_curl'][\CURLOPT_SSL_VERIFYPEER]);
}
public function testAddsVerifyAsTrue()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => true]);
self::assertEquals(2, $_SERVER['_curl'][\CURLOPT_SSL_VERIFYHOST]);
self::assertTrue($_SERVER['_curl'][\CURLOPT_SSL_VERIFYPEER]);
self::assertArrayNotHasKey(\CURLOPT_CAINFO, $_SERVER['_curl']);
}
public function testCanDisableVerify()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => false]);
self::assertEquals(0, $_SERVER['_curl'][\CURLOPT_SSL_VERIFYHOST]);
self::assertFalse($_SERVER['_curl'][\CURLOPT_SSL_VERIFYPEER]);
}
public function testAddsProxy()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['proxy' => 'http://bar.com']);
self::assertEquals('http://bar.com', $_SERVER['_curl'][\CURLOPT_PROXY]);
}
public function testAddsViaScheme()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), [
'proxy' => ['http' => 'http://bar.com', 'https' => 'https://t'],
]);
self::assertEquals('http://bar.com', $_SERVER['_curl'][\CURLOPT_PROXY]);
$this->checkNoProxyForHost('http://test.test.com', ['test.test.com'], false);
$this->checkNoProxyForHost('http://test.test.com', ['.test.com'], false);
$this->checkNoProxyForHost('http://test.test.com', ['*.test.com'], true);
$this->checkNoProxyForHost('http://test.test.com', ['*'], false);
$this->checkNoProxyForHost('http://127.0.0.1', ['127.0.0.*'], true);
}
private function checkNoProxyForHost($url, $noProxy, $assertUseProxy)
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', $url), [
'proxy' => [
'http' => 'http://bar.com',
'https' => 'https://t',
'no' => $noProxy,
],
]);
if ($assertUseProxy) {
self::assertArrayHasKey(\CURLOPT_PROXY, $_SERVER['_curl']);
} else {
self::assertArrayNotHasKey(\CURLOPT_PROXY, $_SERVER['_curl']);
}
}
public function testUsesProxy()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, [
'Foo' => 'Bar',
'Baz' => 'bam',
'Content-Length' => 2,
], 'hi'),
]);
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', 'http://www.example.com', [], null, '1.0');
$promise = $handler($request, [
'proxy' => Server::$url,
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('2', $response->getHeaderLine('Content-Length'));
self::assertSame('hi', (string) $response->getBody());
}
public function testValidatesCryptoMethodInvalidMethod()
{
$f = new CurlFactory(3);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid crypto_method request option: unknown version provided');
$f->create(new Psr7\Request('GET', Server::$url), ['crypto_method' => 123]);
}
public function testAddsCryptoMethodTls10()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT]);
self::assertEquals(\CURL_SSLVERSION_TLSv1_0, $_SERVER['_curl'][\CURLOPT_SSLVERSION]);
}
public function testAddsCryptoMethodTls11()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT]);
self::assertEquals(\CURL_SSLVERSION_TLSv1_1, $_SERVER['_curl'][\CURLOPT_SSLVERSION]);
}
public function testAddsCryptoMethodTls12()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT]);
self::assertEquals(\CURL_SSLVERSION_TLSv1_2, $_SERVER['_curl'][\CURLOPT_SSLVERSION]);
}
/**
* @requires PHP >= 7.4
*/
public function testAddsCryptoMethodTls13()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT]);
self::assertEquals(\CURL_SSLVERSION_TLSv1_3, $_SERVER['_curl'][\CURLOPT_SSLVERSION]);
}
public function testValidatesSslKey()
{
$f = new CurlFactory(3);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('SSL private key not found: /does/not/exist');
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => '/does/not/exist']);
}
public function testAddsSslKey()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][\CURLOPT_SSLKEY]);
}
public function testAddsSslKeyWithPassword()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => [__FILE__, 'test']]);
self::assertEquals(__FILE__, $_SERVER['_curl'][\CURLOPT_SSLKEY]);
self::assertEquals('test', $_SERVER['_curl'][\CURLOPT_SSLKEYPASSWD]);
}
public function testAddsSslKeyWhenUsingArraySyntaxButNoPassword()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => [__FILE__]]);
self::assertEquals(__FILE__, $_SERVER['_curl'][\CURLOPT_SSLKEY]);
}
public function testValidatesCert()
{
$f = new CurlFactory(3);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('SSL certificate not found: /does/not/exist');
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => '/does/not/exist']);
}
public function testAddsCert()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][\CURLOPT_SSLCERT]);
}
public function testAddsCertWithPassword()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => [__FILE__, 'test']]);
self::assertEquals(__FILE__, $_SERVER['_curl'][\CURLOPT_SSLCERT]);
self::assertEquals('test', $_SERVER['_curl'][\CURLOPT_SSLCERTPASSWD]);
}
public function testAddsDerCert()
{
$certFile = tempnam(sys_get_temp_dir(), 'mock_test_cert');
rename($certFile, $certFile .= '.der');
try {
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => $certFile]);
self::assertArrayHasKey(\CURLOPT_SSLCERTTYPE, $_SERVER['_curl']);
self::assertEquals('DER', $_SERVER['_curl'][\CURLOPT_SSLCERTTYPE]);
} finally {
@\unlink($certFile);
}
}
public function testAddsP12Cert()
{
$certFile = tempnam(sys_get_temp_dir(), 'mock_test_cert');
rename($certFile, $certFile .= '.p12');
try {
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => $certFile]);
self::assertArrayHasKey(\CURLOPT_SSLCERTTYPE, $_SERVER['_curl']);
self::assertEquals('P12', $_SERVER['_curl'][\CURLOPT_SSLCERTTYPE]);
} finally {
@\unlink($certFile);
}
}
public function testValidatesProgress()
{
$f = new CurlFactory(3);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('progress client option must be callable');
$f->create(new Psr7\Request('GET', Server::$url), ['progress' => 'foo']);
}
public function testEmitsDebugInfoToStream()
{
$res = \fopen('php://temp', 'r+');
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$response = $a(new Psr7\Request('HEAD', Server::$url), ['debug' => $res]);
$response->wait();
\rewind($res);
$output = \str_replace("\r", '', \stream_get_contents($res));
self::assertStringContainsString('> HEAD / HTTP/1.1', $output);
self::assertStringContainsString('< HTTP/1.1 200', $output);
\fclose($res);
}
public function testEmitsProgressToFunction()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$called = [];
$request = new Psr7\Request('HEAD', Server::$url);
$response = $a($request, [
'progress' => static function (...$args) use (&$called) {
$called[] = $args;
},
]);
$response->wait();
self::assertNotEmpty($called);
foreach ($called as $call) {
self::assertCount(4, $call);
}
}
private function addDecodeResponse($withEncoding = true)
{
$content = \gzencode('test');
$headers = ['Content-Length' => \strlen($content)];
if ($withEncoding) {
$headers['Content-Encoding'] = 'gzip';
}
$response = new Psr7\Response(200, $headers, $content);
Server::flush();
Server::enqueue([$response]);
return $content;
}
public function testDecodesGzippedResponses()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertEquals('test', (string) $response->getBody());
self::assertEquals('', $_SERVER['_curl'][\CURLOPT_ENCODING]);
$sent = Server::received()[0];
self::assertFalse($sent->hasHeader('Accept-Encoding'));
}
public function testReportsOriginalSizeAndContentEncodingAfterDecoding()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertSame(
'gzip',
$response->getHeaderLine('x-encoded-content-encoding')
);
self::assertSame(
\strlen(\gzencode('test')),
(int) $response->getHeaderLine('x-encoded-content-length')
);
}
public function testDecodesGzippedResponsesWithHeader()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url, ['Accept-Encoding' => 'gzip']);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertEquals('gzip', $_SERVER['_curl'][\CURLOPT_ENCODING]);
$sent = Server::received()[0];
self::assertEquals('gzip', $sent->getHeaderLine('Accept-Encoding'));
self::assertEquals('test', (string) $response->getBody());
self::assertFalse($response->hasHeader('content-encoding'));
self::assertTrue(
!$response->hasHeader('content-length')
|| $response->getHeaderLine('content-length') == $response->getBody()->getSize()
);
}
/**
* https://github.com/guzzle/guzzle/issues/2799
*/
public function testDecodesGzippedResponsesWithHeaderForHeadRequest()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('HEAD', Server::$url, ['Accept-Encoding' => 'gzip']);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertEquals('gzip', $_SERVER['_curl'][\CURLOPT_ENCODING]);
$sent = Server::received()[0];
self::assertEquals('gzip', $sent->getHeaderLine('Accept-Encoding'));
// Verify that the content-length matches the encoded size.
self::assertTrue(
!$response->hasHeader('content-length')
|| $response->getHeaderLine('content-length') == \strlen(\gzencode('test'))
);
}
public function testDoesNotForceDecode()
{
$content = $this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => false]);
$response = $response->wait();
$sent = Server::received()[0];
self::assertFalse($sent->hasHeader('Accept-Encoding'));
self::assertEquals($content, (string) $response->getBody());
}
public function testProtocolVersion()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url, [], null, '1.0');
$a($request, []);
self::assertEquals(\CURL_HTTP_VERSION_1_0, $_SERVER['_curl'][\CURLOPT_HTTP_VERSION]);
}
public function testSavesToStream()
{
$stream = \fopen('php://memory', 'r+');
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $stream,
]);
$response->wait();
\rewind($stream);
self::assertEquals('test', \stream_get_contents($stream));
}
public function testSavesToGuzzleStream()
{
$stream = Psr7\Utils::streamFor();
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $stream,
]);
$response->wait();
self::assertEquals('test', (string) $stream);
}
public function testSavesToFileOnDisk()
{
$tmpfile = \tempnam(\sys_get_temp_dir(), 'testfile');
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $tmpfile,
]);
$response->wait();
self::assertStringEqualsFile($tmpfile, 'test');
@\unlink($tmpfile);
}
public function testDoesNotAddMultipleContentLengthHeaders()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('PUT', Server::$url, ['Content-Length' => 3], 'foo');
$response = $handler($request, []);
$response->wait();
$sent = Server::received()[0];
self::assertEquals(3, $sent->getHeaderLine('Content-Length'));
self::assertFalse($sent->hasHeader('Transfer-Encoding'));
self::assertEquals('foo', (string) $sent->getBody());
}
public function testSendsPostWithNoBodyOrDefaultContentType()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('POST', Server::$url);
$response = $handler($request, []);
$response->wait();
$received = Server::received()[0];
self::assertEquals('POST', $received->getMethod());
self::assertFalse($received->hasHeader('content-type'));
self::assertSame('0', $received->getHeaderLine('content-length'));
}
public function testFailsWhenCannotRewindRetryAfterNoResponse()
{
$factory = new CurlFactory(1);
$stream = Psr7\Utils::streamFor('abc');
$stream->read(1);
$stream = new Psr7\NoSeekStream($stream);
$request = new Psr7\Request('PUT', Server::$url, [], $stream);
$fn = static function ($request, $options) use (&$fn, $factory) {
$easy = $factory->create($request, $options);
return CurlFactory::finish($fn, $easy, $factory);
};
$this->expectException(RequestException::class);
$this->expectExceptionMessage('but attempting to rewind the request body failed');
$fn($request, [])->wait();
}
public function testRetriesWhenBodyCanBeRewound()
{
$callHandler = $called = false;
$fn = static function ($r, $options) use (&$callHandler) {
$callHandler = true;
return P\Create::promiseFor(new Psr7\Response());
};
$bd = Psr7\FnStream::decorate(Psr7\Utils::streamFor('test'), [
'tell' => static function () {
return 1;
},
'rewind' => static function () use (&$called) {
$called = true;
},
]);
$factory = new CurlFactory(1);
$req = new Psr7\Request('PUT', Server::$url, [], $bd);
$easy = $factory->create($req, []);
$res = CurlFactory::finish($fn, $easy, $factory);
$res = $res->wait();
self::assertTrue($callHandler);
self::assertTrue($called);
self::assertEquals('200', $res->getStatusCode());
}
public function testFailsWhenRetryMoreThanThreeTimes()
{
$factory = new CurlFactory(1);
$call = 0;
$fn = static function ($request, $options) use (&$mock, &$call, $factory) {
++$call;
$easy = $factory->create($request, $options);
return CurlFactory::finish($mock, $easy, $factory);
};
$mock = new Handler\MockHandler([$fn, $fn, $fn]);
$p = $mock(new Psr7\Request('PUT', Server::$url, [], 'test'), []);
$p->wait(false);
self::assertEquals(3, $call);
$this->expectException(RequestException::class);
$this->expectExceptionMessage('The cURL request was retried 3 times');
$p->wait(true);
}
public function testHandles100Continue()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['Test' => 'Hello', 'Content-Length' => 4], 'test'),
]);
$request = new Psr7\Request('PUT', Server::$url, [
'Expect' => '100-Continue',
], 'test');
$handler = new Handler\CurlMultiHandler();
$response = $handler($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('Hello', $response->getHeaderLine('Test'));
self::assertSame('4', $response->getHeaderLine('Content-Length'));
self::assertSame('test', (string) $response->getBody());
}
public function testCreatesConnectException()
{
$m = new \ReflectionMethod(CurlFactory::class, 'finishError');
if (PHP_VERSION_ID < 80100) {
$m->setAccessible(true);
}
$factory = new CurlFactory(1);
$easy = $factory->create(new Psr7\Request('GET', Server::$url), []);
$easy->errno = \CURLE_COULDNT_CONNECT;
$response = $m->invoke(
null,
static function () {
},
$easy,
$factory
);
$this->expectException(ConnectException::class);
$response->wait();
}
public function testAddsTimeouts()
{
$f = new CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), [
'timeout' => 0.1,
'connect_timeout' => 0.2,
]);
self::assertEquals(100, $_SERVER['_curl'][\CURLOPT_TIMEOUT_MS]);
self::assertEquals(200, $_SERVER['_curl'][\CURLOPT_CONNECTTIMEOUT_MS]);
}
public function testAddsStreamingBody()
{
$f = new CurlFactory(3);
$bd = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [
'getSize' => static function () {
return null;
},
]);
$request = new Psr7\Request('PUT', Server::$url, [], $bd);
$f->create($request, []);
self::assertEquals(1, $_SERVER['_curl'][\CURLOPT_UPLOAD]);
self::assertIsCallable($_SERVER['_curl'][\CURLOPT_READFUNCTION]);
}
public function testEnsuresDirExistsBeforeThrowingWarning()
{
$f = new CurlFactory(3);
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Directory /does/not/exist/so does not exist for sink value of /does/not/exist/so/error.txt');
$f->create(new Psr7\Request('GET', Server::$url), [
'sink' => '/does/not/exist/so/error.txt',
]);
}
public function testClosesIdleHandles()
{
$f = new CurlFactory(3);
$req = new Psr7\Request('GET', Server::$url);
$easy = $f->create($req, []);
$h1 = $easy->handle;
$f->release($easy);
self::assertCount(1, Helpers::readObjectAttribute($f, 'handles'));
$easy = $f->create($req, []);
self::assertSame($easy->handle, $h1);
$easy2 = $f->create($req, []);
$easy3 = $f->create($req, []);
$easy4 = $f->create($req, []);
$f->release($easy);
self::assertCount(1, Helpers::readObjectAttribute($f, 'handles'));
$f->release($easy2);
self::assertCount(2, Helpers::readObjectAttribute($f, 'handles'));
$f->release($easy3);
self::assertCount(3, Helpers::readObjectAttribute($f, 'handles'));
$f->release($easy4);
self::assertCount(3, Helpers::readObjectAttribute($f, 'handles'));
}
public function testRejectsPromiseWhenCreateResponseFails()
{
Server::flush();
Server::enqueueRaw(999, 'Incorrect', ['X-Foo' => 'bar'], 'abc 123');
$req = new Psr7\Request('GET', Server::$url);
$handler = new Handler\CurlHandler();
$promise = $handler($req, []);
$this->expectException(RequestException::class);
$this->expectExceptionMessage('An error was encountered while creating the response');
$promise->wait();
}
public function testEnsuresOnHeadersIsCallable()
{
$req = new Psr7\Request('GET', Server::$url);
$handler = new Handler\CurlHandler();
$this->expectException(\InvalidArgumentException::class);
$handler($req, ['on_headers' => 'error!']);
}
public function testRejectsPromiseWhenOnHeadersFails()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123'),
]);
$req = new Psr7\Request('GET', Server::$url);
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'on_headers' => static function () {
throw new \Exception('test');
},
]);
$this->expectException(RequestException::class);
$this->expectExceptionMessage('An error was encountered during the on_headers event');
$promise->wait();
}
public function testSuccessfullyCallsOnHeadersBeforeWritingToSink()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123'),
]);
$req = new Psr7\Request('GET', Server::$url);
$got = null;
$stream = Psr7\Utils::streamFor();
$stream = Psr7\FnStream::decorate($stream, [
'write' => static function ($data) use ($stream, &$got) {
self::assertNotNull($got);
return $stream->write($data);
},
]);
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'sink' => $stream,
'on_headers' => static function (ResponseInterface $res) use (&$got) {
$got = $res;
self::assertEquals('bar', $res->getHeaderLine('X-Foo'));
},
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('bar', $response->getHeaderLine('X-Foo'));
self::assertSame('abc 123', (string) $response->getBody());
}
public function testInvokesOnStatsOnSuccess()
{
Server::flush();
Server::enqueue([new Psr7\Response(200)]);
$req = new Psr7\Request('GET', Server::$url);
$gotStats = null;
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'on_stats' => static function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
},
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame(200, $gotStats->getResponse()->getStatusCode());
self::assertSame(
Server::$url,
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
Server::$url,
(string) $gotStats->getRequest()->getUri()
);
self::assertGreaterThan(0, $gotStats->getTransferTime());
self::assertArrayHasKey('appconnect_time', $gotStats->getHandlerStats());
}
public function testInvokesOnStatsOnError()
{
$req = new Psr7\Request('GET', 'http://127.0.0.1:123');
$gotStats = null;
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'connect_timeout' => 0.001,
'timeout' => 0.001,
'on_stats' => static function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
},
]);
$promise->wait(false);
self::assertFalse($gotStats->hasResponse());
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getRequest()->getUri()
);
self::assertIsFloat($gotStats->getTransferTime());
self::assertIsInt($gotStats->getHandlerErrorData());
self::assertArrayHasKey('appconnect_time', $gotStats->getHandlerStats());
}
public function testRewindsBodyIfPossible()
{
$body = Psr7\Utils::streamFor(\str_repeat('x', 1024 * 1024 * 2));
$body->seek(1024 * 1024);
self::assertSame(1024 * 1024, $body->tell());
$req = new Psr7\Request('POST', 'https://www.example.com', [
'Content-Length' => 1024 * 1024 * 2,
], $body);
$factory = new CurlFactory(1);
$factory->create($req, []);
self::assertSame(0, $body->tell());
}
public function testDoesNotRewindUnseekableBody()
{
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | true |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Handler/Network/StreamHandlerTest.php | tests/Handler/Network/StreamHandlerTest.php | <?php
namespace GuzzleHttp\Test\Handler\Network;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\StreamHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\StreamHandler
*/
class StreamHandlerTest extends TestCase
{
public function setUp(): void
{
if (!($_SERVER['GUZZLE_TEST_ALLOW_NETWORK'] ?? false)) {
self::markTestSkipped('This test requires the GUZZLE_TEST_ALLOW_NETWORK environment variable.');
}
}
public function testSslRequestWorks()
{
$handler = new StreamHandler();
$response = $handler(
new Request('GET', 'https://www.example.com/'),
[
RequestOptions::STREAM => true,
]
)->wait();
self::assertSame(200, $response->getStatusCode());
self::assertStringContainsString('<h1>Example Domain</h1>', (string) $response->getBody());
}
public function testSslRequestWorksWithForceIpResolve()
{
$handler = new StreamHandler();
$response = $handler(
new Request('GET', 'https://www.example.com/'),
[
RequestOptions::STREAM => true,
'force_ip_resolve' => 'v4',
]
)->wait();
self::assertSame(200, $response->getStatusCode());
self::assertStringContainsString('<h1>Example Domain</h1>', (string) $response->getBody());
}
public function testSslRequestWorksWithForceIpResolveAfterRedirect()
{
$client = new Client(['handler' => HandlerStack::create(new StreamHandler())]);
$response = $client->send(
// Redirects to https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstepsrun.
new Request('GET', 'https://git.io/JvXDl'),
[
RequestOptions::STREAM => true,
'force_ip_resolve' => 'v4',
]
);
self::assertSame(200, $response->getStatusCode());
self::assertStringContainsString('jobsjob_idstepsrun', (string) $response->getBody());
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Exception/ConnectExceptionTest.php | tests/Exception/ConnectExceptionTest.php | <?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Client\RequestExceptionInterface;
/**
* @covers \GuzzleHttp\Exception\ConnectException
*/
class ConnectExceptionTest extends TestCase
{
public function testHasRequest()
{
$req = new Request('GET', '/');
$prev = new \Exception();
$e = new ConnectException('foo', $req, $prev, ['foo' => 'bar']);
self::assertInstanceOf(NetworkExceptionInterface::class, $e);
self::assertNotInstanceOf(RequestExceptionInterface::class, $e);
self::assertSame($req, $e->getRequest());
self::assertSame('foo', $e->getMessage());
self::assertSame('bar', $e->getHandlerContext()['foo']);
self::assertSame($prev, $e->getPrevious());
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Exception/BadResponseExceptionTest.php | tests/Exception/BadResponseExceptionTest.php | <?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
class BadResponseExceptionTest extends TestCase
{
public function testHasNoResponse()
{
$req = new Request('GET', '/');
$prev = new \Exception();
$response = new Response();
$e = new BadResponseException('foo', $req, $response, $prev);
self::assertSame($req, $e->getRequest());
self::assertSame($response, $e->getResponse());
self::assertTrue($e->hasResponse());
self::assertSame('foo', $e->getMessage());
self::assertSame($prev, $e->getPrevious());
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Exception/RequestExceptionTest.php | tests/Exception/RequestExceptionTest.php | <?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Stream;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Client\RequestExceptionInterface;
/**
* @covers \GuzzleHttp\Exception\RequestException
*/
class RequestExceptionTest extends TestCase
{
public function testHasRequestAndResponse()
{
$req = new Request('GET', '/');
$res = new Response(200);
$e = new RequestException('foo', $req, $res);
self::assertInstanceOf(RequestExceptionInterface::class, $e);
self::assertNotInstanceOf(NetworkExceptionInterface::class, $e);
self::assertSame($req, $e->getRequest());
self::assertSame($res, $e->getResponse());
self::assertTrue($e->hasResponse());
self::assertSame('foo', $e->getMessage());
}
public function testCreatesGenerateException()
{
$e = RequestException::create(new Request('GET', '/'));
self::assertSame('Error completing request', $e->getMessage());
self::assertInstanceOf(RequestException::class, $e);
}
public function testCreatesClientErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(400));
self::assertStringContainsString(
'GET /',
$e->getMessage()
);
self::assertStringContainsString(
'400 Bad Request',
$e->getMessage()
);
self::assertInstanceOf(ClientException::class, $e);
}
public function testCreatesServerErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(500));
self::assertStringContainsString(
'GET /',
$e->getMessage()
);
self::assertStringContainsString(
'500 Internal Server Error',
$e->getMessage()
);
self::assertInstanceOf(ServerException::class, $e);
}
public function testCreatesGenericErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(300));
self::assertStringContainsString(
'GET /',
$e->getMessage()
);
self::assertStringContainsString(
'300 ',
$e->getMessage()
);
self::assertInstanceOf(RequestException::class, $e);
}
public function testThrowsInvalidArgumentExceptionOnOutOfBoundsResponseCode()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Status code must be an integer value between 1xx and 5xx.');
throw RequestException::create(new Request('GET', '/'), new Response(600));
}
public static function dataPrintableResponses()
{
return [
['You broke the test!'],
['<h1>zlomený zkouška</h1>'],
['{"tester": "Philépe Gonzalez"}'],
["<xml>\n\t<text>Your friendly test</text>\n</xml>"],
['document.body.write("here comes a test");'],
["body:before {\n\tcontent: 'test style';\n}"],
];
}
/**
* @dataProvider dataPrintableResponses
*/
public function testCreatesExceptionWithPrintableBodySummary($content)
{
$response = new Response(
500,
[],
$content
);
$e = RequestException::create(new Request('GET', '/'), $response);
self::assertStringContainsString(
$content,
$e->getMessage()
);
self::assertInstanceOf(RequestException::class, $e);
}
public function testCreatesExceptionWithTruncatedSummary()
{
$content = \str_repeat('+', 121);
$response = new Response(500, [], $content);
$e = RequestException::create(new Request('GET', '/'), $response);
$expected = \str_repeat('+', 120).' (truncated...)';
self::assertStringContainsString($expected, $e->getMessage());
}
public function testExceptionMessageIgnoresEmptyBody()
{
$e = RequestException::create(new Request('GET', '/'), new Response(500));
self::assertStringEndsWith('response', $e->getMessage());
}
public function testHasStatusCodeAsExceptionCode()
{
$e = RequestException::create(new Request('GET', '/'), new Response(442));
self::assertSame(442, $e->getCode());
}
public function testWrapsRequestExceptions()
{
$e = new \Exception('foo');
$r = new Request('GET', 'http://www.oo.com');
$ex = RequestException::wrapException($r, $e);
self::assertInstanceOf(RequestException::class, $ex);
self::assertSame($e, $ex->getPrevious());
}
public function testDoesNotWrapExistingRequestExceptions()
{
$r = new Request('GET', 'http://www.oo.com');
$e = new RequestException('foo', $r);
$e2 = RequestException::wrapException($r, $e);
self::assertSame($e, $e2);
}
public function testCanProvideHandlerContext()
{
$r = new Request('GET', 'http://www.oo.com');
$e = new RequestException('foo', $r, null, null, ['bar' => 'baz']);
self::assertSame(['bar' => 'baz'], $e->getHandlerContext());
}
public function testObfuscateUrlWithUsername()
{
$r = new Request('GET', 'http://username@www.oo.com');
$e = RequestException::create($r, new Response(500));
self::assertStringContainsString('http://username@www.oo.com', $e->getMessage());
}
public function testObfuscateUrlWithUsernameAndPassword()
{
$r = new Request('GET', 'http://user:password@www.oo.com');
$e = RequestException::create($r, new Response(500));
self::assertStringContainsString('http://user:***@www.oo.com', $e->getMessage());
}
}
final class ReadSeekOnlyStream extends Stream
{
public function __construct()
{
parent::__construct(\fopen('php://memory', 'wb'));
}
public function isSeekable(): bool
{
return true;
}
public function isReadable(): bool
{
return false;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Cookie/FileCookieJarTest.php | tests/Cookie/FileCookieJarTest.php | <?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\FileCookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Cookie\FileCookieJar
*/
class FileCookieJarTest extends TestCase
{
private $file;
public function setUp(): void
{
$this->file = \tempnam(\sys_get_temp_dir(), 'file-cookies');
}
/**
* @dataProvider invalidCookieJarContent
*/
public function testValidatesCookieFile($invalidCookieJarContent)
{
\file_put_contents($this->file, json_encode($invalidCookieJarContent));
$this->expectException(\RuntimeException::class);
new FileCookieJar($this->file);
}
public function testLoadsFromFile()
{
$jar = new FileCookieJar($this->file);
self::assertSame([], $jar->getIterator()->getArrayCopy());
\unlink($this->file);
}
/**
* @dataProvider providerPersistsToFileFileParameters
*/
public function testPersistsToFile($testSaveSessionCookie = false)
{
$jar = new FileCookieJar($this->file, $testSaveSessionCookie);
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => \time() + 1000,
]));
$jar->setCookie(new SetCookie([
'Name' => 'baz',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => \time() + 1000,
]));
$jar->setCookie(new SetCookie([
'Name' => 'boo',
'Value' => 'bar',
'Domain' => 'foo.com',
]));
self::assertCount(3, $jar);
unset($jar);
// Make sure it wrote to the file
$contents = \file_get_contents($this->file);
self::assertNotEmpty($contents);
// Load the cookieJar from the file
$jar = new FileCookieJar($this->file);
if ($testSaveSessionCookie) {
self::assertCount(3, $jar);
} else {
// Weeds out temporary and session cookies
self::assertCount(2, $jar);
}
unset($jar);
\unlink($this->file);
}
public function testRemovesCookie()
{
$jar = new FileCookieJar($this->file);
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => \time() + 1000,
]));
self::assertCount(1, $jar);
// Remove the cookie.
$jar->clear('foo.com', '/', 'foo');
// Confirm that the cookie was removed.
self::assertCount(0, $jar);
\unlink($this->file);
}
public function testUpdatesCookie()
{
$jar = new FileCookieJar($this->file);
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => \time() + 1000,
]));
self::assertCount(1, $jar);
// Update the cookie value.
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'new_value',
'Domain' => 'foo.com',
'Expires' => \time() + 1000,
]));
$cookies = $jar->getIterator()->getArrayCopy();
// Confirm that the cookie was updated.
self::assertEquals('new_value', $cookies[0]->getValue());
\unlink($this->file);
}
public static function providerPersistsToFileFileParameters()
{
return [
[false],
[true],
];
}
public static function invalidCookieJarContent(): array
{
return [
[true],
['invalid-data'],
];
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Cookie/SetCookieTest.php | tests/Cookie/SetCookieTest.php | <?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Cookie\SetCookie
*/
class SetCookieTest extends TestCase
{
public function testInitializesDefaultValues()
{
$cookie = new SetCookie();
self::assertSame('/', $cookie->getPath());
}
public function testConvertsDateTimeMaxAgeToUnixTimestamp()
{
$cookie = new SetCookie(['Expires' => 'November 20, 1984']);
self::assertIsInt($cookie->getExpires());
}
public function testAddsExpiresBasedOnMaxAge()
{
$t = \time();
$cookie = new SetCookie(['Max-Age' => 100]);
self::assertEquals($t + 100, $cookie->getExpires());
}
public function testHoldsValues()
{
$t = \time();
$data = [
'Name' => 'foo',
'Value' => 'baz',
'Path' => '/bar',
'Domain' => 'baz.com',
'Expires' => $t,
'Max-Age' => 100,
'Secure' => true,
'Discard' => true,
'HttpOnly' => true,
'foo' => 'baz',
'bar' => 'bam',
];
$cookie = new SetCookie($data);
self::assertEquals($data, $cookie->toArray());
self::assertSame('foo', $cookie->getName());
self::assertSame('baz', $cookie->getValue());
self::assertSame('baz.com', $cookie->getDomain());
self::assertSame('/bar', $cookie->getPath());
self::assertSame($t, $cookie->getExpires());
self::assertSame(100, $cookie->getMaxAge());
self::assertTrue($cookie->getSecure());
self::assertTrue($cookie->getDiscard());
self::assertTrue($cookie->getHttpOnly());
self::assertSame('baz', $cookie->toArray()['foo']);
self::assertSame('bam', $cookie->toArray()['bar']);
$cookie->setName('a');
$cookie->setValue('b');
$cookie->setPath('c');
$cookie->setDomain('bar.com');
$cookie->setExpires(10);
$cookie->setMaxAge(200);
$cookie->setSecure(false);
$cookie->setHttpOnly(false);
$cookie->setDiscard(false);
self::assertSame('a', $cookie->getName());
self::assertSame('b', $cookie->getValue());
self::assertSame('c', $cookie->getPath());
self::assertSame('bar.com', $cookie->getDomain());
self::assertSame(10, $cookie->getExpires());
self::assertSame(200, $cookie->getMaxAge());
self::assertFalse($cookie->getSecure());
self::assertFalse($cookie->getDiscard());
self::assertFalse($cookie->getHttpOnly());
}
public function testDeterminesIfExpired()
{
$c = new SetCookie();
$c->setExpires(10);
self::assertTrue($c->isExpired());
$c->setExpires(\time() + 10000);
self::assertFalse($c->isExpired());
}
public function testMatchesDomain()
{
$cookie = new SetCookie();
self::assertTrue($cookie->matchesDomain('baz.com'));
$cookie->setDomain('baz.com');
self::assertTrue($cookie->matchesDomain('baz.com'));
self::assertFalse($cookie->matchesDomain('bar.com'));
$cookie->setDomain('.baz.com');
self::assertTrue($cookie->matchesDomain('.baz.com'));
self::assertTrue($cookie->matchesDomain('foo.baz.com'));
self::assertFalse($cookie->matchesDomain('baz.bar.com'));
self::assertTrue($cookie->matchesDomain('baz.com'));
$cookie->setDomain('.127.0.0.1');
self::assertTrue($cookie->matchesDomain('127.0.0.1'));
$cookie->setDomain('127.0.0.1');
self::assertTrue($cookie->matchesDomain('127.0.0.1'));
$cookie->setDomain('.com.');
self::assertFalse($cookie->matchesDomain('baz.com'));
$cookie->setDomain('.local');
self::assertTrue($cookie->matchesDomain('example.local'));
$cookie->setDomain('example.com/'); // malformed domain
self::assertFalse($cookie->matchesDomain('example.com'));
}
public static function pathMatchProvider()
{
return [
['/foo', '/foo', true],
['/foo', '/Foo', false],
['/foo', '/fo', false],
['/foo', '/foo/bar', true],
['/foo', '/foo/bar/baz', true],
['/foo', '/foo/bar//baz', true],
['/foo', '/foobar', false],
['/foo/bar', '/foo', false],
['/foo/bar', '/foobar', false],
['/foo/bar', '/foo/bar', true],
['/foo/bar', '/foo/bar/', true],
['/foo/bar', '/foo/bar/baz', true],
['/foo/bar/', '/foo/bar', false],
['/foo/bar/', '/foo/bar/', true],
['/foo/bar/', '/foo/bar/baz', true],
];
}
/**
* @dataProvider pathMatchProvider
*/
public function testMatchesPath($cookiePath, $requestPath, $isMatch)
{
$cookie = new SetCookie();
$cookie->setPath($cookiePath);
self::assertSame($isMatch, $cookie->matchesPath($requestPath));
}
public static function cookieValidateProvider()
{
return [
['foo', 'baz', 'bar', true],
['0', '0', '0', true],
['foo[bar]', 'baz', 'bar', true],
['foo', '', 'bar', true],
['', 'baz', 'bar', 'The cookie name must not be empty'],
['foo', null, 'bar', 'The cookie value must not be empty'],
['foo', 'baz', '', 'The cookie domain must not be empty'],
["foo\r", 'baz', '0', 'Cookie name must not contain invalid characters: ASCII Control characters (0-31;127), space, tab and the following characters: ()<>@,;:\"/?={}'],
];
}
/**
* @dataProvider cookieValidateProvider
*/
public function testValidatesCookies($name, $value, $domain, $result)
{
$cookie = new SetCookie([
'Name' => $name,
'Value' => $value,
'Domain' => $domain,
]);
self::assertSame($result, $cookie->validate());
}
public function testDoesNotMatchIp()
{
$cookie = new SetCookie(['Domain' => '192.168.16.']);
self::assertFalse($cookie->matchesDomain('192.168.16.121'));
}
public function testConvertsToString()
{
$t = 1382916008;
$cookie = new SetCookie([
'Name' => 'test',
'Value' => '123',
'Domain' => 'foo.com',
'Expires' => $t,
'Path' => '/abc',
'HttpOnly' => true,
'Secure' => true,
]);
self::assertSame(
'test=123; Domain=foo.com; Path=/abc; Expires=Sun, 27 Oct 2013 23:20:08 GMT; Secure; HttpOnly',
(string) $cookie
);
}
/**
* Provides the parsed information from a cookie
*
* @return array
*/
public static function cookieParserDataProvider()
{
return [
[
'ASIHTTPRequestTestCookie=This+is+the+value; expires=Sat, 26-Jul-2008 17:00:42 GMT; path=/tests; domain=allseeing-i.com; PHPSESSID=6c951590e7a9359bcedde25cda73e43c; path=/;',
[
'Domain' => 'allseeing-i.com',
'Path' => '/',
'PHPSESSID' => '6c951590e7a9359bcedde25cda73e43c',
'Max-Age' => null,
'Expires' => 'Sat, 26-Jul-2008 17:00:42 GMT',
'Secure' => null,
'Discard' => null,
'Name' => 'ASIHTTPRequestTestCookie',
'Value' => 'This+is+the+value',
'HttpOnly' => false,
],
],
['', []],
['foo', []],
['; foo', []],
[
'foo="bar"',
[
'Name' => 'foo',
'Value' => '"bar"',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false,
],
],
// Test setting a blank value for a cookie
[[
'foo=', 'foo =', 'foo =;', 'foo= ;', 'foo =', 'foo= ', ],
[
'Name' => 'foo',
'Value' => '',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false,
],
],
// Test setting a value and removing quotes
[[
'foo=1', 'foo =1', 'foo =1;', 'foo=1 ;', 'foo =1', 'foo= 1', 'foo = 1 ;', ],
[
'Name' => 'foo',
'Value' => '1',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false,
],
],
// Some of the following tests are based on https://github.com/zendframework/zf1/blob/master/tests/Zend/Http/CookieTest.php
[
'justacookie=foo; domain=example.com',
[
'Name' => 'justacookie',
'Value' => 'foo',
'Domain' => 'example.com',
'Discard' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false,
],
],
[
'expires=tomorrow; secure; path=/Space Out/; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=.example.com',
[
'Name' => 'expires',
'Value' => 'tomorrow',
'Domain' => '.example.com',
'Path' => '/Space Out/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Discard' => null,
'Secure' => true,
'Max-Age' => null,
'HttpOnly' => false,
],
],
[
'domain=unittests; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=example.com; path=/some value/',
[
'Name' => 'domain',
'Value' => 'unittests',
'Domain' => 'example.com',
'Path' => '/some value/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => false,
'Discard' => null,
'Max-Age' => null,
'HttpOnly' => false,
],
],
[
'path=indexAction; path=/; domain=.foo.com; expires=Tue, 21-Nov-2006 08:33:44 GMT',
[
'Name' => 'path',
'Value' => 'indexAction',
'Domain' => '.foo.com',
'Path' => '/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => false,
'Discard' => null,
'Max-Age' => null,
'HttpOnly' => false,
],
],
[
'secure=sha1; secure; SECURE; domain=some.really.deep.domain.com; version=1; Max-Age=86400',
[
'Name' => 'secure',
'Value' => 'sha1',
'Domain' => 'some.really.deep.domain.com',
'Path' => '/',
'Secure' => true,
'Discard' => null,
'Expires' => \time() + 86400,
'Max-Age' => 86400,
'HttpOnly' => false,
'version' => '1',
],
],
[
'PHPSESSID=123456789+abcd%2Cef; secure; discard; domain=.localdomain; path=/foo/baz; expires=Tue, 21-Nov-2006 08:33:44 GMT;',
[
'Name' => 'PHPSESSID',
'Value' => '123456789+abcd%2Cef',
'Domain' => '.localdomain',
'Path' => '/foo/baz',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => true,
'Discard' => true,
'Max-Age' => null,
'HttpOnly' => false,
],
],
[
'fr=synced; Max-Age=604800 Expires=Mon, 12 Dec 2022 13:27:50 GMT; Domain=.example.com; Path=/; SameSite=None; Secure; HttpOnly',
[
'Name' => 'fr',
'Value' => 'synced',
'Domain' => '.example.com',
'Path' => '/',
'Expires' => null,
'Secure' => true,
'Discard' => false,
'Max-Age' => null,
'HttpOnly' => true,
'SameSite' => 'None',
],
],
[
'SESS3a6f27284c4d8b34b6f4ff98cb87703e=Ts-5YeSyvOCMS%2CzkEb9eDfW4C4ZNFOcRYdu-3JpEAXIm58aH; expires=Wed, 07-Jun-2023 15:56:35 GMT; Max-Age=2000000; path=/; domain=.example.com; HttpOnly; SameSite=Lax',
[
'Name' => 'SESS3a6f27284c4d8b34b6f4ff98cb87703e',
'Value' => 'Ts-5YeSyvOCMS%2CzkEb9eDfW4C4ZNFOcRYdu-3JpEAXIm58aH',
'Domain' => '.example.com',
'Path' => '/',
'Expires' => 'Wed, 07-Jun-2023 15:56:35 GMT',
'Secure' => false,
'Discard' => false,
'Max-Age' => 2000000,
'HttpOnly' => true,
'SameSite' => 'Lax',
],
],
[
'SESS3a6f27284c4d8b34b6f4ff98cb87703e=Ts-5YeSyvOCMS%2CzkEb9eDfW4C4ZNFOcRYdu-3JpEAXIm58aH; expires=Wed, 07-Jun-2023 15:56:35 GMT; Max-Age=qwerty; path=/; domain=.example.com; HttpOnly; SameSite=Lax',
[
'Name' => 'SESS3a6f27284c4d8b34b6f4ff98cb87703e',
'Value' => 'Ts-5YeSyvOCMS%2CzkEb9eDfW4C4ZNFOcRYdu-3JpEAXIm58aH',
'Domain' => '.example.com',
'Path' => '/',
'Expires' => 'Wed, 07-Jun-2023 15:56:35 GMT',
'Secure' => false,
'Discard' => false,
'Max-Age' => null,
'HttpOnly' => true,
'SameSite' => 'Lax',
],
],
];
}
/**
* @dataProvider cookieParserDataProvider
*/
public function testParseCookie($cookie, $parsed)
{
foreach ((array) $cookie as $v) {
$c = SetCookie::fromString($v);
$p = $c->toArray();
if (isset($p['Expires'])) {
$delta = 40;
$parsedExpires = \is_numeric($parsed['Expires']) ? $parsed['Expires'] : \strtotime($parsed['Expires']);
self::assertLessThan($delta, \abs($p['Expires'] - $parsedExpires), 'Comparing Expires '.\var_export($p['Expires'], true).' : '.\var_export($parsed, true).' | '.\var_export($p, true));
unset($p['Expires']);
unset($parsed['Expires']);
}
if (!empty($parsed)) {
foreach ($parsed as $key => $value) {
self::assertEquals($parsed[$key], $p[$key], 'Comparing '.$key.' '.\var_export($value, true).' : '.\var_export($parsed, true).' | '.\var_export($p, true));
}
foreach ($p as $key => $value) {
self::assertEquals($p[$key], $parsed[$key], 'Comparing '.$key.' '.\var_export($value, true).' : '.\var_export($parsed, true).' | '.\var_export($p, true));
}
} else {
self::assertSame([
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
], $p);
}
}
}
/**
* Provides the data for testing isExpired
*
* @return array
*/
public static function isExpiredProvider()
{
return [
[
'FOO=bar; expires=Thu, 01 Jan 1970 00:00:00 GMT;',
true,
],
[
'FOO=bar; expires=Thu, 01 Jan 1970 00:00:01 GMT;',
true,
],
[
'FOO=bar; expires='.\date(\DateTime::RFC1123, \time() + 10).';',
false,
],
[
'FOO=bar; expires='.\date(\DateTime::RFC1123, \time() - 10).';',
true,
],
[
'FOO=bar;',
false,
],
];
}
/**
* @dataProvider isExpiredProvider
*/
public function testIsExpired($cookie, $expired)
{
self::assertSame(
$expired,
SetCookie::fromString($cookie)->isExpired()
);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Cookie/CookieJarTest.php | tests/Cookie/CookieJarTest.php | <?php
namespace GuzzleHttp\Tests\CookieJar;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Cookie\CookieJar
*/
class CookieJarTest extends TestCase
{
/**
* @var CookieJar
*/
private $jar;
public function setUp(): void
{
$this->jar = new CookieJar();
}
protected function getTestCookies()
{
return [
new SetCookie(['Name' => 'foo', 'Value' => 'bar', 'Domain' => 'foo.com', 'Path' => '/', 'Discard' => true]),
new SetCookie(['Name' => 'test', 'Value' => '123', 'Domain' => 'baz.com', 'Path' => '/foo', 'Expires' => 2]),
new SetCookie(['Name' => 'you', 'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', 'Expires' => \time() + 1000]),
];
}
public function testCreatesFromArray()
{
$jar = CookieJar::fromArray([
'foo' => 'bar',
'baz' => 'bam',
], 'example.com');
self::assertCount(2, $jar);
}
public function testEmptyJarIsCountable()
{
self::assertCount(0, new CookieJar());
}
public function testGetsCookiesByName()
{
$cookies = $this->getTestCookies();
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
$testCookie = $cookies[0];
self::assertEquals($testCookie, $this->jar->getCookieByName($testCookie->getName()));
self::assertNull($this->jar->getCookieByName('doesnotexist'));
self::assertNull($this->jar->getCookieByName(''));
}
/**
* Provides test data for cookie cookieJar retrieval
*/
public static function getCookiesDataProvider()
{
return [
[['foo', 'baz', 'test', 'muppet', 'googoo'], '', '', '', false],
[['foo', 'baz', 'muppet', 'googoo'], '', '', '', true],
[['googoo'], 'www.example.com', '', '', false],
[['muppet', 'googoo'], 'test.y.example.com', '', '', false],
[['foo', 'baz'], 'example.com', '', '', false],
[['muppet'], 'x.y.example.com', '/acme/', '', false],
[['muppet'], 'x.y.example.com', '/acme/test/', '', false],
[['googoo'], 'x.y.example.com', '/test/acme/test/', '', false],
[['foo', 'baz'], 'example.com', '', '', false],
[['baz'], 'example.com', '', 'baz', false],
];
}
public function testStoresAndRetrievesCookies()
{
$cookies = $this->getTestCookies();
foreach ($cookies as $cookie) {
self::assertTrue($this->jar->setCookie($cookie));
}
self::assertCount(3, $this->jar);
self::assertCount(3, $this->jar->getIterator());
self::assertEquals($cookies, $this->jar->getIterator()->getArrayCopy());
}
public function testRemovesTemporaryCookies()
{
$cookies = $this->getTestCookies();
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
$this->jar->clearSessionCookies();
self::assertEquals(
[$cookies[1], $cookies[2]],
$this->jar->getIterator()->getArrayCopy()
);
}
public function testRemovesSelectively()
{
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
// Remove foo.com cookies
$this->jar->clear('foo.com');
self::assertCount(2, $this->jar);
// Try again, removing no further cookies
$this->jar->clear('foo.com');
self::assertCount(2, $this->jar);
// Remove bar.com cookies with path of /boo
$this->jar->clear('bar.com', '/boo');
self::assertCount(1, $this->jar);
// Remove cookie by name
$this->jar->clear(null, null, 'test');
self::assertCount(0, $this->jar);
}
public static function providesIncompleteCookies(): array
{
return [
[
[],
],
[
[
'Name' => 'foo',
],
],
[
[
'Name' => false,
],
],
[
[
'Name' => true,
],
],
[
[
'Name' => 'foo',
'Domain' => 'foo.com',
],
],
];
}
/**
* @dataProvider providesIncompleteCookies
*/
public function testDoesNotAddIncompleteCookies(array $cookie)
{
self::assertFalse($this->jar->setCookie(new SetCookie($cookie)));
}
public static function providesEmptyCookies(): array
{
return [
[
[
'Name' => '',
'Domain' => 'foo.com',
'Value' => 0,
],
],
[
[
'Name' => null,
'Domain' => 'foo.com',
'Value' => 0,
],
],
];
}
/**
* @dataProvider providesEmptyCookies
*/
public function testDoesNotAddEmptyCookies(array $cookie)
{
self::assertFalse($this->jar->setCookie(new SetCookie($cookie)));
}
public static function providesValidCookies(): array
{
return [
[
[
'Name' => '0',
'Domain' => 'foo.com',
'Value' => 0,
],
],
[
[
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => 0,
],
],
[
[
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => 0.0,
],
],
[
[
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => '0',
],
],
];
}
/**
* @dataProvider providesValidCookies
*/
public function testDoesAddValidCookies(array $cookie)
{
self::assertTrue($this->jar->setCookie(new SetCookie($cookie)));
}
public function testOverwritesCookiesThatAreOlderOrDiscardable()
{
$t = \time() + 1000;
$data = [
'Name' => 'foo',
'Value' => 'bar',
'Domain' => '.example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true,
'Discard' => true,
'Expires' => $t,
];
// Make sure that the discard cookie is overridden with the non-discard
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$data['Discard'] = false;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertFalse($c[0]->getDiscard());
// Make sure it doesn't duplicate the cookie
$this->jar->setCookie(new SetCookie($data));
self::assertCount(1, $this->jar);
// Make sure the more future-ful expiration date supersede the other
$data['Expires'] = \time() + 2000;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertNotEquals($t, $c[0]->getExpires());
}
public function testOverwritesCookiesThatHaveChanged()
{
$t = \time() + 1000;
$data = [
'Name' => 'foo',
'Value' => 'bar',
'Domain' => '.example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true,
'Discard' => true,
'Expires' => $t,
];
// Make sure that the discard cookie is overridden with the non-discard
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
$data['Value'] = 'boo';
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
// Changing the value plus a parameter also must overwrite the existing one
$data['Value'] = 'zoo';
$data['Secure'] = false;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertSame('zoo', $c[0]->getValue());
}
public function testAddsCookiesFromResponseWithRequest()
{
$response = new Response(200, [
'Set-Cookie' => 'fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;',
]);
$request = new Request('GET', 'http://www.example.com');
$this->jar->extractCookies($request, $response);
self::assertCount(1, $this->jar);
}
public static function getMatchingCookiesDataProvider()
{
return [
['https://example.com', 'foo=bar; baz=foobar'],
['http://example.com', ''],
['https://example.com:8912', 'foo=bar; baz=foobar'],
['https://foo.example.com', 'foo=bar; baz=foobar'],
['http://foo.example.com/test/acme/', 'googoo=gaga'],
];
}
/**
* @dataProvider getMatchingCookiesDataProvider
*/
public function testReturnsCookiesMatchingRequests(string $url, string $cookies)
{
$bag = [
new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true,
]),
new SetCookie([
'Name' => 'baz',
'Value' => 'foobar',
'Domain' => 'example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true,
]),
new SetCookie([
'Name' => 'test',
'Value' => '123',
'Domain' => 'www.foobar.com',
'Path' => '/path/',
'Discard' => true,
]),
new SetCookie([
'Name' => 'muppet',
'Value' => 'cookie_monster',
'Domain' => '.y.example.com',
'Path' => '/acme/',
'Expires' => \time() + 86400,
]),
new SetCookie([
'Name' => 'googoo',
'Value' => 'gaga',
'Domain' => '.example.com',
'Path' => '/test/acme/',
'Max-Age' => 1500,
]),
];
foreach ($bag as $cookie) {
$this->jar->setCookie($cookie);
}
$request = new Request('GET', $url);
$request = $this->jar->withCookieHeader($request);
self::assertSame($cookies, $request->getHeaderLine('Cookie'));
}
public function testThrowsExceptionWithStrictMode()
{
$a = new CookieJar(true);
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Invalid cookie: Cookie name must not contain invalid characters: ASCII Control characters (0-31;127), space, tab and the following characters: ()<>@,;:\\"/?={}');
$a->setCookie(new SetCookie(['Name' => "abc\n", 'Value' => 'foo', 'Domain' => 'bar']));
}
public function testDeletesCookiesByName()
{
$cookies = $this->getTestCookies();
$cookies[] = new SetCookie([
'Name' => 'other',
'Value' => '123',
'Domain' => 'bar.com',
'Path' => '/boo',
'Expires' => \time() + 1000,
]);
$jar = new CookieJar();
foreach ($cookies as $cookie) {
$jar->setCookie($cookie);
}
self::assertCount(4, $jar);
$jar->clear('bar.com', '/boo', 'other');
self::assertCount(3, $jar);
$names = \array_map(static function (SetCookie $c) {
return $c->getName();
}, $jar->getIterator()->getArrayCopy());
self::assertSame(['foo', 'test', 'you'], $names);
}
public function testCanConvertToAndLoadFromArray()
{
$jar = new CookieJar(true);
foreach ($this->getTestCookies() as $cookie) {
$jar->setCookie($cookie);
}
self::assertCount(3, $jar);
$arr = $jar->toArray();
self::assertCount(3, $arr);
$newCookieJar = new CookieJar(false, $arr);
self::assertCount(3, $newCookieJar);
self::assertSame($jar->toArray(), $newCookieJar->toArray());
}
public function testAddsCookiesWithEmptyPathFromResponse()
{
$response = new Response(200, [
'Set-Cookie' => "fpc=foobar; expires={$this->futureExpirationDate()}; path=;",
]);
$request = new Request('GET', 'http://www.example.com');
$this->jar->extractCookies($request, $response);
$newRequest = $this->jar->withCookieHeader(new Request('GET', 'http://www.example.com/foo'));
self::assertTrue($newRequest->hasHeader('Cookie'));
}
public static function getCookiePathsDataProvider()
{
return [
['', '/'],
['/', '/'],
['/foo', '/'],
['/foo/bar', '/foo'],
['/foo/bar/', '/foo/bar'],
];
}
/**
* @dataProvider getCookiePathsDataProvider
*/
public function testCookiePathWithEmptySetCookiePath(string $uriPath, string $cookiePath)
{
$response = (new Response(200))
->withAddedHeader(
'Set-Cookie',
"foo=bar; expires={$this->futureExpirationDate()}; domain=www.example.com; path=;"
)
->withAddedHeader(
'Set-Cookie',
"bar=foo; expires={$this->futureExpirationDate()}; domain=www.example.com; path=foobar;"
)
;
$request = (new Request('GET', "https://www.example.com{$uriPath}"));
$this->jar->extractCookies($request, $response);
self::assertSame($cookiePath, $this->jar->toArray()[0]['Path']);
self::assertSame($cookiePath, $this->jar->toArray()[1]['Path']);
}
public static function getDomainMatchesProvider()
{
return [
['www.example.com', 'www.example.com', true],
['www.example.com', 'www.EXAMPLE.com', true],
['www.example.com', 'www.example.net', false],
['www.example.com', 'ftp.example.com', false],
['www.example.com', 'example.com', true],
['www.example.com', 'EXAMPLE.com', true],
['fra.de.example.com', 'EXAMPLE.com', true],
['www.EXAMPLE.com', 'www.example.com', true],
['www.EXAMPLE.com', 'www.example.COM', true],
];
}
/**
* @dataProvider getDomainMatchesProvider
*/
public function testIgnoresCookiesForMismatchingDomains(string $requestHost, string $domainAttribute, bool $matches)
{
$response = (new Response(200))
->withAddedHeader(
'Set-Cookie',
"foo=bar; expires={$this->futureExpirationDate()}; domain={$domainAttribute}; path=/;"
)
;
$request = (new Request('GET', "https://{$requestHost}/"));
$this->jar->extractCookies($request, $response);
self::assertCount($matches ? 1 : 0, $this->jar->toArray());
}
private function futureExpirationDate()
{
return (new DateTimeImmutable())->add(new DateInterval('P1D'))->format(DateTime::COOKIE);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Cookie/SessionCookieJarTest.php | tests/Cookie/SessionCookieJarTest.php | <?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\SessionCookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Cookie\SessionCookieJar
*/
class SessionCookieJarTest extends TestCase
{
private $sessionVar;
public function setUp(): void
{
$this->sessionVar = 'sessionKey';
if (!isset($_SESSION)) {
$_SESSION = [];
}
}
public function testValidatesCookieSession()
{
$_SESSION[$this->sessionVar] = 'true';
$this->expectException(\RuntimeException::class);
new SessionCookieJar($this->sessionVar);
}
public function testLoadsFromSession()
{
$jar = new SessionCookieJar($this->sessionVar);
self::assertSame([], $jar->getIterator()->getArrayCopy());
unset($_SESSION[$this->sessionVar]);
}
/**
* @dataProvider providerPersistsToSessionParameters
*/
public function testPersistsToSession($testSaveSessionCookie = false)
{
$jar = new SessionCookieJar($this->sessionVar, $testSaveSessionCookie);
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => \time() + 1000,
]));
$jar->setCookie(new SetCookie([
'Name' => 'baz',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => \time() + 1000,
]));
$jar->setCookie(new SetCookie([
'Name' => 'boo',
'Value' => 'bar',
'Domain' => 'foo.com',
]));
self::assertCount(3, $jar);
unset($jar);
// Make sure it wrote to the sessionVar in $_SESSION
$contents = $_SESSION[$this->sessionVar];
self::assertNotEmpty($contents);
// Load the cookieJar from the file
$jar = new SessionCookieJar($this->sessionVar);
if ($testSaveSessionCookie) {
self::assertCount(3, $jar);
} else {
// Weeds out temporary and session cookies
self::assertCount(2, $jar);
}
unset($jar);
unset($_SESSION[$this->sessionVar]);
}
public static function providerPersistsToSessionParameters()
{
return [
[false],
[true],
];
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/.php-cs-fixer.tests.php | .php-cs-fixer.tests.php | <?php
require __DIR__ . '/vendor/autoload.php';
$finder = PhpCsFixer\Finder::create()
->in(__DIR__ . '/tests')
->exclude('__snapshots__');
$config = require __DIR__ . '/.php-cs-fixer.common.php';
// Additional rules for tests
$config = array_merge(
$config,
[
'declare_strict_types' => true,
]
);
return (new PhpCsFixer\Config())
->setFinder($finder)
->setRules($config)
->setRiskyAllowed(true)
->setCacheFile(__DIR__ . '/.php-cs-fixer.tests.cache');
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/.php-cs-fixer.common.php | .php-cs-fixer.common.php | <?php
// Share common rules between non-test and test files
return [
'@PSR12' => true,
'blank_line_after_opening_tag' => true,
'braces' => [
'allow_single_line_anonymous_class_with_empty_body' => true,
],
'compact_nullable_typehint' => true,
'declare_equal_normalize' => true,
'lowercase_cast' => true,
'lowercase_static_reference' => true,
'new_with_braces' => true,
'no_blank_lines_after_class_opening' => true,
'no_leading_import_slash' => true,
'no_whitespace_in_blank_line' => true,
'ordered_class_elements' => [
'order' => [
'use_trait',
],
],
'ordered_imports' => [
'imports_order' => [
'class',
'function',
'const',
],
'sort_algorithm' => 'alpha',
],
'return_type_declaration' => true,
'short_scalar_cast' => true,
'single_trait_insert_per_statement' => true,
'ternary_operator_spaces' => true,
'visibility_required' => [
'elements' => [
'const',
'method',
'property',
],
],
// Further quality-of-life improvements
'array_syntax' => [
'syntax' => 'short',
],
'concat_space' => [
'spacing' => 'one',
],
'fully_qualified_strict_types' => true,
'native_function_invocation' => [
'include' => [],
'strict' => true,
],
'no_unused_imports' => true,
'single_quote' => true,
'space_after_semicolon' => true,
'trailing_comma_in_multiline' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'whitespace_after_comma_in_array' => true,
];
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/.php-cs-fixer.dist.php | .php-cs-fixer.dist.php | <?php
require __DIR__ . '/vendor/autoload.php';
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude('tests');
$config = require __DIR__ . '/.php-cs-fixer.common.php';
return (new PhpCsFixer\Config())
->setFinder($finder)
->setRules($config)
->setRiskyAllowed(true)
->setCacheFile(__DIR__ . '/.php-cs-fixer.cache');
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/php-templates/middleware.php | php-templates/middleware.php | <?php
return collect(app("Illuminate\Contracts\Http\Kernel")->getMiddlewareGroups())
->merge(app("Illuminate\Contracts\Http\Kernel")->getRouteMiddleware())
->map(function ($middleware, $key) {
$result = [
'class' => null,
'uri' => null,
'startLine' => null,
'parameters' => null,
'groups' => [],
];
if (is_array($middleware)) {
$result['groups'] = collect($middleware)->map(function ($m) {
if (!class_exists($m)) {
return [
'class' => $m,
'uri' => null,
'startLine' => null,
];
}
$reflected = new ReflectionClass($m);
$reflectedMethod = $reflected->getMethod('handle');
return [
'class' => $m,
'uri' => $reflected->getFileName(),
'startLine' =>
$reflectedMethod->getFileName() === $reflected->getFileName()
? $reflectedMethod->getStartLine()
: null,
];
})->all();
return $result;
}
$reflected = new ReflectionClass($middleware);
$reflectedMethod = $reflected->getMethod('handle');
$result = array_merge($result, [
'class' => $middleware,
'uri' => $reflected->getFileName(),
'startLine' => $reflectedMethod->getStartLine(),
]);
$parameters = collect($reflectedMethod->getParameters())
->filter(function ($rc) {
return $rc->getName() !== 'request' && $rc->getName() !== 'next';
})
->map(function ($rc) {
return $rc->getName() . ($rc->isVariadic() ? '...' : '');
});
if ($parameters->isEmpty()) {
return $result;
}
return array_merge($result, [
'parameters' => $parameters->implode(','),
]);
});
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/php-templates/configs.php | php-templates/configs.php | <?php
$local = collect(glob(config_path('/*.php')))
->merge(glob(config_path('**/*.php')))
->map(fn ($path) => [
(string) Illuminate\Support\Str::of($path)
->replace([config_path('/'), '.php'], '')
->replace('/', '.'),
$path,
]);
$vendor = collect(glob(base_path('vendor/**/**/config/*.php')))->map(fn (
$path
) => [
(string) Illuminate\Support\Str::of($path)
->afterLast('/config/')
->replace('.php', '')
->replace('/', '.'),
$path,
]);
$configPaths = $local
->merge($vendor)
->groupBy(0)
->map(fn ($items) => $items->pluck(1));
$cachedContents = [];
$cachedParsed = [];
function vsCodeGetConfigValue($value, $key, $configPaths)
{
$parts = explode('.', $key);
$toFind = $key;
$found = null;
while (count($parts) > 0) {
array_pop($parts);
$toFind = implode('.', $parts);
if ($configPaths->has($toFind)) {
$found = $toFind;
break;
}
}
if ($found === null) {
return null;
}
$file = null;
$line = null;
if ($found === $key) {
$file = $configPaths->get($found)[0];
} else {
foreach ($configPaths->get($found) as $path) {
$cachedContents[$path] ??= file_get_contents($path);
$cachedParsed[$path] ??= token_get_all($cachedContents[$path]);
$keysToFind = Illuminate\Support\Str::of($key)
->replaceFirst($found, '')
->ltrim('.')
->explode('.');
if (is_numeric($keysToFind->last())) {
$index = $keysToFind->pop();
if ($index !== '0') {
return null;
}
$key = collect(explode('.', $key));
$key->pop();
$key = $key->implode('.');
$value = [];
}
$nextKey = $keysToFind->shift();
$expectedDepth = 1;
$depth = 0;
foreach ($cachedParsed[$path] as $token) {
if ($token === '[') {
$depth++;
}
if ($token === ']') {
$depth--;
}
if (!is_array($token)) {
continue;
}
$str = trim($token[1], '"\'');
if (
$str === $nextKey &&
$depth === $expectedDepth &&
$token[0] === T_CONSTANT_ENCAPSED_STRING
) {
$nextKey = $keysToFind->shift();
$expectedDepth++;
if ($nextKey === null) {
$file = $path;
$line = $token[2];
break;
}
}
}
if ($file) {
break;
}
}
}
return [
'name' => $key,
'value' => $value,
'file' => $file === null ? null : str_replace(base_path('/'), '', $file),
'line' => $line,
];
}
return collect(Illuminate\Support\Arr::dot(config()->all()))
->map(fn ($value, $key) => vsCodeGetConfigValue($value, $key, $configPaths))
->filter()
->values();
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/php-templates/routes.php | php-templates/routes.php | <?php
function vsCodeGetRouterReflection(Illuminate\Routing\Route $route)
{
if ($route->getActionName() === 'Closure') {
return new ReflectionFunction($route->getAction()['uses']);
}
if (!str_contains($route->getActionName(), '@')) {
return new ReflectionClass($route->getActionName());
}
try {
return new ReflectionMethod($route->getControllerClass(), $route->getActionMethod());
} catch (Throwable $e) {
$namespace = app(Illuminate\Routing\UrlGenerator::class)->getRootControllerNamespace()
?? (app()->getNamespace() . 'Http\Controllers');
return new ReflectionMethod(
$namespace . '\\' . ltrim($route->getControllerClass(), '\\'),
$route->getActionMethod(),
);
}
}
return collect(app('router')->getRoutes()->getRoutes())
->map(function (Illuminate\Routing\Route $route) {
try {
$reflection = vsCodeGetRouterReflection($route);
} catch (Throwable $e) {
$reflection = null;
}
return [
'method' => collect($route->methods())->filter(function ($method) {
return $method !== 'HEAD';
})->implode('|'),
'uri' => $route->uri(),
'name' => $route->getName(),
'action' => $route->getActionName(),
'parameters' => $route->parameterNames(),
'filename' => $reflection ? $reflection->getFileName() : null,
'line' => $reflection ? $reflection->getStartLine() : null,
];
})
;
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/php-templates/translations.php | php-templates/translations.php | <?php
function vsCodeGetTranslationsFromFile(Symfony\Component\Finder\SplFileInfo $file, $path, $namespace)
{
if ($file->getExtension() !== 'php') {
return null;
}
$filePath = $file->getRealPath();
$relativePath = trim(str_replace($path, '', $file->getPath()), DIRECTORY_SEPARATOR);
$lang = explode(DIRECTORY_SEPARATOR, $relativePath)[0] ?? null;
if (!$lang) {
return null;
}
$keyPath = str_replace($path . DIRECTORY_SEPARATOR . $lang . DIRECTORY_SEPARATOR, '', $filePath);
$keyWithSlashes = str_replace('.php', '', $keyPath);
$baseKey = str_replace(DIRECTORY_SEPARATOR, '.', $keyWithSlashes);
if ($namespace) {
$baseKey = "{$namespace}::{$baseKey}";
}
try {
$translations = require $filePath;
} catch (Throwable $e) {
return null;
}
if (!is_array($translations)) {
return null;
}
$fileLines = Illuminate\Support\Facades\File::lines($filePath);
$lines = [];
$inComment = false;
foreach ($fileLines as $index => $line) {
$trimmed = trim($line);
if (str_starts_with($trimmed, '/*')) {
$inComment = true;
}
if ($inComment) {
if (str_ends_with($trimmed, '*/')) {
$inComment = false;
}
continue;
}
if (str_starts_with($trimmed, '//')) {
continue;
}
$lines[] = [$index + 1, $trimmed];
}
return [
'k' => $baseKey,
'la' => $lang,
'vs' => collect(Illuminate\Support\Arr::dot($translations))
->map(
fn ($value, $dotKey) => vsCodeTranslationValue(
$dotKey,
$value,
str_replace(base_path(DIRECTORY_SEPARATOR), '', $filePath),
$lines
)
)
->filter(),
];
}
function vsCodeTranslationValue($key, $value, $file, $lines): ?array
{
if (is_array($value)) {
return null;
}
$lineNumber = 1;
$keys = explode('.', $key);
$currentKey = array_shift($keys);
foreach ($lines as $line) {
if (
strpos($line[1], '"' . $currentKey . '"') !== false ||
strpos($line[1], "'" . $currentKey . "'") !== false
) {
$lineNumber = $line[0];
$currentKey = array_shift($keys);
}
if ($currentKey === null) {
break;
}
}
return [
'v' => $value,
'p' => $file,
'li' => $lineNumber,
'pa' => preg_match_all("/\:([A-Za-z0-9_]+)/", $value, $matches)
? $matches[1]
: [],
];
}
function vscodeCollectTranslations(string $path, ?string $namespace = null)
{
$realPath = realpath($path);
if (!is_dir($realPath)) {
return collect();
}
return collect(Illuminate\Support\Facades\File::allFiles($realPath))
->map(fn ($file) => vsCodeGetTranslationsFromFile($file, $path, $namespace))
->filter();
}
$loader = app('translator')->getLoader();
$namespaces = $loader->namespaces();
$reflection = new ReflectionClass($loader);
$property = $reflection->hasProperty('paths')
? $reflection->getProperty('paths')
: $reflection->getProperty('path');
$paths = Illuminate\Support\Arr::wrap($property->getValue($loader));
$default = collect($paths)->flatMap(
fn ($path) => vscodeCollectTranslations($path)
);
$namespaced = collect($namespaces)->flatMap(
fn ($path, $namespace) => vscodeCollectTranslations($path, $namespace)
);
$final = [];
foreach ($default->merge($namespaced) as $value) {
if (!isset($value['vs']) || !is_iterable($value['vs'])) {
continue;
}
foreach ($value['vs'] as $key => $v) {
$dotKey = "{$value['k']}.{$key}";
if (!isset($final[$dotKey])) {
$final[$dotKey] = [];
}
$final[$dotKey][$value['la']] = $v;
if ($value['la'] === Illuminate\Support\Facades\App::currentLocale()) {
$final[$dotKey]['default'] = $v;
}
}
}
return collect($final);
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/php-templates/views.php | php-templates/views.php | <?php
function vsCodeFindBladeFiles($path)
{
$paths = [];
if (!is_dir($path)) {
return $paths;
}
foreach (
Symfony\Component\Finder\Finder::create()
->files()
->name('*.blade.php')
->in($path) as $file
) {
$paths[] = [
'path' => str_replace(base_path(DIRECTORY_SEPARATOR), '', $file->getRealPath()),
'isVendor' => str_contains($file->getRealPath(), base_path('vendor')),
'key' => Illuminate\Support\Str::of($file->getRealPath())
->replace(realpath($path), '')
->replace('.blade.php', '')
->ltrim(DIRECTORY_SEPARATOR)
->replace(DIRECTORY_SEPARATOR, '.'),
];
}
return $paths;
}
$paths = collect(
app('view')
->getFinder()
->getPaths()
)->flatMap(function ($path) {
return vsCodeFindBladeFiles($path);
});
$hints = collect(
app('view')
->getFinder()
->getHints()
)->flatMap(function ($paths, $key) {
return collect($paths)->flatMap(function ($path) use ($key) {
return collect(vsCodeFindBladeFiles($path))->map(function ($value) use (
$key
) {
return array_merge($value, ['key' => "{$key}::{$value['key']}"]);
});
});
});
[$local, $vendor] = $paths
->merge($hints)
->values()
->partition(function ($v) {
return !$v['isVendor'];
});
return $local
->sortBy('key', SORT_NATURAL)
->merge($vendor->sortBy('key', SORT_NATURAL));
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/php-templates/auth.php | php-templates/auth.php | <?php
return collect(Illuminate\Support\Facades\Gate::abilities())
->map(function ($policy, $key) {
$reflection = new ReflectionFunction($policy);
$policyClass = null;
$closureThis = $reflection->getClosureThis();
if ($closureThis && get_class($closureThis) === Illuminate\Auth\Access\Gate::class) {
$vars = $reflection->getClosureUsedVariables();
if (isset($vars['callback'])) {
[$policyClass, $method] = explode('@', $vars['callback']);
$reflection = new ReflectionMethod($policyClass, $method);
}
}
return [
'key' => $key,
'uri' => $reflection->getFileName(),
'policy_class' => $policyClass,
'lineNumber' => $reflection->getStartLine(),
];
})
->merge(
collect(Illuminate\Support\Facades\Gate::policies())->flatMap(function ($policy, $model) {
$methods = (new ReflectionClass($policy))->getMethods();
return collect($methods)->map(function (ReflectionMethod $method) use ($policy) {
return [
'key' => $method->getName(),
'uri' => $method->getFileName(),
'policy_class' => $policy,
'lineNumber' => $method->getStartLine(),
];
})->filter(function ($ability) {
return !in_array($ability['key'], ['allow', 'deny']);
});
}),
)
->values()
->groupBy('key');
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Method.php | src/Method.php | <?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag;
use Barryvdh\Reflection\DocBlock\Tag\ParamTag;
use Barryvdh\Reflection\DocBlock\Tag\ReturnTag;
class Method
{
/** @var DocBlock */
protected $phpdoc;
/** @var \ReflectionMethod */
protected $method;
protected $output = '';
protected $declaringClassName;
protected $name;
protected $namespace;
protected $params = [];
protected $params_with_default = [];
protected $interfaces = [];
protected $real_name;
protected $return = null;
protected $root;
protected $classAliases;
protected $returnTypeNormalizers;
/** @var string[] */
protected $templateNames = [];
/**
* @param \ReflectionMethod|\ReflectionFunctionAbstract $method
* @param string $alias
* @param \ReflectionClass $class
* @param string|null $methodName
* @param array $interfaces
* @param array $classAliases
* @param array $returnTypeNormalizers
* @param string[] $templateNames
*/
public function __construct($method, $alias, $class, $methodName = null, $interfaces = [], array $classAliases = [], array $returnTypeNormalizers = [], array $templateNames = [])
{
$this->method = $method;
$this->interfaces = $interfaces;
$this->classAliases = $classAliases;
$this->returnTypeNormalizers = $returnTypeNormalizers;
$this->name = $methodName ?: $method->name;
$this->real_name = $method->isClosure() ? $this->name : $method->name;
$this->templateNames = $templateNames;
$this->initClassDefinedProperties($method, $class);
//Reference the 'real' function in the declaring class
$this->root = '\\' . ltrim($method->name === '__invoke' ? $method->getDeclaringClass()->getName() : $class->getName(), '\\');
//Create a DocBlock and serializer instance
$this->initPhpDoc($method);
//Normalize the description and inherit the docs from parents/interfaces
try {
$this->normalizeParams($this->phpdoc);
$this->normalizeReturn($this->phpdoc);
$this->normalizeDescription($this->phpdoc);
} catch (\Exception $e) {
}
//Get the parameters, including formatted default values
$this->getParameters($method);
//Make the method static
$this->phpdoc->appendTag(Tag::createInstance('@static', $this->phpdoc));
}
/**
* @param \ReflectionMethod $method
*/
protected function initPhpDoc($method)
{
$this->phpdoc = new DocBlock($method, new Context($this->namespace, $this->classAliases, generics: $this->templateNames));
}
/**
* @param \ReflectionMethod $method
* @param \ReflectionClass $class
*/
protected function initClassDefinedProperties($method, \ReflectionClass $class)
{
$declaringClass = $method->getDeclaringClass();
$this->namespace = $declaringClass->getNamespaceName();
$this->declaringClassName = '\\' . ltrim($declaringClass->name, '\\');
}
/**
* Get the class wherein the function resides
*
* @return string
*/
public function getDeclaringClass()
{
return $this->declaringClassName;
}
/**
* Return the class from which this function would be called
*
* @return string
*/
public function getRoot()
{
return $this->root;
}
/**
* @return bool
*/
public function isInstanceCall()
{
return !($this->method->isClosure() || $this->method->isStatic());
}
/**
* @return string
*/
public function getRootMethodCall()
{
if ($this->isInstanceCall()) {
return "\$instance->{$this->getRealName()}({$this->getParams()})";
} else {
return "{$this->getRoot()}::{$this->getRealName()}({$this->getParams()})";
}
}
/**
* Get the docblock for this method
*
* @param string $prefix
* @return mixed
*/
public function getDocComment($prefix = "\t\t")
{
$serializer = new DocBlockSerializer(1, $prefix);
return $serializer->getDocComment($this->phpdoc);
}
/**
* Get the method name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get the real method name
*
* @return string
*/
public function getRealName()
{
return $this->real_name;
}
/**
* Get the parameters for this method
*
* @param bool $implode Whether to implode the array or not
* @return string
*/
public function getParams($implode = true)
{
return $implode ? implode(', ', $this->params) : $this->params;
}
/**
* @param DocBlock|null $phpdoc
* @return ReturnTag|null
*/
public function getReturnTag($phpdoc = null)
{
if ($phpdoc === null) {
$phpdoc = $this->phpdoc;
}
$returnTags = $phpdoc->getTagsByName('return');
if (count($returnTags) === 0) {
return null;
}
return reset($returnTags);
}
/**
* Get the parameters for this method including default values
*
* @param bool $implode Whether to implode the array or not
* @return string
*/
public function getParamsWithDefault($implode = true)
{
return $implode ? implode(', ', $this->params_with_default) : $this->params_with_default;
}
/**
* Get the description and get the inherited docs.
*
* @param DocBlock $phpdoc
*/
protected function normalizeDescription(DocBlock $phpdoc)
{
//Get the short + long description from the DocBlock
$description = $phpdoc->getText();
//Loop through parents/interfaces, to fill in {@inheritdoc}
if (strpos($description, '{@inheritdoc}') !== false) {
$inheritdoc = $this->getInheritDoc($this->method);
$inheritDescription = $inheritdoc->getText();
$description = str_replace('{@inheritdoc}', $inheritDescription, $description);
$phpdoc->setText($description);
$this->normalizeParams($inheritdoc);
$this->normalizeReturn($inheritdoc);
//Add the tags that are inherited
$inheritTags = $inheritdoc->getTags();
if ($inheritTags) {
/** @var Tag $tag */
foreach ($inheritTags as $tag) {
$tag->setDocBlock();
$phpdoc->appendTag($tag);
}
}
}
}
/**
* Normalize the parameters
*
* @param DocBlock $phpdoc
*/
protected function normalizeParams(DocBlock $phpdoc)
{
//Get the return type and adjust them for beter autocomplete
$paramTags = $phpdoc->getTagsByName('param');
if ($paramTags) {
/** @var ParamTag $tag */
foreach ($paramTags as $tag) {
// Convert the keywords
$content = $this->convertKeywords($tag->getContent());
$tag->setContent($content);
// Get the expanded type and re-set the content
$content = $tag->getType() . ' ' . $tag->getVariableName() . ' ' . $tag->getDescription();
$tag->setContent(trim($content));
}
}
}
/**
* Normalize the return tag (make full namespace, replace interfaces, resolve $this)
*
* @param DocBlock $phpdoc
*/
protected function normalizeReturn(DocBlock $phpdoc)
{
//Get the return type and adjust them for better autocomplete
$tag = $this->getReturnTag($phpdoc);
if ($tag === null) {
$this->return = null;
return;
}
// Get the expanded type
$returnValue = $tag->getType();
if (array_key_exists($returnValue, $this->returnTypeNormalizers)) {
$returnValue = $this->returnTypeNormalizers[$returnValue];
}
if ($returnValue === '$this') {
$returnValue = $this->root;
}
// Replace the interfaces
foreach ($this->interfaces as $interface => $real) {
$returnValue = str_replace($interface, $real, $returnValue);
}
// Set the changed content
$tag->setContent($returnValue . ' ' . $tag->getDescription());
$this->return = $returnValue;
}
/**
* Convert keywords that are incorrect.
*
* @param string $string
* @return string
*/
protected function convertKeywords($string)
{
$string = str_replace('\Closure', 'Closure', $string);
$string = str_replace('Closure', '\Closure', $string);
$string = str_replace('dynamic', 'mixed', $string);
return $string;
}
/**
* Should the function return a value?
*
* @return bool
*/
public function shouldReturn()
{
if ($this->return !== 'void' && $this->method->name !== '__construct') {
return true;
}
return false;
}
/**
* Get the parameters and format them correctly
*
* @param \ReflectionMethod $method
* @return void
*/
public function getParameters($method)
{
//Loop through the default values for parameters, and make the correct output string
$params = [];
$paramsWithDefault = [];
foreach ($method->getParameters() as $param) {
$paramStr = $param->isVariadic() ? '...$' . $param->getName() : '$' . $param->getName();
$params[] = $paramStr;
if ($param->isOptional() && !$param->isVariadic()) {
$default = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
if (is_bool($default)) {
$default = $default ? 'true' : 'false';
} elseif (is_array($default)) {
$default = '[]';
} elseif (is_null($default)) {
$default = 'null';
} elseif (is_int($default)) {
//$default = $default;
} elseif (is_resource($default)) {
//skip to not fail
} else {
$default = var_export($default, true);
}
$paramStr .= " = $default";
}
$paramsWithDefault[] = $paramStr;
}
$this->params = $params;
$this->params_with_default = $paramsWithDefault;
}
/**
* @param \ReflectionMethod $reflectionMethod
* @return DocBlock
*/
protected function getInheritDoc($reflectionMethod)
{
$parentClass = $reflectionMethod->getDeclaringClass()->getParentClass();
//Get either a parent or the interface
if ($parentClass) {
$method = $parentClass->getMethod($reflectionMethod->getName());
} else {
$method = $reflectionMethod->getPrototype();
}
if ($method) {
$namespace = $method->getDeclaringClass()->getNamespaceName();
$phpdoc = new DocBlock($method, new Context($namespace, $this->classAliases, generics: $this->templateNames));
if (strpos($phpdoc->getText(), '{@inheritdoc}') !== false) {
//Not at the end yet, try another parent/interface..
return $this->getInheritDoc($method);
}
return $phpdoc;
}
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Macro.php | src/Macro.php | <?php
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Tag;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Support\Collection;
class Macro extends Method
{
protected static $macroDefaults = [];
/**
* Macro constructor.
*
* @param \ReflectionFunctionAbstract $method
* @param string $alias
* @param \ReflectionClass $class
* @param null $methodName
* @param array $interfaces
* @param array $classAliases
* @param array $returnTypeNormalizers
*/
public function __construct(
$method,
$alias,
$class,
$methodName = null,
$interfaces = [],
$classAliases = [],
$returnTypeNormalizers = []
) {
parent::__construct($method, $alias, $class, $methodName, $interfaces, $classAliases, $returnTypeNormalizers);
}
public static function setDefaultReturnTypes(array $map = [])
{
static::$macroDefaults = array_merge(static::$macroDefaults, $map);
}
/**
* @param \ReflectionFunctionAbstract $method
*/
protected function initPhpDoc($method)
{
$this->phpdoc = new DocBlock($method);
$this->addLocationToPhpDoc();
// Add macro parameters if they are missed in original docblock
if (!$this->phpdoc->hasTag('param')) {
foreach ($method->getParameters() as $parameter) {
$reflectionType = $parameter->getType();
$type = $this->concatReflectionTypes($reflectionType);
/** @psalm-suppress UndefinedClass */
if ($reflectionType && !$reflectionType instanceof \ReflectionUnionType && $reflectionType->allowsNull()) {
$type .= '|null';
}
$type = $type ?: 'mixed';
$name = $parameter->isVariadic() ? '...' : '';
$name .= '$' . $parameter->getName();
$this->phpdoc->appendTag(Tag::createInstance("@param {$type} {$name}"));
}
}
// Add macro return type if it missed in original docblock
if ($method->hasReturnType() && !$this->phpdoc->hasTag('return')) {
$builder = EloquentBuilder::class;
$return = $method->getReturnType();
$type = $this->concatReflectionTypes($return);
/** @psalm-suppress UndefinedClass */
if (!$return instanceof \ReflectionUnionType) {
$type .= $this->root === "\\{$builder}" && $return->getName() === $builder ? '|static' : '';
$type .= $return->allowsNull() ? '|null' : '';
}
$this->phpdoc->appendTag(Tag::createInstance("@return {$type}"));
}
$class = ltrim($this->declaringClassName, '\\');
if (!$this->phpdoc->hasTag('return') && isset(static::$macroDefaults[$class])) {
$type = static::$macroDefaults[$class];
$this->phpdoc->appendTag(Tag::createInstance("@return {$type}"));
}
}
protected function concatReflectionTypes(?\ReflectionType $type): string
{
/** @psalm-suppress UndefinedClass */
$returnTypes = $type instanceof \ReflectionUnionType
? $type->getTypes()
: [$type];
return Collection::make($returnTypes)
->filter()
->map->getName()
->implode('|');
}
protected function addLocationToPhpDoc()
{
if ($this->method->name === '__invoke') {
$enclosingClass = $this->method->getDeclaringClass();
} else {
$enclosingClass = $this->method->getClosureScopeClass();
}
if (!$enclosingClass) {
return;
}
/** @var \ReflectionMethod $enclosingMethod */
$enclosingMethod = Collection::make($enclosingClass->getMethods())
->first(function (\ReflectionMethod $method) {
return $method->getStartLine() <= $this->method->getStartLine()
&& $method->getEndLine() >= $this->method->getEndLine();
});
if ($enclosingMethod) {
$this->phpdoc->appendTag(Tag::createInstance(
'@see \\' . $enclosingClass->getName() . '::' . $enclosingMethod->getName() . '()'
));
}
}
/**
* @param \ReflectionFunctionAbstract $method
* @param \ReflectionClass $class
*/
protected function initClassDefinedProperties($method, \ReflectionClass $class)
{
$this->namespace = $class->getNamespaceName();
$this->declaringClassName = '\\' . ltrim($class->name, '\\');
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Alias.php | src/Alias.php | <?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\ContextFactory;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag\MethodTag;
use Barryvdh\Reflection\DocBlock\Tag\TemplateTag;
use Closure;
use Illuminate\Config\Repository as ConfigRepository;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Traits\Macroable;
use ReflectionClass;
use Throwable;
class Alias
{
protected $alias;
/** @psalm-var class-string $facade */
protected $facade;
protected $extends = null;
protected $extendsClass = null;
protected $extendsNamespace = null;
protected $classType = 'class';
protected $short;
protected $namespace = '__root';
protected $parentClass;
protected $root = null;
protected $classes = [];
protected $methods = [];
protected $usedMethods = [];
protected $valid = false;
protected $magicMethods = [];
protected $interfaces = [];
protected $phpdoc = null;
protected $classAliases = [];
/** @var ConfigRepository */
protected $config;
/** @var string[] */
protected $templateNames;
/**
* @param ConfigRepository $config
* @param string $alias
* @psalm-param class-string $facade
* @param string $facade
* @param array $magicMethods
* @param array $interfaces
*/
public function __construct($config, $alias, $facade, $magicMethods = [], $interfaces = [])
{
$this->alias = $alias;
$this->magicMethods = $magicMethods;
$this->interfaces = $interfaces;
$this->config = $config;
// Make the class absolute
$facade = '\\' . ltrim($facade, '\\');
$this->facade = $facade;
$this->detectRoot();
if (!$this->root || $this->isTrait()) {
return;
}
$this->valid = true;
$this->addClass($this->root);
$this->detectFake();
$this->detectNamespace();
$this->detectClassType();
$this->detectExtendsNamespace();
$this->detectParentClass();
if (!empty($this->namespace)) {
try {
$this->classAliases = (new ContextFactory())->createFromReflector(new ReflectionClass($this->root))->getNamespaceAliases();
} catch (Throwable $e) {
$this->classAliases = [];
}
//Create a DocBlock and serializer instance
$this->phpdoc = new DocBlock(new ReflectionClass($alias), new Context($this->namespace, $this->classAliases));
}
if ($facade === '\Illuminate\Database\Eloquent\Model') {
$this->usedMethods = ['decrement', 'increment'];
}
}
/**
* Add one or more classes to analyze
*
* @param array|string $classes
*/
public function addClass($classes)
{
$classes = (array)$classes;
foreach ($classes as $class) {
if (class_exists($class) || interface_exists($class)) {
$this->classes[] = $class;
} else {
echo "Class not exists: $class\r\n";
}
}
}
/**
* Check if this class is valid to process.
* @return bool
*/
public function isValid()
{
return $this->valid;
}
/**
* Get the classtype, 'interface' or 'class'
*
* @return string
*/
public function getClasstype()
{
return $this->classType;
}
/**
* Get the class which this alias extends
*
* @return null|string
*/
public function getExtends()
{
return $this->extends;
}
/**
* Get the class short name which this alias extends
*
* @return null|string
*/
public function getExtendsClass()
{
return $this->extendsClass;
}
/**
* Get the namespace of the class which this alias extends
*
* @return null|string
*/
public function getExtendsNamespace()
{
return $this->extendsNamespace;
}
/**
* Get the parent class of the class which this alias extends
*
* @return null|string
*/
public function getParentClass()
{
return $this->parentClass;
}
/**
* Check if this class should extend the parent class
*/
public function shouldExtendParentClass()
{
return $this->parentClass
&& $this->getExtendsNamespace() !== '\\Illuminate\\Support\\Facades';
}
/**
* Get the Alias by which this class is called
*
* @return string
*/
public function getAlias()
{
return $this->alias;
}
/**
* Return the short name (without namespace)
*/
public function getShortName()
{
return $this->short;
}
/**
* Get the namespace from the alias
*
* @return string
*/
public function getNamespace()
{
return $this->namespace;
}
/**
* Get the methods found by this Alias
*
* @return array|Method[]
*/
public function getMethods()
{
if (count($this->methods) > 0) {
return $this->methods;
}
$this->addMagicMethods();
$this->detectMethods();
return $this->methods;
}
/**
* Detect class returned by ::fake()
*/
protected function detectFake()
{
$facade = $this->facade;
if (!is_subclass_of($facade, Facade::class)) {
return;
}
if (!method_exists($facade, 'fake')) {
return;
}
$reflection = new \ReflectionMethod($facade, 'fake');
if ($reflection->getNumberOfRequiredParameters() > 0) {
return;
}
$real = $facade::getFacadeRoot();
try {
$facade::fake();
$fake = $facade::getFacadeRoot();
if ($fake !== $real) {
$this->addClass(get_class($fake));
}
} finally {
$facade::swap($real);
}
}
/**
* Detect the namespace
*/
protected function detectNamespace()
{
if (strpos($this->alias, '\\')) {
$nsParts = explode('\\', $this->alias);
$this->short = array_pop($nsParts);
$this->namespace = implode('\\', $nsParts);
} else {
$this->short = $this->alias;
}
}
/**
* Detect the extends namespace
*/
protected function detectExtendsNamespace()
{
if (strpos($this->extends, '\\') !== false) {
$nsParts = explode('\\', $this->extends);
$this->extendsClass = array_pop($nsParts);
$this->extendsNamespace = implode('\\', $nsParts);
}
}
/**
* Detect the parent class
*/
protected function detectParentClass()
{
$reflection = new ReflectionClass($this->root);
$parentClass = $reflection->getParentClass();
$this->parentClass = $parentClass ? '\\' . $parentClass->getName() : null;
}
/**
* Detect the class type
*/
protected function detectClassType()
{
//Some classes extend the facade
if (interface_exists($this->facade)) {
$this->classType = 'interface';
$this->extends = $this->facade;
} else {
$this->classType = 'class';
if (class_exists($this->facade)) {
$this->extends = $this->facade;
}
}
}
/**
* Get the real root of a facade
*
* @return bool|string
*/
protected function detectRoot()
{
$facade = $this->facade;
try {
//If possible, get the facade root
if (method_exists($facade, 'getFacadeRoot')) {
$root = get_class($facade::getFacadeRoot());
} else {
$root = $facade;
}
//If it doesn't exist, skip it
if (!class_exists($root) && !interface_exists($root)) {
return;
}
$this->root = $root;
//When the database connection is not set, some classes will be skipped
} catch (\PDOException $e) {
$this->error(
'PDOException: ' . $e->getMessage() .
"\nPlease configure your database connection correctly, or use the sqlite memory driver (-M)." .
" Skipping $facade."
);
} catch (Throwable $e) {
$this->error('Exception: ' . $e->getMessage() . "\nSkipping $facade.");
}
}
/**
* Detect if this class is a trait or not.
*
* @return bool
*/
protected function isTrait()
{
// Check if the facade is not a Trait
return trait_exists($this->facade);
}
/**
* Add magic methods, as defined in the configuration files
*/
protected function addMagicMethods()
{
foreach ($this->magicMethods as $magic => $real) {
[$className, $name] = explode('::', $real);
if ((!class_exists($className) && !interface_exists($className)) || !method_exists($className, $name)) {
continue;
}
$method = new \ReflectionMethod($className, $name);
$class = new ReflectionClass($className);
if (!in_array($magic, $this->usedMethods)) {
if ($class !== $this->root) {
$this->methods[] = new Method(
$method,
$this->alias,
$class,
$magic,
$this->interfaces,
$this->classAliases,
$this->getReturnTypeNormalizers($class),
$this->getTemplateNames()
);
}
$this->usedMethods[] = $magic;
}
}
}
/**
* Get the methods for one or multiple classes.
*
* @return string
*/
protected function detectMethods()
{
foreach ($this->classes as $class) {
$reflection = new ReflectionClass($class);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if ($methods) {
foreach ($methods as $method) {
if (!in_array($method->name, $this->usedMethods)) {
// Only add the methods to the output when the root is not the same as the class.
// And don't add the __*() methods
if ($this->extends !== $class && substr($method->name, 0, 2) !== '__') {
$this->methods[] = new Method(
$method,
$this->alias,
$reflection,
$method->name,
$this->interfaces,
$this->classAliases,
$this->getReturnTypeNormalizers($reflection),
$this->getTemplateNames(),
);
}
$this->usedMethods[] = $method->name;
}
}
}
// Check if the class is macroable
// (Eloquent\Builder is also macroable but doesn't use Macroable trait)
if ($class === EloquentBuilder::class || in_array(Macroable::class, $reflection->getTraitNames())) {
$properties = $reflection->getStaticProperties();
$macros = isset($properties['macros']) ? $properties['macros'] : [];
foreach ($macros as $macro_name => $macro_func) {
if (!in_array($macro_name, $this->usedMethods)) {
try {
$method = $this->getMacroFunction($macro_func);
} catch (Throwable $e) {
// Invalid method, skip
continue;
}
// Add macros
$this->methods[] = new Macro(
$method,
$this->alias,
$reflection,
$macro_name,
$this->interfaces,
$this->classAliases,
$this->getReturnTypeNormalizers($reflection)
);
$this->usedMethods[] = $macro_name;
}
}
}
}
}
/**
* @param ReflectionClass $class
* @return array<string, string>
*/
protected function getReturnTypeNormalizers($class)
{
if ($this->alias === 'Eloquent' && in_array($class->getName(), [EloquentBuilder::class, QueryBuilder::class])) {
return [
'$this' => '\\' . EloquentBuilder::class . ($this->config->get('ide-helper.use_generics_annotations') ? '<static>' : '|static'),
];
}
return [];
}
/**
* @param $macro_func
*
* @return \ReflectionFunctionAbstract
* @throws \ReflectionException
*/
protected function getMacroFunction($macro_func)
{
if (is_array($macro_func) && is_callable($macro_func)) {
return new \ReflectionMethod($macro_func[0], $macro_func[1]);
}
if (is_object($macro_func) && is_callable($macro_func) && !$macro_func instanceof Closure) {
return new \ReflectionMethod($macro_func, '__invoke');
}
return new \ReflectionFunction($macro_func);
}
/*
* Get the docblock for this alias
*
* @param string $prefix
* @return mixed
*/
public function getDocComment($prefix = "\t\t")
{
$serializer = new DocBlockSerializer(1, $prefix);
if (!$this->phpdoc) {
return '';
}
if ($this->config->get('ide-helper.include_class_docblocks')) {
// if a class doesn't expose any DocBlock tags
// we can perform reflection on the class and
// add in the original class DocBlock
if (count($this->phpdoc->getTags()) === 0) {
$class = new ReflectionClass($this->root);
$this->phpdoc = new DocBlock($class->getDocComment());
}
}
$this->removeDuplicateMethodsFromPhpDoc();
return $serializer->getDocComment($this->phpdoc);
}
/**
* @param $prefix
* @return string
*/
public function getPhpDocTemplates($prefix = "\t\t")
{
$templateDoc = new DocBlock('');
$serializer = new DocBlockSerializer(1, $prefix);
foreach ($this->getTemplateNames() as $templateName) {
$template = new TemplateTag('template', $templateName);
$template->setBound('static');
$template->setDocBlock($templateDoc);
$templateDoc->appendTag($template);
}
return $serializer->getDocComment($templateDoc);
}
/**
* @return string[]
*/
public function getTemplateNames()
{
if (!isset($this->templateNames)) {
$this->detectTemplateNames();
}
return $this->templateNames;
}
/**
* @return void
* @throws \ReflectionException
*/
protected function detectTemplateNames()
{
$templateNames = [];
foreach ($this->classes as $class) {
$reflection = new ReflectionClass($class);
$traits = collect($reflection->getTraitNames());
$phpdoc = new DocBlock($reflection);
$templates = $phpdoc->getTagsByName('template');
/** @var TemplateTag $template */
foreach ($templates as $template) {
$templateNames[] = $template->getTemplateName();
}
foreach ($traits as $trait) {
$phpdoc = new DocBlock(new ReflectionClass($trait));
$templates = $phpdoc->getTagsByName('template');
/** @var TemplateTag $template */
foreach ($templates as $template) {
$templateNames[] = $template->getTemplateName();
}
}
}
$this->templateNames = $templateNames;
}
/**
* Removes method tags from the doc comment that already appear as functions inside the class.
* This prevents duplicate function errors in the IDE.
*
* @return void
*/
protected function removeDuplicateMethodsFromPhpDoc()
{
$methodNames = array_map(function (Method $method) {
return $method->getName();
}, $this->getMethods());
foreach ($this->phpdoc->getTags() as $tag) {
if ($tag instanceof MethodTag && in_array($tag->getMethodName(), $methodNames)) {
$this->phpdoc->deleteTag($tag);
}
}
}
/**
* Output an error.
*
* @param string $string
* @return void
*/
protected function error($string)
{
echo $string . "\r\n";
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Factories.php | src/Factories.php | <?php
namespace Barryvdh\LaravelIdeHelper;
use Exception;
use Illuminate\Database\Eloquent\Factory;
use ReflectionClass;
class Factories
{
public static function all()
{
$factories = [];
if (static::isLaravelSevenOrLower()) {
$factory = app(Factory::class);
$definitions = (new ReflectionClass(Factory::class))->getProperty('definitions');
foreach ($definitions->getValue($factory) as $factory_target => $config) {
try {
$factories[] = new ReflectionClass($factory_target);
} catch (Exception $exception) {
}
}
}
return $factories;
}
protected static function isLaravelSevenOrLower()
{
return class_exists('Illuminate\Database\Eloquent\Factory');
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/IdeHelperServiceProvider.php | src/IdeHelperServiceProvider.php | <?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\LaravelIdeHelper\Console\EloquentCommand;
use Barryvdh\LaravelIdeHelper\Console\GeneratorCommand;
use Barryvdh\LaravelIdeHelper\Console\MetaCommand;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Listeners\GenerateModelHelper;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Database\Events\MigrationsEnded;
use Illuminate\Support\ServiceProvider;
class IdeHelperServiceProvider extends ServiceProvider implements DeferrableProvider
{
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
if (!$this->app->runningUnitTests() && $this->app['config']->get('ide-helper.post_migrate', [])) {
$this->app['events']->listen(CommandFinished::class, GenerateModelHelper::class);
$this->app['events']->listen(MigrationsEnded::class, function () {
GenerateModelHelper::$shouldRun = true;
});
}
if ($this->app->has('view')) {
$viewPath = __DIR__ . '/../resources/views';
$this->loadViewsFrom($viewPath, 'ide-helper');
}
$configPath = __DIR__ . '/../config/ide-helper.php';
if (function_exists('config_path')) {
$publishPath = config_path('ide-helper.php');
} else {
$publishPath = base_path('config/ide-helper.php');
}
$this->publishes([$configPath => $publishPath], 'config');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$configPath = __DIR__ . '/../config/ide-helper.php';
$this->mergeConfigFrom($configPath, 'ide-helper');
$this->commands(
[
GeneratorCommand::class,
ModelsCommand::class,
MetaCommand::class,
EloquentCommand::class,
]
);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [
GeneratorCommand::class,
ModelsCommand::class,
MetaCommand::class,
EloquentCommand::class,
];
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Eloquent.php | src/Eloquent.php | <?php
/**
* Laravel IDE Helper to add \Eloquent mixin to Eloquent\Model
*
* @author Charles A. Peterson <artistan@gmail.com>
*/
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class Eloquent
{
/**
* Write mixin helper to the Eloquent\Model
* This is needed since laravel/framework v5.4.29
*
* @param Command $command
* @param Filesystem $files
*
* @return void
*/
public static function writeEloquentModelHelper(Command $command, Filesystem $files)
{
$class = 'Illuminate\Database\Eloquent\Model';
$reflection = new \ReflectionClass($class);
$namespace = $reflection->getNamespaceName();
$originalDoc = $reflection->getDocComment();
if (!$originalDoc) {
$command->info('Unexpected no document on ' . $class);
}
$phpdoc = new DocBlock($reflection, new Context($namespace));
$mixins = $phpdoc->getTagsByName('mixin');
$expectedMixins = [
'\Eloquent' => false,
'\Illuminate\Database\Eloquent\Builder' => false,
'\Illuminate\Database\Query\Builder' => false,
];
foreach ($mixins as $m) {
$mixin = $m->getContent();
if (isset($expectedMixins[$mixin])) {
$command->info('Tag Exists: @mixin ' . $mixin . ' in ' . $class);
$expectedMixins[$mixin] = true;
}
}
$changed = false;
foreach ($expectedMixins as $expectedMixin => $present) {
if ($present === false) {
$phpdoc->appendTag(Tag::createInstance('@mixin ' . $expectedMixin, $phpdoc));
$changed = true;
}
}
// If nothing's changed, stop here.
if (!$changed) {
return;
}
$serializer = new DocBlockSerializer();
$serializer->getDocComment($phpdoc);
$docComment = $serializer->getDocComment($phpdoc);
/*
The new DocBlock is appended to the beginning of the class declaration.
Since there is no DocBlock, the declaration is used as a guide.
*/
if (!$originalDoc) {
$originalDoc = 'abstract class Model implements';
$docComment .= "\nabstract class Model implements";
}
$filename = $reflection->getFileName();
if (!$filename) {
$command->error('Filename not found ' . $class);
return;
}
$contents = $files->get($filename);
if (!$contents) {
$command->error('No file contents found ' . $filename);
return;
}
$count = 0;
$contents = str_replace($originalDoc, $docComment, $contents, $count);
if ($count <= 0) {
$command->error('Content did not change ' . $contents);
return;
}
if (!$files->put($filename, $contents)) {
$command->error('File write failed to ' . $filename);
return;
}
$command->info('Wrote expected docblock to ' . $filename);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Generator.php | src/Generator.php | <?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use ReflectionClass;
use Symfony\Component\Console\Output\OutputInterface;
class Generator
{
/** @var \Illuminate\Config\Repository */
protected $config;
/** @var \Illuminate\View\Factory */
protected $view;
/** @var OutputInterface */
protected $output;
protected $extra = [];
protected $magic = [];
protected $interfaces = [];
protected $helpers;
/**
* @param \Illuminate\Config\Repository $config
* @param \Illuminate\View\Factory $view
* @param ?OutputInterface $output
* @param string $helpers
*/
public function __construct(
/*ConfigRepository */
$config,
/* Illuminate\View\Factory */
$view,
?OutputInterface $output = null,
$helpers = ''
) {
$this->config = $config;
$this->view = $view;
$this->output = $output;
// Find the drivers to add to the extra/interfaces
$this->detectDrivers();
$this->extra = array_merge($this->extra, $this->config->get('ide-helper.extra', []));
$this->magic = array_merge($this->magic, $this->config->get('ide-helper.magic', []));
$this->interfaces = array_merge($this->interfaces, $this->config->get('ide-helper.interfaces', []));
Macro::setDefaultReturnTypes($this->config->get('ide-helper.macro_default_return_types', [
\Illuminate\Http\Client\Factory::class => \Illuminate\Http\Client\PendingRequest::class,
]));
// Make all interface classes absolute
foreach ($this->interfaces as &$interface) {
$interface = '\\' . ltrim($interface, '\\');
}
$this->helpers = $helpers;
}
/**
* Generate the helper file contents;
*
* @return string;
*/
public function generate()
{
$app = app();
return $this->view->make('ide-helper::helper')
->with('namespaces_by_extends_ns', $this->getAliasesByExtendsNamespace())
->with('namespaces_by_alias_ns', $this->getAliasesByAliasNamespace())
->with('real_time_facades', $this->getRealTimeFacades())
->with('helpers', $this->detectHelpers())
->with('include_fluent', $this->config->get('ide-helper.include_fluent', true))
->with('factories', $this->config->get('ide-helper.include_factory_builders') ? Factories::all() : [])
->render();
}
public function generateEloquent()
{
$name = 'Eloquent';
$facade = Model::class;
$magicMethods = array_key_exists($name, $this->magic) ? $this->magic[$name] : [];
$alias = new Alias($this->config, $name, $facade, $magicMethods, $this->interfaces);
if (!$alias->isValid()) {
throw new \RuntimeException('Cannot generate Eloquent helper');
}
//Add extra methods, from other classes (magic static calls)
if (array_key_exists($name, $this->extra)) {
$alias->addClass($this->extra[$name]);
}
$app = app();
return $this->view->make('ide-helper::helper')
->with('namespaces_by_extends_ns', [])
->with('namespaces_by_alias_ns', ['__root' => [$alias]])
->with('real_time_facades', [])
->with('helpers', '')
->with('include_fluent', false)
->with('factories', [])
->render();
}
protected function detectHelpers()
{
$helpers = $this->helpers;
$replacements = [
'($guard is null ? \Illuminate\Contracts\Auth\Factory : \Illuminate\Contracts\Auth\StatefulGuard)' => '\\Auth',
];
foreach ($replacements as $search => $replace) {
$helpers = Str::replace(
"@return {$search}",
"@return $replace|$search",
$helpers
);
}
return $helpers;
}
protected function detectDrivers()
{
$defaultUserModel = config('auth.providers.users.model', config('auth.model', 'App\User'));
$this->interfaces['\Illuminate\Contracts\Auth\Authenticatable'] = $defaultUserModel;
try {
if (
class_exists('Auth') && is_a('Auth', '\Illuminate\Support\Facades\Auth', true)
&& app()->bound('auth')
) {
$class = get_class(\Auth::guard());
$this->extra['Auth'] = [$class];
$this->interfaces['\Illuminate\Auth\UserProviderInterface'] = $class;
}
} catch (\Exception $e) {
}
try {
if (class_exists('DB') && is_a('DB', '\Illuminate\Support\Facades\DB', true)) {
$class = get_class(\DB::connection());
$this->extra['DB'] = [$class];
$this->interfaces['\Illuminate\Database\ConnectionInterface'] = $class;
}
} catch (\Exception $e) {
}
try {
if (class_exists('Cache') && is_a('Cache', '\Illuminate\Support\Facades\Cache', true)) {
$driver = get_class(\Cache::driver());
$store = get_class(\Cache::getStore());
$this->extra['Cache'] = [$driver, $store];
$this->interfaces['\Illuminate\Cache\StoreInterface'] = $store;
}
} catch (\Exception $e) {
}
try {
if (class_exists('Queue') && is_a('Queue', '\Illuminate\Support\Facades\Queue', true)) {
$class = get_class(\Queue::connection());
$this->extra['Queue'] = [$class];
$this->interfaces['\Illuminate\Queue\QueueInterface'] = $class;
}
} catch (\Exception $e) {
}
try {
if (class_exists('Storage') && is_a('Storage', '\Illuminate\Support\Facades\Storage', true)) {
$class = get_class(\Storage::disk());
$this->extra['Storage'] = [$class];
$this->interfaces['\Illuminate\Contracts\Filesystem\Filesystem'] = $class;
}
} catch (\Exception $e) {
}
}
/**
* Find all aliases that are valid for us to render
*
* @return Collection
*/
protected function getValidAliases()
{
$aliases = new Collection();
// Get all aliases
foreach ($this->getAliases() as $name => $facade) {
// Skip the Redis facade, if not available (otherwise Fatal PHP Error)
if ($facade == 'Illuminate\Support\Facades\Redis' && $name == 'Redis' && !class_exists('Predis\Client')) {
continue;
}
// Skip the swoole
if ($facade == 'SwooleTW\Http\Server\Facades\Server' && $name == 'Server' && !class_exists('Swoole\Http\Server')) {
continue;
}
$magicMethods = array_key_exists($name, $this->magic) ? $this->magic[$name] : [];
$alias = new Alias($this->config, $name, $facade, $magicMethods, $this->interfaces);
if ($alias->isValid()) {
//Add extra methods, from other classes (magic static calls)
if (array_key_exists($name, $this->extra)) {
$alias->addClass($this->extra[$name]);
}
$aliases[] = $alias;
}
}
return $aliases;
}
protected function getRealTimeFacades()
{
$facades = [];
$realTimeFacadeFiles = glob(storage_path('framework/cache/facade-*.php'));
foreach ($realTimeFacadeFiles as $file) {
try {
$name = $this->getFullyQualifiedClassNameInFile($file);
if ($name) {
$facades[$name] = $name;
}
} catch (\Throwable $e) {
continue;
}
}
return $facades;
}
protected function getFullyQualifiedClassNameInFile(string $path)
{
$contents = file_get_contents($path);
// Match namespace
preg_match('/namespace\s+([^;]+);/', $contents, $namespaceMatch);
$namespace = isset($namespaceMatch[1]) ? $namespaceMatch[1] : '';
// Match class name
preg_match('/class\s+([a-zA-Z0-9_]+)/', $contents, $classMatch);
$className = isset($classMatch[1]) ? $classMatch[1] : '';
// Combine namespace and class name
if ($namespace && $className) {
return $namespace . '\\' . $className;
}
}
/**
* Regroup aliases by namespace of extended classes
*
* @return Collection
*/
protected function getAliasesByExtendsNamespace()
{
$aliases = $this->getValidAliases()->filter(static function (Alias $alias) {
return is_subclass_of($alias->getExtends(), Facade::class);
});
$this->addMacroableClasses($aliases);
return $aliases->groupBy(function (Alias $alias) {
return $alias->getExtendsNamespace();
});
}
/**
* Regroup aliases by namespace of alias
*
* @return Collection
*/
protected function getAliasesByAliasNamespace()
{
return $this->getValidAliases()->groupBy(function (Alias $alias) {
return $alias->getNamespace();
});
}
protected function getAliases()
{
// For Laravel, use the AliasLoader
if (class_exists('Illuminate\Foundation\AliasLoader')) {
return AliasLoader::getInstance()->getAliases();
}
$facades = [
'App' => 'Illuminate\Support\Facades\App',
'Auth' => 'Illuminate\Support\Facades\Auth',
'Bus' => 'Illuminate\Support\Facades\Bus',
'DB' => 'Illuminate\Support\Facades\DB',
'Cache' => 'Illuminate\Support\Facades\Cache',
'Cookie' => 'Illuminate\Support\Facades\Cookie',
'Crypt' => 'Illuminate\Support\Facades\Crypt',
'Event' => 'Illuminate\Support\Facades\Event',
'Hash' => 'Illuminate\Support\Facades\Hash',
'Log' => 'Illuminate\Support\Facades\Log',
'Mail' => 'Illuminate\Support\Facades\Mail',
'Queue' => 'Illuminate\Support\Facades\Queue',
'Request' => 'Illuminate\Support\Facades\Request',
'Schema' => 'Illuminate\Support\Facades\Schema',
'Session' => 'Illuminate\Support\Facades\Session',
'Storage' => 'Illuminate\Support\Facades\Storage',
'Validator' => 'Illuminate\Support\Facades\Validator',
'Gate' => 'Illuminate\Support\Facades\Gate',
];
$facades = array_merge($facades, $this->config->get('app.aliases', []));
// Only return the ones that actually exist
return array_filter(
$facades,
function ($alias) {
return class_exists($alias);
},
ARRAY_FILTER_USE_KEY
);
}
/**
* Write a string as error output.
*
* @param string $string
* @return void
*/
protected function error($string)
{
if ($this->output) {
$this->output->writeln("<error>$string</error>");
} else {
echo $string . "\r\n";
}
}
/**
* Add all macroable classes which are not already loaded as an alias and have defined macros.
*
* @param Collection $aliases
*/
protected function addMacroableClasses(Collection $aliases)
{
$macroable = $this->getMacroableClasses($aliases);
foreach ($macroable as $class) {
$reflection = new ReflectionClass($class);
if (!$reflection->getStaticProperties()['macros']) {
continue;
}
$aliases[] = new Alias($this->config, $class, $class, [], $this->interfaces);
}
}
/**
* Get all loaded macroable classes which are not loaded as an alias.
*
* @param Collection $aliases
* @return Collection
*/
protected function getMacroableClasses(Collection $aliases)
{
return (new Collection(get_declared_classes()))
->filter(function ($class) {
$reflection = new ReflectionClass($class);
// Filter out internal classes and class aliases
return !$reflection->isInternal() && $reflection->getName() === $class;
})
->filter(function ($class) {
$traits = class_uses_recursive($class);
// Filter only classes with the macroable trait
return isset($traits[Macroable::class]);
})
->filter(function ($class) use ($aliases) {
$class = Str::start($class, '\\');
// Filter out aliases
return !$aliases->first(function (Alias $alias) use ($class) {
return $alias->getExtends() === $class;
});
});
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Listeners/GenerateModelHelper.php | src/Listeners/GenerateModelHelper.php | <?php
namespace Barryvdh\LaravelIdeHelper\Listeners;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Contracts\Console\Kernel as Artisan;
class GenerateModelHelper
{
/**
* Tracks whether we should run the models command on the CommandFinished event or not.
* Set to true by the MigrationsEnded event, needs to be cleared before artisan call to prevent infinite loop.
*
* @var bool
*/
public static $shouldRun = false;
/** @var Artisan */
protected $artisan;
/** @var Config */
protected $config;
/**
* @param Artisan $artisan
* @param Config $config
*/
public function __construct(Artisan $artisan, Config $config)
{
$this->artisan = $artisan;
$this->config = $config;
}
/**
* Handle the event.
*
* @param CommandFinished $event
*/
public function handle(CommandFinished $event)
{
if (!self::$shouldRun) {
return;
}
self::$shouldRun = false;
foreach ($this->config->get('ide-helper.post_migrate', []) as $command) {
$this->artisan->call($command, [], $event->output);
}
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Contracts/ModelHookInterface.php | src/Contracts/ModelHookInterface.php | <?php
namespace Barryvdh\LaravelIdeHelper\Contracts;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Illuminate\Database\Eloquent\Model;
interface ModelHookInterface
{
public function run(ModelsCommand $command, Model $model): void;
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Console/MetaCommand.php | src/Console/MetaCommand.php | <?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2015 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Factories;
use Dotenv\Parser\Entry;
use Dotenv\Parser\Parser;
use Illuminate\Console\Command;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\View\Factory;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use RuntimeException;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* A command to generate phpstorm meta data
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
class MetaCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'ide-helper:meta';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate metadata for PhpStorm';
/** @var \Illuminate\Contracts\Filesystem\Filesystem */
protected $files;
/** @var Factory */
protected $view;
/** @var Repository */
protected $config;
protected $methods = [
'new \Illuminate\Contracts\Container\Container',
'\Illuminate\Container\Container::makeWith(0)',
'\Illuminate\Contracts\Container\Container::get(0)',
'\Illuminate\Contracts\Container\Container::make(0)',
'\Illuminate\Contracts\Container\Container::makeWith(0)',
'\App::get(0)',
'\App::make(0)',
'\App::makeWith(0)',
'\app(0)',
'\resolve(0)',
'\Psr\Container\ContainerInterface::get(0)',
];
protected $configMethods = [
'\config()',
'\Illuminate\Config\Repository::get()',
'\Illuminate\Support\Facades\Config::get()',
];
protected $userMethods = [
'\auth()->user()',
'\Illuminate\Contracts\Auth\Guard::user()',
'\Illuminate\Support\Facades\Auth::user()',
'\request()->user()',
'\Illuminate\Http\Request::user()',
'\Illuminate\Support\Facades\Request::user()',
];
protected $templateCache = [];
/**
*
* @param Filesystem $files
* @param Factory $view
* @param Repository $config
*/
public function __construct(
Filesystem $files,
Factory $view,
Repository $config
) {
$this->files = $files;
$this->view = $view;
$this->config = $config;
parent::__construct();
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
// Needs to run before exception handler is registered
$factories = $this->config->get('ide-helper.include_factory_builders') ? Factories::all() : [];
$ourAutoloader = $this->registerClassAutoloadExceptions();
$bindings = [];
foreach ($this->getAbstracts() as $abstract) {
// Validator and seeder cause problems
if (in_array($abstract, ['validator', 'seeder'])) {
continue;
}
try {
$concrete = $this->laravel->make($abstract);
if ($concrete === null) {
throw new RuntimeException("Cannot create instance for '$abstract', received 'null'");
}
$reflectionClass = new \ReflectionClass($concrete);
if (is_object($concrete) && !$reflectionClass->isAnonymous() && $abstract !== get_class($concrete)) {
$bindings[$abstract] = get_class($concrete);
}
} catch (\Throwable $e) {
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$this->comment("Cannot make '$abstract': " . $e->getMessage());
}
}
}
$this->unregisterClassAutoloadExceptions($ourAutoloader);
$configValues = $this->loadTemplate('configs')->pluck('value', 'name')->map(function ($value, $key) {
return gettype($value);
});
$defaultUserModel = $this->config->get('auth.providers.users.model', $this->config->get('auth.model', 'App\User'));
$content = $this->view->make('ide-helper::meta', [
'bindings' => $bindings,
'methods' => $this->methods,
'factories' => $factories,
'configMethods' => $this->configMethods,
'configValues' => $configValues,
'expectedArgumentSets' => $this->getExpectedArgumentSets(),
'expectedArguments' => $this->getExpectedArguments(),
'userModel' => $defaultUserModel,
'userMethods' => $this->userMethods,
])->render();
$filename = $this->option('filename');
$written = $this->files->put($filename, $content);
if ($written !== false) {
$this->info("A new meta file was written to $filename");
} else {
$this->error("The meta file could not be created at $filename");
}
}
/**
* Get a list of abstracts from the Laravel Application.
*
* @return array
*/
protected function getAbstracts()
{
$abstracts = $this->laravel->getBindings();
// Return the abstract names only
$keys = array_keys($abstracts);
sort($keys);
return $keys;
}
/**
* Register an autoloader the throws exceptions when a class is not found.
*
* @return callable
*/
protected function registerClassAutoloadExceptions(): callable
{
$aliases = array_filter([...$this->getAbstracts(), 'config'], fn ($abstract) => !str_contains($abstract, '\\'));
$autoloader = function ($class) use ($aliases) {
// ignore aliases as they're meant to be resolved elsewhere
if (in_array($class, $aliases, true)) {
return;
}
throw new \ReflectionException("Class '$class' not found.");
};
spl_autoload_register($autoloader);
return $autoloader;
}
protected function getExpectedArgumentSets()
{
return [
'auth' => $this->loadTemplate('auth')->keys()->filter()->toArray(),
'configs' => $this->loadTemplate('configs')->pluck('name')->filter()->toArray(),
'middleware' => $this->loadTemplate('middleware')->keys()->filter()->toArray(),
'routes' => $this->loadTemplate('routes')->pluck('name')->filter()->toArray(),
'views' => $this->loadTemplate('views')->pluck('key')->filter()->map(function ($value) {
return (string) $value;
})->toArray(),
'translations' => $this->loadTemplate('translations')->filter()->keys()->toArray(),
'env' => $this->getEnv(),
];
}
protected function getExpectedArguments()
{
return [
[
'class' => '\Illuminate\Support\Facades\Gate',
'method' => [
'has',
'allows',
'denies',
'check',
'any',
'none',
'authorize',
'inspect',
],
'argumentSet' => 'auth',
],
[
'class' => ['\Illuminate\Support\Facades\Route', '\Illuminate\Support\Facades\Auth', 'Illuminate\Foundation\Auth\Access\Authorizable'],
'method' => ['can', 'cannot', 'cant'],
'argumentSet' => 'auth',
],
[
'class' => ['Illuminate\Contracts\Auth\Access\Authorizable'],
'method' => ['can'],
'argumentSet' => 'auth',
],
[
'class' => ['\Illuminate\Config\Repository', '\Illuminate\Support\Facades\Config'],
'method' => [
// 'get', // config() and Config::Get() are added with return type hints already
'getMany',
'set',
'string',
'integer',
'boolean',
'float',
'array',
'prepend',
'push',
],
'argumentSet' => 'configs',
],
[
'class' => ['\Illuminate\Support\Facades\Route', '\Illuminate\Routing\Router'],
'method' => ['middleware', 'withoutMiddleware'],
'argumentSet' => 'middleware',
],
[
'method' => ['route', 'to_route', 'signedRoute'],
'argumentSet' => 'routes',
],
[
'class' => [
'\Illuminate\Support\Facades\Redirect',
'\Illuminate\Support\Facades\URL',
'\Illuminate\Routing\Redirector',
'\Illuminate\Routing\UrlGenerator',
],
'method' => ['route', 'signedRoute', 'temporarySignedRoute'],
'argumentSet' => 'routes',
],
[
'method' => 'view',
'argumentSet' => 'views',
],
[
'class' => ['\Illuminate\Support\Facades\View', '\Illuminate\View\Factory'],
'method' => 'make',
'argumentSet' => 'views',
],
[
'method' => ['__', 'trans'],
'argumentSet' => 'translations',
],
[
'class' => ['\Illuminate\Contracts\Translation\Translator'],
'method' => ['get'],
'argumentSet' => 'translations',
],
[
'method' => 'env',
'argumentSet' => 'env',
],
[
'class' => '\Illuminate\Support\Env',
'method' => 'get',
'argumentSet' => 'env',
],
];
}
/**
* @return Collection
*/
protected function loadTemplate($name)
{
if (!isset($this->templateCache[$name])) {
$file = __DIR__ . '/../../php-templates/' . basename($name) . '.php';
try {
$value = $this->files->requireOnce($file) ?: [];
} catch (\Throwable $e) {
$value = [];
$this->warn('Cannot load template for ' . $name . ': ' . $e->getMessage());
}
if (!$value instanceof Collection) {
$value = collect($value);
}
$this->templateCache[$name] = $value;
}
return $this->templateCache[$name];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
$filename = $this->config->get('ide-helper.meta_filename');
return [
['filename', 'F', InputOption::VALUE_OPTIONAL, 'The path to the meta file', $filename],
];
}
protected function getEnv()
{
$envPath = base_path('.env');
if (!file_exists($envPath)) {
return [];
}
$parser = new Parser();
$entries = $parser->parse(file_get_contents($envPath));
return collect($entries)->map(function (Entry $entry) {
return $entry->getName();
});
}
/**
* Remove our custom autoloader that we pushed onto the autoload stack
*
* @param callable $ourAutoloader
*/
private function unregisterClassAutoloadExceptions(callable $ourAutoloader): void
{
spl_autoload_unregister($ourAutoloader);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Console/EloquentCommand.php | src/Console/EloquentCommand.php | <?php
/**
* Laravel IDE Helper Generator - Eloquent Model Mixin
*
* @author Charles A. Peterson <artistan@gmail.com>
* @copyright 2017 Charles A. Peterson / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Eloquent;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
/**
* A command to add \Eloquent mixin to Eloquent\Model
*
* @author Charles A. Peterson <artistan@gmail.com>
*/
class EloquentCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'ide-helper:eloquent';
/**
* @var Filesystem $files
*/
protected $files;
/**
* The console command description.
*
* @var string
*/
protected $description = 'Add \Eloquent helper to \Eloquent\Model';
/**
* @param Filesystem $files
*/
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
Eloquent::writeEloquentModelHelper($this, $this->files);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Console/ModelsCommand.php | src/Console/ModelsCommand.php | <?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface;
use Barryvdh\LaravelIdeHelper\Generator;
use Barryvdh\LaravelIdeHelper\Parsers\PhpDocReturnTypeParser;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\ContextFactory;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag;
use Composer\ClassMapGenerator\ClassMapGenerator;
use Illuminate\Console\Command;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Casts\AsCollection;
use Illuminate\Database\Eloquent\Casts\AsEnumCollection;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\MorphPivot;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Schema\Builder;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\View\Factory as ViewFactory;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionObject;
use ReflectionType;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
/**
* A command to generate autocomplete information for your IDE
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
class ModelsCommand extends Command
{
protected const RELATION_TYPES = [
'hasMany' => HasMany::class,
'hasManyThrough' => HasManyThrough::class,
'hasOneThrough' => HasOneThrough::class,
'belongsToMany' => BelongsToMany::class,
'hasOne' => HasOne::class,
'belongsTo' => BelongsTo::class,
'morphOne' => MorphOne::class,
'morphTo' => MorphTo::class,
'morphMany' => MorphMany::class,
'morphToMany' => MorphToMany::class,
'morphedByMany' => MorphToMany::class,
];
/**
* @var Filesystem $files
*/
protected $files;
/**
* @var Repository
*/
protected $config;
/** @var ViewFactory */
protected $view;
/**
* The console command name.
*
* @var string
*/
protected $name = 'ide-helper:models';
/**
* @var string
*/
protected $filename;
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate autocompletion for models';
protected $write_model_magic_where;
protected $write_model_relation_count_properties;
protected $write_model_relation_exists_properties;
protected $properties = [];
protected $methods = [];
protected $write = false;
protected $write_mixin = false;
protected $dirs = [];
protected $reset;
protected $phpstorm_noinspections;
protected $write_model_external_builder_methods;
/**
* @var array<string, true>
*/
protected $nullableColumns = [];
/**
* @var string[]
*/
protected $foreignKeyConstraintsColumns = [];
/**
* During initialization we use Laravels Date Facade to
* determine the actual date class and store it here.
*
* @var string
*/
protected $dateClass;
/**
* @param Filesystem $files
*/
public function __construct(Filesystem $files, Repository $config, ViewFactory $view)
{
$this->config = $config;
$this->files = $files;
$this->view = $view;
parent::__construct();
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->filename = $this->laravel['config']->get('ide-helper.models_filename', '_ide_helper_models.php');
$filename = $this->option('filename') ?? $this->filename;
$this->write = $this->option('write');
$this->write_mixin = $this->option('write-mixin');
$this->dirs = array_merge(
$this->laravel['config']->get('ide-helper.model_locations', []),
$this->option('dir')
);
$model = $this->argument('model');
$ignore = $this->option('ignore');
$this->reset = $this->option('reset');
$this->phpstorm_noinspections = $this->option('phpstorm-noinspections');
$this->write_model_magic_where = $this->laravel['config']->get('ide-helper.write_model_magic_where', true);
$this->write_model_external_builder_methods = $this->laravel['config']->get('ide-helper.write_model_external_builder_methods', true);
$this->write_model_relation_count_properties =
$this->laravel['config']->get('ide-helper.write_model_relation_count_properties', true);
$this->write_model_relation_exists_properties =
$this->laravel['config']->get('ide-helper.write_model_relation_exists_properties', false);
$this->write = $this->write_mixin ? true : $this->write;
//If filename is default and Write is not specified, ask what to do
if (!$this->write && $filename === $this->filename && !$this->option('nowrite')) {
if (
$this->confirm(
"Do you want to overwrite the existing model files? Choose no to write to $filename instead"
)
) {
$this->write = true;
}
}
$this->dateClass = class_exists(\Illuminate\Support\Facades\Date::class)
? '\\' . get_class(\Illuminate\Support\Facades\Date::now())
: '\Illuminate\Support\Carbon';
$content = $this->generateDocs($model, $ignore);
if (!$this->write || $this->write_mixin) {
$written = $this->files->put($filename, $content);
if ($written !== false) {
$this->info("Model information was written to $filename");
} else {
$this->error("Failed to write model information to $filename");
}
}
$helperFilename = $this->config->get('ide-helper.filename');
$writeHelper = $this->option('write-eloquent-helper');
if (!$writeHelper && !$this->files->exists($helperFilename) && ($this->write || $this->write_mixin)) {
if ($this->confirm("{$helperFilename} does not exist.
Do you want to generate a minimal helper to generate the Eloquent methods?")) {
$writeHelper = true;
}
}
if ($writeHelper) {
$generator = new Generator($this->config, $this->view, $this->getOutput());
$content = $generator->generateEloquent();
$written = $this->files->put($helperFilename, $content);
if ($written !== false) {
$this->info("Eloquent helper was written to $helperFilename");
} else {
$this->error("Failed to write eloquent helper to $helperFilename");
}
}
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['model', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'Which models to include', []],
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['filename', 'F', InputOption::VALUE_OPTIONAL, 'The path to the helper file'],
['dir', 'D', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
'The model dir, supports glob patterns', [], ],
['write', 'W', InputOption::VALUE_NONE, 'Write to Model file'],
['write-mixin', 'M', InputOption::VALUE_NONE,
"Write models to {$this->filename} and adds @mixin to each model, avoiding IDE duplicate declaration warnings",
],
['write-eloquent-helper', 'E', InputOption::VALUE_NONE,
'Write Eloquent helper file to _ide_helper.php',
],
['nowrite', 'N', InputOption::VALUE_NONE, 'Don\'t write to Model file'],
['reset', 'R', InputOption::VALUE_NONE, 'Remove the original phpdocs instead of appending'],
['smart-reset', 'r', InputOption::VALUE_NONE, 'Retained for compatibility, while it no longer has any effect'],
['phpstorm-noinspections', 'p', InputOption::VALUE_NONE,
'Add PhpFullyQualifiedNameUsageInspection and PhpUnnecessaryFullyQualifiedNameInspection PHPStorm ' .
'noinspection tags',
],
['ignore', 'I', InputOption::VALUE_OPTIONAL, 'Which models to ignore', ''],
];
}
protected function generateDocs($loadModels, $ignore = '')
{
$output = "<?php
// @formatter:off
// phpcs:ignoreFile
/**
* A helper file for your Eloquent Models
* Copy the phpDocs from this file to the correct Model,
* And remove them from this file, to prevent double declarations.
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
\n\n";
if (empty($loadModels)) {
$models = $this->loadModels();
} else {
$models = [];
foreach ($loadModels as $model) {
$models = array_merge($models, explode(',', $model));
}
}
$ignore = array_merge(
explode(',', $ignore),
$this->laravel['config']->get('ide-helper.ignored_models', [])
);
foreach ($models as $name) {
if (in_array($name, $ignore)) {
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$this->comment("Ignoring model '$name'");
}
continue;
}
$this->properties = [];
$this->methods = [];
$this->foreignKeyConstraintsColumns = [];
if (class_exists($name)) {
try {
// handle abstract classes, interfaces, ...
$reflectionClass = new ReflectionClass($name);
if (!$reflectionClass->isSubclassOf('Illuminate\Database\Eloquent\Model')) {
continue;
}
$this->comment("Loading model '$name'", OutputInterface::VERBOSITY_VERBOSE);
if (!$reflectionClass->IsInstantiable()) {
// ignore abstract class or interface
continue;
}
$model = $this->laravel->make($name);
$this->getPropertiesFromTable($model);
if (method_exists($model, 'getCasts')) {
$this->castPropertiesType($model);
}
$this->getPropertiesFromMethods($model);
$this->getSoftDeleteMethods($model);
$this->getCollectionMethods($model);
$this->getFactoryMethods($model);
$this->runModelHooks($model);
$output .= $this->createPhpDocs($name);
$ignore[] = $name;
$this->nullableColumns = [];
} catch (Throwable $e) {
$this->error('Exception: ' . $e->getMessage() .
"\nCould not analyze class $name.\n\nTrace:\n" .
$e->getTraceAsString());
}
}
}
return $output;
}
protected function loadModels()
{
$models = [];
foreach ($this->dirs as $dir) {
if (is_dir(base_path($dir))) {
$dir = base_path($dir);
}
$dirs = glob($dir, GLOB_ONLYDIR);
foreach ($dirs as $dir) {
if (!is_dir($dir)) {
$this->error("Cannot locate directory '{$dir}'");
continue;
}
if (file_exists($dir)) {
$classMap = ClassMapGenerator::createMap($dir);
// Sort list so it's stable across different environments
ksort($classMap);
foreach ($classMap as $model => $path) {
$models[] = $model;
}
}
}
}
return $models;
}
/**
* cast the properties's type from $casts.
*
* @param Model $model
*/
public function castPropertiesType($model)
{
$casts = $model->getCasts();
foreach ($casts as $name => $type) {
if (Str::startsWith($type, 'decimal:')) {
$type = 'decimal';
} elseif (Str::startsWith($type, 'custom_datetime:')) {
$type = 'date';
} elseif (Str::startsWith($type, 'date:')) {
$type = 'date';
} elseif (Str::startsWith($type, 'datetime:')) {
$type = 'date';
} elseif (Str::startsWith($type, 'immutable_custom_datetime:')) {
$type = 'immutable_date';
} elseif (Str::startsWith($type, 'immutable_date:')) {
$type = 'immutable_date';
} elseif (Str::startsWith($type, 'immutable_datetime:')) {
$type = 'immutable_datetime';
} elseif (Str::startsWith($type, 'encrypted:')) {
$type = Str::after($type, ':');
}
$params = [];
switch ($type) {
case 'boolean':
case 'bool':
$realType = 'bool';
break;
case 'decimal':
$realType = 'numeric';
break;
case 'encrypted':
case 'string':
case 'hashed':
$realType = 'string';
break;
case 'array':
case 'json':
$realType = 'array<array-key, mixed>';
break;
case 'object':
$realType = 'object';
break;
case 'int':
case 'integer':
case 'timestamp':
$realType = 'int';
break;
case 'real':
case 'double':
case 'float':
$realType = 'float';
break;
case 'date':
case 'datetime':
$realType = $this->dateClass;
break;
case 'immutable_date':
case 'immutable_datetime':
$realType = '\Carbon\CarbonImmutable';
break;
case 'collection':
$realType = '\Illuminate\Support\Collection<array-key, mixed>';
break;
case AsArrayObject::class:
$realType = '\Illuminate\Database\Eloquent\Casts\ArrayObject<array-key, mixed>';
break;
default:
// In case of an optional custom cast parameter , only evaluate
// the `$type` until the `:`
$type = strtok($type, ':');
$realType = class_exists($type) ? ('\\' . $type) : 'mixed';
$this->setProperty($name, null, true, true);
$params = strtok(':');
$params = $params ? explode(',', $params) : [];
break;
}
if (!isset($this->properties[$name])) {
continue;
}
if ($this->isInboundCast($realType)) {
continue;
}
if (Str::startsWith($type, AsCollection::class)) {
$realType = $this->getTypeInModel($model, $params[0] ?? null) ?: '\Illuminate\Support\Collection';
$relatedModel = $this->getTypeInModel($model, $params[1] ?? null);
if ($relatedModel) {
$realType = $this->getCollectionTypeHint($realType, $relatedModel);
}
}
if (Str::startsWith($type, AsEnumCollection::class)) {
$realType = '\Illuminate\Support\Collection';
$relatedModel = $this->getTypeInModel($model, $params[0] ?? null);
if ($relatedModel) {
$realType = $this->getCollectionTypeHint($realType, $relatedModel);
}
}
$realType = $this->checkForCastableCasts($realType, $params);
$realType = $this->checkForCustomLaravelCasts($realType);
$realType = $this->getTypeOverride($realType);
$realType = $this->getTypeInModel($model, $realType);
$realType = $this->applyNullability($realType, isset($this->nullableColumns[$name]));
$this->properties[$name]['type'] = $realType;
}
}
protected function applyNullability(?string $type, bool $isNullable): ?string
{
if (!$type) {
return null;
}
$nullString = null;
// Find instance of:
// A) start of string or non-word character (like space or pipe) followed by 'null|'
// B) '|null' followed by end of string or non-word character (like space or pipe)
// This will find 'or null' instances at the beginning, middle or end of a type string,
// but will exclude solo/pure null instances and null being part of a type's name (e.g. class 'Benull').
if (preg_match('/(?:(?:^|\W)(null\|))|(\|null(?:$|\W))/', $type, $matches) === 1) {
$nullString = array_pop($matches);
}
// Return the current type string if:
// A) the type can be null and the type contains a null instance
// B) the type can not be null and the type does not contain a null instance
if (!($isNullable xor $nullString)) {
return $type;
}
if ($isNullable) {
$type .= '|null';
} else {
$type = str_replace($nullString, '', $type);
}
return $type;
}
/**
* Returns the override type for the give type.
*
* @param string $type
* @return string|null
*/
protected function getTypeOverride($type)
{
$typeOverrides = $this->laravel['config']->get('ide-helper.type_overrides', []);
return $typeOverrides[$type] ?? $type;
}
/**
* Load the properties from the database table.
*
* @param Model $model
*
*/
public function getPropertiesFromTable($model)
{
$table = $model->getTable();
$schema = $model->getConnection()->getSchemaBuilder();
$columns = $schema->getColumns($table);
$driverName = $model->getConnection()->getDriverName();
if (!$columns) {
return;
}
$this->setForeignKeys($schema, $table);
foreach ($columns as $column) {
$name = $column['name'];
if (in_array($name, $model->getDates())) {
$type = $this->dateClass;
} else {
// Match types to php equivalent
$type = match ($column['type_name']) {
'tinyint', 'bit',
'integer', 'int', 'int4',
'smallint', 'int2',
'mediumint',
'bigint', 'int8' => 'int',
'boolean', 'bool' => 'bool',
'float', 'real', 'float4',
'double', 'float8' => 'float',
'decimal', 'numeric' => 'numeric',
default => 'string',
};
}
if ($column['nullable']) {
$this->nullableColumns[$name] = true;
}
$this->setProperty(
$name,
$this->getTypeInModel($model, $type),
true,
true,
$column['comment'],
$column['nullable']
);
if ($this->write_model_magic_where) {
$builderClass = $this->write_model_external_builder_methods
? get_class($model->newModelQuery())
: '\Illuminate\Database\Eloquent\Builder';
$this->setMethod(
Str::camel('where_' . $name),
$this->getClassNameInDestinationFile($model, $builderClass)
. '<static>|'
. $this->getClassNameInDestinationFile($model, get_class($model)),
['$value']
);
}
}
}
/**
* @param Model $model
*/
public function getPropertiesFromMethods($model)
{
$reflectionClass = new ReflectionClass($model);
$reflections = $reflectionClass->getMethods();
if ($reflections) {
// Filter out private methods because they can't be used to generate magic properties and HasAttributes'
// methods that resemble mutators but aren't.
$reflections = array_filter($reflections, function (\ReflectionMethod $methodReflection) {
return !$methodReflection->isPrivate() && !(
$methodReflection->getDeclaringClass()->getName() === Model::class && (
$methodReflection->getName() === 'setClassCastableAttribute' ||
$methodReflection->getName() === 'setEnumCastableAttribute'
)
);
});
// https://github.com/barryvdh/laravel-ide-helper/issues/1664
$reflections = array_filter($reflections, function (\ReflectionMethod $methodReflection) {
return !($methodReflection->getName() === 'getUseFactoryAttribute');
});
sort($reflections);
foreach ($reflections as $reflection) {
$type = $this->getReturnTypeFromReflection($reflection);
$isAttribute = is_a($type, '\Illuminate\Database\Eloquent\Casts\Attribute', true);
$method = $reflection->getName();
if (
Str::startsWith($method, 'get') && Str::endsWith($method, 'Attribute') && $method !== 'getAttribute'
) {
//Magic get<name>Attribute
$name = Str::snake(substr($method, 3, -9));
if (!empty($name)) {
$type = $this->getReturnType($reflection);
$type = $this->getTypeInModel($model, $type);
$comment = $this->getCommentFromDocBlock($reflection);
$this->setProperty($name, $type, true, null, $comment);
}
} elseif ($isAttribute) {
$types = $this->getAttributeTypes($model, $reflection);
$type = $this->getTypeInModel($model, $types->get('get') ?: $types->get('set')) ?: null;
$this->setProperty(
Str::snake($method),
$type,
$types->has('get') ?: null,
$types->has('set') ?: null,
$this->getCommentFromDocBlock($reflection)
);
} elseif (
Str::startsWith($method, 'set') &&
Str::endsWith($method, 'Attribute') &&
$method !== 'setAttribute'
) {
//Magic set<name>Attribute
$name = Str::snake(substr($method, 3, -9));
if (!empty($name)) {
$comment = $this->getCommentFromDocBlock($reflection);
$this->setProperty($name, null, null, true, $comment);
}
} elseif (!empty($reflection->getAttributes('Illuminate\Database\Eloquent\Attributes\Scope')) || (Str::startsWith($method, 'scope') && $method !== 'scopeQuery' && $method !== 'scope' && $method !== 'scopes')) {
$scopeUsingAttribute = !empty($reflection->getAttributes('Illuminate\Database\Eloquent\Attributes\Scope'));
//Magic scope<name>Attribute
$name = $scopeUsingAttribute ? $method : Str::camel(substr($method, 5));
if (!empty($name)) {
$comment = $this->getCommentFromDocBlock($reflection);
$args = $this->getParameters($reflection);
//Remove the first ($query) argument
array_shift($args);
$builder = $this->getClassNameInDestinationFile(
$reflection->getDeclaringClass(),
get_class($model->newModelQuery())
);
$modelName = $this->getClassNameInDestinationFile(
new ReflectionClass($model),
get_class($model)
);
$this->setMethod($name, $builder . '<static>|' . $modelName, $args, $comment);
}
} elseif (in_array($method, ['query', 'newQuery', 'newModelQuery'])) {
$builder = $this->getClassNameInDestinationFile($model, get_class($model->newModelQuery()));
$this->setMethod(
$method,
$builder . '<static>|' . $this->getClassNameInDestinationFile($model, get_class($model))
);
if ($this->write_model_external_builder_methods) {
$this->writeModelExternalBuilderMethods($model);
}
} elseif (
!method_exists('Illuminate\Database\Eloquent\Model', $method)
&& !Str::startsWith($method, 'get')
) {
//Use reflection to inspect the code, based on Illuminate/Support/SerializableClosure.php
if ($returnType = $reflection->getReturnType()) {
$type = $returnType instanceof ReflectionNamedType
? $returnType->getName()
: (string)$returnType;
} else {
// php 7.x type or fallback to docblock
$type = (string)$this->getReturnTypeFromDocBlock($reflection);
}
$file = new \SplFileObject($reflection->getFileName());
$file->seek($reflection->getStartLine() - 1);
$code = '';
while ($file->key() < $reflection->getEndLine()) {
$code .= $file->current();
$file->next();
}
$code = trim(preg_replace('/\s\s+/', '', $code));
$begin = strpos($code, 'function(');
$code = substr($code, $begin, strrpos($code, '}') - $begin + 1);
foreach (
$this->getRelationTypes() as $relation => $impl
) {
$search = '$this->' . $relation . '(';
if (stripos($code, $search) || ltrim($impl, '\\') === ltrim((string)$type, '\\')) {
//Resolve the relation's model to a Relation object.
if ($reflection->getNumberOfParameters()) {
continue;
}
$comment = $this->getCommentFromDocBlock($reflection);
// Adding constraints requires reading model properties which
// can cause errors. Since we don't need constraints we can
// disable them when we fetch the relation to avoid errors.
$relationObj = Relation::noConstraints(function () use ($model, $reflection) {
try {
$methodName = $reflection->getName();
return $model->$methodName();
} catch (Throwable $e) {
$this->warn(sprintf('Error resolving relation model of %s:%s() : %s', get_class($model), $reflection->getName(), $e->getMessage()));
return null;
}
});
if ($relationObj instanceof Relation) {
$relatedModel = $this->getClassNameInDestinationFile(
$model,
get_class($relationObj->getRelated())
);
$relationReturnType = $this->getRelationReturnTypes()[$relation] ?? false;
if (
$relationReturnType === 'many' ||
(
!$relationReturnType &&
str_contains(get_class($relationObj), 'Many')
)
) {
if ($relationObj instanceof BelongsToMany) {
$pivot = get_class($relationObj->newPivot());
if (!in_array($pivot, [Pivot::class, MorphPivot::class])) {
$pivot = $this->getClassNameInDestinationFile($model, $pivot);
if ($existingPivot = ($this->properties[$relationObj->getPivotAccessor()] ?? null)) {
$existingClasses = explode('|', $existingPivot['type']);
if (!in_array($pivot, $existingClasses)) {
array_unshift($existingClasses, $pivot);
}
} else {
// No existing pivot property, so we need to add a null type
$existingClasses = [$pivot, 'null'];
}
// create a union type of all pivot classes
$unionType = implode('|', $existingClasses);
$this->setProperty(
$relationObj->getPivotAccessor(),
$unionType,
true,
false
);
}
}
//Collection or array of models (because Collection is Arrayable)
$relatedClass = '\\' . get_class($relationObj->getRelated());
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | true |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Console/GeneratorCommand.php | src/Console/GeneratorCommand.php | <?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Eloquent;
use Barryvdh\LaravelIdeHelper\Generator;
use Illuminate\Console\Command;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Filesystem\Filesystem;
use Illuminate\View\Factory;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
/**
* A command to generate autocomplete information for your IDE
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
class GeneratorCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'ide-helper:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a new IDE Helper file.';
/** @var \Illuminate\Config\Repository */
protected $config;
/** @var Filesystem */
protected $files;
/** @var Factory */
protected $view;
protected $onlyExtend;
/**
*
* @param \Illuminate\Config\Repository $config
* @param Filesystem $files
* @param Factory $view
*/
public function __construct(
Repository $config,
Filesystem $files,
Factory $view
) {
$this->config = $config;
$this->files = $files;
$this->view = $view;
parent::__construct();
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
if (
file_exists(base_path() . '/vendor/compiled.php') ||
file_exists(base_path() . '/bootstrap/cache/compiled.php') ||
file_exists(base_path() . '/storage/framework/compiled.php')
) {
$this->error(
'Error generating IDE Helper: first delete your compiled file (php artisan clear-compiled)'
);
return;
}
$filename = $this->argument('filename');
// Add the php extension if missing
// This is a backwards-compatible shim and can be removed in the future
if (substr($filename, -4, 4) !== '.php') {
$filename .= '.php';
}
if ($this->option('memory')) {
$this->useMemoryDriver();
}
$helpers = '';
if ($this->option('helpers') || ($this->config->get('ide-helper.include_helpers'))) {
foreach ($this->config->get('ide-helper.helper_files', []) as $helper) {
if (file_exists($helper)) {
$helpers .= str_replace(['<?php', '?>'], '', $this->files->get($helper));
}
}
} else {
$helpers = '';
}
$generator = new Generator($this->config, $this->view, $this->getOutput(), $helpers);
if ($this->option('eloquent')) {
$content = $generator->generateEloquent();
} else {
$content = $generator->generate();
}
$written = $this->files->put($filename, $content);
if ($written !== false) {
$this->info("A new helper file was written to $filename");
if ($this->option('write_mixins')) {
Eloquent::writeEloquentModelHelper($this, $this->files);
}
} else {
$this->error("The helper file could not be created at $filename");
}
}
protected function useMemoryDriver()
{
//Use a sqlite database in memory, to avoid connection errors on Database facades
$this->config->set(
'database.connections.sqlite',
[
'driver' => 'sqlite',
'database' => ':memory:',
]
);
$this->config->set('database.default', 'sqlite');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
$filename = $this->config->get('ide-helper.filename');
return [
[
'filename', InputArgument::OPTIONAL, 'The path to the helper file', $filename,
],
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
$writeMixins = $this->config->get('ide-helper.write_eloquent_model_mixins');
return [
['write_mixins', 'W', InputOption::VALUE_OPTIONAL, 'Write mixins to Laravel Model?', $writeMixins],
['helpers', 'H', InputOption::VALUE_NONE, 'Include the helper files'],
['memory', 'M', InputOption::VALUE_NONE, 'Use sqlite memory driver'],
['eloquent', 'E', InputOption::VALUE_NONE, 'Only write Eloquent methods'],
];
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/src/Parsers/PhpDocReturnTypeParser.php | src/Parsers/PhpDocReturnTypeParser.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Parsers;
class PhpDocReturnTypeParser
{
/**
* @var string
*/
private string $typeAlias;
/**
* @var array
*/
private array $namespaceAliases;
/**
* @param string $typeAlias
* @param array $namespaceAliases
*/
public function __construct(string $typeAlias, array $namespaceAliases)
{
$this->typeAlias = $typeAlias;
$this->namespaceAliases = $namespaceAliases;
}
/**
* @return string|null
*/
public function parse(): string|null
{
$matches = [];
preg_match('/(\w+)(<.*>)/', $this->typeAlias, $matches);
$matchCount = count($matches);
if ($matchCount === 0 || $matchCount === 1) {
return null;
}
if (empty($this->namespaceAliases[$matches[1]])) {
return null;
}
return $this->namespaceAliases[$matches[1]] . $this->parseTemplate($matches[2] ?? null);
}
/**
* @param string|null $template
* @return string
*/
private function parseTemplate(string|null $template): string
{
if ($template === null || $template === '') {
return '';
}
$type = '';
$result = '';
foreach (str_split($template) as $char) {
$match = preg_match('/[A-z]/', $char);
if (!$match) {
$type = $this->namespaceAliases[$type] ?? $type;
$result .= $type;
$result .= $char;
$type = '';
continue;
}
$type .= $char;
}
return $result;
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/MethodTest.php | tests/MethodTest.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests;
use Barryvdh\LaravelIdeHelper\Method;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use PHPUnit\Framework\TestCase;
class MethodTest extends TestCase
{
/**
* Test that we can actually instantiate the class
*/
public function testCanInstantiate()
{
$reflectionClass = new \ReflectionClass(ExampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('setName');
$method = new Method($reflectionMethod, 'Example', $reflectionClass);
$this->assertInstanceOf(Method::class, $method);
}
/**
* Test the output of a class
*/
public function testOutput()
{
$reflectionClass = new \ReflectionClass(ExampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('setName');
$method = new Method($reflectionMethod, 'Example', $reflectionClass);
$output = <<<'DOC'
/**
* @param string $last
* @param string $first
* @param string $middle
* @static
*/
DOC;
$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('setName', $method->getName());
$this->assertSame('\\' . ExampleClass::class, $method->getDeclaringClass());
$this->assertSame('$last, $first, ...$middle', $method->getParams(true));
$this->assertSame(['$last', '$first', '...$middle'], $method->getParams(false));
$this->assertSame('$last, $first = \'Barry\', ...$middle', $method->getParamsWithDefault(true));
$this->assertSame(['$last', '$first = \'Barry\'', '...$middle'], $method->getParamsWithDefault(false));
$this->assertTrue($method->shouldReturn());
}
/**
* Test the output of Illuminate\Database\Eloquent\Builder
*/
public function testEloquentBuilderOutput()
{
$reflectionClass = new \ReflectionClass(EloquentBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('upsert');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass);
$output = <<<'DOC'
/**
* Insert new records or update the existing ones.
*
* @param array $values
* @param array|string $uniqueBy
* @param array|null $update
* @return int
* @static
*/
DOC;
$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('upsert', $method->getName());
$this->assertSame('\\' . EloquentBuilder::class, $method->getDeclaringClass());
$this->assertSame('$values, $uniqueBy, $update', $method->getParams(true));
$this->assertSame(['$values', '$uniqueBy', '$update'], $method->getParams(false));
$this->assertSame('$values, $uniqueBy, $update = null', $method->getParamsWithDefault(true));
$this->assertSame(['$values', '$uniqueBy', '$update = null'], $method->getParamsWithDefault(false));
$this->assertTrue($method->shouldReturn());
$this->assertSame('int', rtrim($method->getReturnTag()->getType()));
}
/**
* Test normalized return type of Illuminate\Database\Eloquent\Builder
*/
public function testEloquentBuilderNormalizedReturnType()
{
$reflectionClass = new \ReflectionClass(EloquentBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('where');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass, null, [], [], ['$this' => '\\' . EloquentBuilder::class . '<static>']);
$output = <<<'DOC'
/**
* Add a basic where clause to the query.
*
* @param (\Closure(static): mixed)|string|array|\Illuminate\Contracts\Database\Query\Expression $column
* @param mixed $operator
* @param mixed $value
* @param string $boolean
* @return \Illuminate\Database\Eloquent\Builder<static>
* @static
*/
DOC;
$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('where', $method->getName());
$this->assertSame('\\' . EloquentBuilder::class, $method->getDeclaringClass());
$this->assertSame(['$column', '$operator', '$value', '$boolean'], $method->getParams(false));
$this->assertSame(['$column', '$operator = null', '$value = null', "\$boolean = 'and'"], $method->getParamsWithDefault(false));
$this->assertTrue($method->shouldReturn());
$this->assertSame('\Illuminate\Database\Eloquent\Builder<static>', rtrim($method->getReturnTag()->getType()));
}
/**
* Test normalized return type of Illuminate\Database\Query\Builder
*/
public function testQueryBuilderNormalizedReturnType()
{
$reflectionClass = new \ReflectionClass(QueryBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('whereNull');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass, null, [], [], ['$this' => '\\' . EloquentBuilder::class . '<static>']);
$output = <<<'DOC'
/**
* Add a "where null" clause to the query.
*
* @param string|array|\Illuminate\Contracts\Database\Query\Expression $columns
* @param string $boolean
* @param bool $not
* @return \Illuminate\Database\Eloquent\Builder<static>
* @static
*/
DOC;
$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('whereNull', $method->getName());
$this->assertSame('\\' . QueryBuilder::class, $method->getDeclaringClass());
$this->assertSame(['$columns', '$boolean', '$not'], $method->getParams(false));
$this->assertSame(['$columns', "\$boolean = 'and'", '$not = false'], $method->getParamsWithDefault(false));
$this->assertTrue($method->shouldReturn());
$this->assertSame('\Illuminate\Database\Eloquent\Builder<static>', rtrim($method->getReturnTag()->getType()));
}
/**
* Test special characters in methods default values
*/
public function testDefaultSpecialChars()
{
$reflectionClass = new \ReflectionClass(ExampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('setSpecialChars');
$method = new Method($reflectionMethod, 'Example', $reflectionClass);
$this->assertSame('$chars', $method->getParams(true));
$this->assertSame(['$chars'], $method->getParams(false));
$this->assertSame('$chars = \'$\\\'\\\\\'', $method->getParamsWithDefault(true));
$this->assertSame(['$chars = \'$\\\'\\\\\''], $method->getParamsWithDefault(false));
}
/**
* Test the output of a class when using class aliases for it
*/
public function testClassAliases()
{
$reflectionClass = new \ReflectionClass(ExampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('getApplication');
$method = new Method($reflectionMethod, 'Example', $reflectionClass, null, [], [
'Application' => '\\Illuminate\\Foundation\\Application',
]);
$output = <<<'DOC'
/**
* @return \Illuminate\Foundation\Application
* @static
*/
DOC;
$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('getApplication', $method->getName());
$this->assertSame('\\' . ExampleClass::class, $method->getDeclaringClass());
$this->assertSame('', $method->getParams(true));
$this->assertSame([], $method->getParams(false));
$this->assertSame('', $method->getParamsWithDefault(true));
$this->assertSame([], $method->getParamsWithDefault(false));
$this->assertTrue($method->shouldReturn());
}
public function testEloquentBuilderWithTemplates()
{
$reflectionClass = new \ReflectionClass(EloquentBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('firstOr');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass, null, [], [], [], ['TModel']);
$output = <<<'DOC'
/**
* Execute the query and get the first result or call a callback.
*
* @template TValue
* @param (\Closure(): TValue)|list<string> $columns
* @param (\Closure(): TValue)|null $callback
* @return TModel|TValue
* @static
*/
DOC;
$this->assertSame($output, $method->getDocComment(''));
$this->assertSame('firstOr', $method->getName());
$this->assertSame('\\' . EloquentBuilder::class, $method->getDeclaringClass());
}
}
class ExampleClass
{
/**
* @param string $last
* @param string $first
* @param string $middle
*/
public function setName($last, $first = 'Barry', ...$middle)
{
return;
}
public function setSpecialChars($chars = "\$'\\")
{
return;
}
/**
* @return Application
*/
public function getApplication()
{
return;
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/AliasTest.php | tests/AliasTest.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests;
use Barryvdh\LaravelIdeHelper\Alias;
use Barryvdh\LaravelIdeHelper\Macro;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Facade;
/**
* @internal
* @coversDefaultClass \Barryvdh\LaravelIdeHelper\Alias
*/
class AliasTest extends TestCase
{
/**
* @covers ::detectMethods
*/
public function testDetectMethodsMacroableMacros(): void
{
// Mock
$macro = __FUNCTION__;
$alias = new AliasMock();
// Macros
Builder::macro(
$macro,
function () {
// empty
}
);
// Prepare
$alias->setClasses([Builder::class]);
$alias->detectMethods();
// Test
$this->assertNotNull($this->getAliasMacro($alias, Builder::class, $macro));
}
/**
* @covers ::detectMethods
*/
public function testDetectMethodsEloquentBuilderMacros(): void
{
// Mock
$macro = __FUNCTION__;
$alias = new AliasMock();
// Macros
EloquentBuilder::macro(
$macro,
function () {
// empty
}
);
// Prepare
$alias->setClasses([EloquentBuilder::class]);
$alias->detectMethods();
// Test
$this->assertNotNull($this->getAliasMacro($alias, EloquentBuilder::class, $macro));
}
/**
* @covers ::detectFake
*/
public function testNoExceptionOnRequiredFakeParameters(): void
{
// Mock
$alias = new AliasMock();
// Prepare
$alias->setFacade(MockFacade::class);
$this->expectNotToPerformAssertions();
// Test
$alias->detectFake();
}
/**
* @covers ::detectTemplateNames
*/
public function testTemplateNamesAreDetected(): void
{
// Mock
$alias = new AliasMock();
// Prepare
$alias->setClasses([EloquentBuilder::class]);
// Test
$this->assertSame(['TModel', 'TValue'], $alias->getTemplateNames());
}
protected function getAliasMacro(Alias $alias, string $class, string $method): ?Macro
{
return Arr::first(
$alias->getMethods(),
function ($macro) use ($class, $method) {
return $macro instanceof Macro
&& $macro->getDeclaringClass() === "\\{$class}"
&& $macro->getName() === $method;
}
);
}
}
/**
* @internal
* @noinspection PhpMultipleClassesDeclarationsInOneFile
* @template TValue
*/
class AliasMock extends Alias
{
public function __construct()
{
// no need to call parent
}
/**
* @param string[] $classes
*/
public function setClasses(array $classes)
{
$this->classes = $classes;
}
public function detectMethods()
{
parent::detectMethods();
}
public function detectFake()
{
parent::detectFake();
}
public function setFacade(string $facade)
{
$this->facade = $facade;
}
}
class MockFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'Illuminate\Foundation\Exceptions\Handler';
}
public static function fake(string $test1, $test2 = null)
{
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/SnapshotPhpDriver.php | tests/SnapshotPhpDriver.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests;
use PHPUnit\Framework\Assert;
use Spatie\Snapshots\Driver;
class SnapshotPhpDriver implements Driver
{
public function serialize($data): string
{
return str_replace(["\r\n", "\r"], "\n", (string) $data);
}
public function extension(): string
{
return 'php';
}
public function match($expected, $actual)
{
Assert::assertSame(str_replace(["\r\n", "\r"], "\n", $expected), $this->serialize($actual));
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/SnapshotTxtDriver.php | tests/SnapshotTxtDriver.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests;
use PHPUnit\Framework\Assert;
use Spatie\Snapshots\Driver;
class SnapshotTxtDriver implements Driver
{
public function serialize($data): string
{
return str_replace(["\r\n", "\r"], "\n", (string) $data);
}
public function extension(): string
{
return 'txt';
}
public function match($expected, $actual)
{
Assert::assertSame(str_replace(["\r\n", "\r"], "\n", $expected), $this->serialize($actual));
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/MacroTest.php | tests/MacroTest.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests;
use Barryvdh\LaravelIdeHelper\Macro;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Tag;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Routing\UrlGenerator;
use ReflectionClass;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use function array_map;
use function implode;
use const PHP_EOL;
/**
* @internal
* @coversDefaultClass \Barryvdh\LaravelIdeHelper\Macro
*/
class MacroTest extends TestCase
{
/**
* @covers ::initPhpDoc
* @throws \ReflectionException
*/
public function testInitPhpDocEloquentBuilderHasStaticInReturnType(): void
{
$class = new ReflectionClass(EloquentBuilder::class);
$phpdoc = (new MacroMock())->getPhpDoc(
new ReflectionFunction(
function (): EloquentBuilder {
return $this;
}
),
$class
);
$this->assertNotNull($phpdoc);
$this->assertEquals(
'@return \Illuminate\Database\Eloquent\Builder|static',
$this->tagsToString($phpdoc, 'return')
);
}
/**
* @covers ::initPhpDoc
* @throws \ReflectionException
*/
public function testInitPhpDocClosureWithoutDocBlock(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(
new ReflectionFunction(
function (?int $a = null): int {
return 0;
}
)
);
$this->assertNotNull($phpdoc);
$this->assertEmpty($phpdoc->getText());
$this->assertEquals('@param int|null $a', $this->tagsToString($phpdoc, 'param'));
$this->assertEquals('@return int', $this->tagsToString($phpdoc, 'return'));
$this->assertTrue($phpdoc->hasTag('see'));
}
/**
* @covers ::initPhpDoc
* @throws \ReflectionException
*/
public function testInitPhpDocClosureWithArgsAndReturnType(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(
new ReflectionFunction(
/**
* Test docblock.
*/
function (?int $a = null): int {
return 0;
}
)
);
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock', $phpdoc->getText());
$this->assertEquals('@param int|null $a', $this->tagsToString($phpdoc, 'param'));
$this->assertEquals('@return int', $this->tagsToString($phpdoc, 'return'));
$this->assertTrue($phpdoc->hasTag('see'));
}
/**
* @covers ::initPhpDoc
* @throws \ReflectionException
*/
public function testInitPhpDocClosureWithArgs(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(
new ReflectionFunction(
/**
* Test docblock.
*/
function (?int $a = null) {
return 0;
}
)
);
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock', $phpdoc->getText());
$this->assertEquals('@param int|null $a', $this->tagsToString($phpdoc, 'param'));
$this->assertFalse($phpdoc->hasTag('return'));
$this->assertTrue($phpdoc->hasTag('see'));
}
/**
* @covers ::initPhpDoc
* @throws \ReflectionException
*/
public function testInitPhpDocClosureWithReturnType(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(
new ReflectionFunction(
/**
* Test docblock.
*/
function (): int {
return 0;
}
)
);
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock', $phpdoc->getText());
$this->assertFalse($phpdoc->hasTag('param'));
$this->assertEquals('@return int', $this->tagsToString($phpdoc, 'return'));
$this->assertTrue($phpdoc->hasTag('see'));
}
/**
* @covers ::initPhpDoc
*/
public function testInitPhpDocParamsAddedOnlyNotPresent(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(
new ReflectionFunction(
/**
* Test docblock.
*
* @param \stdClass|null $a aaaaa
*/
function ($a = null): int {
return 0;
}
)
);
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock', $phpdoc->getText());
$this->assertEquals('@param \stdClass|null $a aaaaa', $this->tagsToString($phpdoc, 'param'));
$this->assertEquals('@return int', $this->tagsToString($phpdoc, 'return'));
}
/**
* @covers ::initPhpDoc
*/
public function testInitPhpDocReturnAddedOnlyNotPresent(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(
new ReflectionFunction(
/**
* Test docblock.
*
* @return \stdClass|null rrrrrrr
*/
function ($a = null): int {
return 0;
}
)
);
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock', $phpdoc->getText());
$this->assertEquals('@param mixed $a', $this->tagsToString($phpdoc, 'param'));
$this->assertEquals('@return \stdClass|null rrrrrrr', $this->tagsToString($phpdoc, 'return'));
}
public function testInitPhpDocParamsWithUnionTypes(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(eval(<<<'PHP'
return new ReflectionFunction(
/**
* Test docblock.
*/
function (\Stringable|string $a = null): \Stringable|string|null {
return $a;
}
);
PHP));
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock', $phpdoc->getText());
$this->assertEquals('@param \Stringable|string|null $a', $this->tagsToString($phpdoc, 'param'));
$this->assertEquals('@return \Stringable|string|null', $this->tagsToString($phpdoc, 'return'));
}
protected function tagsToString(DocBlock $docBlock, string $name)
{
$tags = $docBlock->getTagsByName($name);
$tags = array_map(
function (Tag $tag) {
return trim((string)$tag);
},
$tags
);
$tags = implode(PHP_EOL, $tags);
return $tags;
}
/**
* Test that we can actually instantiate the class
*/
public function testCanInstantiate()
{
$reflectionMethod = new \ReflectionMethod(UrlGeneratorMacroClass::class, '__invoke');
$macro = new Macro($reflectionMethod, UrlGenerator::class, new ReflectionClass(UrlGenerator::class), 'macroName');
$this->assertInstanceOf(Macro::class, $macro);
}
/**
* Test the output of a class
*/
public function testOutput()
{
$reflectionMethod = new \ReflectionMethod(UrlGeneratorMacroClass::class, '__invoke');
$macro = new Macro($reflectionMethod, 'URL', new ReflectionClass(UrlGenerator::class), 'macroName');
$output = <<<'DOC'
/**
* @param string $foo
* @param int $bar
* @return string
* @see \Barryvdh\LaravelIdeHelper\Tests\UrlGeneratorMacroClass::__invoke()
* @static
*/
DOC;
$this->assertSame($output, $macro->getDocComment(''));
$this->assertSame('__invoke', $macro->getRealName());
$this->assertSame('\\' . UrlGenerator::class, $macro->getDeclaringClass());
$this->assertSame('$foo, $bar', $macro->getParams(true));
$this->assertSame(['$foo', '$bar'], $macro->getParams(false));
$this->assertSame('$foo, $bar = 0', $macro->getParamsWithDefault(true));
$this->assertSame(['$foo', '$bar = 0'], $macro->getParamsWithDefault(false));
$this->assertTrue($macro->shouldReturn());
$this->assertSame('$instance->__invoke($foo, $bar)', $macro->getRootMethodCall());
}
}
/**
* @internal
* @noinspection PhpMultipleClassesDeclarationsInOneFile
*/
class MacroMock extends Macro
{
public function __construct()
{
// no need to call parent
}
public function getPhpDoc(ReflectionFunctionAbstract $method, ?ReflectionClass $class = null): DocBlock
{
return (new Macro($method, '', $class ?? $method->getClosureScopeClass()))->phpdoc;
}
}
/**
* Example of an invokable class to be used as a macro.
*/
class UrlGeneratorMacroClass
{
/**
* @param string $foo
* @param int $bar
* @return string
*/
public function __invoke(string $foo, int $bar = 0): string
{
return '';
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/TestCase.php | tests/TestCase.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Mockery;
use Orchestra\Testbench\TestCase as BaseTestCase;
use Spatie\Snapshots\MatchesSnapshots;
use Symfony\Component\Console\Tester\CommandTester;
abstract class TestCase extends BaseTestCase
{
use MatchesSnapshots;
protected $mockFilesystemOutput;
/**
* The `CommandTester` is directly returned, use methods like
* `->getDisplay()` or `->getStatusCode()` on it.
*
* @param Command $command
* @param array $arguments The command line arguments, array of key=>value
* Examples:
* - named arguments: ['model' => 'Post']
* - boolean flags: ['--all' => true]
* - arguments with values: ['--arg' => 'value']
* @param array $interactiveInput Interactive responses to the command
* I.e. anything the command `->ask()` or `->confirm()`, etc.
* @return CommandTester
*/
protected function runCommand(Command $command, array $arguments = [], array $interactiveInput = []): CommandTester
{
$this->withoutMockingConsoleOutput();
$command->setLaravel($this->app);
$tester = new CommandTester($command);
$tester->setInputs($interactiveInput);
$tester->execute($arguments);
return $tester;
}
protected function assertMatchesPhpSnapshot(?string $actualContent)
{
$this->assertMatchesSnapshot($actualContent, new SnapshotPhpDriver());
}
protected function assertMatchesTxtSnapshot(?string $actualContent)
{
$this->assertMatchesSnapshot($actualContent, new SnapshotTxtDriver());
}
protected function assertMatchesMockedSnapshot()
{
$this->assertMatchesSnapshot($this->mockFilesystemOutput, new SnapshotPhpDriver());
}
protected function mockFilesystem()
{
$mockFilesystem = Mockery::mock(Filesystem::class)->makePartial();
$mockFilesystem
->shouldReceive('put')
->with(
Mockery::any(),
Mockery::any()
)
->andReturnUsing(function ($path, $contents) {
$contents = str_replace(["\r\n", "\r"], "\n", $contents);
$this->mockFilesystemOutput .= $contents;
return strlen($contents);
});
$this->instance(Filesystem::class, $mockFilesystem);
$this->instance('files', $mockFilesystem);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/RealTimeFacadesTest.php | tests/RealTimeFacadesTest.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests;
use Barryvdh\LaravelIdeHelper\Generator;
use Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use PhpParser\Lexer\Emulative;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Parser\Php7;
class RealTimeFacadesTest extends TestCase
{
public function testRealTimeFacades()
{
// Add the views path to the view finder so the generator actually generates the file
View::addLocation(__DIR__ . '/../resources/views');
// Clear cached real-time facades
$cachedFacades = glob(storage_path('framework/cache/facade-*.php'));
foreach ($cachedFacades as $cachedFacade) {
unlink($cachedFacade);
}
// Copy stubs to storage path as if the real-time facades were cached by the framework
copy(
__DIR__ . '/stubs/facade-0e0385307adf5db34c7986ecbd11646061356ec8.php',
storage_path('framework/cache/facade-0e0385307adf5db34c7986ecbd11646061356ec8.php')
);
copy(
__DIR__ . '/stubs/facade-9431b04ec1494fc71a1bc848f020044aba2af7b1.php',
storage_path('framework/cache/facade-9431b04ec1494fc71a1bc848f020044aba2af7b1.php')
);
// new instance of the generator which we test
$generator = new Generator($this->app['config'], $this->app['view'], null, false);
// Clear aliases and macros to have a small output file
AliasLoader::getInstance()->setAliases([]);
Request::flushMacros();
// Generate the helper file and return the content
$content = $generator->generate();
$this->assertStringContainsString('namespace Facades\Illuminate\Foundation\Exceptions {', $content, 'Could not find Facades\Illuminate\Foundation\Exceptions namespace in the generated helper file.');
$this->assertStringContainsString('namespace Facades\App\Exceptions {', $content, 'Could not find Facades\App\Exceptions namespace in the generated helper file.');
$parsed = collect((new Php7(new Emulative()))->parse($content) ?: []);
// test the Facades\Illuminate\Foundation\Exceptions namespace in the generated helper file
$frameworkExceptionsNamespace = $parsed->first(function ($stmt) {
return ($stmt instanceof Namespace_) && $stmt->name->toString() === 'Facades\Illuminate\Foundation\Exceptions';
});
$this->assertNotNull($frameworkExceptionsNamespace, 'Could not find Facades\Illuminate\Foundation\Exceptions namespace');
$this->assertSame('Facades\Illuminate\Foundation\Exceptions', $frameworkExceptionsNamespace->name->toString());
$this->verifyNamespace($frameworkExceptionsNamespace, 'Illuminate\Foundation\Exceptions\Handler');
// test the Facades\App\Exceptions namespace in the generated helper file
$appExceptionsNamespace = $parsed->first(function ($stmt) {
return ($stmt instanceof Namespace_) && $stmt->name->toString() === 'Facades\App\Exceptions';
});
$this->assertNotNull($appExceptionsNamespace, 'Could not find Facades\App\Exceptions namespace');
$this->assertSame('Facades\App\Exceptions', $appExceptionsNamespace->name->toString());
$this->verifyNamespace($appExceptionsNamespace, 'App\Exceptions\Handler');
}
private function verifyNamespace(Namespace_ $namespace, $target)
{
$stmts = collect($namespace->stmts);
$this->assertInstanceOf(Class_::class, $stmts[0], 'Expected instance of Class_');
$statement = $stmts[0];
$this->assertArrayHasKey('comments', $statement->getAttributes());
$this->assertStringContainsString('@mixin \\' . $target, $statement->getAttributes()['comments'][0]->getText(), 'Mixin comment not found');
$this->assertSame(class_basename($target), $statement->name->toString(), 'Class name not found');
$this->assertSame($target, $statement->extends->toString(), 'Class extends not found');
}
protected function getPackageProviders($app)
{
return [IdeHelperServiceProvider::class];
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/EloquentCommandTest.php | tests/Console/EloquentCommandTest.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\EloquentCommand;
use Barryvdh\LaravelIdeHelper\Console\EloquentCommand;
use Barryvdh\LaravelIdeHelper\Tests\TestCase;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Filesystem\Filesystem;
use Mockery;
use ReflectionClass;
class EloquentCommandTest extends TestCase
{
public function testCommand()
{
$modelFilename = $this->getVendorModelFilename();
$modelSource = file_get_contents($modelFilename);
if (false !== strpos($modelSource, '* @mixin')) {
$msg = sprintf('Class %s already contains the @mixin markers', Model::class);
$this->markTestSkipped($msg);
}
$actualContent = null;
$mockFilesystem = Mockery::mock(Filesystem::class)->makePartial();
$mockFilesystem
->shouldReceive('get')
// We don't care about actual args (filename)
->andReturn('abstract class Model implements'); // This is enough to trigger the replacement logic
$mockFilesystem
->shouldReceive('put')
->with(
Mockery::any(), // First arg is path, we don't care
Mockery::capture($actualContent)
)
->andReturn(1) // Simulate we wrote _something_ to the file
->once();
$this->instance(Filesystem::class, $mockFilesystem);
$command = $this->app->make(EloquentCommand::class);
$tester = $this->runCommand($command);
$this->assertMatchesTxtSnapshot($actualContent);
$display = $tester->getDisplay();
$this->assertMatchesRegularExpression(
';Unexpected no document on Illuminate\\\Database\\\Eloquent\\\Model;',
$display
);
$modelClassFilePath = preg_quote(
str_replace('/', DIRECTORY_SEPARATOR, '/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php')
);
$this->assertMatchesRegularExpression(
';Wrote expected docblock to .*' . $modelClassFilePath . ';',
$display
);
}
private function getVendorModelFilename(): string
{
$class = Model::class;
$reflectedClass = new ReflectionClass($class);
return $reflectedClass->getFileName();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/AbstractModelsCommand.php | tests/Console/ModelsCommand/AbstractModelsCommand.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider;
use Barryvdh\LaravelIdeHelper\Tests\TestCase;
abstract class AbstractModelsCommand extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$this->loadMigrationsFrom(__DIR__ . '/migrations');
$this->artisan('migrate');
$this->mockFilesystem();
}
/**
* Get package providers.
*
* @param \Illuminate\Foundation\Application $app
*
* @return array
*/
protected function getPackageProviders($app)
{
return [IdeHelperServiceProvider::class];
}
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
$config = $app['config'];
$config->set('database.default', 'sqlite');
$config->set('database.connections.sqlite', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
// Load the Models from the Test dir
$config->set('ide-helper.model_locations', [
dirname((new \ReflectionClass(static::class))->getFileName()) . '/Models',
]);
// Don't override integer -> int for tests
$config->set('ide-helper.type_overrides', []);
$config->set('ide-helper.write_model_relation_exists_properties', true);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/DynamicRelations/Test.php | tests/Console/ModelsCommand/DynamicRelations/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$errors = [
'Error resolving relation model of Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations\Models\Dynamic:dynamicBelongsTo() : Attempt to read property "created_at" on null',
'Error resolving relation model of Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations\Models\Dynamic:dynamicHasMany() : Attempt to read property "created_at" on null',
'Error resolving relation model of Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations\Models\Dynamic:dynamicHasOne() : Attempt to read property "created_at" on null',
];
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
foreach ($errors as $error) {
$this->assertStringContainsString($error, $tester->getDisplay());
}
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/DynamicRelations/OtherModels/Account.php | tests/Console/ModelsCommand/DynamicRelations/OtherModels/Account.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations\OtherModels;
use Illuminate\Database\Eloquent\Model;
class Account extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/DynamicRelations/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/DynamicRelations/__snapshots__/Test__test__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
/**
* @property-read \Illuminate\Database\Eloquent\Collection<int, Dynamic> $regularHasMany
* @property-read int|null $regular_has_many_count
* @property-read bool|null $regular_has_many_exists
* @method static \Illuminate\Database\Eloquent\Builder<static>|Dynamic newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Dynamic newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Dynamic query()
* @mixin \Eloquent
*/
class Dynamic extends Model
{
/** @var \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations\OtherModels\Account */
protected $account;
// Regular relations
public function regularHasMany(): HasMany
{
return $this->hasMany(Dynamic::class);
}
// Dynamic relations
public function dynamicHasMany(): HasMany
{
return $this->hasMany(Dynamic::class)->where('date', '>=', $this->account->created_at);
}
public function dynamicHasOne(): HasOne
{
return $this->hasOne(Dynamic::class)->where('date', '>=', $this->account->created_at);
}
public function dynamicBelongsTo(): BelongsTo
{
return $this->belongsTo(Dynamic::class)->where('date', '>=', $this->account->created_at);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/DynamicRelations/Models/Dynamic.php | tests/Console/ModelsCommand/DynamicRelations/Models/Dynamic.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
class Dynamic extends Model
{
/** @var \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DynamicRelations\OtherModels\Account */
protected $account;
// Regular relations
public function regularHasMany(): HasMany
{
return $this->hasMany(Dynamic::class);
}
// Dynamic relations
public function dynamicHasMany(): HasMany
{
return $this->hasMany(Dynamic::class)->where('date', '>=', $this->account->created_at);
}
public function dynamicHasOne(): HasOne
{
return $this->hasOne(Dynamic::class)->where('date', '>=', $this->account->created_at);
}
public function dynamicBelongsTo(): BelongsTo
{
return $this->belongsTo(Dynamic::class)->where('date', '>=', $this->account->created_at);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Ignored/Test.php | tests/Console/ModelsCommand/Ignored/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Ignored;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Ignored\Models\Ignored;
class Test extends AbstractModelsCommand
{
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
$app['config']->set('ide-helper.ignored_models', [
Ignored::class,
]);
}
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Ignored/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/Ignored/__snapshots__/Test__test__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Ignored\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @method static \Illuminate\Database\Eloquent\Builder<static>|NotIgnored newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|NotIgnored newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|NotIgnored query()
* @mixin \Eloquent
*/
class NotIgnored extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Ignored/Models/Ignored.php | tests/Console/ModelsCommand/Ignored/Models/Ignored.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Ignored\Models;
use Illuminate\Database\Eloquent\Model;
class Ignored extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Ignored/Models/NotIgnored.php | tests/Console/ModelsCommand/Ignored/Models/NotIgnored.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Ignored\Models;
use Illuminate\Database\Eloquent\Model;
class NotIgnored extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateMixinCollection/Test.php | tests/Console/ModelsCommand/GenerateMixinCollection/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write-mixin' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateMixinCollection/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/GenerateMixinCollection/__snapshots__/Test__test__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels\CollectionModel;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels\NonModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Collection as IntCollection;
/**
* @mixin IdeHelperWithCollection
*/
class WithCollection extends Model
{
/**
* @return Collection<int, string>
*/
public function getCollectionAttribute(): Collection
{
return new Collection();
}
/**
* @return Collection
*/
public function getCollectionWithoutTemplateAttribute(): Collection
{
return new Collection();
}
public function getCollectionWithoutDocBlockAttribute(): Collection
{
return new Collection();
}
/**
* @return Collection<int, NonModel>
*/
public function getCollectionWithNonModelTemplateAttribute(): Collection
{
return new Collection();
}
/**
* @return Collection<Collection, CollectionModel<IntCollection, CollectionModel<int, NonModel>>>
*/
public function getCollectionWithNestedTemplateAttribute(): Collection
{
return new Collection();
}
}
<?php
// @formatter:off
// phpcs:ignoreFile
/**
* A helper file for your Eloquent Models
* Copy the phpDocs from this file to the correct Model,
* And remove them from this file, to prevent double declarations.
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\Models{
/**
* @property-read \Illuminate\Support\Collection<int, string> $collection
* @property-read \Illuminate\Support\Collection<\Illuminate\Support\Collection, \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels\CollectionModel<\Illuminate\Support\Collection, \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels\CollectionModel<int, \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels\NonModel>>> $collection_with_nested_template
* @property-read \Illuminate\Support\Collection<int, \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels\NonModel> $collection_with_non_model_template
* @property-read \Illuminate\Support\Collection $collection_without_doc_block
* @property-read \Illuminate\Support\Collection $collection_without_template
* @method static \Illuminate\Database\Eloquent\Builder<static>|WithCollection newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|WithCollection newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|WithCollection query()
* @mixin \Eloquent
*/
#[\AllowDynamicProperties]
class IdeHelperWithCollection {}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateMixinCollection/NonModels/NonModel.php | tests/Console/ModelsCommand/GenerateMixinCollection/NonModels/NonModel.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels;
class NonModel
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateMixinCollection/NonModels/CollectionModel.php | tests/Console/ModelsCommand/GenerateMixinCollection/NonModels/CollectionModel.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels;
class CollectionModel
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateMixinCollection/Models/WithCollection.php | tests/Console/ModelsCommand/GenerateMixinCollection/Models/WithCollection.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels\CollectionModel;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateMixinCollection\NonModels\NonModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Collection as IntCollection;
class WithCollection extends Model
{
/**
* @return Collection<int, string>
*/
public function getCollectionAttribute(): Collection
{
return new Collection();
}
/**
* @return Collection
*/
public function getCollectionWithoutTemplateAttribute(): Collection
{
return new Collection();
}
public function getCollectionWithoutDocBlockAttribute(): Collection
{
return new Collection();
}
/**
* @return Collection<int, NonModel>
*/
public function getCollectionWithNonModelTemplateAttribute(): Collection
{
return new Collection();
}
/**
* @return Collection<Collection, CollectionModel<IntCollection, CollectionModel<int, NonModel>>>
*/
public function getCollectionWithNestedTemplateAttribute(): Collection
{
return new Collection();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateBasicPhpDocWithEnumDefaults/Test.php | tests/Console/ModelsCommand/GenerateBasicPhpDocWithEnumDefaults/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpDocWithEnumDefaults;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateBasicPhpDocWithEnumDefaults/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/GenerateBasicPhpDocWithEnumDefaults/__snapshots__/Test__test__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpDocWithEnumDefaults\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpDocWithEnumDefaults\Enums\PostStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string|null $char_nullable
* @property string $char_not_nullable
* @property string|null $string_nullable
* @property string $string_not_nullable
* @property string|null $text_nullable
* @property string $text_not_nullable
* @property string|null $medium_text_nullable
* @property string $medium_text_not_nullable
* @property string|null $long_text_nullable
* @property string $long_text_not_nullable
* @property int|null $integer_nullable
* @property int $integer_not_nullable
* @property int|null $tiny_integer_nullable
* @property int $tiny_integer_not_nullable
* @property int|null $small_integer_nullable
* @property int $small_integer_not_nullable
* @property int|null $medium_integer_nullable
* @property int $medium_integer_not_nullable
* @property int|null $big_integer_nullable
* @property int $big_integer_not_nullable
* @property int|null $unsigned_integer_nullable
* @property int $unsigned_integer_not_nullable
* @property int|null $unsigned_tiny_integer_nullable
* @property int $unsigned_tiny_integer_not_nullable
* @property int|null $unsigned_small_integer_nullable
* @property int $unsigned_small_integer_not_nullable
* @property int|null $unsigned_medium_integer_nullable
* @property int $unsigned_medium_integer_not_nullable
* @property int|null $unsigned_big_integer_nullable
* @property int $unsigned_big_integer_not_nullable
* @property float|null $float_nullable
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
* @property string $enum_not_nullable
* @property string|null $json_nullable
* @property string $json_not_nullable
* @property string|null $jsonb_nullable
* @property string $jsonb_not_nullable
* @property string|null $date_nullable
* @property string $date_not_nullable
* @property string|null $datetime_nullable
* @property string $datetime_not_nullable
* @property string|null $datetimetz_nullable
* @property string $datetimetz_not_nullable
* @property string|null $time_nullable
* @property string $time_not_nullable
* @property string|null $timetz_nullable
* @property string $timetz_not_nullable
* @property string|null $timestamp_nullable
* @property string $timestamp_not_nullable
* @property string|null $timestamptz_nullable
* @property string $timestamptz_not_nullable
* @property int|null $year_nullable
* @property int $year_not_nullable
* @property string|null $binary_nullable
* @property string $binary_not_nullable
* @property string|null $uuid_nullable
* @property string $uuid_not_nullable
* @property string|null $ipaddress_nullable
* @property string $ipaddress_not_nullable
* @property string|null $macaddress_nullable
* @property string $macaddress_not_nullable
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static Builder<static>|Post hasStatus(?\Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpDocWithEnumDefaults\Enums\PostStatus $status = \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpDocWithEnumDefaults\Enums\PostStatus::Published)
* @method static Builder<static>|Post newModelQuery()
* @method static Builder<static>|Post newQuery()
* @method static Builder<static>|Post query()
* @method static Builder<static>|Post whereBigIntegerNotNullable($value)
* @method static Builder<static>|Post whereBigIntegerNullable($value)
* @method static Builder<static>|Post whereBinaryNotNullable($value)
* @method static Builder<static>|Post whereBinaryNullable($value)
* @method static Builder<static>|Post whereBooleanNotNullable($value)
* @method static Builder<static>|Post whereBooleanNullable($value)
* @method static Builder<static>|Post whereCharNotNullable($value)
* @method static Builder<static>|Post whereCharNullable($value)
* @method static Builder<static>|Post whereCreatedAt($value)
* @method static Builder<static>|Post whereDateNotNullable($value)
* @method static Builder<static>|Post whereDateNullable($value)
* @method static Builder<static>|Post whereDatetimeNotNullable($value)
* @method static Builder<static>|Post whereDatetimeNullable($value)
* @method static Builder<static>|Post whereDatetimetzNotNullable($value)
* @method static Builder<static>|Post whereDatetimetzNullable($value)
* @method static Builder<static>|Post whereDecimalNotNullable($value)
* @method static Builder<static>|Post whereDecimalNullable($value)
* @method static Builder<static>|Post whereDoubleNotNullable($value)
* @method static Builder<static>|Post whereDoubleNullable($value)
* @method static Builder<static>|Post whereEnumNotNullable($value)
* @method static Builder<static>|Post whereEnumNullable($value)
* @method static Builder<static>|Post whereFloatNotNullable($value)
* @method static Builder<static>|Post whereFloatNullable($value)
* @method static Builder<static>|Post whereId($value)
* @method static Builder<static>|Post whereIntegerNotNullable($value)
* @method static Builder<static>|Post whereIntegerNullable($value)
* @method static Builder<static>|Post whereIpaddressNotNullable($value)
* @method static Builder<static>|Post whereIpaddressNullable($value)
* @method static Builder<static>|Post whereJsonNotNullable($value)
* @method static Builder<static>|Post whereJsonNullable($value)
* @method static Builder<static>|Post whereJsonbNotNullable($value)
* @method static Builder<static>|Post whereJsonbNullable($value)
* @method static Builder<static>|Post whereLongTextNotNullable($value)
* @method static Builder<static>|Post whereLongTextNullable($value)
* @method static Builder<static>|Post whereMacaddressNotNullable($value)
* @method static Builder<static>|Post whereMacaddressNullable($value)
* @method static Builder<static>|Post whereMediumIntegerNotNullable($value)
* @method static Builder<static>|Post whereMediumIntegerNullable($value)
* @method static Builder<static>|Post whereMediumTextNotNullable($value)
* @method static Builder<static>|Post whereMediumTextNullable($value)
* @method static Builder<static>|Post whereSmallIntegerNotNullable($value)
* @method static Builder<static>|Post whereSmallIntegerNullable($value)
* @method static Builder<static>|Post whereStringNotNullable($value)
* @method static Builder<static>|Post whereStringNullable($value)
* @method static Builder<static>|Post whereTextNotNullable($value)
* @method static Builder<static>|Post whereTextNullable($value)
* @method static Builder<static>|Post whereTimeNotNullable($value)
* @method static Builder<static>|Post whereTimeNullable($value)
* @method static Builder<static>|Post whereTimestampNotNullable($value)
* @method static Builder<static>|Post whereTimestampNullable($value)
* @method static Builder<static>|Post whereTimestamptzNotNullable($value)
* @method static Builder<static>|Post whereTimestamptzNullable($value)
* @method static Builder<static>|Post whereTimetzNotNullable($value)
* @method static Builder<static>|Post whereTimetzNullable($value)
* @method static Builder<static>|Post whereTinyIntegerNotNullable($value)
* @method static Builder<static>|Post whereTinyIntegerNullable($value)
* @method static Builder<static>|Post whereUnsignedBigIntegerNotNullable($value)
* @method static Builder<static>|Post whereUnsignedBigIntegerNullable($value)
* @method static Builder<static>|Post whereUnsignedIntegerNotNullable($value)
* @method static Builder<static>|Post whereUnsignedIntegerNullable($value)
* @method static Builder<static>|Post whereUnsignedMediumIntegerNotNullable($value)
* @method static Builder<static>|Post whereUnsignedMediumIntegerNullable($value)
* @method static Builder<static>|Post whereUnsignedSmallIntegerNotNullable($value)
* @method static Builder<static>|Post whereUnsignedSmallIntegerNullable($value)
* @method static Builder<static>|Post whereUnsignedTinyIntegerNotNullable($value)
* @method static Builder<static>|Post whereUnsignedTinyIntegerNullable($value)
* @method static Builder<static>|Post whereUpdatedAt($value)
* @method static Builder<static>|Post whereUuidNotNullable($value)
* @method static Builder<static>|Post whereUuidNullable($value)
* @method static Builder<static>|Post whereYearNotNullable($value)
* @method static Builder<static>|Post whereYearNullable($value)
* @mixin \Eloquent
*/
class Post extends Model
{
public function scopeHasStatus(Builder $query, ?PostStatus $status = PostStatus::Published)
{
//
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateBasicPhpDocWithEnumDefaults/Enums/PostStatus.php | tests/Console/ModelsCommand/GenerateBasicPhpDocWithEnumDefaults/Enums/PostStatus.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpDocWithEnumDefaults\Enums;
enum PostStatus
{
case Published;
case Unpublished;
case Archived;
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateBasicPhpDocWithEnumDefaults/Models/Post.php | tests/Console/ModelsCommand/GenerateBasicPhpDocWithEnumDefaults/Models/Post.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpDocWithEnumDefaults\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpDocWithEnumDefaults\Enums\PostStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function scopeHasStatus(Builder $query, ?PostStatus $status = PostStatus::Published)
{
//
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Test.php | tests/Console/ModelsCommand/Relations/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToAnyMorphedRelationType;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToAnyRelationType;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToBadlyNamedNotManyRelationType;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToManyRelationType;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToOneRelationType;
use Illuminate\Support\Facades\Config;
class Test extends AbstractModelsCommand
{
protected function setUp(): void
{
parent::setUp();
Config::set('ide-helper.additional_relation_types', [
'testToOneRelation' => SampleToOneRelationType::class,
'testToManyRelation' => SampleToManyRelationType::class,
'testToAnyRelation' => SampleToAnyRelationType::class,
'testToAnyMorphedRelation' => SampleToAnyMorphedRelationType::class,
'testToBadlyNamedNotManyRelation' => SampleToBadlyNamedNotManyRelationType::class,
]);
Config::set('ide-helper.additional_relation_return_types', [
'testToAnyRelation' => 'many',
'testToAnyMorphedRelation' => 'morphTo',
'testToBadlyNamedNotManyRelation' => 'one',
]);
}
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
public function testRelationNotNullable(): void
{
// Disable enforcing nullable relationships
Config::set('ide-helper.enforce_nullable_relationships', false);
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
// Re-enable default enforcing nullable relationships
Config::set('ide-helper.enforce_nullable_relationships', true);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Types/SampleToManyRelationType.php | tests/Console/ModelsCommand/Relations/Types/SampleToManyRelationType.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Relation;
class SampleToManyRelationType extends Relation
{
public function addConstraints()
{
// Fake
}
public function addEagerConstraints(array $models)
{
// Fake
}
public function initRelation(array $models, $relation)
{
// Fake
}
public function match(array $models, Collection $results, $relation)
{
// Fake
}
public function getResults()
{
// Fake
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Types/SampleToAnyMorphedRelationType.php | tests/Console/ModelsCommand/Relations/Types/SampleToAnyMorphedRelationType.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Relation;
class SampleToAnyMorphedRelationType extends Relation
{
public function addConstraints()
{
// Fake
}
public function addEagerConstraints(array $models)
{
// Fake
}
public function initRelation(array $models, $relation)
{
// Fake
}
public function match(array $models, Collection $results, $relation)
{
// Fake
}
public function getResults()
{
// Fake
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Types/SampleToOneRelationType.php | tests/Console/ModelsCommand/Relations/Types/SampleToOneRelationType.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Concerns\SupportsDefaultModels;
use Illuminate\Database\Eloquent\Relations\Relation;
/**
* Sample for custom relation
*
* the relation is a big fake and only for testing of the docblock generation
*
* @package Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations
*/
class SampleToOneRelationType extends Relation
{
use SupportsDefaultModels;
public function addConstraints()
{
// Fake
}
public function addEagerConstraints(array $models)
{
// Fake
}
public function initRelation(array $models, $relation)
{
// Fake
}
public function match(array $models, Collection $results, $relation)
{
// Fake
}
public function getResults()
{
// Fake
}
protected function newRelatedInstanceFor(Model $parent)
{
// Fake
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Types/SampleToBadlyNamedNotManyRelationType.php | tests/Console/ModelsCommand/Relations/Types/SampleToBadlyNamedNotManyRelationType.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Concerns\SupportsDefaultModels;
use Illuminate\Database\Eloquent\Relations\Relation;
/**
* Sample for custom relation
*
* the relation is a big fake and only for testing of the docblock generation
*
* @package Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations
*/
class SampleToBadlyNamedNotManyRelationType extends Relation
{
use SupportsDefaultModels;
public function addConstraints()
{
// Fake
}
public function addEagerConstraints(array $models)
{
// Fake
}
public function initRelation(array $models, $relation)
{
// Fake
}
public function match(array $models, Collection $results, $relation)
{
// Fake
}
public function getResults()
{
// Fake
}
protected function newRelatedInstanceFor(Model $parent)
{
// Fake
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Types/SampleToAnyRelationType.php | tests/Console/ModelsCommand/Relations/Types/SampleToAnyRelationType.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Relation;
class SampleToAnyRelationType extends Relation
{
public function addConstraints()
{
// Fake
}
public function addEagerConstraints(array $models)
{
// Fake
}
public function initRelation(array $models, $relation)
{
// Fake
}
public function match(array $models, Collection $results, $relation)
{
// Fake
}
public function getResults()
{
// Fake
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Traits/HasTestRelations.php | tests/Console/ModelsCommand/Relations/Traits/HasTestRelations.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Traits;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToAnyMorphedRelationType;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToAnyRelationType;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToBadlyNamedNotManyRelationType;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToManyRelationType;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Types\SampleToOneRelationType;
trait HasTestRelations
{
public function testToOneRelation($related)
{
$instance = $this->newRelatedInstance($related);
return new SampleToOneRelationType($instance->newQuery(), $this);
}
public function testToManyRelation($related)
{
$instance = $this->newRelatedInstance($related);
return new SampleToManyRelationType($instance->newQuery(), $this);
}
public function testToAnyRelation($related)
{
$instance = $this->newRelatedInstance($related);
return new SampleToAnyRelationType($instance->newQuery(), $this);
}
public function testToAnyMorphedRelation($related)
{
$instance = $this->newRelatedInstance($related);
return new SampleToAnyMorphedRelationType($instance->newQuery(), $this);
}
public function testToBadlyNamedNotManyRelation($related)
{
$instance = $this->newRelatedInstance($related);
return new SampleToBadlyNamedNotManyRelationType($instance->newQuery(), $this);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/Relations/__snapshots__/Test__test__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* @property int $id
* @property int $not_null_column_with_foreign_key_constraint
* @property int $not_null_column_with_no_foreign_key_constraint
* @property int|null $nullable_column_with_foreign_key_constraint
* @property int|null $nullable_column_with_no_foreign_key_constraint
* @property-read BelongsToVariation $notNullColumnWithForeignKeyConstraint
* @property-read BelongsToVariation|null $notNullColumnWithNoForeignKeyConstraint
* @property-read BelongsToVariation|null $nullableColumnWithForeignKeyConstraint
* @property-read BelongsToVariation|null $nullableColumnWithNoForeignKeyConstraint
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereNotNullColumnWithForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereNotNullColumnWithNoForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereNullableColumnWithForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereNullableColumnWithNoForeignKeyConstraint($value)
* @mixin \Eloquent
*/
class BelongsToVariation extends Model
{
public function notNullColumnWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'not_null_column_with_foreign_key_constraint');
}
public function notNullColumnWithNoForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'not_null_column_with_no_foreign_key_constraint');
}
public function nullableColumnWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'nullable_column_with_foreign_key_constraint');
}
public function nullableColumnWithNoForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'nullable_column_with_no_foreign_key_constraint');
}
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* @property int $id
* @property int $not_null_column_with_foreign_key_constraint
* @property int $not_null_column_with_no_foreign_key_constraint
* @property int|null $nullable_column_with_foreign_key_constraint
* @property int|null $nullable_column_with_no_foreign_key_constraint
* @property-read CompositeBelongsToVariation $bothNonNullableWithForeignKeyConstraint
* @property-read CompositeBelongsToVariation|null $nonNullableMixedWithoutForeignKeyConstraint
* @property-read CompositeBelongsToVariation|null $nullableMixedWithForeignKeyConstraint
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereNotNullColumnWithForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereNotNullColumnWithNoForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereNullableColumnWithForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereNullableColumnWithNoForeignKeyConstraint($value)
* @mixin \Eloquent
*/
class CompositeBelongsToVariation extends Model
{
public $table = 'belongs_to_variations';
public function bothNonNullableWithForeignKeyConstraint(): BelongsTo
{
// Note, duplicating the keys here for simplicity.
return $this->belongsTo(
self::class,
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
);
}
public function nonNullableMixedWithoutForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(
self::class,
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_no_foreign_key_constraint'],
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_no_foreign_key_constraint'],
);
}
public function nullableMixedWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(
self::class,
['nullable_column_with_no_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
['nullable_column_with_no_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
);
}
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\ModelsOtherNamespace\AnotherModel;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Traits\HasTestRelations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
/**
* @property int $id
* @property-read Simple|null $relationBelongsTo
* @property-read AnotherModel|null $relationBelongsToInAnotherNamespace
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToMany
* @property-read int|null $relation_belongs_to_many_count
* @property-read bool|null $relation_belongs_to_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToManyWithSub
* @property-read int|null $relation_belongs_to_many_with_sub_count
* @property-read bool|null $relation_belongs_to_many_with_sub_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToManyWithSubAnother
* @property-read int|null $relation_belongs_to_many_with_sub_another_count
* @property-read bool|null $relation_belongs_to_many_with_sub_another_exists
* @property-read AnotherModel|null $relationBelongsToSameNameAsColumn
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationHasMany
* @property-read int|null $relation_has_many_count
* @property-read bool|null $relation_has_many_exists
* @property-read Simple|null $relationHasOne
* @property-read Simple $relationHasOneWithDefault
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationMorphMany
* @property-read int|null $relation_morph_many_count
* @property-read bool|null $relation_morph_many_exists
* @property-read Simple|null $relationMorphOne
* @property-read Model|\Eloquent $relationMorphTo
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationMorphedByMany
* @property-read int|null $relation_morphed_by_many_count
* @property-read bool|null $relation_morphed_by_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationSampleRelationType
* @property-read int|null $relation_sample_relation_type_count
* @property-read bool|null $relation_sample_relation_type_exists
* @property-read Model|\Eloquent $relationSampleToAnyMorphedRelationType
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationSampleToAnyRelationType
* @property-read int|null $relation_sample_to_any_relation_type_count
* @property-read bool|null $relation_sample_to_any_relation_type_exists
* @property-read Simple $relationSampleToBadlyNamedNotManyRelation
* @property-read Simple $relationSampleToManyRelationType
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple whereId($value)
* @mixin \Eloquent
*/
class Simple extends Model
{
use HasTestRelations;
// Regular relations
public function relationHasMany(): HasMany
{
return $this->hasMany(Simple::class);
}
public function relationHasOne(): HasOne
{
return $this->hasOne(Simple::class);
}
public function relationHasOneWithDefault(): HasOne
{
return $this->hasOne(Simple::class)->withDefault();
}
public function relationBelongsTo(): BelongsTo
{
return $this->belongsTo(Simple::class);
}
public function relationBelongsToMany(): BelongsToMany
{
return $this->belongsToMany(Simple::class);
}
public function relationBelongsToManyWithSub(): BelongsToMany
{
return $this->belongsToMany(Simple::class)->where('foo', 'bar');
}
public function relationBelongsToManyWithSubAnother(): BelongsToMany
{
return $this->relationBelongsToManyWithSub()->where('foo', 'bar');
}
public function relationMorphTo(): MorphTo
{
return $this->morphTo();
}
public function relationMorphOne(): MorphOne
{
return $this->morphOne(Simple::class, 'relationMorphTo');
}
public function relationMorphMany(): MorphMany
{
return $this->morphMany(Simple::class, 'relationMorphTo');
}
public function relationMorphedByMany(): MorphToMany
{
return $this->morphedByMany(Simple::class, 'foo');
}
// Custom relations
public function relationBelongsToInAnotherNamespace(): BelongsTo
{
return $this->belongsTo(AnotherModel::class);
}
public function relationBelongsToSameNameAsColumn(): BelongsTo
{
return $this->belongsTo(AnotherModel::class, __FUNCTION__);
}
public function relationSampleToManyRelationType()
{
return $this->testToOneRelation(Simple::class);
}
public function relationSampleRelationType()
{
return $this->testToManyRelation(Simple::class);
}
public function relationSampleToAnyRelationType()
{
return $this->testToAnyRelation(Simple::class);
}
public function relationSampleToAnyMorphedRelationType()
{
return $this->testToAnyMorphedRelation(Simple::class);
}
public function relationSampleToBadlyNamedNotManyRelation()
{
return $this->testToBadlyNamedNotManyRelation(Simple::class);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/__snapshots__/Test__testRelationNotNullable__1.php | tests/Console/ModelsCommand/Relations/__snapshots__/Test__testRelationNotNullable__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* @property int $id
* @property int $not_null_column_with_foreign_key_constraint
* @property int $not_null_column_with_no_foreign_key_constraint
* @property int|null $nullable_column_with_foreign_key_constraint
* @property int|null $nullable_column_with_no_foreign_key_constraint
* @property-read BelongsToVariation $notNullColumnWithForeignKeyConstraint
* @property-read BelongsToVariation $notNullColumnWithNoForeignKeyConstraint
* @property-read BelongsToVariation|null $nullableColumnWithForeignKeyConstraint
* @property-read BelongsToVariation|null $nullableColumnWithNoForeignKeyConstraint
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereNotNullColumnWithForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereNotNullColumnWithNoForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereNullableColumnWithForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|BelongsToVariation whereNullableColumnWithNoForeignKeyConstraint($value)
* @mixin \Eloquent
*/
class BelongsToVariation extends Model
{
public function notNullColumnWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'not_null_column_with_foreign_key_constraint');
}
public function notNullColumnWithNoForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'not_null_column_with_no_foreign_key_constraint');
}
public function nullableColumnWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'nullable_column_with_foreign_key_constraint');
}
public function nullableColumnWithNoForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'nullable_column_with_no_foreign_key_constraint');
}
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* @property int $id
* @property int $not_null_column_with_foreign_key_constraint
* @property int $not_null_column_with_no_foreign_key_constraint
* @property int|null $nullable_column_with_foreign_key_constraint
* @property int|null $nullable_column_with_no_foreign_key_constraint
* @property-read CompositeBelongsToVariation $bothNonNullableWithForeignKeyConstraint
* @property-read CompositeBelongsToVariation $nonNullableMixedWithoutForeignKeyConstraint
* @property-read CompositeBelongsToVariation|null $nullableMixedWithForeignKeyConstraint
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereNotNullColumnWithForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereNotNullColumnWithNoForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereNullableColumnWithForeignKeyConstraint($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|CompositeBelongsToVariation whereNullableColumnWithNoForeignKeyConstraint($value)
* @mixin \Eloquent
*/
class CompositeBelongsToVariation extends Model
{
public $table = 'belongs_to_variations';
public function bothNonNullableWithForeignKeyConstraint(): BelongsTo
{
// Note, duplicating the keys here for simplicity.
return $this->belongsTo(
self::class,
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
);
}
public function nonNullableMixedWithoutForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(
self::class,
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_no_foreign_key_constraint'],
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_no_foreign_key_constraint'],
);
}
public function nullableMixedWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(
self::class,
['nullable_column_with_no_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
['nullable_column_with_no_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
);
}
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\ModelsOtherNamespace\AnotherModel;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Traits\HasTestRelations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
/**
* @property int $id
* @property-read Simple $relationBelongsTo
* @property-read AnotherModel $relationBelongsToInAnotherNamespace
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToMany
* @property-read int|null $relation_belongs_to_many_count
* @property-read bool|null $relation_belongs_to_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToManyWithSub
* @property-read int|null $relation_belongs_to_many_with_sub_count
* @property-read bool|null $relation_belongs_to_many_with_sub_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToManyWithSubAnother
* @property-read int|null $relation_belongs_to_many_with_sub_another_count
* @property-read bool|null $relation_belongs_to_many_with_sub_another_exists
* @property-read AnotherModel $relationBelongsToSameNameAsColumn
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationHasMany
* @property-read int|null $relation_has_many_count
* @property-read bool|null $relation_has_many_exists
* @property-read Simple|null $relationHasOne
* @property-read Simple $relationHasOneWithDefault
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationMorphMany
* @property-read int|null $relation_morph_many_count
* @property-read bool|null $relation_morph_many_exists
* @property-read Simple|null $relationMorphOne
* @property-read Model|\Eloquent $relationMorphTo
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationMorphedByMany
* @property-read int|null $relation_morphed_by_many_count
* @property-read bool|null $relation_morphed_by_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationSampleRelationType
* @property-read int|null $relation_sample_relation_type_count
* @property-read bool|null $relation_sample_relation_type_exists
* @property-read Model|\Eloquent $relationSampleToAnyMorphedRelationType
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationSampleToAnyRelationType
* @property-read int|null $relation_sample_to_any_relation_type_count
* @property-read bool|null $relation_sample_to_any_relation_type_exists
* @property-read Simple $relationSampleToBadlyNamedNotManyRelation
* @property-read Simple $relationSampleToManyRelationType
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple whereId($value)
* @mixin \Eloquent
*/
class Simple extends Model
{
use HasTestRelations;
// Regular relations
public function relationHasMany(): HasMany
{
return $this->hasMany(Simple::class);
}
public function relationHasOne(): HasOne
{
return $this->hasOne(Simple::class);
}
public function relationHasOneWithDefault(): HasOne
{
return $this->hasOne(Simple::class)->withDefault();
}
public function relationBelongsTo(): BelongsTo
{
return $this->belongsTo(Simple::class);
}
public function relationBelongsToMany(): BelongsToMany
{
return $this->belongsToMany(Simple::class);
}
public function relationBelongsToManyWithSub(): BelongsToMany
{
return $this->belongsToMany(Simple::class)->where('foo', 'bar');
}
public function relationBelongsToManyWithSubAnother(): BelongsToMany
{
return $this->relationBelongsToManyWithSub()->where('foo', 'bar');
}
public function relationMorphTo(): MorphTo
{
return $this->morphTo();
}
public function relationMorphOne(): MorphOne
{
return $this->morphOne(Simple::class, 'relationMorphTo');
}
public function relationMorphMany(): MorphMany
{
return $this->morphMany(Simple::class, 'relationMorphTo');
}
public function relationMorphedByMany(): MorphToMany
{
return $this->morphedByMany(Simple::class, 'foo');
}
// Custom relations
public function relationBelongsToInAnotherNamespace(): BelongsTo
{
return $this->belongsTo(AnotherModel::class);
}
public function relationBelongsToSameNameAsColumn(): BelongsTo
{
return $this->belongsTo(AnotherModel::class, __FUNCTION__);
}
public function relationSampleToManyRelationType()
{
return $this->testToOneRelation(Simple::class);
}
public function relationSampleRelationType()
{
return $this->testToManyRelation(Simple::class);
}
public function relationSampleToAnyRelationType()
{
return $this->testToAnyRelation(Simple::class);
}
public function relationSampleToAnyMorphedRelationType()
{
return $this->testToAnyMorphedRelation(Simple::class);
}
public function relationSampleToBadlyNamedNotManyRelation()
{
return $this->testToBadlyNamedNotManyRelation(Simple::class);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/ModelsOtherNamespace/AnotherModel.php | tests/Console/ModelsCommand/Relations/ModelsOtherNamespace/AnotherModel.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\ModelsOtherNamespace;
use Illuminate\Database\Eloquent\Model;
class AnotherModel extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Models/BelongsToVariation.php | tests/Console/ModelsCommand/Relations/Models/BelongsToVariation.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BelongsToVariation extends Model
{
public function notNullColumnWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'not_null_column_with_foreign_key_constraint');
}
public function notNullColumnWithNoForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'not_null_column_with_no_foreign_key_constraint');
}
public function nullableColumnWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'nullable_column_with_foreign_key_constraint');
}
public function nullableColumnWithNoForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(self::class, 'nullable_column_with_no_foreign_key_constraint');
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Models/CompositeBelongsToVariation.php | tests/Console/ModelsCommand/Relations/Models/CompositeBelongsToVariation.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class CompositeBelongsToVariation extends Model
{
public $table = 'belongs_to_variations';
public function bothNonNullableWithForeignKeyConstraint(): BelongsTo
{
// Note, duplicating the keys here for simplicity.
return $this->belongsTo(
self::class,
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
);
}
public function nonNullableMixedWithoutForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(
self::class,
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_no_foreign_key_constraint'],
['not_null_column_with_foreign_key_constraint', 'not_null_column_with_no_foreign_key_constraint'],
);
}
public function nullableMixedWithForeignKeyConstraint(): BelongsTo
{
return $this->belongsTo(
self::class,
['nullable_column_with_no_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
['nullable_column_with_no_foreign_key_constraint', 'not_null_column_with_foreign_key_constraint'],
);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Relations/Models/Simple.php | tests/Console/ModelsCommand/Relations/Models/Simple.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\ModelsOtherNamespace\AnotherModel;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Relations\Traits\HasTestRelations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
class Simple extends Model
{
use HasTestRelations;
// Regular relations
public function relationHasMany(): HasMany
{
return $this->hasMany(Simple::class);
}
public function relationHasOne(): HasOne
{
return $this->hasOne(Simple::class);
}
public function relationHasOneWithDefault(): HasOne
{
return $this->hasOne(Simple::class)->withDefault();
}
public function relationBelongsTo(): BelongsTo
{
return $this->belongsTo(Simple::class);
}
public function relationBelongsToMany(): BelongsToMany
{
return $this->belongsToMany(Simple::class);
}
public function relationBelongsToManyWithSub(): BelongsToMany
{
return $this->belongsToMany(Simple::class)->where('foo', 'bar');
}
public function relationBelongsToManyWithSubAnother(): BelongsToMany
{
return $this->relationBelongsToManyWithSub()->where('foo', 'bar');
}
public function relationMorphTo(): MorphTo
{
return $this->morphTo();
}
public function relationMorphOne(): MorphOne
{
return $this->morphOne(Simple::class, 'relationMorphTo');
}
public function relationMorphMany(): MorphMany
{
return $this->morphMany(Simple::class, 'relationMorphTo');
}
public function relationMorphedByMany(): MorphToMany
{
return $this->morphedByMany(Simple::class, 'foo');
}
// Custom relations
public function relationBelongsToInAnotherNamespace(): BelongsTo
{
return $this->belongsTo(AnotherModel::class);
}
public function relationBelongsToSameNameAsColumn(): BelongsTo
{
return $this->belongsTo(AnotherModel::class, __FUNCTION__);
}
public function relationSampleToManyRelationType()
{
return $this->testToOneRelation(Simple::class);
}
public function relationSampleRelationType()
{
return $this->testToManyRelation(Simple::class);
}
public function relationSampleToAnyRelationType()
{
return $this->testToAnyRelation(Simple::class);
}
public function relationSampleToAnyMorphedRelationType()
{
return $this->testToAnyMorphedRelation(Simple::class);
}
public function relationSampleToBadlyNamedNotManyRelation()
{
return $this->testToBadlyNamedNotManyRelation(Simple::class);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Interfaces/Test.php | tests/Console/ModelsCommand/Interfaces/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Interfaces;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
final class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--nowrite' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Model information was written to _ide_helper_models.php', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Interfaces/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/Interfaces/__snapshots__/Test__test__1.php | <?php
// @formatter:off
// phpcs:ignoreFile
/**
* A helper file for your Eloquent Models
* Copy the phpDocs from this file to the correct Model,
* And remove them from this file, to prevent double declarations.
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Interfaces\Models{
/**
* @method static \Illuminate\Database\Eloquent\Builder<static>|User newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|User newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|User query()
*/
class User extends \Eloquent implements \Illuminate\Contracts\Auth\Authenticatable {}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/Interfaces/Models/User.php | tests/Console/ModelsCommand/Interfaces/Models/User.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Interfaces\Models;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
public function getAuthIdentifierName()
{
// TODO: Implement getAuthIdentifierName() method.
}
public function getAuthIdentifier()
{
// TODO: Implement getAuthIdentifier() method.
}
public function getAuthPasswordName()
{
// TODO: Implement getAuthPasswordName() method.
}
public function getAuthPassword()
{
// TODO: Implement getAuthPassword() method.
}
public function getRememberToken()
{
// TODO: Implement getRememberToken() method.
}
public function setRememberToken($value)
{
// TODO: Implement setRememberToken() method.
}
public function getRememberTokenName()
{
// TODO: Implement getRememberTokenName() method.
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateBasicPhpdoc/Test.php | tests/Console/ModelsCommand/GenerateBasicPhpdoc/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpdoc;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertStringContainsString('Do you want to generate a minimal helper to generate the Eloquent methods?', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateBasicPhpdoc/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/GenerateBasicPhpdoc/__snapshots__/Test__test__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpdoc\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string|null $char_nullable
* @property string $char_not_nullable
* @property string|null $string_nullable
* @property string $string_not_nullable
* @property string|null $text_nullable
* @property string $text_not_nullable
* @property string|null $medium_text_nullable
* @property string $medium_text_not_nullable
* @property string|null $long_text_nullable
* @property string $long_text_not_nullable
* @property int|null $integer_nullable
* @property int $integer_not_nullable
* @property int|null $tiny_integer_nullable
* @property int $tiny_integer_not_nullable
* @property int|null $small_integer_nullable
* @property int $small_integer_not_nullable
* @property int|null $medium_integer_nullable
* @property int $medium_integer_not_nullable
* @property int|null $big_integer_nullable
* @property int $big_integer_not_nullable
* @property int|null $unsigned_integer_nullable
* @property int $unsigned_integer_not_nullable
* @property int|null $unsigned_tiny_integer_nullable
* @property int $unsigned_tiny_integer_not_nullable
* @property int|null $unsigned_small_integer_nullable
* @property int $unsigned_small_integer_not_nullable
* @property int|null $unsigned_medium_integer_nullable
* @property int $unsigned_medium_integer_not_nullable
* @property int|null $unsigned_big_integer_nullable
* @property int $unsigned_big_integer_not_nullable
* @property float|null $float_nullable
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
* @property string $enum_not_nullable
* @property string|null $json_nullable
* @property string $json_not_nullable
* @property string|null $jsonb_nullable
* @property string $jsonb_not_nullable
* @property string|null $date_nullable
* @property string $date_not_nullable
* @property string|null $datetime_nullable
* @property string $datetime_not_nullable
* @property string|null $datetimetz_nullable
* @property string $datetimetz_not_nullable
* @property string|null $time_nullable
* @property string $time_not_nullable
* @property string|null $timetz_nullable
* @property string $timetz_not_nullable
* @property string|null $timestamp_nullable
* @property string $timestamp_not_nullable
* @property string|null $timestamptz_nullable
* @property string $timestamptz_not_nullable
* @property int|null $year_nullable
* @property int $year_not_nullable
* @property string|null $binary_nullable
* @property string $binary_not_nullable
* @property string|null $uuid_nullable
* @property string $uuid_not_nullable
* @property string|null $ipaddress_nullable
* @property string $ipaddress_not_nullable
* @property string|null $macaddress_nullable
* @property string $macaddress_not_nullable
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBigIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBigIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBinaryNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBinaryNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBooleanNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBooleanNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCharNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCharNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDateNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDateNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimeNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimeNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimetzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimetzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDecimalNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDecimalNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDoubleNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDoubleNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereEnumNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereEnumNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereFloatNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereFloatNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIpaddressNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIpaddressNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonbNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonbNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereLongTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereLongTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMacaddressNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMacaddressNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereSmallIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereSmallIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereStringNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereStringNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimeNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimeNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestampNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestampNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestamptzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestamptzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimetzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimetzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTinyIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTinyIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedBigIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedBigIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedMediumIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedMediumIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedSmallIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedSmallIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedTinyIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedTinyIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUuidNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUuidNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereYearNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereYearNullable($value)
* @mixin \Eloquent
*/
class Post extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GenerateBasicPhpdoc/Models/Post.php | tests/Console/ModelsCommand/GenerateBasicPhpdoc/Models/Post.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GenerateBasicPhpdoc\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/DoesNotGeneratePhpdocWithExternalEloquentBuilder/Test.php | tests/Console/ModelsCommand/DoesNotGeneratePhpdocWithExternalEloquentBuilder/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGeneratePhpdocWithExternalEloquentBuilder;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
$app['config']->set('ide-helper.write_model_external_builder_methods', false);
}
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--nowrite' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Model information was written to _ide_helper_models.php', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/DoesNotGeneratePhpdocWithExternalEloquentBuilder/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/DoesNotGeneratePhpdocWithExternalEloquentBuilder/__snapshots__/Test__test__1.php | <?php
// @formatter:off
// phpcs:ignoreFile
/**
* A helper file for your Eloquent Models
* Copy the phpDocs from this file to the correct Model,
* And remove them from this file, to prevent double declarations.
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGeneratePhpdocWithExternalEloquentBuilder\Models{
/**
* @property int $id
* @property string|null $char_nullable
* @property string $char_not_nullable
* @property string|null $string_nullable
* @property string $string_not_nullable
* @property string|null $text_nullable
* @property string $text_not_nullable
* @property string|null $medium_text_nullable
* @property string $medium_text_not_nullable
* @property string|null $long_text_nullable
* @property string $long_text_not_nullable
* @property int|null $integer_nullable
* @property int $integer_not_nullable
* @property int|null $tiny_integer_nullable
* @property int $tiny_integer_not_nullable
* @property int|null $small_integer_nullable
* @property int $small_integer_not_nullable
* @property int|null $medium_integer_nullable
* @property int $medium_integer_not_nullable
* @property int|null $big_integer_nullable
* @property int $big_integer_not_nullable
* @property int|null $unsigned_integer_nullable
* @property int $unsigned_integer_not_nullable
* @property int|null $unsigned_tiny_integer_nullable
* @property int $unsigned_tiny_integer_not_nullable
* @property int|null $unsigned_small_integer_nullable
* @property int $unsigned_small_integer_not_nullable
* @property int|null $unsigned_medium_integer_nullable
* @property int $unsigned_medium_integer_not_nullable
* @property int|null $unsigned_big_integer_nullable
* @property int $unsigned_big_integer_not_nullable
* @property float|null $float_nullable
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
* @property string $enum_not_nullable
* @property string|null $json_nullable
* @property string $json_not_nullable
* @property string|null $jsonb_nullable
* @property string $jsonb_not_nullable
* @property string|null $date_nullable
* @property string $date_not_nullable
* @property string|null $datetime_nullable
* @property string $datetime_not_nullable
* @property string|null $datetimetz_nullable
* @property string $datetimetz_not_nullable
* @property string|null $time_nullable
* @property string $time_not_nullable
* @property string|null $timetz_nullable
* @property string $timetz_not_nullable
* @property string|null $timestamp_nullable
* @property string $timestamp_not_nullable
* @property string|null $timestamptz_nullable
* @property string $timestamptz_not_nullable
* @property int|null $year_nullable
* @property int $year_not_nullable
* @property string|null $binary_nullable
* @property string $binary_not_nullable
* @property string|null $uuid_nullable
* @property string $uuid_not_nullable
* @property string|null $ipaddress_nullable
* @property string $ipaddress_not_nullable
* @property string|null $macaddress_nullable
* @property string $macaddress_not_nullable
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGeneratePhpdocWithExternalEloquentBuilder\Builders\PostExternalQueryBuilder<static>|Post newModelQuery()
* @method static \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGeneratePhpdocWithExternalEloquentBuilder\Builders\PostExternalQueryBuilder<static>|Post newQuery()
* @method static \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGeneratePhpdocWithExternalEloquentBuilder\Builders\PostExternalQueryBuilder<static>|Post query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBigIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBigIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBinaryNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBinaryNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBooleanNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBooleanNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCharNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCharNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDateNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDateNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimeNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimeNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimetzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimetzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDecimalNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDecimalNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDoubleNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDoubleNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereEnumNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereEnumNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereFloatNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereFloatNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIpaddressNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIpaddressNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonbNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonbNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereLongTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereLongTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMacaddressNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMacaddressNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereSmallIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereSmallIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereStringNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereStringNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimeNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimeNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestampNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestampNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestamptzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestamptzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimetzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimetzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTinyIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTinyIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedBigIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedBigIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedMediumIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedMediumIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedSmallIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedSmallIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedTinyIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedTinyIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUuidNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUuidNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereYearNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereYearNullable($value)
*/
class Post extends \Eloquent {}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/DoesNotGeneratePhpdocWithExternalEloquentBuilder/Builders/PostExternalQueryBuilder.php | tests/Console/ModelsCommand/DoesNotGeneratePhpdocWithExternalEloquentBuilder/Builders/PostExternalQueryBuilder.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGeneratePhpdocWithExternalEloquentBuilder\Builders;
use Illuminate\Database\Eloquent\Builder;
class PostExternalQueryBuilder extends Builder
{
public function isActive(): self
{
return $this;
}
public function isStatus(string $status): self
{
return $this;
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/DoesNotGeneratePhpdocWithExternalEloquentBuilder/Models/Post.php | tests/Console/ModelsCommand/DoesNotGeneratePhpdocWithExternalEloquentBuilder/Models/Post.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGeneratePhpdocWithExternalEloquentBuilder\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGeneratePhpdocWithExternalEloquentBuilder\Builders\PostExternalQueryBuilder;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function newEloquentBuilder($query): PostExternalQueryBuilder
{
return new PostExternalQueryBuilder($query);
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Test.php | tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Casts/CastType.php | tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Casts/CastType.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn\Casts;
final class CastType
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/__snapshots__/Test__test__1.php | tests/Console/ModelsCommand/GeneratePhpdocWithFqn/__snapshots__/Test__test__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn\Casts\CastType;
use Eloquent;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property string|null $char_nullable
* @property CastType $char_not_nullable
* @property string|null $string_nullable
* @property string $string_not_nullable
* @property string|null $text_nullable
* @property string $text_not_nullable
* @property string|null $medium_text_nullable
* @property string $medium_text_not_nullable
* @property string|null $long_text_nullable
* @property string $long_text_not_nullable
* @property int|null $integer_nullable
* @property int $integer_not_nullable
* @property int|null $tiny_integer_nullable
* @property int $tiny_integer_not_nullable
* @property int|null $small_integer_nullable
* @property int $small_integer_not_nullable
* @property int|null $medium_integer_nullable
* @property int $medium_integer_not_nullable
* @property int|null $big_integer_nullable
* @property int $big_integer_not_nullable
* @property int|null $unsigned_integer_nullable
* @property int $unsigned_integer_not_nullable
* @property int|null $unsigned_tiny_integer_nullable
* @property int $unsigned_tiny_integer_not_nullable
* @property int|null $unsigned_small_integer_nullable
* @property int $unsigned_small_integer_not_nullable
* @property int|null $unsigned_medium_integer_nullable
* @property int $unsigned_medium_integer_not_nullable
* @property int|null $unsigned_big_integer_nullable
* @property int $unsigned_big_integer_not_nullable
* @property float|null $float_nullable
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
* @property string $enum_not_nullable
* @property string|null $json_nullable
* @property string $json_not_nullable
* @property string|null $jsonb_nullable
* @property string $jsonb_not_nullable
* @property string|null $date_nullable
* @property string $date_not_nullable
* @property string|null $datetime_nullable
* @property string $datetime_not_nullable
* @property string|null $datetimetz_nullable
* @property string $datetimetz_not_nullable
* @property string|null $time_nullable
* @property string $time_not_nullable
* @property string|null $timetz_nullable
* @property string $timetz_not_nullable
* @property string|null $timestamp_nullable
* @property string $timestamp_not_nullable
* @property string|null $timestamptz_nullable
* @property string $timestamptz_not_nullable
* @property int|null $year_nullable
* @property int $year_not_nullable
* @property string|null $binary_nullable
* @property string $binary_not_nullable
* @property string|null $uuid_nullable
* @property string $uuid_not_nullable
* @property string|null $ipaddress_nullable
* @property string $ipaddress_not_nullable
* @property string|null $macaddress_nullable
* @property string $macaddress_not_nullable
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Collection<int, Post> $posts
* @property-read int|null $posts_count
* @property-read bool|null $posts_exists
* @method static EloquentBuilder<static>|Post newModelQuery()
* @method static EloquentBuilder<static>|Post newQuery()
* @method static EloquentBuilder<static>|Post null(string $unusedParam)
* @method static EloquentBuilder<static>|Post onlyTrashed()
* @method static EloquentBuilder<static>|Post query()
* @method static EloquentBuilder<static>|Post whereBigIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereBigIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereBinaryNotNullable($value)
* @method static EloquentBuilder<static>|Post whereBinaryNullable($value)
* @method static EloquentBuilder<static>|Post whereBooleanNotNullable($value)
* @method static EloquentBuilder<static>|Post whereBooleanNullable($value)
* @method static EloquentBuilder<static>|Post whereCharNotNullable($value)
* @method static EloquentBuilder<static>|Post whereCharNullable($value)
* @method static EloquentBuilder<static>|Post whereCreatedAt($value)
* @method static EloquentBuilder<static>|Post whereDateNotNullable($value)
* @method static EloquentBuilder<static>|Post whereDateNullable($value)
* @method static EloquentBuilder<static>|Post whereDatetimeNotNullable($value)
* @method static EloquentBuilder<static>|Post whereDatetimeNullable($value)
* @method static EloquentBuilder<static>|Post whereDatetimetzNotNullable($value)
* @method static EloquentBuilder<static>|Post whereDatetimetzNullable($value)
* @method static EloquentBuilder<static>|Post whereDecimalNotNullable($value)
* @method static EloquentBuilder<static>|Post whereDecimalNullable($value)
* @method static EloquentBuilder<static>|Post whereDoubleNotNullable($value)
* @method static EloquentBuilder<static>|Post whereDoubleNullable($value)
* @method static EloquentBuilder<static>|Post whereEnumNotNullable($value)
* @method static EloquentBuilder<static>|Post whereEnumNullable($value)
* @method static EloquentBuilder<static>|Post whereFloatNotNullable($value)
* @method static EloquentBuilder<static>|Post whereFloatNullable($value)
* @method static EloquentBuilder<static>|Post whereId($value)
* @method static EloquentBuilder<static>|Post whereIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereIpaddressNotNullable($value)
* @method static EloquentBuilder<static>|Post whereIpaddressNullable($value)
* @method static EloquentBuilder<static>|Post whereJsonNotNullable($value)
* @method static EloquentBuilder<static>|Post whereJsonNullable($value)
* @method static EloquentBuilder<static>|Post whereJsonbNotNullable($value)
* @method static EloquentBuilder<static>|Post whereJsonbNullable($value)
* @method static EloquentBuilder<static>|Post whereLongTextNotNullable($value)
* @method static EloquentBuilder<static>|Post whereLongTextNullable($value)
* @method static EloquentBuilder<static>|Post whereMacaddressNotNullable($value)
* @method static EloquentBuilder<static>|Post whereMacaddressNullable($value)
* @method static EloquentBuilder<static>|Post whereMediumIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereMediumIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereMediumTextNotNullable($value)
* @method static EloquentBuilder<static>|Post whereMediumTextNullable($value)
* @method static EloquentBuilder<static>|Post whereSmallIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereSmallIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereStringNotNullable($value)
* @method static EloquentBuilder<static>|Post whereStringNullable($value)
* @method static EloquentBuilder<static>|Post whereTextNotNullable($value)
* @method static EloquentBuilder<static>|Post whereTextNullable($value)
* @method static EloquentBuilder<static>|Post whereTimeNotNullable($value)
* @method static EloquentBuilder<static>|Post whereTimeNullable($value)
* @method static EloquentBuilder<static>|Post whereTimestampNotNullable($value)
* @method static EloquentBuilder<static>|Post whereTimestampNullable($value)
* @method static EloquentBuilder<static>|Post whereTimestamptzNotNullable($value)
* @method static EloquentBuilder<static>|Post whereTimestamptzNullable($value)
* @method static EloquentBuilder<static>|Post whereTimetzNotNullable($value)
* @method static EloquentBuilder<static>|Post whereTimetzNullable($value)
* @method static EloquentBuilder<static>|Post whereTinyIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereTinyIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedBigIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedBigIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedMediumIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedMediumIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedSmallIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedSmallIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedTinyIntegerNotNullable($value)
* @method static EloquentBuilder<static>|Post whereUnsignedTinyIntegerNullable($value)
* @method static EloquentBuilder<static>|Post whereUpdatedAt($value)
* @method static EloquentBuilder<static>|Post whereUuidNotNullable($value)
* @method static EloquentBuilder<static>|Post whereUuidNullable($value)
* @method static EloquentBuilder<static>|Post whereYearNotNullable($value)
* @method static EloquentBuilder<static>|Post whereYearNullable($value)
* @method static EloquentBuilder<static>|Post withTrashed(bool $withTrashed = true)
* @method static EloquentBuilder<static>|Post withoutTrashed()
* @mixin Eloquent
*/
class Post extends Model
{
use SoftDeletes;
/**
* Special hack to avoid code style fixer removing unused imports
* which play a role when generating the snapshot
*/
private $hack = [
Carbon::class,
Collection::class,
Eloquent::class,
EloquentBuilder::class,
QueryBuilder::class,
];
protected $casts = [
'char_not_nullable' => CastType::class,
];
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
public function scopeNull($query, string $unusedParam)
{
return $query;
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Models/Post.php | tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Models/Post.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn\Models;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn\Casts\CastType;
use Eloquent;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Carbon;
class Post extends Model
{
use SoftDeletes;
/**
* Special hack to avoid code style fixer removing unused imports
* which play a role when generating the snapshot
*/
private $hack = [
Carbon::class,
Collection::class,
Eloquent::class,
EloquentBuilder::class,
QueryBuilder::class,
];
protected $casts = [
'char_not_nullable' => CastType::class,
];
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
public function scopeNull($query, string $unusedParam)
{
return $query;
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/CustomPhpdocTags/Test.php | tests/Console/ModelsCommand/CustomPhpdocTags/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\CustomPhpdocTags;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
/**
* This test makes sure that custom phpdoc tags are not mangled, e.g.
* there are no spaces inserted etc.
*
* @link https://github.com/barryvdh/laravel-ide-helper/issues/666
*/
public function testNoSpaceAfterCustomPhpdocTag(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/CustomPhpdocTags/__snapshots__/Test__testNoSpaceAfterCustomPhpdocTag__1.php | tests/Console/ModelsCommand/CustomPhpdocTags/__snapshots__/Test__testNoSpaceAfterCustomPhpdocTag__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\CustomPhpdocTags\Models;
use Illuminate\Database\Eloquent\Model;
/**
* The `@SuppressWarnings` tag below contains no space before the `(` but when
* the class phpdoc is written back, one is inserted.
*
* @link https://github.com/barryvdh/laravel-ide-helper/issues/666
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @property int $id
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple whereId($value)
* @mixin \Eloquent
*/
class Simple extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/CustomPhpdocTags/Models/Simple.php | tests/Console/ModelsCommand/CustomPhpdocTags/Models/Simple.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\CustomPhpdocTags\Models;
use Illuminate\Database\Eloquent\Model;
/**
* The `@SuppressWarnings` tag below contains no space before the `(` but when
* the class phpdoc is written back, one is inserted.
*
* @link https://github.com/barryvdh/laravel-ide-helper/issues/666
*
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class Simple extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/PHPStormNoInspection/Test.php | tests/Console/ModelsCommand/PHPStormNoInspection/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PHPStormNoInspection;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function testNoinspectionNotPresent(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
public function testNoinspectionPresent(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
'--phpstorm-noinspections' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/PHPStormNoInspection/__snapshots__/Test__testNoinspectionPresent__1.php | tests/Console/ModelsCommand/PHPStormNoInspection/__snapshots__/Test__testNoinspectionPresent__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PHPStormNoInspection\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple whereId($value)
* @mixin \Eloquent
* @noinspection PhpFullyQualifiedNameUsageInspection
* @noinspection PhpUnnecessaryFullyQualifiedNameInspection
*/
class Simple extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/PHPStormNoInspection/__snapshots__/Test__testNoinspectionNotPresent__1.php | tests/Console/ModelsCommand/PHPStormNoInspection/__snapshots__/Test__testNoinspectionNotPresent__1.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PHPStormNoInspection\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple whereId($value)
* @mixin \Eloquent
*/
class Simple extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/PHPStormNoInspection/Models/Simple.php | tests/Console/ModelsCommand/PHPStormNoInspection/Models/Simple.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PHPStormNoInspection\Models;
use Illuminate\Database\Eloquent\Model;
class Simple extends Model
{
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
barryvdh/laravel-ide-helper | https://github.com/barryvdh/laravel-ide-helper/blob/2ac73f2953f59e43b798e959a352e09305cb5320/tests/Console/ModelsCommand/QueryScopes/Test.php | tests/Console/ModelsCommand/QueryScopes/Test.php | <?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\QueryScopes;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
| php | MIT | 2ac73f2953f59e43b798e959a352e09305cb5320 | 2026-01-04T15:02:42.026190Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.