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 |
|---|---|---|---|---|---|---|---|---|
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/DotAtStart.php | src/Result/Reason/DotAtStart.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class DotAtStart implements Reason
{
public function code() : int
{
return 141;
}
public function description() : string
{
return "Starts with a DOT";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/Reason.php | src/Result/Reason/Reason.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
interface Reason
{
/**
* Code for user land to act upon;
*/
public function code() : int;
/**
* Short description of the result, human readable.
*/
public function description() : string;
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/DomainAcceptsNoMail.php | src/Result/Reason/DomainAcceptsNoMail.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class DomainAcceptsNoMail implements Reason
{
public function code() : int
{
return 154;
}
public function description() : string
{
return 'Domain accepts no mail (Null MX, RFC7505)';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/ExpectingCTEXT.php | src/Result/Reason/ExpectingCTEXT.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class ExpectingCTEXT implements Reason
{
public function code() : int
{
return 139;
}
public function description() : string
{
return 'Expecting CTEXT';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/CommaInDomain.php | src/Result/Reason/CommaInDomain.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class CommaInDomain implements Reason
{
public function code() : int
{
return 200;
}
public function description() : string
{
return "Comma ',' is not allowed in domain part";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/LocalOrReservedDomain.php | src/Result/Reason/LocalOrReservedDomain.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class LocalOrReservedDomain implements Reason
{
public function code() : int
{
return 153;
}
public function description() : string
{
return 'Local, mDNS or reserved domain (RFC2606, RFC6762)';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/CommentsInIDRight.php | src/Result/Reason/CommentsInIDRight.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class CommentsInIDRight implements Reason
{
public function code() : int
{
return 400;
}
public function description() : string
{
return 'Comments are not allowed in IDRight for message-id';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/ExceptionFound.php | src/Result/Reason/ExceptionFound.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class ExceptionFound implements Reason
{
/**
* @var \Exception
*/
private $exception;
public function __construct(\Exception $exception)
{
$this->exception = $exception;
}
public function code() : int
{
return 999;
}
public function description() : string
{
return $this->exception->getMessage();
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/SpoofEmail.php | src/Result/Reason/SpoofEmail.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class SpoofEmail implements Reason
{
public function code() : int
{
return 298;
}
public function description() : string
{
return 'The email contains mixed UTF8 chars that makes it suspicious';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/UnusualElements.php | src/Result/Reason/UnusualElements.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class UnusualElements implements Reason
{
/**
* @var string $element
*/
private $element;
public function __construct(string $element)
{
$this->element = $element;
}
public function code() : int
{
return 201;
}
public function description() : string
{
return 'Unusual element found, wourld render invalid in majority of cases. Element found: ' . $this->element;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/ExpectingDomainLiteralClose.php | src/Result/Reason/ExpectingDomainLiteralClose.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class ExpectingDomainLiteralClose implements Reason
{
public function code() : int
{
return 137;
}
public function description() : string
{
return "Closing bracket ']' for domain literal not found";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/UnOpenedComment.php | src/Result/Reason/UnOpenedComment.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class UnOpenedComment implements Reason
{
public function code() : int
{
return 152;
}
public function description(): string
{
return 'Missing opening comment parentheses - https://tools.ietf.org/html/rfc5322#section-3.2.2';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/DetailedReason.php | src/Result/Reason/DetailedReason.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
abstract class DetailedReason implements Reason
{
protected $detailedDescription;
public function __construct(string $details)
{
$this->detailedDescription = $details;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/UnableToGetDNSRecord.php | src/Result/Reason/UnableToGetDNSRecord.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
/**
* Used on SERVFAIL, TIMEOUT or other runtime and network errors
*/
class UnableToGetDNSRecord extends NoDNSRecord
{
public function code() : int
{
return 3;
}
public function description() : string
{
return 'Unable to get DNS records for the host';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/UnclosedQuotedString.php | src/Result/Reason/UnclosedQuotedString.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class UnclosedQuotedString implements Reason
{
public function code() : int
{
return 145;
}
public function description() : string
{
return "Unclosed quoted string";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/CRNoLF.php | src/Result/Reason/CRNoLF.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class CRNoLF implements Reason
{
public function code() : int
{
return 150;
}
public function description() : string
{
return 'Missing LF after CR';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/LabelTooLong.php | src/Result/Reason/LabelTooLong.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class LabelTooLong implements Reason
{
public function code() : int
{
return 245;
}
public function description() : string
{
return 'Domain "label" is longer than 63 characters';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/EmailLexerTest.php | tests/EmailValidator/EmailLexerTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator;
use Egulias\EmailValidator\EmailLexer;
use PHPUnit\Framework\TestCase;
class EmailLexerTest extends TestCase
{
public function testLexerExtendsLib()
{
$lexer = new EmailLexer();
$this->assertInstanceOf('Doctrine\Common\Lexer\AbstractLexer', $lexer);
}
/**
* @dataProvider getTokens
*
*/
public function testLexerTokens($str, $token)
{
$lexer = new EmailLexer();
$lexer->setInput($str);
$lexer->moveNext();
$lexer->moveNext();
$this->assertEquals($token, $lexer->current->type);
}
public function testLexerParsesMultipleSpaces()
{
$lexer = new EmailLexer();
$lexer->setInput(' ');
$lexer->moveNext();
$lexer->moveNext();
$this->assertEquals(EmailLexer::S_SP, $lexer->current->type);
$lexer->moveNext();
$this->assertEquals(EmailLexer::S_SP, $lexer->current->type);
}
/**
* @dataProvider invalidUTF8CharsProvider
*/
public function testLexerParsesInvalidUTF8($char)
{
$lexer = new EmailLexer();
$lexer->setInput($char);
$lexer->moveNext();
$lexer->moveNext();
$this->assertEquals(EmailLexer::INVALID, $lexer->current->type);
}
public static function invalidUTF8CharsProvider()
{
$chars = array();
for ($i = 0; $i < 0x100; ++$i) {
$c = self::utf8Chr($i);
if (preg_match('/(?=\p{Cc})(?=[^\t\n\n\r])/u', $c) && !preg_match('/\x{0000}/u', $c)) {
$chars[] = array($c);
}
}
return $chars;
}
protected static function utf8Chr($code_point)
{
if ($code_point < 0 || 0x10FFFF < $code_point || (0xD800 <= $code_point && $code_point <= 0xDFFF)) {
return '';
}
if ($code_point < 0x80) {
$hex[0] = $code_point;
$ret = chr($hex[0]);
} elseif ($code_point < 0x800) {
$hex[0] = 0x1C0 | $code_point >> 6;
$hex[1] = 0x80 | $code_point & 0x3F;
$ret = chr($hex[0]) . chr($hex[1]);
} elseif ($code_point < 0x10000) {
$hex[0] = 0xE0 | $code_point >> 12;
$hex[1] = 0x80 | $code_point >> 6 & 0x3F;
$hex[2] = 0x80 | $code_point & 0x3F;
$ret = chr($hex[0]) . chr($hex[1]) . chr($hex[2]);
} else {
$hex[0] = 0xF0 | $code_point >> 18;
$hex[1] = 0x80 | $code_point >> 12 & 0x3F;
$hex[2] = 0x80 | $code_point >> 6 & 0x3F;
$hex[3] = 0x80 | $code_point & 0x3F;
$ret = chr($hex[0]) . chr($hex[1]) . chr($hex[2]) . chr($hex[3]);
}
return $ret;
}
public function testLexerForTab()
{
$lexer = new EmailLexer();
$lexer->setInput("foo\tbar");
$lexer->moveNext();
$lexer->skipUntil(EmailLexer::S_HTAB);
$lexer->moveNext();
$this->assertEquals(EmailLexer::S_HTAB, $lexer->current->type);
}
public function testLexerForUTF8()
{
$lexer = new EmailLexer();
$lexer->setInput("áÇ@bar.com");
$lexer->moveNext();
$lexer->moveNext();
$this->assertEquals(EmailLexer::GENERIC, $lexer->current->type);
$lexer->moveNext();
$this->assertEquals(EmailLexer::GENERIC, $lexer->current->type);
}
public function testLexerSearchToken()
{
$lexer = new EmailLexer();
$lexer->setInput("foo\tbar");
$lexer->moveNext();
$this->assertTrue($lexer->find(EmailLexer::S_HTAB));
}
public static function getTokens()
{
return array(
array("foo", EmailLexer::GENERIC),
array("\r", EmailLexer::S_CR),
array("\t", EmailLexer::S_HTAB),
array("\r\n", EmailLexer::CRLF),
array("\n", EmailLexer::S_LF),
array(" ", EmailLexer::S_SP),
array("@", EmailLexer::S_AT),
array("IPv6", EmailLexer::S_IPV6TAG),
array("::", EmailLexer::S_DOUBLECOLON),
array(":", EmailLexer::S_COLON),
array(".", EmailLexer::S_DOT),
array("\"", EmailLexer::S_DQUOTE),
array("`", EmailLexer::S_BACKTICK),
array("'", EmailLexer::S_SQUOTE),
array("-", EmailLexer::S_HYPHEN),
array("\\", EmailLexer::S_BACKSLASH),
array("/", EmailLexer::S_SLASH),
array("(", EmailLexer::S_OPENPARENTHESIS),
array(")", EmailLexer::S_CLOSEPARENTHESIS),
array('<', EmailLexer::S_LOWERTHAN),
array('>', EmailLexer::S_GREATERTHAN),
array('[', EmailLexer::S_OPENBRACKET),
array(']', EmailLexer::S_CLOSEBRACKET),
array(';', EmailLexer::S_SEMICOLON),
array(',', EmailLexer::S_COMMA),
array('<', EmailLexer::S_LOWERTHAN),
array('>', EmailLexer::S_GREATERTHAN),
array('{', EmailLexer::S_OPENCURLYBRACES),
array('}', EmailLexer::S_CLOSECURLYBRACES),
array('|', EmailLexer::S_PIPE),
array('~', EmailLexer::S_TILDE),
array('=', EmailLexer::S_EQUAL),
array('+', EmailLexer::S_PLUS),
array('¿', EmailLexer::INVERT_QUESTIONMARK),
array('?', EmailLexer::QUESTIONMARK),
array('#', EmailLexer::NUMBER_SIGN),
array('¡', EmailLexer::INVERT_EXCLAMATION),
array('_', EmailLexer::S_UNDERSCORE),
array('', EmailLexer::S_EMPTY),
array(chr(31), EmailLexer::INVALID),
array(chr(226), EmailLexer::GENERIC),
array(chr(0), EmailLexer::C_NUL)
);
}
public function testRecordIsOffAtStart()
{
$lexer = new EmailLexer();
$lexer->setInput('foo-bar');
$lexer->moveNext();
$this->assertEquals('', $lexer->getAccumulatedValues());
}
public function testRecord()
{
$lexer = new EmailLexer();
$lexer->setInput('foo-bar');
$lexer->startRecording();
$lexer->moveNext();
$lexer->moveNext();
$this->assertEquals('foo', $lexer->getAccumulatedValues());
}
public function testRecordAndClear()
{
$lexer = new EmailLexer();
$lexer->setInput('foo-bar');
$lexer->startRecording();
$lexer->moveNext();
$lexer->moveNext();
$lexer->clearRecorded();
$this->assertEquals('', $lexer->getAccumulatedValues());
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/LexerTokensTest.php | tests/EmailValidator/LexerTokensTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator;
use PHPUnit\Framework\TestCase;
class LexerTokensTest extends TestCase
{
public function testToken()
{
$this->markTestIncomplete("implement better lexer tokens");
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/EmailValidatorTest.php | tests/EmailValidator/EmailValidatorTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator;
use PHPUnit\Framework\TestCase;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Tests\EmailValidator\Dummy\DummyReason;
use Egulias\EmailValidator\Validation\EmailValidation;
use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
class EmailValidatorTest extends TestCase
{
public function testValidationIsUsed()
{
$invalidEmail = new InvalidEmail(new DummyReason(), '');
$validator = new EmailValidator();
$validation = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation->expects($this->once())->method("isValid")->willReturn(true);
$validation->expects($this->once())->method("getWarnings")->willReturn([]);
$validation->expects($this->once())->method("getError")->willReturn($invalidEmail);
$this->assertTrue($validator->isValid("example@example.com", $validation));
}
public function testMultipleValidation()
{
$validator = new EmailValidator();
$validation = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation->expects($this->once())->method("isValid")->willReturn(true);
$validation->expects($this->once())->method("getWarnings")->willReturn([]);
$validation->expects($this->never(2))->method("getError");
$multiple = new MultipleValidationWithAnd([$validation]);
$this->assertTrue($validator->isValid("example@example.com", $multiple));
}
public function testValidationIsFalse()
{
$invalidEmail = new InvalidEmail(new DummyReason(), '');
$validator = new EmailValidator();
$validation = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation->expects($this->once())->method("isValid")->willReturn(false);
$validation->expects($this->once())->method("getWarnings")->willReturn([]);
$validation->expects($this->once())->method("getError")->willReturn($invalidEmail);
$this->assertFalse($validator->isValid("example@example.com", $validation));
$this->assertEquals(false, $validator->hasWarnings());
$this->assertEquals([], $validator->getWarnings());
$this->assertEquals($invalidEmail, $validator->getError());
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/EmailParserTest.php | tests/EmailValidator/EmailParserTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\EmailParser;
use PHPUnit\Framework\TestCase;
class EmailParserTest extends TestCase
{
public static function emailPartsProvider()
{
return [
['test@foo.com', 'test', 'foo.com'],
['"user@name"@example.com', '"user@name"', 'example.com'],
['validipv6@[IPv6:2001:db8:1ff::a0b:dbd0]', 'validipv6', '[IPv6:2001:db8:1ff::a0b:dbd0]'],
['validipv4@[127.0.0.0]', 'validipv4', '[127.0.0.0]']
];
}
/**
* @dataProvider emailPartsProvider
*/
public function testGetParts($email, $local, $domain)
{
$parser = new EmailParser(new EmailLexer());
$parser->parse($email);
$this->assertEquals($local, $parser->getLocalPart());
$this->assertEquals($domain, $parser->getDomainPart());
}
public function testMultipleEmailAddresses()
{
$parser = new EmailParser(new EmailLexer());
$parser->parse('some-local-part@some-random-but-large-domain-part.example.com');
$this->assertSame('some-local-part', $parser->getLocalPart());
$this->assertSame('some-random-but-large-domain-part.example.com', $parser->getDomainPart());
$parser->parse('another-local-part@another.example.com');
$this->assertSame('another-local-part', $parser->getLocalPart());
$this->assertSame('another.example.com', $parser->getDomainPart());
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Validation/MessageIDValidationTest.php | tests/EmailValidator/Validation/MessageIDValidationTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Validation\MessageIDValidation;
use PHPUnit\Framework\TestCase;
class MessageIDValidationTest extends TestCase
{
/**
* @dataProvider validMessageIDs
*/
public function testValidMessageIDs(string $messageID)
{
$validator = new MessageIDValidation();
$this->assertTrue($validator->isValid($messageID, new EmailLexer()));
}
public static function validMessageIDs() : array
{
return [
['a@b.c+&%$.d'],
['a.b+&%$.c@d'],
['a@ä'],
];
}
/**
* @dataProvider invalidMessageIDs
*/
public function testInvalidMessageIDs(string $messageID)
{
$validator = new MessageIDValidation();
$this->assertFalse($validator->isValid($messageID, new EmailLexer()));
}
public static function invalidMessageIDs() : array
{
return [
['example'],
['example@with space'],
['example@iana.'],
['example@ia\na.'],
/**
* RFC 2822, section 3.6.4, Page 25
* Since the msg-id has
* a similar syntax to angle-addr (identical except that comments and
* folding white space are not allowed), a good method is to put the
* domain name (or a domain literal IP address) of the host on which the
* message identifier was created on the right hand side of the "@", and
* put a combination of the current absolute date and time along with
* some other currently unique (perhaps sequential) identifier available
* on the system (for example, a process id number) on the left hand
* side.
*/
['example(comment)@example.com'],
["\r\nFWS@example.com"]
];
}
public function testInvalidMessageIDsWithError()
{
$this->markTestIncomplete("missing error check");
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Validation/NoRFCWarningsValidationTest.php | tests/EmailValidator/Validation/NoRFCWarningsValidationTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Reason\NoDomainPart;
use Egulias\EmailValidator\Result\Reason\RFCWarnings;
use Egulias\EmailValidator\Validation\NoRFCWarningsValidation;
use PHPUnit\Framework\TestCase;
class NoRFCWarningsValidationTest extends TestCase
{
public function testInvalidEmailIsInvalid()
{
$validation = new NoRFCWarningsValidation();
$this->assertFalse($validation->isValid('non-email-string', new EmailLexer()));
$this->assertInstanceOf(NoDomainPart::class, $validation->getError()->reason());
}
public function testEmailWithWarningsIsInvalid()
{
$validation = new NoRFCWarningsValidation();
$this->assertFalse($validation->isValid('test()@example.com', new EmailLexer()));
$this->assertInstanceOf(RFCWarnings::class, $validation->getError()->reason());
}
/**
* @dataProvider getValidEmailsWithoutWarnings
*/
public function testEmailWithoutWarningsIsValid($email)
{
$validation = new NoRFCWarningsValidation();
$this->assertTrue($validation->isValid('example@example.com', new EmailLexer()));
$this->assertTrue($validation->isValid($email, new EmailLexer()));
$this->assertNull($validation->getError());
}
public static function getValidEmailsWithoutWarnings()
{
return [
['example@example.com',],
[sprintf('example@%s.com', str_repeat('ъ', 40)),],
];
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Validation/RFCValidationTest.php | tests/EmailValidator/Validation/RFCValidationTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;
use PHPUnit\Framework\TestCase;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Warning\Comment;
use Egulias\EmailValidator\Warning\CFWSNearAt;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Warning\LocalTooLong;
use Egulias\EmailValidator\Warning\QuotedString;
use Egulias\EmailValidator\Validation\RFCValidation;
use Egulias\EmailValidator\Result\Reason\NoLocalPart;
use Egulias\EmailValidator\Result\Reason\AtextAfterCFWS;
use Egulias\EmailValidator\Result\Reason\UnOpenedComment;
use Egulias\EmailValidator\Result\Reason\UnclosedQuotedString;
use Egulias\EmailValidator\Result\Reason\CRNoLF;
use Egulias\EmailValidator\Result\Reason\DotAtEnd;
use Egulias\EmailValidator\Result\Reason\DotAtStart;
use Egulias\EmailValidator\Result\Reason\ConsecutiveDot;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Result\Reason\UnclosedComment;
use Egulias\EmailValidator\Warning\TLD;
class RFCValidationTest extends TestCase
{
/**
* @var RFCValidation
*/
protected $validator;
/**
* @var EmailLexer
*/
protected $lexer;
protected function setUp() : void
{
$this->validator = new RFCValidation();
$this->lexer = new EmailLexer();
}
protected function tearDown() : void
{
$this->validator = null;
}
/**
* @dataProvider getValidEmails
*/
public function testValidEmails($email)
{
$this->assertTrue($this->validator->isValid($email, $this->lexer));
}
public static function getValidEmails()
{
return array(
['â@iana.org'],
['fabien@symfony.com'],
['example@example.co.uk'],
['fabien_potencier@example.fr'],
['fab\'ien@symfony.com'],
['fab\ ien@symfony.com'],
['example((example))@fakedfake.co.uk'],
['fabien+a@symfony.com'],
['exampl=e@example.com'],
['инфо@письмо.рф'],
['"username"@example.com'],
['"user,name"@example.com'],
['"user name"@example.com'],
['"user@name"@example.com'],
['"user\"name"@example.com'],
['"\a"@iana.org'],
['"test\ test"@iana.org'],
['""@iana.org'],
['"\""@iana.org'],
['müller@möller.de'],
["1500111@профи-инвест.рф"],
[sprintf('example@%s.com', str_repeat('ъ', 40))],
);
}
/**
* @dataProvider getValidEmailsWithWarnings
*/
public function testValidEmailsWithWarningsCheck($email, $expectedWarnings)
{
$this->assertTrue($this->validator->isValid($email, $this->lexer));
$this->assertEquals($expectedWarnings, $this->validator->getWarnings());
}
public static function getValidEmailsWithWarnings()
{
return [
['a5aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@example.com', [new LocalTooLong()]],
['example@example', [new TLD()]],
['example @invalid.example.com', [new CFWSNearAt()]],
['example(examplecomment)@invalid.example.com',[new Comment(), new CFWSNearAt()]],
["\"\t\"@invalid.example.com", [new QuotedString("", '"'), new CFWSWithFWS(),]],
["\"\r\"@invalid.example.com", [new QuotedString('', '"'), new CFWSWithFWS(),]],
['"example"@invalid.example.com', [new QuotedString('', '"')]],
['too_long_localpart_too_long_localpart_too_long_localpart_too_long_localpart@invalid.example.com',
[new LocalTooLong()]],
];
}
public function testInvalidUTF8Email()
{
$email = "\x80\x81\x82@\x83\x84\x85.\x86\x87\x88";
$this->assertFalse($this->validator->isValid($email, $this->lexer));
}
/**
* @dataProvider getInvalidEmails
*/
public function testInvalidEmails($email)
{
$this->assertFalse($this->validator->isValid($email, $this->lexer));
}
public static function getInvalidEmails()
{
return [
['user name@example.com'],
['user name@example.com'],
['example.@example.co.uk'],
['example@example@example.co.uk'],
['(test_exampel@example.fr'],
['example(example]example@example.co.uk'],
['.example@localhost'],
['ex\ample@localhost'],
['user name@example.com'],
['usern,ame@example.com'],
['user[na]me@example.com'],
['"""@iana.org'],
['"\"@iana.org'],
['"test"test@iana.org'],
['"test""test"@iana.org'],
['"test"."test"@iana.org'],
['"test".test@iana.org'],
['"test"' . chr(0) . '@iana.org'],
['"test\"@iana.org'],
[chr(226) . '@iana.org'],
['\r\ntest@iana.org'],
['\r\n test@iana.org'],
['\r\n \r\ntest@iana.org'],
['\r\n \r\ntest@iana.org'],
['\r\n \r\n test@iana.org'],
['test;123@foobar.com'],
['examp║le@symfony.com'],
['example@invalid-.domain.com'],
['example@-invalid.com'],
['0'],
[0],
];
}
/**
* @dataProvider getInvalidEmailsWithErrors
*/
public function testInvalidDEmailsWithErrorsCheck($error, $email)
{
$this->assertFalse($this->validator->isValid($email, $this->lexer));
$this->assertEquals($error, $this->validator->getError());
}
public static function getInvalidEmailsWithErrors()
{
return [
[new InvalidEmail(new NoLocalPart(), "@"), '@example.co.uk'],
[new InvalidEmail(new ConsecutiveDot(), '.'), 'example..example@example.co.uk'],
[new InvalidEmail(new ExpectingATEXT('Invalid token found'), '<'), '<example_example>@example.fr'],
[new InvalidEmail(new DotAtStart(), '.'), '.example@localhost'],
[new InvalidEmail(new DotAtEnd(), '.'), 'example.@example.co.uk'],
[new InvalidEmail(new UnclosedComment(), '('), '(example@localhost'],
[new InvalidEmail(new UnclosedQuotedString(), '"'), '"example@localhost'],
[
new InvalidEmail(
new ExpectingATEXT('https://tools.ietf.org/html/rfc5322#section-3.2.4 - quoted string should be a unit'),
'"'),
'exa"mple@localhost'
],
[new InvalidEmail(new UnOpenedComment(), ')'), 'comment)example@localhost'],
[new InvalidEmail(new UnOpenedComment(), ')'), 'example(comment))@localhost'],
[new InvalidEmail(new AtextAfterCFWS(), "\n"), "exampl\ne@example.co.uk"],
[new InvalidEmail(new AtextAfterCFWS(), "\t"), "exampl\te@example.co.uk"],
[new InvalidEmail(new CRNoLF(), "\r"), "exam\rple@example.co.uk"],
];
}
} | php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Validation/MultipleValidationWithAndTest.php | tests/EmailValidator/Validation/MultipleValidationWithAndTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;
use PHPUnit\Framework\TestCase;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\MultipleErrors;
use Egulias\EmailValidator\Tests\EmailValidator\Dummy\AnotherDummyReason;
use Egulias\EmailValidator\Warning\DomainLiteral;
use Egulias\EmailValidator\Warning\AddressLiteral;
use Egulias\EmailValidator\Validation\RFCValidation;
use Egulias\EmailValidator\Validation\EmailValidation;
use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
use Egulias\EmailValidator\Tests\EmailValidator\Dummy\DummyReason;
use Egulias\EmailValidator\Validation\Exception\EmptyValidationList;
class MultipleValidationWithAndTest extends TestCase
{
public function testUsesAndLogicalOperation()
{
$invalidEmail = new InvalidEmail(new DummyReason(), '');
$lexer = new EmailLexer();
$validationTrue = $this->getMockBuilder(EmailValidation::class)->getMock();
$validationTrue->expects($this->any())->method("isValid")->willReturn(true);
$validationTrue->expects($this->any())->method("getWarnings")->willReturn([]);
$validationFalse = $this->getMockBuilder(EmailValidation::class)->getMock();
$validationFalse->expects($this->any())->method("isValid")->willReturn(false);
$validationFalse->expects($this->any())->method("getWarnings")->willReturn([]);
$validationFalse->expects($this->any())->method("getError")->willReturn($invalidEmail);
$multipleValidation = new MultipleValidationWithAnd([$validationTrue, $validationFalse]);
$this->assertFalse($multipleValidation->isValid("exmpale@example.com", $lexer));
}
public function testEmptyListIsNotAllowed()
{
$this->expectException(EmptyValidationList::class);
new MultipleValidationWithAnd([]);
}
public function testValidationIsValid()
{
$lexer = new EmailLexer();
$validation = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation->expects($this->any())->method("isValid")->willReturn(true);
$validation->expects($this->once())->method("getWarnings")->willReturn([]);
$validation->expects($this->any())->method("getError")->willReturn(null);
$multipleValidation = new MultipleValidationWithAnd([$validation]);
$this->assertTrue($multipleValidation->isValid("example@example.com", $lexer));
$this->assertNull($multipleValidation->getError());
}
public function testAccumulatesWarnings()
{
$invalidEmail = new InvalidEmail(new DummyReason(), '');
$warnings1 = [
AddressLiteral::CODE => new AddressLiteral()
];
$warnings2 = [
DomainLiteral::CODE => new DomainLiteral()
];
$expectedResult = array_merge($warnings1, $warnings2);
$lexer = new EmailLexer();
$validation1 = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation1->expects($this->any())->method("isValid")->willReturn(true);
$validation1->expects($this->once())->method("getWarnings")->willReturn($warnings1);
$validation1->expects($this->any())->method("getError")->willReturn($invalidEmail);
$validation2 = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation2->expects($this->any())->method("isValid")->willReturn(false);
$validation2->expects($this->once())->method("getWarnings")->willReturn($warnings2);
$validation2->expects($this->any())->method("getError")->willReturn($invalidEmail);
$multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2]);
$multipleValidation->isValid("example@example.com", $lexer);
$this->assertEquals($expectedResult, $multipleValidation->getWarnings());
}
public function testGathersAllTheErrors()
{
$invalidEmail = new InvalidEmail(new DummyReason(), '');
$invalidEmail2 = new InvalidEmail(new AnotherDummyReason(), '');
$error1 = new DummyReason();
$error2 = new AnotherDummyReason();
$expectedResult = new MultipleErrors();
$expectedResult->addReason($error1);
$expectedResult->addReason($error2);
$lexer = new EmailLexer();
$validation1 = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation1->expects($this->once())->method("isValid")->willReturn(false);
$validation1->expects($this->once())->method("getWarnings")->willReturn([]);
$validation1->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail);
$validation2 = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation2->expects($this->once())->method("isValid")->willReturn(false);
$validation2->expects($this->once())->method("getWarnings")->willReturn([]);
$validation2->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail2);
$multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2]);
$multipleValidation->isValid("example@example.com", $lexer);
$this->assertEquals($expectedResult, $multipleValidation->getError());
}
public function testStopsAfterFirstError()
{
$invalidEmail = new InvalidEmail(new DummyReason(), '');
$invalidEmail2 = new InvalidEmail(new AnotherDummyReason(), '');
$error1 = new DummyReason();
$expectedResult = new MultipleErrors();
$expectedResult->addReason($error1);
$lexer = new EmailLexer();
$validation1 = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation1->expects($this->any())->method("isValid")->willReturn(false);
$validation1->expects($this->once())->method("getWarnings")->willReturn([]);
$validation1->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail);
$validation2 = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation2->expects($this->any())->method("isValid")->willReturn(false);
$validation2->expects($this->never())->method("getWarnings")->willReturn([]);
$validation1->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail2);
$multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2], MultipleValidationWithAnd::STOP_ON_ERROR);
$multipleValidation->isValid("example@example.com", $lexer);
$this->assertEquals($expectedResult, $multipleValidation->getError());
}
public function testBreakOutOfLoopWhenError()
{
$invalidEmail = new InvalidEmail(new DummyReason(), '');
$error1 = new DummyReason();
$expectedResult = new MultipleErrors();
$expectedResult->addReason($error1);
$lexer = new EmailLexer();
$validation1 = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation1->expects($this->any())->method("isValid")->willReturn(false);
$validation1->expects($this->once())->method("getWarnings")->willReturn([]);
$validation1->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail);
$validation2 = $this->getMockBuilder(EmailValidation::class)->getMock();
$validation2->expects($this->never())->method("isValid");
$validation2->expects($this->never())->method("getWarnings");
$validation2->expects($this->never())->method("getError");
$multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2], MultipleValidationWithAnd::STOP_ON_ERROR);
$multipleValidation->isValid("example@example.com", $lexer);
$this->assertEquals($expectedResult, $multipleValidation->getError());
}
public function testBreakoutOnInvalidEmail()
{
$lexer = new EmailLexer();
$validationNotCalled = $this->getMockBuilder(EmailValidation::class)->getMock();
$validationNotCalled->expects($this->never())->method("isValid");
$validationNotCalled->expects($this->never())->method("getWarnings");
$validationNotCalled->expects($this->never())->method("getError");
$multipleValidation = new MultipleValidationWithAnd([new RFCValidation(), $validationNotCalled], MultipleValidationWithAnd::STOP_ON_ERROR);
$this->assertFalse($multipleValidation->isValid("invalid-email", $lexer));
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Validation/RFCValidationDomainPartTest.php | tests/EmailValidator/Validation/RFCValidationDomainPartTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;
use PHPUnit\Framework\TestCase;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Warning\TLD;
use Egulias\EmailValidator\Warning\Comment;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\IPV6BadChar;
use Egulias\EmailValidator\Result\Reason\CRNoLF;
use Egulias\EmailValidator\Warning\IPV6ColonEnd;
use Egulias\EmailValidator\Warning\DomainLiteral;
use Egulias\EmailValidator\Warning\IPV6MaxGroups;
use Egulias\EmailValidator\Warning\ObsoleteDTEXT;
use Egulias\EmailValidator\Result\Reason\DotAtEnd;
use Egulias\EmailValidator\Warning\AddressLiteral;
use Egulias\EmailValidator\Warning\IPV6ColonStart;
use Egulias\EmailValidator\Warning\IPV6Deprecated;
use Egulias\EmailValidator\Warning\IPV6GroupCount;
use Egulias\EmailValidator\Warning\IPV6DoubleColon;
use Egulias\EmailValidator\Result\Reason\DotAtStart;
use Egulias\EmailValidator\Validation\RFCValidation;
use Egulias\EmailValidator\Result\Reason\LabelTooLong;
use Egulias\EmailValidator\Result\Reason\NoDomainPart;
use Egulias\EmailValidator\Result\Reason\ConsecutiveAt;
use Egulias\EmailValidator\Result\Reason\ConsecutiveDot;
use Egulias\EmailValidator\Result\Reason\DomainHyphened;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Result\Reason\ExpectingDTEXT;
use Egulias\EmailValidator\Result\Reason\UnOpenedComment;
class RFCValidationDomainPartTest extends TestCase
{
/**
* @var RFCValidation
*/
protected $validator;
/**
* @var EmailLexer
*/
protected $lexer;
protected function setUp() : void
{
$this->validator = new RFCValidation();
$this->lexer = new EmailLexer();
}
protected function tearDown() : void
{
$this->validator = null;
}
/**
* @dataProvider getValidEmails
*/
public function testValidEmails($email)
{
$this->assertTrue($this->validator->isValid($email, $this->lexer));
}
public static function getValidEmails()
{
return array(
['fabien@symfony.com'],
['example@example.co.uk'],
['example@localhost'],
['example@faked(fake).co.uk'],
['инфо@письмо.рф'],
['müller@möller.de'],
["1500111@профи-инвест.рф"],
['validipv6@[IPv6:2001:db8:1ff::a0b:dbd0]'],
['validipv4@[127.0.0.0]'],
['validipv4@127.0.0.0'],
['withhyphen@domain-exam.com'],
['valid_long_domain@71846jnrsoj91yfhc18rkbrf90ue3onl8y46js38kae8inz0t1.5a-xdycuau.na49.le.example.com']
);
}
/**
* @dataProvider getInvalidEmails
*/
public function testInvalidEmails($email)
{
$this->assertFalse($this->validator->isValid($email, $this->lexer));
}
public static function getInvalidEmails()
{
return [
['test@example.com test'],
['example@example@example.co.uk'],
['test_exampel@example.fr]'],
['example@local\host'],
['example@localhost\\'],
['example@localhost.'],
['username@ example . com'],
['username@ example.com'],
['example@(fake].com'],
['example@(fake.com'],
['username@example,com'],
['test@' . chr(226) . '.org'],
['test@iana.org \r\n'],
['test@iana.org \r\n '],
['test@iana.org \r\n \r\n'],
['test@iana.org \r\n\r\n'],
['test@iana.org \r\n\r\n '],
['test@iana/icann.org'],
['test@foo;bar.com'],
['test@example..com'],
["test@examp'le.com"],
['email.email@email."'],
['test@email>'],
['test@email<'],
['test@email{'],
['username@examp,le.com'],
['test@ '],
['invalidipv4@[127.\0.0.0]'],
['test@example.com []'],
['test@example.com. []'],
['test@test. example.com'],
['example@toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocal'.
'parttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpart'.
'toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpar'],
['example@toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpart.co.uk'],
['example@toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpart.test.co.uk'],
['example@test.toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpart.co.uk'],
['test@email*a.com'],
['test@email!a.com'],
['test@email&a.com'],
['test@email^a.com'],
['test@email%a.com'],
['test@email$a.com'],
['test@email`a.com'],
['test@email|a.com'],
['test@email~a.com'],
['test@email{a.com'],
['test@email}a.com'],
['test@email=a.com'],
['test@email+a.com'],
['test@email_a.com'],
['test@email¡a.com'],
['test@email?a.com'],
['test@email#a.com'],
['test@email¨a.com'],
['test@email€a.com'],
['test@email$a.com'],
['test@email£a.com'],
];
}
/**
* @dataProvider getInvalidEmailsWithErrors
*/
public function testInvalidEmailsWithErrorsCheck($error, $email)
{
$this->assertFalse($this->validator->isValid($email, $this->lexer));
$this->assertEquals($error, $this->validator->getError());
}
public static function getInvalidEmailsWithErrors()
{
return [
[new InvalidEmail(new NoDomainPart(), ''), 'example@'],
[new InvalidEmail(new DomainHyphened('Hypen found near DOT'), '-'), 'example@example-.co.uk'], [new InvalidEmail(new CRNoLF(), "\r"), "example@example\r.com"],
[new InvalidEmail(new DomainHyphened('Hypen found at the end of the domain'), '-'), 'example@example-'],
[new InvalidEmail(new ConsecutiveAt(), '@'), 'example@@example.co.uk'],
[new InvalidEmail(new ConsecutiveDot(), '.'), 'example@example..co.uk'],
[new InvalidEmail(new DotAtStart(), '.'), 'example@.localhost'],
[new InvalidEmail(new DomainHyphened('After AT'), '-'), 'example@-localhost'],
[new InvalidEmail(new DotAtEnd(), ''), 'example@localhost.'],
[new InvalidEmail(new UnOpenedComment(), ')'), 'example@comment)localhost'],
[new InvalidEmail(new UnOpenedComment(), ')'), 'example@localhost(comment))'],
[new InvalidEmail(new UnOpenedComment(), 'com'), 'example@(comment))example.com'],
[new InvalidEmail(new ExpectingDTEXT(), '['), "example@[[]"],
[new InvalidEmail(new CRNoLF(), "\r"), "example@exa\rmple.co.uk"],
[new InvalidEmail(new CRNoLF(), "["), "example@[\r]"],
[new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ,'), ','), 'example@exam,ple.com'],
[new InvalidEmail(new ExpectingATEXT("Invalid token in domain: '"), "'"), "test@example.com'"],
[new InvalidEmail(new LabelTooLong(), "."), sprintf('example@%s.com', str_repeat('ъ', 64))],
[new InvalidEmail(new LabelTooLong(), "."), sprintf('example@%s.com', str_repeat('a4t', 22))],
[new InvalidEmail(new LabelTooLong(), ""), sprintf('example@%s', str_repeat('a4t', 22))],
];
}
/**
* @dataProvider getValidEmailsWithWarnings
*/
public function testValidEmailsWithWarningsCheck($expectedWarnings, $email)
{
$this->assertTrue($this->validator->isValid($email, $this->lexer));
$warnings = $this->validator->getWarnings();
$this->assertCount(
count($expectedWarnings), $warnings,
"Expected: " . implode(",", $expectedWarnings) . " and got: " . PHP_EOL . implode(PHP_EOL, $warnings)
);
foreach ($warnings as $warning) {
$this->assertArrayHasKey($warning->code(), $expectedWarnings);
}
}
public static function getValidEmailsWithWarnings()
{
return [
//Check if this is actually possible
//[[CFWSNearAt::CODE], 'example@ invalid.example.com'],
[[Comment::CODE], 'example@invalid.example(examplecomment).com'],
[[AddressLiteral::CODE, TLD::CODE], 'example@[127.0.0.1]'],
[[AddressLiteral::CODE, TLD::CODE], 'example@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:7334]'],
[[AddressLiteral::CODE, IPV6Deprecated::CODE, TLD::CODE], 'example@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370::]'],
[[AddressLiteral::CODE, IPV6MaxGroups::CODE, TLD::CODE], 'example@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:7334::]'],
[[AddressLiteral::CODE, IPV6DoubleColon::CODE, TLD::CODE], 'example@[IPv6:1::1::1]'],
[[ObsoleteDTEXT::CODE, DomainLiteral::CODE, TLD::CODE], "example@[\n]"],
[[DomainLiteral::CODE, TLD::CODE], 'example@[::1]'],
[[DomainLiteral::CODE, TLD::CODE], 'example@[::123.45.67.178]'],
[
[IPV6ColonStart::CODE, AddressLiteral::CODE, IPV6GroupCount::CODE, TLD::CODE],
'example@[IPv6::2001:0db8:85a3:0000:0000:8a2e:0370:7334]'
],
[
[AddressLiteral::CODE, IPV6BadChar::CODE, TLD::CODE],
'example@[IPv6:z001:0db8:85a3:0000:0000:8a2e:0370:7334]'
],
[
[AddressLiteral::CODE, IPV6ColonEnd::CODE, TLD::CODE],
'example@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:]'
],
];
}
public static function invalidUTF16Chars()
{
return [
['example@symƒony.com'],
];
}
/**
* @dataProvider invalidUTF16Chars
*/
public function testInvalidUTF16($email)
{
$this->markTestSkipped('Util finding a way to control this kind of chars');
$this->assertFalse($this->validator->isValid($email, $this->lexer));
}
} | php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Validation/DNSCheckValidationTest.php | tests/EmailValidator/Validation/DNSCheckValidationTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\DomainAcceptsNoMail;
use Egulias\EmailValidator\Result\Reason\LocalOrReservedDomain;
use Egulias\EmailValidator\Result\Reason\NoDNSRecord;
use Egulias\EmailValidator\Result\Reason\UnableToGetDNSRecord;
use Egulias\EmailValidator\Validation\DNSCheckValidation;
use Egulias\EmailValidator\Validation\DNSGetRecordWrapper;
use Egulias\EmailValidator\Validation\DNSRecords;
use Egulias\EmailValidator\Warning\NoDNSMXRecord;
use PHPUnit\Framework\TestCase;
class DNSCheckValidationTest extends TestCase
{
public static function validEmailsProvider()
{
return [
// dot-atom
['Abc@ietf.org'],
['Abc@fake.ietf.org'],
['ABC@ietf.org'],
['Abc.123@ietf.org'],
['user+mailbox/department=shipping@ietf.org'],
['!#$%&\'*+-/=?^_`.{|}~@ietf.org'],
// quoted string
['"Abc@def"@ietf.org'],
['"Fred\ Bloggs"@ietf.org'],
['"Joe.\\Blow"@ietf.org'],
// unicode
['info@ñandu.cl'],
['ñandu@ñandu.cl'],
];
}
public static function localOrReservedEmailsProvider()
{
return [
// Reserved Top Level DNS Names
['test'],
['example'],
['invalid'],
['localhost'],
// mDNS
['local'],
// Private DNS Namespaces
['intranet'],
['internal'],
['private'],
['corp'],
['home'],
['lan'],
];
}
/**
* @dataProvider validEmailsProvider
*/
public function testValidDNS($validEmail)
{
$validation = new DNSCheckValidation();
$this->assertTrue($validation->isValid($validEmail, new EmailLexer()));
}
public function testInvalidDNS()
{
$validation = new DNSCheckValidation();
$this->assertFalse($validation->isValid("example@invalid.example.com", new EmailLexer()));
}
/**
* @dataProvider localOrReservedEmailsProvider
*/
public function testLocalOrReservedDomainError($localOrReservedEmails)
{
$validation = new DNSCheckValidation();
$expectedError = new InvalidEmail(new LocalOrReservedDomain(), $localOrReservedEmails);
$validation->isValid($localOrReservedEmails, new EmailLexer());
$this->assertEquals($expectedError, $validation->getError());
}
public function testDomainAcceptsNoMailError()
{
$validation = new DNSCheckValidation();
$expectedError = new InvalidEmail(new DomainAcceptsNoMail(), "");
$isValidResult = $validation->isValid("nullmx@example.com", new EmailLexer());
$this->assertEquals($expectedError, $validation->getError());
$this->assertFalse($isValidResult);
}
public function testDNSWarnings()
{
$this->markTestSkipped('Need to found a domain with AAAA records and no MX that fails later in the validations');
$validation = new DNSCheckValidation();
$expectedWarnings = [NoDNSMXRecord::CODE => new NoDNSMXRecord()];
$validation->isValid("example@invalid.example.com", new EmailLexer());
$this->assertEquals($expectedWarnings, $validation->getWarnings());
}
public function testNoDNSError()
{
$validation = new DNSCheckValidation();
$expectedError = new InvalidEmail(new NoDNSRecord(), '');
$validation->isValid("example@invalid.example.com", new EmailLexer());
$this->assertEquals($expectedError, $validation->getError());
}
/**
* @group flaky
*/
public function testUnableToGetDNSRecord()
{
error_reporting(\E_ALL);
// UnableToGetDNSRecord raises on network errors (e.g. timeout) that we can‘t emulate in tests (for sure),
// but we can simulate with the wrapper helper
$wrapper = new class extends DNSGetRecordWrapper {
public function getRecords(string $host, int $type) : DNSRecords
{
return new DNSRecords([], true);
}
};
$validation = new DNSCheckValidation($wrapper);
$expectedError = new InvalidEmail(new UnableToGetDNSRecord(), '');
$validation->isValid('example@invalid.example.com', new EmailLexer());
$this->assertEquals($expectedError, $validation->getError());
}
public function testMissingTypeKey()
{
$wrapper = new class extends DNSGetRecordWrapper {
public function getRecords(string $host, int $type): DNSRecords
{
return new DNSRecords(['host' => 'test']);
}
};
$validation = new DNSCheckValidation($wrapper);
$expectedError = new InvalidEmail(new NoDNSRecord(), '');
$validation->isValid('example@invalid.example.com', new EmailLexer());
$this->assertEquals($expectedError, $validation->getError());
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Validation/IsEmailFunctionTests.php | tests/EmailValidator/Validation/IsEmailFunctionTests.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\DNSCheckValidation;
use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
use Egulias\EmailValidator\Validation\NoRFCWarningsValidation;
use PHPUnit\Framework\TestCase;
class IsEmailFunctionTests extends TestCase
{
/**
* @dataProvider isEmailTestSuite
*/
public function testAgainstIsEmailTestSuite($email)
{
$validator = new EmailValidator();
$validations = new MultipleValidationWithAnd([
new NoRFCWarningsValidation(),
new DNSCheckValidation()
]);
$this->assertFalse($validator->isValid($email, $validations), "Tested email " . $email);
}
public function isEmailTestSuite()
{
$testSuite = __DIR__ . '/../../resources/is_email_tests.xml';
$document = new \DOMDocument();
$document->load($testSuite);
$elements = $document->getElementsByTagName('test');
$tests = [];
foreach($elements as $testElement) {
$childNode = $testElement->childNodes;
$tests[][] = ($childNode->item(1)->getAttribute('value'));
}
return $tests;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Validation/Extra/SpoofCheckValidationTest.php | tests/EmailValidator/Validation/Extra/SpoofCheckValidationTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Validation\Extra;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Validation\Extra\SpoofCheckValidation;
use PHPUnit\Framework\TestCase;
class SpoofCheckValidationTest extends TestCase
{
/**
* @dataProvider validUTF8EmailsProvider
*/
public function testUTF8EmailAreValid($email)
{
$validation = new SpoofCheckValidation();
$this->assertTrue($validation->isValid($email, new EmailLexer()));
}
public function testEmailWithSpoofsIsInvalid()
{
$validation = new SpoofCheckValidation();
$this->assertFalse($validation->isValid("Кириллица"."latin漢字"."ひらがな"."カタカナ", new EmailLexer()));
}
public static function validUTF8EmailsProvider()
{
return [
// Cyrillic
['Кириллица@Кириллица'],
// Latin + Han + Hiragana + Katakana
["latin漢字"."ひらがな"."カタカナ"."@example.com"],
// Latin + Han + Hangul
["latin"."漢字"."조선말"."@example.com"],
// Latin + Han + Bopomofo
["latin"."漢字"."ㄅㄆㄇㄈ"."@example.com"]
];
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Reason/MultipleErrorsTest.php | tests/EmailValidator/Reason/MultipleErrorsTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Reason;
use Egulias\EmailValidator\Result\MultipleErrors;
use Egulias\EmailValidator\Result\Reason\EmptyReason;
use Egulias\EmailValidator\Tests\EmailValidator\Dummy\AnotherDummyReason;
use Egulias\EmailValidator\Tests\EmailValidator\Dummy\DummyReason;
use PHPUnit\Framework\TestCase;
class MultipleErrorsTest extends TestCase
{
public function testRegisterSameReason()
{
$error1 = new DummyReason();
$error2 = new DummyReason();
$multiError = new MultipleErrors();
$multiError->addReason($error1);
$multiError->addReason($error2);
$this->assertCount(1, $multiError->getReasons());
}
public function testRegisterDifferentReasons()
{
$error1 = new DummyReason();
$error2 = new AnotherDummyReason();
$expectedReason = $error1->description() . PHP_EOL . $error2->description() . PHP_EOL;
$multiError = new MultipleErrors();
$multiError->addReason($error1);
$multiError->addReason($error2);
$this->assertCount(2, $multiError->getReasons());
$this->assertEquals($expectedReason, $multiError->description());
$this->assertEquals($error1, $multiError->reason());
}
public function testRetrieveFirstReasonWithReasonCodeEqualsZero(): void
{
$error1 = new DummyReason();
$multiError = new MultipleErrors();
$multiError->addReason($error1);
$this->assertEquals($error1, $multiError->reason());
}
public function testRetrieveFirstReasonWithReasonCodeDistinctToZero(): void
{
$error1 = new AnotherDummyReason();
$multiError = new MultipleErrors();
$multiError->addReason($error1);
$this->assertEquals($error1, $multiError->reason());
}
public function testRetrieveFirstReasonWithNoReasonAdded()
{
$emptyReason = new EmptyReason();
$multiError = new MultipleErrors();
$this->assertEquals($emptyReason, $multiError->reason());
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Dummy/DummyReason.php | tests/EmailValidator/Dummy/DummyReason.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Dummy;
use Egulias\EmailValidator\Result\Reason\Reason;
class DummyReason implements Reason
{
public function code() : int
{
return 0;
}
public function description() : string
{
return 'Dummy Reason';
}
} | php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Dummy/AnotherDummyReason.php | tests/EmailValidator/Dummy/AnotherDummyReason.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Dummy;
use Egulias\EmailValidator\Result\Reason\Reason;
class AnotherDummyReason implements Reason
{
public function code() : int
{
return 1;
}
public function description() : string
{
return 'Dummy Reason';
}
} | php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/tests/EmailValidator/Result/ResultTest.php | tests/EmailValidator/Result/ResultTest.php | <?php
namespace Egulias\EmailValidator\Tests\EmailValidator\Result;
use PHPUnit\Framework\TestCase;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\CharNotAllowed;
class ResultTest extends TestCase
{
public function testResultIsValidEmail()
{
$result = new ValidEmail();
$expectedCode = 0;
$expectedDescription = "Valid email";
$this->assertTrue($result->isValid());
$this->assertEquals($expectedCode, $result->code());
$this->assertEquals($expectedDescription, $result->description());
}
public function testResultIsInvalidEmail()
{
$reason = new CharNotAllowed();
$token = "T";
$result = new InvalidEmail($reason, $token);
$expectedCode = $reason->code();
$expectedDescription = $reason->description() . " in char " . $token;
$this->assertFalse($result->isValid());
$this->assertEquals($expectedCode, $result->code());
$this->assertEquals($expectedDescription, $result->description());
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/VoyagerServiceProvider.php | src/VoyagerServiceProvider.php | <?php
namespace TCG\Voyager;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Pagination\Paginator;
use Illuminate\Routing\Router;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Str;
use Intervention\Image\ImageServiceProvider;
use TCG\Voyager\Events\FormFieldsRegistered;
use TCG\Voyager\Facades\Voyager as VoyagerFacade;
use TCG\Voyager\FormFields\After\DescriptionHandler;
use TCG\Voyager\Http\Middleware\VoyagerAdminMiddleware;
use TCG\Voyager\Models\MenuItem;
use TCG\Voyager\Models\Setting;
use TCG\Voyager\Policies\BasePolicy;
use TCG\Voyager\Policies\MenuItemPolicy;
use TCG\Voyager\Policies\SettingPolicy;
use TCG\Voyager\Providers\VoyagerDummyServiceProvider;
use TCG\Voyager\Providers\VoyagerEventServiceProvider;
use TCG\Voyager\Seed;
use TCG\Voyager\Translator\Collection as TranslatorCollection;
class VoyagerServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
Setting::class => SettingPolicy::class,
MenuItem::class => MenuItemPolicy::class,
];
protected $gates = [
'browse_admin',
'browse_bread',
'browse_database',
'browse_media',
'browse_compass',
];
/**
* Register the application services.
*/
public function register()
{
$this->app->register(VoyagerEventServiceProvider::class);
$this->app->register(ImageServiceProvider::class);
$this->app->register(VoyagerDummyServiceProvider::class);
$loader = AliasLoader::getInstance();
$loader->alias('Voyager', VoyagerFacade::class);
$this->app->singleton('voyager', function () {
return new Voyager();
});
$this->app->singleton('VoyagerGuard', function () {
return config('auth.defaults.guard', 'web');
});
$this->loadHelpers();
$this->registerAlertComponents();
$this->registerFormFields();
$this->registerConfigs();
if ($this->app->runningInConsole()) {
$this->registerPublishableResources();
$this->registerConsoleCommands();
}
if (!$this->app->runningInConsole() || config('app.env') == 'testing') {
$this->registerAppCommands();
}
}
/**
* Bootstrap the application services.
*
* @param \Illuminate\Routing\Router $router
*/
public function boot(Router $router, Dispatcher $event)
{
if (config('voyager.user.add_default_role_on_register')) {
$model = Auth::guard(app('VoyagerGuard'))->getProvider()->getModel();
call_user_func($model.'::created', function ($user) use ($model) {
if (is_null($user->role_id)) {
call_user_func($model.'::findOrFail', $user->id)
->setRole(config('voyager.user.default_role'))
->save();
}
});
}
$this->loadViewsFrom(__DIR__.'/../resources/views', 'voyager');
$router->aliasMiddleware('admin.user', VoyagerAdminMiddleware::class);
$this->loadTranslationsFrom(realpath(__DIR__.'/../publishable/lang'), 'voyager');
if (config('voyager.database.autoload_migrations', true)) {
if (config('app.env') == 'testing') {
$this->loadMigrationsFrom(realpath(__DIR__.'/migrations'));
}
$this->loadMigrationsFrom(realpath(__DIR__.'/../migrations'));
}
$this->loadAuth();
$this->registerViewComposers();
$event->listen('voyager.alerts.collecting', function () {
$this->addStorageSymlinkAlert();
});
$this->bootTranslatorCollectionMacros();
if (method_exists('Paginator', 'useBootstrap')) {
Paginator::useBootstrap();
}
}
/**
* Load helpers.
*/
protected function loadHelpers()
{
foreach (glob(__DIR__.'/Helpers/*.php') as $filename) {
require_once $filename;
}
}
/**
* Register view composers.
*/
protected function registerViewComposers()
{
// Register alerts
View::composer('voyager::*', function ($view) {
$view->with('alerts', VoyagerFacade::alerts());
});
}
/**
* Add storage symlink alert.
*/
protected function addStorageSymlinkAlert()
{
if (app('router')->current() !== null) {
$currentRouteAction = app('router')->current()->getAction();
} else {
$currentRouteAction = null;
}
$routeName = is_array($currentRouteAction) ? Arr::get($currentRouteAction, 'as') : null;
if ($routeName != 'voyager.dashboard') {
return;
}
$storage_disk = (!empty(config('voyager.storage.disk'))) ? config('voyager.storage.disk') : 'public';
if (request()->has('fix-missing-storage-symlink')) {
if (file_exists(public_path('storage'))) {
if (@readlink(public_path('storage')) == public_path('storage')) {
rename(public_path('storage'), 'storage_old');
}
}
if (!file_exists(public_path('storage'))) {
$this->fixMissingStorageSymlink();
}
} elseif ($storage_disk == 'public') {
if (!file_exists(public_path('storage')) || @readlink(public_path('storage')) == public_path('storage')) {
$alert = (new Alert('missing-storage-symlink', 'warning'))
->title(__('voyager::error.symlink_missing_title'))
->text(__('voyager::error.symlink_missing_text'))
->button(__('voyager::error.symlink_missing_button'), '?fix-missing-storage-symlink=1');
VoyagerFacade::addAlert($alert);
}
}
}
protected function fixMissingStorageSymlink()
{
app('files')->link(storage_path('app/public'), public_path('storage'));
if (file_exists(public_path('storage'))) {
$alert = (new Alert('fixed-missing-storage-symlink', 'success'))
->title(__('voyager::error.symlink_created_title'))
->text(__('voyager::error.symlink_created_text'));
} else {
$alert = (new Alert('failed-fixing-missing-storage-symlink', 'danger'))
->title(__('voyager::error.symlink_failed_title'))
->text(__('voyager::error.symlink_failed_text'));
}
VoyagerFacade::addAlert($alert);
}
/**
* Register alert components.
*/
protected function registerAlertComponents()
{
$components = ['title', 'text', 'button'];
foreach ($components as $component) {
$class = 'TCG\\Voyager\\Alert\\Components\\'.ucfirst(Str::camel($component)).'Component';
$this->app->bind("voyager.alert.components.{$component}", $class);
}
}
protected function bootTranslatorCollectionMacros()
{
Collection::macro('translate', function () {
$transtors = [];
foreach ($this->all() as $item) {
$transtors[] = call_user_func_array([$item, 'translate'], func_get_args());
}
return new TranslatorCollection($transtors);
});
}
/**
* Register the publishable files.
*/
private function registerPublishableResources()
{
$publishablePath = dirname(__DIR__).'/publishable';
$publishable = [
'voyager_avatar' => [
"{$publishablePath}/dummy_content/users/" => storage_path('app/public/users'),
],
'seeders' => [
"{$publishablePath}/database/seeders/" => database_path('seeders'),
],
'config' => [
"{$publishablePath}/config/voyager.php" => config_path('voyager.php'),
],
];
foreach ($publishable as $group => $paths) {
$this->publishes($paths, $group);
}
}
public function registerConfigs()
{
$this->mergeConfigFrom(
dirname(__DIR__).'/publishable/config/voyager.php',
'voyager'
);
}
public function loadAuth()
{
// DataType Policies
// This try catch is necessary for the Package Auto-discovery
// otherwise it will throw an error because no database
// connection has been made yet.
try {
if (Schema::hasTable(VoyagerFacade::model('DataType')->getTable())) {
$dataType = VoyagerFacade::model('DataType');
$dataTypes = $dataType->select('policy_name', 'model_name')->get();
foreach ($dataTypes as $dataType) {
$policyClass = BasePolicy::class;
if (isset($dataType->policy_name) && $dataType->policy_name !== ''
&& class_exists($dataType->policy_name)) {
$policyClass = $dataType->policy_name;
}
$this->policies[$dataType->model_name] = $policyClass;
}
$this->registerPolicies();
}
} catch (\PDOException $e) {
Log::info('No database connection yet in VoyagerServiceProvider loadAuth(). No worries, this is not a problem!');
}
// Gates
foreach ($this->gates as $gate) {
Gate::define($gate, function ($user) use ($gate) {
return $user->hasPermission($gate);
});
}
}
protected function registerFormFields()
{
$formFields = [
'checkbox',
'multiple_checkbox',
'color',
'date',
'file',
'image',
'multiple_images',
'media_picker',
'number',
'password',
'radio_btn',
'rich_text_box',
'code_editor',
'markdown_editor',
'select_dropdown',
'select_multiple',
'text',
'text_area',
'time',
'timestamp',
'hidden',
'coordinates',
];
foreach ($formFields as $formField) {
$class = Str::studly("{$formField}_handler");
VoyagerFacade::addFormField("TCG\\Voyager\\FormFields\\{$class}");
}
VoyagerFacade::addAfterFormField(DescriptionHandler::class);
event(new FormFieldsRegistered($formFields));
}
/**
* Register the commands accessible from the Console.
*/
private function registerConsoleCommands()
{
$this->commands(Commands\InstallCommand::class);
$this->commands(Commands\ControllersCommand::class);
$this->commands(Commands\AdminCommand::class);
}
/**
* Register the commands accessible from the App.
*/
private function registerAppCommands()
{
$this->commands(Commands\MakeModelCommand::class);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Translator.php | src/Translator.php | <?php
namespace TCG\Voyager;
use ArrayAccess;
use Illuminate\Database\Eloquent\Model;
use JsonSerializable;
use TCG\Voyager\Facades\Voyager as VoyagerFacade;
class Translator implements ArrayAccess, JsonSerializable
{
protected $model;
protected $attributes = [];
protected $locale;
public function __construct(Model $model)
{
if (!$model->relationLoaded('translations')) {
$model->load('translations');
}
$this->model = $model;
$this->locale = config('voyager.multilingual.default', 'en');
$attributes = [];
foreach ($this->model->getAttributes() as $attribute => $value) {
$attributes[$attribute] = [
'value' => $value,
'locale' => $this->locale,
'exists' => true,
'modified' => false,
];
}
$this->attributes = $attributes;
}
public function translate($locale = null, $fallback = true)
{
$this->locale = $locale;
foreach ($this->model->getTranslatableAttributes() as $attribute) {
$this->translateAttribute($attribute, $locale, $fallback);
}
return $this;
}
/**
* Save changes made to the translator attributes.
*
* @return bool
*/
public function save()
{
$attributes = $this->getModifiedAttributes();
$savings = [];
foreach ($attributes as $key => $attribute) {
if ($attribute['exists']) {
$translation = $this->getTranslationModel($key);
} else {
$translation = VoyagerFacade::model('Translation')->where('table_name', $this->model->getTable())
->where('column_name', $key)
->where('foreign_key', $this->model->getKey())
->where('locale', $this->locale)
->first();
}
if (is_null($translation)) {
$translation = VoyagerFacade::model('Translation');
}
$translation->fill([
'table_name' => $this->model->getTable(),
'column_name' => $key,
'foreign_key' => $this->model->getKey(),
'value' => $attribute['value'],
'locale' => $this->locale,
]);
$savings[] = $translation->save();
$this->attributes[$key]['locale'] = $this->locale;
$this->attributes[$key]['exists'] = true;
$this->attributes[$key]['modified'] = false;
}
return in_array(false, $savings);
}
public function getModel()
{
return $this->model;
}
public function getRawAttributes()
{
return $this->attributes;
}
public function getOriginalAttributes()
{
return $this->model->getAttributes();
}
public function getOriginalAttribute($key)
{
return $this->model->getAttribute($key);
}
public function getTranslationModel($key, $locale = null)
{
return $this->model->getRelation('translations')
->where('column_name', $key)
->where('locale', $locale ? $locale : $this->locale)
->first();
}
public function getModifiedAttributes()
{
return collect($this->attributes)->where('modified', 1)->all();
}
protected function translateAttribute($attribute, $locale = null, $fallback = true)
{
list($value, $locale, $exists) = $this->model->getTranslatedAttributeMeta($attribute, $locale, $fallback);
$this->attributes[$attribute] = [
'value' => $value,
'locale' => $locale,
'exists' => $exists,
'modified' => false,
];
return $this;
}
protected function translateAttributeToOriginal($attribute)
{
$this->attributes[$attribute] = [
'value' => $this->model->attributes[$attribute],
'locale' => config('voyager.multilingual.default', 'en'),
'exists' => true,
'modified' => false,
];
return $this;
}
public function __get($name)
{
if (!isset($this->attributes[$name])) {
if (isset($this->model->$name)) {
return $this->model->$name;
}
return;
}
if (!$this->attributes[$name]['exists'] && !$this->attributes[$name]['modified']) {
return $this->getOriginalAttribute($name);
}
return $this->attributes[$name]['value'];
}
public function __set($name, $value)
{
$this->attributes[$name]['value'] = $value;
if (!in_array($name, $this->model->getTranslatableAttributes())) {
return $this->model->$name = $value;
}
$this->attributes[$name]['modified'] = true;
}
public function offsetGet($offset)
{
return $this->attributes[$offset]['value'];
}
public function offsetSet($offset, $value)
{
$this->attributes[$offset]['value'] = $value;
if (!in_array($offset, $this->model->getTranslatableAttributes())) {
return $this->model->$offset = $value;
}
$this->attributes[$offset]['modified'] = true;
}
public function offsetExists($offset)
{
return isset($this->attributes[$offset]);
}
public function offsetUnset($offset)
{
unset($this->attributes[$offset]);
}
public function getLocale()
{
return $this->locale;
}
public function translationAttributeExists($name)
{
if (!isset($this->attributes[$name])) {
return false;
}
return $this->attributes[$name]['exists'];
}
public function translationAttributeModified($name)
{
if (!isset($this->attributes[$name])) {
return false;
}
return $this->attributes[$name]['modified'];
}
public function createTranslation($key, $value)
{
if (!isset($this->attributes[$key])) {
return false;
}
if (!in_array($key, $this->model->getTranslatableAttributes())) {
return false;
}
$translation = VoyagerFacade::model('Translation');
$translation->fill([
'table_name' => $this->model->getTable(),
'column_name' => $key,
'foreign_key' => $this->model->getKey(),
'value' => $value,
'locale' => $this->locale,
]);
$translation->save();
$this->model->getRelation('translations')->add($translation);
$this->attributes[$key]['exists'] = true;
$this->attributes[$key]['value'] = $value;
return $this->model->getRelation('translations')
->where('key', $key)
->where('locale', $this->locale)
->first();
}
public function createTranslations(array $translations)
{
foreach ($translations as $key => $value) {
$this->createTranslation($key, $value);
}
}
public function deleteTranslation($key)
{
if (!isset($this->attributes[$key])) {
return false;
}
if (!$this->attributes[$key]['exists']) {
return false;
}
$translations = $this->model->getRelation('translations');
$locale = $this->locale;
VoyagerFacade::model('Translation')->where('table_name', $this->model->getTable())
->where('column_name', $key)
->where('foreign_key', $this->model->getKey())
->where('locale', $locale)
->delete();
$this->model->setRelation('translations', $translations->filter(function ($translation) use ($key, $locale) {
return $translation->column_name != $key && $translation->locale != $locale;
}));
$this->attributes[$key]['value'] = null;
$this->attributes[$key]['exists'] = false;
$this->attributes[$key]['modified'] = false;
return true;
}
public function deleteTranslations(array $keys)
{
foreach ($keys as $key) {
$this->deleteTranslation($key);
}
}
public function __call($method, array $arguments)
{
if (!$this->model->hasTranslatorMethod($method)) {
throw new \Exception('Call to undefined method TCG\Voyager\Translator::'.$method.'()');
}
return call_user_func_array([$this, 'runTranslatorMethod'], [$method, $arguments]);
}
public function runTranslatorMethod($method, array $arguments)
{
array_unshift($arguments, $this);
$method = $this->model->getTranslatorMethod($method);
return call_user_func_array([$this->model, $method], $arguments);
}
public function jsonSerialize()
{
return array_map(function ($array) {
return $array['value'];
}, $this->getRawAttributes());
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Voyager.php | src/Voyager.php | <?php
namespace TCG\Voyager;
use Arrilot\Widgets\Facade as Widget;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use TCG\Voyager\Actions\DeleteAction;
use TCG\Voyager\Actions\EditAction;
use TCG\Voyager\Actions\RestoreAction;
use TCG\Voyager\Actions\ViewAction;
use TCG\Voyager\Events\AlertsCollection;
use TCG\Voyager\FormFields\After\HandlerInterface as AfterHandlerInterface;
use TCG\Voyager\FormFields\HandlerInterface;
use TCG\Voyager\Models\Category;
use TCG\Voyager\Models\DataRow;
use TCG\Voyager\Models\DataType;
use TCG\Voyager\Models\Menu;
use TCG\Voyager\Models\MenuItem;
use TCG\Voyager\Models\Page;
use TCG\Voyager\Models\Permission;
use TCG\Voyager\Models\Post;
use TCG\Voyager\Models\Role;
use TCG\Voyager\Models\Setting;
use TCG\Voyager\Models\Translation;
use TCG\Voyager\Models\User;
use TCG\Voyager\Traits\Translatable;
class Voyager
{
protected $version;
protected $filesystem;
protected $alerts = [];
protected $alertsCollected = false;
protected $formFields = [];
protected $afterFormFields = [];
protected $viewLoadingEvents = [];
protected $actions = [
DeleteAction::class,
RestoreAction::class,
EditAction::class,
ViewAction::class,
];
protected $models = [
'Category' => Category::class,
'DataRow' => DataRow::class,
'DataType' => DataType::class,
'Menu' => Menu::class,
'MenuItem' => MenuItem::class,
'Page' => Page::class,
'Permission' => Permission::class,
'Post' => Post::class,
'Role' => Role::class,
'Setting' => Setting::class,
'User' => User::class,
'Translation' => Translation::class,
];
public $setting_cache = null;
public function __construct()
{
$this->filesystem = app(Filesystem::class);
$this->findVersion();
}
public function model($name)
{
return app($this->models[Str::studly($name)]);
}
public function modelClass($name)
{
return $this->models[$name];
}
public function useModel($name, $object)
{
if (is_string($object)) {
$object = app($object);
}
$class = get_class($object);
if (isset($this->models[Str::studly($name)]) && !$object instanceof $this->models[Str::studly($name)]) {
throw new \Exception("[{$class}] must be instance of [{$this->models[Str::studly($name)]}].");
}
$this->models[Str::studly($name)] = $class;
return $this;
}
public function view($name, array $parameters = [])
{
foreach (Arr::get($this->viewLoadingEvents, $name, []) as $event) {
$event($name, $parameters);
}
return view($name, $parameters);
}
public function onLoadingView($name, \Closure $closure)
{
if (!isset($this->viewLoadingEvents[$name])) {
$this->viewLoadingEvents[$name] = [];
}
$this->viewLoadingEvents[$name][] = $closure;
}
public function formField($row, $dataType, $dataTypeContent)
{
if (!isset($this->formFields[$row->type])) {
throw new \Exception(__('Missing field type: ' . $row->type), 500);
}
$formField = $this->formFields[$row->type];
return $formField->handle($row, $dataType, $dataTypeContent);
}
public function afterFormFields($row, $dataType, $dataTypeContent)
{
return collect($this->afterFormFields)->filter(function ($after) use ($row, $dataType, $dataTypeContent) {
return $after->visible($row, $dataType, $dataTypeContent, $row->details);
});
}
public function addFormField($handler)
{
if (!$handler instanceof HandlerInterface) {
$handler = app($handler);
}
$this->formFields[$handler->getCodename()] = $handler;
return $this;
}
public function addAfterFormField($handler)
{
if (!$handler instanceof AfterHandlerInterface) {
$handler = app($handler);
}
$this->afterFormFields[$handler->getCodename()] = $handler;
return $this;
}
public function formFields()
{
$connection = config('database.default');
$driver = config("database.connections.{$connection}.driver", 'mysql');
return collect($this->formFields)->filter(function ($after) use ($driver) {
return $after->supports($driver);
});
}
public function addAction($action)
{
array_push($this->actions, $action);
}
public function replaceAction($actionToReplace, $action)
{
$key = array_search($actionToReplace, $this->actions);
$this->actions[$key] = $action;
}
public function actions()
{
return $this->actions;
}
/**
* Get a collection of dashboard widgets.
* Each of our widget groups contain a max of three widgets.
* After that, we will switch to a new widget group.
*
* @return array - Array consisting of \Arrilot\Widget\WidgetGroup objects
*/
public function dimmers()
{
$widgetClasses = config('voyager.dashboard.widgets');
$dimmerGroups = [];
$dimmerCount = 0;
$dimmers = Widget::group("voyager::dimmers-{$dimmerCount}");
foreach ($widgetClasses as $widgetClass) {
$widget = app($widgetClass);
if ($widget->shouldBeDisplayed()) {
// Every third dimmer, we consider out WidgetGroup filled.
// We switch that out with another WidgetGroup.
if ($dimmerCount % 3 === 0 && $dimmerCount !== 0) {
$dimmerGroups[] = $dimmers;
$dimmerGroupTag = ceil($dimmerCount / 3);
$dimmers = Widget::group("voyager::dimmers-{$dimmerGroupTag}");
}
$dimmers->addWidget($widgetClass);
$dimmerCount++;
}
}
$dimmerGroups[] = $dimmers;
return $dimmerGroups;
}
public function setting($key, $default = null)
{
$globalCache = config('voyager.settings.cache', false);
if ($globalCache && Cache::tags('settings')->has($key)) {
return Cache::tags('settings')->get($key);
}
if ($this->setting_cache === null) {
if ($globalCache) {
// A key is requested that is not in the cache
// this is a good opportunity to update all keys
// albeit not strictly necessary
Cache::tags('settings')->flush();
}
foreach (self::model('Setting')->orderBy('order')->get() as $setting) {
$keys = explode('.', $setting->key);
@$this->setting_cache[$keys[0]][$keys[1]] = $setting->value;
if ($globalCache) {
Cache::tags('settings')->forever($setting->key, $setting->value);
}
}
}
$parts = explode('.', $key);
if (count($parts) == 2) {
return @$this->setting_cache[$parts[0]][$parts[1]] ?: $default;
} else {
return @$this->setting_cache[$parts[0]] ?: $default;
}
}
public function image($file, $default = '')
{
if (!empty($file)) {
return str_replace('\\', '/', Storage::disk(config('voyager.storage.disk'))->url($file));
}
return $default;
}
public function routes()
{
require __DIR__.'/../routes/voyager.php';
}
public function getVersion()
{
return $this->version;
}
public function addAlert(Alert $alert)
{
$this->alerts[] = $alert;
}
public function alerts()
{
if (!$this->alertsCollected) {
event(new AlertsCollection($this->alerts));
$this->alertsCollected = true;
}
return $this->alerts;
}
protected function findVersion()
{
if (!is_null($this->version)) {
return;
}
if ($this->filesystem->exists(base_path('composer.lock'))) {
// Get the composer.lock file
$file = json_decode(
$this->filesystem->get(base_path('composer.lock'))
);
// Loop through all the packages and get the version of voyager
foreach ($file->packages as $package) {
if ($package->name == 'tcg/voyager') {
$this->version = $package->version;
break;
}
}
}
}
/**
* @param string|Model|Collection $model
*
* @return bool
*/
public function translatable($model)
{
if (!config('voyager.multilingual.enabled')) {
return false;
}
if (is_string($model)) {
$model = app($model);
}
if ($model instanceof Collection) {
$model = $model->first();
}
if (!is_subclass_of($model, Model::class)) {
return false;
}
$traits = class_uses_recursive(get_class($model));
return in_array(Translatable::class, $traits);
}
public function getLocales()
{
$appLocales = [];
if ($this->filesystem->exists(resource_path('lang/vendor/voyager'))) {
$appLocales = array_diff(scandir(resource_path('lang/vendor/voyager')), ['..', '.']);
}
$vendorLocales = array_diff(scandir(realpath(__DIR__.'/../publishable/lang')), ['..', '.']);
$allLocales = array_merge($vendorLocales, $appLocales);
asort($allLocales);
return $allLocales;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Alert.php | src/Alert.php | <?php
namespace TCG\Voyager;
use TCG\Voyager\Alert\Components\ComponentInterface;
class Alert
{
protected $components;
protected $name;
protected $type;
public function __construct($name, $type = 'default')
{
$this->name = $name;
$this->type = $type;
}
public function addComponent(ComponentInterface $component)
{
$this->components[] = $component;
return $this;
}
public function __get($name)
{
return $this->$name;
}
public function __call($name, $arguments)
{
$component = app('voyager.alert.components.'.$name, ['alert' => $this])
->setAlert($this);
call_user_func_array([$component, 'create'], $arguments);
return $this->addComponent($component);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Helpers/helpers.php | src/Helpers/helpers.php | <?php
if (!function_exists('setting')) {
function setting($key, $default = null)
{
return TCG\Voyager\Facades\Voyager::setting($key, $default);
}
}
if (!function_exists('menu')) {
function menu($menuName, $type = null, array $options = [])
{
return TCG\Voyager\Facades\Voyager::model('Menu')->display($menuName, $type, $options);
}
}
if (!function_exists('voyager_asset')) {
function voyager_asset($path, $secure = null)
{
return route('voyager.voyager_assets').'?path='.urlencode($path);
}
}
if (!function_exists('get_file_name')) {
function get_file_name($name)
{
preg_match('/(_)([0-9])+$/', $name, $matches);
if (count($matches) == 3) {
return Illuminate\Support\Str::replaceLast($matches[0], '', $name).'_'.(intval($matches[2]) + 1);
} else {
return $name.'_1';
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Helpers/helpersi18n.php | src/Helpers/helpersi18n.php | <?php
if (!function_exists('__')) {
function __($key, array $par = [])
{
return trans($key, $par);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Helpers/helperTranslations.php | src/Helpers/helperTranslations.php | <?php
if (!function_exists('is_field_translatable')) {
/**
* Check if a Field is translatable.
*
* @param Illuminate\Database\Eloquent\Model $model
* @param Illuminate\Database\Eloquent\Collection $row
*/
function is_field_translatable($model, $row)
{
if (!is_bread_translatable($model)) {
return;
}
return $model->translatable()
&& method_exists($model, 'getTranslatableAttributes')
&& in_array($row->field, $model->getTranslatableAttributes());
}
}
if (!function_exists('get_field_translations')) {
/**
* Return all field translations.
*
* @param Illuminate\Database\Eloquent\Model $model
* @param string $field
* @param string $rowType
* @param bool $stripHtmlTags
*/
function get_field_translations($model, $field, $rowType = '', $stripHtmlTags = false)
{
$_out = $model->getTranslationsOf($field);
if ($stripHtmlTags && $rowType == 'rich_text_box') {
foreach ($_out as $language => $value) {
$_out[$language] = strip_tags($_out[$language]);
}
}
return json_encode($_out);
}
}
if (!function_exists('is_bread_translatable')) {
/**
* Check if BREAD is translatable.
*
* @param Illuminate\Database\Eloquent\Model $model
*/
function is_bread_translatable($model)
{
return config('voyager.multilingual.enabled')
&& isset($model)
&& method_exists($model, 'translatable')
&& $model->translatable();
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Helpers/helperSlugify.php | src/Helpers/helperSlugify.php | <?php
if (!function_exists('isBreadSlugAutoGenerator')) {
/**
* Check if a field slug can be auto generated.
*
* @param json $options
*
* @return string HTML output.
*/
function isBreadSlugAutoGenerator($options)
{
if (isset($options->slugify)) {
return ' data-slug-origin='.$options->slugify->origin
.((isset($options->slugify->forceUpdate))
? ' data-slug-forceupdate=true'
: '');
}
}
}
if (!function_exists('isFieldSlugAutoGenerator')) {
/**
* Determine the details field, for a given dataTypeContent.
*
* @param Illuminate\Database\Eloquent\Collection $dType Data type
* @param Illuminate\Database\Eloquent\Collection $dContent Data type Content
* @param string $field Field name
*
* @return string HTML output.
*/
function isFieldSlugAutoGenerator($dType, $dContent, $field)
{
$_row = (isset($dContent->id))
? $dType->editRows
: $dType->addRows;
$_row = $_row->where('field', $field)->first();
if (!$_row) {
return;
}
return isBreadSlugAutoGenerator($_row->details);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Helpers/Reflection.php | src/Helpers/Reflection.php | <?php
if (!function_exists('get_reflection_method')) {
function get_reflection_method($object, $method)
{
$reflectionMethod = new \ReflectionMethod($object, $method);
$reflectionMethod->setAccessible(true);
return $reflectionMethod;
}
}
if (!function_exists('call_protected_method')) {
function call_protected_method($object, $method, ...$args)
{
return get_reflection_method($object, $method)->invoke($object, ...$args);
}
}
if (!function_exists('get_reflection_property')) {
function get_reflection_property($object, $property)
{
$reflectionProperty = new \ReflectionProperty($object, $property);
$reflectionProperty->setAccessible(true);
return $reflectionProperty;
}
}
if (!function_exists('get_protected_property')) {
function get_protected_property($object, $property)
{
return get_reflection_property($object, $property)->getValue($object);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerUserController.php | src/Http/Controllers/VoyagerUserController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use TCG\Voyager\Facades\Voyager;
class VoyagerUserController extends VoyagerBaseController
{
public function profile(Request $request)
{
$route = '';
$dataType = Voyager::model('DataType')->where('model_name', Auth::guard(app('VoyagerGuard'))->getProvider()->getModel())->first();
if (!$dataType && app('VoyagerGuard') == 'web') {
$route = route('voyager.users.edit', Auth::user()->getKey());
} elseif ($dataType) {
$route = route('voyager.'.$dataType->slug.'.edit', Auth::user()->getKey());
}
return Voyager::view('voyager::profile', compact('route'));
}
// POST BR(E)AD
public function update(Request $request, $id)
{
if (Auth::user()->getKey() == $id) {
$request->merge([
'role_id' => Auth::user()->role_id,
'user_belongstomany_role_relationship' => Auth::user()->roles->pluck('id')->toArray(),
]);
}
return parent::update($request, $id);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerAuthController.php | src/Http/Controllers/VoyagerAuthController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use TCG\Voyager\Facades\Voyager;
class VoyagerAuthController extends Controller
{
use AuthenticatesUsers;
public function login()
{
if ($this->guard()->user()) {
return redirect()->route('voyager.dashboard');
}
return Voyager::view('voyager::login');
}
public function postLogin(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->credentials($request);
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
/*
* Preempts $redirectTo member variable (from RedirectsUsers trait)
*/
public function redirectTo()
{
return config('voyager.user.redirect', route('voyager.dashboard'));
}
/**
* Get the guard to be used during authentication.
*
* @return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard(app('VoyagerGuard'));
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerCompassController.php | src/Http/Controllers/VoyagerCompassController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Artisan;
use Exception;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class VoyagerCompassController extends Controller
{
protected $request;
public function __construct()
{
$this->request = app('request');
}
public function index(Request $request)
{
// Check permission
$this->authorize('browse_compass');
//Check if app is not local
if (!\App::environment('local') && !config('voyager.compass_in_production', false)) {
throw new AccessDeniedHttpException();
}
$message = '';
$active_tab = '';
if ($this->request->input('log')) {
$active_tab = 'logs';
LogViewer::setFile(base64_decode($this->request->input('log')));
}
if ($this->request->input('logs')) {
$active_tab = 'logs';
}
if ($this->request->input('download')) {
$active_tab = 'logs';
return $this->download(LogViewer::pathToLogFile(base64_decode($this->request->input('download'))));
} elseif ($this->request->has('del')) {
$active_tab = 'logs';
app('files')->delete(LogViewer::pathToLogFile(base64_decode($this->request->input('del'))));
return redirect($this->request->url().'?logs=true')->with([
'message' => __('voyager::compass.logs.delete_success').' '.base64_decode($this->request->input('del')),
'alert-type' => 'success',
]);
} elseif ($this->request->has('delall')) {
$active_tab = 'logs';
foreach (LogViewer::getFiles(true) as $file) {
app('files')->delete(LogViewer::pathToLogFile($file));
}
return redirect($this->request->url().'?logs=true')->with([
'message' => __('voyager::compass.logs.delete_all_success'),
'alert-type' => 'success',
]);
}
$artisan_output = '';
if ($request->isMethod('post')) {
$command = $request->command;
$args = $request->args;
$args = (isset($args)) ? ' '.$args : '';
try {
Artisan::call($command.$args);
$artisan_output = Artisan::output();
} catch (Exception $e) {
$artisan_output = $e->getMessage();
}
$active_tab = 'commands';
}
$logs = LogViewer::all();
$files = LogViewer::getFiles(true);
$current_file = LogViewer::getFileName();
// get the full list of artisan commands and store the output
$commands = $this->getArtisanCommands();
return view('voyager::compass.index', compact('logs', 'files', 'current_file', 'active_tab', 'commands', 'artisan_output'))->with($message);
}
private function getArtisanCommands()
{
Artisan::call('list');
// Get the output from the previous command
$artisan_output = Artisan::output();
$artisan_output = $this->cleanArtisanOutput($artisan_output);
$commands = $this->getCommandsFromOutput($artisan_output);
return $commands;
}
private function cleanArtisanOutput($output)
{
// Add each new line to an array item and strip out any empty items
$output = array_filter(explode("\n", $output));
// Get the current index of: "Available commands:"
$index = array_search('Available commands:', $output);
// Remove all commands that precede "Available commands:", and remove that
// Element itself -1 for offset zero and -1 for the previous index (equals -2)
$output = array_slice($output, $index - 2, count($output));
return $output;
}
private function getCommandsFromOutput($output)
{
$commands = [];
foreach ($output as $output_line) {
if (empty(trim(substr($output_line, 0, 2)))) {
$parts = preg_split('/ +/', trim($output_line));
$command = (object) ['name' => trim(@$parts[0]), 'description' => trim(@$parts[1])];
array_push($commands, $command);
}
}
return $commands;
}
private function download($data)
{
return response()->download($data);
}
}
/***
**** Credit for the LogViewer class
**** https://github.com/rap2hpoutre/laravel-log-viewer
***/
class LogViewer
{
/**
* @var string file
*/
private static $file;
private static $levels_classes = [
'debug' => 'info',
'info' => 'info',
'notice' => 'info',
'warning' => 'warning',
'error' => 'danger',
'critical' => 'danger',
'alert' => 'danger',
'emergency' => 'danger',
'processed' => 'info',
];
private static $levels_imgs = [
'debug' => 'info',
'info' => 'info',
'notice' => 'info',
'warning' => 'warning',
'error' => 'warning',
'critical' => 'warning',
'alert' => 'warning',
'emergency' => 'warning',
'processed' => 'info',
];
/**
* Log levels that are used.
*
* @var array
*/
private static $log_levels = [
'emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'info',
'debug',
'processed',
];
public const MAX_FILE_SIZE = 52428800; // Why? Uh... Sorry
/**
* @param string $file
*/
public static function setFile($file)
{
$file = self::pathToLogFile($file);
if (app('files')->exists($file)) {
self::$file = $file;
}
}
/**
* @param string $file
*
* @throws \Exception
*
* @return string
*/
public static function pathToLogFile($file)
{
$logsPath = storage_path('logs');
if (app('files')->exists($file)) { // try the absolute path
return $file;
}
$file = $logsPath.'/'.$file;
// check if requested file is really in the logs directory
if (dirname($file) !== $logsPath) {
throw new \Exception('No such log file');
}
return $file;
}
/**
* @return string
*/
public static function getFileName()
{
return basename(self::$file);
}
/**
* @return array
*/
public static function all()
{
$log = [];
$pattern = '/\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\].*/';
if (!self::$file) {
$log_file = self::getFiles();
if (!count($log_file)) {
return [];
}
self::$file = $log_file[0];
}
if (app('files')->size(self::$file) > self::MAX_FILE_SIZE) {
return;
}
$file = app('files')->get(self::$file);
preg_match_all($pattern, $file, $headings);
if (!is_array($headings)) {
return $log;
}
$log_data = preg_split($pattern, $file);
if ($log_data[0] < 1) {
array_shift($log_data);
}
foreach ($headings as $h) {
for ($i = 0, $j = count($h); $i < $j; $i++) {
foreach (self::$log_levels as $level) {
if (strpos(strtolower($h[$i]), '.'.$level) || strpos(strtolower($h[$i]), $level.':')) {
preg_match('/^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\](?:.*?(\w+)\.|.*?)'.$level.': (.*?)( in .*?:[0-9]+)?$/i', $h[$i], $current);
if (!isset($current[3])) {
continue;
}
$log[] = [
'context' => $current[2],
'level' => $level,
'level_class' => self::$levels_classes[$level],
'level_img' => self::$levels_imgs[$level],
'date' => $current[1],
'text' => $current[3],
'in_file' => $current[4] ?? null,
'stack' => preg_replace("/^\n*/", '', $log_data[$i]),
];
}
}
}
}
return array_reverse($log);
}
/**
* @param bool $basename
*
* @return array
*/
public static function getFiles($basename = false)
{
$files = glob(storage_path().'/logs/*.log');
$files = array_reverse($files);
$files = array_filter($files, 'is_file');
if ($basename && is_array($files)) {
foreach ($files as $k => $file) {
$files[$k] = basename($file);
}
}
return array_values($files);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerMenuController.php | src/Http/Controllers/VoyagerMenuController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use TCG\Voyager\Facades\Voyager;
class VoyagerMenuController extends Controller
{
public function builder($id)
{
$menu = Voyager::model('Menu')->findOrFail($id);
$this->authorize('edit', $menu);
$isModelTranslatable = is_bread_translatable(Voyager::model('MenuItem'));
return Voyager::view('voyager::menus.builder', compact('menu', 'isModelTranslatable'));
}
public function delete_menu($menu, $id)
{
$item = Voyager::model('MenuItem')->findOrFail($id);
$this->authorize('delete', $item);
$item->deleteAttributeTranslation('title');
$item->destroy($id);
return redirect()
->route('voyager.menus.builder', [$menu])
->with([
'message' => __('voyager::menu_builder.successfully_deleted'),
'alert-type' => 'success',
]);
}
public function add_item(Request $request)
{
$menu = Voyager::model('Menu');
$this->authorize('add', $menu);
$data = $this->prepareParameters(
$request->all()
);
unset($data['id']);
$data['order'] = Voyager::model('MenuItem')->highestOrderMenuItem();
// Check if is translatable
$_isTranslatable = is_bread_translatable(Voyager::model('MenuItem'));
if ($_isTranslatable) {
// Prepare data before saving the menu
$trans = $this->prepareMenuTranslations($data);
}
$menuItem = Voyager::model('MenuItem')->create($data);
// Save menu translations
if ($_isTranslatable) {
$menuItem->setAttributeTranslations('title', $trans, true);
}
return redirect()
->route('voyager.menus.builder', [$data['menu_id']])
->with([
'message' => __('voyager::menu_builder.successfully_created'),
'alert-type' => 'success',
]);
}
public function update_item(Request $request)
{
$id = $request->input('id');
$data = $this->prepareParameters(
$request->except(['id'])
);
$menuItem = Voyager::model('MenuItem')->findOrFail($id);
$this->authorize('edit', $menuItem->menu);
if (is_bread_translatable($menuItem)) {
$trans = $this->prepareMenuTranslations($data);
// Save menu translations
$menuItem->setAttributeTranslations('title', $trans, true);
}
$menuItem->update($data);
return redirect()
->route('voyager.menus.builder', [$menuItem->menu_id])
->with([
'message' => __('voyager::menu_builder.successfully_updated'),
'alert-type' => 'success',
]);
}
public function order_item(Request $request)
{
$menuItemOrder = json_decode($request->input('order'));
$this->orderMenu($menuItemOrder, null);
}
private function orderMenu(array $menuItems, $parentId)
{
foreach ($menuItems as $index => $menuItem) {
$item = Voyager::model('MenuItem')->findOrFail($menuItem->id);
$item->order = $index + 1;
$item->parent_id = $parentId;
$item->save();
if (isset($menuItem->children)) {
$this->orderMenu($menuItem->children, $item->id);
}
}
}
protected function prepareParameters($parameters)
{
switch (Arr::get($parameters, 'type')) {
case 'route':
$parameters['url'] = null;
break;
default:
$parameters['route'] = null;
$parameters['parameters'] = '';
break;
}
if (isset($parameters['type'])) {
unset($parameters['type']);
}
return $parameters;
}
/**
* Prepare menu translations.
*
* @param array $data menu data
*
* @return JSON translated item
*/
protected function prepareMenuTranslations(&$data)
{
$trans = json_decode($data['title_i18n'], true);
// Set field value with the default locale
$data['title'] = $trans[config('voyager.multilingual.default', 'en')];
unset($data['title_i18n']); // Remove hidden input holding translations
unset($data['i18n_selector']); // Remove language selector input radio
return $trans;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerController.php | src/Http/Controllers/VoyagerController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Constraint;
use Intervention\Image\Facades\Image;
use TCG\Voyager\Facades\Voyager;
class VoyagerController extends Controller
{
public function index()
{
return Voyager::view('voyager::index');
}
public function logout()
{
Auth::logout();
return redirect()->route('voyager.login');
}
public function upload(Request $request)
{
$fullFilename = null;
$resizeWidth = 1800;
$resizeHeight = null;
$slug = $request->input('type_slug');
$file = $request->file('image');
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->firstOrFail();
if ($this->userCannotUploadImageIn($dataType, 'add') && $this->userCannotUploadImageIn($dataType, 'edit')) {
abort(403);
}
$path = $slug.'/'.date('FY').'/';
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension());
$filename_counter = 1;
// Make sure the filename does not exist, if it does make sure to add a number to the end 1, 2, 3, etc...
while (Storage::disk(config('voyager.storage.disk'))->exists($path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension()).(string) ($filename_counter++);
}
$fullPath = $path.$filename.'.'.$file->getClientOriginalExtension();
$ext = $file->guessClientExtension();
if (in_array($ext, ['jpeg', 'jpg', 'png', 'gif'])) {
$image = Image::make($file)
->resize($resizeWidth, $resizeHeight, function (Constraint $constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
if ($ext !== 'gif') {
$image->orientate();
}
$image->encode($file->getClientOriginalExtension(), 75);
// move uploaded file from temp to uploads directory
if (Storage::disk(config('voyager.storage.disk'))->put($fullPath, (string) $image, 'public')) {
$status = __('voyager::media.success_uploading');
$fullFilename = $fullPath;
} else {
$status = __('voyager::media.error_uploading');
}
} else {
$status = __('voyager::media.uploading_wrong_type');
}
// Return URL for TinyMCE
return Voyager::image($fullFilename);
}
public function assets(Request $request)
{
try {
if (class_exists(\League\Flysystem\Util::class)) {
// Flysystem 1.x
$path = dirname(__DIR__, 3).'/publishable/assets/'.\League\Flysystem\Util::normalizeRelativePath(urldecode($request->path));
} elseif (class_exists(\League\Flysystem\WhitespacePathNormalizer::class)) {
// Flysystem >= 2.x
$normalizer = new \League\Flysystem\WhitespacePathNormalizer();
$path = dirname(__DIR__, 3).'/publishable/assets/'. $normalizer->normalizePath(urldecode($request->path));
}
} catch (\LogicException $e) {
abort(404);
}
if (File::exists($path)) {
$mime = '';
if (Str::endsWith($path, '.js')) {
$mime = 'text/javascript';
} elseif (Str::endsWith($path, '.css')) {
$mime = 'text/css';
} else {
$mime = File::mimeType($path);
}
$response = response(File::get($path), 200, ['Content-Type' => $mime]);
$response->setSharedMaxAge(31536000);
$response->setMaxAge(31536000);
$response->setExpires(new \DateTime('+1 year'));
return $response;
}
return response('', 404);
}
protected function userCannotUploadImageIn($dataType, $action)
{
return auth()->user()->cannot($action, app($dataType->model_name))
|| $dataType->{$action.'Rows'}->where('type', 'rich_text_box')->count() === 0;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerSettingsController.php | src/Http/Controllers/VoyagerSettingsController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use TCG\Voyager\Facades\Voyager;
class VoyagerSettingsController extends Controller
{
public function index()
{
// Check permission
$this->authorize('browse', Voyager::model('Setting'));
$data = Voyager::model('Setting')->orderBy('order', 'ASC')->get();
$settings = [];
$settings[__('voyager::settings.group_general')] = [];
foreach ($data as $d) {
if ($d->group == '' || $d->group == __('voyager::settings.group_general')) {
$settings[__('voyager::settings.group_general')][] = $d;
} else {
$settings[$d->group][] = $d;
}
}
if (count($settings[__('voyager::settings.group_general')]) == 0) {
unset($settings[__('voyager::settings.group_general')]);
}
$groups_data = Voyager::model('Setting')->select('group')->distinct()->get();
$groups = [];
foreach ($groups_data as $group) {
if ($group->group != '') {
$groups[] = $group->group;
}
}
$active = (request()->session()->has('setting_tab')) ? request()->session()->get('setting_tab') : old('setting_tab', key($settings));
return Voyager::view('voyager::settings.index', compact('settings', 'groups', 'active'));
}
public function store(Request $request)
{
// Check permission
$this->authorize('add', Voyager::model('Setting'));
$key = implode('.', [Str::slug($request->input('group')), $request->input('key')]);
$key_check = Voyager::model('Setting')->where('key', $key)->get()->count();
if ($key_check > 0) {
return back()->with([
'message' => __('voyager::settings.key_already_exists', ['key' => $key]),
'alert-type' => 'error',
]);
}
$lastSetting = Voyager::model('Setting')->orderBy('order', 'DESC')->first();
if (is_null($lastSetting)) {
$order = 0;
} else {
$order = intval($lastSetting->order) + 1;
}
$request->merge(['order' => $order]);
$request->merge(['value' => '']);
$request->merge(['key' => $key]);
Voyager::model('Setting')->create($request->except('setting_tab'));
request()->flashOnly('setting_tab');
return back()->with([
'message' => __('voyager::settings.successfully_created'),
'alert-type' => 'success',
]);
}
public function update(Request $request)
{
// Check permission
$this->authorize('edit', Voyager::model('Setting'));
$settings = Voyager::model('Setting')->all();
foreach ($settings as $setting) {
$content = $this->getContentBasedOnType($request, 'settings', (object) [
'type' => $setting->type,
'field' => str_replace('.', '_', $setting->key),
'group' => $setting->group,
], $setting->details);
if ($setting->type == 'image' && $content == null) {
continue;
}
if ($setting->type == 'file' && $content == null) {
continue;
}
$key = preg_replace('/^'.Str::slug($setting->group).'./i', '', $setting->key);
$setting->group = $request->input(str_replace('.', '_', $setting->key).'_group');
$setting->key = implode('.', [Str::slug($setting->group), $key]);
$setting->value = $content;
$setting->save();
}
request()->flashOnly('setting_tab');
return back()->with([
'message' => __('voyager::settings.successfully_saved'),
'alert-type' => 'success',
]);
}
public function delete($id)
{
// Check permission
$this->authorize('delete', Voyager::model('Setting'));
$setting = Voyager::model('Setting')->find($id);
Voyager::model('Setting')->destroy($id);
request()->session()->flash('setting_tab', $setting->group);
return back()->with([
'message' => __('voyager::settings.successfully_deleted'),
'alert-type' => 'success',
]);
}
public function move_up($id)
{
// Check permission
$this->authorize('edit', Voyager::model('Setting'));
$setting = Voyager::model('Setting')->find($id);
// Check permission
$this->authorize('browse', $setting);
$swapOrder = $setting->order;
$previousSetting = Voyager::model('Setting')
->where('order', '<', $swapOrder)
->where('group', $setting->group)
->orderBy('order', 'DESC')->first();
$data = [
'message' => __('voyager::settings.already_at_top'),
'alert-type' => 'error',
];
if (isset($previousSetting->order)) {
$setting->order = $previousSetting->order;
$setting->save();
$previousSetting->order = $swapOrder;
$previousSetting->save();
$data = [
'message' => __('voyager::settings.moved_order_up', ['name' => $setting->display_name]),
'alert-type' => 'success',
];
}
request()->session()->flash('setting_tab', $setting->group);
return back()->with($data);
}
public function delete_value($id)
{
$setting = Voyager::model('Setting')->find($id);
// Check permission
$this->authorize('delete', $setting);
if (isset($setting->id)) {
// If the type is an image... Then delete it
if ($setting->type == 'image') {
if (Storage::disk(config('voyager.storage.disk'))->exists($setting->value)) {
Storage::disk(config('voyager.storage.disk'))->delete($setting->value);
}
}
$setting->value = '';
$setting->save();
}
request()->session()->flash('setting_tab', $setting->group);
return back()->with([
'message' => __('voyager::settings.successfully_removed', ['name' => $setting->display_name]),
'alert-type' => 'success',
]);
}
public function move_down($id)
{
// Check permission
$this->authorize('edit', Voyager::model('Setting'));
$setting = Voyager::model('Setting')->find($id);
// Check permission
$this->authorize('browse', $setting);
$swapOrder = $setting->order;
$previousSetting = Voyager::model('Setting')
->where('order', '>', $swapOrder)
->where('group', $setting->group)
->orderBy('order', 'ASC')->first();
$data = [
'message' => __('voyager::settings.already_at_bottom'),
'alert-type' => 'error',
];
if (isset($previousSetting->order)) {
$setting->order = $previousSetting->order;
$setting->save();
$previousSetting->order = $swapOrder;
$previousSetting->save();
$data = [
'message' => __('voyager::settings.moved_order_down', ['name' => $setting->display_name]),
'alert-type' => 'success',
];
}
request()->session()->flash('setting_tab', $setting->group);
return back()->with($data);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/Controller.php | src/Http/Controllers/Controller.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Storage;
use TCG\Voyager\Events\FileDeleted;
use TCG\Voyager\Http\Controllers\ContentTypes\Checkbox;
use TCG\Voyager\Http\Controllers\ContentTypes\Coordinates;
use TCG\Voyager\Http\Controllers\ContentTypes\File;
use TCG\Voyager\Http\Controllers\ContentTypes\Image as ContentImage;
use TCG\Voyager\Http\Controllers\ContentTypes\MultipleCheckbox;
use TCG\Voyager\Http\Controllers\ContentTypes\MultipleImage;
use TCG\Voyager\Http\Controllers\ContentTypes\Password;
use TCG\Voyager\Http\Controllers\ContentTypes\Relationship;
use TCG\Voyager\Http\Controllers\ContentTypes\SelectMultiple;
use TCG\Voyager\Http\Controllers\ContentTypes\Text;
use TCG\Voyager\Http\Controllers\ContentTypes\Timestamp;
use TCG\Voyager\Traits\AlertsMessages;
use Validator;
abstract class Controller extends BaseController
{
use DispatchesJobs;
use ValidatesRequests;
use AuthorizesRequests;
use AlertsMessages;
public function getSlug(Request $request)
{
if (isset($this->slug)) {
$slug = $this->slug;
} else {
$slug = explode('.', $request->route()->getName())[1];
}
return $slug;
}
public function insertUpdateData($request, $slug, $rows, $data)
{
$multi_select = [];
// Pass $rows so that we avoid checking unused fields
$request->attributes->add(['breadRows' => $rows->pluck('field')->toArray()]);
/*
* Prepare Translations and Transform data
*/
$translations = is_bread_translatable($data)
? $data->prepareTranslations($request)
: [];
foreach ($rows as $row) {
// if the field for this row is absent from the request, continue
// checkboxes will be absent when unchecked, thus they are the exception
if (!$request->hasFile($row->field) && !$request->has($row->field) && $row->type !== 'checkbox') {
// if the field is a belongsToMany relationship, don't remove it
// if no content is provided, that means the relationships need to be removed
if (isset($row->details->type) && $row->details->type !== 'belongsToMany') {
continue;
}
}
// Value is saved from $row->details->column row
if ($row->type == 'relationship' && $row->details->type == 'belongsTo') {
continue;
}
$content = $this->getContentBasedOnType($request, $slug, $row, $row->details);
if ($row->type == 'relationship' && $row->details->type != 'belongsToMany') {
$row->field = @$row->details->column;
}
/*
* merge ex_images/files and upload images/files
*/
if (in_array($row->type, ['multiple_images', 'file']) && !is_null($content)) {
if (isset($data->{$row->field})) {
$ex_files = json_decode($data->{$row->field}, true);
if (!is_null($ex_files)) {
$content = json_encode(array_merge($ex_files, json_decode($content)));
}
}
}
if (is_null($content)) {
// If the image upload is null and it has a current image keep the current image
if ($row->type == 'image' && is_null($request->input($row->field)) && isset($data->{$row->field})) {
$content = $data->{$row->field};
}
// If the multiple_images upload is null and it has a current image keep the current image
if ($row->type == 'multiple_images' && is_null($request->input($row->field)) && isset($data->{$row->field})) {
$content = $data->{$row->field};
}
// If the file upload is null and it has a current file keep the current file
if ($row->type == 'file') {
$content = $data->{$row->field};
if (!$content) {
$content = json_encode([]);
}
}
if ($row->type == 'password') {
$content = $data->{$row->field};
}
}
if ($row->type == 'relationship' && $row->details->type == 'belongsToMany') {
// Only if select_multiple is working with a relationship
$multi_select[] = [
'model' => $row->details->model,
'content' => $content,
'table' => $row->details->pivot_table,
'foreignPivotKey' => $row->details->foreign_pivot_key ?? null,
'relatedPivotKey' => $row->details->related_pivot_key ?? null,
'parentKey' => $row->details->parent_key ?? null,
'relatedKey' => $row->details->key,
];
} else {
$data->{$row->field} = $content;
}
}
if (isset($data->additional_attributes)) {
foreach ($data->additional_attributes as $attr) {
if ($request->has($attr)) {
$data->{$attr} = $request->{$attr};
}
}
}
$data->save();
// Save translations
if (count($translations) > 0) {
$data->saveTranslations($translations);
}
foreach ($multi_select as $sync_data) {
$data->belongsToMany(
$sync_data['model'],
$sync_data['table'],
$sync_data['foreignPivotKey'],
$sync_data['relatedPivotKey'],
$sync_data['parentKey'],
$sync_data['relatedKey']
)->sync($sync_data['content']);
}
// Rename folders for newly created data through media-picker
if ($request->session()->has($slug.'_path') || $request->session()->has($slug.'_uuid')) {
$old_path = $request->session()->get($slug.'_path');
$uuid = $request->session()->get($slug.'_uuid');
$new_path = str_replace($uuid, $data->getKey(), $old_path);
$folder_path = substr($old_path, 0, strpos($old_path, $uuid)).$uuid;
$rows->where('type', 'media_picker')->each(function ($row) use ($data, $uuid) {
$data->{$row->field} = str_replace($uuid, $data->getKey(), $data->{$row->field});
});
$data->save();
if ($old_path != $new_path &&
!Storage::disk(config('voyager.storage.disk'))->exists($new_path) &&
Storage::disk(config('voyager.storage.disk'))->exists($old_path)
)
{
$request->session()->forget([$slug.'_path', $slug.'_uuid']);
Storage::disk(config('voyager.storage.disk'))->move($old_path, $new_path);
Storage::disk(config('voyager.storage.disk'))->deleteDirectory($folder_path);
}
}
return $data;
}
/**
* Validates bread POST request.
*
* @param array $data The data
* @param array $rows The rows
* @param string $slug Slug
* @param int $id Id of the record to update
*
* @return mixed
*/
public function validateBread($data, $rows, $name = null, $id = null)
{
$rules = [];
$messages = [];
$customAttributes = [];
$is_update = $name && $id;
$fieldsWithValidationRules = $this->getFieldsWithValidationRules($rows);
foreach ($fieldsWithValidationRules as $field) {
$fieldRules = $field->details->validation->rule;
$fieldName = $field->field;
// Show the field's display name on the error message
if (!empty($field->display_name)) {
if (!empty($data[$fieldName]) && is_array($data[$fieldName])) {
foreach ($data[$fieldName] as $index => $element) {
if ($element instanceof UploadedFile) {
$name = $element->getClientOriginalName();
} else {
$name = $index + 1;
}
$customAttributes[$fieldName.'.'.$index] = $field->getTranslatedAttribute('display_name').' '.$name;
}
} else {
$customAttributes[$fieldName] = $field->getTranslatedAttribute('display_name');
}
}
// If field is an array apply rules to all array elements
$fieldName = !empty($data[$fieldName]) && is_array($data[$fieldName]) ? $fieldName.'.*' : $fieldName;
// Get the rules for the current field whatever the format it is in
$rules[$fieldName] = is_array($fieldRules) ? $fieldRules : explode('|', $fieldRules);
if ($id && property_exists($field->details->validation, 'edit')) {
$action_rules = $field->details->validation->edit->rule;
$rules[$fieldName] = array_merge($rules[$fieldName], (is_array($action_rules) ? $action_rules : explode('|', $action_rules)));
} elseif (!$id && property_exists($field->details->validation, 'add')) {
$action_rules = $field->details->validation->add->rule;
$rules[$fieldName] = array_merge($rules[$fieldName], (is_array($action_rules) ? $action_rules : explode('|', $action_rules)));
}
// Fix Unique validation rule on Edit Mode
if ($is_update) {
foreach ($rules[$fieldName] as &$fieldRule) {
if (strpos(strtoupper($fieldRule), 'UNIQUE') !== false) {
$fieldRule = \Illuminate\Validation\Rule::unique($name)->ignore($id);
}
}
}
// Set custom validation messages if any
if (!empty($field->details->validation->messages)) {
foreach ($field->details->validation->messages as $key => $msg) {
$messages["{$field->field}.{$key}"] = $msg;
}
}
}
return Validator::make($data, $rules, $messages, $customAttributes);
}
public function getContentBasedOnType(Request $request, $slug, $row, $options = null)
{
switch ($row->type) {
/********** PASSWORD TYPE **********/
case 'password':
return (new Password($request, $slug, $row, $options))->handle();
/********** CHECKBOX TYPE **********/
case 'checkbox':
return (new Checkbox($request, $slug, $row, $options))->handle();
/********** MULTIPLE CHECKBOX TYPE **********/
case 'multiple_checkbox':
return (new MultipleCheckbox($request, $slug, $row, $options))->handle();
/********** FILE TYPE **********/
case 'file':
return (new File($request, $slug, $row, $options))->handle();
/********** MULTIPLE IMAGES TYPE **********/
case 'multiple_images':
return (new MultipleImage($request, $slug, $row, $options))->handle();
/********** SELECT MULTIPLE TYPE **********/
case 'select_multiple':
return (new SelectMultiple($request, $slug, $row, $options))->handle();
/********** IMAGE TYPE **********/
case 'image':
return (new ContentImage($request, $slug, $row, $options))->handle();
/********** DATE TYPE **********/
case 'date':
/********** TIMESTAMP TYPE **********/
case 'timestamp':
return (new Timestamp($request, $slug, $row, $options))->handle();
/********** COORDINATES TYPE **********/
case 'coordinates':
return (new Coordinates($request, $slug, $row, $options))->handle();
/********** RELATIONSHIPS TYPE **********/
case 'relationship':
return (new Relationship($request, $slug, $row, $options))->handle();
/********** ALL OTHER TEXT TYPE **********/
default:
return (new Text($request, $slug, $row, $options))->handle();
}
}
public function deleteFileIfExists($path)
{
if ($path && Storage::disk(config('voyager.storage.disk'))->exists($path)) {
Storage::disk(config('voyager.storage.disk'))->delete($path);
event(new FileDeleted($path));
}
}
/**
* Get fields having validation rules in proper format.
*
* @param array $fieldsConfig
*
* @return \Illuminate\Support\Collection
*/
protected function getFieldsWithValidationRules($fieldsConfig)
{
return $fieldsConfig->filter(function ($value) {
if (empty($value->details)) {
return false;
}
return !empty($value->details->validation->rule);
});
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerBaseController.php | src/Http/Controllers/VoyagerBaseController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Exception;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use TCG\Voyager\Database\Schema\SchemaManager;
use TCG\Voyager\Events\BreadDataAdded;
use TCG\Voyager\Events\BreadDataDeleted;
use TCG\Voyager\Events\BreadDataRestored;
use TCG\Voyager\Events\BreadDataUpdated;
use TCG\Voyager\Events\BreadImagesDeleted;
use TCG\Voyager\Facades\Voyager;
use TCG\Voyager\Http\Controllers\Traits\BreadRelationshipParser;
class VoyagerBaseController extends Controller
{
use BreadRelationshipParser;
//***************************************
// ____
// | _ \
// | |_) |
// | _ <
// | |_) |
// |____/
//
// Browse our Data Type (B)READ
//
//****************************************
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = $this->getSlug($request);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('browse', app($dataType->model_name));
$getter = $dataType->server_side ? 'paginate' : 'get';
$search = (object) ['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name.'.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model)) && Auth::user()->can('delete', app($dataType->model_name))) {
$usesSoftDeletes = true;
if ($request->get('showSoftDeleted')) {
$showSoftDeleted = true;
$query = $query->withTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%'.$search->value.'%';
$searchField = $dataType->name.'.'.$search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name.'.*',
'joined.'.$row->details->label.' as '.$orderBy,
])->leftJoin(
$row->details->table.' as joined',
$dataType->name.'.'.$row->details->column,
'joined.'.$row->details->key
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT), $getter]);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC'), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
// Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.browse';
if (view()->exists("voyager::$slug.browse")) {
$view = "voyager::$slug.browse";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
//***************************************
// _____
// | __ \
// | |__) |
// | _ /
// | | \ \
// |_| \_\
//
// Read an item of our Data Type B(R)EAD
//
//****************************************
public function show(Request $request, $id)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
$isSoftDeleted = false;
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model->query();
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$query = $query->withTrashed();
}
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
$query = $query->{$dataType->scope}();
}
$dataTypeContent = call_user_func([$query, 'findOrFail'], $id);
if ($dataTypeContent->deleted_at) {
$isSoftDeleted = true;
}
} else {
// If Model doest exist, get data from table name
$dataTypeContent = DB::table($dataType->name)->where('id', $id)->first();
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType, true);
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'read');
// Check permission
$this->authorize('read', $dataTypeContent);
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($dataTypeContent);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'read', $isModelTranslatable);
$view = 'voyager::bread.read';
if (view()->exists("voyager::$slug.read")) {
$view = "voyager::$slug.read";
}
return Voyager::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable', 'isSoftDeleted'));
}
//***************************************
// ______
// | ____|
// | |__
// | __|
// | |____
// |______|
//
// Edit an item of our Data Type BR(E)AD
//
//****************************************
public function edit(Request $request, $id)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model->query();
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$query = $query->withTrashed();
}
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
$query = $query->{$dataType->scope}();
}
$dataTypeContent = call_user_func([$query, 'findOrFail'], $id);
} else {
// If Model doest exist, get data from table name
$dataTypeContent = DB::table($dataType->name)->where('id', $id)->first();
}
foreach ($dataType->editRows as $key => $row) {
$dataType->editRows[$key]['col_width'] = isset($row->details->width) ? $row->details->width : 100;
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'edit');
// Check permission
$this->authorize('edit', $dataTypeContent);
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($dataTypeContent);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'edit', $isModelTranslatable);
$view = 'voyager::bread.edit-add';
if (view()->exists("voyager::$slug.edit-add")) {
$view = "voyager::$slug.edit-add";
}
return Voyager::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable'));
}
// POST BR(E)AD
public function update(Request $request, $id)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Compatibility with Model binding.
$id = $id instanceof \Illuminate\Database\Eloquent\Model ? $id->{$id->getKeyName()} : $id;
$model = app($dataType->model_name);
$query = $model->query();
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
$query = $query->{$dataType->scope}();
}
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$query = $query->withTrashed();
}
$data = $query->findOrFail($id);
// Check permission
$this->authorize('edit', $data);
// Validate fields with ajax
$val = $this->validateBread($request->all(), $dataType->editRows, $dataType->name, $id)->validate();
// Get fields with images to remove before updating and make a copy of $data
$to_remove = $dataType->editRows->where('type', 'image')
->filter(function ($item, $key) use ($request) {
return $request->hasFile($item->field);
});
$original_data = clone($data);
$this->insertUpdateData($request, $slug, $dataType->editRows, $data);
// Delete Images
$this->deleteBreadImages($original_data, $to_remove);
event(new BreadDataUpdated($dataType, $data));
if (auth()->user()->can('browse', app($dataType->model_name))) {
$redirect = redirect()->route("voyager.{$dataType->slug}.index");
} else {
$redirect = redirect()->back();
}
return $redirect->with([
'message' => __('voyager::generic.successfully_updated')." {$dataType->getTranslatedAttribute('display_name_singular')}",
'alert-type' => 'success',
]);
}
//***************************************
//
// /\
// / \
// / /\ \
// / ____ \
// /_/ \_\
//
//
// Add a new item of our Data Type BRE(A)D
//
//****************************************
public function create(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('add', app($dataType->model_name));
$dataTypeContent = (strlen($dataType->model_name) != 0)
? new $dataType->model_name()
: false;
foreach ($dataType->addRows as $key => $row) {
$dataType->addRows[$key]['col_width'] = $row->details->width ?? 100;
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'add');
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($dataTypeContent);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'add', $isModelTranslatable);
$view = 'voyager::bread.edit-add';
if (view()->exists("voyager::$slug.edit-add")) {
$view = "voyager::$slug.edit-add";
}
return Voyager::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable'));
}
/**
* POST BRE(A)D - Store data.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('add', app($dataType->model_name));
// Validate fields with ajax
$val = $this->validateBread($request->all(), $dataType->addRows)->validate();
$data = $this->insertUpdateData($request, $slug, $dataType->addRows, new $dataType->model_name());
event(new BreadDataAdded($dataType, $data));
if (!$request->has('_tagging')) {
if (auth()->user()->can('browse', $data)) {
$redirect = redirect()->route("voyager.{$dataType->slug}.index");
} else {
$redirect = redirect()->back();
}
return $redirect->with([
'message' => __('voyager::generic.successfully_added_new')." {$dataType->getTranslatedAttribute('display_name_singular')}",
'alert-type' => 'success',
]);
} else {
return response()->json(['success' => true, 'data' => $data]);
}
}
//***************************************
// _____
// | __ \
// | | | |
// | | | |
// | |__| |
// |_____/
//
// Delete an item BREA(D)
//
//****************************************
public function destroy(Request $request, $id)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Init array of IDs
$ids = [];
if (empty($id)) {
// Bulk delete, get IDs from POST
$ids = explode(',', $request->ids);
} else {
// Single item delete, get ID from URL
$ids[] = $id;
}
$affected = 0;
foreach ($ids as $id) {
$data = call_user_func([$dataType->model_name, 'findOrFail'], $id);
// Check permission
$this->authorize('delete', $data);
$model = app($dataType->model_name);
if (!($model && in_array(SoftDeletes::class, class_uses_recursive($model)))) {
$this->cleanup($dataType, $data);
}
$res = $data->delete();
if ($res) {
$affected++;
event(new BreadDataDeleted($dataType, $data));
}
}
$displayName = $affected > 1 ? $dataType->getTranslatedAttribute('display_name_plural') : $dataType->getTranslatedAttribute('display_name_singular');
$data = $affected
? [
'message' => __('voyager::generic.successfully_deleted')." {$displayName}",
'alert-type' => 'success',
]
: [
'message' => __('voyager::generic.error_deleting')." {$displayName}",
'alert-type' => 'error',
];
return redirect()->route("voyager.{$dataType->slug}.index")->with($data);
}
public function restore(Request $request, $id)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$model = app($dataType->model_name);
$this->authorize('delete', $model);
// Get record
$query = $model->withTrashed();
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
$query = $query->{$dataType->scope}();
}
$data = $query->findOrFail($id);
$displayName = $dataType->getTranslatedAttribute('display_name_singular');
$res = $data->restore($id);
$data = $res
? [
'message' => __('voyager::generic.successfully_restored')." {$displayName}",
'alert-type' => 'success',
]
: [
'message' => __('voyager::generic.error_restoring')." {$displayName}",
'alert-type' => 'error',
];
if ($res) {
event(new BreadDataRestored($dataType, $data));
}
return redirect()->route("voyager.{$dataType->slug}.index")->with($data);
}
//***************************************
//
// Delete uploaded file
//
//****************************************
public function remove_media(Request $request)
{
try {
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = $request->get('slug');
// GET file name
$filename = $request->get('filename');
// GET record id
$id = $request->get('id');
// GET field name
$field = $request->get('field');
// GET multi value
$multi = $request->get('multi');
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Load model and find record
$model = app($dataType->model_name);
$data = $model::find([$id])->first();
// Check if field exists
if (!isset($data->{$field})) {
throw new Exception(__('voyager::generic.field_does_not_exist'), 400);
}
// Check permission
$this->authorize('edit', $data);
if (@json_decode($multi)) {
// Check if valid json
if (is_null(@json_decode($data->{$field}))) {
throw new Exception(__('voyager::json.invalid'), 500);
}
// Decode field value
$fieldData = @json_decode($data->{$field}, true);
$key = null;
// Check if we're dealing with a nested array for the case of multiple files
if (is_array($fieldData[0])) {
foreach ($fieldData as $index=>$file) {
// file type has a different structure than images
if (!empty($file['original_name'])) {
if ($file['original_name'] == $filename) {
$key = $index;
break;
}
} else {
$file = array_flip($file);
if (array_key_exists($filename, $file)) {
$key = $index;
break;
}
}
}
} else {
$key = array_search($filename, $fieldData);
}
// Check if file was found in array
if (is_null($key) || $key === false) {
throw new Exception(__('voyager::media.file_does_not_exist'), 400);
}
$fileToRemove = $fieldData[$key]['download_link'] ?? $fieldData[$key];
// Remove file from array
unset($fieldData[$key]);
// Generate json and update field
$data->{$field} = empty($fieldData) ? null : json_encode(array_values($fieldData));
} else {
if ($filename == $data->{$field}) {
$fileToRemove = $data->{$field};
$data->{$field} = null;
} else {
throw new Exception(__('voyager::media.file_does_not_exist'), 400);
}
}
$row = $dataType->rows->where('field', $field)->first();
// Remove file from filesystem
if (in_array($row->type, ['image', 'multiple_images'])) {
$this->deleteBreadImages($data, [$row], $fileToRemove);
} else {
$this->deleteFileIfExists($fileToRemove);
}
$data->save();
return response()->json([
'data' => [
'status' => 200,
'message' => __('voyager::media.file_removed'),
],
]);
} catch (Exception $e) {
$code = 500;
$message = __('voyager::generic.internal_error');
if ($e->getCode()) {
$code = $e->getCode();
}
if ($e->getMessage()) {
$message = $e->getMessage();
}
return response()->json([
'data' => [
'status' => $code,
'message' => $message,
],
], $code);
}
}
/**
* Remove translations, images and files related to a BREAD item.
*
* @param \Illuminate\Database\Eloquent\Model $dataType
* @param \Illuminate\Database\Eloquent\Model $data
*
* @return void
*/
protected function cleanup($dataType, $data)
{
// Delete Translations, if present
if (is_bread_translatable($data)) {
$data->deleteAttributeTranslations($data->getTranslatableAttributes());
}
// Delete Images
$this->deleteBreadImages($data, $dataType->deleteRows->whereIn('type', ['image', 'multiple_images']));
// Delete Files
foreach ($dataType->deleteRows->where('type', 'file') as $row) {
if (isset($data->{$row->field})) {
foreach (json_decode($data->{$row->field}) as $file) {
$this->deleteFileIfExists($file->download_link);
}
}
}
// Delete media-picker files
$dataType->rows->where('type', 'media_picker')->where('details.delete_files', true)->each(function ($row) use ($data) {
$content = $data->{$row->field};
if (isset($content)) {
if (!is_array($content)) {
$content = json_decode($content);
}
if (is_array($content)) {
foreach ($content as $file) {
$this->deleteFileIfExists($file);
}
} else {
$this->deleteFileIfExists($content);
}
}
});
}
/**
* Delete all images related to a BREAD item.
*
* @param \Illuminate\Database\Eloquent\Model $data
* @param \Illuminate\Database\Eloquent\Model $rows
*
* @return void
*/
public function deleteBreadImages($data, $rows, $single_image = null)
{
$imagesDeleted = false;
foreach ($rows as $row) {
if ($row->type == 'multiple_images') {
$images_to_remove = json_decode($data->getOriginal($row->field), true) ?? [];
} else {
$images_to_remove = [$data->getOriginal($row->field)];
}
foreach ($images_to_remove as $image) {
// Remove only $single_image if we are removing from bread edit
if ($image != config('voyager.user.default_avatar') && (is_null($single_image) || $single_image == $image)) {
$this->deleteFileIfExists($image);
$imagesDeleted = true;
if (isset($row->details->thumbnails)) {
foreach ($row->details->thumbnails as $thumbnail) {
$ext = explode('.', $image);
$extension = '.'.$ext[count($ext) - 1];
$path = str_replace($extension, '', $image);
$thumb_name = $thumbnail->name;
$this->deleteFileIfExists($path.'-'.$thumb_name.$extension);
}
}
}
}
}
if ($imagesDeleted) {
event(new BreadImagesDeleted($data, $rows));
}
}
/**
* Order BREAD items.
*
* @param string $table
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function order(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('edit', app($dataType->model_name));
if (empty($dataType->order_column) || empty($dataType->order_display_column)) {
return redirect()
->route("voyager.{$dataType->slug}.index")
->with([
'message' => __('voyager::bread.ordering_not_set'),
'alert-type' => 'error',
]);
}
$model = app($dataType->model_name);
$query = $model->query();
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$query = $query->withTrashed();
}
$results = $query->orderBy($dataType->order_column, $dataType->order_direction)->get();
$display_column = $dataType->order_display_column;
$dataRow = Voyager::model('DataRow')->whereDataTypeId($dataType->id)->whereField($display_column)->first();
$view = 'voyager::bread.order';
if (view()->exists("voyager::$slug.order")) {
$view = "voyager::$slug.order";
}
return Voyager::view($view, compact(
'dataType',
'display_column',
'dataRow',
'results'
));
}
public function update_order(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('edit', app($dataType->model_name));
$model = app($dataType->model_name);
$order = json_decode($request->input('order'));
$column = $dataType->order_column;
foreach ($order as $key => $item) {
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$i = $model->withTrashed()->findOrFail($item->id);
} else {
$i = $model->findOrFail($item->id);
}
$i->$column = ($key + 1);
$i->save();
}
}
public function action(Request $request)
{
if (!$request->action || !class_exists($request->action)) {
throw new \Exception("Action {$request->action} doesn't exist or has not been defined");
}
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
$action = new $request->action($dataType, null);
return $action->massAction(explode(',', $request->ids), $request->headers->get('referer'));
}
/**
* Get BREAD relations data.
*
* @param Request $request
*
* @return mixed
*/
public function relation(Request $request)
{
$slug = $this->getSlug($request);
$page = $request->input('page');
$on_page = 50;
$search = $request->input('search', false);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
$method = $request->input('method', 'add');
$model = app($dataType->model_name);
if ($method != 'add') {
$model = $model->find($request->input('id'));
}
$this->authorize($method, $model);
$rows = $dataType->{$method.'Rows'};
foreach ($rows as $key => $row) {
if ($row->field === $request->input('type')) {
$options = $row->details;
$model = app($options->model);
$skip = $on_page * ($page - 1);
$additional_attributes = $model->additional_attributes ?? [];
// Apply local scope if it is defined in the relationship-options
if (isset($options->scope) && $options->scope != '' && method_exists($model, 'scope'.ucfirst($options->scope))) {
$model = $model->{$options->scope}();
}
// If search query, use LIKE to filter results depending on field label
if ($search) {
// If we are using additional_attribute as label
if (in_array($options->label, $additional_attributes)) {
$relationshipOptions = $model;
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | true |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerRoleController.php | src/Http/Controllers/VoyagerRoleController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Illuminate\Http\Request;
use TCG\Voyager\Facades\Voyager;
class VoyagerRoleController extends VoyagerBaseController
{
// POST BR(E)AD
public function update(Request $request, $id)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('edit', app($dataType->model_name));
//Validate fields
$val = $this->validateBread($request->all(), $dataType->editRows, $dataType->name, $id)->validate();
$data = call_user_func([$dataType->model_name, 'findOrFail'], $id);
$this->insertUpdateData($request, $slug, $dataType->editRows, $data);
$data->permissions()->sync($request->input('permissions', []));
return redirect()
->route("voyager.{$dataType->slug}.index")
->with([
'message' => __('voyager::generic.successfully_updated')." {$dataType->getTranslatedAttribute('display_name_singular')}",
'alert-type' => 'success',
]);
}
// POST BRE(A)D
public function store(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('add', app($dataType->model_name));
//Validate fields
$val = $this->validateBread($request->all(), $dataType->addRows)->validate();
$data = new $dataType->model_name();
$this->insertUpdateData($request, $slug, $dataType->addRows, $data);
$data->permissions()->sync($request->input('permissions', []));
return redirect()
->route("voyager.{$dataType->slug}.index")
->with([
'message' => __('voyager::generic.successfully_added_new')." {$dataType->getTranslatedAttribute('display_name_singular')}",
'alert-type' => 'success',
]);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerBreadController.php | src/Http/Controllers/VoyagerBreadController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use ReflectionClass;
use TCG\Voyager\Database\Schema\SchemaManager;
use TCG\Voyager\Database\Schema\Table;
use TCG\Voyager\Database\Types\Type;
use TCG\Voyager\Events\BreadAdded;
use TCG\Voyager\Events\BreadDeleted;
use TCG\Voyager\Events\BreadUpdated;
use TCG\Voyager\Facades\Voyager;
class VoyagerBreadController extends Controller
{
public function index()
{
$this->authorize('browse_bread');
$dataTypes = Voyager::model('DataType')->select('id', 'name', 'slug')->get()->keyBy('name')->toArray();
$tables = array_map(function ($table) use ($dataTypes) {
$table = Str::replaceFirst(DB::getTablePrefix(), '', $table);
$table = [
'prefix' => DB::getTablePrefix(),
'name' => $table,
'slug' => $dataTypes[$table]['slug'] ?? null,
'dataTypeId' => $dataTypes[$table]['id'] ?? null,
];
return (object) $table;
}, SchemaManager::listTableNames());
return Voyager::view('voyager::tools.bread.index')->with(compact('dataTypes', 'tables'));
}
/**
* Create BREAD.
*
* @param Request $request
* @param string $table Table name.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function create(Request $request, $table)
{
$this->authorize('browse_bread');
$dataType = Voyager::model('DataType')->whereName($table)->first();
$data = $this->prepopulateBreadInfo($table);
$data['fieldOptions'] = SchemaManager::describeTable(
(isset($dataType) && strlen($dataType->model_name) != 0)
? DB::getTablePrefix().app($dataType->model_name)->getTable()
: DB::getTablePrefix().$table
);
return Voyager::view('voyager::tools.bread.edit-add', $data);
}
private function prepopulateBreadInfo($table)
{
$displayName = Str::singular(implode(' ', explode('_', Str::title($table))));
$modelNamespace = config('voyager.models.namespace', app()->getNamespace());
if (empty($modelNamespace)) {
$modelNamespace = app()->getNamespace();
}
return [
'isModelTranslatable' => true,
'table' => $table,
'slug' => Str::slug($table),
'display_name' => $displayName,
'display_name_plural' => Str::plural($displayName),
'model_name' => $modelNamespace.Str::studly(Str::singular($table)),
'generate_permissions' => true,
'server_side' => false,
];
}
/**
* Store BREAD.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request)
{
$this->authorize('browse_bread');
try {
$dataType = Voyager::model('DataType');
$res = $dataType->updateDataType($request->all(), true);
$data = $res
? $this->alertSuccess(__('voyager::bread.success_created_bread'))
: $this->alertError(__('voyager::bread.error_creating_bread'));
if ($res) {
event(new BreadAdded($dataType, $data));
}
return redirect()->route('voyager.bread.index')->with($data);
} catch (Exception $e) {
return redirect()->route('voyager.bread.index')->with($this->alertException($e, 'Saving Failed'));
}
}
/**
* Edit BREAD.
*
* @param string $table
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit($table)
{
$this->authorize('browse_bread');
$dataType = Voyager::model('DataType')->whereName($table)->first();
$fieldOptions = SchemaManager::describeTable(
(strlen($dataType->model_name) != 0)
? DB::getTablePrefix().app($dataType->model_name)->getTable()
: DB::getTablePrefix().$dataType->name
);
$isModelTranslatable = is_bread_translatable($dataType);
$tables = SchemaManager::listTableNames();
$dataTypeRelationships = Voyager::model('DataRow')->where('data_type_id', '=', $dataType->id)->where('type', '=', 'relationship')->get();
$scopes = [];
if ($dataType->model_name != '') {
$scopes = $this->getModelScopes($dataType->model_name);
}
return Voyager::view('voyager::tools.bread.edit-add', compact('dataType', 'fieldOptions', 'isModelTranslatable', 'tables', 'dataTypeRelationships', 'scopes'));
}
/**
* Update BREAD.
*
* @param \Illuminate\Http\Request $request
* @param number $id
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function update(Request $request, $id)
{
$this->authorize('browse_bread');
/* @var \TCG\Voyager\Models\DataType $dataType */
try {
$dataType = Voyager::model('DataType')->find($id);
// Prepare Translations and Transform data
$translations = is_bread_translatable($dataType)
? $dataType->prepareTranslations($request)
: [];
$res = $dataType->updateDataType($request->all(), true);
$data = $res
? $this->alertSuccess(__('voyager::bread.success_update_bread', ['datatype' => $dataType->name]))
: $this->alertError(__('voyager::bread.error_updating_bread'));
if ($res) {
event(new BreadUpdated($dataType, $data));
}
// Save translations if applied
$dataType->saveTranslations($translations);
return redirect()->route('voyager.bread.index')->with($data);
} catch (Exception $e) {
return back()->with($this->alertException($e, __('voyager::generic.update_failed')));
}
}
/**
* Delete BREAD.
*
* @param Number $id BREAD data_type id.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($id)
{
$this->authorize('browse_bread');
/* @var \TCG\Voyager\Models\DataType $dataType */
$dataType = Voyager::model('DataType')->find($id);
// Delete Translations, if present
if (is_bread_translatable($dataType)) {
$dataType->deleteAttributeTranslations($dataType->getTranslatableAttributes());
}
$res = Voyager::model('DataType')->destroy($id);
$data = $res
? $this->alertSuccess(__('voyager::bread.success_remove_bread', ['datatype' => $dataType->name]))
: $this->alertError(__('voyager::bread.error_updating_bread'));
if ($res) {
event(new BreadDeleted($dataType, $data));
}
if (!is_null($dataType)) {
Voyager::model('Permission')->removeFrom($dataType->name);
}
return redirect()->route('voyager.bread.index')->with($data);
}
public function getModelScopes($model_name)
{
$reflection = new ReflectionClass($model_name);
return collect($reflection->getMethods())->filter(function ($method) {
return Str::startsWith($method->name, 'scope');
})->whereNotIn('name', ['scopeWithTranslations', 'scopeWithTranslation', 'scopeWhereTranslation'])->transform(function ($method) {
return lcfirst(Str::replaceFirst('scope', '', $method->name));
});
}
// ************************************************************
// _____ _ _ _ _ _
// | __ \ | | | | (_) | | (_)
// | |__) |___| | __ _| |_ _ ___ _ __ ___| |__ _ _ __ ___
// | _ // _ \ |/ _` | __| |/ _ \| '_ \/ __| '_ \| | '_ \/ __|
// | | \ \ __/ | (_| | |_| | (_) | | | \__ \ | | | | |_) \__ \
// |_| \_\___|_|\__,_|\__|_|\___/|_| |_|___/_| |_|_| .__/|___/
// | |
// |_|
// ************************************************************
/**
* Add Relationship.
*
* @param Request $request
*/
public function addRelationship(Request $request)
{
$relationshipField = $this->getRelationshipField($request);
if (!class_exists($request->relationship_model)) {
return back()->with([
'message' => 'Model Class '.$request->relationship_model.' does not exist. Please create Model before creating relationship.',
'alert-type' => 'error',
]);
}
try {
DB::beginTransaction();
$relationship_column = $request->relationship_column_belongs_to;
if ($request->relationship_type == 'hasOne' || $request->relationship_type == 'hasMany') {
$relationship_column = $request->relationship_column;
}
// Build the relationship details
$relationshipDetails = [
'model' => $request->relationship_model,
'table' => $request->relationship_table,
'type' => $request->relationship_type,
'column' => $relationship_column,
'key' => $request->relationship_key,
'label' => $request->relationship_label,
'pivot_table' => $request->relationship_pivot,
'pivot' => ($request->relationship_type == 'belongsToMany') ? '1' : '0',
'taggable' => $request->relationship_taggable,
];
$className = Voyager::modelClass('DataRow');
$newRow = new $className();
$newRow->data_type_id = $request->data_type_id;
$newRow->field = $relationshipField;
$newRow->type = 'relationship';
$newRow->display_name = $request->relationship_table;
$newRow->required = 0;
foreach (['browse', 'read', 'edit', 'add', 'delete'] as $check) {
$newRow->{$check} = 1;
}
$newRow->details = $relationshipDetails;
$newRow->order = intval(Voyager::model('DataType')->find($request->data_type_id)->lastRow()->order) + 1;
if (!$newRow->save()) {
return back()->with([
'message' => 'Error saving new relationship row for '.$request->relationship_table,
'alert-type' => 'error',
]);
}
DB::commit();
return back()->with([
'message' => 'Successfully created new relationship for '.$request->relationship_table,
'alert-type' => 'success',
]);
} catch (\Exception $e) {
DB::rollBack();
return back()->with([
'message' => 'Error creating new relationship: '.$e->getMessage(),
'alert-type' => 'error',
]);
}
}
/**
* Get Relationship Field.
*
* @param Request $request
*
* @return string
*/
private function getRelationshipField($request)
{
// We need to make sure that we aren't creating an already existing field
$dataType = Voyager::model('DataType')->find($request->data_type_id);
$field = Str::singular($dataType->name).'_'.$request->relationship_type.'_'.Str::singular($request->relationship_table).'_relationship';
$relationshipFieldOriginal = $relationshipField = strtolower($field);
$existingRow = Voyager::model('DataRow')->where('field', '=', $relationshipField)->first();
$index = 1;
while (isset($existingRow->id)) {
$relationshipField = $relationshipFieldOriginal.'_'.$index;
$existingRow = Voyager::model('DataRow')->where('field', '=', $relationshipField)->first();
$index += 1;
}
return $relationshipField;
}
/**
* Delete Relationship.
*
* @param Number $id Record id
*
* @return \Illuminate\Http\RedirectResponse
*/
public function deleteRelationship($id)
{
Voyager::model('DataRow')->destroy($id);
return back()->with([
'message' => 'Successfully deleted relationship.',
'alert-type' => 'success',
]);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerDatabaseController.php | src/Http/Controllers/VoyagerDatabaseController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use TCG\Voyager\Database\DatabaseUpdater;
use TCG\Voyager\Database\Schema\Column;
use TCG\Voyager\Database\Schema\Identifier;
use TCG\Voyager\Database\Schema\SchemaManager;
use TCG\Voyager\Database\Schema\Table;
use TCG\Voyager\Database\Types\Type;
use TCG\Voyager\Events\TableAdded;
use TCG\Voyager\Events\TableDeleted;
use TCG\Voyager\Events\TableUpdated;
use TCG\Voyager\Facades\Voyager;
class VoyagerDatabaseController extends Controller
{
public function index()
{
$this->authorize('browse_database');
$dataTypes = Voyager::model('DataType')->select('id', 'name', 'slug')->get()->keyBy('name')->toArray();
$tables = array_map(function ($table) use ($dataTypes) {
$table = Str::replaceFirst(DB::getTablePrefix(), '', $table);
$table = [
'prefix' => DB::getTablePrefix(),
'name' => $table,
'slug' => $dataTypes[$table]['slug'] ?? null,
'dataTypeId' => $dataTypes[$table]['id'] ?? null,
];
return (object) $table;
}, SchemaManager::listTableNames());
return Voyager::view('voyager::tools.database.index')->with(compact('dataTypes', 'tables'));
}
/**
* Create database table.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function create()
{
$this->authorize('browse_database');
$db = $this->prepareDbManager('create');
return Voyager::view('voyager::tools.database.edit-add', compact('db'));
}
/**
* Store new database table.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request)
{
$this->authorize('browse_database');
try {
$conn = 'database.connections.'.config('database.default');
Type::registerCustomPlatformTypes();
$table = $request->table;
if (!is_array($request->table)) {
$table = json_decode($request->table, true);
}
$table['options']['collate'] = config($conn.'.collation', 'utf8mb4_unicode_ci');
$table['options']['charset'] = config($conn.'.charset', 'utf8mb4');
$table = Table::make($table);
SchemaManager::createTable($table);
if (isset($request->create_model) && $request->create_model == 'on') {
$modelNamespace = config('voyager.models.namespace', app()->getNamespace());
$params = [
'name' => $modelNamespace.Str::studly(Str::singular($table->name)),
];
// if (in_array('deleted_at', $request->input('field.*'))) {
// $params['--softdelete'] = true;
// }
if (isset($request->create_migration) && $request->create_migration == 'on') {
$params['--migration'] = true;
}
Artisan::call('voyager:make:model', $params);
} elseif (isset($request->create_migration) && $request->create_migration == 'on') {
Artisan::call('make:migration', [
'name' => 'create_'.$table->name.'_table',
'--table' => $table->name,
]);
}
event(new TableAdded($table));
return redirect()
->route('voyager.database.index')
->with($this->alertSuccess(__('voyager::database.success_create_table', ['table' => $table->name])));
} catch (Exception $e) {
return back()->with($this->alertException($e))->withInput();
}
}
/**
* Edit database table.
*
* @param string $table
*
* @return \Illuminate\Http\RedirectResponse
*/
public function edit($table)
{
$this->authorize('browse_database');
if (!SchemaManager::tableExists($table)) {
return redirect()
->route('voyager.database.index')
->with($this->alertError(__('voyager::database.edit_table_not_exist')));
}
$db = $this->prepareDbManager('update', $table);
return Voyager::view('voyager::tools.database.edit-add', compact('db'));
}
/**
* Update database table.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\RedirectResponse
*/
public function update(Request $request)
{
$this->authorize('browse_database');
$table = json_decode($request->table, true);
try {
DatabaseUpdater::update($table);
// TODO: synch BREAD with Table
// $this->cleanOldAndCreateNew($request->original_name, $request->name);
event(new TableUpdated($table));
} catch (Exception $e) {
return back()->with($this->alertException($e))->withInput();
}
return redirect()
->route('voyager.database.index')
->with($this->alertSuccess(__('voyager::database.success_create_table', ['table' => $table['name']])));
}
protected function prepareDbManager($action, $table = '')
{
$db = new \stdClass();
// Need to get the types first to register custom types
$db->types = Type::getPlatformTypes();
if ($action == 'update') {
$db->table = SchemaManager::listTableDetails($table);
$db->formAction = route('voyager.database.update', $table);
} else {
$db->table = new Table('New Table');
// Add prefilled columns
$db->table->addColumn('id', 'integer', [
'unsigned' => true,
'notnull' => true,
'autoincrement' => true,
]);
$db->table->setPrimaryKey(['id'], 'primary');
$db->formAction = route('voyager.database.store');
}
$oldTable = old('table');
$db->oldTable = $oldTable ? $oldTable : json_encode(null);
$db->action = $action;
$db->identifierRegex = Identifier::REGEX;
$db->platform = SchemaManager::getDatabasePlatform()->getName();
return $db;
}
public function cleanOldAndCreateNew($originalName, $tableName)
{
if (!empty($originalName) && $originalName != $tableName) {
$dt = DB::table('data_types')->where('name', $originalName);
if ($dt->get()) {
$dt->delete();
}
$perm = DB::table('permissions')->where('table_name', $originalName);
if ($perm->get()) {
$perm->delete();
}
$params = ['name' => Str::studly(Str::singular($tableName))];
Artisan::call('voyager:make:model', $params);
}
}
public function reorder_column(Request $request)
{
$this->authorize('browse_database');
if ($request->ajax()) {
$table = $request->table;
$column = $request->column;
$after = $request->after;
if ($after == null) {
// SET COLUMN TO THE TOP
DB::query("ALTER $table MyTable CHANGE COLUMN $column FIRST");
}
return 1;
}
return 0;
}
/**
* Show table.
*
* @param string $table
*
* @return JSON
*/
public function show($table)
{
$this->authorize('browse_database');
$additional_attributes = [];
$model_name = Voyager::model('DataType')->where('name', $table)->pluck('model_name')->first();
if (isset($model_name)) {
$model = app($model_name);
if (isset($model->additional_attributes)) {
foreach ($model->additional_attributes as $attribute) {
$additional_attributes[$attribute] = [];
}
}
}
return response()->json(collect(SchemaManager::describeTable($table))->merge($additional_attributes));
}
/**
* Destroy table.
*
* @param string $table
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($table)
{
$this->authorize('browse_database');
try {
SchemaManager::dropTable($table);
event(new TableDeleted($table));
return redirect()
->route('voyager.database.index')
->with($this->alertSuccess(__('voyager::database.success_delete_table', ['table' => $table])));
} catch (Exception $e) {
return back()->with($this->alertException($e));
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/VoyagerMediaController.php | src/Http/Controllers/VoyagerMediaController.php | <?php
namespace TCG\Voyager\Http\Controllers;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use TCG\Voyager\Events\MediaFileAdded;
use TCG\Voyager\Facades\Voyager;
class VoyagerMediaController extends Controller
{
/** @var string */
private $filesystem;
/** @var string */
private $directory = '';
public function __construct()
{
$this->filesystem = config('voyager.storage.disk');
}
public function index()
{
// Check permission
$this->authorize('browse_media');
return Voyager::view('voyager::media.index');
}
public function files(Request $request)
{
// Check permission
$this->authorize('browse_media');
$options = $request->details ?? [];
$thumbnail_names = [];
$thumbnails = [];
if (!($options->hide_thumbnails ?? false)) {
$thumbnail_names = array_column(($options['thumbnails'] ?? []), 'name');
}
$folder = $request->folder;
if ($folder == '/') {
$folder = '';
}
$dir = $this->directory.$folder;
$files = [];
if (class_exists(\League\Flysystem\Plugin\ListWith::class)) {
$storage = Storage::disk($this->filesystem)->addPlugin(new \League\Flysystem\Plugin\ListWith());
$storageItems = $storage->listWith(['mimetype'], $dir);
} else {
$storage = Storage::disk($this->filesystem);
$storageItems = $storage->listContents($dir)->sortByPath()->toArray();
}
foreach ($storageItems as $item) {
if ($item['type'] == 'dir') {
$files[] = [
'name' => $item['basename'] ?? basename($item['path']),
'type' => 'folder',
'path' => Storage::disk($this->filesystem)->url($item['path']),
'relative_path' => $item['path'],
'items' => '',
'last_modified' => '',
];
} else {
if (empty(pathinfo($item['path'], PATHINFO_FILENAME)) && !config('voyager.hidden_files')) {
continue;
}
// Its a thumbnail and thumbnails should be hidden
if (Str::endsWith($item['path'], $thumbnail_names)) {
$thumbnails[] = $item;
continue;
}
$mime = 'file';
if (class_exists(\League\MimeTypeDetection\ExtensionMimeTypeDetector::class)) {
$mime = (new \League\MimeTypeDetection\ExtensionMimeTypeDetector())->detectMimeTypeFromFile($item['path']);
}
$files[] = [
'name' => $item['basename'] ?? basename($item['path']),
'filename' => $item['filename'] ?? basename($item['path'], '.'.pathinfo($item['path'])['extension']),
'type' => $item['mimetype'] ?? $mime,
'path' => Storage::disk($this->filesystem)->url($item['path']),
'relative_path' => $item['path'],
'size' => $item['size'] ?? $item->fileSize(),
'last_modified' => $item['timestamp'] ?? $item->lastModified(),
'thumbnails' => [],
];
}
}
foreach ($files as $key => $file) {
foreach ($thumbnails as $thumbnail) {
if ($file['type'] != 'folder' && Str::startsWith($thumbnail['filename'], $file['filename'])) {
$thumbnail['thumb_name'] = str_replace($file['filename'].'-', '', $thumbnail['filename']);
$thumbnail['path'] = Storage::disk($this->filesystem)->url($thumbnail['path']);
$files[$key]['thumbnails'][] = $thumbnail;
}
}
}
return response()->json($files);
}
public function new_folder(Request $request)
{
// Check permission
$this->authorize('browse_media');
$new_folder = $request->new_folder;
$success = false;
$error = '';
if (Storage::disk($this->filesystem)->exists($new_folder)) {
$error = __('voyager::media.folder_exists_already');
} elseif (Storage::disk($this->filesystem)->makeDirectory($new_folder)) {
$success = true;
} else {
$error = __('voyager::media.error_creating_dir');
}
return compact('success', 'error');
}
public function delete(Request $request)
{
// Check permission
$this->authorize('browse_media');
$path = str_replace('//', '/', Str::finish($request->path, '/'));
$success = true;
$error = '';
foreach ($request->get('files') as $file) {
$file_path = $path.$file['name'];
if ($file['type'] == 'folder') {
if (!Storage::disk($this->filesystem)->deleteDirectory($file_path)) {
$error = __('voyager::media.error_deleting_folder');
$success = false;
}
} elseif (!Storage::disk($this->filesystem)->delete($file_path)) {
$error = __('voyager::media.error_deleting_file');
$success = false;
}
}
return compact('success', 'error');
}
public function move(Request $request)
{
// Check permission
$this->authorize('browse_media');
$path = str_replace('//', '/', Str::finish($request->path, '/'));
$dest = str_replace('//', '/', Str::finish($request->destination, '/'));
if (strpos($dest, '/../') !== false) {
$dest = substr($path, 0, -1);
$dest = substr($dest, 0, strripos($dest, '/') + 1);
}
$dest = str_replace('//', '/', Str::finish($dest, '/'));
$success = true;
$error = '';
foreach ($request->get('files') as $file) {
$old_path = $path.$file['name'];
$new_path = $dest.$file['name'];
try {
Storage::disk($this->filesystem)->move($old_path, $new_path);
} catch (\Exception $ex) {
$success = false;
$error = $ex->getMessage();
return compact('success', 'error');
}
}
return compact('success', 'error');
}
public function rename(Request $request)
{
// Check permission
$this->authorize('browse_media');
$folderLocation = $request->folder_location;
$filename = $request->filename;
$newFilename = $request->new_filename;
$success = false;
$error = false;
if (pathinfo($filename)['extension'] !== pathinfo($newFilename)['extension']) {
$error = __('voyager::media.error_renaming_ext');
} else {
if (is_array($folderLocation)) {
$folderLocation = rtrim(implode('/', $folderLocation), '/');
}
$location = "{$this->directory}/{$folderLocation}";
if (!Storage::disk($this->filesystem)->exists("{$location}/{$newFilename}")) {
if (Storage::disk($this->filesystem)->move("{$location}/{$filename}", "{$location}/{$newFilename}")) {
$success = true;
} else {
$error = __('voyager::media.error_moving');
}
} else {
$error = __('voyager::media.error_may_exist');
}
}
return compact('success', 'error');
}
public function upload(Request $request)
{
// Check permission
$this->authorize('browse_media');
$extension = $request->file->getClientOriginalExtension();
$name = Str::replaceLast('.'.$extension, '', $request->file->getClientOriginalName());
$details = json_decode($request->get('details') ?? '{}');
$absolute_path = Storage::disk($this->filesystem)->path($request->upload_path);
try {
$realPath = Storage::disk($this->filesystem)->path('/');
$allowedMimeTypes = config('voyager.media.allowed_mimetypes', '*');
if ($allowedMimeTypes != '*' && (is_array($allowedMimeTypes) && !in_array($request->file->getMimeType(), $allowedMimeTypes))) {
throw new Exception(__('voyager::generic.mimetype_not_allowed'));
}
if (!$request->has('filename') || $request->get('filename') == 'null') {
while (Storage::disk($this->filesystem)->exists(Str::finish($request->upload_path, '/').$name.'.'.$extension, $this->filesystem)) {
$name = get_file_name($name);
}
} else {
$name = str_replace('{uid}', Auth::user()->getKey(), $request->get('filename'));
if (Str::contains($name, '{date:')) {
$name = preg_replace_callback('/\{date:([^\/\}]*)\}/', function ($date) {
return \Carbon\Carbon::now()->format($date[1]);
}, $name);
}
if (Str::contains($name, '{random:')) {
$name = preg_replace_callback('/\{random:([0-9]+)\}/', function ($random) {
return Str::random($random[1]);
}, $name);
}
}
$file = $request->file->storeAs($request->upload_path, $name.'.'.$extension, $this->filesystem);
$file = preg_replace('#/+#', '/', $file);
$imageMimeTypes = [
'image/jpeg',
'image/png',
'image/gif',
'image/bmp',
'image/svg+xml',
];
if (in_array($request->file->getMimeType(), $imageMimeTypes)) {
$content = Storage::disk($this->filesystem)->get($file);
$image = Image::make($content);
if ($request->file->getClientOriginalExtension() == 'gif') {
copy($request->file->getRealPath(), $realPath.$file);
} else {
$image = $image->orientate();
// Generate thumbnails
if (property_exists($details, 'thumbnails') && is_array($details->thumbnails)) {
foreach ($details->thumbnails as $thumbnail_data) {
$type = $thumbnail_data->type ?? 'fit';
$thumbnail = Image::make(clone $image);
if ($type == 'fit') {
$thumbnail = $thumbnail->fit(
$thumbnail_data->width,
($thumbnail_data->height ?? null),
function ($constraint) {
$constraint->aspectRatio();
},
($thumbnail_data->position ?? 'center')
);
} elseif ($type == 'crop') {
$thumbnail = $thumbnail->crop(
$thumbnail_data->width,
$thumbnail_data->height,
($thumbnail_data->x ?? null),
($thumbnail_data->y ?? null)
);
} elseif ($type == 'resize') {
$thumbnail = $thumbnail->resize(
$thumbnail_data->width,
($thumbnail_data->height ?? null),
function ($constraint) use ($thumbnail_data) {
$constraint->aspectRatio();
if (!($thumbnail_data->upsize ?? true)) {
$constraint->upsize();
}
}
);
}
if (
property_exists($details, 'watermark') &&
property_exists($details->watermark, 'source') &&
property_exists($thumbnail_data, 'watermark') &&
$thumbnail_data->watermark
) {
$thumbnail = $this->addWatermarkToImage($thumbnail, $details->watermark);
}
$thumbnail_file = $request->upload_path.$name.'-'.($thumbnail_data->name ?? 'thumbnail').'.'.$extension;
Storage::disk($this->filesystem)->put($thumbnail_file, $thumbnail->encode($extension, ($details->quality ?? 90))->encoded);
}
}
// Add watermark to image
if (property_exists($details, 'watermark') && property_exists($details->watermark, 'source')) {
$image = $this->addWatermarkToImage($image, $details->watermark);
}
Storage::disk($this->filesystem)->put($file, $image->encode($extension, ($details->quality ?? 90))->encoded);
}
}
$success = true;
$message = __('voyager::media.success_uploaded_file');
$path = preg_replace('/^public\//', '', $file);
event(new MediaFileAdded($path));
} catch (Exception $e) {
$success = false;
$message = $e->getMessage();
$path = '';
}
return response()->json(compact('success', 'message', 'path'));
}
public function crop(Request $request)
{
// Check permission
$this->authorize('browse_media');
$createMode = $request->get('createMode') === 'true';
$x = $request->get('x');
$y = $request->get('y');
$height = $request->get('height');
$width = $request->get('width');
$realPath = Storage::disk($this->filesystem)->path('/');
$originImagePath = $request->upload_path.'/'.$request->originImageName;
$originImagePath = preg_replace('#/+#', '/', $originImagePath);
try {
if ($createMode) {
// create a new image with the cpopped data
$fileNameParts = explode('.', $request->originImageName);
array_splice($fileNameParts, count($fileNameParts) - 1, 0, 'cropped_'.time());
$newImageName = implode('.', $fileNameParts);
$destImagePath = preg_replace('#/+#', '/', $request->upload_path.'/'.$newImageName);
} else {
// override the original image
$destImagePath = $originImagePath;
}
$content = Storage::disk($this->filesystem)->get($originImagePath);
$image = Image::make($content)->crop($width, $height, $x, $y);
Storage::disk($this->filesystem)->put($destImagePath, $image->encode()->encoded);
$success = true;
$message = __('voyager::media.success_crop_image');
} catch (Exception $e) {
$success = false;
$message = $e->getMessage();
}
return response()->json(compact('success', 'message'));
}
private function addWatermarkToImage($image, $options)
{
$watermark = Image::make(Storage::disk($this->filesystem)->path($options->source));
// Resize watermark
$width = $image->width() * (($options->size ?? 15) / 100);
$watermark->resize($width, null, function ($constraint) {
$constraint->aspectRatio();
});
return $image->insert(
$watermark,
($options->position ?? 'top-left'),
($options->x ?? 0),
($options->y ?? 0)
);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/Traits/BreadRelationshipParser.php | src/Http/Controllers/Traits/BreadRelationshipParser.php | <?php
namespace TCG\Voyager\Http\Controllers\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use TCG\Voyager\Models\DataType;
trait BreadRelationshipParser
{
protected function removeRelationshipField(DataType $dataType, $bread_type = 'browse')
{
$forget_keys = [];
foreach ($dataType->{$bread_type.'Rows'} as $key => $row) {
if ($row->type == 'relationship') {
if ($row->details->type == 'belongsTo') {
$relationshipField = @$row->details->column;
$keyInCollection = key($dataType->{$bread_type.'Rows'}->where('field', '=', $relationshipField)->toArray());
array_push($forget_keys, $keyInCollection);
}
}
}
foreach ($forget_keys as $forget_key) {
$dataType->{$bread_type.'Rows'}->forget($forget_key);
}
// Reindex collection
$dataType->{$bread_type.'Rows'} = $dataType->{$bread_type.'Rows'}->values();
}
/**
* Replace relationships' keys for labels and create READ links if a slug is provided.
*
* @param $dataTypeContent Can be either an eloquent Model, Collection or LengthAwarePaginator instance.
* @param DataType $dataType
*
* @return $dataTypeContent
*/
protected function resolveRelations($dataTypeContent, DataType $dataType)
{
// In case of using server-side pagination, we need to work on the Collection (BROWSE)
if ($dataTypeContent instanceof LengthAwarePaginator) {
$dataTypeCollection = $dataTypeContent->getCollection();
}
// If it's a model just make the changes directly on it (READ / EDIT)
elseif ($dataTypeContent instanceof Model) {
return $dataTypeContent;
}
// Or we assume it's a Collection
else {
$dataTypeCollection = $dataTypeContent;
}
return $dataTypeContent instanceof LengthAwarePaginator ? $dataTypeContent->setCollection($dataTypeCollection) : $dataTypeCollection;
}
/**
* Eagerload relationships.
*
* @param mixed $dataTypeContent Can be either an eloquent Model or Collection.
* @param DataType $dataType
* @param string $action
* @param bool $isModelTranslatable
*
* @return void
*/
protected function eagerLoadRelations($dataTypeContent, DataType $dataType, string $action, bool $isModelTranslatable)
{
// Eagerload Translations
if (config('voyager.multilingual.enabled')) {
// Check if BREAD is Translatable
if ($isModelTranslatable) {
$dataTypeContent->load('translations');
}
// DataRow is translatable so it will always try to load translations
// even if current Model is not translatable
$dataType->{$action.'Rows'}->load('translations');
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/BaseType.php | src/Http/Controllers/ContentTypes/BaseType.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
use Illuminate\Http\Request;
abstract class BaseType
{
/**
* @var Request
*/
protected $request;
/**
* @var
*/
protected $slug;
/**
* @var
*/
protected $row;
/**
* @var
*/
protected $options;
/**
* Password constructor.
*
* @param Request $request
* @param $slug
* @param $row
*/
public function __construct(Request $request, $slug, $row, $options)
{
$this->request = $request;
$this->slug = $slug;
$this->row = $row;
$this->options = $options;
}
/**
* @return mixed
*/
abstract public function handle();
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/Checkbox.php | src/Http/Controllers/ContentTypes/Checkbox.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
class Checkbox extends BaseType
{
/**
* @return int
*/
public function handle()
{
return (int) ($this->request->input($this->row->field) == 'on');
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/Text.php | src/Http/Controllers/ContentTypes/Text.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
class Text extends BaseType
{
/**
* @return null|string
*/
public function handle()
{
$value = $this->request->input($this->row->field);
if (isset($this->options->null)) {
return $value == $this->options->null ? null : $value;
}
return $value;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/Image.php | src/Http/Controllers/ContentTypes/Image.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Constraint;
use Intervention\Image\Facades\Image as InterventionImage;
class Image extends BaseType
{
public function handle()
{
if ($this->request->hasFile($this->row->field)) {
$file = $this->request->file($this->row->field);
$path = $this->slug.DIRECTORY_SEPARATOR.date('FY').DIRECTORY_SEPARATOR;
$filename = $this->generateFileName($file, $path);
$image = InterventionImage::make($file)->orientate();
$fullPath = $path.$filename.'.'.$file->getClientOriginalExtension();
$resize_width = null;
$resize_height = null;
if (isset($this->options->resize) && (
isset($this->options->resize->width) || isset($this->options->resize->height)
)) {
if (isset($this->options->resize->width)) {
$resize_width = $this->options->resize->width;
}
if (isset($this->options->resize->height)) {
$resize_height = $this->options->resize->height;
}
} else {
$resize_width = $image->width();
$resize_height = $image->height();
}
$resize_quality = isset($this->options->quality) ? intval($this->options->quality) : 75;
$image = $image->resize(
$resize_width,
$resize_height,
function (Constraint $constraint) {
$constraint->aspectRatio();
if (isset($this->options->upsize) && !$this->options->upsize) {
$constraint->upsize();
}
}
)->encode($file->getClientOriginalExtension(), $resize_quality);
if ($this->is_animated_gif($file)) {
Storage::disk(config('voyager.storage.disk'))->put($fullPath, file_get_contents($file), 'public');
$fullPathStatic = $path.$filename.'-static.'.$file->getClientOriginalExtension();
Storage::disk(config('voyager.storage.disk'))->put($fullPathStatic, (string) $image, 'public');
} else {
Storage::disk(config('voyager.storage.disk'))->put($fullPath, (string) $image, 'public');
}
if (isset($this->options->thumbnails)) {
foreach ($this->options->thumbnails as $thumbnails) {
if (isset($thumbnails->name) && isset($thumbnails->scale)) {
$scale = intval($thumbnails->scale) / 100;
$thumb_resize_width = $resize_width;
$thumb_resize_height = $resize_height;
if ($thumb_resize_width != null && $thumb_resize_width != 'null') {
$thumb_resize_width = intval($thumb_resize_width * $scale);
}
if ($thumb_resize_height != null && $thumb_resize_height != 'null') {
$thumb_resize_height = intval($thumb_resize_height * $scale);
}
$image = InterventionImage::make($file)
->orientate()
->resize(
$thumb_resize_width,
$thumb_resize_height,
function (Constraint $constraint) {
$constraint->aspectRatio();
if (isset($this->options->upsize) && !$this->options->upsize) {
$constraint->upsize();
}
}
)->encode($file->getClientOriginalExtension(), $resize_quality);
} elseif (isset($thumbnails->crop->width) && isset($thumbnails->crop->height)) {
$crop_width = $thumbnails->crop->width;
$crop_height = $thumbnails->crop->height;
$image = InterventionImage::make($file)
->orientate()
->fit($crop_width, $crop_height)
->encode($file->getClientOriginalExtension(), $resize_quality);
}
Storage::disk(config('voyager.storage.disk'))->put(
$path.$filename.'-'.$thumbnails->name.'.'.$file->getClientOriginalExtension(),
(string) $image,
'public'
);
}
}
return $fullPath;
}
}
/**
* @param \Illuminate\Http\UploadedFile $file
* @param $path
*
* @return string
*/
protected function generateFileName($file, $path)
{
if (isset($this->options->preserveFileUploadName) && $this->options->preserveFileUploadName) {
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension());
$filename_counter = 1;
// Make sure the filename does not exist, if it does make sure to add a number to the end 1, 2, 3, etc...
while (Storage::disk(config('voyager.storage.disk'))->exists($path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension()).(string) ($filename_counter++);
}
} else {
$filename = Str::random(20);
// Make sure the filename does not exist, if it does, just regenerate
while (Storage::disk(config('voyager.storage.disk'))->exists($path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = Str::random(20);
}
}
return $filename;
}
private function is_animated_gif($filename)
{
$raw = file_get_contents($filename);
$offset = 0;
$frames = 0;
while ($frames < 2) {
$where1 = strpos($raw, "\x00\x21\xF9\x04", $offset);
if ($where1 === false) {
break;
} else {
$offset = $where1 + 1;
$where2 = strpos($raw, "\x00\x2C", $offset);
if ($where2 === false) {
break;
} else {
if ($where1 + 8 == $where2) {
$frames++;
}
$offset = $where2 + 1;
}
}
}
return $frames > 1;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/Relationship.php | src/Http/Controllers/ContentTypes/Relationship.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
class Relationship extends BaseType
{
/**
* @return array
*/
public function handle()
{
$content = $this->request->input($this->row->field);
if (is_array($content)) {
$content = array_filter($content, function ($value) {
return $value !== null;
});
}
return $content;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/Password.php | src/Http/Controllers/ContentTypes/Password.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
class Password extends BaseType
{
/**
* Handle password fields.
*
* @return string
*/
public function handle()
{
return empty($this->request->input($this->row->field)) ? null :
bcrypt($this->request->input($this->row->field));
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/MultipleCheckbox.php | src/Http/Controllers/ContentTypes/MultipleCheckbox.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
class MultipleCheckbox extends BaseType
{
/**
* @return mixed
*/
public function handle()
{
$content = $this->request->input($this->row->field, []);
if (true === empty($content)) {
return json_encode([]);
}
return json_encode($content);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/Timestamp.php | src/Http/Controllers/ContentTypes/Timestamp.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
use Carbon\Carbon;
class Timestamp extends BaseType
{
public function handle()
{
if (!in_array($this->request->method(), ['PUT', 'POST'])) {
return;
}
$content = $this->request->input($this->row->field);
if (empty($content)) {
return;
}
return Carbon::parse($content);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/File.php | src/Http/Controllers/ContentTypes/File.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class File extends BaseType
{
/**
* @return string
*/
public function handle()
{
if (!$this->request->hasFile($this->row->field)) {
return;
}
$files = Arr::wrap($this->request->file($this->row->field));
$filesPath = [];
$path = $this->generatePath();
foreach ($files as $file) {
$filename = $this->generateFileName($file, $path);
$file->storeAs(
$path,
$filename.'.'.$file->getClientOriginalExtension(),
config('voyager.storage.disk', 'public')
);
array_push($filesPath, [
'download_link' => $path.$filename.'.'.$file->getClientOriginalExtension(),
'original_name' => $file->getClientOriginalName(),
]);
}
return json_encode($filesPath);
}
/**
* @return string
*/
protected function generatePath()
{
return $this->slug.DIRECTORY_SEPARATOR.date('FY').DIRECTORY_SEPARATOR;
}
/**
* @return string
*/
protected function generateFileName($file, $path)
{
if (isset($this->options->preserveFileUploadName) && $this->options->preserveFileUploadName) {
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension());
$filename_counter = 1;
// Make sure the filename does not exist, if it does make sure to add a number to the end 1, 2, 3, etc...
while (Storage::disk(config('voyager.storage.disk'))->exists($path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension()).(string) ($filename_counter++);
}
} else {
$filename = Str::random(20);
// Make sure the filename does not exist, if it does, just regenerate
while (Storage::disk(config('voyager.storage.disk'))->exists($path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = Str::random(20);
}
}
return $filename;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/Coordinates.php | src/Http/Controllers/ContentTypes/Coordinates.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
use Illuminate\Support\Facades\DB;
class Coordinates extends BaseType
{
/**
* @return string|\Illuminate\Database\Query\Expression
*/
public function handle()
{
if (empty($coordinates = $this->request->input($this->row->field))) {
return;
}
//DB::connection()->getPdo()->quote won't work as it quotes the
// lat/lng, which leads to wrong Geometry type in POINT() MySQL constructor
$lat = (float) $coordinates['lat'];
$lng = (float) $coordinates['lng'];
return DB::raw("ST_GeomFromText('POINT({$lng} {$lat})')");
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/SelectMultiple.php | src/Http/Controllers/ContentTypes/SelectMultiple.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
class SelectMultiple extends BaseType
{
public function handle()
{
$content = $this->request->input($this->row->field, []);
if (true === empty($content)) {
return json_encode([]);
}
// Check if we need to parse the editablePivotFields to update fields in the corresponding pivot table
if (isset($this->options->relationship) && !empty($this->options->relationship->editablePivotFields)) {
$pivotContent = [];
// Read all values for fields in pivot tables from the request
foreach ($this->options->relationship->editablePivotFields as $pivotField) {
if (!isset($pivotContent[$pivotField])) {
$pivotContent[$pivotField] = [];
}
$pivotContent[$pivotField] = $this->request->input('pivot_'.$pivotField);
}
// Create a new content array for updating pivot table
$newContent = [];
foreach ($content as $contentIndex => $contentValue) {
$newContent[$contentValue] = [];
foreach ($pivotContent as $pivotContentKey => $value) {
$newContent[$contentValue][$pivotContentKey] = $value[$contentIndex];
}
}
$content = $newContent;
}
return json_encode($content);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Controllers/ContentTypes/MultipleImage.php | src/Http/Controllers/ContentTypes/MultipleImage.php | <?php
namespace TCG\Voyager\Http\Controllers\ContentTypes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Constraint;
use Intervention\Image\Facades\Image as InterventionImage;
class MultipleImage extends BaseType
{
/**
* @return string
*/
public function handle()
{
$filesPath = [];
$files = $this->request->file($this->row->field);
if (!$files) {
return;
}
foreach ($files as $file) {
if (!$file->isValid()) {
continue;
}
$image = InterventionImage::make($file)->orientate();
$resize_width = null;
$resize_height = null;
if (isset($this->options->resize) && (
isset($this->options->resize->width) || isset($this->options->resize->height)
)) {
if (isset($this->options->resize->width)) {
$resize_width = $this->options->resize->width;
}
if (isset($this->options->resize->height)) {
$resize_height = $this->options->resize->height;
}
} else {
$resize_width = $image->width();
$resize_height = $image->height();
}
$resize_quality = intval($this->options->quality ?? 75);
$filename = Str::random(20);
$path = $this->slug.DIRECTORY_SEPARATOR.date('FY').DIRECTORY_SEPARATOR;
array_push($filesPath, $path.$filename.'.'.$file->getClientOriginalExtension());
$filePath = $path.$filename.'.'.$file->getClientOriginalExtension();
$image = $image->resize(
$resize_width,
$resize_height,
function (Constraint $constraint) {
$constraint->aspectRatio();
if (isset($this->options->upsize) && !$this->options->upsize) {
$constraint->upsize();
}
}
)->encode($file->getClientOriginalExtension(), $resize_quality);
Storage::disk(config('voyager.storage.disk'))->put($filePath, (string) $image, 'public');
if (isset($this->options->thumbnails)) {
foreach ($this->options->thumbnails as $thumbnails) {
if (isset($thumbnails->name) && isset($thumbnails->scale)) {
$scale = intval($thumbnails->scale) / 100;
$thumb_resize_width = $resize_width;
$thumb_resize_height = $resize_height;
if ($thumb_resize_width != null && $thumb_resize_width != 'null') {
$thumb_resize_width = $thumb_resize_width * $scale;
}
if ($thumb_resize_height != null && $thumb_resize_height != 'null') {
$thumb_resize_height = $thumb_resize_height * $scale;
}
$image = InterventionImage::make($file)
->orientate()
->resize(
$thumb_resize_width,
$thumb_resize_height,
function (Constraint $constraint) {
$constraint->aspectRatio();
if (isset($this->options->upsize) && !$this->options->upsize) {
$constraint->upsize();
}
}
)->encode($file->getClientOriginalExtension(), $resize_quality);
} elseif (isset($this->options->thumbnails) && isset($thumbnails->crop->width) && isset($thumbnails->crop->height)) {
$crop_width = $thumbnails->crop->width;
$crop_height = $thumbnails->crop->height;
$image = InterventionImage::make($file)
->orientate()
->fit($crop_width, $crop_height)
->encode($file->getClientOriginalExtension(), $resize_quality);
}
Storage::disk(config('voyager.storage.disk'))->put(
$path.$filename.'-'.$thumbnails->name.'.'.$file->getClientOriginalExtension(),
(string) $image,
'public'
);
}
}
}
return json_encode($filesPath);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Http/Middleware/VoyagerAdminMiddleware.php | src/Http/Middleware/VoyagerAdminMiddleware.php | <?php
namespace TCG\Voyager\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class VoyagerAdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
auth()->setDefaultDriver(app('VoyagerGuard'));
if (!Auth::guest()) {
$user = Auth::user();
app()->setLocale($user->locale ?? app()->getLocale());
return $user->hasPermission('browse_admin') ? $next($request) : redirect('/');
}
$urlLogin = route('voyager.login');
return redirect()->guest($urlLogin);
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Traits/Seedable.php | src/Traits/Seedable.php | <?php
namespace TCG\Voyager\Traits;
trait Seedable
{
public function seed($class)
{
if (!class_exists($class)) {
require_once $this->seedersPath.$class.'.php';
}
with(new $class())->run();
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Traits/Resizable.php | src/Traits/Resizable.php | <?php
namespace TCG\Voyager\Traits;
use Illuminate\Support\Str;
trait Resizable
{
/**
* Method for returning specific thumbnail for model.
*
* @param string $type
* @param string $attribute
*
* @return string
*/
public function thumbnail($type, $attribute = 'image')
{
// Return empty string if the field not found
if (!isset($this->attributes[$attribute])) {
return '';
}
// We take image from posts field
$image = $this->attributes[$attribute];
return $this->getThumbnail($image, $type);
}
/**
* Generate thumbnail URL.
*
* @param $image
* @param $type
*
* @return string
*/
public function getThumbnail($image, $type)
{
// We need to get extension type ( .jpeg , .png ...)
$ext = pathinfo($image, PATHINFO_EXTENSION);
// We remove extension from file name so we can append thumbnail type
$name = Str::replaceLast('.'.$ext, '', $image);
// We merge original name + type + extension
return $name.'-'.$type.'.'.$ext;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Traits/Spatial.php | src/Traits/Spatial.php | <?php
namespace TCG\Voyager\Traits;
use Illuminate\Support\Facades\DB;
trait Spatial
{
/**
* Get location as WKT from Geometry for given field.
*
* @param string $column
*
* @return string
*/
public function getLocation($column)
{
$model = self::select(DB::raw('ST_AsText('.$column.') AS '.$column))
->where('id', $this->id)
->first();
return isset($model) ? $model->$column : '';
}
/**
* Format and return array of (lat,lng) pairs of points fetched from the database.
*
* @return array $coords
*/
public function getCoordinates()
{
$coords = [];
if (!empty($this->spatial)) {
foreach ($this->spatial as $column) {
$clear = trim(preg_replace('/[a-zA-Z\(\)]/', '', $this->getLocation($column)));
if (!empty($clear)) {
foreach (explode(',', $clear) as $point) {
list($lng, $lat) = explode(' ', $point);
$coords[] = [
'lat' => $lat,
'lng' => $lng,
];
}
}
}
}
return $coords;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Traits/VoyagerUser.php | src/Traits/VoyagerUser.php | <?php
namespace TCG\Voyager\Traits;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use TCG\Voyager\Facades\Voyager;
/**
* @property \Illuminate\Database\Eloquent\Collection roles
*/
trait VoyagerUser
{
/**
* Return default User Role.
*/
public function role()
{
return $this->belongsTo(Voyager::modelClass('Role'));
}
/**
* Return alternative User Roles.
*/
public function roles()
{
return $this->belongsToMany(Voyager::modelClass('Role'), 'user_roles', 'user_id', 'role_id');
}
/**
* Return all User Roles, merging the default and alternative roles.
*/
public function roles_all()
{
$this->loadRolesRelations();
return collect([$this->role])->merge($this->roles);
}
/**
* Check if User has a Role(s) associated.
*
* @param string|array $name The role(s) to check.
*
* @return bool
*/
public function hasRole($name)
{
$roles = $this->roles_all()->pluck('name')->toArray();
foreach ((is_array($name) ? $name : [$name]) as $role) {
if (in_array($role, $roles)) {
return true;
}
}
return false;
}
/**
* Set default User Role.
*
* @param string $name The role name to associate.
*/
public function setRole($name)
{
$role = Voyager::model('Role')->where('name', '=', $name)->first();
if ($role) {
$this->role()->associate($role);
$this->save();
}
return $this;
}
public function hasPermission($name)
{
$this->loadPermissionsRelations();
$_permissions = $this->roles_all()
->pluck('permissions')->flatten()
->pluck('key')->unique()->toArray();
return in_array($name, $_permissions);
}
public function hasPermissionOrFail($name)
{
if (!$this->hasPermission($name)) {
throw new UnauthorizedHttpException(null);
}
return true;
}
public function hasPermissionOrAbort($name, $statusCode = 403)
{
if (!$this->hasPermission($name)) {
return abort($statusCode);
}
return true;
}
private function loadRolesRelations()
{
if (!$this->relationLoaded('role')) {
$this->load('role');
}
if (!$this->relationLoaded('roles')) {
$this->load('roles');
}
}
private function loadPermissionsRelations()
{
$this->loadRolesRelations();
if ($this->role && !$this->role->relationLoaded('permissions')) {
$this->role->load('permissions');
$this->load('roles.permissions');
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Traits/Translatable.php | src/Traits/Translatable.php | <?php
namespace TCG\Voyager\Traits;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use TCG\Voyager\Facades\Voyager;
use TCG\Voyager\Models\Translation;
use TCG\Voyager\Translator;
trait Translatable
{
/**
* Check if this model can translate.
*
* @return bool
*/
public function translatable()
{
if (isset($this->translatable) && $this->translatable == false) {
return false;
}
return !empty($this->getTranslatableAttributes());
}
/**
* Load translations relation.
*
* @return mixed
*/
public function translations()
{
return $this->hasMany(Voyager::model('Translation'), 'foreign_key', $this->getKeyName())
->where('table_name', $this->getTable())
->whereIn('locale', config('voyager.multilingual.locales', []));
}
/**
* This scope eager loads the translations for the default and the fallback locale only.
* We can use this as a shortcut to improve performance in our application.
*
* @param Builder $query
* @param string|null $locale
* @param string|bool $fallback
*/
public function scopeWithTranslation(Builder $query, $locale = null, $fallback = true)
{
if (is_null($locale)) {
$locale = app()->getLocale();
}
if ($fallback === true) {
$fallback = config('app.fallback_locale', 'en');
}
$query->with(['translations' => function (Relation $query) use ($locale, $fallback) {
$query->where(function ($q) use ($locale, $fallback) {
$q->where('locale', $locale);
if ($fallback !== false) {
$q->orWhere('locale', $fallback);
}
});
}]);
}
/**
* This scope eager loads the translations for the default and the fallback locale only.
* We can use this as a shortcut to improve performance in our application.
*
* @param Builder $query
* @param string|null|array $locales
* @param string|bool $fallback
*/
public function scopeWithTranslations(Builder $query, $locales = null, $fallback = true)
{
if (is_null($locales)) {
$locales = app()->getLocale();
}
if ($fallback === true) {
$fallback = config('app.fallback_locale', 'en');
}
$query->with(['translations' => function (Relation $query) use ($locales, $fallback) {
if (is_null($locales)) {
return;
}
$query->where(function ($q) use ($locales, $fallback) {
if (is_array($locales)) {
$q->whereIn('locale', $locales);
} else {
$q->where('locale', $locales);
}
if ($fallback !== false) {
$q->orWhere('locale', $fallback);
}
});
}]);
}
/**
* Translate the whole model.
*
* @param null|string $language
* @param bool|string $fallback
*
* @return Translator
*/
public function translate($language = null, $fallback = true)
{
if (!$this->relationLoaded('translations')) {
$this->load('translations');
}
return (new Translator($this))->translate($language, $fallback);
}
/**
* Get a single translated attribute.
*
* @param $attribute
* @param null $language
* @param bool $fallback
*
* @return null
*/
public function getTranslatedAttribute($attribute, $language = null, $fallback = true)
{
// If multilingual is not enabled don't check for translations
if (!config('voyager.multilingual.enabled')) {
return $this->getAttributeValue($attribute);
}
list($value) = $this->getTranslatedAttributeMeta($attribute, $language, $fallback);
return $value;
}
public function getTranslationsOf($attribute, array $languages = null, $fallback = true)
{
if (is_null($languages)) {
$languages = config('voyager.multilingual.locales', [config('voyager.multilingual.default')]);
}
$response = [];
foreach ($languages as $language) {
$response[$language] = $this->getTranslatedAttribute($attribute, $language, $fallback);
}
return $response;
}
public function getTranslatedAttributeMeta($attribute, $locale = null, $fallback = true)
{
// Attribute is translatable
//
if (!in_array($attribute, $this->getTranslatableAttributes())) {
return [$this->getAttribute($attribute), config('voyager.multilingual.default'), false];
}
if (is_null($locale)) {
$locale = app()->getLocale();
}
if ($fallback === true) {
$fallback = config('app.fallback_locale', 'en');
}
$default = config('voyager.multilingual.default');
if ($default == $locale) {
return [$this->getAttribute($attribute), $default, true];
}
if (!$this->relationLoaded('translations')) {
$this->load('translations');
}
$translations = $this->getRelation('translations')
->where('column_name', $attribute);
$localeTranslation = $translations->where('locale', $locale)->first();
if ($localeTranslation) {
return [$localeTranslation->value, $locale, true];
}
if ($fallback == $locale) {
return [$this->getAttribute($attribute), $locale, false];
}
if ($fallback == $default) {
return [$this->getAttribute($attribute), $locale, false];
}
$fallbackTranslation = $translations->where('locale', $fallback)->first();
if ($fallbackTranslation && $fallback !== false) {
return [$fallbackTranslation->value, $locale, true];
}
return [null, $locale, false];
}
/**
* Get attributes that can be translated.
*
* @return array
*/
public function getTranslatableAttributes()
{
return property_exists($this, 'translatable') ? $this->translatable : [];
}
public function setAttributeTranslations($attribute, array $translations, $save = false)
{
$response = [];
if (!$this->relationLoaded('translations')) {
$this->load('translations');
}
$default = config('voyager.multilingual.default', 'en');
$locales = config('voyager.multilingual.locales', [$default]);
foreach ($locales as $locale) {
if (empty($translations[$locale])) {
continue;
}
if ($locale == $default) {
$this->$attribute = $translations[$locale];
continue;
}
$tranlator = $this->translate($locale, false);
$tranlator->$attribute = $translations[$locale];
if ($save) {
$tranlator->save();
}
$response[] = $tranlator;
}
return $response;
}
/**
* Get entries filtered by translated value.
*
* @example Class::whereTranslation('title', '=', 'zuhause', ['de', 'iu'])
* @example $query->whereTranslation('title', '=', 'zuhause', ['de', 'iu'])
*
* @param string $field {required} the field your looking to find a value in.
* @param string $operator {required} value you are looking for or a relation modifier such as LIKE, =, etc.
* @param string $value {optional} value you are looking for. Only use if you supplied an operator.
* @param string|array $locales {optional} locale(s) you are looking for the field.
* @param bool $default {optional} if true checks for $value is in default database before checking translations.
*
* @return Builder
*/
public static function scopeWhereTranslation($query, $field, $operator, $value = null, $locales = null, $default = true)
{
if ($locales && !is_array($locales)) {
$locales = [$locales];
}
if (!isset($value)) {
$value = $operator;
$operator = '=';
}
$self = new static();
$table = $self->getTable();
return $query->whereIn(
$self->getKeyName(),
Translation::where('table_name', $table)
->where('column_name', $field)
->where('value', $operator, $value)
->when(!is_null($locales), function ($query) use ($locales) {
return $query->whereIn('locale', $locales);
})
->pluck('foreign_key')
)->when($default, function ($query) use ($field, $operator, $value) {
return $query->orWhere($field, $operator, $value);
});
}
public function hasTranslatorMethod($name)
{
if (!isset($this->translatorMethods)) {
return false;
}
return isset($this->translatorMethods[$name]);
}
public function getTranslatorMethod($name)
{
if (!$this->hasTranslatorMethod($name)) {
return;
}
return $this->translatorMethods[$name];
}
public function deleteAttributeTranslations(array $attributes, $locales = null)
{
$this->translations()
->whereIn('column_name', $attributes)
->when(!is_null($locales), function ($query) use ($locales) {
$method = is_array($locales) ? 'whereIn' : 'where';
return $query->$method('locale', $locales);
})
->delete();
}
public function deleteAttributeTranslation($attribute, $locales = null)
{
$this->translations()
->where('column_name', $attribute)
->when(!is_null($locales), function ($query) use ($locales) {
$method = is_array($locales) ? 'whereIn' : 'where';
return $query->$method('locale', $locales);
})
->delete();
}
/**
* Prepare translations and set default locale field value.
*
* @param object $request
*
* @return array translations
*/
public function prepareTranslations($request)
{
$translations = [];
// Translatable Fields
$transFields = $this->getTranslatableAttributes();
$fields = !empty($request->attributes->get('breadRows')) ? array_intersect($request->attributes->get('breadRows'), $transFields) : $transFields;
foreach ($fields as $field) {
if (!$request->input($field.'_i18n')) {
throw new Exception('Invalid Translatable field'.$field);
}
$trans = json_decode($request->input($field.'_i18n'), true);
// Set the default local value
$request->merge([$field => $trans[config('voyager.multilingual.default', 'en')]]);
$translations[$field] = $this->setAttributeTranslations(
$field,
$trans
);
// Remove field hidden input
unset($request[$field.'_i18n']);
}
// Remove language selector input
unset($request['i18n_selector']);
return $translations;
}
/**
* Prepare translations and set default locale field value.
*
* @param object $requestData
*
* @return array translations
*/
public function prepareTranslationsFromArray($field, &$requestData)
{
$translations = [];
$field = 'field_display_name_'.$field;
if (empty($requestData[$field.'_i18n'])) {
throw new Exception('Invalid Translatable field '.$field);
}
$trans = json_decode($requestData[$field.'_i18n'], true);
// Set the default local value
$requestData['display_name'] = $trans[config('voyager.multilingual.default', 'en')];
$translations['display_name'] = $this->setAttributeTranslations(
'display_name',
$trans
);
// Remove field hidden input
unset($requestData[$field.'_i18n']);
return $translations;
}
/**
* Save translations.
*
* @param object $translations
*
* @return void
*/
public function saveTranslations($translations)
{
foreach ($translations as $field => $locales) {
foreach ($locales as $locale => $translation) {
$translation->save();
}
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Traits/Renderable.php | src/Traits/Renderable.php | <?php
namespace TCG\Voyager\Traits;
use Illuminate\View\View;
trait Renderable
{
public function render($content)
{
if ($content instanceof View) {
return $content->render();
}
return $content;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Traits/AlertsMessages.php | src/Traits/AlertsMessages.php | <?php
namespace TCG\Voyager\Traits;
trait AlertsMessages
{
protected $alerts = [];
protected function getAlerts($group = false)
{
if (isset($this->alerts['alerts'])) {
$alerts = $this->alerts['alerts'];
if ($group) {
$alerts = collect($alerts)->groupBy('type')->toArray();
}
return $alerts;
}
return [];
}
protected function alert($message, $type)
{
$this->alerts['alerts'][] = [
'type' => $type,
'message' => $message,
];
return $this->alerts;
}
protected function alertSuccess($message)
{
return $this->alert($message, 'success');
}
protected function alertInfo($message)
{
return $this->alert($message, 'info');
}
protected function alertWarning($message)
{
return $this->alert($message, 'warning');
}
protected function alertError($message)
{
return $this->alert($message, 'error');
}
protected function alertException(\Exception $e, $prefixMessage = '')
{
return $this->alertError("{$prefixMessage} ".__('voyager::generic.exception').": {$e->getMessage()}");
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Listeners/AddBreadPermission.php | src/Listeners/AddBreadPermission.php | <?php
namespace TCG\Voyager\Listeners;
use TCG\Voyager\Events\BreadAdded;
use TCG\Voyager\Facades\Voyager;
class AddBreadPermission
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Create Permission for a given BREAD.
*
* @param BreadAdded $event
*
* @return void
*/
public function handle(BreadAdded $bread)
{
if (config('voyager.bread.add_permission') && file_exists(base_path('routes/web.php'))) {
// Create permission
//
// Permission::generateFor(Str::snake($bread->dataType->slug));
$role = Voyager::model('Role')->where('name', config('voyager.bread.default_role'))->firstOrFail();
// Get permission for added table
$permissions = Voyager::model('Permission')->where(['table_name' => $bread->dataType->name])->get()->pluck('id')->all();
// Assign permission to admin
$role->permissions()->attach($permissions);
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Listeners/DeleteBreadMenuItem.php | src/Listeners/DeleteBreadMenuItem.php | <?php
namespace TCG\Voyager\Listeners;
use TCG\Voyager\Events\BreadDeleted;
use TCG\Voyager\Facades\Voyager;
class DeleteBreadMenuItem
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Delete a MenuItem for a given BREAD.
*
* @param BreadDeleted $bread
*
* @return void
*/
public function handle(BreadDeleted $bread)
{
if (config('voyager.bread.add_menu_item')) {
$menuItem = Voyager::model('MenuItem')->where('route', 'voyager.'.$bread->dataType->slug.'.index');
if ($menuItem->exists()) {
$menuItem->delete();
}
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Listeners/ClearCachedSettingValue.php | src/Listeners/ClearCachedSettingValue.php | <?php
namespace TCG\Voyager\Listeners;
use Cache;
use TCG\Voyager\Events\SettingUpdated;
class ClearCachedSettingValue
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* handle.
*
* @param SettingUpdated $event
*
* @return void
*/
public function handle(SettingUpdated $event)
{
if (config('voyager.settings.cache', false) === true) {
Cache::tags('settings')->forget($event->setting->key);
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Listeners/AddBreadMenuItem.php | src/Listeners/AddBreadMenuItem.php | <?php
namespace TCG\Voyager\Listeners;
use TCG\Voyager\Events\BreadAdded;
use TCG\Voyager\Facades\Voyager;
class AddBreadMenuItem
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Create a MenuItem for a given BREAD.
*
* @param BreadAdded $event
*
* @return void
*/
public function handle(BreadAdded $bread)
{
if (config('voyager.bread.add_menu_item') && file_exists(base_path('routes/web.php'))) {
$menu = Voyager::model('Menu')->where('name', config('voyager.bread.default_menu'))->firstOrFail();
$menuItem = Voyager::model('MenuItem')->firstOrNew([
'menu_id' => $menu->id,
'title' => $bread->dataType->getTranslatedAttribute('display_name_plural'),
'url' => '',
'route' => 'voyager.'.$bread->dataType->slug.'.index',
]);
$order = Voyager::model('MenuItem')->highestOrderMenuItem();
if (!$menuItem->exists) {
$menuItem->fill([
'target' => '_self',
'icon_class' => $bread->dataType->icon,
'color' => null,
'parent_id' => null,
'order' => $order,
])->save();
}
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Actions/AbstractAction.php | src/Actions/AbstractAction.php | <?php
namespace TCG\Voyager\Actions;
abstract class AbstractAction implements ActionInterface
{
protected $dataType;
protected $data;
public function __construct($dataType, $data)
{
$this->dataType = $dataType;
$this->data = $data;
}
public function getDataType()
{
}
public function getPolicy()
{
}
public function getRoute($key)
{
if (method_exists($this, $method = 'get'.ucfirst($key).'Route')) {
return $this->$method();
} else {
return $this->getDefaultRoute();
}
}
public function getAttributes()
{
return [];
}
public function convertAttributesToHtml()
{
$result = [];
foreach ($this->getAttributes() as $key => $attribute) {
$result[] = sprintf('%s="%s"', $key, $attribute);
}
return implode(" ", $result);
}
public function shouldActionDisplayOnDataType()
{
return $this->dataType->name === $this->getDataType() || $this->getDataType() === null;
}
public function shouldActionDisplayOnRow($row)
{
return true;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Actions/ViewAction.php | src/Actions/ViewAction.php | <?php
namespace TCG\Voyager\Actions;
class ViewAction extends AbstractAction
{
public function getTitle()
{
return __('voyager::generic.view');
}
public function getIcon()
{
return 'voyager-eye';
}
public function getPolicy()
{
return 'read';
}
public function getAttributes()
{
return [
'class' => 'btn btn-sm btn-warning pull-right view',
];
}
public function getDefaultRoute()
{
return route('voyager.'.$this->dataType->slug.'.show', $this->data->{$this->data->getKeyName()});
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Actions/RestoreAction.php | src/Actions/RestoreAction.php | <?php
namespace TCG\Voyager\Actions;
class RestoreAction extends AbstractAction
{
public function getTitle()
{
return __('voyager::generic.restore');
}
public function getIcon()
{
return 'voyager-trash';
}
public function getPolicy()
{
return 'restore';
}
public function getAttributes()
{
return [
'class' => 'btn btn-sm btn-success pull-right restore',
'data-id' => $this->data->{$this->data->getKeyName()},
'id' => 'restore-'.$this->data->{$this->data->getKeyName()},
];
}
public function getDefaultRoute()
{
return route('voyager.'.$this->dataType->slug.'.restore', $this->data->{$this->data->getKeyName()});
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Actions/EditAction.php | src/Actions/EditAction.php | <?php
namespace TCG\Voyager\Actions;
class EditAction extends AbstractAction
{
public function getTitle()
{
return __('voyager::generic.edit');
}
public function getIcon()
{
return 'voyager-edit';
}
public function getPolicy()
{
return 'edit';
}
public function getAttributes()
{
return [
'class' => 'btn btn-sm btn-primary pull-right edit',
];
}
public function getDefaultRoute()
{
return route('voyager.'.$this->dataType->slug.'.edit', $this->data->{$this->data->getKeyName()});
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Actions/ActionInterface.php | src/Actions/ActionInterface.php | <?php
namespace TCG\Voyager\Actions;
interface ActionInterface
{
public function getTitle();
public function getIcon();
public function getPolicy();
public function getAttributes();
public function getRoute($key);
public function getDefaultRoute();
public function getDataType();
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Actions/DeleteAction.php | src/Actions/DeleteAction.php | <?php
namespace TCG\Voyager\Actions;
class DeleteAction extends AbstractAction
{
public function getTitle()
{
return __('voyager::generic.delete');
}
public function getIcon()
{
return 'voyager-trash';
}
public function getPolicy()
{
return 'delete';
}
public function getAttributes()
{
return [
'class' => 'btn btn-sm btn-danger pull-right delete',
'data-id' => $this->data->{$this->data->getKeyName()},
'id' => 'delete-'.$this->data->{$this->data->getKeyName()},
];
}
public function getDefaultRoute()
{
return 'javascript:;';
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Translator/Collection.php | src/Translator/Collection.php | <?php
namespace TCG\Voyager\Translator;
use Illuminate\Support\Collection as IlluminateCollection;
class Collection extends IlluminateCollection
{
//
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Contracts/User.php | src/Contracts/User.php | <?php
namespace TCG\Voyager\Contracts;
interface User
{
public function role();
public function hasRole($name);
public function setRole($name);
public function hasPermission($name);
public function hasPermissionOrFail($name);
public function hasPermissionOrAbort($name, $statusCode = 403);
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/DatabaseUpdater.php | src/Database/DatabaseUpdater.php | <?php
namespace TCG\Voyager\Database;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\DBAL\Schema\TableDiff;
use TCG\Voyager\Database\Schema\SchemaManager;
use TCG\Voyager\Database\Schema\Table;
use TCG\Voyager\Database\Types\Type;
class DatabaseUpdater
{
protected $tableArr;
protected $table;
protected $originalTable;
public function __construct(array $tableArr)
{
Type::registerCustomPlatformTypes();
$this->table = Table::make($tableArr);
$this->tableArr = $tableArr;
$this->originalTable = SchemaManager::listTableDetails($tableArr['oldName']);
}
/**
* Update the table.
*
* @return void
*/
public static function update($table)
{
if (!is_array($table)) {
$table = json_decode($table, true);
}
if (!SchemaManager::tableExists($table['oldName'])) {
throw SchemaException::tableDoesNotExist($table['oldName']);
}
$updater = new self($table);
$updater->updateTable();
}
/**
* Updates the table.
*
* @return void
*/
public function updateTable()
{
// Get table new name
if (($newName = $this->table->getName()) != $this->originalTable->getName()) {
// Make sure the new name doesn't already exist
if (SchemaManager::tableExists($newName)) {
throw SchemaException::tableAlreadyExists($newName);
}
} else {
$newName = false;
}
// Rename columns
if ($renamedColumnsDiff = $this->getRenamedColumnsDiff()) {
SchemaManager::alterTable($renamedColumnsDiff);
// Refresh original table after renaming the columns
$this->originalTable = SchemaManager::listTableDetails($this->tableArr['oldName']);
}
$tableDiff = $this->originalTable->diff($this->table);
// Add new table name to tableDiff
if ($newName) {
if (!$tableDiff) {
$tableDiff = new TableDiff($this->tableArr['oldName']);
$tableDiff->fromTable = $this->originalTable;
}
$tableDiff->newName = $newName;
}
// Update the table
if ($tableDiff) {
SchemaManager::alterTable($tableDiff);
}
}
/**
* Get the table diff to rename columns.
*
* @return \Doctrine\DBAL\Schema\TableDiff
*/
protected function getRenamedColumnsDiff()
{
$renamedColumns = $this->getRenamedColumns();
if (empty($renamedColumns)) {
return false;
}
$renamedColumnsDiff = new TableDiff($this->tableArr['oldName']);
$renamedColumnsDiff->fromTable = $this->originalTable;
foreach ($renamedColumns as $oldName => $newName) {
$renamedColumnsDiff->renamedColumns[$oldName] = $this->table->getColumn($newName);
}
return $renamedColumnsDiff;
}
/**
* Get the table diff to rename columns and indexes.
*
* @return \Doctrine\DBAL\Schema\TableDiff
*/
protected function getRenamedDiff()
{
$renamedColumns = $this->getRenamedColumns();
$renamedIndexes = $this->getRenamedIndexes();
if (empty($renamedColumns) && empty($renamedIndexes)) {
return false;
}
$renamedDiff = new TableDiff($this->tableArr['oldName']);
$renamedDiff->fromTable = $this->originalTable;
foreach ($renamedColumns as $oldName => $newName) {
$renamedDiff->renamedColumns[$oldName] = $this->table->getColumn($newName);
}
foreach ($renamedIndexes as $oldName => $newName) {
$renamedDiff->renamedIndexes[$oldName] = $this->table->getIndex($newName);
}
return $renamedDiff;
}
/**
* Get columns that were renamed.
*
* @return array
*/
protected function getRenamedColumns()
{
$renamedColumns = [];
foreach ($this->tableArr['columns'] as $column) {
$oldName = $column['oldName'];
// make sure this is an existing column and not a new one
if ($this->originalTable->hasColumn($oldName)) {
$name = $column['name'];
if ($name != $oldName) {
$renamedColumns[$oldName] = $name;
}
}
}
return $renamedColumns;
}
/**
* Get indexes that were renamed.
*
* @return array
*/
protected function getRenamedIndexes()
{
$renamedIndexes = [];
foreach ($this->tableArr['indexes'] as $index) {
$oldName = $index['oldName'];
// make sure this is an existing index and not a new one
if ($this->originalTable->hasIndex($oldName)) {
$name = $index['name'];
if ($name != $oldName) {
$renamedIndexes[$oldName] = $name;
}
}
}
return $renamedIndexes;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Type.php | src/Database/Types/Type.php | <?php
namespace TCG\Voyager\Database\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform as DoctrineAbstractPlatform;
use Doctrine\DBAL\Types\Type as DoctrineType;
use TCG\Voyager\Database\Platforms\Platform;
use TCG\Voyager\Database\Schema\SchemaManager;
abstract class Type extends DoctrineType
{
protected static $customTypesRegistered = false;
protected static $platformTypeMapping = [];
protected static $allTypes = [];
protected static $platformTypes = [];
protected static $customTypeOptions = [];
protected static $typeCategories = [];
public const NAME = 'UNDEFINED_TYPE_NAME';
public const NOT_SUPPORTED = 'notSupported';
public const NOT_SUPPORT_INDEX = 'notSupportIndex';
// todo: make sure this is not overwrting DoctrineType properties
// Note: length, precision and scale need default values manually
public function getName()
{
return static::NAME;
}
public static function toArray(DoctrineType $type)
{
$customTypeOptions = $type->customOptions ?? [];
return array_merge([
'name' => $type->getName(),
], $customTypeOptions);
}
public static function getPlatformTypes()
{
if (static::$platformTypes) {
return static::$platformTypes;
}
if (!static::$customTypesRegistered) {
static::registerCustomPlatformTypes();
}
$platform = SchemaManager::getDatabasePlatform();
static::$platformTypes = Platform::getPlatformTypes(
$platform->getName(),
static::getPlatformTypeMapping($platform)
);
static::$platformTypes = static::$platformTypes->map(function ($type) {
return static::toArray(static::getType($type));
})->groupBy('category');
return static::$platformTypes;
}
public static function getPlatformTypeMapping(DoctrineAbstractPlatform $platform)
{
if (static::$platformTypeMapping) {
return static::$platformTypeMapping;
}
static::$platformTypeMapping = collect(
get_protected_property($platform, 'doctrineTypeMapping')
);
return static::$platformTypeMapping;
}
public static function registerCustomPlatformTypes($force = false)
{
if (static::$customTypesRegistered && !$force) {
return;
}
$platform = SchemaManager::getDatabasePlatform();
$platformName = ucfirst($platform->getName());
$customTypes = array_merge(
static::getPlatformCustomTypes('Common'),
static::getPlatformCustomTypes($platformName)
);
foreach ($customTypes as $type) {
$name = $type::NAME;
if (static::hasType($name)) {
static::overrideType($name, $type);
} else {
static::addType($name, $type);
}
$dbType = defined("{$type}::DBTYPE") ? $type::DBTYPE : $name;
$platform->registerDoctrineTypeMapping($dbType, $name);
}
static::addCustomTypeOptions($platformName);
static::$customTypesRegistered = true;
}
protected static function addCustomTypeOptions($platformName)
{
static::registerCommonCustomTypeOptions();
Platform::registerPlatformCustomTypeOptions($platformName);
// Add the custom options to the types
foreach (static::$customTypeOptions as $option) {
foreach ($option['types'] as $type) {
if (static::hasType($type)) {
static::getType($type)->customOptions[$option['name']] = $option['value'];
}
}
}
}
protected static function getPlatformCustomTypes($platformName)
{
$typesPath = __DIR__.DIRECTORY_SEPARATOR.$platformName.DIRECTORY_SEPARATOR;
$namespace = __NAMESPACE__.'\\'.$platformName.'\\';
$types = [];
foreach (glob($typesPath.'*.php') as $classFile) {
$types[] = $namespace.str_replace(
'.php',
'',
str_replace($typesPath, '', $classFile)
);
}
return $types;
}
public static function registerCustomOption($name, $value, $types)
{
if (is_string($types)) {
$types = trim($types);
if ($types == '*') {
$types = static::getAllTypes()->toArray();
} elseif (strpos($types, '*') !== false) {
$searchType = str_replace('*', '', $types);
$types = static::getAllTypes()->filter(function ($type) use ($searchType) {
return strpos($type, $searchType) !== false;
})->toArray();
} else {
$types = [$types];
}
}
static::$customTypeOptions[] = [
'name' => $name,
'value' => $value,
'types' => $types,
];
}
protected static function registerCommonCustomTypeOptions()
{
static::registerTypeCategories();
static::registerTypeDefaultOptions();
}
protected static function registerTypeDefaultOptions()
{
$types = static::getTypeCategories();
// Numbers
static::registerCustomOption('default', [
'type' => 'number',
'step' => 'any',
], $types['numbers']);
// Date and Time
static::registerCustomOption('default', [
'type' => 'date',
], 'date');
static::registerCustomOption('default', [
'type' => 'time',
'step' => '1',
], 'time');
static::registerCustomOption('default', [
'type' => 'number',
'min' => '0',
], 'year');
}
protected static function registerTypeCategories()
{
$types = static::getTypeCategories();
static::registerCustomOption('category', 'Numbers', $types['numbers']);
static::registerCustomOption('category', 'Strings', $types['strings']);
static::registerCustomOption('category', 'Date and Time', $types['datetime']);
static::registerCustomOption('category', 'Lists', $types['lists']);
static::registerCustomOption('category', 'Binary', $types['binary']);
static::registerCustomOption('category', 'Geometry', $types['geometry']);
static::registerCustomOption('category', 'Network', $types['network']);
static::registerCustomOption('category', 'Objects', $types['objects']);
}
public static function getAllTypes()
{
if (static::$allTypes) {
return static::$allTypes;
}
static::$allTypes = collect(static::getTypeCategories())->flatten();
return static::$allTypes;
}
public static function getTypeCategories()
{
if (static::$typeCategories) {
return static::$typeCategories;
}
$numbers = [
'boolean',
'tinyint',
'smallint',
'mediumint',
'integer',
'int',
'bigint',
'decimal',
'numeric',
'money',
'float',
'real',
'double',
'double precision',
];
$strings = [
'char',
'character',
'varchar',
'character varying',
'string',
'guid',
'uuid',
'tinytext',
'text',
'mediumtext',
'longtext',
'tsquery',
'tsvector',
'xml',
];
$datetime = [
'date',
'datetime',
'year',
'time',
'timetz',
'timestamp',
'timestamptz',
'datetimetz',
'dateinterval',
'interval',
];
$lists = [
'enum',
'set',
'simple_array',
'array',
'json',
'jsonb',
'json_array',
];
$binary = [
'bit',
'bit varying',
'binary',
'varbinary',
'tinyblob',
'blob',
'mediumblob',
'longblob',
'bytea',
];
$network = [
'cidr',
'inet',
'macaddr',
'txid_snapshot',
];
$geometry = [
'geometry',
'point',
'linestring',
'polygon',
'multipoint',
'multilinestring',
'multipolygon',
'geometrycollection',
];
$objects = [
'object',
];
static::$typeCategories = [
'numbers' => $numbers,
'strings' => $strings,
'datetime' => $datetime,
'lists' => $lists,
'binary' => $binary,
'network' => $network,
'geometry' => $geometry,
'objects' => $objects,
];
return static::$typeCategories;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/MediumIntType.php | src/Database/Types/Mysql/MediumIntType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class MediumIntType extends Type
{
public const NAME = 'mediumint';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
$commonIntegerTypeDeclaration = call_protected_method($platform, '_getCommonIntegerTypeDeclarationSQL', $field);
return 'mediumint'.$commonIntegerTypeDeclaration;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/TinyTextType.php | src/Database/Types/Mysql/TinyTextType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class TinyTextType extends Type
{
public const NAME = 'tinytext';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
return 'tinytext';
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/MultiPointType.php | src/Database/Types/Mysql/MultiPointType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class MultiPointType extends Type
{
public const NAME = 'multipoint';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
return 'multipoint';
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/TinyBlobType.php | src/Database/Types/Mysql/TinyBlobType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class TinyBlobType extends Type
{
public const NAME = 'tinyblob';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
return 'tinyblob';
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/MediumBlobType.php | src/Database/Types/Mysql/MediumBlobType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class MediumBlobType extends Type
{
public const NAME = 'mediumblob';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
return 'mediumblob';
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/LongTextType.php | src/Database/Types/Mysql/LongTextType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class LongTextType extends Type
{
public const NAME = 'longtext';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
return 'longtext';
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/BitType.php | src/Database/Types/Mysql/BitType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class BitType extends Type
{
public const NAME = 'bit';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
$length = empty($field['length']) ? 1 : $field['length'];
$length = $length > 64 ? 64 : $length;
return "bit({$length})";
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/EnumType.php | src/Database/Types/Mysql/EnumType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Illuminate\Support\Facades\DB;
use TCG\Voyager\Database\Types\Type;
class EnumType extends Type
{
public const NAME = 'enum';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
$enumField = collect(DB::select(DB::raw('SHOW COLUMNS FROM '.DB::getQueryGrammar()->wrap($this->tableName))))->where('Field', $field['name'])->first();
if (!is_null($enumField)) {
return $enumField->Type;
} else {
throw new \Exception('Enum definition error');
// throw new \Exception('Enum type is not supported');
// get allowed from $column instance???
// learn more about this....
$pdo = DB::connection()->getPdo();
// trim the values
$allowed = array_map(function ($value) use ($pdo) {
return $pdo->quote(trim($value));
}, $allowed);
return 'enum('.implode(', ', $allowed).')';
}
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/BlobType.php | src/Database/Types/Mysql/BlobType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class BlobType extends Type
{
public const NAME = 'blob';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
return 'blob';
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/TinyIntType.php | src/Database/Types/Mysql/TinyIntType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class TinyIntType extends Type
{
public const NAME = 'tinyint';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
$commonIntegerTypeDeclaration = call_protected_method($platform, '_getCommonIntegerTypeDeclarationSQL', $field);
return 'tinyint'.$commonIntegerTypeDeclaration;
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/src/Database/Types/Mysql/MediumTextType.php | src/Database/Types/Mysql/MediumTextType.php | <?php
namespace TCG\Voyager\Database\Types\Mysql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use TCG\Voyager\Database\Types\Type;
class MediumTextType extends Type
{
public const NAME = 'mediumtext';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
return 'mediumtext';
}
}
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.