2
0
forked from Wavyzz/dolibarr

Merge pull request #19570 from Easya-Solutions/12.0

FIX: Update swiftmailer librairies
This commit is contained in:
Laurent Destailleur
2022-01-23 12:15:43 +01:00
committed by GitHub
156 changed files with 2370 additions and 1637 deletions

View File

@@ -13,6 +13,8 @@ class EmailLexer extends AbstractLexer
const S_BACKSLASH = 92; const S_BACKSLASH = 92;
const S_DOT = 46; const S_DOT = 46;
const S_DQUOTE = 34; const S_DQUOTE = 34;
const S_SQUOTE = 39;
const S_BACKTICK = 96;
const S_OPENPARENTHESIS = 49; const S_OPENPARENTHESIS = 49;
const S_CLOSEPARENTHESIS = 261; const S_CLOSEPARENTHESIS = 261;
const S_OPENBRACKET = 262; const S_OPENBRACKET = 262;
@@ -58,6 +60,8 @@ class EmailLexer extends AbstractLexer
'/' => self::S_SLASH, '/' => self::S_SLASH,
',' => self::S_COMMA, ',' => self::S_COMMA,
'.' => self::S_DOT, '.' => self::S_DOT,
"'" => self::S_SQUOTE,
"`" => self::S_BACKTICK,
'"' => self::S_DQUOTE, '"' => self::S_DQUOTE,
'-' => self::S_HYPHEN, '-' => self::S_HYPHEN,
'::' => self::S_DOUBLECOLON, '::' => self::S_DOUBLECOLON,
@@ -73,25 +77,73 @@ class EmailLexer extends AbstractLexer
'\0' => self::C_NUL, '\0' => self::C_NUL,
); );
/**
* @var bool
*/
protected $hasInvalidTokens = false; protected $hasInvalidTokens = false;
protected $previous; /**
* @var array
*
* @psalm-var array{value:string, type:null|int, position:int}|array<empty, empty>
*/
protected $previous = [];
/**
* The last matched/seen token.
*
* @var array
*
* @psalm-var array{value:string, type:null|int, position:int}
*/
public $token;
/**
* The next token in the input.
*
* @var array|null
*/
public $lookahead;
/**
* @psalm-var array{value:'', type:null, position:0}
*/
private static $nullToken = [
'value' => '',
'type' => null,
'position' => 0,
];
public function __construct()
{
$this->previous = $this->token = self::$nullToken;
$this->lookahead = null;
}
/**
* @return void
*/
public function reset() public function reset()
{ {
$this->hasInvalidTokens = false; $this->hasInvalidTokens = false;
parent::reset(); parent::reset();
$this->previous = $this->token = self::$nullToken;
} }
/**
* @return bool
*/
public function hasInvalidTokens() public function hasInvalidTokens()
{ {
return $this->hasInvalidTokens; return $this->hasInvalidTokens;
} }
/** /**
* @param $type * @param int $type
* @throws \UnexpectedValueException * @throws \UnexpectedValueException
* @return boolean * @return boolean
*
* @psalm-suppress InvalidScalarArgument
*/ */
public function find($type) public function find($type)
{ {
@@ -107,7 +159,7 @@ class EmailLexer extends AbstractLexer
/** /**
* getPrevious * getPrevious
* *
* @return array token * @return array
*/ */
public function getPrevious() public function getPrevious()
{ {
@@ -122,8 +174,10 @@ class EmailLexer extends AbstractLexer
public function moveNext() public function moveNext()
{ {
$this->previous = $this->token; $this->previous = $this->token;
$hasNext = parent::moveNext();
$this->token = $this->token ?: self::$nullToken;
return parent::moveNext(); return $hasNext;
} }
/** /**
@@ -179,6 +233,11 @@ class EmailLexer extends AbstractLexer
return self::GENERIC; return self::GENERIC;
} }
/**
* @param string $value
*
* @return bool
*/
protected function isValid($value) protected function isValid($value)
{ {
if (isset($this->charValue[$value])) { if (isset($this->charValue[$value])) {
@@ -189,7 +248,7 @@ class EmailLexer extends AbstractLexer
} }
/** /**
* @param $value * @param string $value
* @return bool * @return bool
*/ */
protected function isNullType($value) protected function isNullType($value)
@@ -202,7 +261,7 @@ class EmailLexer extends AbstractLexer
} }
/** /**
* @param $value * @param string $value
* @return bool * @return bool
*/ */
protected function isUTF8Invalid($value) protected function isUTF8Invalid($value)
@@ -214,6 +273,9 @@ class EmailLexer extends AbstractLexer
return false; return false;
} }
/**
* @return string
*/
protected function getModifiers() protected function getModifiers()
{ {
return 'iu'; return 'iu';

View File

@@ -17,11 +17,33 @@ class EmailParser
{ {
const EMAIL_MAX_LENGTH = 254; const EMAIL_MAX_LENGTH = 254;
protected $warnings; /**
* @var array
*/
protected $warnings = [];
/**
* @var string
*/
protected $domainPart = ''; protected $domainPart = '';
/**
* @var string
*/
protected $localPart = ''; protected $localPart = '';
/**
* @var EmailLexer
*/
protected $lexer; protected $lexer;
/**
* @var LocalPart
*/
protected $localPartParser; protected $localPartParser;
/**
* @var DomainPart
*/
protected $domainPartParser; protected $domainPartParser;
public function __construct(EmailLexer $lexer) public function __construct(EmailLexer $lexer)
@@ -29,11 +51,10 @@ class EmailParser
$this->lexer = $lexer; $this->lexer = $lexer;
$this->localPartParser = new LocalPart($this->lexer); $this->localPartParser = new LocalPart($this->lexer);
$this->domainPartParser = new DomainPart($this->lexer); $this->domainPartParser = new DomainPart($this->lexer);
$this->warnings = new \SplObjectStorage();
} }
/** /**
* @param $str * @param string $str
* @return array * @return array
*/ */
public function parse($str) public function parse($str)
@@ -57,6 +78,9 @@ class EmailParser
return array('local' => $this->localPart, 'domain' => $this->domainPart); return array('local' => $this->localPart, 'domain' => $this->domainPart);
} }
/**
* @return Warning\Warning[]
*/
public function getWarnings() public function getWarnings()
{ {
$localPartWarnings = $this->localPartParser->getWarnings(); $localPartWarnings = $this->localPartParser->getWarnings();
@@ -68,11 +92,17 @@ class EmailParser
return $this->warnings; return $this->warnings;
} }
/**
* @return string
*/
public function getParsedDomainPart() public function getParsedDomainPart()
{ {
return $this->domainPart; return $this->domainPart;
} }
/**
* @param string $email
*/
protected function setParts($email) protected function setParts($email)
{ {
$parts = explode('@', $email); $parts = explode('@', $email);
@@ -80,6 +110,9 @@ class EmailParser
$this->localPart = $parts[0]; $this->localPart = $parts[0];
} }
/**
* @return bool
*/
protected function hasAtToken() protected function hasAtToken()
{ {
$this->lexer->moveNext(); $this->lexer->moveNext();

View File

@@ -13,12 +13,12 @@ class EmailValidator
private $lexer; private $lexer;
/** /**
* @var array * @var Warning\Warning[]
*/ */
protected $warnings; protected $warnings = [];
/** /**
* @var InvalidEmail * @var InvalidEmail|null
*/ */
protected $error; protected $error;
@@ -28,7 +28,7 @@ class EmailValidator
} }
/** /**
* @param $email * @param string $email
* @param EmailValidation $emailValidation * @param EmailValidation $emailValidation
* @return bool * @return bool
*/ */
@@ -58,7 +58,7 @@ class EmailValidator
} }
/** /**
* @return InvalidEmail * @return InvalidEmail|null
*/ */
public function getError() public function getError()
{ {

View File

@@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class DomainAcceptsNoMail extends InvalidEmail
{
const CODE = 154;
const REASON = 'Domain accepts no mail (Null MX, RFC7505)';
}

View File

@@ -2,7 +2,7 @@
namespace Egulias\EmailValidator\Exception; namespace Egulias\EmailValidator\Exception;
class ExpectedQPair extends InvalidEmail class ExpectingQPair extends InvalidEmail
{ {
const CODE = 136; const CODE = 136;
const REASON = "Expecting QPAIR"; const REASON = "Expecting QPAIR";

View File

@@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class LocalOrReservedDomain extends InvalidEmail
{
const CODE = 153;
const REASON = 'Local, mDNS or reserved domain (RFC2606, RFC6762)';
}

View File

@@ -2,8 +2,6 @@
namespace Egulias\EmailValidator\Exception; namespace Egulias\EmailValidator\Exception;
use Egulias\EmailValidator\Exception\InvalidEmail;
class NoDNSRecord extends InvalidEmail class NoDNSRecord extends InvalidEmail
{ {
const CODE = 5; const CODE = 5;

View File

@@ -5,5 +5,5 @@ namespace Egulias\EmailValidator\Exception;
class UnclosedComment extends InvalidEmail class UnclosedComment extends InvalidEmail
{ {
const CODE = 146; const CODE = 146;
const REASON = "No colosing comment token found"; const REASON = "No closing comment token found";
} }

View File

@@ -35,27 +35,18 @@ use Egulias\EmailValidator\Warning\TLD;
class DomainPart extends Parser class DomainPart extends Parser
{ {
const DOMAIN_MAX_LENGTH = 254; const DOMAIN_MAX_LENGTH = 254;
const LABEL_MAX_LENGTH = 63;
/**
* @var string
*/
protected $domainPart = ''; protected $domainPart = '';
public function parse($domainPart) public function parse($domainPart)
{ {
$this->lexer->moveNext(); $this->lexer->moveNext();
if ($this->lexer->token['type'] === EmailLexer::S_DOT) { $this->performDomainStartChecks();
throw new DotAtStart();
}
if ($this->lexer->token['type'] === EmailLexer::S_EMPTY) {
throw new NoDomainPart();
}
if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN) {
throw new DomainHyphened();
}
if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) {
$this->warnings[DeprecatedComment::CODE] = new DeprecatedComment();
$this->parseDomainComments();
}
$domain = $this->doParseDomainPart(); $domain = $this->doParseDomainPart();
@@ -77,11 +68,50 @@ class DomainPart extends Parser
$this->domainPart = $domain; $this->domainPart = $domain;
} }
private function performDomainStartChecks()
{
$this->checkInvalidTokensAfterAT();
$this->checkEmptyDomain();
if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) {
$this->warnings[DeprecatedComment::CODE] = new DeprecatedComment();
$this->parseDomainComments();
}
}
private function checkEmptyDomain()
{
$thereIsNoDomain = $this->lexer->token['type'] === EmailLexer::S_EMPTY ||
($this->lexer->token['type'] === EmailLexer::S_SP &&
!$this->lexer->isNextToken(EmailLexer::GENERIC));
if ($thereIsNoDomain) {
throw new NoDomainPart();
}
}
private function checkInvalidTokensAfterAT()
{
if ($this->lexer->token['type'] === EmailLexer::S_DOT) {
throw new DotAtStart();
}
if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN) {
throw new DomainHyphened();
}
}
/**
* @return string
*/
public function getDomainPart() public function getDomainPart()
{ {
return $this->domainPart; return $this->domainPart;
} }
/**
* @param string $addressLiteral
* @param int $maxGroups
*/
public function checkIPV6Tag($addressLiteral, $maxGroups = 8) public function checkIPV6Tag($addressLiteral, $maxGroups = 8)
{ {
$prev = $this->lexer->getPrevious(); $prev = $this->lexer->getPrevious();
@@ -125,9 +155,13 @@ class DomainPart extends Parser
} }
} }
/**
* @return string
*/
protected function doParseDomainPart() protected function doParseDomainPart()
{ {
$domain = ''; $domain = '';
$label = '';
$openedParenthesis = 0; $openedParenthesis = 0;
do { do {
$prev = $this->lexer->getPrevious(); $prev = $this->lexer->getPrevious();
@@ -158,7 +192,12 @@ class DomainPart extends Parser
$this->parseDomainLiteral(); $this->parseDomainLiteral();
} }
$this->checkLabelLength($prev); if ($this->lexer->token['type'] === EmailLexer::S_DOT) {
$this->checkLabelLength($label);
$label = '';
} else {
$label .= $this->lexer->token['value'];
}
if ($this->isFWS()) { if ($this->isFWS()) {
$this->parseFWS(); $this->parseFWS();
@@ -166,12 +205,17 @@ class DomainPart extends Parser
$domain .= $this->lexer->token['value']; $domain .= $this->lexer->token['value'];
$this->lexer->moveNext(); $this->lexer->moveNext();
} while ($this->lexer->token); if ($this->lexer->token['type'] === EmailLexer::S_SP) {
throw new CharNotAllowed();
}
} while (null !== $this->lexer->token['type']);
$this->checkLabelLength($label);
return $domain; return $domain;
} }
private function checkNotAllowedChars($token) private function checkNotAllowedChars(array $token)
{ {
$notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH=> true]; $notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH=> true];
if (isset($notAllowed[$token['type']])) { if (isset($notAllowed[$token['type']])) {
@@ -179,6 +223,9 @@ class DomainPart extends Parser
} }
} }
/**
* @return string|false
*/
protected function parseDomainLiteral() protected function parseDomainLiteral()
{ {
if ($this->lexer->isNextToken(EmailLexer::S_COLON)) { if ($this->lexer->isNextToken(EmailLexer::S_COLON)) {
@@ -195,6 +242,9 @@ class DomainPart extends Parser
return $this->doParseDomainLiteral(); return $this->doParseDomainLiteral();
} }
/**
* @return string|false
*/
protected function doParseDomainLiteral() protected function doParseDomainLiteral()
{ {
$IPv6TAG = false; $IPv6TAG = false;
@@ -262,6 +312,11 @@ class DomainPart extends Parser
return $addressLiteral; return $addressLiteral;
} }
/**
* @param string $addressLiteral
*
* @return string|false
*/
protected function checkIPV4Tag($addressLiteral) protected function checkIPV4Tag($addressLiteral)
{ {
$matchesIP = array(); $matchesIP = array();
@@ -279,16 +334,18 @@ class DomainPart extends Parser
return false; return false;
} }
// Convert IPv4 part to IPv6 format for further testing // Convert IPv4 part to IPv6 format for further testing
$addressLiteral = substr($addressLiteral, 0, $index) . '0:0'; $addressLiteral = substr($addressLiteral, 0, (int) $index) . '0:0';
} }
return $addressLiteral; return $addressLiteral;
} }
protected function checkDomainPartExceptions($prev) protected function checkDomainPartExceptions(array $prev)
{ {
$invalidDomainTokens = array( $invalidDomainTokens = array(
EmailLexer::S_DQUOTE => true, EmailLexer::S_DQUOTE => true,
EmailLexer::S_SQUOTE => true,
EmailLexer::S_BACKTICK => true,
EmailLexer::S_SEMICOLON => true, EmailLexer::S_SEMICOLON => true,
EmailLexer::S_GREATERTHAN => true, EmailLexer::S_GREATERTHAN => true,
EmailLexer::S_LOWERTHAN => true, EmailLexer::S_LOWERTHAN => true,
@@ -320,6 +377,9 @@ class DomainPart extends Parser
} }
} }
/**
* @return bool
*/
protected function hasBrackets() protected function hasBrackets()
{ {
if ($this->lexer->token['type'] !== EmailLexer::S_OPENBRACKET) { if ($this->lexer->token['type'] !== EmailLexer::S_OPENBRACKET) {
@@ -335,16 +395,31 @@ class DomainPart extends Parser
return true; return true;
} }
protected function checkLabelLength($prev) /**
* @param string $label
*/
protected function checkLabelLength($label)
{ {
if ($this->lexer->token['type'] === EmailLexer::S_DOT && if ($this->isLabelTooLong($label)) {
$prev['type'] === EmailLexer::GENERIC &&
strlen($prev['value']) > 63
) {
$this->warnings[LabelTooLong::CODE] = new LabelTooLong(); $this->warnings[LabelTooLong::CODE] = new LabelTooLong();
} }
} }
/**
* @param string $label
* @return bool
*/
private function isLabelTooLong($label)
{
if (preg_match('/[^\x00-\x7F]/', $label)) {
idn_to_ascii($label, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46, $idnaInfo);
return (bool) ($idnaInfo['errors'] & IDNA_ERROR_LABEL_TOO_LONG);
}
return strlen($label) > self::LABEL_MAX_LENGTH;
}
protected function parseDomainComments() protected function parseDomainComments()
{ {
$this->isUnclosedComment(); $this->isUnclosedComment();

View File

@@ -5,7 +5,6 @@ namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\Exception\DotAtEnd; use Egulias\EmailValidator\Exception\DotAtEnd;
use Egulias\EmailValidator\Exception\DotAtStart; use Egulias\EmailValidator\Exception\DotAtStart;
use Egulias\EmailValidator\EmailLexer; use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Exception\ExpectingAT; use Egulias\EmailValidator\Exception\ExpectingAT;
use Egulias\EmailValidator\Exception\ExpectingATEXT; use Egulias\EmailValidator\Exception\ExpectingATEXT;
use Egulias\EmailValidator\Exception\UnclosedQuotedString; use Egulias\EmailValidator\Exception\UnclosedQuotedString;
@@ -20,9 +19,10 @@ class LocalPart extends Parser
$parseDQuote = true; $parseDQuote = true;
$closingQuote = false; $closingQuote = false;
$openedParenthesis = 0; $openedParenthesis = 0;
$totalLength = 0;
while ($this->lexer->token['type'] !== EmailLexer::S_AT && $this->lexer->token) { while ($this->lexer->token['type'] !== EmailLexer::S_AT && null !== $this->lexer->token['type']) {
if ($this->lexer->token['type'] === EmailLexer::S_DOT && !$this->lexer->getPrevious()) { if ($this->lexer->token['type'] === EmailLexer::S_DOT && null === $this->lexer->getPrevious()['type']) {
throw new DotAtStart(); throw new DotAtStart();
} }
@@ -35,12 +35,13 @@ class LocalPart extends Parser
$this->parseComments(); $this->parseComments();
$openedParenthesis += $this->getOpenedParenthesis(); $openedParenthesis += $this->getOpenedParenthesis();
} }
if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) { if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) {
if ($openedParenthesis === 0) { if ($openedParenthesis === 0) {
throw new UnopenedComment(); throw new UnopenedComment();
} else {
$openedParenthesis--;
} }
$openedParenthesis--;
} }
$this->checkConsecutiveDots(); $this->checkConsecutiveDots();
@@ -58,15 +59,18 @@ class LocalPart extends Parser
$this->parseFWS(); $this->parseFWS();
} }
$totalLength += strlen($this->lexer->token['value']);
$this->lexer->moveNext(); $this->lexer->moveNext();
} }
$prev = $this->lexer->getPrevious(); if ($totalLength > LocalTooLong::LOCAL_PART_LENGTH) {
if (strlen($prev['value']) > LocalTooLong::LOCAL_PART_LENGTH) {
$this->warnings[LocalTooLong::CODE] = new LocalTooLong(); $this->warnings[LocalTooLong::CODE] = new LocalTooLong();
} }
} }
/**
* @return bool
*/
protected function parseDoubleQuote() protected function parseDoubleQuote()
{ {
$parseAgain = true; $parseAgain = true;
@@ -86,7 +90,7 @@ class LocalPart extends Parser
$this->lexer->moveNext(); $this->lexer->moveNext();
while ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE && $this->lexer->token) { while ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE && null !== $this->lexer->token['type']) {
$parseAgain = false; $parseAgain = false;
if (isset($special[$this->lexer->token['type']]) && $setSpecialsWarning) { if (isset($special[$this->lexer->token['type']]) && $setSpecialsWarning) {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
@@ -118,7 +122,10 @@ class LocalPart extends Parser
return $parseAgain; return $parseAgain;
} }
protected function isInvalidToken($token, $closingQuote) /**
* @param bool $closingQuote
*/
protected function isInvalidToken(array $token, $closingQuote)
{ {
$forbidden = array( $forbidden = array(
EmailLexer::S_COMMA, EmailLexer::S_COMMA,

View File

@@ -8,7 +8,7 @@ use Egulias\EmailValidator\Exception\ConsecutiveDot;
use Egulias\EmailValidator\Exception\CRLFAtTheEnd; use Egulias\EmailValidator\Exception\CRLFAtTheEnd;
use Egulias\EmailValidator\Exception\CRLFX2; use Egulias\EmailValidator\Exception\CRLFX2;
use Egulias\EmailValidator\Exception\CRNoLF; use Egulias\EmailValidator\Exception\CRNoLF;
use Egulias\EmailValidator\Exception\ExpectedQPair; use Egulias\EmailValidator\Exception\ExpectingQPair;
use Egulias\EmailValidator\Exception\ExpectingATEXT; use Egulias\EmailValidator\Exception\ExpectingATEXT;
use Egulias\EmailValidator\Exception\ExpectingCTEXT; use Egulias\EmailValidator\Exception\ExpectingCTEXT;
use Egulias\EmailValidator\Exception\UnclosedComment; use Egulias\EmailValidator\Exception\UnclosedComment;
@@ -21,8 +21,19 @@ use Egulias\EmailValidator\Warning\QuotedString;
abstract class Parser abstract class Parser
{ {
/**
* @var array
*/
protected $warnings = []; protected $warnings = [];
/**
* @var EmailLexer
*/
protected $lexer; protected $lexer;
/**
* @var int
*/
protected $openedParenthesis = 0; protected $openedParenthesis = 0;
public function __construct(EmailLexer $lexer) public function __construct(EmailLexer $lexer)
@@ -30,11 +41,17 @@ abstract class Parser
$this->lexer = $lexer; $this->lexer = $lexer;
} }
/**
* @return \Egulias\EmailValidator\Warning\Warning[]
*/
public function getWarnings() public function getWarnings()
{ {
return $this->warnings; return $this->warnings;
} }
/**
* @param string $str
*/
abstract public function parse($str); abstract public function parse($str);
/** @return int */ /** @return int */
@@ -50,7 +67,7 @@ abstract class Parser
{ {
if (!($this->lexer->token['type'] === EmailLexer::INVALID if (!($this->lexer->token['type'] === EmailLexer::INVALID
|| $this->lexer->token['type'] === EmailLexer::C_DEL)) { || $this->lexer->token['type'] === EmailLexer::C_DEL)) {
throw new ExpectedQPair(); throw new ExpectingQPair();
} }
$this->warnings[QuotedPart::CODE] = $this->warnings[QuotedPart::CODE] =
@@ -80,6 +97,9 @@ abstract class Parser
} }
} }
/**
* @return bool
*/
protected function isUnclosedComment() protected function isUnclosedComment()
{ {
try { try {
@@ -122,6 +142,9 @@ abstract class Parser
} }
} }
/**
* @return bool
*/
protected function isFWS() protected function isFWS()
{ {
if ($this->escaped()) { if ($this->escaped()) {
@@ -140,11 +163,14 @@ abstract class Parser
return false; return false;
} }
/**
* @return bool
*/
protected function escaped() protected function escaped()
{ {
$previous = $this->lexer->getPrevious(); $previous = $this->lexer->getPrevious();
if ($previous['type'] === EmailLexer::S_BACKSLASH if ($previous && $previous['type'] === EmailLexer::S_BACKSLASH
&& &&
$this->lexer->token['type'] !== EmailLexer::GENERIC $this->lexer->token['type'] !== EmailLexer::GENERIC
) { ) {
@@ -154,6 +180,9 @@ abstract class Parser
return false; return false;
} }
/**
* @return bool
*/
protected function warnEscaping() protected function warnEscaping()
{ {
if ($this->lexer->token['type'] !== EmailLexer::S_BACKSLASH) { if ($this->lexer->token['type'] !== EmailLexer::S_BACKSLASH) {
@@ -174,6 +203,11 @@ abstract class Parser
} }
/**
* @param bool $hasClosingQuote
*
* @return bool
*/
protected function checkDQUOTE($hasClosingQuote) protected function checkDQUOTE($hasClosingQuote)
{ {
if ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE) { if ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE) {

View File

@@ -4,6 +4,8 @@ namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer; use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Exception\InvalidEmail; use Egulias\EmailValidator\Exception\InvalidEmail;
use Egulias\EmailValidator\Exception\LocalOrReservedDomain;
use Egulias\EmailValidator\Exception\DomainAcceptsNoMail;
use Egulias\EmailValidator\Warning\NoDNSMXRecord; use Egulias\EmailValidator\Warning\NoDNSMXRecord;
use Egulias\EmailValidator\Exception\NoDNSRecord; use Egulias\EmailValidator\Exception\NoDNSRecord;
@@ -15,10 +17,23 @@ class DNSCheckValidation implements EmailValidation
private $warnings = []; private $warnings = [];
/** /**
* @var InvalidEmail * @var InvalidEmail|null
*/ */
private $error; private $error;
/**
* @var array
*/
private $mxRecords = [];
public function __construct()
{
if (!function_exists('idn_to_ascii')) {
throw new \LogicException(sprintf('The %s class requires the Intl extension.', __CLASS__));
}
}
public function isValid($email, EmailLexer $emailLexer) public function isValid($email, EmailLexer $emailLexer)
{ {
// use the input to check DNS if we cannot extract something similar to a domain // use the input to check DNS if we cannot extract something similar to a domain
@@ -29,7 +44,40 @@ class DNSCheckValidation implements EmailValidation
$host = substr($email, $lastAtPos + 1); $host = substr($email, $lastAtPos + 1);
} }
return $this->checkDNS($host); // Get the domain parts
$hostParts = explode('.', $host);
// Reserved Top Level DNS Names (https://tools.ietf.org/html/rfc2606#section-2),
// mDNS and private DNS Namespaces (https://tools.ietf.org/html/rfc6762#appendix-G)
$reservedTopLevelDnsNames = [
// Reserved Top Level DNS Names
'test',
'example',
'invalid',
'localhost',
// mDNS
'local',
// Private DNS Namespaces
'intranet',
'internal',
'private',
'corp',
'home',
'lan',
];
$isLocalDomain = count($hostParts) <= 1;
$isReservedTopLevel = in_array($hostParts[(count($hostParts) - 1)], $reservedTopLevelDnsNames, true);
// Exclude reserved top level DNS names
if ($isLocalDomain || $isReservedTopLevel) {
$this->error = new LocalOrReservedDomain();
return false;
}
return $this->checkDns($host);
} }
public function getError() public function getError()
@@ -42,20 +90,77 @@ class DNSCheckValidation implements EmailValidation
return $this->warnings; return $this->warnings;
} }
protected function checkDNS($host) /**
* @param string $host
*
* @return bool
*/
protected function checkDns($host)
{ {
$host = rtrim($host, '.') . '.'; $variant = INTL_IDNA_VARIANT_UTS46;
$Aresult = true; $host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.') . '.';
$MXresult = checkdnsrr($host, 'MX');
if (!$MXresult) { return $this->validateDnsRecords($host);
$this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord(); }
$Aresult = checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA');
if (!$Aresult) {
$this->error = new NoDNSRecord(); /**
* Validate the DNS records for given host.
*
* @param string $host A set of DNS records in the format returned by dns_get_record.
*
* @return bool True on success.
*/
private function validateDnsRecords($host)
{
// Get all MX, A and AAAA DNS records for host
// Using @ as workaround to fix https://bugs.php.net/bug.php?id=73149
$dnsRecords = @dns_get_record($host, DNS_MX + DNS_A + DNS_AAAA);
// No MX, A or AAAA DNS records
if (empty($dnsRecords)) {
$this->error = new NoDNSRecord();
return false;
}
// For each DNS record
foreach ($dnsRecords as $dnsRecord) {
if (!$this->validateMXRecord($dnsRecord)) {
return false;
} }
} }
return $MXresult || $Aresult;
// No MX records (fallback to A or AAAA records)
if (empty($this->mxRecords)) {
$this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord();
}
return true;
}
/**
* Validate an MX record
*
* @param array $dnsRecord Given DNS record.
*
* @return bool True if valid.
*/
private function validateMxRecord($dnsRecord)
{
if ($dnsRecord['type'] !== 'MX') {
return true;
}
// "Null MX" record indicates the domain accepts no mail (https://tools.ietf.org/html/rfc7505)
if (empty($dnsRecord['target']) || $dnsRecord['target'] === '.') {
$this->error = new DomainAcceptsNoMail();
return false;
}
$this->mxRecords[] = $dnsRecord;
return true;
} }
} }

View File

@@ -6,6 +6,9 @@ use Exception;
class EmptyValidationList extends \InvalidArgumentException class EmptyValidationList extends \InvalidArgumentException
{ {
/**
* @param int $code
*/
public function __construct($code = 0, Exception $previous = null) public function __construct($code = 0, Exception $previous = null)
{ {
parent::__construct("Empty validation list is not allowed", $code, $previous); parent::__construct("Empty validation list is not allowed", $code, $previous);

View File

@@ -9,16 +9,22 @@ class MultipleErrors extends InvalidEmail
const CODE = 999; const CODE = 999;
const REASON = "Accumulated errors for multiple validations"; const REASON = "Accumulated errors for multiple validations";
/** /**
* @var array * @var InvalidEmail[]
*/ */
private $errors = []; private $errors = [];
/**
* @param InvalidEmail[] $errors
*/
public function __construct(array $errors) public function __construct(array $errors)
{ {
$this->errors = $errors; $this->errors = $errors;
parent::__construct(); parent::__construct();
} }
/**
* @return InvalidEmail[]
*/
public function getErrors() public function getErrors()
{ {
return $this->errors; return $this->errors;

View File

@@ -30,12 +30,12 @@ class MultipleValidationWithAnd implements EmailValidation
private $warnings = []; private $warnings = [];
/** /**
* @var MultipleErrors * @var MultipleErrors|null
*/ */
private $error; private $error;
/** /**
* @var bool * @var int
*/ */
private $mode; private $mode;
@@ -62,7 +62,8 @@ class MultipleValidationWithAnd implements EmailValidation
$errors = []; $errors = [];
foreach ($this->validations as $validation) { foreach ($this->validations as $validation) {
$emailLexer->reset(); $emailLexer->reset();
$result = $result && $validation->isValid($email, $emailLexer); $validationResult = $validation->isValid($email, $emailLexer);
$result = $result && $validationResult;
$this->warnings = array_merge($this->warnings, $validation->getWarnings()); $this->warnings = array_merge($this->warnings, $validation->getWarnings());
$errors = $this->addNewError($validation->getError(), $errors); $errors = $this->addNewError($validation->getError(), $errors);
@@ -78,6 +79,12 @@ class MultipleValidationWithAnd implements EmailValidation
return $result; return $result;
} }
/**
* @param \Egulias\EmailValidator\Exception\InvalidEmail|null $possibleError
* @param \Egulias\EmailValidator\Exception\InvalidEmail[] $errors
*
* @return \Egulias\EmailValidator\Exception\InvalidEmail[]
*/
private function addNewError($possibleError, array $errors) private function addNewError($possibleError, array $errors)
{ {
if (null !== $possibleError) { if (null !== $possibleError) {
@@ -87,13 +94,20 @@ class MultipleValidationWithAnd implements EmailValidation
return $errors; return $errors;
} }
/**
* @param bool $result
*
* @return bool
*/
private function shouldStop($result) private function shouldStop($result)
{ {
return !$result && $this->mode === self::STOP_ON_ERROR; return !$result && $this->mode === self::STOP_ON_ERROR;
} }
/** /**
* {@inheritdoc} * Returns the validation errors.
*
* @return MultipleErrors|null
*/ */
public function getError() public function getError()
{ {

View File

@@ -9,7 +9,7 @@ use Egulias\EmailValidator\Validation\Error\RFCWarnings;
class NoRFCWarningsValidation extends RFCValidation class NoRFCWarningsValidation extends RFCValidation
{ {
/** /**
* @var InvalidEmail * @var InvalidEmail|null
*/ */
private $error; private $error;
@@ -22,8 +22,7 @@ class NoRFCWarningsValidation extends RFCValidation
return false; return false;
} }
$ret = $this->getWarnings(); if (empty($this->getWarnings())) {
if (empty($ret)) {
return true; return true;
} }

View File

@@ -9,7 +9,7 @@ use Egulias\EmailValidator\Exception\InvalidEmail;
class RFCValidation implements EmailValidation class RFCValidation implements EmailValidation
{ {
/** /**
* @var EmailParser * @var EmailParser|null
*/ */
private $parser; private $parser;
@@ -19,7 +19,7 @@ class RFCValidation implements EmailValidation
private $warnings = []; private $warnings = [];
/** /**
* @var InvalidEmail * @var InvalidEmail|null
*/ */
private $error; private $error;

View File

@@ -10,7 +10,7 @@ use \Spoofchecker;
class SpoofCheckValidation implements EmailValidation class SpoofCheckValidation implements EmailValidation
{ {
/** /**
* @var InvalidEmail * @var InvalidEmail|null
*/ */
private $error; private $error;
@@ -21,6 +21,9 @@ class SpoofCheckValidation implements EmailValidation
} }
} }
/**
* @psalm-suppress InvalidArgument
*/
public function isValid($email, EmailLexer $emailLexer) public function isValid($email, EmailLexer $emailLexer)
{ {
$checker = new Spoofchecker(); $checker = new Spoofchecker();
@@ -33,6 +36,9 @@ class SpoofCheckValidation implements EmailValidation
return $this->error === null; return $this->error === null;
} }
/**
* @return InvalidEmail|null
*/
public function getError() public function getError()
{ {
return $this->error; return $this->error;

View File

@@ -6,6 +6,10 @@ class QuotedPart extends Warning
{ {
const CODE = 36; const CODE = 36;
/**
* @param scalar $prevToken
* @param scalar $postToken
*/
public function __construct($prevToken, $postToken) public function __construct($prevToken, $postToken)
{ {
$this->message = "Deprecated Quoted String found between $prevToken and $postToken"; $this->message = "Deprecated Quoted String found between $prevToken and $postToken";

View File

@@ -6,6 +6,10 @@ class QuotedString extends Warning
{ {
const CODE = 11; const CODE = 11;
/**
* @param scalar $prevToken
* @param scalar $postToken
*/
public function __construct($prevToken, $postToken) public function __construct($prevToken, $postToken)
{ {
$this->message = "Quoted String found between $prevToken and $postToken"; $this->message = "Quoted String found between $prevToken and $postToken";

View File

@@ -5,19 +5,36 @@ namespace Egulias\EmailValidator\Warning;
abstract class Warning abstract class Warning
{ {
const CODE = 0; const CODE = 0;
protected $message;
protected $rfcNumber;
/**
* @var string
*/
protected $message = '';
/**
* @var int
*/
protected $rfcNumber = 0;
/**
* @return string
*/
public function message() public function message()
{ {
return $this->message; return $this->message;
} }
/**
* @return int
*/
public function code() public function code()
{ {
return self::CODE; return static::CODE;
} }
/**
* @return int
*/
public function RFCNumber() public function RFCNumber()
{ {
return $this->rfcNumber; return $this->rfcNumber;

View File

@@ -258,6 +258,11 @@ abstract class AbstractLexer
$flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE; $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE;
$matches = preg_split($regex, $input, -1, $flags); $matches = preg_split($regex, $input, -1, $flags);
if (false === $matches) {
// Work around https://bugs.php.net/78122
$matches = array(array($input, 0));
}
foreach ($matches as $match) { foreach ($matches as $match) {
// Must remain before 'value' assignment since it can change content // Must remain before 'value' assignment since it can change content
$type = $this->getType($match[0]); $type = $this->getType($match[0]);

View File

@@ -11,15 +11,14 @@
/** /**
* General utility class in Swift Mailer, not to be instantiated. * General utility class in Swift Mailer, not to be instantiated.
* *
*
* @author Chris Corbyn * @author Chris Corbyn
*/ */
abstract class Swift abstract class Swift
{ {
const VERSION = '6.0.2'; const VERSION = '6.3.0';
public static $initialized = false; public static $initialized = false;
public static $inits = array(); public static $inits = [];
/** /**
* Registers an initializer callable that will be called the first time * Registers an initializer callable that will be called the first time
@@ -57,7 +56,7 @@ abstract class Swift
if (self::$inits && !self::$initialized) { if (self::$inits && !self::$initialized) {
self::$initialized = true; self::$initialized = true;
foreach (self::$inits as $init) { foreach (self::$inits as $init) {
call_user_func($init); \call_user_func($init);
} }
} }
} }
@@ -74,6 +73,6 @@ abstract class Swift
if (null !== $callable) { if (null !== $callable) {
self::$inits[] = $callable; self::$inits[] = $callable;
} }
spl_autoload_register(array('Swift', 'autoload')); spl_autoload_register(['Swift', 'autoload']);
} }
} }

View File

@@ -0,0 +1,25 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2018 Christian Schmidt
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Email address encoder.
*
* @author Christian Schmidt
*/
interface Swift_AddressEncoder
{
/**
* Encodes an email address.
*
* @throws Swift_AddressEncoderException if the email cannot be represented in
* the encoding implemented by this class
*/
public function encodeString(string $address): string;
}

View File

@@ -0,0 +1,50 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2018 Christian Schmidt
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An IDN email address encoder.
*
* Encodes the domain part of an address using IDN. This is compatible will all
* SMTP servers.
*
* This encoder does not support email addresses with non-ASCII characters in
* local-part (the substring before @). To send to such addresses, use
* Swift_AddressEncoder_Utf8AddressEncoder together with
* Swift_Transport_Esmtp_SmtpUtf8Handler. Your outbound SMTP server must support
* the SMTPUTF8 extension.
*
* @author Christian Schmidt
*/
class Swift_AddressEncoder_IdnAddressEncoder implements Swift_AddressEncoder
{
/**
* Encodes the domain part of an address using IDN.
*
* @throws Swift_AddressEncoderException If local-part contains non-ASCII characters
*/
public function encodeString(string $address): string
{
$i = strrpos($address, '@');
if (false !== $i) {
$local = substr($address, 0, $i);
$domain = substr($address, $i + 1);
if (preg_match('/[^\x00-\x7F]/', $local)) {
throw new Swift_AddressEncoderException('Non-ASCII characters not supported in local-part', $address);
}
if (preg_match('/[^\x00-\x7F]/', $domain)) {
$address = sprintf('%s@%s', $local, idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46));
}
}
return $address;
}
}

View File

@@ -0,0 +1,36 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2018 Christian Schmidt
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A UTF-8 email address encoder.
*
* Returns the email address verbatimly in UTF-8 as permitted by RFC 6531 and
* RFC 6532. It supports addresses containing non-ASCII characters in both
* local-part and domain (i.e. on both sides of @).
*
* This encoder must be used together with Swift_Transport_Esmtp_SmtpUtf8Handler
* and requires that the outbound SMTP server supports the SMTPUTF8 extension.
*
* If your outbound SMTP server does not support SMTPUTF8, use
* Swift_AddressEncoder_IdnAddressEncoder instead. This allows sending to email
* addresses with non-ASCII characters in the domain, but not in local-part.
*
* @author Christian Schmidt
*/
class Swift_AddressEncoder_Utf8AddressEncoder implements Swift_AddressEncoder
{
/**
* Returns the address verbatimly.
*/
public function encodeString(string $address): string
{
return $address;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2018 Christian Schmidt
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* AddressEncoderException when the specified email address is in a format that
* cannot be encoded by a given address encoder.
*
* @author Christian Schmidt
*/
class Swift_AddressEncoderException extends Swift_RfcComplianceException
{
protected $address;
public function __construct(string $message, string $address)
{
parent::__construct($message);
$this->address = $address;
}
public function getAddress(): string
{
return $this->address;
}
}

View File

@@ -26,17 +26,14 @@ class Swift_Attachment extends Swift_Mime_Attachment
*/ */
public function __construct($data = null, $filename = null, $contentType = null) public function __construct($data = null, $filename = null, $contentType = null)
{ {
call_user_func_array( \call_user_func_array(
array($this, 'Swift_Mime_Attachment::__construct'), [$this, 'Swift_Mime_Attachment::__construct'],
Swift_DependencyContainer::getInstance() Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.attachment') ->createDependenciesFor('mime.attachment')
); );
$this->setBody($data); $this->setBody($data, $contentType);
$this->setFilename($filename); $this->setFilename($filename);
if ($contentType) {
$this->setContentType($contentType);
}
} }
/** /**
@@ -45,7 +42,7 @@ class Swift_Attachment extends Swift_Mime_Attachment
* @param string $path * @param string $path
* @param string $contentType optional * @param string $contentType optional
* *
* @return Swift_Mime_Attachment * @return self
*/ */
public static function fromPath($path, $contentType = null) public static function fromPath($path, $contentType = null)
{ {

View File

@@ -25,7 +25,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
* *
* @var Swift_StreamFilter[] * @var Swift_StreamFilter[]
*/ */
private $filters = array(); private $filters = [];
/** /**
* A buffer for writing. * A buffer for writing.
@@ -37,7 +37,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
* *
* @var Swift_InputByteStream[] * @var Swift_InputByteStream[]
*/ */
private $mirrors = array(); private $mirrors = [];
/** /**
* Commit the given bytes to the storage medium immediately. * Commit the given bytes to the storage medium immediately.
@@ -54,8 +54,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
/** /**
* Add a StreamFilter to this InputByteStream. * Add a StreamFilter to this InputByteStream.
* *
* @param Swift_StreamFilter $filter * @param string $key
* @param string $key
*/ */
public function addFilter(Swift_StreamFilter $filter, $key) public function addFilter(Swift_StreamFilter $filter, $key)
{ {
@@ -110,8 +109,6 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
* *
* The stream acts as an observer, receiving all data that is written. * The stream acts as an observer, receiving all data that is written.
* All {@link write()} and {@link flushBuffers()} operations will be mirrored. * All {@link write()} and {@link flushBuffers()} operations will be mirrored.
*
* @param Swift_InputByteStream $is
*/ */
public function bind(Swift_InputByteStream $is) public function bind(Swift_InputByteStream $is)
{ {
@@ -124,14 +121,12 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
* If $is is not bound, no errors will be raised. * If $is is not bound, no errors will be raised.
* If the stream currently has any buffered data it will be written to $is * If the stream currently has any buffered data it will be written to $is
* before unbinding occurs. * before unbinding occurs.
*
* @param Swift_InputByteStream $is
*/ */
public function unbind(Swift_InputByteStream $is) public function unbind(Swift_InputByteStream $is)
{ {
foreach ($this->mirrors as $k => $stream) { foreach ($this->mirrors as $k => $stream) {
if ($is === $stream) { if ($is === $stream) {
if ($this->writeBuffer !== '') { if ('' !== $this->writeBuffer) {
$stream->write($this->writeBuffer); $stream->write($this->writeBuffer);
} }
unset($this->mirrors[$k]); unset($this->mirrors[$k]);
@@ -147,7 +142,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
*/ */
public function flushBuffers() public function flushBuffers()
{ {
if ($this->writeBuffer !== '') { if ('' !== $this->writeBuffer) {
$this->doWrite($this->writeBuffer); $this->doWrite($this->writeBuffer);
} }
$this->flush(); $this->flush();

View File

@@ -20,7 +20,7 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
* *
* @var string[] * @var string[]
*/ */
private $array = array(); private $array = [];
/** /**
* The size of the stack. * The size of the stack.
@@ -41,7 +41,7 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
* *
* @var Swift_InputByteStream[] * @var Swift_InputByteStream[]
*/ */
private $mirrors = array(); private $mirrors = [];
/** /**
* Create a new ArrayByteStream. * Create a new ArrayByteStream.
@@ -52,13 +52,13 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
*/ */
public function __construct($stack = null) public function __construct($stack = null)
{ {
if (is_array($stack)) { if (\is_array($stack)) {
$this->array = $stack; $this->array = $stack;
$this->arraySize = count($stack); $this->arraySize = \count($stack);
} elseif (is_string($stack)) { } elseif (\is_string($stack)) {
$this->write($stack); $this->write($stack);
} else { } else {
$this->array = array(); $this->array = [];
} }
} }
@@ -102,7 +102,7 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
foreach ($to_add as $value) { foreach ($to_add as $value) {
$this->array[] = $value; $this->array[] = $value;
} }
$this->arraySize = count($this->array); $this->arraySize = \count($this->array);
foreach ($this->mirrors as $stream) { foreach ($this->mirrors as $stream) {
$stream->write($bytes); $stream->write($bytes);
@@ -121,8 +121,6 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
* *
* The stream acts as an observer, receiving all data that is written. * The stream acts as an observer, receiving all data that is written.
* All {@link write()} and {@link flushBuffers()} operations will be mirrored. * All {@link write()} and {@link flushBuffers()} operations will be mirrored.
*
* @param Swift_InputByteStream $is
*/ */
public function bind(Swift_InputByteStream $is) public function bind(Swift_InputByteStream $is)
{ {
@@ -135,8 +133,6 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
* If $is is not bound, no errors will be raised. * If $is is not bound, no errors will be raised.
* If the stream currently has any buffered data it will be written to $is * If the stream currently has any buffered data it will be written to $is
* before unbinding occurs. * before unbinding occurs.
*
* @param Swift_InputByteStream $is
*/ */
public function unbind(Swift_InputByteStream $is) public function unbind(Swift_InputByteStream $is)
{ {
@@ -172,7 +168,7 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
public function flushBuffers() public function flushBuffers()
{ {
$this->offset = 0; $this->offset = 0;
$this->array = array(); $this->array = [];
$this->arraySize = 0; $this->arraySize = 0;
foreach ($this->mirrors as $stream) { foreach ($this->mirrors as $stream) {

View File

@@ -81,7 +81,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
// If we read one byte after reaching the end of the file // If we read one byte after reaching the end of the file
// feof() will return false and an empty string is returned // feof() will return false and an empty string is returned
if ($bytes === '' && feof($fp)) { if ((false === $bytes || '' === $bytes) && feof($fp)) {
$this->resetReadHandle(); $this->resetReadHandle();
return false; return false;
@@ -131,7 +131,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
throw new Swift_IoException('Unable to open file for reading ['.$this->path.']'); throw new Swift_IoException('Unable to open file for reading ['.$this->path.']');
} }
$this->reader = $pointer; $this->reader = $pointer;
if ($this->offset != 0) { if (0 != $this->offset) {
$this->getReadStreamSeekableStatus(); $this->getReadStreamSeekableStatus();
$this->seekReadStreamToPosition($this->offset); $this->seekReadStreamToPosition($this->offset);
} }
@@ -145,9 +145,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
{ {
if (!isset($this->writer)) { if (!isset($this->writer)) {
if (!$this->writer = fopen($this->path, $this->mode)) { if (!$this->writer = fopen($this->path, $this->mode)) {
throw new Swift_IoException( throw new Swift_IoException('Unable to open file for writing ['.$this->path.']');
'Unable to open file for writing ['.$this->path.']'
);
} }
} }
@@ -173,10 +171,10 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
/** Streams in a readOnly stream ensuring copy if needed */ /** Streams in a readOnly stream ensuring copy if needed */
private function seekReadStreamToPosition($offset) private function seekReadStreamToPosition($offset)
{ {
if ($this->seekable === null) { if (null === $this->seekable) {
$this->getReadStreamSeekableStatus(); $this->getReadStreamSeekableStatus();
} }
if ($this->seekable === false) { if (false === $this->seekable) {
$currentPos = ftell($this->reader); $currentPos = ftell($this->reader);
if ($currentPos < $offset) { if ($currentPos < $offset) {
$toDiscard = $offset - $currentPos; $toDiscard = $offset - $currentPos;
@@ -194,7 +192,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
{ {
if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) { if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) {
/* We have opened a php:// Stream Should work without problem */ /* We have opened a php:// Stream Should work without problem */
} elseif (function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir()) && ($tmpFile = tmpfile())) { } elseif (\function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir()) && ($tmpFile = tmpfile())) {
/* We have opened a tmpfile */ /* We have opened a tmpfile */
} else { } else {
throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available'); throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available');

View File

@@ -17,7 +17,7 @@ class Swift_ByteStream_TemporaryFileByteStream extends Swift_ByteStream_FileByte
{ {
$filePath = tempnam(sys_get_temp_dir(), 'FileByteStream'); $filePath = tempnam(sys_get_temp_dir(), 'FileByteStream');
if ($filePath === false) { if (false === $filePath) {
throw new Swift_IoException('Failed to retrieve temporary file name.'); throw new Swift_IoException('Failed to retrieve temporary file name.');
} }
@@ -26,7 +26,7 @@ class Swift_ByteStream_TemporaryFileByteStream extends Swift_ByteStream_FileByte
public function getContent() public function getContent()
{ {
if (($content = file_get_contents($this->getPath())) === false) { if (false === ($content = file_get_contents($this->getPath()))) {
throw new Swift_IoException('Failed to get temporary file content.'); throw new Swift_IoException('Failed to get temporary file content.');
} }
@@ -39,4 +39,14 @@ class Swift_ByteStream_TemporaryFileByteStream extends Swift_ByteStream_FileByte
@unlink($this->getPath()); @unlink($this->getPath());
} }
} }
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
} }

View File

@@ -45,7 +45,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe
*/ */
public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars)
{ {
$strlen = strlen($string); $strlen = \strlen($string);
// % and / are CPU intensive, so, maybe find a better way // % and / are CPU intensive, so, maybe find a better way
$ignored = $strlen % $this->width; $ignored = $strlen % $this->width;
$ignoredChars = $ignored ? substr($string, -$ignored) : ''; $ignoredChars = $ignored ? substr($string, -$ignored) : '';

View File

@@ -27,7 +27,7 @@ class Swift_CharacterReader_UsAsciiReader implements Swift_CharacterReader
*/ */
public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars)
{ {
$strlen = strlen($string); $strlen = \strlen($string);
$ignoredChars = ''; $ignoredChars = '';
for ($i = 0; $i < $strlen; ++$i) { for ($i = 0; $i < $strlen; ++$i) {
if ($string[$i] > "\x07F") { if ($string[$i] > "\x07F") {
@@ -65,7 +65,7 @@ class Swift_CharacterReader_UsAsciiReader implements Swift_CharacterReader
public function validateByteSequence($bytes, $size) public function validateByteSequence($bytes, $size)
{ {
$byte = reset($bytes); $byte = reset($bytes);
if (1 == count($bytes) && $byte >= 0x00 && $byte <= 0x7F) { if (1 == \count($bytes) && $byte >= 0x00 && $byte <= 0x7F) {
return 0; return 0;
} }

View File

@@ -17,8 +17,8 @@
class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader
{ {
/** Pre-computed for optimization */ /** Pre-computed for optimization */
private static $length_map = array( private static $length_map = [
// N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F, // N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x0N 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x0N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1N 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x2N 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x2N
@@ -34,10 +34,10 @@ class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xCN 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xCN
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDN 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDN
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEN 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEN
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0, // 0xFN 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0, // 0xFN
); ];
private static $s_length_map = array( private static $s_length_map = [
"\x00" => 1, "\x01" => 1, "\x02" => 1, "\x03" => 1, "\x04" => 1, "\x05" => 1, "\x06" => 1, "\x07" => 1, "\x00" => 1, "\x01" => 1, "\x02" => 1, "\x03" => 1, "\x04" => 1, "\x05" => 1, "\x06" => 1, "\x07" => 1,
"\x08" => 1, "\x09" => 1, "\x0a" => 1, "\x0b" => 1, "\x0c" => 1, "\x0d" => 1, "\x0e" => 1, "\x0f" => 1, "\x08" => 1, "\x09" => 1, "\x0a" => 1, "\x0b" => 1, "\x0c" => 1, "\x0d" => 1, "\x0e" => 1, "\x0f" => 1,
"\x10" => 1, "\x11" => 1, "\x12" => 1, "\x13" => 1, "\x14" => 1, "\x15" => 1, "\x16" => 1, "\x17" => 1, "\x10" => 1, "\x11" => 1, "\x12" => 1, "\x13" => 1, "\x14" => 1, "\x15" => 1, "\x16" => 1, "\x17" => 1,
@@ -70,7 +70,7 @@ class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader
"\xe8" => 3, "\xe9" => 3, "\xea" => 3, "\xeb" => 3, "\xec" => 3, "\xed" => 3, "\xee" => 3, "\xef" => 3, "\xe8" => 3, "\xe9" => 3, "\xea" => 3, "\xeb" => 3, "\xec" => 3, "\xed" => 3, "\xee" => 3, "\xef" => 3,
"\xf0" => 4, "\xf1" => 4, "\xf2" => 4, "\xf3" => 4, "\xf4" => 4, "\xf5" => 4, "\xf6" => 4, "\xf7" => 4, "\xf0" => 4, "\xf1" => 4, "\xf2" => 4, "\xf3" => 4, "\xf4" => 4, "\xf5" => 4, "\xf6" => 4, "\xf7" => 4,
"\xf8" => 5, "\xf9" => 5, "\xfa" => 5, "\xfb" => 5, "\xfc" => 6, "\xfd" => 6, "\xfe" => 0, "\xff" => 0, "\xf8" => 5, "\xf9" => 5, "\xfa" => 5, "\xfb" => 5, "\xfc" => 6, "\xfd" => 6, "\xfe" => 0, "\xff" => 0,
); ];
/** /**
* Returns the complete character map. * Returns the complete character map.
@@ -85,22 +85,22 @@ class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader
public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars)
{ {
if (!isset($currentMap['i']) || !isset($currentMap['p'])) { if (!isset($currentMap['i']) || !isset($currentMap['p'])) {
$currentMap['p'] = $currentMap['i'] = array(); $currentMap['p'] = $currentMap['i'] = [];
} }
$strlen = strlen($string); $strlen = \strlen($string);
$charPos = count($currentMap['p']); $charPos = \count($currentMap['p']);
$foundChars = 0; $foundChars = 0;
$invalid = false; $invalid = false;
for ($i = 0; $i < $strlen; ++$i) { for ($i = 0; $i < $strlen; ++$i) {
$char = $string[$i]; $char = $string[$i];
$size = self::$s_length_map[$char]; $size = self::$s_length_map[$char];
if ($size == 0) { if (0 == $size) {
/* char is invalid, we must wait for a resync */ /* char is invalid, we must wait for a resync */
$invalid = true; $invalid = true;
continue; continue;
} else { } else {
if ($invalid == true) { if (true === $invalid) {
/* We mark the chars as invalid and start a new char */ /* We mark the chars as invalid and start a new char */
$currentMap['p'][$charPos + $foundChars] = $startOffset + $i; $currentMap['p'][$charPos + $foundChars] = $startOffset + $i;
$currentMap['i'][$charPos + $foundChars] = true; $currentMap['i'][$charPos + $foundChars] = true;

View File

@@ -20,14 +20,14 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift
* *
* @var array * @var array
*/ */
private static $map = array(); private static $map = [];
/** /**
* Factories which have already been loaded. * Factories which have already been loaded.
* *
* @var Swift_CharacterReaderFactory[] * @var Swift_CharacterReaderFactory[]
*/ */
private static $loaded = array(); private static $loaded = [];
/** /**
* Creates a new CharacterReaderFactory. * Creates a new CharacterReaderFactory.
@@ -44,32 +44,32 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift
public function init() public function init()
{ {
if (count(self::$map) > 0) { if (\count(self::$map) > 0) {
return; return;
} }
$prefix = 'Swift_CharacterReader_'; $prefix = 'Swift_CharacterReader_';
$singleByte = array( $singleByte = [
'class' => $prefix.'GenericFixedWidthReader', 'class' => $prefix.'GenericFixedWidthReader',
'constructor' => array(1), 'constructor' => [1],
); ];
$doubleByte = array( $doubleByte = [
'class' => $prefix.'GenericFixedWidthReader', 'class' => $prefix.'GenericFixedWidthReader',
'constructor' => array(2), 'constructor' => [2],
); ];
$fourBytes = array( $fourBytes = [
'class' => $prefix.'GenericFixedWidthReader', 'class' => $prefix.'GenericFixedWidthReader',
'constructor' => array(4), 'constructor' => [4],
); ];
// Utf-8 // Utf-8
self::$map['utf-?8'] = array( self::$map['utf-?8'] = [
'class' => $prefix.'Utf8Reader', 'class' => $prefix.'Utf8Reader',
'constructor' => array(), 'constructor' => [],
); ];
//7-8 bit charsets //7-8 bit charsets
self::$map['(us-)?ascii'] = $singleByte; self::$map['(us-)?ascii'] = $singleByte;
@@ -103,11 +103,11 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift
*/ */
public function getReaderFor($charset) public function getReaderFor($charset)
{ {
$charset = strtolower(trim($charset)); $charset = strtolower(trim($charset ?? ''));
foreach (self::$map as $pattern => $spec) { foreach (self::$map as $pattern => $spec) {
$re = '/^'.$pattern.'$/D'; $re = '/^'.$pattern.'$/D';
if (preg_match($re, $charset)) { if (preg_match($re, $charset)) {
if (!array_key_exists($pattern, self::$loaded)) { if (!\array_key_exists($pattern, self::$loaded)) {
$reflector = new ReflectionClass($spec['class']); $reflector = new ReflectionClass($spec['class']);
if ($reflector->getConstructor()) { if ($reflector->getConstructor()) {
$reader = $reflector->newInstanceArgs($spec['constructor']); $reader = $reflector->newInstanceArgs($spec['constructor']);

View File

@@ -28,8 +28,6 @@ interface Swift_CharacterStream
/** /**
* Set the CharacterReaderFactory for multi charset support. * Set the CharacterReaderFactory for multi charset support.
*
* @param Swift_CharacterReaderFactory $factory
*/ */
public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory); public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory);

View File

@@ -31,10 +31,10 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
private $charset; private $charset;
/** Array of characters */ /** Array of characters */
private $array = array(); private $array = [];
/** Size of the array of character */ /** Size of the array of character */
private $array_size = array(); private $array_size = [];
/** The current character offset in the stream */ /** The current character offset in the stream */
private $offset = 0; private $offset = 0;
@@ -65,8 +65,6 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
/** /**
* Set the CharacterReaderFactory for multi charset support. * Set the CharacterReaderFactory for multi charset support.
*
* @param Swift_CharacterReaderFactory $factory
*/ */
public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory)
{ {
@@ -87,16 +85,16 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
$startLength = $this->charReader->getInitialByteSize(); $startLength = $this->charReader->getInitialByteSize();
while (false !== $bytes = $os->read($startLength)) { while (false !== $bytes = $os->read($startLength)) {
$c = array(); $c = [];
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { for ($i = 0, $len = \strlen($bytes); $i < $len; ++$i) {
$c[] = self::$byteMap[$bytes[$i]]; $c[] = self::$byteMap[$bytes[$i]];
} }
$size = count($c); $size = \count($c);
$need = $this->charReader $need = $this->charReader
->validateByteSequence($c, $size); ->validateByteSequence($c, $size);
if ($need > 0 && if ($need > 0 &&
false !== $bytes = $os->read($need)) { false !== $bytes = $os->read($need)) {
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { for ($i = 0, $len = \strlen($bytes); $i < $len; ++$i) {
$c[] = self::$byteMap[$bytes[$i]]; $c[] = self::$byteMap[$bytes[$i]];
} }
} }
@@ -132,7 +130,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
} }
// Don't use array slice // Don't use array slice
$arrays = array(); $arrays = [];
$end = $length + $this->offset; $end = $length + $this->offset;
for ($i = $this->offset; $i < $end; ++$i) { for ($i = $this->offset; $i < $end; ++$i) {
if (!isset($this->array[$i])) { if (!isset($this->array[$i])) {
@@ -162,7 +160,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
if ($this->offset == $this->array_size) { if ($this->offset == $this->array_size) {
return false; return false;
} }
$arrays = array(); $arrays = [];
$end = $length + $this->offset; $end = $length + $this->offset;
for ($i = $this->offset; $i < $end; ++$i) { for ($i = $this->offset; $i < $end; ++$i) {
if (!isset($this->array[$i])) { if (!isset($this->array[$i])) {
@@ -172,7 +170,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
} }
$this->offset += ($i - $this->offset); // Limit function calls $this->offset += ($i - $this->offset); // Limit function calls
return call_user_func_array('array_merge', $arrays); return array_merge(...$arrays);
} }
/** /**
@@ -194,19 +192,19 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
unset($chars); unset($chars);
fseek($fp, 0, SEEK_SET); fseek($fp, 0, SEEK_SET);
$buffer = array(0); $buffer = [0];
$buf_pos = 1; $buf_pos = 1;
$buf_len = 1; $buf_len = 1;
$has_datas = true; $has_datas = true;
do { do {
$bytes = array(); $bytes = [];
// Buffer Filing // Buffer Filing
if ($buf_len - $buf_pos < $startLength) { if ($buf_len - $buf_pos < $startLength) {
$buf = array_splice($buffer, $buf_pos); $buf = array_splice($buffer, $buf_pos);
$new = $this->reloadBuffer($fp, 100); $new = $this->reloadBuffer($fp, 100);
if ($new) { if ($new) {
$buffer = array_merge($buf, $new); $buffer = array_merge($buf, $new);
$buf_len = count($buffer); $buf_len = \count($buffer);
$buf_pos = 0; $buf_pos = 0;
} else { } else {
$has_datas = false; $has_datas = false;
@@ -226,7 +224,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
if ($new) { if ($new) {
$buffer = array_merge($buffer, $new); $buffer = array_merge($buffer, $new);
$buf_len = count($buffer); $buf_len = \count($buffer);
} }
} }
for ($i = 0; $i < $need && isset($buffer[$buf_pos]); ++$i) { for ($i = 0; $i < $need && isset($buffer[$buf_pos]); ++$i) {
@@ -262,15 +260,15 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
public function flushContents() public function flushContents()
{ {
$this->offset = 0; $this->offset = 0;
$this->array = array(); $this->array = [];
$this->array_size = 0; $this->array_size = 0;
} }
private function reloadBuffer($fp, $len) private function reloadBuffer($fp, $len)
{ {
if (!feof($fp) && ($bytes = fread($fp, $len)) !== false) { if (!feof($fp) && false !== ($bytes = fread($fp, $len))) {
$buf = array(); $buf = [];
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { for ($i = 0, $len = \strlen($bytes); $i < $len; ++$i) {
$buf[] = self::$byteMap[$bytes[$i]]; $buf[] = self::$byteMap[$bytes[$i]];
} }
@@ -283,9 +281,9 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
private static function initializeMaps() private static function initializeMaps()
{ {
if (!isset(self::$charMap)) { if (!isset(self::$charMap)) {
self::$charMap = array(); self::$charMap = [];
for ($byte = 0; $byte < 256; ++$byte) { for ($byte = 0; $byte < 256; ++$byte) {
self::$charMap[$byte] = chr($byte); self::$charMap[$byte] = \chr($byte);
} }
self::$byteMap = array_flip(self::$charMap); self::$byteMap = array_flip(self::$charMap);
} }

View File

@@ -81,8 +81,7 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
/** /**
* Constructor. * Constructor.
* *
* @param Swift_CharacterReaderFactory $factory * @param string $charset
* @param string $charset
*/ */
public function __construct(Swift_CharacterReaderFactory $factory, $charset) public function __construct(Swift_CharacterReaderFactory $factory, $charset)
{ {
@@ -106,8 +105,6 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
/** /**
* Set the CharacterReaderFactory for multi charset support. * Set the CharacterReaderFactory for multi charset support.
*
* @param Swift_CharacterReaderFactory $factory
*/ */
public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory)
{ {
@@ -128,8 +125,6 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
/** /**
* @see Swift_CharacterStream::importByteStream() * @see Swift_CharacterStream::importByteStream()
*
* @param Swift_OutputByteStream $os
*/ */
public function importByteStream(Swift_OutputByteStream $os) public function importByteStream(Swift_OutputByteStream $os)
{ {
@@ -220,7 +215,7 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
public function readBytes($length) public function readBytes($length)
{ {
$read = $this->read($length); $read = $this->read($length);
if ($read !== false) { if (false !== $read) {
$ret = array_map('ord', str_split($read, 1)); $ret = array_map('ord', str_split($read, 1));
return $ret; return $ret;
@@ -252,16 +247,16 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
if (!isset($this->charReader)) { if (!isset($this->charReader)) {
$this->charReader = $this->charReaderFactory->getReaderFor( $this->charReader = $this->charReaderFactory->getReaderFor(
$this->charset); $this->charset);
$this->map = array(); $this->map = [];
$this->mapType = $this->charReader->getMapType(); $this->mapType = $this->charReader->getMapType();
} }
$ignored = ''; $ignored = '';
$this->datas .= $chars; $this->datas .= $chars;
$this->charCount += $this->charReader->getCharPositions(substr($this->datas, $this->datasSize), $this->datasSize, $this->map, $ignored); $this->charCount += $this->charReader->getCharPositions(substr($this->datas, $this->datasSize), $this->datasSize, $this->map, $ignored);
if ($ignored !== false) { if (false !== $ignored) {
$this->datasSize = strlen($this->datas) - strlen($ignored); $this->datasSize = \strlen($this->datas) - \strlen($ignored);
} else { } else {
$this->datasSize = strlen($this->datas); $this->datasSize = \strlen($this->datas);
} }
} }
} }

View File

@@ -16,22 +16,25 @@
class Swift_DependencyContainer class Swift_DependencyContainer
{ {
/** Constant for literal value types */ /** Constant for literal value types */
const TYPE_VALUE = 0x0001; const TYPE_VALUE = 0x00001;
/** Constant for new instance types */ /** Constant for new instance types */
const TYPE_INSTANCE = 0x0010; const TYPE_INSTANCE = 0x00010;
/** Constant for shared instance types */ /** Constant for shared instance types */
const TYPE_SHARED = 0x0100; const TYPE_SHARED = 0x00100;
/** Constant for aliases */ /** Constant for aliases */
const TYPE_ALIAS = 0x1000; const TYPE_ALIAS = 0x01000;
/** Constant for arrays */
const TYPE_ARRAY = 0x10000;
/** Singleton instance */ /** Singleton instance */
private static $instance = null; private static $instance = null;
/** The data container */ /** The data container */
private $store = array(); private $store = [];
/** The current endpoint in the data container */ /** The current endpoint in the data container */
private $endPoint; private $endPoint;
@@ -80,7 +83,7 @@ class Swift_DependencyContainer
*/ */
public function has($itemName) public function has($itemName)
{ {
return array_key_exists($itemName, $this->store) return \array_key_exists($itemName, $this->store)
&& isset($this->store[$itemName]['lookupType']); && isset($this->store[$itemName]['lookupType']);
} }
@@ -98,9 +101,7 @@ class Swift_DependencyContainer
public function lookup($itemName) public function lookup($itemName)
{ {
if (!$this->has($itemName)) { if (!$this->has($itemName)) {
throw new Swift_DependencyException( throw new Swift_DependencyException('Cannot lookup dependency "'.$itemName.'" since it is not registered.');
'Cannot lookup dependency "'.$itemName.'" since it is not registered.'
);
} }
switch ($this->store[$itemName]['lookupType']) { switch ($this->store[$itemName]['lookupType']) {
@@ -112,6 +113,8 @@ class Swift_DependencyContainer
return $this->createNewInstance($itemName); return $this->createNewInstance($itemName);
case self::TYPE_SHARED: case self::TYPE_SHARED:
return $this->createSharedInstance($itemName); return $this->createSharedInstance($itemName);
case self::TYPE_ARRAY:
return $this->createDependenciesFor($itemName);
} }
} }
@@ -124,7 +127,7 @@ class Swift_DependencyContainer
*/ */
public function createDependenciesFor($itemName) public function createDependenciesFor($itemName)
{ {
$args = array(); $args = [];
if (isset($this->store[$itemName]['args'])) { if (isset($this->store[$itemName]['args'])) {
$args = $this->resolveArgs($this->store[$itemName]['args']); $args = $this->resolveArgs($this->store[$itemName]['args']);
} }
@@ -147,7 +150,7 @@ class Swift_DependencyContainer
*/ */
public function register($itemName) public function register($itemName)
{ {
$this->store[$itemName] = array(); $this->store[$itemName] = [];
$this->endPoint = &$this->store[$itemName]; $this->endPoint = &$this->store[$itemName];
return $this; return $this;
@@ -227,6 +230,21 @@ class Swift_DependencyContainer
return $this; return $this;
} }
/**
* Specify the previously registered item as array of dependencies.
*
* {@link register()} must be called before this will work.
*
* @return $this
*/
public function asArray()
{
$endPoint = &$this->getEndPoint();
$endPoint['lookupType'] = self::TYPE_ARRAY;
return $this;
}
/** /**
* Specify a list of injected dependencies for the previously registered item. * Specify a list of injected dependencies for the previously registered item.
* *
@@ -234,14 +252,12 @@ class Swift_DependencyContainer
* *
* @see addConstructorValue(), addConstructorLookup() * @see addConstructorValue(), addConstructorLookup()
* *
* @param array $lookups
*
* @return $this * @return $this
*/ */
public function withDependencies(array $lookups) public function withDependencies(array $lookups)
{ {
$endPoint = &$this->getEndPoint(); $endPoint = &$this->getEndPoint();
$endPoint['args'] = array(); $endPoint['args'] = [];
foreach ($lookups as $lookup) { foreach ($lookups as $lookup) {
$this->addConstructorLookup($lookup); $this->addConstructorLookup($lookup);
} }
@@ -263,9 +279,9 @@ class Swift_DependencyContainer
{ {
$endPoint = &$this->getEndPoint(); $endPoint = &$this->getEndPoint();
if (!isset($endPoint['args'])) { if (!isset($endPoint['args'])) {
$endPoint['args'] = array(); $endPoint['args'] = [];
} }
$endPoint['args'][] = array('type' => 'value', 'item' => $value); $endPoint['args'][] = ['type' => 'value', 'item' => $value];
return $this; return $this;
} }
@@ -284,9 +300,9 @@ class Swift_DependencyContainer
{ {
$endPoint = &$this->getEndPoint(); $endPoint = &$this->getEndPoint();
if (!isset($this->endPoint['args'])) { if (!isset($this->endPoint['args'])) {
$endPoint['args'] = array(); $endPoint['args'] = [];
} }
$endPoint['args'][] = array('type' => 'lookup', 'item' => $lookup); $endPoint['args'][] = ['type' => 'lookup', 'item' => $lookup];
return $this; return $this;
} }
@@ -330,9 +346,7 @@ class Swift_DependencyContainer
private function &getEndPoint() private function &getEndPoint()
{ {
if (!isset($this->endPoint)) { if (!isset($this->endPoint)) {
throw new BadMethodCallException( throw new BadMethodCallException('Component must first be registered by calling register()');
'Component must first be registered by calling register()'
);
} }
return $this->endPoint; return $this->endPoint;
@@ -341,7 +355,7 @@ class Swift_DependencyContainer
/** Get an argument list with dependencies resolved */ /** Get an argument list with dependencies resolved */
private function resolveArgs(array $args) private function resolveArgs(array $args)
{ {
$resolved = array(); $resolved = [];
foreach ($args as $argDefinition) { foreach ($args as $argDefinition) {
switch ($argDefinition['type']) { switch ($argDefinition['type']) {
case 'lookup': case 'lookup':
@@ -359,8 +373,8 @@ class Swift_DependencyContainer
/** Resolve a single dependency with an collections */ /** Resolve a single dependency with an collections */
private function lookupRecursive($item) private function lookupRecursive($item)
{ {
if (is_array($item)) { if (\is_array($item)) {
$collection = array(); $collection = [];
foreach ($item as $k => $v) { foreach ($item as $k => $v) {
$collection[$k] = $this->lookupRecursive($v); $collection[$k] = $this->lookupRecursive($v);
} }

View File

@@ -26,8 +26,8 @@ class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile
*/ */
public function __construct($data = null, $filename = null, $contentType = null) public function __construct($data = null, $filename = null, $contentType = null)
{ {
call_user_func_array( \call_user_func_array(
array($this, 'Swift_Mime_EmbeddedFile::__construct'), [$this, 'Swift_Mime_EmbeddedFile::__construct'],
Swift_DependencyContainer::getInstance() Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.embeddedfile') ->createDependenciesFor('mime.embeddedfile')
); );

View File

@@ -34,7 +34,7 @@ class Swift_Encoder_Base64Encoder implements Swift_Encoder
$maxLineLength = 76; $maxLineLength = 76;
} }
$encodedString = base64_encode($string); $encodedString = base64_encode($string ?? '');
$firstLine = ''; $firstLine = '';
if (0 != $firstLineOffset) { if (0 != $firstLineOffset) {

View File

@@ -36,7 +36,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
* *
* @var string[] * @var string[]
*/ */
protected static $qpMap = array( protected static $qpMap = [
0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', 0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04',
5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09',
10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E',
@@ -89,16 +89,16 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
245 => '=F5', 246 => '=F6', 247 => '=F7', 248 => '=F8', 249 => '=F9', 245 => '=F5', 246 => '=F6', 247 => '=F7', 248 => '=F8', 249 => '=F9',
250 => '=FA', 251 => '=FB', 252 => '=FC', 253 => '=FD', 254 => '=FE', 250 => '=FA', 251 => '=FB', 252 => '=FC', 253 => '=FD', 254 => '=FE',
255 => '=FF', 255 => '=FF',
); ];
protected static $safeMapShare = array(); protected static $safeMapShare = [];
/** /**
* A map of non-encoded ascii characters. * A map of non-encoded ascii characters.
* *
* @var string[] * @var string[]
*/ */
protected $safeMap = array(); protected $safeMap = [];
/** /**
* Creates a new QpEncoder for the given CharacterStream. * Creates a new QpEncoder for the given CharacterStream.
@@ -120,7 +120,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
public function __sleep() public function __sleep()
{ {
return array('charStream', 'filter'); return ['charStream', 'filter'];
} }
public function __wakeup() public function __wakeup()
@@ -135,14 +135,14 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
protected function getSafeMapShareId() protected function getSafeMapShareId()
{ {
return get_class($this); return static::class;
} }
protected function initSafeMap() protected function initSafeMap()
{ {
foreach (array_merge( foreach (array_merge(
array(0x09, 0x20), range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) { [0x09, 0x20], range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) {
$this->safeMap[$byte] = chr($byte); $this->safeMap[$byte] = \chr($byte);
} }
} }
@@ -153,9 +153,9 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
* If the first line needs to be shorter, indicate the difference with * If the first line needs to be shorter, indicate the difference with
* $firstLineOffset. * $firstLineOffset.
* *
* @param string $string to encode * @param string $string to encode
* @param int $firstLineOffset, optional * @param int $firstLineOffset optional
* @param int $maxLineLength, optional 0 indicates the default of 76 chars * @param int $maxLineLength optional 0 indicates the default of 76 chars
* *
* @return string * @return string
*/ */
@@ -167,7 +167,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
$thisLineLength = $maxLineLength - $firstLineOffset; $thisLineLength = $maxLineLength - $firstLineOffset;
$lines = array(); $lines = [];
$lNo = 0; $lNo = 0;
$lines[$lNo] = ''; $lines[$lNo] = '';
$currentLine = &$lines[$lNo++]; $currentLine = &$lines[$lNo++];
@@ -200,7 +200,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
$enc = $this->encodeByteSequence($bytes, $size); $enc = $this->encodeByteSequence($bytes, $size);
$i = strpos($enc, '=0D=0A'); $i = strpos($enc, '=0D=0A');
$newLineLength = $lineLen + ($i === false ? $size : $i); $newLineLength = $lineLen + (false === $i ? $size : $i);
if ($currentLine && $newLineLength >= $thisLineLength) { if ($currentLine && $newLineLength >= $thisLineLength) {
$lines[$lNo] = ''; $lines[$lNo] = '';
@@ -211,7 +211,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
$currentLine .= $enc; $currentLine .= $enc;
if ($i === false) { if (false === $i) {
$lineLen += $size; $lineLen += $size;
} else { } else {
// 6 is the length of '=0D=0A'. // 6 is the length of '=0D=0A'.
@@ -278,10 +278,10 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
*/ */
protected function standardize($string) protected function standardize($string)
{ {
$string = str_replace(array("\t=0D=0A", ' =0D=0A', '=0D=0A'), $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'],
array("=09\r\n", "=20\r\n", "\r\n"), $string ["=09\r\n", "=20\r\n", "\r\n"], $string
); );
switch ($end = ord(substr($string, -1))) { switch ($end = \ord(substr($string, -1))) {
case 0x09: case 0x09:
case 0x20: case 0x20:
$string = substr_replace($string, self::$qpMap[$end], -1); $string = substr_replace($string, self::$qpMap[$end], -1);

View File

@@ -24,8 +24,6 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
/** /**
* Creates a new Rfc2231Encoder using the given character stream instance. * Creates a new Rfc2231Encoder using the given character stream instance.
*
* @param Swift_CharacterStream
*/ */
public function __construct(Swift_CharacterStream $charStream) public function __construct(Swift_CharacterStream $charStream)
{ {
@@ -44,7 +42,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
*/ */
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{ {
$lines = array(); $lines = [];
$lineCount = 0; $lineCount = 0;
$lines[] = ''; $lines[] = '';
$currentLine = &$lines[$lineCount++]; $currentLine = &$lines[$lineCount++];
@@ -60,8 +58,8 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
while (false !== $char = $this->charStream->read(4)) { while (false !== $char = $this->charStream->read(4)) {
$encodedChar = rawurlencode($char); $encodedChar = rawurlencode($char);
if (0 != strlen($currentLine) if (0 != \strlen($currentLine)
&& strlen($currentLine.$encodedChar) > $thisLineLength) { && \strlen($currentLine.$encodedChar) > $thisLineLength) {
$lines[] = ''; $lines[] = '';
$currentLine = &$lines[$lineCount++]; $currentLine = &$lines[$lineCount++];
$thisLineLength = $maxLineLength; $thisLineLength = $maxLineLength;

View File

@@ -27,16 +27,15 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject
* *
* @var int[] * @var int[]
*/ */
private $successCodes = array(); private $successCodes = [];
/** /**
* Create a new CommandEvent for $source with $command. * Create a new CommandEvent for $source with $command.
* *
* @param Swift_Transport $source * @param string $command
* @param string $command * @param array $successCodes
* @param array $successCodes
*/ */
public function __construct(Swift_Transport $source, $command, $successCodes = array()) public function __construct(Swift_Transport $source, $command, $successCodes = [])
{ {
parent::__construct($source); parent::__construct($source);
$this->command = $command; $this->command = $command;

View File

@@ -17,8 +17,6 @@ interface Swift_Events_CommandListener extends Swift_Events_EventListener
{ {
/** /**
* Invoked immediately following a command being sent. * Invoked immediately following a command being sent.
*
* @param Swift_Events_CommandEvent $evt
*/ */
public function commandSent(Swift_Events_CommandEvent $evt); public function commandSent(Swift_Events_CommandEvent $evt);
} }

View File

@@ -18,9 +18,6 @@ interface Swift_Events_EventDispatcher
/** /**
* Create a new SendEvent for $source and $message. * Create a new SendEvent for $source and $message.
* *
* @param Swift_Transport $source
* @param Swift_Mime_SimpleMessage
*
* @return Swift_Events_SendEvent * @return Swift_Events_SendEvent
*/ */
public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message); public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message);
@@ -28,20 +25,18 @@ interface Swift_Events_EventDispatcher
/** /**
* Create a new CommandEvent for $source and $command. * Create a new CommandEvent for $source and $command.
* *
* @param Swift_Transport $source * @param string $command That will be executed
* @param string $command That will be executed * @param array $successCodes That are needed
* @param array $successCodes That are needed
* *
* @return Swift_Events_CommandEvent * @return Swift_Events_CommandEvent
*/ */
public function createCommandEvent(Swift_Transport $source, $command, $successCodes = array()); public function createCommandEvent(Swift_Transport $source, $command, $successCodes = []);
/** /**
* Create a new ResponseEvent for $source and $response. * Create a new ResponseEvent for $source and $response.
* *
* @param Swift_Transport $source * @param string $response
* @param string $response * @param bool $valid If the response is valid
* @param bool $valid If the response is valid
* *
* @return Swift_Events_ResponseEvent * @return Swift_Events_ResponseEvent
*/ */
@@ -50,8 +45,6 @@ interface Swift_Events_EventDispatcher
/** /**
* Create a new TransportChangeEvent for $source. * Create a new TransportChangeEvent for $source.
* *
* @param Swift_Transport $source
*
* @return Swift_Events_TransportChangeEvent * @return Swift_Events_TransportChangeEvent
*/ */
public function createTransportChangeEvent(Swift_Transport $source); public function createTransportChangeEvent(Swift_Transport $source);
@@ -59,25 +52,19 @@ interface Swift_Events_EventDispatcher
/** /**
* Create a new TransportExceptionEvent for $source. * Create a new TransportExceptionEvent for $source.
* *
* @param Swift_Transport $source
* @param Swift_TransportException $ex
*
* @return Swift_Events_TransportExceptionEvent * @return Swift_Events_TransportExceptionEvent
*/ */
public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex); public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex);
/** /**
* Bind an event listener to this dispatcher. * Bind an event listener to this dispatcher.
*
* @param Swift_Events_EventListener $listener
*/ */
public function bindEventListener(Swift_Events_EventListener $listener); public function bindEventListener(Swift_Events_EventListener $listener);
/** /**
* Dispatch the given Event to all suitable listeners. * Dispatch the given Event to all suitable listeners.
* *
* @param Swift_Events_EventObject $evt * @param string $target method
* @param string $target method
*/ */
public function dispatchEvent(Swift_Events_EventObject $evt, $target); public function dispatchEvent(Swift_Events_EventObject $evt, $target);
} }

View File

@@ -43,8 +43,6 @@ class Swift_Events_EventObject implements Swift_Events_Event
/** /**
* Prevent this Event from bubbling any further up the stack. * Prevent this Event from bubbling any further up the stack.
*
* @param bool $cancel, optional
*/ */
public function cancelBubble($cancel = true) public function cancelBubble($cancel = true)
{ {

View File

@@ -32,9 +32,8 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject
/** /**
* Create a new ResponseEvent for $source and $response. * Create a new ResponseEvent for $source and $response.
* *
* @param Swift_Transport $source * @param string $response
* @param string $response * @param bool $valid
* @param bool $valid
*/ */
public function __construct(Swift_Transport $source, $response, $valid = false) public function __construct(Swift_Transport $source, $response, $valid = false)
{ {

View File

@@ -17,8 +17,6 @@ interface Swift_Events_ResponseListener extends Swift_Events_EventListener
{ {
/** /**
* Invoked immediately following a response coming back. * Invoked immediately following a response coming back.
*
* @param Swift_Events_ResponseEvent $evt
*/ */
public function responseReceived(Swift_Events_ResponseEvent $evt); public function responseReceived(Swift_Events_ResponseEvent $evt);
} }

View File

@@ -42,7 +42,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject
* *
* @var string[] * @var string[]
*/ */
private $failedRecipients = array(); private $failedRecipients = [];
/** /**
* The overall result as a bitmask from the class constants. * The overall result as a bitmask from the class constants.
@@ -53,9 +53,6 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject
/** /**
* Create a new SendEvent for $source and $message. * Create a new SendEvent for $source and $message.
*
* @param Swift_Transport $source
* @param Swift_Mime_SimpleMessage $message
*/ */
public function __construct(Swift_Transport $source, Swift_Mime_SimpleMessage $message) public function __construct(Swift_Transport $source, Swift_Mime_SimpleMessage $message)
{ {

View File

@@ -17,15 +17,11 @@ interface Swift_Events_SendListener extends Swift_Events_EventListener
{ {
/** /**
* Invoked immediately before the Message is sent. * Invoked immediately before the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/ */
public function beforeSendPerformed(Swift_Events_SendEvent $evt); public function beforeSendPerformed(Swift_Events_SendEvent $evt);
/** /**
* Invoked immediately after the Message is sent. * Invoked immediately after the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/ */
public function sendPerformed(Swift_Events_SendEvent $evt); public function sendPerformed(Swift_Events_SendEvent $evt);
} }

View File

@@ -16,34 +16,28 @@
class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
{ {
/** A map of event types to their associated listener types */ /** A map of event types to their associated listener types */
private $eventMap = array(); private $eventMap = [];
/** Event listeners bound to this dispatcher */ /** Event listeners bound to this dispatcher */
private $listeners = array(); private $listeners = [];
/** Listeners queued to have an Event bubbled up the stack to them */
private $bubbleQueue = array();
/** /**
* Create a new EventDispatcher. * Create a new EventDispatcher.
*/ */
public function __construct() public function __construct()
{ {
$this->eventMap = array( $this->eventMap = [
'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener', 'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener',
'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener', 'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener',
'Swift_Events_SendEvent' => 'Swift_Events_SendListener', 'Swift_Events_SendEvent' => 'Swift_Events_SendListener',
'Swift_Events_TransportChangeEvent' => 'Swift_Events_TransportChangeListener', 'Swift_Events_TransportChangeEvent' => 'Swift_Events_TransportChangeListener',
'Swift_Events_TransportExceptionEvent' => 'Swift_Events_TransportExceptionListener', 'Swift_Events_TransportExceptionEvent' => 'Swift_Events_TransportExceptionListener',
); ];
} }
/** /**
* Create a new SendEvent for $source and $message. * Create a new SendEvent for $source and $message.
* *
* @param Swift_Transport $source
* @param Swift_Mime_SimpleMessage
*
* @return Swift_Events_SendEvent * @return Swift_Events_SendEvent
*/ */
public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message) public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message)
@@ -54,13 +48,12 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
/** /**
* Create a new CommandEvent for $source and $command. * Create a new CommandEvent for $source and $command.
* *
* @param Swift_Transport $source * @param string $command That will be executed
* @param string $command That will be executed * @param array $successCodes That are needed
* @param array $successCodes That are needed
* *
* @return Swift_Events_CommandEvent * @return Swift_Events_CommandEvent
*/ */
public function createCommandEvent(Swift_Transport $source, $command, $successCodes = array()) public function createCommandEvent(Swift_Transport $source, $command, $successCodes = [])
{ {
return new Swift_Events_CommandEvent($source, $command, $successCodes); return new Swift_Events_CommandEvent($source, $command, $successCodes);
} }
@@ -68,9 +61,8 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
/** /**
* Create a new ResponseEvent for $source and $response. * Create a new ResponseEvent for $source and $response.
* *
* @param Swift_Transport $source * @param string $response
* @param string $response * @param bool $valid If the response is valid
* @param bool $valid If the response is valid
* *
* @return Swift_Events_ResponseEvent * @return Swift_Events_ResponseEvent
*/ */
@@ -82,8 +74,6 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
/** /**
* Create a new TransportChangeEvent for $source. * Create a new TransportChangeEvent for $source.
* *
* @param Swift_Transport $source
*
* @return Swift_Events_TransportChangeEvent * @return Swift_Events_TransportChangeEvent
*/ */
public function createTransportChangeEvent(Swift_Transport $source) public function createTransportChangeEvent(Swift_Transport $source)
@@ -94,9 +84,6 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
/** /**
* Create a new TransportExceptionEvent for $source. * Create a new TransportExceptionEvent for $source.
* *
* @param Swift_Transport $source
* @param Swift_TransportException $ex
*
* @return Swift_Events_TransportExceptionEvent * @return Swift_Events_TransportExceptionEvent
*/ */
public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex) public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex)
@@ -106,8 +93,6 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
/** /**
* Bind an event listener to this dispatcher. * Bind an event listener to this dispatcher.
*
* @param Swift_Events_EventListener $listener
*/ */
public function bindEventListener(Swift_Events_EventListener $listener) public function bindEventListener(Swift_Events_EventListener $listener)
{ {
@@ -123,34 +108,35 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
/** /**
* Dispatch the given Event to all suitable listeners. * Dispatch the given Event to all suitable listeners.
* *
* @param Swift_Events_EventObject $evt * @param string $target method
* @param string $target method
*/ */
public function dispatchEvent(Swift_Events_EventObject $evt, $target) public function dispatchEvent(Swift_Events_EventObject $evt, $target)
{ {
$this->prepareBubbleQueue($evt); $bubbleQueue = $this->prepareBubbleQueue($evt);
$this->bubble($evt, $target); $this->bubble($bubbleQueue, $evt, $target);
} }
/** Queue listeners on a stack ready for $evt to be bubbled up it */ /** Queue listeners on a stack ready for $evt to be bubbled up it */
private function prepareBubbleQueue(Swift_Events_EventObject $evt) private function prepareBubbleQueue(Swift_Events_EventObject $evt)
{ {
$this->bubbleQueue = array(); $bubbleQueue = [];
$evtClass = get_class($evt); $evtClass = \get_class($evt);
foreach ($this->listeners as $listener) { foreach ($this->listeners as $listener) {
if (array_key_exists($evtClass, $this->eventMap) if (\array_key_exists($evtClass, $this->eventMap)
&& ($listener instanceof $this->eventMap[$evtClass])) { && ($listener instanceof $this->eventMap[$evtClass])) {
$this->bubbleQueue[] = $listener; $bubbleQueue[] = $listener;
} }
} }
return $bubbleQueue;
} }
/** Bubble $evt up the stack calling $target() on each listener */ /** Bubble $evt up the stack calling $target() on each listener */
private function bubble(Swift_Events_EventObject $evt, $target) private function bubble(array &$bubbleQueue, Swift_Events_EventObject $evt, $target)
{ {
if (!$evt->bubbleCancelled() && $listener = array_shift($this->bubbleQueue)) { if (!$evt->bubbleCancelled() && $listener = array_shift($bubbleQueue)) {
$listener->$target($evt); $listener->$target($evt);
$this->bubble($evt, $target); $this->bubble($bubbleQueue, $evt, $target);
} }
} }
} }

View File

@@ -17,29 +17,21 @@ interface Swift_Events_TransportChangeListener extends Swift_Events_EventListene
{ {
/** /**
* Invoked just before a Transport is started. * Invoked just before a Transport is started.
*
* @param Swift_Events_TransportChangeEvent $evt
*/ */
public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt); public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt);
/** /**
* Invoked immediately after the Transport is started. * Invoked immediately after the Transport is started.
*
* @param Swift_Events_TransportChangeEvent $evt
*/ */
public function transportStarted(Swift_Events_TransportChangeEvent $evt); public function transportStarted(Swift_Events_TransportChangeEvent $evt);
/** /**
* Invoked just before a Transport is stopped. * Invoked just before a Transport is stopped.
*
* @param Swift_Events_TransportChangeEvent $evt
*/ */
public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt); public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt);
/** /**
* Invoked immediately after the Transport is stopped. * Invoked immediately after the Transport is stopped.
*
* @param Swift_Events_TransportChangeEvent $evt
*/ */
public function transportStopped(Swift_Events_TransportChangeEvent $evt); public function transportStopped(Swift_Events_TransportChangeEvent $evt);
} }

View File

@@ -24,9 +24,6 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject
/** /**
* Create a new TransportExceptionEvent for $transport. * Create a new TransportExceptionEvent for $transport.
*
* @param Swift_Transport $transport
* @param Swift_TransportException $ex
*/ */
public function __construct(Swift_Transport $transport, Swift_TransportException $ex) public function __construct(Swift_Transport $transport, Swift_TransportException $ex)
{ {

View File

@@ -17,8 +17,6 @@ interface Swift_Events_TransportExceptionListener extends Swift_Events_EventList
{ {
/** /**
* Invoked as a TransportException is thrown in the Transport system. * Invoked as a TransportException is thrown in the Transport system.
*
* @param Swift_Events_TransportExceptionEvent $evt
*/ */
public function exceptionThrown(Swift_Events_TransportExceptionEvent $evt); public function exceptionThrown(Swift_Events_TransportExceptionEvent $evt);
} }

View File

@@ -20,10 +20,10 @@ class Swift_FailoverTransport extends Swift_Transport_FailoverTransport
* *
* @param Swift_Transport[] $transports * @param Swift_Transport[] $transports
*/ */
public function __construct($transports = array()) public function __construct($transports = [])
{ {
call_user_func_array( \call_user_func_array(
array($this, 'Swift_Transport_FailoverTransport::__construct'), [$this, 'Swift_Transport_FailoverTransport::__construct'],
Swift_DependencyContainer::getInstance() Swift_DependencyContainer::getInstance()
->createDependenciesFor('transport.failover') ->createDependenciesFor('transport.failover')
); );

View File

@@ -121,7 +121,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
foreach (new DirectoryIterator($this->path) as $file) { foreach (new DirectoryIterator($this->path) as $file) {
$file = $file->getRealPath(); $file = $file->getRealPath();
if (substr($file, -16) == '.message.sending') { if ('.message.sending' == substr($file, -16)) {
$lockedtime = filectime($file); $lockedtime = filectime($file);
if ((time() - $lockedtime) > $timeout) { if ((time() - $lockedtime) > $timeout) {
rename($file, substr($file, 0, -8)); rename($file, substr($file, 0, -8));
@@ -145,7 +145,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
/* Start the transport only if there are queued files to send */ /* Start the transport only if there are queued files to send */
if (!$transport->isStarted()) { if (!$transport->isStarted()) {
foreach ($directoryIterator as $file) { foreach ($directoryIterator as $file) {
if (substr($file->getRealPath(), -8) == '.message') { if ('.message' == substr($file->getRealPath(), -8)) {
$transport->start(); $transport->start();
break; break;
} }
@@ -158,7 +158,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
foreach ($directoryIterator as $file) { foreach ($directoryIterator as $file) {
$file = $file->getRealPath(); $file = $file->getRealPath();
if (substr($file, -8) != '.message') { if ('.message' != substr($file, -8)) {
continue; continue;
} }
@@ -198,7 +198,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
// This string MUST stay FS safe, avoid special chars // This string MUST stay FS safe, avoid special chars
$base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-'; $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
$ret = ''; $ret = '';
$strlen = strlen($base); $strlen = \strlen($base);
for ($i = 0; $i < $count; ++$i) { for ($i = 0; $i < $count; ++$i) {
$ret .= $base[random_int(0, $strlen - 1)]; $ret .= $base[random_int(0, $strlen - 1)];
} }

View File

@@ -18,8 +18,7 @@ interface Swift_Filterable
/** /**
* Add a new StreamFilter, referenced by $key. * Add a new StreamFilter, referenced by $key.
* *
* @param Swift_StreamFilter $filter * @param string $key
* @param string $key
*/ */
public function addFilter(Swift_StreamFilter $filter, $key); public function addFilter(Swift_StreamFilter $filter, $key);

View File

@@ -52,7 +52,7 @@ interface Swift_InputByteStream
* *
* @param Swift_InputByteStream $is * @param Swift_InputByteStream $is
*/ */
public function bind(Swift_InputByteStream $is); public function bind(self $is);
/** /**
* Remove an already bound stream. * Remove an already bound stream.
@@ -63,7 +63,7 @@ interface Swift_InputByteStream
* *
* @param Swift_InputByteStream $is * @param Swift_InputByteStream $is
*/ */
public function unbind(Swift_InputByteStream $is); public function unbind(self $is);
/** /**
* Flush the contents of the stream (empty it) and set the internal pointer * Flush the contents of the stream (empty it) and set the internal pointer

View File

@@ -18,9 +18,8 @@ class Swift_IoException extends Swift_SwiftException
/** /**
* Create a new IoException with $message. * Create a new IoException with $message.
* *
* @param string $message * @param string $message
* @param int $code * @param int $code
* @param Exception $previous
*/ */
public function __construct($message, $code = 0, Exception $previous = null) public function __construct($message, $code = 0, Exception $previous = null)
{ {

View File

@@ -38,10 +38,9 @@ interface Swift_KeyCache
* *
* @see MODE_WRITE, MODE_APPEND * @see MODE_WRITE, MODE_APPEND
* *
* @param string $nsKey * @param string $nsKey
* @param string $itemKey * @param string $itemKey
* @param Swift_OutputByteStream $os * @param int $mode
* @param int $mode
*/ */
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode); public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode);

View File

@@ -20,7 +20,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
* *
* @var array * @var array
*/ */
private $contents = array(); private $contents = [];
/** /**
* An InputStream for cloning. * An InputStream for cloning.
@@ -32,8 +32,6 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
/** /**
* Create a new ArrayKeyCache with the given $stream for cloning to make * Create a new ArrayKeyCache with the given $stream for cloning to make
* InputByteStreams. * InputByteStreams.
*
* @param Swift_KeyCache_KeyCacheInputStream $stream
*/ */
public function __construct(Swift_KeyCache_KeyCacheInputStream $stream) public function __construct(Swift_KeyCache_KeyCacheInputStream $stream)
{ {
@@ -64,10 +62,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
$this->contents[$nsKey][$itemKey] .= $string; $this->contents[$nsKey][$itemKey] .= $string;
break; break;
default: default:
throw new Swift_SwiftException( throw new Swift_SwiftException('Invalid mode ['.$mode.'] used to set nsKey='.$nsKey.', itemKey='.$itemKey);
'Invalid mode ['.$mode.'] used to set nsKey='.
$nsKey.', itemKey='.$itemKey
);
} }
} }
@@ -76,10 +71,9 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
* *
* @see MODE_WRITE, MODE_APPEND * @see MODE_WRITE, MODE_APPEND
* *
* @param string $nsKey * @param string $nsKey
* @param string $itemKey * @param string $itemKey
* @param Swift_OutputByteStream $os * @param int $mode
* @param int $mode
*/ */
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode)
{ {
@@ -87,6 +81,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
switch ($mode) { switch ($mode) {
case self::MODE_WRITE: case self::MODE_WRITE:
$this->clearKey($nsKey, $itemKey); $this->clearKey($nsKey, $itemKey);
// no break
case self::MODE_APPEND: case self::MODE_APPEND:
if (!$this->hasKey($nsKey, $itemKey)) { if (!$this->hasKey($nsKey, $itemKey)) {
$this->contents[$nsKey][$itemKey] = ''; $this->contents[$nsKey][$itemKey] = '';
@@ -96,10 +91,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
} }
break; break;
default: default:
throw new Swift_SwiftException( throw new Swift_SwiftException('Invalid mode ['.$mode.'] used to set nsKey='.$nsKey.', itemKey='.$itemKey);
'Invalid mode ['.$mode.'] used to set nsKey='.
$nsKey.', itemKey='.$itemKey
);
} }
} }
@@ -108,9 +100,8 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
* *
* NOTE: The stream will always write in append mode. * NOTE: The stream will always write in append mode.
* *
* @param string $nsKey * @param string $nsKey
* @param string $itemKey * @param string $itemKey
* @param Swift_InputByteStream $writeThrough
* *
* @return Swift_InputByteStream * @return Swift_InputByteStream
*/ */
@@ -168,7 +159,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
{ {
$this->prepareCache($nsKey); $this->prepareCache($nsKey);
return array_key_exists($itemKey, $this->contents[$nsKey]); return \array_key_exists($itemKey, $this->contents[$nsKey]);
} }
/** /**
@@ -199,8 +190,8 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/ */
private function prepareCache($nsKey) private function prepareCache($nsKey)
{ {
if (!array_key_exists($nsKey, $this->contents)) { if (!\array_key_exists($nsKey, $this->contents)) {
$this->contents[$nsKey] = array(); $this->contents[$nsKey] = [];
} }
} }
} }

View File

@@ -43,14 +43,13 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
* *
* @var array * @var array
*/ */
private $keys = array(); private $keys = [];
/** /**
* Create a new DiskKeyCache with the given $stream for cloning to make * Create a new DiskKeyCache with the given $stream for cloning to make
* InputByteStreams, and the given $path to save to. * InputByteStreams, and the given $path to save to.
* *
* @param Swift_KeyCache_KeyCacheInputStream $stream * @param string $path to save to
* @param string $path to save to
*/ */
public function __construct(Swift_KeyCache_KeyCacheInputStream $stream, $path) public function __construct(Swift_KeyCache_KeyCacheInputStream $stream, $path)
{ {
@@ -81,10 +80,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END); $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END);
break; break;
default: default:
throw new Swift_SwiftException( throw new Swift_SwiftException('Invalid mode ['.$mode.'] used to set nsKey='.$nsKey.', itemKey='.$itemKey);
'Invalid mode ['.$mode.'] used to set nsKey='.
$nsKey.', itemKey='.$itemKey
);
break; break;
} }
fwrite($fp, $string); fwrite($fp, $string);
@@ -96,10 +92,9 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
* *
* @see MODE_WRITE, MODE_APPEND * @see MODE_WRITE, MODE_APPEND
* *
* @param string $nsKey * @param string $nsKey
* @param string $itemKey * @param string $itemKey
* @param Swift_OutputByteStream $os * @param int $mode
* @param int $mode
* *
* @throws Swift_IoException * @throws Swift_IoException
*/ */
@@ -114,10 +109,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END); $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END);
break; break;
default: default:
throw new Swift_SwiftException( throw new Swift_SwiftException('Invalid mode ['.$mode.'] used to set nsKey='.$nsKey.', itemKey='.$itemKey);
'Invalid mode ['.$mode.'] used to set nsKey='.
$nsKey.', itemKey='.$itemKey
);
break; break;
} }
while (false !== $bytes = $os->read(8192)) { while (false !== $bytes = $os->read(8192)) {
@@ -131,9 +123,8 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
* *
* NOTE: The stream will always write in append mode. * NOTE: The stream will always write in append mode.
* *
* @param string $nsKey * @param string $nsKey
* @param string $itemKey * @param string $itemKey
* @param Swift_InputByteStream $writeThrough
* *
* @return Swift_InputByteStream * @return Swift_InputByteStream
*/ */
@@ -227,7 +218,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/ */
public function clearAll($nsKey) public function clearAll($nsKey)
{ {
if (array_key_exists($nsKey, $this->keys)) { if (\array_key_exists($nsKey, $this->keys)) {
foreach ($this->keys[$nsKey] as $itemKey => $null) { foreach ($this->keys[$nsKey] as $itemKey => $null) {
$this->clearKey($nsKey, $itemKey); $this->clearKey($nsKey, $itemKey);
} }
@@ -250,7 +241,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
if (!mkdir($cacheDir)) { if (!mkdir($cacheDir)) {
throw new Swift_IoException('Failed to create cache directory '.$cacheDir); throw new Swift_IoException('Failed to create cache directory '.$cacheDir);
} }
$this->keys[$nsKey] = array(); $this->keys[$nsKey] = [];
} }
} }
@@ -295,4 +286,9 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
$this->clearAll($nsKey); $this->clearAll($nsKey);
} }
} }
public function __wakeup()
{
$this->keys = [];
}
} }

View File

@@ -17,8 +17,6 @@ interface Swift_KeyCache_KeyCacheInputStream extends Swift_InputByteStream
{ {
/** /**
* Set the KeyCache to wrap. * Set the KeyCache to wrap.
*
* @param Swift_KeyCache $keyCache
*/ */
public function setKeyCache(Swift_KeyCache $keyCache); public function setKeyCache(Swift_KeyCache $keyCache);
@@ -38,8 +36,6 @@ interface Swift_KeyCache_KeyCacheInputStream extends Swift_InputByteStream
/** /**
* Specify a stream to write through for each write(). * Specify a stream to write through for each write().
*
* @param Swift_InputByteStream $is
*/ */
public function setWriteThroughStream(Swift_InputByteStream $is); public function setWriteThroughStream(Swift_InputByteStream $is);

View File

@@ -34,10 +34,9 @@ class Swift_KeyCache_NullKeyCache implements Swift_KeyCache
* *
* @see MODE_WRITE, MODE_APPEND * @see MODE_WRITE, MODE_APPEND
* *
* @param string $nsKey * @param string $nsKey
* @param string $itemKey * @param string $itemKey
* @param Swift_OutputByteStream $os * @param int $mode
* @param int $mode
*/ */
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode)
{ {
@@ -48,9 +47,8 @@ class Swift_KeyCache_NullKeyCache implements Swift_KeyCache
* *
* NOTE: The stream will always write in append mode. * NOTE: The stream will always write in append mode.
* *
* @param string $nsKey * @param string $nsKey
* @param string $itemKey * @param string $itemKey
* @param Swift_InputByteStream $writeThrough
* *
* @return Swift_InputByteStream * @return Swift_InputByteStream
*/ */

View File

@@ -29,8 +29,6 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
/** /**
* Set the KeyCache to wrap. * Set the KeyCache to wrap.
*
* @param Swift_KeyCache $keyCache
*/ */
public function setKeyCache(Swift_KeyCache $keyCache) public function setKeyCache(Swift_KeyCache $keyCache)
{ {
@@ -39,8 +37,6 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
/** /**
* Specify a stream to write through for each write(). * Specify a stream to write through for each write().
*
* @param Swift_InputByteStream $is
*/ */
public function setWriteThroughStream(Swift_InputByteStream $is) public function setWriteThroughStream(Swift_InputByteStream $is)
{ {

View File

@@ -20,10 +20,10 @@ class Swift_LoadBalancedTransport extends Swift_Transport_LoadBalancedTransport
* *
* @param array $transports * @param array $transports
*/ */
public function __construct($transports = array()) public function __construct($transports = [])
{ {
call_user_func_array( \call_user_func_array(
array($this, 'Swift_Transport_LoadBalancedTransport::__construct'), [$this, 'Swift_Transport_LoadBalancedTransport::__construct'],
Swift_DependencyContainer::getInstance() Swift_DependencyContainer::getInstance()
->createDependenciesFor('transport.loadbalanced') ->createDependenciesFor('transport.loadbalanced')
); );

View File

@@ -20,8 +20,6 @@ class Swift_Mailer
/** /**
* Create a new Mailer using $transport for delivery. * Create a new Mailer using $transport for delivery.
*
* @param Swift_Transport $transport
*/ */
public function __construct(Swift_Transport $transport) public function __construct(Swift_Transport $transport)
{ {
@@ -54,8 +52,7 @@ class Swift_Mailer
* The return value is the number of recipients who were accepted for * The return value is the number of recipients who were accepted for
* delivery. * delivery.
* *
* @param Swift_Mime_SimpleMessage $message * @param array $failedRecipients An array of failures by-reference
* @param array $failedRecipients An array of failures by-reference
* *
* @return int The number of successful recipients. Can be 0 which indicates failure * @return int The number of successful recipients. Can be 0 which indicates failure
*/ */
@@ -63,6 +60,7 @@ class Swift_Mailer
{ {
$failedRecipients = (array) $failedRecipients; $failedRecipients = (array) $failedRecipients;
// FIXME: to be removed in 7.0 (as transport must now start itself on send)
if (!$this->transport->isStarted()) { if (!$this->transport->isStarted()) {
$this->transport->start(); $this->transport->start();
} }
@@ -82,8 +80,6 @@ class Swift_Mailer
/** /**
* Register a plugin using a known unique key (e.g. myPlugin). * Register a plugin using a known unique key (e.g. myPlugin).
*
* @param Swift_Events_EventListener $plugin
*/ */
public function registerPlugin(Swift_Events_EventListener $plugin) public function registerPlugin(Swift_Events_EventListener $plugin)
{ {

View File

@@ -20,12 +20,10 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera
* *
* @var array * @var array
*/ */
private $recipients = array(); private $recipients = [];
/** /**
* Create a new ArrayRecipientIterator from $recipients. * Create a new ArrayRecipientIterator from $recipients.
*
* @param array $recipients
*/ */
public function __construct(array $recipients) public function __construct(array $recipients)
{ {

View File

@@ -15,7 +15,7 @@
*/ */
class Swift_MemorySpool implements Swift_Spool class Swift_MemorySpool implements Swift_Spool
{ {
protected $messages = array(); protected $messages = [];
private $flushRetries = 3; private $flushRetries = 3;
/** /**

View File

@@ -18,17 +18,17 @@ class Swift_Message extends Swift_Mime_SimpleMessage
/** /**
* @var Swift_Signers_HeaderSigner[] * @var Swift_Signers_HeaderSigner[]
*/ */
private $headerSigners = array(); private $headerSigners = [];
/** /**
* @var Swift_Signers_BodySigner[] * @var Swift_Signers_BodySigner[]
*/ */
private $bodySigners = array(); private $bodySigners = [];
/** /**
* @var array * @var array
*/ */
private $savedMessage = array(); private $savedMessage = [];
/** /**
* Create a new Message. * Create a new Message.
@@ -42,8 +42,8 @@ class Swift_Message extends Swift_Mime_SimpleMessage
*/ */
public function __construct($subject = null, $body = null, $contentType = null, $charset = null) public function __construct($subject = null, $body = null, $contentType = null, $charset = null)
{ {
call_user_func_array( \call_user_func_array(
array($this, 'Swift_Mime_SimpleMessage::__construct'), [$this, 'Swift_Mime_SimpleMessage::__construct'],
Swift_DependencyContainer::getInstance() Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.message') ->createDependenciesFor('mime.message')
); );
@@ -75,9 +75,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage
} }
/** /**
* Detach a signature handler from a message. * Attach a new signature handler to the message.
*
* @param Swift_Signer $signer
* *
* @return $this * @return $this
*/ */
@@ -93,9 +91,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage
} }
/** /**
* Attach a new signature handler to the message. * Detach a signature handler from a message.
*
* @param Swift_Signer $signer
* *
* @return $this * @return $this
*/ */
@@ -122,6 +118,19 @@ class Swift_Message extends Swift_Mime_SimpleMessage
return $this; return $this;
} }
/**
* Clear all signature handlers attached to the message.
*
* @return $this
*/
public function clearSigners()
{
$this->headerSigners = [];
$this->bodySigners = [];
return $this;
}
/** /**
* Get this message as a complete string. * Get this message as a complete string.
* *
@@ -146,8 +155,6 @@ class Swift_Message extends Swift_Mime_SimpleMessage
/** /**
* Write this message to a {@link Swift_InputByteStream}. * Write this message to a {@link Swift_InputByteStream}.
*
* @param Swift_InputByteStream $is
*/ */
public function toByteStream(Swift_InputByteStream $is) public function toByteStream(Swift_InputByteStream $is)
{ {
@@ -202,24 +209,22 @@ class Swift_Message extends Swift_Mime_SimpleMessage
*/ */
protected function saveMessage() protected function saveMessage()
{ {
$this->savedMessage = array('headers' => array()); $this->savedMessage = ['headers' => []];
$this->savedMessage['body'] = $this->getBody(); $this->savedMessage['body'] = $this->getBody();
$this->savedMessage['children'] = $this->getChildren(); $this->savedMessage['children'] = $this->getChildren();
if (count($this->savedMessage['children']) > 0 && $this->getBody() != '') { if (\count($this->savedMessage['children']) > 0 && '' != $this->getBody()) {
$this->setChildren(array_merge(array($this->becomeMimePart()), $this->savedMessage['children'])); $this->setChildren(array_merge([$this->becomeMimePart()], $this->savedMessage['children']));
$this->setBody(''); $this->setBody('');
} }
} }
/** /**
* save the original headers. * save the original headers.
*
* @param array $altered
*/ */
protected function saveHeaders(array $altered) protected function saveHeaders(array $altered)
{ {
foreach ($altered as $head) { foreach ($altered as $head) {
$lc = strtolower($head); $lc = strtolower($head ?? '');
if (!isset($this->savedMessage['headers'][$lc])) { if (!isset($this->savedMessage['headers'][$lc])) {
$this->savedMessage['headers'][$lc] = $this->getHeaders()->getAll($head); $this->savedMessage['headers'][$lc] = $this->getHeaders()->getAll($head);
@@ -252,7 +257,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage
$this->setChildren($this->savedMessage['children']); $this->setChildren($this->savedMessage['children']);
$this->restoreHeaders(); $this->restoreHeaders();
$this->savedMessage = array(); $this->savedMessage = [];
} }
/** /**

View File

@@ -16,18 +16,14 @@
class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
{ {
/** Recognized MIME types */ /** Recognized MIME types */
private $mimeTypes = array(); private $mimeTypes = [];
/** /**
* Create a new Attachment with $headers, $encoder and $cache. * Create a new Attachment with $headers, $encoder and $cache.
* *
* @param Swift_Mime_SimpleHeaderSet $headers * @param array $mimeTypes
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param array $mimeTypes
*/ */
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array()) public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = [])
{ {
parent::__construct($headers, $encoder, $cache, $idGenerator); parent::__construct($headers, $encoder, $cache, $idGenerator);
$this->setDisposition('attachment'); $this->setDisposition('attachment');
@@ -127,8 +123,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
/** /**
* Set the file that this attachment is for. * Set the file that this attachment is for.
* *
* @param Swift_FileStream $file * @param string $contentType optional
* @param string $contentType optional
* *
* @return $this * @return $this
*/ */
@@ -139,7 +134,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
if (!isset($contentType)) { if (!isset($contentType)) {
$extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1)); $extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1));
if (array_key_exists($extension, $this->mimeTypes)) { if (\array_key_exists($extension, $this->mimeTypes)) {
$this->setContentType($this->mimeTypes[$extension]); $this->setContentType($this->mimeTypes[$extension]);
} }
} }

View File

@@ -18,10 +18,7 @@ class Swift_Mime_ContentEncoder_Base64ContentEncoder extends Swift_Encoder_Base6
/** /**
* Encode stream $in to stream $out. * Encode stream $in to stream $out.
* *
* @param Swift_OutputByteStream $os * @param int $firstLineOffset
* @param Swift_InputByteStream $is
* @param int $firstLineOffset
* @param int $maxLineLength, optional, 0 indicates the default of 76 bytes
*/ */
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{ {
@@ -30,7 +27,7 @@ class Swift_Mime_ContentEncoder_Base64ContentEncoder extends Swift_Encoder_Base6
} }
$remainder = 0; $remainder = 0;
$base64ReadBufferRemainderBytes = null; $base64ReadBufferRemainderBytes = '';
// To reduce memory usage, the output buffer is streamed to the input buffer like so: // To reduce memory usage, the output buffer is streamed to the input buffer like so:
// Output Stream => base64encode => wrap line length => Input Stream // Output Stream => base64encode => wrap line length => Input Stream
@@ -41,17 +38,17 @@ class Swift_Mime_ContentEncoder_Base64ContentEncoder extends Swift_Encoder_Base6
// When the OutputStream is empty, we must flush any remainder bytes. // When the OutputStream is empty, we must flush any remainder bytes.
while (true) { while (true) {
$readBytes = $os->read(8192); $readBytes = $os->read(8192);
$atEOF = ($readBytes === false); $atEOF = (false === $readBytes);
if ($atEOF) { if ($atEOF) {
$streamTheseBytes = $base64ReadBufferRemainderBytes; $streamTheseBytes = $base64ReadBufferRemainderBytes;
} else { } else {
$streamTheseBytes = $base64ReadBufferRemainderBytes.$readBytes; $streamTheseBytes = $base64ReadBufferRemainderBytes.$readBytes;
} }
$base64ReadBufferRemainderBytes = null; $base64ReadBufferRemainderBytes = '';
$bytesLength = strlen($streamTheseBytes); $bytesLength = \strlen($streamTheseBytes);
if ($bytesLength === 0) { // no data left to encode if (0 === $bytesLength) { // no data left to encode
break; break;
} }
@@ -59,7 +56,7 @@ class Swift_Mime_ContentEncoder_Base64ContentEncoder extends Swift_Encoder_Base6
// and carry over remainder 1-2 bytes to the next loop iteration // and carry over remainder 1-2 bytes to the next loop iteration
if (!$atEOF) { if (!$atEOF) {
$excessBytes = $bytesLength % 3; $excessBytes = $bytesLength % 3;
if ($excessBytes !== 0) { if (0 !== $excessBytes) {
$base64ReadBufferRemainderBytes = substr($streamTheseBytes, -$excessBytes); $base64ReadBufferRemainderBytes = substr($streamTheseBytes, -$excessBytes);
$streamTheseBytes = substr($streamTheseBytes, 0, $bytesLength - $excessBytes); $streamTheseBytes = substr($streamTheseBytes, 0, $bytesLength - $excessBytes);
} }
@@ -69,7 +66,7 @@ class Swift_Mime_ContentEncoder_Base64ContentEncoder extends Swift_Encoder_Base6
$encodedTransformed = ''; $encodedTransformed = '';
$thisMaxLineLength = $maxLineLength - $remainder - $firstLineOffset; $thisMaxLineLength = $maxLineLength - $remainder - $firstLineOffset;
while ($thisMaxLineLength < strlen($encoded)) { while ($thisMaxLineLength < \strlen($encoded)) {
$encodedTransformed .= substr($encoded, 0, $thisMaxLineLength)."\r\n"; $encodedTransformed .= substr($encoded, 0, $thisMaxLineLength)."\r\n";
$firstLineOffset = 0; $firstLineOffset = 0;
$encoded = substr($encoded, $thisMaxLineLength); $encoded = substr($encoded, $thisMaxLineLength);
@@ -77,7 +74,7 @@ class Swift_Mime_ContentEncoder_Base64ContentEncoder extends Swift_Encoder_Base6
$remainder = 0; $remainder = 0;
} }
if (0 < $remainingLength = strlen($encoded)) { if (0 < $remainingLength = \strlen($encoded)) {
$remainder += $remainingLength; $remainder += $remainingLength;
$encodedTransformed .= $encoded; $encodedTransformed .= $encoded;
$encoded = null; $encoded = null;

View File

@@ -16,16 +16,16 @@
class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_ContentEncoder class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_ContentEncoder
{ {
/** /**
* @var null|string * @var string|null
*/ */
private $charset; private $charset;
/** /**
* @param null|string $charset * @param string|null $charset
*/ */
public function __construct($charset = null) public function __construct($charset = null)
{ {
$this->charset = $charset ? $charset : 'utf-8'; $this->charset = $charset ?: 'utf-8';
} }
/** /**
@@ -50,9 +50,8 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con
*/ */
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{ {
if ($this->charset !== 'utf-8') { if ('utf-8' !== $this->charset) {
throw new RuntimeException( throw new RuntimeException(sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset));
sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset));
} }
$string = ''; $string = '';
@@ -87,9 +86,8 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con
*/ */
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{ {
if ($this->charset !== 'utf-8') { if ('utf-8' !== $this->charset) {
throw new RuntimeException( throw new RuntimeException(sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset));
sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset));
} }
return $this->standardize(quoted_printable_encode($string)); return $this->standardize(quoted_printable_encode($string));
@@ -107,9 +105,9 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con
// transform CR or LF to CRLF // transform CR or LF to CRLF
$string = preg_replace('~=0D(?!=0A)|(?<!=0D)=0A~', '=0D=0A', $string); $string = preg_replace('~=0D(?!=0A)|(?<!=0D)=0A~', '=0D=0A', $string);
// transform =0D=0A to CRLF // transform =0D=0A to CRLF
$string = str_replace(array("\t=0D=0A", ' =0D=0A', '=0D=0A'), array("=09\r\n", "=20\r\n", "\r\n"), $string); $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], ["=09\r\n", "=20\r\n", "\r\n"], $string);
switch ($end = ord(substr($string, -1))) { switch (\ord(substr($string, -1))) {
case 0x09: case 0x09:
$string = substr_replace($string, '=09', -1); $string = substr_replace($string, '=09', -1);
break; break;

View File

@@ -0,0 +1,79 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles the case where the email body is already encoded and you just need specify the correct
* encoding without actually changing the encoding of the body.
*
* @author Jan Flora <jf@penneo.com>
*/
class Swift_Mime_ContentEncoder_NullContentEncoder implements Swift_Mime_ContentEncoder
{
/**
* The name of this encoding scheme (probably 7bit or 8bit).
*
* @var string
*/
private $name;
/**
* Creates a new NullContentEncoder with $name (probably 7bit or 8bit).
*
* @param string $name
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* Encode a given string to produce an encoded string.
*
* @param string $string
* @param int $firstLineOffset ignored
* @param int $maxLineLength ignored
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
return $string;
}
/**
* Encode stream $in to stream $out.
*
* @param int $firstLineOffset ignored
* @param int $maxLineLength ignored
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
while (false !== ($bytes = $os->read(8192))) {
$is->write($bytes);
}
}
/**
* Get the name of this encoding scheme.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Not used.
*/
public function charsetChanged($charset)
{
}
}

View File

@@ -11,6 +11,10 @@
/** /**
* Handles binary/7/8-bit Transfer Encoding in Swift Mailer. * Handles binary/7/8-bit Transfer Encoding in Swift Mailer.
* *
* When sending 8-bit content over SMTP, you should use
* Swift_Transport_Esmtp_EightBitMimeHandler to enable the 8BITMIME SMTP
* extension.
*
* @author Chris Corbyn * @author Chris Corbyn
*/ */
class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_ContentEncoder class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_ContentEncoder
@@ -33,7 +37,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
* Creates a new PlainContentEncoder with $name (probably 7bit or 8bit). * Creates a new PlainContentEncoder with $name (probably 7bit or 8bit).
* *
* @param string $name * @param string $name
* @param bool $canonical If canonicalization transformation should be done. * @param bool $canonical if canonicalization transformation should be done
*/ */
public function __construct($name, $canonical = false) public function __construct($name, $canonical = false)
{ {
@@ -62,10 +66,8 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
/** /**
* Encode stream $in to stream $out. * Encode stream $in to stream $out.
* *
* @param Swift_OutputByteStream $os * @param int $firstLineOffset ignored
* @param Swift_InputByteStream $is * @param int $maxLineLength optional, 0 means no wrapping will occur
* @param int $firstLineOffset ignored
* @param int $maxLineLength optional, 0 means no wrapping will occur
*/ */
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{ {
@@ -82,7 +84,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
$is->write($wrapped); $is->write($wrapped);
} }
if (strlen($leftOver)) { if (\strlen($leftOver)) {
$is->write($leftOver); $is->write($leftOver);
} }
} }
@@ -121,7 +123,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
$originalLines = explode($le, $string); $originalLines = explode($le, $string);
$lines = array(); $lines = [];
$lineCount = 0; $lineCount = 0;
foreach ($originalLines as $originalLine) { foreach ($originalLines as $originalLine) {
@@ -132,8 +134,8 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
$chunks = preg_split('/(?<=\s)/', $originalLine); $chunks = preg_split('/(?<=\s)/', $originalLine);
foreach ($chunks as $chunk) { foreach ($chunks as $chunk) {
if (0 != strlen($currentLine) if (0 != \strlen($currentLine)
&& strlen($currentLine.$chunk) > $length) { && \strlen($currentLine.$chunk) > $length) {
$lines[] = ''; $lines[] = '';
$currentLine = &$lines[$lineCount++]; $currentLine = &$lines[$lineCount++];
} }
@@ -154,8 +156,8 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
private function canonicalize($string) private function canonicalize($string)
{ {
return str_replace( return str_replace(
array("\r\n", "\r", "\n"), ["\r\n", "\r", "\n"],
array("\n", "\n", "\r\n"), ["\n", "\n", "\r\n"],
$string $string
); );
} }

View File

@@ -32,12 +32,12 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder
public function __sleep() public function __sleep()
{ {
return array('charStream', 'filter', 'dotEscape'); return ['charStream', 'filter', 'dotEscape'];
} }
protected function getSafeMapShareId() protected function getSafeMapShareId()
{ {
return get_class($this).($this->dotEscape ? '.dotEscape' : ''); return static::class.($this->dotEscape ? '.dotEscape' : '');
} }
protected function initSafeMap() protected function initSafeMap()
@@ -97,7 +97,7 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder
$enc = $this->encodeByteSequence($bytes, $size); $enc = $this->encodeByteSequence($bytes, $size);
$i = strpos($enc, '=0D=0A'); $i = strpos($enc, '=0D=0A');
$newLineLength = $lineLen + ($i === false ? $size : $i); $newLineLength = $lineLen + (false === $i ? $size : $i);
if ($currentLine && $newLineLength >= $thisLineLength) { if ($currentLine && $newLineLength >= $thisLineLength) {
$is->write($prepend.$this->standardize($currentLine)); $is->write($prepend.$this->standardize($currentLine));
@@ -109,14 +109,14 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder
$currentLine .= $enc; $currentLine .= $enc;
if ($i === false) { if (false === $i) {
$lineLen += $size; $lineLen += $size;
} else { } else {
// 6 is the length of '=0D=0A'. // 6 is the length of '=0D=0A'.
$lineLen = $size - strrpos($enc, '=0D=0A') - 6; $lineLen = $size - strrpos($enc, '=0D=0A') - 6;
} }
} }
if (strlen($currentLine)) { if (\strlen($currentLine)) {
$is->write($prepend.$this->standardize($currentLine)); $is->write($prepend.$this->standardize($currentLine));
} }
} }

View File

@@ -28,16 +28,14 @@ class Swift_Mime_ContentEncoder_QpContentEncoderProxy implements Swift_Mime_Cont
private $nativeEncoder; private $nativeEncoder;
/** /**
* @var null|string * @var string|null
*/ */
private $charset; private $charset;
/** /**
* Constructor. * Constructor.
* *
* @param Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder * @param string|null $charset
* @param Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder
* @param string|null $charset
*/ */
public function __construct(Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder, Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder, $charset) public function __construct(Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder, Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder, $charset)
{ {

View File

@@ -11,6 +11,9 @@
/** /**
* Handles raw Transfer Encoding in Swift Mailer. * Handles raw Transfer Encoding in Swift Mailer.
* *
* When sending 8-bit content over SMTP, you should use
* Swift_Transport_Esmtp_EightBitMimeHandler to enable the 8BITMIME SMTP
* extension.
* *
* @author Sebastiaan Stok <s.stok@rollerscapes.net> * @author Sebastiaan Stok <s.stok@rollerscapes.net>
*/ */
@@ -33,10 +36,8 @@ class Swift_Mime_ContentEncoder_RawContentEncoder implements Swift_Mime_ContentE
/** /**
* Encode stream $in to stream $out. * Encode stream $in to stream $out.
* *
* @param Swift_OutputByteStream $in * @param int $firstLineOffset ignored
* @param Swift_InputByteStream $out * @param int $maxLineLength ignored
* @param int $firstLineOffset ignored
* @param int $maxLineLength ignored
*/ */
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{ {

View File

@@ -18,13 +18,9 @@ class Swift_Mime_EmbeddedFile extends Swift_Mime_Attachment
/** /**
* Creates a new Attachment with $headers and $encoder. * Creates a new Attachment with $headers and $encoder.
* *
* @param Swift_Mime_SimpleHeaderSet $headers * @param array $mimeTypes optional
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param array $mimeTypes optional
*/ */
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array()) public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = [])
{ {
parent::__construct($headers, $encoder, $cache, $idGenerator, $mimeTypes); parent::__construct($headers, $encoder, $cache, $idGenerator, $mimeTypes);
$this->setDisposition('inline'); $this->setDisposition('inline');

View File

@@ -17,8 +17,6 @@ interface Swift_Mime_EncodingObserver
{ {
/** /**
* Notify this observer that the observed entity's ContentEncoder has changed. * Notify this observer that the observed entity's ContentEncoder has changed.
*
* @param Swift_Mime_ContentEncoder $encoder
*/ */
public function encoderChanged(Swift_Mime_ContentEncoder $encoder); public function encoderChanged(Swift_Mime_ContentEncoder $encoder);
} }

View File

@@ -85,7 +85,7 @@ interface Swift_Mime_Header
public function getFieldBody(); public function getFieldBody();
/** /**
* Get this Header rendered as a compliant string. * Get this Header rendered as a compliant string, including trailing CRLF.
* *
* @return string * @return string
*/ */

View File

@@ -41,7 +41,7 @@ class Swift_Mime_HeaderEncoder_Base64HeaderEncoder extends Swift_Encoder_Base64E
*/ */
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0, $charset = 'utf-8') public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0, $charset = 'utf-8')
{ {
if (strtolower($charset) === 'iso-2022-jp') { if ('iso-2022-jp' === strtolower($charset ?? '')) {
$old = mb_internal_encoding(); $old = mb_internal_encoding();
mb_internal_encoding('utf-8'); mb_internal_encoding('utf-8');
$newstring = mb_encode_mimeheader($string, $charset, $this->getName(), "\r\n"); $newstring = mb_encode_mimeheader($string, $charset, $this->getName(), "\r\n");

View File

@@ -29,9 +29,9 @@ class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder i
{ {
foreach (array_merge( foreach (array_merge(
range(0x61, 0x7A), range(0x41, 0x5A), range(0x61, 0x7A), range(0x41, 0x5A),
range(0x30, 0x39), array(0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F) range(0x30, 0x39), [0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F]
) as $byte) { ) as $byte) {
$this->safeMap[$byte] = chr($byte); $this->safeMap[$byte] = \chr($byte);
} }
} }
@@ -58,7 +58,7 @@ class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder i
*/ */
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{ {
return str_replace(array(' ', '=20', "=\r\n"), array('_', '_', "\r\n"), return str_replace([' ', '=20', "=\r\n"], ['_', '_', "\r\n"],
parent::encodeString($string, $firstLineOffset, $maxLineLength) parent::encodeString($string, $firstLineOffset, $maxLineLength)
); );
} }

View File

@@ -109,8 +109,6 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
/** /**
* Set the encoder used for encoding the header. * Set the encoder used for encoding the header.
*
* @param Swift_Mime_HeaderEncoder $encoder
*/ */
public function setEncoder(Swift_Mime_HeaderEncoder $encoder) public function setEncoder(Swift_Mime_HeaderEncoder $encoder)
{ {
@@ -196,11 +194,9 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
/** /**
* Produces a compliant, formatted RFC 2822 'phrase' based on the string given. * Produces a compliant, formatted RFC 2822 'phrase' based on the string given.
* *
* @param Swift_Mime_Header $header * @param string $string as displayed
* @param string $string as displayed * @param string $charset of the text
* @param string $charset of the text * @param bool $shorten the first line to make remove for header name
* @param Swift_Mime_HeaderEncoder $encoder
* @param bool $shorten the first line to make remove for header name
* *
* @return string * @return string
*/ */
@@ -214,13 +210,13 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
// .. but it is just ascii text, try escaping some characters // .. but it is just ascii text, try escaping some characters
// and make it a quoted-string // and make it a quoted-string
if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) { if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) {
$phraseStr = $this->escapeSpecials($phraseStr, array('"')); $phraseStr = $this->escapeSpecials($phraseStr, ['"']);
$phraseStr = '"'.$phraseStr.'"'; $phraseStr = '"'.$phraseStr.'"';
} else { } else {
// ... otherwise it needs encoding // ... otherwise it needs encoding
// Determine space remaining on line if first line // Determine space remaining on line if first line
if ($shorten) { if ($shorten) {
$usedLength = strlen($header->getFieldName().': '); $usedLength = \strlen($header->getFieldName().': ');
} else { } else {
$usedLength = 0; $usedLength = 0;
} }
@@ -239,9 +235,9 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
* *
* @return string * @return string
*/ */
private function escapeSpecials($token, $include = array()) private function escapeSpecials($token, $include = [])
{ {
foreach (array_merge(array('\\'), $include) as $char) { foreach (array_merge(['\\'], $include) as $char) {
$token = str_replace($char, '\\'.$char, $token); $token = str_replace($char, '\\'.$char, $token);
} }
@@ -251,9 +247,8 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
/** /**
* Encode needed word tokens within a string of input. * Encode needed word tokens within a string of input.
* *
* @param Swift_Mime_Header $header * @param string $input
* @param string $input * @param string $usedLength optional
* @param string $usedLength optional
* *
* @return string * @return string
*/ */
@@ -276,7 +271,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
} }
if (-1 == $usedLength) { if (-1 == $usedLength) {
$usedLength = strlen($header->getFieldName().': ') + strlen($value); $usedLength = \strlen($header->getFieldName().': ') + \strlen($value);
} }
$value .= $this->getTokenAsEncodedWord($token, $usedLength); $value .= $this->getTokenAsEncodedWord($token, $usedLength);
@@ -310,22 +305,22 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/ */
protected function getEncodableWordTokens($string) protected function getEncodableWordTokens($string)
{ {
$tokens = array(); $tokens = [];
$encodedToken = ''; $encodedToken = '';
// Split at all whitespace boundaries // Split at all whitespace boundaries
foreach (preg_split('~(?=[\t ])~', $string) as $token) { foreach (preg_split('~(?=[\t ])~', $string ?? '') as $token) {
if ($this->tokenNeedsEncoding($token)) { if ($this->tokenNeedsEncoding($token)) {
$encodedToken .= $token; $encodedToken .= $token;
} else { } else {
if (strlen($encodedToken) > 0) { if (\strlen($encodedToken) > 0) {
$tokens[] = $encodedToken; $tokens[] = $encodedToken;
$encodedToken = ''; $encodedToken = '';
} }
$tokens[] = $token; $tokens[] = $token;
} }
} }
if (strlen($encodedToken)) { if (\strlen($encodedToken)) {
$tokens[] = $encodedToken; $tokens[] = $encodedToken;
} }
@@ -347,7 +342,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
if (isset($this->lang)) { if (isset($this->lang)) {
$charsetDecl .= '*'.$this->lang; $charsetDecl .= '*'.$this->lang;
} }
$encodingWrapperLength = strlen( $encodingWrapperLength = \strlen(
'=?'.$charsetDecl.'?'.$this->encoder->getName().'??=' '=?'.$charsetDecl.'?'.$this->encoder->getName().'??='
); );
@@ -359,10 +354,10 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
$encodedTextLines = explode("\r\n", $encodedTextLines = explode("\r\n",
$this->encoder->encodeString( $this->encoder->encodeString(
$token, $firstLineOffset, 75 - $encodingWrapperLength, $this->charset $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->charset
) ) ?? ''
); );
if (strtolower($this->charset) !== 'iso-2022-jp') { if ('iso-2022-jp' !== strtolower($this->charset ?? '')) {
// special encoding for iso-2022-jp using mb_encode_mimeheader // special encoding for iso-2022-jp using mb_encode_mimeheader
foreach ($encodedTextLines as $lineNum => $line) { foreach ($encodedTextLines as $lineNum => $line) {
$encodedTextLines[$lineNum] = '=?'.$charsetDecl. $encodedTextLines[$lineNum] = '=?'.$charsetDecl.
@@ -383,7 +378,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/ */
protected function generateTokenLines($token) protected function generateTokenLines($token)
{ {
return preg_split('~(\r\n)~', $token, -1, PREG_SPLIT_DELIM_CAPTURE); return preg_split('~(\r\n)~', $token ?? '', -1, PREG_SPLIT_DELIM_CAPTURE);
} }
/** /**
@@ -431,10 +426,10 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
$string = $this->getFieldBody(); $string = $this->getFieldBody();
} }
$tokens = array(); $tokens = [];
// Generate atoms; split at all invisible boundaries followed by WSP // Generate atoms; split at all invisible boundaries followed by WSP
foreach (preg_split('~(?=[ \t])~', $string) as $token) { foreach (preg_split('~(?=[ \t])~', $string ?? '') as $token) {
$newTokens = $this->generateTokenLines($token); $newTokens = $this->generateTokenLines($token);
foreach ($newTokens as $newToken) { foreach ($newTokens as $newToken) {
$tokens[] = $newToken; $tokens[] = $newToken;
@@ -455,7 +450,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
private function tokensToString(array $tokens) private function tokensToString(array $tokens)
{ {
$lineCount = 0; $lineCount = 0;
$headerLines = array(); $headerLines = [];
$headerLines[] = $this->name.': '; $headerLines[] = $this->name.': ';
$currentLine = &$headerLines[$lineCount++]; $currentLine = &$headerLines[$lineCount++];
@@ -463,8 +458,8 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
foreach ($tokens as $i => $token) { foreach ($tokens as $i => $token) {
// Line longer than specified maximum or token was just a new line // Line longer than specified maximum or token was just a new line
if (("\r\n" == $token) || if (("\r\n" == $token) ||
($i > 0 && strlen($currentLine.$token) > $this->lineLength) ($i > 0 && \strlen($currentLine.$token) > $this->lineLength)
&& 0 < strlen($currentLine)) { && 0 < \strlen($currentLine)) {
$headerLines[] = ''; $headerLines[] = '';
$currentLine = &$headerLines[$lineCount++]; $currentLine = &$headerLines[$lineCount++];
} }
@@ -478,4 +473,14 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
// Implode with FWS (RFC 2822, 2.2.3) // Implode with FWS (RFC 2822, 2.2.3)
return implode("\r\n", $headerLines)."\r\n"; return implode("\r\n", $headerLines)."\r\n";
} }
/**
* Make a deep copy of object.
*/
public function __clone()
{
if ($this->encoder) {
$this->encoder = clone $this->encoder;
}
}
} }

View File

@@ -79,8 +79,6 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader
* Set the date-time of the Date in this Header. * Set the date-time of the Date in this Header.
* *
* If a DateTime instance is provided, it is converted to DateTimeImmutable. * If a DateTime instance is provided, it is converted to DateTimeImmutable.
*
* @param DateTimeInterface $dateTime
*/ */
public function setDateTime(DateTimeInterface $dateTime) public function setDateTime(DateTimeInterface $dateTime)
{ {

View File

@@ -9,6 +9,7 @@
*/ */
use Egulias\EmailValidator\EmailValidator; use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\MessageIDValidation;
use Egulias\EmailValidator\Validation\RFCValidation; use Egulias\EmailValidator\Validation\RFCValidation;
/** /**
@@ -25,7 +26,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
* *
* @var string[] * @var string[]
*/ */
private $ids = array(); private $ids = [];
/** /**
* The strict EmailValidator. * The strict EmailValidator.
@@ -34,16 +35,18 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*/ */
private $emailValidator; private $emailValidator;
private $addressEncoder;
/** /**
* Creates a new IdentificationHeader with the given $name and $id. * Creates a new IdentificationHeader with the given $name and $id.
* *
* @param string $name * @param string $name
* @param EmailValidator $emailValidator
*/ */
public function __construct($name, EmailValidator $emailValidator) public function __construct($name, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null)
{ {
$this->setFieldName($name); $this->setFieldName($name);
$this->emailValidator = $emailValidator; $this->emailValidator = $emailValidator;
$this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
} }
/** /**
@@ -94,7 +97,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*/ */
public function setId($id) public function setId($id)
{ {
$this->setIds(is_array($id) ? $id : array($id)); $this->setIds(\is_array($id) ? $id : [$id]);
} }
/** /**
@@ -106,7 +109,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*/ */
public function getId() public function getId()
{ {
if (count($this->ids) > 0) { if (\count($this->ids) > 0) {
return $this->ids[0]; return $this->ids[0];
} }
} }
@@ -120,7 +123,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*/ */
public function setIds(array $ids) public function setIds(array $ids)
{ {
$actualIds = array(); $actualIds = [];
foreach ($ids as $id) { foreach ($ids as $id) {
$this->assertValidId($id); $this->assertValidId($id);
@@ -156,10 +159,10 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
public function getFieldBody() public function getFieldBody()
{ {
if (!$this->getCachedValue()) { if (!$this->getCachedValue()) {
$angleAddrs = array(); $angleAddrs = [];
foreach ($this->ids as $id) { foreach ($this->ids as $id) {
$angleAddrs[] = '<'.$id.'>'; $angleAddrs[] = '<'.$this->addressEncoder->encodeString($id).'>';
} }
$this->setCachedValue(implode(' ', $angleAddrs)); $this->setCachedValue(implode(' ', $angleAddrs));
@@ -177,7 +180,9 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*/ */
private function assertValidId($id) private function assertValidId($id)
{ {
if (!$this->emailValidator->isValid($id, new RFCValidation())) { $emailValidation = class_exists(MessageIDValidation::class) ? new MessageIDValidation() : new RFCValidation();
if (!$this->emailValidator->isValid($id, $emailValidation)) {
throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>'); throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>');
} }
} }

View File

@@ -23,7 +23,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
* *
* @var string[] * @var string[]
*/ */
private $mailboxes = array(); private $mailboxes = [];
/** /**
* The strict EmailValidator. * The strict EmailValidator.
@@ -32,18 +32,19 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/ */
private $emailValidator; private $emailValidator;
private $addressEncoder;
/** /**
* Creates a new MailboxHeader with $name. * Creates a new MailboxHeader with $name.
* *
* @param string $name of Header * @param string $name of Header
* @param Swift_Mime_HeaderEncoder $encoder
* @param EmailValidator $emailValidator
*/ */
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, EmailValidator $emailValidator) public function __construct($name, Swift_Mime_HeaderEncoder $encoder, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null)
{ {
$this->setFieldName($name); $this->setFieldName($name);
$this->setEncoder($encoder); $this->setEncoder($encoder);
$this->emailValidator = $emailValidator; $this->emailValidator = $emailValidator;
$this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
} }
/** /**
@@ -257,10 +258,10 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/ */
protected function normalizeMailboxes(array $mailboxes) protected function normalizeMailboxes(array $mailboxes)
{ {
$actualMailboxes = array(); $actualMailboxes = [];
foreach ($mailboxes as $key => $value) { foreach ($mailboxes as $key => $value) {
if (is_string($key)) { if (\is_string($key)) {
//key is email addr //key is email addr
$address = $key; $address = $key;
$name = $value; $name = $value;
@@ -327,10 +328,10 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/ */
private function createNameAddressStrings(array $mailboxes) private function createNameAddressStrings(array $mailboxes)
{ {
$strings = array(); $strings = [];
foreach ($mailboxes as $email => $name) { foreach ($mailboxes as $email => $name) {
$mailboxStr = $email; $mailboxStr = $this->addressEncoder->encodeString($email);
if (null !== $name) { if (null !== $name) {
$nameStr = $this->createDisplayNameString($name, empty($strings)); $nameStr = $this->createDisplayNameString($name, empty($strings));
$mailboxStr = $nameStr.' <'.$mailboxStr.'>'; $mailboxStr = $nameStr.' <'.$mailboxStr.'>';
@@ -346,14 +347,12 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
* *
* @param string $address * @param string $address
* *
* @throws Swift_RfcComplianceException If invalid. * @throws Swift_RfcComplianceException if invalid
*/ */
private function assertValidAddress($address) private function assertValidAddress($address)
{ {
if (!$this->emailValidator->isValid($address, new RFCValidation())) { if (!$this->emailValidator->isValid($address, new RFCValidation())) {
throw new Swift_RfcComplianceException( throw new Swift_RfcComplianceException('Address in mailbox given ['.$address.'] does not comply with RFC 2822, 3.6.2.');
'Address in mailbox given ['.$address.'] does not comply with RFC 2822, 3.6.2.'
);
} }
} }
} }

View File

@@ -12,6 +12,8 @@
* An OpenDKIM Specific Header using only raw header datas without encoding. * An OpenDKIM Specific Header using only raw header datas without encoding.
* *
* @author De Cock Xavier <xdecock@gmail.com> * @author De Cock Xavier <xdecock@gmail.com>
*
* @deprecated since SwiftMailer 6.1.0; use Swift_Signers_DKIMSigner instead.
*/ */
class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
{ {
@@ -111,7 +113,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
*/ */
public function toString() public function toString()
{ {
return $this->fieldName.': '.$this->value; return $this->fieldName.': '.$this->value."\r\n";
} }
/** /**

View File

@@ -34,14 +34,12 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
* *
* @var string[] * @var string[]
*/ */
private $params = array(); private $params = [];
/** /**
* Creates a new ParameterizedHeader with $name. * Creates a new ParameterizedHeader with $name.
* *
* @param string $name * @param string $name
* @param Swift_Mime_HeaderEncoder $encoder
* @param Swift_Encoder $paramEncoder, optional
*/ */
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null) public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null)
{ {
@@ -83,7 +81,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
*/ */
public function setParameter($parameter, $value) public function setParameter($parameter, $value)
{ {
$this->setParameters(array_merge($this->getParameters(), array($parameter => $value))); $this->setParameters(array_merge($this->getParameters(), [$parameter => $value]));
} }
/** /**
@@ -97,7 +95,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
{ {
$params = $this->getParameters(); $params = $this->getParameters();
return isset($params[$parameter]) ? $params[$parameter] : null; return $params[$parameter] ?? null;
} }
/** /**
@@ -157,7 +155,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
foreach ($this->params as $name => $value) { foreach ($this->params as $name => $value) {
if (null !== $value) { if (null !== $value) {
// Add the semi-colon separator // Add the semi-colon separator
$tokens[count($tokens) - 1] .= ';'; $tokens[\count($tokens) - 1] .= ';';
$tokens = array_merge($tokens, $this->generateTokenLines( $tokens = array_merge($tokens, $this->generateTokenLines(
' '.$this->createParameter($name, $value) ' '.$this->createParameter($name, $value)
)); ));
@@ -181,7 +179,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
$encoded = false; $encoded = false;
// Allow room for parameter name, indices, "=" and DQUOTEs // Allow room for parameter name, indices, "=" and DQUOTEs
$maxValueLength = $this->getMaxLineLength() - strlen($name.'=*N"";') - 1; $maxValueLength = $this->getMaxLineLength() - \strlen($name.'=*N"";') - 1;
$firstLineOffset = 0; $firstLineOffset = 0;
// If it's not already a valid parameter value... // If it's not already a valid parameter value...
@@ -191,15 +189,15 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
if (!preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $value)) { if (!preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $value)) {
$encoded = true; $encoded = true;
// Allow space for the indices, charset and language // Allow space for the indices, charset and language
$maxValueLength = $this->getMaxLineLength() - strlen($name.'*N*="";') - 1; $maxValueLength = $this->getMaxLineLength() - \strlen($name.'*N*="";') - 1;
$firstLineOffset = strlen( $firstLineOffset = \strlen(
$this->getCharset()."'".$this->getLanguage()."'" $this->getCharset()."'".$this->getLanguage()."'"
); );
} }
} }
// Encode if we need to // Encode if we need to
if ($encoded || strlen($value) > $maxValueLength) { if ($encoded || \strlen($value) > $maxValueLength) {
if (isset($this->paramEncoder)) { if (isset($this->paramEncoder)) {
$value = $this->paramEncoder->encodeString( $value = $this->paramEncoder->encodeString(
$origValue, $firstLineOffset, $maxValueLength, $this->getCharset() $origValue, $firstLineOffset, $maxValueLength, $this->getCharset()
@@ -211,14 +209,14 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
} }
} }
$valueLines = isset($this->paramEncoder) ? explode("\r\n", $value) : array($value); $valueLines = isset($this->paramEncoder) ? explode("\r\n", $value) : [$value];
// Need to add indices // Need to add indices
if (count($valueLines) > 1) { if (\count($valueLines) > 1) {
$paramLines = array(); $paramLines = [];
foreach ($valueLines as $i => $line) { foreach ($valueLines as $i => $line) {
$paramLines[] = $name.'*'.$i. $paramLines[] = $name.'*'.$i.
$this->getEndOfParameterValue($line, true, $i == 0); $this->getEndOfParameterValue($line, true, 0 == $i);
} }
return implode(";\r\n ", $paramLines); return implode(";\r\n ", $paramLines);

View File

@@ -32,16 +32,18 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
*/ */
private $emailValidator; private $emailValidator;
private $addressEncoder;
/** /**
* Creates a new PathHeader with the given $name. * Creates a new PathHeader with the given $name.
* *
* @param string $name * @param string $name
* @param EmailValidator $emailValidator
*/ */
public function __construct($name, EmailValidator $emailValidator) public function __construct($name, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null)
{ {
$this->setFieldName($name); $this->setFieldName($name);
$this->emailValidator = $emailValidator; $this->emailValidator = $emailValidator;
$this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
} }
/** /**
@@ -127,7 +129,8 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
{ {
if (!$this->getCachedValue()) { if (!$this->getCachedValue()) {
if (isset($this->address)) { if (isset($this->address)) {
$this->setCachedValue('<'.$this->address.'>'); $address = $this->addressEncoder->encodeString($this->address);
$this->setCachedValue('<'.$address.'>');
} }
} }
@@ -144,9 +147,7 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
private function assertValidAddress($address) private function assertValidAddress($address)
{ {
if (!$this->emailValidator->isValid($address, new RFCValidation())) { if (!$this->emailValidator->isValid($address, new RFCValidation())) {
throw new Swift_RfcComplianceException( throw new Swift_RfcComplianceException('Address set in PathHeader does not comply with addr-spec of RFC 2822.');
'Address set in PathHeader does not comply with addr-spec of RFC 2822.'
);
} }
} }
} }

View File

@@ -25,8 +25,7 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH
/** /**
* Creates a new SimpleHeader with $name. * Creates a new SimpleHeader with $name.
* *
* @param string $name * @param string $name
* @param Swift_Mime_HeaderEncoder $encoder
*/ */
public function __construct($name, Swift_Mime_HeaderEncoder $encoder) public function __construct($name, Swift_Mime_HeaderEncoder $encoder)
{ {

View File

@@ -13,6 +13,8 @@
*/ */
class Swift_Mime_IdGenerator implements Swift_IdGenerator class Swift_Mime_IdGenerator implements Swift_IdGenerator
{ {
private $idRight;
/** /**
* @param string $idRight * @param string $idRight
*/ */
@@ -46,8 +48,7 @@ class Swift_Mime_IdGenerator implements Swift_IdGenerator
*/ */
public function generateId() public function generateId()
{ {
$idLeft = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)); // 32 hex values for the left part
return bin2hex(random_bytes(16)).'@'.$this->idRight;
return $idLeft.'@'.$this->idRight;
} }
} }

View File

@@ -30,11 +30,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
/** /**
* Create a new MimePart with $headers, $encoder and $cache. * Create a new MimePart with $headers, $encoder and $cache.
* *
* @param Swift_Mime_SimpleHeaderSet $headers * @param string $charset
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param string $charset
*/ */
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null) public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null)
{ {
@@ -173,7 +169,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
protected function fixHeaders() protected function fixHeaders()
{ {
parent::fixHeaders(); parent::fixHeaders();
if (count($this->getChildren())) { if (\count($this->getChildren())) {
$this->setHeaderParameter('Content-Type', 'charset', null); $this->setHeaderParameter('Content-Type', 'charset', null);
$this->setHeaderParameter('Content-Type', 'format', null); $this->setHeaderParameter('Content-Type', 'format', null);
$this->setHeaderParameter('Content-Type', 'delsp', null); $this->setHeaderParameter('Content-Type', 'delsp', null);
@@ -193,18 +189,9 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
/** Encode charset when charset is not utf-8 */ /** Encode charset when charset is not utf-8 */
protected function convertString($string) protected function convertString($string)
{ {
$charset = strtolower($this->getCharset()); $charset = strtolower($this->getCharset() ?? '');
if (!in_array($charset, array('utf-8', 'iso-8859-1', 'iso-8859-15', ''))) { if (!\in_array($charset, ['utf-8', 'iso-8859-1', 'iso-8859-15', ''])) {
// mb_convert_encoding must be the first one to check, since iconv cannot convert some words. return mb_convert_encoding($string, $charset, 'utf-8');
if (function_exists('mb_convert_encoding')) {
$string = mb_convert_encoding($string, $charset, 'utf-8');
} elseif (function_exists('iconv')) {
$string = iconv('utf-8//TRANSLIT//IGNORE', $charset, $string);
} else {
throw new Swift_SwiftException('No suitable convert encoding function (use UTF-8 as your charset or install the mbstring or iconv extension).');
}
return $string;
} }
return $string; return $string;

View File

@@ -23,29 +23,27 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_CharsetObserver
/** The Encoder used by parameters */ /** The Encoder used by parameters */
private $paramEncoder; private $paramEncoder;
/** The Grammar */
private $grammar;
/** Strict EmailValidator */ /** Strict EmailValidator */
private $emailValidator; private $emailValidator;
/** The charset of created Headers */ /** The charset of created Headers */
private $charset; private $charset;
/** Swift_AddressEncoder */
private $addressEncoder;
/** /**
* Creates a new SimpleHeaderFactory using $encoder and $paramEncoder. * Creates a new SimpleHeaderFactory using $encoder and $paramEncoder.
* *
* @param Swift_Mime_HeaderEncoder $encoder * @param string|null $charset
* @param Swift_Encoder $paramEncoder
* @param EmailValidator $emailValidator
* @param string|null $charset
*/ */
public function __construct(Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder, EmailValidator $emailValidator, $charset = null) public function __construct(Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder, EmailValidator $emailValidator, $charset = null, Swift_AddressEncoder $addressEncoder = null)
{ {
$this->encoder = $encoder; $this->encoder = $encoder;
$this->paramEncoder = $paramEncoder; $this->paramEncoder = $paramEncoder;
$this->emailValidator = $emailValidator; $this->emailValidator = $emailValidator;
$this->charset = $charset; $this->charset = $charset;
$this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
} }
/** /**
@@ -58,7 +56,7 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_CharsetObserver
*/ */
public function createMailboxHeader($name, $addresses = null) public function createMailboxHeader($name, $addresses = null)
{ {
$header = new Swift_Mime_Headers_MailboxHeader($name, $this->encoder, $this->emailValidator); $header = new Swift_Mime_Headers_MailboxHeader($name, $this->encoder, $this->emailValidator, $this->addressEncoder);
if (isset($addresses)) { if (isset($addresses)) {
$header->setFieldBodyModel($addresses); $header->setFieldBodyModel($addresses);
} }
@@ -70,8 +68,7 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_CharsetObserver
/** /**
* Create a new Date header using $dateTime. * Create a new Date header using $dateTime.
* *
* @param string $name * @param string $name
* @param DateTimeInterface|null $dateTime
* *
* @return Swift_Mime_Header * @return Swift_Mime_Header
*/ */
@@ -114,9 +111,9 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_CharsetObserver
* *
* @return Swift_Mime_Headers_ParameterizedHeader * @return Swift_Mime_Headers_ParameterizedHeader
*/ */
public function createParameterizedHeader($name, $value = null, $params = array()) public function createParameterizedHeader($name, $value = null, $params = [])
{ {
$header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->encoder, (strtolower($name) == 'content-disposition') ? $this->paramEncoder : null); $header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->encoder, ('content-disposition' == strtolower($name ?? '')) ? $this->paramEncoder : null);
if (isset($value)) { if (isset($value)) {
$header->setFieldBodyModel($value); $header->setFieldBodyModel($value);
} }
@@ -185,6 +182,7 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_CharsetObserver
{ {
$this->encoder = clone $this->encoder; $this->encoder = clone $this->encoder;
$this->paramEncoder = clone $this->paramEncoder; $this->paramEncoder = clone $this->paramEncoder;
$this->addressEncoder = clone $this->addressEncoder;
} }
/** Apply the charset to the Header */ /** Apply the charset to the Header */

View File

@@ -19,13 +19,13 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
private $factory; private $factory;
/** Collection of set Headers */ /** Collection of set Headers */
private $headers = array(); private $headers = [];
/** Field ordering details */ /** Field ordering details */
private $order = array(); private $order = [];
/** List of fields which are required to be displayed */ /** List of fields which are required to be displayed */
private $required = array(); private $required = [];
/** The charset used by Headers */ /** The charset used by Headers */
private $charset; private $charset;
@@ -33,8 +33,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
/** /**
* Create a new SimpleHeaderSet with the given $factory. * Create a new SimpleHeaderSet with the given $factory.
* *
* @param Swift_Mime_SimpleHeaderFactory $factory * @param string $charset
* @param string $charset
*/ */
public function __construct(Swift_Mime_SimpleHeaderFactory $factory, $charset = null) public function __construct(Swift_Mime_SimpleHeaderFactory $factory, $charset = null)
{ {
@@ -69,20 +68,17 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
*/ */
public function addMailboxHeader($name, $addresses = null) public function addMailboxHeader($name, $addresses = null)
{ {
$this->storeHeader($name, $this->storeHeader($name, $this->factory->createMailboxHeader($name, $addresses));
$this->factory->createMailboxHeader($name, $addresses));
} }
/** /**
* Add a new Date header using $dateTime. * Add a new Date header using $dateTime.
* *
* @param string $name * @param string $name
* @param DateTimeInterface $dateTime
*/ */
public function addDateHeader($name, DateTimeInterface $dateTime = null) public function addDateHeader($name, DateTimeInterface $dateTime = null)
{ {
$this->storeHeader($name, $this->storeHeader($name, $this->factory->createDateHeader($name, $dateTime));
$this->factory->createDateHeader($name, $dateTime));
} }
/** /**
@@ -93,8 +89,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
*/ */
public function addTextHeader($name, $value = null) public function addTextHeader($name, $value = null)
{ {
$this->storeHeader($name, $this->storeHeader($name, $this->factory->createTextHeader($name, $value));
$this->factory->createTextHeader($name, $value));
} }
/** /**
@@ -104,7 +99,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
* @param string $value * @param string $value
* @param array $params * @param array $params
*/ */
public function addParameterizedHeader($name, $value = null, $params = array()) public function addParameterizedHeader($name, $value = null, $params = [])
{ {
$this->storeHeader($name, $this->factory->createParameterizedHeader($name, $value, $params)); $this->storeHeader($name, $this->factory->createParameterizedHeader($name, $value, $params));
} }
@@ -143,18 +138,18 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
*/ */
public function has($name, $index = 0) public function has($name, $index = 0)
{ {
$lowerName = strtolower($name); $lowerName = strtolower($name ?? '');
if (!array_key_exists($lowerName, $this->headers)) { if (!\array_key_exists($lowerName, $this->headers)) {
return false; return false;
} }
if (func_num_args() < 2) { if (\func_num_args() < 2) {
// index was not specified, so we only need to check that there is at least one header value set // index was not specified, so we only need to check that there is at least one header value set
return (bool) count($this->headers[$lowerName]); return (bool) \count($this->headers[$lowerName]);
} }
return array_key_exists($index, $this->headers[$lowerName]); return \array_key_exists($index, $this->headers[$lowerName]);
} }
/** /**
@@ -166,8 +161,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
* If $index is specified, the header will be inserted into the set at this * If $index is specified, the header will be inserted into the set at this
* offset. * offset.
* *
* @param Swift_Mime_Header $header * @param int $index
* @param int $index
*/ */
public function set(Swift_Mime_Header $header, $index = 0) public function set(Swift_Mime_Header $header, $index = 0)
{ {
@@ -183,13 +177,13 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
* @param string $name * @param string $name
* @param int $index * @param int $index
* *
* @return Swift_Mime_Header * @return Swift_Mime_Header|null
*/ */
public function get($name, $index = 0) public function get($name, $index = 0)
{ {
$name = strtolower($name); $name = strtolower($name ?? '');
if (func_num_args() < 2) { if (\func_num_args() < 2) {
if ($this->has($name)) { if ($this->has($name)) {
$values = array_values($this->headers[$name]); $values = array_values($this->headers[$name]);
@@ -212,7 +206,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
public function getAll($name = null) public function getAll($name = null)
{ {
if (!isset($name)) { if (!isset($name)) {
$headers = array(); $headers = [];
foreach ($this->headers as $collection) { foreach ($this->headers as $collection) {
$headers = array_merge($headers, $collection); $headers = array_merge($headers, $collection);
} }
@@ -220,9 +214,9 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
return $headers; return $headers;
} }
$lowerName = strtolower($name); $lowerName = strtolower($name ?? '');
if (!array_key_exists($lowerName, $this->headers)) { if (!\array_key_exists($lowerName, $this->headers)) {
return array(); return [];
} }
return $this->headers[$lowerName]; return $this->headers[$lowerName];
@@ -237,7 +231,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
{ {
$headers = $this->headers; $headers = $this->headers;
if ($this->canSort()) { if ($this->canSort()) {
uksort($headers, array($this, 'sortHeaders')); uksort($headers, [$this, 'sortHeaders']);
} }
return array_keys($headers); return array_keys($headers);
@@ -253,7 +247,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
*/ */
public function remove($name, $index = 0) public function remove($name, $index = 0)
{ {
$lowerName = strtolower($name); $lowerName = strtolower($name ?? '');
unset($this->headers[$lowerName][$index]); unset($this->headers[$lowerName][$index]);
} }
@@ -264,7 +258,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
*/ */
public function removeAll($name) public function removeAll($name)
{ {
$lowerName = strtolower($name); $lowerName = strtolower($name ?? '');
unset($this->headers[$lowerName]); unset($this->headers[$lowerName]);
} }
@@ -272,8 +266,6 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
* Define a list of Header names as an array in the correct order. * Define a list of Header names as an array in the correct order.
* *
* These Headers will be output in the given order where present. * These Headers will be output in the given order where present.
*
* @param array $sequence
*/ */
public function defineOrdering(array $sequence) public function defineOrdering(array $sequence)
{ {
@@ -284,8 +276,6 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
* Set a list of header names which must always be displayed when set. * Set a list of header names which must always be displayed when set.
* *
* Usually headers without a field value won't be output unless set here. * Usually headers without a field value won't be output unless set here.
*
* @param array $names
*/ */
public function setAlwaysDisplayed(array $names) public function setAlwaysDisplayed(array $names)
{ {
@@ -312,11 +302,11 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
$string = ''; $string = '';
$headers = $this->headers; $headers = $this->headers;
if ($this->canSort()) { if ($this->canSort()) {
uksort($headers, array($this, 'sortHeaders')); uksort($headers, [$this, 'sortHeaders']);
} }
foreach ($headers as $collection) { foreach ($headers as $collection) {
foreach ($collection as $header) { foreach ($collection as $header) {
if ($this->isDisplayed($header) || $header->getFieldBody() != '') { if ($this->isDisplayed($header) || '' != $header->getFieldBody()) {
$string .= $header->toString(); $string .= $header->toString();
} }
} }
@@ -340,38 +330,38 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
/** Save a Header to the internal collection */ /** Save a Header to the internal collection */
private function storeHeader($name, Swift_Mime_Header $header, $offset = null) private function storeHeader($name, Swift_Mime_Header $header, $offset = null)
{ {
if (!isset($this->headers[strtolower($name)])) { if (!isset($this->headers[strtolower($name ?? '')])) {
$this->headers[strtolower($name)] = array(); $this->headers[strtolower($name ?? '')] = [];
} }
if (!isset($offset)) { if (!isset($offset)) {
$this->headers[strtolower($name)][] = $header; $this->headers[strtolower($name ?? '')][] = $header;
} else { } else {
$this->headers[strtolower($name)][$offset] = $header; $this->headers[strtolower($name ?? '')][$offset] = $header;
} }
} }
/** Test if the headers can be sorted */ /** Test if the headers can be sorted */
private function canSort() private function canSort()
{ {
return count($this->order) > 0; return \count($this->order) > 0;
} }
/** uksort() algorithm for Header ordering */ /** uksort() algorithm for Header ordering */
private function sortHeaders($a, $b) private function sortHeaders($a, $b)
{ {
$lowerA = strtolower($a); $lowerA = strtolower($a ?? '');
$lowerB = strtolower($b); $lowerB = strtolower($b ?? '');
$aPos = array_key_exists($lowerA, $this->order) ? $this->order[$lowerA] : -1; $aPos = \array_key_exists($lowerA, $this->order) ? $this->order[$lowerA] : -1;
$bPos = array_key_exists($lowerB, $this->order) ? $this->order[$lowerB] : -1; $bPos = \array_key_exists($lowerB, $this->order) ? $this->order[$lowerB] : -1;
if (-1 === $aPos && -1 === $bPos) { if (-1 === $aPos && -1 === $bPos) {
// just be sure to be determinist here // just be sure to be determinist here
return $a > $b ? -1 : 1; return $a > $b ? -1 : 1;
} }
if ($aPos == -1) { if (-1 == $aPos) {
return 1; return 1;
} elseif ($bPos == -1) { } elseif (-1 == $bPos) {
return -1; return -1;
} }
@@ -381,7 +371,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
/** Test if the given Header is always displayed */ /** Test if the given Header is always displayed */
private function isDisplayed(Swift_Mime_Header $header) private function isDisplayed(Swift_Mime_Header $header)
{ {
return array_key_exists(strtolower($header->getFieldName()), $this->required); return \array_key_exists(strtolower($header->getFieldName() ?? ''), $this->required);
} }
/** Notify all Headers of the new charset */ /** Notify all Headers of the new charset */

View File

@@ -24,16 +24,12 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
/** /**
* Create a new SimpleMessage with $headers, $encoder and $cache. * Create a new SimpleMessage with $headers, $encoder and $cache.
* *
* @param Swift_Mime_SimpleHeaderSet $headers * @param string $charset
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param string $charset
*/ */
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null) public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null)
{ {
parent::__construct($headers, $encoder, $cache, $idGenerator, $charset); parent::__construct($headers, $encoder, $cache, $idGenerator, $charset);
$this->getHeaders()->defineOrdering(array( $this->getHeaders()->defineOrdering([
'Return-Path', 'Return-Path',
'Received', 'Received',
'DKIM-Signature', 'DKIM-Signature',
@@ -50,8 +46,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
'MIME-Version', 'MIME-Version',
'Content-Type', 'Content-Type',
'Content-Transfer-Encoding', 'Content-Transfer-Encoding',
)); ]);
$this->getHeaders()->setAlwaysDisplayed(array('Date', 'Message-ID', 'From')); $this->getHeaders()->setAlwaysDisplayed(['Date', 'Message-ID', 'From']);
$this->getHeaders()->addTextHeader('MIME-Version', '1.0'); $this->getHeaders()->addTextHeader('MIME-Version', '1.0');
$this->setDate(new DateTimeImmutable()); $this->setDate(new DateTimeImmutable());
$this->setId($this->getId()); $this->setId($this->getId());
@@ -97,8 +93,6 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
/** /**
* Set the date at which this message was created. * Set the date at which this message was created.
* *
* @param DateTimeInterface $dateTime
*
* @return $this * @return $this
*/ */
public function setDate(DateTimeInterface $dateTime) public function setDate(DateTimeInterface $dateTime)
@@ -158,8 +152,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
*/ */
public function setSender($address, $name = null) public function setSender($address, $name = null)
{ {
if (!is_array($address) && isset($name)) { if (!\is_array($address) && isset($name)) {
$address = array($address => $name); $address = [$address => $name];
} }
if (!$this->setHeaderFieldModel('Sender', (array) $address)) { if (!$this->setHeaderFieldModel('Sender', (array) $address)) {
@@ -212,8 +206,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
*/ */
public function setFrom($addresses, $name = null) public function setFrom($addresses, $name = null)
{ {
if (!is_array($addresses) && isset($name)) { if (!\is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name); $addresses = [$addresses => $name];
} }
if (!$this->setHeaderFieldModel('From', (array) $addresses)) { if (!$this->setHeaderFieldModel('From', (array) $addresses)) {
@@ -266,8 +260,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
*/ */
public function setReplyTo($addresses, $name = null) public function setReplyTo($addresses, $name = null)
{ {
if (!is_array($addresses) && isset($name)) { if (!\is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name); $addresses = [$addresses => $name];
} }
if (!$this->setHeaderFieldModel('Reply-To', (array) $addresses)) { if (!$this->setHeaderFieldModel('Reply-To', (array) $addresses)) {
@@ -321,8 +315,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
*/ */
public function setTo($addresses, $name = null) public function setTo($addresses, $name = null)
{ {
if (!is_array($addresses) && isset($name)) { if (!\is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name); $addresses = [$addresses => $name];
} }
if (!$this->setHeaderFieldModel('To', (array) $addresses)) { if (!$this->setHeaderFieldModel('To', (array) $addresses)) {
@@ -373,8 +367,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
*/ */
public function setCc($addresses, $name = null) public function setCc($addresses, $name = null)
{ {
if (!is_array($addresses) && isset($name)) { if (!\is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name); $addresses = [$addresses => $name];
} }
if (!$this->setHeaderFieldModel('Cc', (array) $addresses)) { if (!$this->setHeaderFieldModel('Cc', (array) $addresses)) {
@@ -425,8 +419,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
*/ */
public function setBcc($addresses, $name = null) public function setBcc($addresses, $name = null)
{ {
if (!is_array($addresses) && isset($name)) { if (!\is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name); $addresses = [$addresses => $name];
} }
if (!$this->setHeaderFieldModel('Bcc', (array) $addresses)) { if (!$this->setHeaderFieldModel('Bcc', (array) $addresses)) {
@@ -457,13 +451,13 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
*/ */
public function setPriority($priority) public function setPriority($priority)
{ {
$priorityMap = array( $priorityMap = [
self::PRIORITY_HIGHEST => 'Highest', self::PRIORITY_HIGHEST => 'Highest',
self::PRIORITY_HIGH => 'High', self::PRIORITY_HIGH => 'High',
self::PRIORITY_NORMAL => 'Normal', self::PRIORITY_NORMAL => 'Normal',
self::PRIORITY_LOW => 'Low', self::PRIORITY_LOW => 'Low',
self::PRIORITY_LOWEST => 'Lowest', self::PRIORITY_LOWEST => 'Lowest',
); ];
$pMapKeys = array_keys($priorityMap); $pMapKeys = array_keys($priorityMap);
if ($priority > max($pMapKeys)) { if ($priority > max($pMapKeys)) {
$priority = max($pMapKeys); $priority = max($pMapKeys);
@@ -493,7 +487,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
'%[1-5]' '%[1-5]'
); );
return isset($priority) ? $priority : 3; return $priority ?? 3;
} }
/** /**
@@ -526,13 +520,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
/** /**
* Attach a {@link Swift_Mime_SimpleMimeEntity} such as an Attachment or MimePart. * Attach a {@link Swift_Mime_SimpleMimeEntity} such as an Attachment or MimePart.
* *
* @param Swift_Mime_SimpleMimeEntity $entity
*
* @return $this * @return $this
*/ */
public function attach(Swift_Mime_SimpleMimeEntity $entity) public function attach(Swift_Mime_SimpleMimeEntity $entity)
{ {
$this->setChildren(array_merge($this->getChildren(), array($entity))); $this->setChildren(array_merge($this->getChildren(), [$entity]));
return $this; return $this;
} }
@@ -540,13 +532,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
/** /**
* Remove an already attached entity. * Remove an already attached entity.
* *
* @param Swift_Mime_SimpleMimeEntity $entity
*
* @return $this * @return $this
*/ */
public function detach(Swift_Mime_SimpleMimeEntity $entity) public function detach(Swift_Mime_SimpleMimeEntity $entity)
{ {
$newChildren = array(); $newChildren = [];
foreach ($this->getChildren() as $child) { foreach ($this->getChildren() as $child) {
if ($entity !== $child) { if ($entity !== $child) {
$newChildren[] = $child; $newChildren[] = $child;
@@ -559,9 +549,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
/** /**
* Attach a {@link Swift_Mime_SimpleMimeEntity} and return it's CID source. * Attach a {@link Swift_Mime_SimpleMimeEntity} and return it's CID source.
* This method should be used when embedding images or other data in a message.
* *
* @param Swift_Mime_SimpleMimeEntity $entity * This method should be used when embedding images or other data in a message.
* *
* @return string * @return string
*/ */
@@ -579,8 +568,8 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
*/ */
public function toString() public function toString()
{ {
if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { if (\count($children = $this->getChildren()) > 0 && '' != $this->getBody()) {
$this->setChildren(array_merge(array($this->becomeMimePart()), $children)); $this->setChildren(array_merge([$this->becomeMimePart()], $children));
$string = parent::toString(); $string = parent::toString();
$this->setChildren($children); $this->setChildren($children);
} else { } else {
@@ -604,13 +593,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
/** /**
* Write this message to a {@link Swift_InputByteStream}. * Write this message to a {@link Swift_InputByteStream}.
*
* @param Swift_InputByteStream $is
*/ */
public function toByteStream(Swift_InputByteStream $is) public function toByteStream(Swift_InputByteStream $is)
{ {
if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { if (\count($children = $this->getChildren()) > 0 && '' != $this->getBody()) {
$this->setChildren(array_merge(array($this->becomeMimePart()), $children)); $this->setChildren(array_merge([$this->becomeMimePart()], $children));
parent::toByteStream($is); parent::toByteStream($is);
$this->setChildren($children); $this->setChildren($children);
} else { } else {

View File

@@ -43,14 +43,14 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
private $boundary; private $boundary;
/** Mime types to be used based on the nesting level */ /** Mime types to be used based on the nesting level */
private $compositeRanges = array( private $compositeRanges = [
'multipart/mixed' => array(self::LEVEL_TOP, self::LEVEL_MIXED), 'multipart/mixed' => [self::LEVEL_TOP, self::LEVEL_MIXED],
'multipart/alternative' => array(self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE), 'multipart/alternative' => [self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE],
'multipart/related' => array(self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED), 'multipart/related' => [self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED],
); ];
/** A set of filter rules to define what level an entity should be nested at */ /** A set of filter rules to define what level an entity should be nested at */
private $compoundLevelFilters = array(); private $compoundLevelFilters = [];
/** The nesting level of this entity */ /** The nesting level of this entity */
private $nestingLevel = self::LEVEL_ALTERNATIVE; private $nestingLevel = self::LEVEL_ALTERNATIVE;
@@ -59,20 +59,20 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
private $cache; private $cache;
/** Direct descendants of this entity */ /** Direct descendants of this entity */
private $immediateChildren = array(); private $immediateChildren = [];
/** All descendants of this entity */ /** All descendants of this entity */
private $children = array(); private $children = [];
/** The maximum line length of the body of this entity */ /** The maximum line length of the body of this entity */
private $maxLineLength = 78; private $maxLineLength = 78;
/** The order in which alternative mime types should appear */ /** The order in which alternative mime types should appear */
private $alternativePartOrder = array( private $alternativePartOrder = [
'text/plain' => 1, 'text/plain' => 1,
'text/html' => 2, 'text/html' => 2,
'multipart/related' => 3, 'multipart/related' => 3,
); ];
/** The CID of this entity */ /** The CID of this entity */
private $id; private $id;
@@ -84,20 +84,15 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
/** /**
* Create a new SimpleMimeEntity with $headers, $encoder and $cache. * Create a new SimpleMimeEntity with $headers, $encoder and $cache.
*
* @param Swift_Mime_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
*/ */
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator) public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator)
{ {
$this->cacheKey = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)); $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values
$this->cache = $cache; $this->cache = $cache;
$this->headers = $headers; $this->headers = $headers;
$this->idGenerator = $idGenerator; $this->idGenerator = $idGenerator;
$this->setEncoder($encoder); $this->setEncoder($encoder);
$this->headers->defineOrdering(array('Content-Type', 'Content-Transfer-Encoding')); $this->headers->defineOrdering(['Content-Type', 'Content-Transfer-Encoding']);
// This array specifies that, when the entire MIME document contains // This array specifies that, when the entire MIME document contains
// $compoundLevel, then for each child within $level, if its Content-Type // $compoundLevel, then for each child within $level, if its Content-Type
@@ -112,14 +107,14 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
// ) // )
// ) // )
$this->compoundLevelFilters = array( $this->compoundLevelFilters = [
(self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array( (self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => [
self::LEVEL_ALTERNATIVE => array( self::LEVEL_ALTERNATIVE => [
'text/plain' => self::LEVEL_ALTERNATIVE, 'text/plain' => self::LEVEL_ALTERNATIVE,
'text/html' => self::LEVEL_RELATED, 'text/html' => self::LEVEL_RELATED,
), ],
), ],
); ];
$this->id = $this->idGenerator->generateId(); $this->id = $this->idGenerator->generateId();
} }
@@ -168,6 +163,16 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
return $this->getHeaderFieldModel('Content-Type'); return $this->getHeaderFieldModel('Content-Type');
} }
/**
* Get the Body Content-type of this entity.
*
* @return string
*/
public function getBodyContentType()
{
return $this->userContentType;
}
/** /**
* Set the Content-type of this entity. * Set the Content-type of this entity.
* *
@@ -293,16 +298,16 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
public function setChildren(array $children, $compoundLevel = null) public function setChildren(array $children, $compoundLevel = null)
{ {
// TODO: Try to refactor this logic // TODO: Try to refactor this logic
$compoundLevel = isset($compoundLevel) ? $compoundLevel : $this->getCompoundLevel($children); $compoundLevel = $compoundLevel ?? $this->getCompoundLevel($children);
$immediateChildren = array(); $immediateChildren = [];
$grandchildren = array(); $grandchildren = [];
$newContentType = $this->userContentType; $newContentType = $this->userContentType;
foreach ($children as $child) { foreach ($children as $child) {
$level = $this->getNeededChildLevel($child, $compoundLevel); $level = $this->getNeededChildLevel($child, $compoundLevel);
if (empty($immediateChildren)) { if (empty($immediateChildren)) {
//first iteration //first iteration
$immediateChildren = array($child); $immediateChildren = [$child];
} else { } else {
$nextLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel); $nextLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel);
if ($nextLevel == $level) { if ($nextLevel == $level) {
@@ -311,7 +316,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
// Re-assign immediateChildren to grandchildren // Re-assign immediateChildren to grandchildren
$grandchildren = array_merge($grandchildren, $immediateChildren); $grandchildren = array_merge($grandchildren, $immediateChildren);
// Set new children // Set new children
$immediateChildren = array($child); $immediateChildren = [$child];
} else { } else {
$grandchildren[] = $child; $grandchildren[] = $child;
} }
@@ -375,7 +380,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
} }
$this->body = $body; $this->body = $body;
if (isset($contentType)) { if (null !== $contentType) {
$this->setContentType($contentType); $this->setContentType($contentType);
} }
@@ -395,8 +400,6 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
/** /**
* Set the encoder used for the body of this entity. * Set the encoder used for the body of this entity.
* *
* @param Swift_Mime_ContentEncoder $encoder
*
* @return $this * @return $this
*/ */
public function setEncoder(Swift_Mime_ContentEncoder $encoder) public function setEncoder(Swift_Mime_ContentEncoder $encoder)
@@ -420,7 +423,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
public function getBoundary() public function getBoundary()
{ {
if (!isset($this->boundary)) { if (!isset($this->boundary)) {
$this->boundary = '_=_swift_'.time().'_'.md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)).'_=_'; $this->boundary = '_=_swift_'.time().'_'.bin2hex(random_bytes(16)).'_=_';
} }
return $this->boundary; return $this->boundary;
@@ -457,8 +460,6 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
/** /**
* Receive notification that the encoder of this entity or a parent entity * Receive notification that the encoder of this entity or a parent entity
* has changed. * has changed.
*
* @param Swift_Mime_ContentEncoder $encoder
*/ */
public function encoderChanged(Swift_Mime_ContentEncoder $encoder) public function encoderChanged(Swift_Mime_ContentEncoder $encoder)
{ {
@@ -522,8 +523,6 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
/** /**
* Write this entire entity to a {@see Swift_InputByteStream}. * Write this entire entity to a {@see Swift_InputByteStream}.
*
* @param Swift_InputByteStream
*/ */
public function toByteStream(Swift_InputByteStream $is) public function toByteStream(Swift_InputByteStream $is)
{ {
@@ -535,8 +534,6 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
/** /**
* Write this entire entity to a {@link Swift_InputByteStream}. * Write this entire entity to a {@link Swift_InputByteStream}.
*
* @param Swift_InputByteStream
*/ */
protected function bodyToByteStream(Swift_InputByteStream $is) protected function bodyToByteStream(Swift_InputByteStream $is)
{ {
@@ -637,7 +634,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
*/ */
protected function fixHeaders() protected function fixHeaders()
{ {
if (count($this->immediateChildren)) { if (\count($this->immediateChildren)) {
$this->setHeaderParameter('Content-Type', 'boundary', $this->setHeaderParameter('Content-Type', 'boundary',
$this->getBoundary() $this->getBoundary()
); );
@@ -726,7 +723,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
private function getNeededChildLevel($child, $compoundLevel) private function getNeededChildLevel($child, $compoundLevel)
{ {
$filter = array(); $filter = [];
foreach ($this->compoundLevelFilters as $bitmask => $rules) { foreach ($this->compoundLevelFilters as $bitmask => $rules) {
if (($compoundLevel & $bitmask) === $bitmask) { if (($compoundLevel & $bitmask) === $bitmask) {
$filter = $rules + $filter; $filter = $rules + $filter;
@@ -734,7 +731,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
} }
$realLevel = $child->getNestingLevel(); $realLevel = $child->getNestingLevel();
$lowercaseType = strtolower($child->getContentType()); $lowercaseType = strtolower($child->getContentType() ?? '');
if (isset($filter[$realLevel]) && isset($filter[$realLevel][$lowercaseType])) { if (isset($filter[$realLevel]) && isset($filter[$realLevel][$lowercaseType])) {
return $filter[$realLevel][$lowercaseType]; return $filter[$realLevel][$lowercaseType];
@@ -769,7 +766,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
$shouldSort = false; $shouldSort = false;
foreach ($this->immediateChildren as $child) { foreach ($this->immediateChildren as $child) {
// NOTE: This include alternative parts moved into a related part // NOTE: This include alternative parts moved into a related part
if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE) { if (self::LEVEL_ALTERNATIVE == $child->getNestingLevel()) {
$shouldSort = true; $shouldSort = true;
break; break;
} }
@@ -778,13 +775,13 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
// Sort in order of preference, if there is one // Sort in order of preference, if there is one
if ($shouldSort) { if ($shouldSort) {
// Group the messages by order of preference // Group the messages by order of preference
$sorted = array(); $sorted = [];
foreach ($this->immediateChildren as $child) { foreach ($this->immediateChildren as $child) {
$type = $child->getContentType(); $type = $child->getContentType();
$level = array_key_exists($type, $this->alternativePartOrder) ? $this->alternativePartOrder[$type] : max($this->alternativePartOrder) + 1; $level = \array_key_exists($type, $this->alternativePartOrder) ? $this->alternativePartOrder[$type] : max($this->alternativePartOrder) + 1;
if (empty($sorted[$level])) { if (empty($sorted[$level])) {
$sorted[$level] = array(); $sorted[$level] = [];
} }
$sorted[$level][] = $child; $sorted[$level][] = $child;
@@ -792,7 +789,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
ksort($sorted); ksort($sorted);
$this->immediateChildren = array_reduce($sorted, 'array_merge', array()); $this->immediateChildren = array_reduce($sorted, 'array_merge', []);
} }
} }
@@ -813,11 +810,17 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_M
{ {
$this->headers = clone $this->headers; $this->headers = clone $this->headers;
$this->encoder = clone $this->encoder; $this->encoder = clone $this->encoder;
$this->cacheKey = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)); $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values
$children = array(); $children = [];
foreach ($this->children as $pos => $child) { foreach ($this->children as $pos => $child) {
$children[$pos] = clone $child; $children[$pos] = clone $child;
} }
$this->setChildren($children); $this->setChildren($children);
} }
public function __wakeup()
{
$this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values
$this->cache = new Swift_KeyCache_ArrayKeyCache(new Swift_KeyCache_SimpleKeyCacheInputStream());
}
} }

View File

@@ -26,8 +26,8 @@ class Swift_MimePart extends Swift_Mime_MimePart
*/ */
public function __construct($body = null, $contentType = null, $charset = null) public function __construct($body = null, $contentType = null, $charset = null)
{ {
call_user_func_array( \call_user_func_array(
array($this, 'Swift_Mime_MimePart::__construct'), [$this, 'Swift_Mime_MimePart::__construct'],
Swift_DependencyContainer::getInstance() Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.part') ->createDependenciesFor('mime.part')
); );

Some files were not shown because too many files have changed in this diff Show More