* setNameAddresses(array(
* 'chris@swiftmailer.org' => 'Chris Corbyn',
* 'mark@swiftmailer.org' //No associated personal name
* ));
* ?>
*
* @param string|string[] $mailboxes
* @throws Swift_RfcComplianceException
* @see __construct()
* @see setAddresses()
* @see setValue()
*/
public function setNameAddresses($mailboxes)
{
$this->_mailboxes = $this->normalizeMailboxes((array) $mailboxes);
$this->setCachedValue(null); //Clear any cached value
}
/**
* Get the full mailbox list of this Header as an array of valid RFC 2822 strings.
* Example:
*
* 'Chris Corbyn',
* 'mark@swiftmailer.org' => 'Mark Corbyn')
* );
* print_r($header->getNameAddressStrings());
* // array (
* // 0 => Chris Corbyn ,
* // 1 => Mark Corbyn
* // )
* ?>
*
* @return string[]
* @throws Swift_RfcComplianceException
* @see getNameAddresses()
* @see toString()
*/
public function getNameAddressStrings()
{
return $this->_createNameAddressStrings($this->getNameAddresses());
}
/**
* Get all mailboxes in this Header as key=>value pairs.
* The key is the address and the value is the name (or null if none set).
* Example:
*
* 'Chris Corbyn',
* 'mark@swiftmailer.org' => 'Mark Corbyn')
* );
* print_r($header->getNameAddresses());
* // array (
* // chris@swiftmailer.org => Chris Corbyn,
* // mark@swiftmailer.org => Mark Corbyn
* // )
* ?>
*
* @return string[]
* @see getAddresses()
* @see getNameAddressStrings()
*/
public function getNameAddresses()
{
return $this->_mailboxes;
}
/**
* Makes this Header represent a list of plain email addresses with no names.
* Example:
*
* setAddresses(
* array('one@domain.tld', 'two@domain.tld', 'three@domain.tld')
* );
* ?>
*
* @param string[] $addresses
* @throws Swift_RfcComplianceException
* @see setNameAddresses()
* @see setValue()
*/
public function setAddresses($addresses)
{
$this->setNameAddresses(array_values((array) $addresses));
}
/**
* Get all email addresses in this Header.
* @return string[]
* @see getNameAddresses()
*/
public function getAddresses()
{
return array_keys($this->_mailboxes);
}
/**
* Remove one or more addresses from this Header.
* @param string|string[] $addresses
*/
public function removeAddresses($addresses)
{
$this->setCachedValue(null);
foreach ((array) $addresses as $address) {
unset($this->_mailboxes[$address]);
}
}
/**
* Get the string value of the body in this Header.
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
* @return string
* @throws Swift_RfcComplianceException
* @see toString()
*/
public function getFieldBody()
{
//Compute the string value of the header only if needed
if (is_null($this->getCachedValue())) {
$this->setCachedValue($this->createMailboxListString($this->_mailboxes));
}
return $this->getCachedValue();
}
// -- Points of extension
/**
* Normalizes a user-input list of mailboxes into consistent key=>value pairs.
* @param string[] $mailboxes
* @return string[]
* @access protected
*/
protected function normalizeMailboxes(array $mailboxes)
{
$actualMailboxes = array();
foreach ($mailboxes as $key => $value) {
if (is_string($key)) { //key is email addr
$address = $key;
$name = $value;
} else {
$address = $value;
$name = null;
}
$this->_assertValidAddress($address);
$actualMailboxes[$address] = $name;
}
return $actualMailboxes;
}
/**
* Produces a compliant, formatted display-name based on the string given.
* @param string $displayName as displayed
* @param boolean $shorten the first line to make remove for header name
* @return string
* @access protected
*/
protected function createDisplayNameString($displayName, $shorten = false)
{
return $this->createPhrase($this, $displayName,
$this->getCharset(), $this->getEncoder(), $shorten
);
}
/**
* Creates a string form of all the mailboxes in the passed array.
* @param string[] $mailboxes
* @return string
* @throws Swift_RfcComplianceException
* @access protected
*/
protected function createMailboxListString(array $mailboxes)
{
return implode(', ', $this->_createNameAddressStrings($mailboxes));
}
/**
* Redefine the encoding requirements for mailboxes. Commas and semicolons are used to separate
* multiple addresses, and should therefore be encoded
* @param string $token
* @return boolean
*/
protected function tokenNeedsEncoding($token)
{
return preg_match('/[,;]/', $token) || parent::tokenNeedsEncoding($token);
}
// -- Private methods
/**
* Return an array of strings conforming the the name-addr spec of RFC 2822.
* @param string[] $mailboxes
* @return string[]
* @access private
*/
private function _createNameAddressStrings(array $mailboxes)
{
$strings = array();
foreach ($mailboxes as $email => $name) {
$mailboxStr = $email;
if (!is_null($name)) {
$nameStr = $this->createDisplayNameString($name, empty($strings));
$mailboxStr = $nameStr . ' <' . $mailboxStr . '>';
}
$strings[] = $mailboxStr;
}
return $strings;
}
/**
* Throws an Exception if the address passed does not comply with RFC 2822.
* @param string $address
* @throws Swift_RfcComplianceException If invalid.
* @access private
*/
private function _assertValidAddress($address)
{
if (!preg_match('/^' . $this->getGrammar()->getDefinition('addr-spec') . '$/D',
$address))
{
throw new Swift_RfcComplianceException(
'Address in mailbox given [' . $address .
'] does not comply with RFC 2822, 3.6.2.'
);
}
}
}
Swift-4.2.1/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php 100644 0 0 16467 12000050366 22146 0 ustar 0 0 _paramEncoder = $paramEncoder;
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_PARAMETERIZED;
}
/**
* Set the character set used in this Header.
* @param string $charset
*/
public function setCharset($charset)
{
parent::setCharset($charset);
if (isset($this->_paramEncoder)) {
$this->_paramEncoder->charsetChanged($charset);
}
}
/**
* Set the value of $parameter.
* @param string $parameter
* @param string $value
*/
public function setParameter($parameter, $value)
{
$this->setParameters(array_merge($this->getParameters(), array($parameter => $value)));
}
/**
* Get the value of $parameter.
* @return string
*/
public function getParameter($parameter)
{
$params = $this->getParameters();
return array_key_exists($parameter, $params)
? $params[$parameter]
: null;
}
/**
* Set an associative array of parameter names mapped to values.
* @param string[]
*/
public function setParameters(array $parameters)
{
$this->clearCachedValueIf($this->_params != $parameters);
$this->_params = $parameters;
}
/**
* Returns an associative array of parameter names mapped to values.
* @return string[]
*/
public function getParameters()
{
return $this->_params;
}
/**
* Get the value of this header prepared for rendering.
* @return string
*/
public function getFieldBody() //TODO: Check caching here
{
$body = parent::getFieldBody();
foreach ($this->_params as $name => $value) {
if (!is_null($value)) {
//Add the parameter
$body .= '; ' . $this->_createParameter($name, $value);
}
}
return $body;
}
// -- Protected methods
/**
* Generate a list of all tokens in the final header.
* This doesn't need to be overridden in theory, but it is for implementation
* reasons to prevent potential breakage of attributes.
* @param string $string The string to tokenize
* @return array An array of tokens as strings
* @access protected
*/
protected function toTokens($string = null)
{
$tokens = parent::toTokens(parent::getFieldBody());
//Try creating any parameters
foreach ($this->_params as $name => $value) {
if (!is_null($value)) {
//Add the semi-colon separator
$tokens[count($tokens)-1] .= ';';
$tokens = array_merge($tokens, $this->generateTokenLines(
' ' . $this->_createParameter($name, $value)
));
}
}
return $tokens;
}
// -- Private methods
/**
* Render a RFC 2047 compliant header parameter from the $name and $value.
* @param string $name
* @param string $value
* @return string
* @access private
*/
private function _createParameter($name, $value)
{
$origValue = $value;
$encoded = false;
//Allow room for parameter name, indices, "=" and DQUOTEs
$maxValueLength = $this->getMaxLineLength() - strlen($name . '=*N"";') - 1;
$firstLineOffset = 0;
//If it's not already a valid parameter value...
if (!preg_match('/^' . self::TOKEN_REGEX . '$/D', $value)) {
//TODO: text, or something else??
//... and it's not ascii
if (!preg_match('/^' . $this->getGrammar()->getDefinition('text') . '*$/D', $value)) {
$encoded = true;
//Allow space for the indices, charset and language
$maxValueLength = $this->getMaxLineLength() - strlen($name . '*N*="";') - 1;
$firstLineOffset = strlen(
$this->getCharset() . "'" . $this->getLanguage() . "'"
);
}
}
//Encode if we need to
if ($encoded || strlen($value) > $maxValueLength) {
if (isset($this->_paramEncoder)) {
$value = $this->_paramEncoder->encodeString(
$origValue, $firstLineOffset, $maxValueLength, $this->getCharset()
);
} else { //We have to go against RFC 2183/2231 in some areas for interoperability
$value = $this->getTokenAsEncodedWord($origValue);
$encoded = false;
}
}
$valueLines = isset($this->_paramEncoder) ? explode("\r\n", $value) : array($value);
//Need to add indices
if (count($valueLines) > 1) {
$paramLines = array();
foreach ($valueLines as $i => $line) {
$paramLines[] = $name . '*' . $i .
$this->_getEndOfParameterValue($line, true, $i == 0);
}
return implode(";\r\n ", $paramLines);
} else {
return $name . $this->_getEndOfParameterValue(
$valueLines[0], $encoded, true
);
}
}
/**
* Returns the parameter value from the "=" and beyond.
* @param string $value to append
* @param boolean $encoded
* @param boolean $firstLine
* @return string
* @access private
*/
private function _getEndOfParameterValue($value, $encoded = false, $firstLine = false)
{
if (!preg_match('/^' . self::TOKEN_REGEX . '$/D', $value)) {
$value = '"' . $value . '"';
}
$prepend = '=';
if ($encoded) {
$prepend = '*=';
if ($firstLine) {
$prepend = '*=' . $this->getCharset() . "'" . $this->getLanguage() .
"'";
}
}
return $prepend . $value;
}
}
Swift-4.2.1/lib/classes/Swift/Mime/Headers/PathHeader.php 100644 0 0 6653 12000050366 20222 0 ustar 0 0 setFieldName($name);
parent::__construct($grammar);
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_PATH;
}
/**
* Set the model for the field body.
* This method takes a string for an address.
* @param string $model
* @throws Swift_RfcComplianceException
*/
public function setFieldBodyModel($model)
{
$this->setAddress($model);
}
/**
* Get the model for the field body.
* This method returns a string email address.
* @return mixed
*/
public function getFieldBodyModel()
{
return $this->getAddress();
}
/**
* Set the Address which should appear in this Header.
* @param string $address
* @throws Swift_RfcComplianceException
*/
public function setAddress($address)
{
if (is_null($address)) {
$this->_address = null;
} elseif ('' == $address) {
$this->_address = '';
} else {
$this->_assertValidAddress($address);
$this->_address = $address;
}
$this->setCachedValue(null);
}
/**
* Get the address which is used in this Header (if any).
* Null is returned if no address is set.
* @return string
*/
public function getAddress()
{
return $this->_address;
}
/**
* Get the string value of the body in this Header.
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
* @return string
* @see toString()
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
if (isset($this->_address)) {
$this->setCachedValue('<' . $this->_address . '>');
}
}
return $this->getCachedValue();
}
/**
* Throws an Exception if the address passed does not comply with RFC 2822.
* @param string $address
* @throws Swift_RfcComplianceException If invalid.
* @access private
*/
private function _assertValidAddress($address)
{
if (!preg_match('/^' . $this->getGrammar()->getDefinition('addr-spec') . '$/D',
$address))
{
throw new Swift_RfcComplianceException(
'Address set in PathHeader does not comply with addr-spec of RFC 2822.'
);
}
}
}
Swift-4.2.1/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php 100644 0 0 4531 12000050366 22026 0 ustar 0 0 setFieldName($name);
$this->setEncoder($encoder);
parent::__construct($grammar);
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_TEXT;
}
/**
* Set the model for the field body.
* This method takes a string for the field value.
* @param string $model
*/
public function setFieldBodyModel($model)
{
$this->setValue($model);
}
/**
* Get the model for the field body.
* This method returns a string.
* @return string
*/
public function getFieldBodyModel()
{
return $this->getValue();
}
/**
* Get the (unencoded) value of this header.
* @return string
*/
public function getValue()
{
return $this->_value;
}
/**
* Set the (unencoded) value of this header.
* @param string $value
*/
public function setValue($value)
{
$this->clearCachedValueIf($this->_value != $value);
$this->_value = $value;
}
/**
* Get the value of this header prepared for rendering.
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
$this->setCachedValue(
$this->encodeWords($this, $this->_value)
);
}
return $this->getCachedValue();
}
}
Swift-4.2.1/lib/classes/Swift/Mime/Message.php 100644 0 0 13711 12000050366 16237 0 ustar 0 0 'Real Name').
*
* If the second parameter is provided and the first is a string, then $name
* is associated with the address.
*
* @param mixed $address
* @param string $name optional
*/
public function setSender($address, $name = null);
/**
* Get the sender address for this message.
*
* This has a higher significance than the From address.
*
* @return string
*/
public function getSender();
/**
* Set the From address of this message.
*
* It is permissible for multiple From addresses to be set using an array.
*
* If multiple From addresses are used, you SHOULD set the Sender address and
* according to RFC 2822, MUST set the sender address.
*
* An array can be used if display names are to be provided: i.e.
* array('email@address.com' => 'Real Name').
*
* If the second parameter is provided and the first is a string, then $name
* is associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setFrom($addresses, $name = null);
/**
* Get the From address(es) of this message.
*
* This method always returns an associative array where the keys are the
* addresses.
*
* @return string[]
*/
public function getFrom();
/**
* Set the Reply-To address(es).
*
* Any replies from the receiver will be sent to this address.
*
* It is permissible for multiple reply-to addresses to be set using an array.
*
* This method has the same synopsis as {@link setFrom()} and {@link setTo()}.
*
* If the second parameter is provided and the first is a string, then $name
* is associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setReplyTo($addresses, $name = null);
/**
* Get the Reply-To addresses for this message.
*
* This method always returns an associative array where the keys provide the
* email addresses.
*
* @return string[]
*/
public function getReplyTo();
/**
* Set the To address(es).
*
* Recipients set in this field will receive a copy of this message.
*
* This method has the same synopsis as {@link setFrom()} and {@link setCc()}.
*
* If the second parameter is provided and the first is a string, then $name
* is associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setTo($addresses, $name = null);
/**
* Get the To addresses for this message.
*
* This method always returns an associative array, whereby the keys provide
* the actual email addresses.
*
* @return string[]
*/
public function getTo();
/**
* Set the Cc address(es).
*
* Recipients set in this field will receive a 'carbon-copy' of this message.
*
* This method has the same synopsis as {@link setFrom()} and {@link setTo()}.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setCc($addresses, $name = null);
/**
* Get the Cc addresses for this message.
*
* This method always returns an associative array, whereby the keys provide
* the actual email addresses.
*
* @return string[]
*/
public function getCc();
/**
* Set the Bcc address(es).
*
* Recipients set in this field will receive a 'blind-carbon-copy' of this
* message.
*
* In other words, they will get the message, but any other recipients of the
* message will have no such knowledge of their receipt of it.
*
* This method has the same synopsis as {@link setFrom()} and {@link setTo()}.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setBcc($addresses, $name = null);
/**
* Get the Bcc addresses for this message.
*
* This method always returns an associative array, whereby the keys provide
* the actual email addresses.
*
* @return string[]
*/
public function getBcc();
}
Swift-4.2.1/lib/classes/Swift/Mime/MimeEntity.php 100644 0 0 5515 12000050366 16722 0 ustar 0 0 setContentType('text/plain');
if (!is_null($charset)) {
$this->setCharset($charset);
}
}
/**
* Set the body of this entity, either as a string, or as an instance of
* {@link Swift_OutputByteStream}.
*
* @param mixed $body
* @param string $contentType optional
* @param string $charset optional
* @param Swift_Mime_MimePart
*/
public function setBody($body, $contentType = null, $charset = null)
{
if (isset($charset)) {
$this->setCharset($charset);
}
$body = $this->_convertString($body);
parent::setBody($body, $contentType);
return $this;
}
/**
* Get the character set of this entity.
*
* @return string
*/
public function getCharset()
{
return $this->_getHeaderParameter('Content-Type', 'charset');
}
/**
* Set the character set of this entity.
*
* @param string $charset
* @param Swift_Mime_MimePart
*/
public function setCharset($charset)
{
$this->_setHeaderParameter('Content-Type', 'charset', $charset);
if ($charset !== $this->_userCharset) {
$this->_clearCache();
}
$this->_userCharset = $charset;
parent::charsetChanged($charset);
return $this;
}
/**
* Get the format of this entity (i.e. flowed or fixed).
*
* @return string
*/
public function getFormat()
{
return $this->_getHeaderParameter('Content-Type', 'format');
}
/**
* Set the format of this entity (flowed or fixed).
*
* @param string $format
* @param Swift_Mime_MimePart
*/
public function setFormat($format)
{
$this->_setHeaderParameter('Content-Type', 'format', $format);
$this->_userFormat = $format;
return $this;
}
/**
* Test if delsp is being used for this entity.
*
* @return boolean
*/
public function getDelSp()
{
return ($this->_getHeaderParameter('Content-Type', 'delsp') == 'yes')
? true
: false;
}
/**
* Turn delsp on or off for this entity.
*
* @param boolean $delsp
* @param Swift_Mime_MimePart
*/
public function setDelSp($delsp = true)
{
$this->_setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null);
$this->_userDelSp = $delsp;
return $this;
}
/**
* Get the nesting level of this entity.
*
* @return int
* @see LEVEL_TOP, LEVEL_ALTERNATIVE, LEVEL_MIXED, LEVEL_RELATED
*/
public function getNestingLevel()
{
return $this->_nestingLevel;
}
/**
* Receive notification that the charset has changed on this document, or a
* parent document.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->setCharset($charset);
}
// -- Protected methods
/** Fix the content-type and encoding of this entity */
protected function _fixHeaders()
{
parent::_fixHeaders();
if (count($this->getChildren())) {
$this->_setHeaderParameter('Content-Type', 'charset', null);
$this->_setHeaderParameter('Content-Type', 'format', null);
$this->_setHeaderParameter('Content-Type', 'delsp', null);
} else {
$this->setCharset($this->_userCharset);
$this->setFormat($this->_userFormat);
$this->setDelSp($this->_userDelSp);
}
}
/** Set the nesting level of this entity */
protected function _setNestingLevel($level)
{
$this->_nestingLevel = $level;
}
/** Encode charset when charset is not utf-8 */
protected function _convertString($string)
{
$charset = strtolower($this->getCharset());
if (!in_array($charset, array('utf-8', 'iso-8859-1', ""))) {
// mb_convert_encoding must be the first one to check, since iconv cannot convert some words.
if (function_exists('mb_convert_encoding')) {
$string = mb_convert_encoding($string, $charset, 'utf-8');
} elseif (function_exists('iconv')) {
$string = iconv($charset, 'utf-8//TRANSLIT//IGNORE', $string);
} else {
throw new Swift_SwiftException('No suitable convert encoding function (use UTF-8 as your harset or install the mbstring or iconv extension).');
}
return $string;
}
return $string;
}
}
Swift-4.2.1/lib/classes/Swift/Mime/ParameterizedHeader.php 100644 0 0 1242 12000050366 20534 0 ustar 0 0 _encoder = $encoder;
$this->_paramEncoder = $paramEncoder;
$this->_grammar = $grammar;
$this->_charset = $charset;
}
/**
* Create a new Mailbox Header with a list of $addresses.
* @param string $name
* @param array|string $addresses
* @return Swift_Mime_Header
*/
public function createMailboxHeader($name, $addresses = null)
{
$header = new Swift_Mime_Headers_MailboxHeader($name, $this->_encoder, $this->_grammar);
if (isset($addresses)) {
$header->setFieldBodyModel($addresses);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new Date header using $timestamp (UNIX time).
* @param string $name
* @param int $timestamp
* @return Swift_Mime_Header
*/
public function createDateHeader($name, $timestamp = null)
{
$header = new Swift_Mime_Headers_DateHeader($name, $this->_grammar);
if (isset($timestamp)) {
$header->setFieldBodyModel($timestamp);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new basic text header with $name and $value.
* @param string $name
* @param string $value
* @return Swift_Mime_Header
*/
public function createTextHeader($name, $value = null)
{
$header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->_encoder, $this->_grammar);
if (isset($value)) {
$header->setFieldBodyModel($value);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new ParameterizedHeader with $name, $value and $params.
* @param string $name
* @param string $value
* @param array $params
* @return Swift_Mime_ParameterizedHeader
*/
public function createParameterizedHeader($name, $value = null,
$params = array())
{
$header = new Swift_Mime_Headers_ParameterizedHeader($name,
$this->_encoder, (strtolower($name) == 'content-disposition')
? $this->_paramEncoder
: null,
$this->_grammar
);
if (isset($value)) {
$header->setFieldBodyModel($value);
}
foreach ($params as $k => $v) {
$header->setParameter($k, $v);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new ID header for Message-ID or Content-ID.
* @param string $name
* @param string|array $ids
* @return Swift_Mime_Header
*/
public function createIdHeader($name, $ids = null)
{
$header = new Swift_Mime_Headers_IdentificationHeader($name, $this->_grammar);
if (isset($ids)) {
$header->setFieldBodyModel($ids);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new Path header with an address (path) in it.
* @param string $name
* @param string $path
* @return Swift_Mime_Header
*/
public function createPathHeader($name, $path = null)
{
$header = new Swift_Mime_Headers_PathHeader($name, $this->_grammar);
if (isset($path)) {
$header->setFieldBodyModel($path);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Notify this observer that the entity's charset has changed.
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->_charset = $charset;
$this->_encoder->charsetChanged($charset);
$this->_paramEncoder->charsetChanged($charset);
}
// -- Private methods
/** Apply the charset to the Header */
private function _setHeaderCharset(Swift_Mime_Header $header)
{
if (isset($this->_charset)) {
$header->setCharset($this->_charset);
}
}
}
Swift-4.2.1/lib/classes/Swift/Mime/SimpleHeaderSet.php 100644 0 0 22653 12000050366 17676 0 ustar 0 0 _factory = $factory;
if (isset($charset)) {
$this->setCharset($charset);
}
}
/**
* Set the charset used by these headers.
*
* @param string $charset
*/
public function setCharset($charset)
{
$this->_charset = $charset;
$this->_factory->charsetChanged($charset);
$this->_notifyHeadersOfCharset($charset);
}
/**
* Add a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string $addresses
*/
public function addMailboxHeader($name, $addresses = null)
{
$this->_storeHeader($name,
$this->_factory->createMailboxHeader($name, $addresses));
}
/**
* Add a new Date header using $timestamp (UNIX time).
*
* @param string $name
* @param int $timestamp
*/
public function addDateHeader($name, $timestamp = null)
{
$this->_storeHeader($name,
$this->_factory->createDateHeader($name, $timestamp));
}
/**
* Add a new basic text header with $name and $value.
*
* @param string $name
* @param string $value
*/
public function addTextHeader($name, $value = null)
{
$this->_storeHeader($name,
$this->_factory->createTextHeader($name, $value));
}
/**
* Add a new ParameterizedHeader with $name, $value and $params.
*
* @param string $name
* @param string $value
* @param array $params
*/
public function addParameterizedHeader($name, $value = null, $params = array())
{
$this->_storeHeader($name,
$this->_factory->createParameterizedHeader($name, $value,
$params));
}
/**
* Add a new ID header for Message-ID or Content-ID.
*
* @param string $name
* @param string|array $ids
*/
public function addIdHeader($name, $ids = null)
{
$this->_storeHeader($name, $this->_factory->createIdHeader($name, $ids));
}
/**
* Add a new Path header with an address (path) in it.
*
* @param string $name
* @param string $path
*/
public function addPathHeader($name, $path = null)
{
$this->_storeHeader($name, $this->_factory->createPathHeader($name, $path));
}
/**
* Returns true if at least one header with the given $name exists.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*
* @return boolean
*/
public function has($name, $index = 0)
{
$lowerName = strtolower($name);
return array_key_exists($lowerName, $this->_headers)
&& array_key_exists($index, $this->_headers[$lowerName]);
}
/**
* Set a header in the HeaderSet.
*
* The header may be a previously fetched header via {@link get()} or it may
* be one that has been created separately.
*
* If $index is specified, the header will be inserted into the set at this
* offset.
*
* @param Swift_Mime_Header $header
* @param int $index
*/
public function set(Swift_Mime_Header $header, $index = 0)
{
$this->_storeHeader($header->getFieldName(), $header, $index);
}
/**
* Get the header with the given $name.
*
* If multiple headers match, the actual one may be specified by $index.
* Returns NULL if none present.
*
* @param string $name
* @param int $index
*
* @return Swift_Mime_Header
*/
public function get($name, $index = 0)
{
if ($this->has($name, $index)) {
$lowerName = strtolower($name);
return $this->_headers[$lowerName][$index];
}
}
/**
* Get all headers with the given $name.
*
* @param string $name
*
* @return array
*/
public function getAll($name = null)
{
if (!isset($name)) {
$headers = array();
foreach ($this->_headers as $collection) {
$headers = array_merge($headers, $collection);
}
return $headers;
}
$lowerName = strtolower($name);
if (!array_key_exists($lowerName, $this->_headers)) {
return array();
}
return $this->_headers[$lowerName];
}
/**
* Remove the header with the given $name if it's set.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*/
public function remove($name, $index = 0)
{
$lowerName = strtolower($name);
unset($this->_headers[$lowerName][$index]);
}
/**
* Remove all headers with the given $name.
*
* @param string $name
*/
public function removeAll($name)
{
$lowerName = strtolower($name);
unset($this->_headers[$lowerName]);
}
/**
* Create a new instance of this HeaderSet.
*
* @return Swift_Mime_HeaderSet
*/
public function newInstance()
{
return new self($this->_factory);
}
/**
* Define a list of Header names as an array in the correct order.
*
* These Headers will be output in the given order where present.
*
* @param array $sequence
*/
public function defineOrdering(array $sequence)
{
$this->_order = array_flip(array_map('strtolower', $sequence));
}
/**
* 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.
*
* @param array $names
*/
public function setAlwaysDisplayed(array $names)
{
$this->_required = array_flip(array_map('strtolower', $names));
}
/**
* Notify this observer that the entity's charset has changed.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->setCharset($charset);
}
/**
* Returns a string with a representation of all headers.
*
* @return string
*/
public function toString()
{
$string = '';
$headers = $this->_headers;
if ($this->_canSort()) {
uksort($headers, array($this, '_sortHeaders'));
}
foreach ($headers as $collection) {
foreach ($collection as $header) {
if ($this->_isDisplayed($header) || $header->getFieldBody() != '') {
$string .= $header->toString();
}
}
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
// -- Private methods
/** Save a Header to the internal collection */
private function _storeHeader($name, Swift_Mime_Header $header, $offset = null)
{
if (!isset($this->_headers[strtolower($name)])) {
$this->_headers[strtolower($name)] = array();
}
if (!isset($offset)) {
$this->_headers[strtolower($name)][] = $header;
} else {
$this->_headers[strtolower($name)][$offset] = $header;
}
}
/** Test if the headers can be sorted */
private function _canSort()
{
return count($this->_order) > 0;
}
/** uksort() algorithm for Header ordering */
private function _sortHeaders($a, $b)
{
$lowerA = strtolower($a);
$lowerB = strtolower($b);
$aPos = array_key_exists($lowerA, $this->_order)
? $this->_order[$lowerA]
: -1;
$bPos = array_key_exists($lowerB, $this->_order)
? $this->_order[$lowerB]
: -1;
if ($aPos == -1) {
return 1;
} elseif ($bPos == -1) {
return -1;
}
return ($aPos < $bPos) ? -1 : 1;
}
/** Test if the given Header is always displayed */
private function _isDisplayed(Swift_Mime_Header $header)
{
return array_key_exists(strtolower($header->getFieldName()), $this->_required);
}
/** Notify all Headers of the new charset */
private function _notifyHeadersOfCharset($charset)
{
foreach ($this->_headers as $headerGroup) {
foreach ($headerGroup as $header) {
$header->setCharset($charset);
}
}
}
}
Swift-4.2.1/lib/classes/Swift/Mime/SimpleMessage.php 100644 0 0 41311 12000050366 17406 0 ustar 0 0 getHeaders()->defineOrdering(array(
'Return-Path',
'Sender',
'Message-ID',
'Date',
'Subject',
'From',
'Reply-To',
'To',
'Cc',
'Bcc',
'MIME-Version',
'Content-Type',
'Content-Transfer-Encoding'
));
$this->getHeaders()->setAlwaysDisplayed(
array('Date', 'Message-ID', 'From')
);
$this->getHeaders()->addTextHeader('MIME-Version', '1.0');
$this->setDate(time());
$this->setId($this->getId());
$this->getHeaders()->addMailboxHeader('From');
}
/**
* Always returns {@link LEVEL_TOP} for a message instance.
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_TOP;
}
/**
* Set the subject of this message.
* @param string $subject
* @return Swift_Mime_SimpleMessage
*/
public function setSubject($subject)
{
if (!$this->_setHeaderFieldModel('Subject', $subject)) {
$this->getHeaders()->addTextHeader('Subject', $subject);
}
return $this;
}
/**
* Get the subject of this message.
* @return string
*/
public function getSubject()
{
return $this->_getHeaderFieldModel('Subject');
}
/**
* Set the date at which this message was created.
* @param int $date
* @return Swift_Mime_SimpleMessage
*/
public function setDate($date)
{
if (!$this->_setHeaderFieldModel('Date', $date)) {
$this->getHeaders()->addDateHeader('Date', $date);
}
return $this;
}
/**
* Get the date at which this message was created.
* @return int
*/
public function getDate()
{
return $this->_getHeaderFieldModel('Date');
}
/**
* Set the return-path (the bounce address) of this message.
* @param string $address
* @return Swift_Mime_SimpleMessage
*/
public function setReturnPath($address)
{
if (!$this->_setHeaderFieldModel('Return-Path', $address)) {
$this->getHeaders()->addPathHeader('Return-Path', $address);
}
return $this;
}
/**
* Get the return-path (bounce address) of this message.
* @return string
*/
public function getReturnPath()
{
return $this->_getHeaderFieldModel('Return-Path');
}
/**
* Set the sender of this message.
* This does not override the From field, but it has a higher significance.
* @param string $sender
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function setSender($address, $name = null)
{
if (!is_array($address) && isset($name)) {
$address = array($address => $name);
}
if (!$this->_setHeaderFieldModel('Sender', (array) $address)) {
$this->getHeaders()->addMailboxHeader('Sender', (array) $address);
}
return $this;
}
/**
* Get the sender of this message.
* @return string
*/
public function getSender()
{
return $this->_getHeaderFieldModel('Sender');
}
/**
* Add a From: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*/
public function addFrom($address, $name = null)
{
$current = $this->getFrom();
$current[$address] = $name;
return $this->setFrom($current);
}
/**
* Set the from address of this message.
*
* You may pass an array of addresses if this message is from multiple people.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param string $addresses
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function setFrom($addresses, $name = null)
{
if (!is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('From', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('From', (array) $addresses);
}
return $this;
}
/**
* Get the from address of this message.
*
* @return string
*/
public function getFrom()
{
return $this->_getHeaderFieldModel('From');
}
/**
* Add a Reply-To: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function addReplyTo($address, $name = null)
{
$current = $this->getReplyTo();
$current[$address] = $name;
return $this->setReplyTo($current);
}
/**
* Set the reply-to address of this message.
*
* You may pass an array of addresses if replies will go to multiple people.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param string $addresses
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function setReplyTo($addresses, $name = null)
{
if (!is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Reply-To', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses);
}
return $this;
}
/**
* Get the reply-to address of this message.
*
* @return string
*/
public function getReplyTo()
{
return $this->_getHeaderFieldModel('Reply-To');
}
/**
* Add a To: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function addTo($address, $name = null)
{
$current = $this->getTo();
$current[$address] = $name;
return $this->setTo($current);
}
/**
* Set the to addresses of this message.
*
* If multiple recipients will receive the message and array should be used.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param array $addresses
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function setTo($addresses, $name = null)
{
if (!is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('To', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('To', (array) $addresses);
}
return $this;
}
/**
* Get the To addresses of this message.
*
* @return array
*/
public function getTo()
{
return $this->_getHeaderFieldModel('To');
}
/**
* Add a Cc: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function addCc($address, $name = null)
{
$current = $this->getCc();
$current[$address] = $name;
return $this->setCc($current);
}
/**
* Set the Cc addresses of this message.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param array $addresses
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function setCc($addresses, $name = null)
{
if (!is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Cc', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Cc', (array) $addresses);
}
return $this;
}
/**
* Get the Cc address of this message.
*
* @return array
*/
public function getCc()
{
return $this->_getHeaderFieldModel('Cc');
}
/**
* Add a Bcc: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function addBcc($address, $name = null)
{
$current = $this->getBcc();
$current[$address] = $name;
return $this->setBcc($current);
}
/**
* Set the Bcc addresses of this message.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param array $addresses
* @param string $name optional
* @return Swift_Mime_SimpleMessage
*/
public function setBcc($addresses, $name = null)
{
if (!is_array($addresses) && isset($name)) {
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Bcc', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses);
}
return $this;
}
/**
* Get the Bcc addresses of this message.
*
* @return array
*/
public function getBcc()
{
return $this->_getHeaderFieldModel('Bcc');
}
/**
* Set the priority of this message.
* The value is an integer where 1 is the highest priority and 5 is the lowest.
* @param int $priority
* @return Swift_Mime_SimpleMessage
*/
public function setPriority($priority)
{
$priorityMap = array(
1 => 'Highest',
2 => 'High',
3 => 'Normal',
4 => 'Low',
5 => 'Lowest'
);
$pMapKeys = array_keys($priorityMap);
if ($priority > max($pMapKeys)) {
$priority = max($pMapKeys);
} elseif ($priority < min($pMapKeys)) {
$priority = min($pMapKeys);
}
if (!$this->_setHeaderFieldModel('X-Priority',
sprintf('%d (%s)', $priority, $priorityMap[$priority])))
{
$this->getHeaders()->addTextHeader('X-Priority',
sprintf('%d (%s)', $priority, $priorityMap[$priority]));
}
return $this;
}
/**
* Get the priority of this message.
* The returned value is an integer where 1 is the highest priority and 5
* is the lowest.
* @return int
*/
public function getPriority()
{
list($priority) = sscanf($this->_getHeaderFieldModel('X-Priority'),
'%[1-5]'
);
return isset($priority) ? $priority : 3;
}
/**
* Ask for a delivery receipt from the recipient to be sent to $addresses
* @param array $addresses
* @return Swift_Mime_SimpleMessage
*/
public function setReadReceiptTo($addresses)
{
if (!$this->_setHeaderFieldModel('Disposition-Notification-To', $addresses)) {
$this->getHeaders()
->addMailboxHeader('Disposition-Notification-To', $addresses);
}
return $this;
}
/**
* Get the addresses to which a read-receipt will be sent.
* @return string
*/
public function getReadReceiptTo()
{
return $this->_getHeaderFieldModel('Disposition-Notification-To');
}
/**
* Attach a {@link Swift_Mime_MimeEntity} such as an Attachment or MimePart.
* @param Swift_Mime_MimeEntity $entity
* @return Swift_Mime_SimpleMessage
*/
public function attach(Swift_Mime_MimeEntity $entity)
{
$this->setChildren(array_merge($this->getChildren(), array($entity)));
return $this;
}
/**
* Remove an already attached entity.
* @param Swift_Mime_MimeEntity $entity
* @return Swift_Mime_SimpleMessage
*/
public function detach(Swift_Mime_MimeEntity $entity)
{
$newChildren = array();
foreach ($this->getChildren() as $child) {
if ($entity !== $child) {
$newChildren[] = $child;
}
}
$this->setChildren($newChildren);
return $this;
}
/**
* Attach a {@link Swift_Mime_MimeEntity} and return it's CID source.
* This method should be used when embedding images or other data in a message.
* @param Swift_Mime_MimeEntity $entity
* @return string
*/
public function embed(Swift_Mime_MimeEntity $entity)
{
$this->attach($entity);
return 'cid:' . $entity->getId();
}
/**
* Get this message as a complete string.
* @return string
*/
public function toString()
{
if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') {
$this->setChildren(array_merge(array($this->_becomeMimePart()), $children));
$string = parent::toString();
$this->setChildren($children);
} else {
$string = parent::toString();
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
/**
* Write this message to a {@link Swift_InputByteStream}.
* @param Swift_InputByteStream $is
*/
public function toByteStream(Swift_InputByteStream $is)
{
if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') {
$this->setChildren(array_merge(array($this->_becomeMimePart()), $children));
parent::toByteStream($is);
$this->setChildren($children);
} else {
parent::toByteStream($is);
}
}
// -- Protected methods
/** @see Swift_Mime_SimpleMimeEntity::_getIdField() */
protected function _getIdField()
{
return 'Message-ID';
}
// -- Private methods
/** Turn the body of this message into a child of itself if needed */
private function _becomeMimePart()
{
$part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(),
$this->_getCache(), $this->_getGrammar(), $this->_userCharset
);
$part->setContentType($this->_userContentType);
$part->setBody($this->getBody());
$part->setFormat($this->_userFormat);
$part->setDelSp($this->_userDelSp);
$part->_setNestingLevel($this->_getTopNestingLevel());
return $part;
}
/** Get the highest nesting level nested inside this message */
private function _getTopNestingLevel()
{
$highestLevel = $this->getNestingLevel();
foreach ($this->getChildren() as $child) {
$childLevel = $child->getNestingLevel();
if ($highestLevel < $childLevel) {
$highestLevel = $childLevel;
}
}
return $highestLevel;
}
}
Swift-4.2.1/lib/classes/Swift/Mime/SimpleMimeEntity.php 100644 0 0 55265 12000050366 20123 0 ustar 0 0 array(self::LEVEL_TOP, self::LEVEL_MIXED),
'multipart/alternative' => array(self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE),
'multipart/related' => array(self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED)
);
/** A set of filter rules to define what level an entity should be nested at */
private $_compoundLevelFilters = array();
/** The nesting level of this entity */
private $_nestingLevel = self::LEVEL_ALTERNATIVE;
/** A KeyCache instance used during encoding and streaming */
private $_cache;
/** Direct descendants of this entity */
private $_immediateChildren = array();
/** All descendants of this entity */
private $_children = array();
/** The maximum line length of the body of this entity */
private $_maxLineLength = 78;
/** The order in which alternative mime types should appear */
private $_alternativePartOrder = array(
'text/plain' => 1,
'text/html' => 2,
'multipart/related' => 3
);
/** The CID of this entity */
private $_id;
/** The key used for accessing the cache */
private $_cacheKey;
protected $_userContentType;
/**
* Create a new SimpleMimeEntity with $headers, $encoder and $cache.
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_Mime_Grammar $grammar
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar)
{
$this->_cacheKey = uniqid();
$this->_cache = $cache;
$this->_headers = $headers;
$this->_grammar = $grammar;
$this->setEncoder($encoder);
$this->_headers->defineOrdering(
array('Content-Type', 'Content-Transfer-Encoding')
);
// This array specifies that, when the entire MIME document contains
// $compoundLevel, then for each child within $level, if its Content-Type
// is $contentType then it should be treated as if it's level is
// $neededLevel instead. I tried to write that unambiguously! :-\
// Data Structure:
// array (
// $compoundLevel => array(
// $level => array(
// $contentType => $neededLevel
// )
// )
// )
$this->_compoundLevelFilters = array(
(self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array(
self::LEVEL_ALTERNATIVE => array(
'text/plain' => self::LEVEL_ALTERNATIVE,
'text/html' => self::LEVEL_RELATED
)
)
);
$this->_id = $this->getRandomId();
}
/**
* Generate a new Content-ID or Message-ID for this MIME entity.
* @return string
*/
public function generateId()
{
$this->setId($this->getRandomId());
return $this->_id;
}
/**
* Get the {@link Swift_Mime_HeaderSet} for this entity.
* @return Swift_Mime_HeaderSet
*/
public function getHeaders()
{
return $this->_headers;
}
/**
* Get the nesting level of this entity.
* @return int
* @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE
*/
public function getNestingLevel()
{
return $this->_nestingLevel;
}
/**
* Get the Content-type of this entity.
* @return string
*/
public function getContentType()
{
return $this->_getHeaderFieldModel('Content-Type');
}
/**
* Set the Content-type of this entity.
* @param string $type
* @return Swift_Mime_SimpleMimeEntity
*/
public function setContentType($type)
{
$this->_setContentTypeInHeaders($type);
// Keep track of the value so that if the content-type changes automatically
// due to added child entities, it can be restored if they are later removed
$this->_userContentType = $type;
return $this;
}
/**
* Get the CID of this entity.
* The CID will only be present in headers if a Content-ID header is present.
* @return string
*/
public function getId()
{
return $this->_headers->has($this->_getIdField())
? current((array) $this->_getHeaderFieldModel($this->_getIdField()))
: $this->_id;
}
/**
* Set the CID of this entity.
* @param string $id
* @return Swift_Mime_SimpleMimeEntity
*/
public function setId($id)
{
if (!$this->_setHeaderFieldModel($this->_getIdField(), $id)) {
$this->_headers->addIdHeader($this->_getIdField(), $id);
}
$this->_id = $id;
return $this;
}
/**
* Get the description of this entity.
* This value comes from the Content-Description header if set.
* @return string
*/
public function getDescription()
{
return $this->_getHeaderFieldModel('Content-Description');
}
/**
* Set the description of this entity.
* This method sets a value in the Content-ID header.
* @param string $description
* @return Swift_Mime_SimpleMimeEntity
*/
public function setDescription($description)
{
if (!$this->_setHeaderFieldModel('Content-Description', $description)) {
$this->_headers->addTextHeader('Content-Description', $description);
}
return $this;
}
/**
* Get the maximum line length of the body of this entity.
* @return int
*/
public function getMaxLineLength()
{
return $this->_maxLineLength;
}
/**
* Set the maximum line length of lines in this body.
* Though not enforced by the library, lines should not exceed 1000 chars.
* @param int $length
* @return Swift_Mime_SimpleMimeEntity
*/
public function setMaxLineLength($length)
{
$this->_maxLineLength = $length;
return $this;
}
/**
* Get all children added to this entity.
* @return array of Swift_Mime_Entity
*/
public function getChildren()
{
return $this->_children;
}
/**
* Set all children of this entity.
* @param array $children Swiift_Mime_Entity instances
* @param int $compoundLevel For internal use only
* @return Swift_Mime_SimpleMimeEntity
*/
public function setChildren(array $children, $compoundLevel = null)
{
//TODO: Try to refactor this logic
$compoundLevel = isset($compoundLevel)
? $compoundLevel
: $this->_getCompoundLevel($children)
;
$immediateChildren = array();
$grandchildren = array();
$newContentType = $this->_userContentType;
foreach ($children as $child) {
$level = $this->_getNeededChildLevel($child, $compoundLevel);
if (empty($immediateChildren)) { //first iteration
$immediateChildren = array($child);
} else {
$nextLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
if ($nextLevel == $level) {
$immediateChildren[] = $child;
} elseif ($level < $nextLevel) {
//Re-assign immediateChildren to grandchilden
$grandchildren = array_merge($grandchildren, $immediateChildren);
//Set new children
$immediateChildren = array($child);
} else {
$grandchildren[] = $child;
}
}
}
if (!empty($immediateChildren)) {
$lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
//Determine which composite media type is needed to accomodate the
// immediate children
foreach ($this->_compositeRanges as $mediaType => $range) {
if ($lowestLevel > $range[0]
&& $lowestLevel <= $range[1])
{
$newContentType = $mediaType;
break;
}
}
//Put any grandchildren in a subpart
if (!empty($grandchildren)) {
$subentity = $this->_createChild();
$subentity->_setNestingLevel($lowestLevel);
$subentity->setChildren($grandchildren, $compoundLevel);
array_unshift($immediateChildren, $subentity);
}
}
$this->_immediateChildren = $immediateChildren;
$this->_children = $children;
$this->_setContentTypeInHeaders($newContentType);
$this->_fixHeaders();
$this->_sortChildren();
return $this;
}
/**
* Get the body of this entity as a string.
* @return string
*/
public function getBody()
{
return ($this->_body instanceof Swift_OutputByteStream)
? $this->_readStream($this->_body)
: $this->_body;
}
/**
* Set the body of this entity, either as a string, or as an instance of
* {@link Swift_OutputByteStream}.
* @param mixed $body
* @param string $contentType optional
* @return Swift_Mime_SimpleMimeEntity
*/
public function setBody($body, $contentType = null)
{
if ($body !== $this->_body) {
$this->_clearCache();
}
$this->_body = $body;
if (isset($contentType)) {
$this->setContentType($contentType);
}
return $this;
}
/**
* Get the encoder used for the body of this entity.
* @return Swift_Mime_ContentEncoder
*/
public function getEncoder()
{
return $this->_encoder;
}
/**
* Set the encoder used for the body of this entity.
* @param Swift_Mime_ContentEncoder $encoder
* @return Swift_Mime_SimpleMimeEntity
*/
public function setEncoder(Swift_Mime_ContentEncoder $encoder)
{
if ($encoder !== $this->_encoder) {
$this->_clearCache();
}
$this->_encoder = $encoder;
$this->_setEncoding($encoder->getName());
$this->_notifyEncoderChanged($encoder);
return $this;
}
/**
* Get the boundary used to separate children in this entity.
* @return string
*/
public function getBoundary()
{
if (!isset($this->_boundary)) {
$this->_boundary = '_=_swift_v4_' . time() . uniqid() . '_=_';
}
return $this->_boundary;
}
/**
* Set the boundary used to separate children in this entity.
* @param string $boundary
* @throws Swift_RfcComplianceException
* @return Swift_Mime_SimpleMimeEntity
*/
public function setBoundary($boundary)
{
$this->_assertValidBoundary($boundary);
$this->_boundary = $boundary;
return $this;
}
/**
* Receive notification that the charset of this entity, or a parent entity
* has changed.
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->_notifyCharsetChanged($charset);
}
/**
* Receive notification that the encoder of this entity or a parent entity
* has changed.
* @param Swift_Mime_ContentEncoder $encoder
*/
public function encoderChanged(Swift_Mime_ContentEncoder $encoder)
{
$this->_notifyEncoderChanged($encoder);
}
/**
* Get this entire entity as a string.
* @return string
*/
public function toString()
{
$string = $this->_headers->toString();
if (isset($this->_body) && empty($this->_immediateChildren)) {
if ($this->_cache->hasKey($this->_cacheKey, 'body')) {
$body = $this->_cache->getString($this->_cacheKey, 'body');
} else {
$body = "\r\n" . $this->_encoder->encodeString($this->getBody(), 0,
$this->getMaxLineLength()
);
$this->_cache->setString($this->_cacheKey, 'body', $body,
Swift_KeyCache::MODE_WRITE
);
}
$string .= $body;
}
if (!empty($this->_immediateChildren)) {
foreach ($this->_immediateChildren as $child) {
$string .= "\r\n\r\n--" . $this->getBoundary() . "\r\n";
$string .= $child->toString();
}
$string .= "\r\n\r\n--" . $this->getBoundary() . "--\r\n";
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
/**
* Write this entire entity to a {@link Swift_InputByteStream}.
* @param Swift_InputByteStream
*/
public function toByteStream(Swift_InputByteStream $is)
{
$is->write($this->_headers->toString());
$is->commit();
if (empty($this->_immediateChildren)) {
if (isset($this->_body)) {
if ($this->_cache->hasKey($this->_cacheKey, 'body')) {
$this->_cache->exportToByteStream($this->_cacheKey, 'body', $is);
} else {
$cacheIs = $this->_cache->getInputByteStream($this->_cacheKey, 'body');
if ($cacheIs) {
$is->bind($cacheIs);
}
$is->write("\r\n");
if ($this->_body instanceof Swift_OutputByteStream) {
$this->_body->setReadPointer(0);
$this->_encoder->encodeByteStream($this->_body, $is, 0,
$this->getMaxLineLength()
);
} else {
$is->write($this->_encoder->encodeString(
$this->getBody(), 0, $this->getMaxLineLength()
));
}
if ($cacheIs) {
$is->unbind($cacheIs);
}
}
}
}
if (!empty($this->_immediateChildren)) {
foreach ($this->_immediateChildren as $child) {
$is->write("\r\n\r\n--" . $this->getBoundary() . "\r\n");
$child->toByteStream($is);
}
$is->write("\r\n\r\n--" . $this->getBoundary() . "--\r\n");
}
}
// -- Protected methods
/**
* Get the name of the header that provides the ID of this entity */
protected function _getIdField()
{
return 'Content-ID';
}
/**
* Get the model data (usually an array or a string) for $field.
*/
protected function _getHeaderFieldModel($field)
{
if ($this->_headers->has($field)) {
return $this->_headers->get($field)->getFieldBodyModel();
}
}
/**
* Set the model data for $field.
*/
protected function _setHeaderFieldModel($field, $model)
{
if ($this->_headers->has($field)) {
$this->_headers->get($field)->setFieldBodyModel($model);
return true;
} else {
return false;
}
}
/**
* Get the parameter value of $parameter on $field header.
*/
protected function _getHeaderParameter($field, $parameter)
{
if ($this->_headers->has($field)) {
return $this->_headers->get($field)->getParameter($parameter);
}
}
/**
* Set the parameter value of $parameter on $field header.
*/
protected function _setHeaderParameter($field, $parameter, $value)
{
if ($this->_headers->has($field)) {
$this->_headers->get($field)->setParameter($parameter, $value);
return true;
} else {
return false;
}
}
/**
* Re-evaluate what content type and encoding should be used on this entity.
*/
protected function _fixHeaders()
{
if (count($this->_immediateChildren)) {
$this->_setHeaderParameter('Content-Type', 'boundary',
$this->getBoundary()
);
$this->_headers->remove('Content-Transfer-Encoding');
} else {
$this->_setHeaderParameter('Content-Type', 'boundary', null);
$this->_setEncoding($this->_encoder->getName());
}
}
/**
* Get the KeyCache used in this entity.
*/
protected function _getCache()
{
return $this->_cache;
}
/**
* Get the grammar used for validation.
* @return Swift_Mime_Grammar
*/
protected function _getGrammar()
{
return $this->_grammar;
}
/**
* Empty the KeyCache for this entity.
*/
protected function _clearCache()
{
$this->_cache->clearKey($this->_cacheKey, 'body');
}
/**
* Returns a random Content-ID or Message-ID.
* @return string
*/
protected function getRandomId()
{
$idLeft = time() . '.' . uniqid();
$idRight = !empty($_SERVER['SERVER_NAME'])
? $_SERVER['SERVER_NAME']
: 'swift.generated';
$id = $idLeft . '@' . $idRight;
try {
$this->_assertValidId($id);
} catch (Swift_RfcComplianceException $e) {
$id = $idLeft . '@swift.generated';
}
return $id;
}
// -- Private methods
private function _readStream(Swift_OutputByteStream $os)
{
$string = '';
while (false !== $bytes = $os->read(8192)) {
$string .= $bytes;
}
return $string;
}
private function _setEncoding($encoding)
{
if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) {
$this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding);
}
}
private function _assertValidBoundary($boundary)
{
if (!preg_match(
'/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di',
$boundary))
{
throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.');
}
}
private function _setContentTypeInHeaders($type)
{
if (!$this->_setHeaderFieldModel('Content-Type', $type)) {
$this->_headers->addParameterizedHeader('Content-Type', $type);
}
}
private function _setNestingLevel($level)
{
$this->_nestingLevel = $level;
}
private function _getCompoundLevel($children)
{
$level = 0;
foreach ($children as $child) {
$level |= $child->getNestingLevel();
}
return $level;
}
private function _getNeededChildLevel($child, $compoundLevel)
{
$filter = array();
foreach ($this->_compoundLevelFilters as $bitmask => $rules) {
if (($compoundLevel & $bitmask) === $bitmask) {
$filter = $rules + $filter;
}
}
$realLevel = $child->getNestingLevel();
$lowercaseType = strtolower($child->getContentType());
if (isset($filter[$realLevel])
&& isset($filter[$realLevel][$lowercaseType]))
{
return $filter[$realLevel][$lowercaseType];
} else {
return $realLevel;
}
}
private function _createChild()
{
return new self($this->_headers->newInstance(),
$this->_encoder, $this->_cache, $this->_grammar);
}
private function _notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder)
{
foreach ($this->_immediateChildren as $child) {
$child->encoderChanged($encoder);
}
}
private function _notifyCharsetChanged($charset)
{
$this->_encoder->charsetChanged($charset);
$this->_headers->charsetChanged($charset);
foreach ($this->_immediateChildren as $child) {
$child->charsetChanged($charset);
}
}
private function _sortChildren()
{
$shouldSort = false;
foreach ($this->_immediateChildren as $child) {
//NOTE: This include alternative parts moved into a related part
if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE) {
$shouldSort = true;
break;
}
}
//Sort in order of preference, if there is one
if ($shouldSort) {
usort($this->_immediateChildren, array($this, '_childSortAlgorithm'));
}
}
private function _childSortAlgorithm($a, $b)
{
$typePrefs = array();
$types = array(
strtolower($a->getContentType()),
strtolower($b->getContentType())
);
foreach ($types as $type) {
$typePrefs[] = (array_key_exists($type, $this->_alternativePartOrder))
? $this->_alternativePartOrder[$type]
: (max($this->_alternativePartOrder) + 1);
}
return ($typePrefs[0] >= $typePrefs[1]) ? 1 : -1;
}
// -- Destructor
/**
* Empties it's own contents from the cache.
*/
public function __destruct()
{
$this->_cache->clearAll($this->_cacheKey);
}
/**
* Throws an Exception if the id passed does not comply with RFC 2822.
* @param string $id
* @throws Swift_RfcComplianceException
*/
private function _assertValidId($id)
{
if (!preg_match(
'/^' . $this->_grammar->getDefinition('id-left') . '@' .
$this->_grammar->getDefinition('id-right') . '$/D',
$id
))
{
throw new Swift_RfcComplianceException(
'Invalid ID given <' . $id . '>'
);
}
}
}
Swift-4.2.1/lib/classes/Swift/MimePart.php 100644 0 0 3037 12000050366 15462 0 ustar 0 0 createDependenciesFor('mime.part')
);
if (!isset($charset)) {
$charset = Swift_DependencyContainer::getInstance()
->lookup('properties.charset');
}
$this->setBody($body);
$this->setCharset($charset);
if ($contentType) {
$this->setContentType($contentType);
}
}
/**
* Create a new MimePart.
* @param string $body
* @param string $contentType
* @param string $charset
* @return Swift_Mime_MimePart
*/
public static function newInstance($body = null, $contentType = null, $charset = null)
{
return new self($body, $contentType, $charset);
}
}
Swift-4.2.1/lib/classes/Swift/NullTransport.php 100644 0 0 1630 12000050366 16570 0 ustar 0 0
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Pretends messages have been sent, but just ignores them.
* @package Swift
* @author Fabien Potencier
*/
class Swift_NullTransport extends Swift_Transport_NullTransport
{
/**
* Create a new NullTransport.
*/
public function __construct()
{
call_user_func_array(
array($this, 'Swift_Transport_NullTransport::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('transport.null')
);
}
/**
* Create a new NullTransport instance.
* @return Swift_NullTransport
*/
public static function newInstance()
{
return new self();
}
}
Swift-4.2.1/lib/classes/Swift/OutputByteStream.php 100644 0 0 2171 12000050366 17242 0 ustar 0 0 setThreshold($threshold);
$this->setSleepTime($sleep);
$this->_sleeper = $sleeper;
}
/**
* Set the number of emails to send before restarting.
* @param int $threshold
*/
public function setThreshold($threshold)
{
$this->_threshold = $threshold;
}
/**
* Get the number of emails to send before restarting.
* @return int
*/
public function getThreshold()
{
return $this->_threshold;
}
/**
* Set the number of seconds to sleep for during a restart.
* @param int $sleep time
*/
public function setSleepTime($sleep)
{
$this->_sleep = $sleep;
}
/**
* Get the number of seconds to sleep for during a restart.
* @return int
*/
public function getSleepTime()
{
return $this->_sleep;
}
/**
* Invoked immediately before the Message is sent.
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(Swift_Events_SendEvent $evt)
{
}
/**
* Invoked immediately after the Message is sent.
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
{
++$this->_counter;
if ($this->_counter >= $this->_threshold) {
$transport = $evt->getTransport();
$transport->stop();
if ($this->_sleep) {
$this->sleep($this->_sleep);
}
$transport->start();
$this->_counter = 0;
}
}
/**
* Sleep for $seconds.
* @param int $seconds
*/
public function sleep($seconds)
{
if (isset($this->_sleeper)) {
$this->_sleeper->sleep($seconds);
} else {
sleep($seconds);
}
}
}
Swift-4.2.1/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php 100644 0 0 7076 12000050366 22027 0 ustar 0 0 getMessage();
$message->toByteStream($this);
}
/**
* Invoked immediately following a command being sent.
* @param Swift_Events_ResponseEvent $evt
*/
public function commandSent(Swift_Events_CommandEvent $evt)
{
$command = $evt->getCommand();
$this->_out += strlen($command);
}
/**
* Invoked immediately following a response coming back.
* @param Swift_Events_ResponseEvent $evt
*/
public function responseReceived(Swift_Events_ResponseEvent $evt)
{
$response = $evt->getResponse();
$this->_in += strlen($response);
}
/**
* Called when a message is sent so that the outgoing counter can be increased.
* @param string $bytes
*/
public function write($bytes)
{
$this->_out += strlen($bytes);
foreach ($this->_mirrors as $stream) {
$stream->write($bytes);
}
}
/**
* Not used.
*/
public function commit()
{
}
/**
* Attach $is to this stream.
* The stream acts as an observer, receiving all data that is written.
* All {@link write()} and {@link flushBuffers()} operations will be mirrored.
*
* @param Swift_InputByteStream $is
*/
public function bind(Swift_InputByteStream $is)
{
$this->_mirrors[] = $is;
}
/**
* Remove an already bound stream.
* If $is is not bound, no errors will be raised.
* If the stream currently has any buffered data it will be written to $is
* before unbinding occurs.
*
* @param Swift_InputByteStream $is
*/
public function unbind(Swift_InputByteStream $is)
{
foreach ($this->_mirrors as $k => $stream) {
if ($is === $stream) {
unset($this->_mirrors[$k]);
}
}
}
/**
* Not used.
*/
public function flushBuffers()
{
foreach ($this->_mirrors as $stream) {
$stream->flushBuffers();
}
}
/**
* Get the total number of bytes sent to the server.
* @return int
*/
public function getBytesOut()
{
return $this->_out;
}
/**
* Get the total number of bytes received from the server.
* @return int
*/
public function getBytesIn()
{
return $this->_in;
}
/**
* Reset the internal counters to zero.
*/
public function reset()
{
$this->_out = 0;
$this->_in = 0;
}
}
Swift-4.2.1/lib/classes/Swift/Plugins/Decorator/Replacements.php 100644 0 0 1447 12000050366 21734 0 ustar 0 0
* $replacements = array(
* "address1@domain.tld" => array("{a}" => "b", "{c}" => "d"),
* "address2@domain.tld" => array("{a}" => "x", "{c}" => "y")
* )
*
*
* When using an instance of {@link Swift_Plugins_Decorator_Replacements},
* the object should return just the array of replacements for the address
* given to {@link Swift_Plugins_Decorator_Replacements::getReplacementsFor()}.
*
* @param mixed $replacements Array or Swift_Plugins_Decorator_Replacements
*/
public function __construct($replacements)
{
$this->setReplacements($replacements);
}
/**
* Sets replacements.
*
* @param mixed $replacements Array or Swift_Plugins_Decorator_Replacements
*
* @see __construct()
*/
public function setReplacements($replacements)
{
if (!($replacements instanceof \Swift_Plugins_Decorator_Replacements)) {
$this->_replacements = (array) $replacements;
} else {
$this->_replacements = $replacements;
}
}
/**
* Invoked immediately before the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(Swift_Events_SendEvent $evt)
{
$message = $evt->getMessage();
$this->_restoreMessage($message);
$to = array_keys($message->getTo());
$address = array_shift($to);
if ($replacements = $this->getReplacementsFor($address)) {
$body = $message->getBody();
$search = array_keys($replacements);
$replace = array_values($replacements);
$bodyReplaced = str_replace(
$search, $replace, $body
);
if ($body != $bodyReplaced) {
$this->_originalBody = $body;
$message->setBody($bodyReplaced);
}
foreach ($message->getHeaders()->getAll() as $header) {
$body = $header->getFieldBodyModel();
$count = 0;
if (is_array($body)) {
$bodyReplaced = array();
foreach ($body as $key => $value) {
$count1 = 0;
$count2 = 0;
$key = is_string($key) ? str_replace($search, $replace, $key, $count1) : $key;
$value = is_string($value) ? str_replace($search, $replace, $value, $count2) : $value;
$bodyReplaced[$key] = $value;
if (!$count && ($count1 || $count2)) {
$count = 1;
}
}
} else {
$bodyReplaced = str_replace($search, $replace, $body, $count);
}
if ($count) {
$this->_originalHeaders[$header->getFieldName()] = $body;
$header->setFieldBodyModel($bodyReplaced);
}
}
$children = (array) $message->getChildren();
foreach ($children as $child) {
list($type, ) = sscanf($child->getContentType(), '%[^/]/%s');
if ('text' == $type) {
$body = $child->getBody();
$bodyReplaced = str_replace(
$search, $replace, $body
);
if ($body != $bodyReplaced) {
$child->setBody($bodyReplaced);
$this->_originalChildBodies[$child->getId()] = $body;
}
}
}
$this->_lastMessage = $message;
}
}
/**
* Find a map of replacements for the address.
*
* If this plugin was provided with a delegate instance of
* {@link Swift_Plugins_Decorator_Replacements} then the call will be
* delegated to it. Otherwise, it will attempt to find the replacements
* from the array provided in the constructor.
*
* If no replacements can be found, an empty value (NULL) is returned.
*
* @param string $address
*
* @return array
*/
public function getReplacementsFor($address)
{
if ($this->_replacements instanceof Swift_Plugins_Decorator_Replacements) {
return $this->_replacements->getReplacementsFor($address);
} else {
return isset($this->_replacements[$address])
? $this->_replacements[$address]
: null
;
}
}
/**
* Invoked immediately after the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
{
$this->_restoreMessage($evt->getMessage());
}
// -- Private methods
/** Restore a changed message back to its original state */
private function _restoreMessage(Swift_Mime_Message $message)
{
if ($this->_lastMessage === $message) {
if (isset($this->_originalBody)) {
$message->setBody($this->_originalBody);
$this->_originalBody = null;
}
if (!empty($this->_originalHeaders)) {
foreach ($message->getHeaders()->getAll() as $header) {
if (array_key_exists($header->getFieldName(), $this->_originalHeaders)) {
$header->setFieldBodyModel($this->_originalHeaders[$header->getFieldName()]);
}
}
$this->_originalHeaders = array();
}
if (!empty($this->_originalChildBodies)) {
$children = (array) $message->getChildren();
foreach ($children as $child) {
$id = $child->getId();
if (array_key_exists($id, $this->_originalChildBodies)) {
$child->setBody($this->_originalChildBodies[$id]);
}
}
$this->_originalChildBodies = array();
}
$this->_lastMessage = null;
}
}
}
Swift-4.2.1/lib/classes/Swift/Plugins/ImpersonatePlugin.php 100644 0 0 3345 12000050366 21034 0 ustar 0 0 _sender = $sender;
}
/**
* Invoked immediately before the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(Swift_Events_SendEvent $evt)
{
$message = $evt->getMessage();
$headers = $message->getHeaders();
// save current recipients
$headers->addPathHeader('X-Swift-Return-Path', $message->getReturnPath());
// replace them with the one to send to
$message->setReturnPath($this->_sender);
}
/**
* Invoked immediately after the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
{
$message = $evt->getMessage();
// restore original headers
$headers = $message->getHeaders();
if ($headers->has('X-Swift-Return-Path')) {
$message->setReturnPath($headers->get('X-Swift-Return-Path')->getAddress());
$headers->removeAll('X-Swift-Return-Path');
}
}
}
Swift-4.2.1/lib/classes/Swift/Plugins/Logger.php 100644 0 0 1200 12000050366 16572 0 ustar 0 0 _logger = $logger;
}
/**
* Add a log entry.
*
* @param string $entry
*/
public function add($entry)
{
$this->_logger->add($entry);
}
/**
* Clear the log contents.
*/
public function clear()
{
$this->_logger->clear();
}
/**
* Get this log as a string.
*
* @return string
*/
public function dump()
{
return $this->_logger->dump();
}
/**
* Invoked immediately following a command being sent.
*
* @param Swift_Events_ResponseEvent $evt
*/
public function commandSent(Swift_Events_CommandEvent $evt)
{
$command = $evt->getCommand();
$this->_logger->add(sprintf(">> %s", $command));
}
/**
* Invoked immediately following a response coming back.
*
* @param Swift_Events_ResponseEvent $evt
*/
public function responseReceived(Swift_Events_ResponseEvent $evt)
{
$response = $evt->getResponse();
$this->_logger->add(sprintf("<< %s", $response));
}
/**
* Invoked just before a Transport is started.
*
* @param Swift_Events_TransportChangeEvent $evt
*/
public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt)
{
$transportName = get_class($evt->getSource());
$this->_logger->add(sprintf("++ Starting %s", $transportName));
}
/**
* Invoked immediately after the Transport is started.
*
* @param Swift_Events_TransportChangeEvent $evt
*/
public function transportStarted(Swift_Events_TransportChangeEvent $evt)
{
$transportName = get_class($evt->getSource());
$this->_logger->add(sprintf("++ %s started", $transportName));
}
/**
* Invoked just before a Transport is stopped.
*
* @param Swift_Events_TransportChangeEvent $evt
*/
public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt)
{
$transportName = get_class($evt->getSource());
$this->_logger->add(sprintf("++ Stopping %s", $transportName));
}
/**
* Invoked immediately after the Transport is stopped.
*
* @param Swift_Events_TransportChangeEvent $evt
*/
public function transportStopped(Swift_Events_TransportChangeEvent $evt)
{
$transportName = get_class($evt->getSource());
$this->_logger->add(sprintf("++ %s stopped", $transportName));
}
/**
* Invoked as a TransportException is thrown in the Transport system.
*
* @param Swift_Events_TransportExceptionEvent $evt
*/
public function exceptionThrown(Swift_Events_TransportExceptionEvent $evt)
{
$e = $evt->getException();
$message = $e->getMessage();
$this->_logger->add(sprintf("!! %s", $message));
$message .= PHP_EOL;
$message .= 'Log data:' . PHP_EOL;
$message .= $this->_logger->dump();
$evt->cancelBubble();
throw new Swift_TransportException($message);
}
}
Swift-4.2.1/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php 100644 0 0 2452 12000050366 21205 0 ustar 0 0 _size = $size;
}
/**
* Add a log entry.
* @param string $entry
*/
public function add($entry)
{
$this->_log[] = $entry;
while (count($this->_log) > $this->_size) {
array_shift($this->_log);
}
}
/**
* Clear the log contents.
*/
public function clear()
{
$this->_log = array();
}
/**
* Get this log as a string.
* @return string
*/
public function dump()
{
return implode(PHP_EOL, $this->_log);
}
}
Swift-4.2.1/lib/classes/Swift/Plugins/Loggers/EchoLogger.php 100644 0 0 2137 12000050366 21005 0 ustar 0 0 _isHtml = $isHtml;
}
/**
* Add a log entry.
* @param string $entry
*/
public function add($entry)
{
if ($this->_isHtml) {
printf('%s%s%s', htmlspecialchars($entry, ENT_QUOTES), 'The following is the approximate plan for the next full point release.
Before each release we hope to have the following done. More may get done, depending on the interest of the volunteers, but this is the current minimum.
The aim of this release cycle is to produce a functionally identical version to the 1.0.1 release, but bug-fixed and fully compatible with PHP 5.0.5+ under E_STRICT. We are also hoping to flush out issues and use cases caused by people hacking against unpublished flex points in SimpleTest. We want to break people's code now, not while we are developing features down the line.
With the website move to a new server, and more developers, we are able and need to improve the test automation and developer cooperation. This release is a deep drawing of breath before going forward.
' . $this->htmlEntities($message) . ''; } /** * Character set adjusted entity conversion. * @param string $message Plain text or Unicode message. * @return string Browser readable message. * @access protected */ protected function htmlEntities($message) { return htmlentities($message, ENT_COMPAT, $this->character_set); } } /** * Sample minimal test displayer. Generates only * failure messages and a pass count. For command * line use. I've tried to make it look like JUnit, * but I wanted to output the errors as they arrived * which meant dropping the dots. * @package SimpleTest * @subpackage UnitTester */ class TextReporter extends SimpleReporter { /** * Does nothing yet. The first output will * be sent on the first test start. * @access public */ function __construct() { parent::__construct(); } /** * Paints the title only. * @param string $test_name Name class of test. * @access public */ function paintHeader($test_name) { if (! SimpleReporter::inCli()) { header('Content-type: text/plain'); } print "$test_name\n"; flush(); } /** * Paints the end of the test with a summary of * the passes and failures. * @param string $test_name Name class of test. * @access public */ function paintFooter($test_name) { if ($this->getFailCount() + $this->getExceptionCount() == 0) { print "OK\n"; } else { print "FAILURES!!!\n"; } print "Test cases run: " . $this->getTestCaseProgress() . "/" . $this->getTestCaseCount() . ", Passes: " . $this->getPassCount() . ", Failures: " . $this->getFailCount() . ", Exceptions: " . $this->getExceptionCount() . "\n"; } /** * Paints the test failure as a stack trace. * @param string $message Failure message displayed in * the context of the other tests. * @access public */ function paintFail($message) { parent::paintFail($message); print $this->getFailCount() . ") $message\n"; $breadcrumb = $this->getTestList(); array_shift($breadcrumb); print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); print "\n"; } /** * Paints a PHP error or exception. * @param string $message Message to be shown. * @access public * @abstract */ function paintError($message) { parent::paintError($message); print "Exception " . $this->getExceptionCount() . "!\n$message\n"; $breadcrumb = $this->getTestList(); array_shift($breadcrumb); print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); print "\n"; } /** * Paints a PHP error or exception. * @param Exception $exception Exception to describe. * @access public * @abstract */ function paintException($exception) { parent::paintException($exception); $message = 'Unexpected exception of type [' . get_class($exception) . '] with message ['. $exception->getMessage() . '] in ['. $exception->getFile() . ' line ' . $exception->getLine() . ']'; print "Exception " . $this->getExceptionCount() . "!\n$message\n"; $breadcrumb = $this->getTestList(); array_shift($breadcrumb); print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); print "\n"; } /** * Prints the message for skipping tests. * @param string $message Text of skip condition. * @access public */ function paintSkip($message) { parent::paintSkip($message); print "Skip: $message\n"; } /** * Paints formatted text such as dumped privateiables. * @param string $message Text to show. * @access public */ function paintFormattedMessage($message) { print "$message\n"; flush(); } } /** * Runs just a single test group, a single case or * even a single test within that case. * @package SimpleTest * @subpackage UnitTester */ class SelectiveReporter extends SimpleReporterDecorator { private $just_this_case = false; private $just_this_test = false; private $on; /** * Selects the test case or group to be run, * and optionally a specific test. * @param SimpleScorer $reporter Reporter to receive events. * @param string $just_this_case Only this case or group will run. * @param string $just_this_test Only this test method will run. */ function __construct($reporter, $just_this_case = false, $just_this_test = false) { if (isset($just_this_case) && $just_this_case) { $this->just_this_case = strtolower($just_this_case); $this->off(); } else { $this->on(); } if (isset($just_this_test) && $just_this_test) { $this->just_this_test = strtolower($just_this_test); } parent::__construct($reporter); } /** * Compares criteria to actual the case/group name. * @param string $test_case The incoming test. * @return boolean True if matched. * @access protected */ protected function matchesTestCase($test_case) { return $this->just_this_case == strtolower($test_case); } /** * Compares criteria to actual the test name. If no * name was specified at the beginning, then all tests * can run. * @param string $method The incoming test method. * @return boolean True if matched. * @access protected */ protected function shouldRunTest($test_case, $method) { if ($this->isOn() || $this->matchesTestCase($test_case)) { if ($this->just_this_test) { return $this->just_this_test == strtolower($method); } else { return true; } } return false; } /** * Switch on testing for the group or subgroup. * @access private */ protected function on() { $this->on = true; } /** * Switch off testing for the group or subgroup. * @access private */ protected function off() { $this->on = false; } /** * Is this group actually being tested? * @return boolean True if the current test group is active. * @access private */ protected function isOn() { return $this->on; } /** * Veto everything that doesn't match the method wanted. * @param string $test_case Name of test case. * @param string $method Name of test method. * @return boolean True if test should be run. * @access public */ function shouldInvoke($test_case, $method) { if ($this->shouldRunTest($test_case, $method)) { return $this->reporter->shouldInvoke($test_case, $method); } return false; } /** * Paints the start of a group test. * @param string $test_case Name of test or other label. * @param integer $size Number of test cases starting. * @access public */ function paintGroupStart($test_case, $size) { if ($this->just_this_case && $this->matchesTestCase($test_case)) { $this->on(); } $this->reporter->paintGroupStart($test_case, $size); } /** * Paints the end of a group test. * @param string $test_case Name of test or other label. * @access public */ function paintGroupEnd($test_case) { $this->reporter->paintGroupEnd($test_case); if ($this->just_this_case && $this->matchesTestCase($test_case)) { $this->off(); } } } /** * Suppresses skip messages. * @package SimpleTest * @subpackage UnitTester */ class NoSkipsReporter extends SimpleReporterDecorator { /** * Does nothing. * @param string $message Text of skip condition. * @access public */ function paintSkip($message) { } } ?> Swift-4.2.1/test-suite/lib/simpletest/scorer.php 100644 0 0 57712 12000050366 17040 0 ustar 0 0 passes = 0; $this->fails = 0; $this->exceptions = 0; $this->is_dry_run = false; } /** * Signals that the next evaluation will be a dry * run. That is, the structure events will be * recorded, but no tests will be run. * @param boolean $is_dry Dry run if true. * @access public */ function makeDry($is_dry = true) { $this->is_dry_run = $is_dry; } /** * The reporter has a veto on what should be run. * @param string $test_case_name name of test case. * @param string $method Name of test method. * @access public */ function shouldInvoke($test_case_name, $method) { return ! $this->is_dry_run; } /** * Can wrap the invoker in preperation for running * a test. * @param SimpleInvoker $invoker Individual test runner. * @return SimpleInvoker Wrapped test runner. * @access public */ function createInvoker($invoker) { return $invoker; } /** * Accessor for current status. Will be false * if there have been any failures or exceptions. * Used for command line tools. * @return boolean True if no failures. * @access public */ function getStatus() { if ($this->exceptions + $this->fails > 0) { return false; } return true; } /** * Paints the start of a group test. * @param string $test_name Name of test or other label. * @param integer $size Number of test cases starting. * @access public */ function paintGroupStart($test_name, $size) { } /** * Paints the end of a group test. * @param string $test_name Name of test or other label. * @access public */ function paintGroupEnd($test_name) { } /** * Paints the start of a test case. * @param string $test_name Name of test or other label. * @access public */ function paintCaseStart($test_name) { } /** * Paints the end of a test case. * @param string $test_name Name of test or other label. * @access public */ function paintCaseEnd($test_name) { } /** * Paints the start of a test method. * @param string $test_name Name of test or other label. * @access public */ function paintMethodStart($test_name) { } /** * Paints the end of a test method. * @param string $test_name Name of test or other label. * @access public */ function paintMethodEnd($test_name) { } /** * Increments the pass count. * @param string $message Message is ignored. * @access public */ function paintPass($message) { $this->passes++; } /** * Increments the fail count. * @param string $message Message is ignored. * @access public */ function paintFail($message) { $this->fails++; } /** * Deals with PHP 4 throwing an error. * @param string $message Text of error formatted by * the test case. * @access public */ function paintError($message) { $this->exceptions++; } /** * Deals with PHP 5 throwing an exception. * @param Exception $exception The actual exception thrown. * @access public */ function paintException($exception) { $this->exceptions++; } /** * Prints the message for skipping tests. * @param string $message Text of skip condition. * @access public */ function paintSkip($message) { } /** * Accessor for the number of passes so far. * @return integer Number of passes. * @access public */ function getPassCount() { return $this->passes; } /** * Accessor for the number of fails so far. * @return integer Number of fails. * @access public */ function getFailCount() { return $this->fails; } /** * Accessor for the number of untrapped errors * so far. * @return integer Number of exceptions. * @access public */ function getExceptionCount() { return $this->exceptions; } /** * Paints a simple supplementary message. * @param string $message Text to display. * @access public */ function paintMessage($message) { } /** * Paints a formatted ASCII message such as a * privateiable dump. * @param string $message Text to display. * @access public */ function paintFormattedMessage($message) { } /** * By default just ignores user generated events. * @param string $type Event type as text. * @param mixed $payload Message or object. * @access public */ function paintSignal($type, $payload) { } } /** * Recipient of generated test messages that can display * page footers and headers. Also keeps track of the * test nesting. This is the main base class on which * to build the finished test (page based) displays. * @package SimpleTest * @subpackage UnitTester */ class SimpleReporter extends SimpleScorer { private $test_stack; private $size; private $progress; /** * Starts the display with no results in. * @access public */ function __construct() { parent::__construct(); $this->test_stack = array(); $this->size = null; $this->progress = 0; } /** * Gets the formatter for privateiables and other small * generic data items. * @return SimpleDumper Formatter. * @access public */ function getDumper() { return new SimpleDumper(); } /** * Paints the start of a group test. Will also paint * the page header and footer if this is the * first test. Will stash the size if the first * start. * @param string $test_name Name of test that is starting. * @param integer $size Number of test cases starting. * @access public */ function paintGroupStart($test_name, $size) { if (! isset($this->size)) { $this->size = $size; } if (count($this->test_stack) == 0) { $this->paintHeader($test_name); } $this->test_stack[] = $test_name; } /** * Paints the end of a group test. Will paint the page * footer if the stack of tests has unwound. * @param string $test_name Name of test that is ending. * @param integer $progress Number of test cases ending. * @access public */ function paintGroupEnd($test_name) { array_pop($this->test_stack); if (count($this->test_stack) == 0) { $this->paintFooter($test_name); } } /** * Paints the start of a test case. Will also paint * the page header and footer if this is the * first test. Will stash the size if the first * start. * @param string $test_name Name of test that is starting. * @access public */ function paintCaseStart($test_name) { if (! isset($this->size)) { $this->size = 1; } if (count($this->test_stack) == 0) { $this->paintHeader($test_name); } $this->test_stack[] = $test_name; } /** * Paints the end of a test case. Will paint the page * footer if the stack of tests has unwound. * @param string $test_name Name of test that is ending. * @access public */ function paintCaseEnd($test_name) { $this->progress++; array_pop($this->test_stack); if (count($this->test_stack) == 0) { $this->paintFooter($test_name); } } /** * Paints the start of a test method. * @param string $test_name Name of test that is starting. * @access public */ function paintMethodStart($test_name) { $this->test_stack[] = $test_name; } /** * Paints the end of a test method. Will paint the page * footer if the stack of tests has unwound. * @param string $test_name Name of test that is ending. * @access public */ function paintMethodEnd($test_name) { array_pop($this->test_stack); } /** * Paints the test document header. * @param string $test_name First test top level * to start. * @access public * @abstract */ function paintHeader($test_name) { } /** * Paints the test document footer. * @param string $test_name The top level test. * @access public * @abstract */ function paintFooter($test_name) { } /** * Accessor for internal test stack. For * subclasses that need to see the whole test * history for display purposes. * @return array List of methods in nesting order. * @access public */ function getTestList() { return $this->test_stack; } /** * Accessor for total test size in number * of test cases. Null until the first * test is started. * @return integer Total number of cases at start. * @access public */ function getTestCaseCount() { return $this->size; } /** * Accessor for the number of test cases * completed so far. * @return integer Number of ended cases. * @access public */ function getTestCaseProgress() { return $this->progress; } /** * Static check for running in the comand line. * @return boolean True if CLI. * @access public */ static function inCli() { return php_sapi_name() == 'cli'; } } /** * For modifying the behaviour of the visual reporters. * @package SimpleTest * @subpackage UnitTester */ class SimpleReporterDecorator { protected $reporter; /** * Mediates between the reporter and the test case. * @param SimpleScorer $reporter Reporter to receive events. */ function __construct($reporter) { $this->reporter = $reporter; } /** * Signals that the next evaluation will be a dry * run. That is, the structure events will be * recorded, but no tests will be run. * @param boolean $is_dry Dry run if true. * @access public */ function makeDry($is_dry = true) { $this->reporter->makeDry($is_dry); } /** * Accessor for current status. Will be false * if there have been any failures or exceptions. * Used for command line tools. * @return boolean True if no failures. * @access public */ function getStatus() { return $this->reporter->getStatus(); } /** * The reporter has a veto on what should be run. * @param string $test_case_name name of test case. * @param string $method Name of test method. * @return boolean True if test should be run. * @access public */ function shouldInvoke($test_case_name, $method) { return $this->reporter->shouldInvoke($test_case_name, $method); } /** * Can wrap the invoker in preperation for running * a test. * @param SimpleInvoker $invoker Individual test runner. * @return SimpleInvoker Wrapped test runner. * @access public */ function createInvoker($invoker) { return $this->reporter->createInvoker($invoker); } /** * Gets the formatter for privateiables and other small * generic data items. * @return SimpleDumper Formatter. * @access public */ function getDumper() { return $this->reporter->getDumper(); } /** * Paints the start of a group test. * @param string $test_name Name of test or other label. * @param integer $size Number of test cases starting. * @access public */ function paintGroupStart($test_name, $size) { $this->reporter->paintGroupStart($test_name, $size); } /** * Paints the end of a group test. * @param string $test_name Name of test or other label. * @access public */ function paintGroupEnd($test_name) { $this->reporter->paintGroupEnd($test_name); } /** * Paints the start of a test case. * @param string $test_name Name of test or other label. * @access public */ function paintCaseStart($test_name) { $this->reporter->paintCaseStart($test_name); } /** * Paints the end of a test case. * @param string $test_name Name of test or other label. * @access public */ function paintCaseEnd($test_name) { $this->reporter->paintCaseEnd($test_name); } /** * Paints the start of a test method. * @param string $test_name Name of test or other label. * @access public */ function paintMethodStart($test_name) { $this->reporter->paintMethodStart($test_name); } /** * Paints the end of a test method. * @param string $test_name Name of test or other label. * @access public */ function paintMethodEnd($test_name) { $this->reporter->paintMethodEnd($test_name); } /** * Chains to the wrapped reporter. * @param string $message Message is ignored. * @access public */ function paintPass($message) { $this->reporter->paintPass($message); } /** * Chains to the wrapped reporter. * @param string $message Message is ignored. * @access public */ function paintFail($message) { $this->reporter->paintFail($message); } /** * Chains to the wrapped reporter. * @param string $message Text of error formatted by * the test case. * @access public */ function paintError($message) { $this->reporter->paintError($message); } /** * Chains to the wrapped reporter. * @param Exception $exception Exception to show. * @access public */ function paintException($exception) { $this->reporter->paintException($exception); } /** * Prints the message for skipping tests. * @param string $message Text of skip condition. * @access public */ function paintSkip($message) { $this->reporter->paintSkip($message); } /** * Chains to the wrapped reporter. * @param string $message Text to display. * @access public */ function paintMessage($message) { $this->reporter->paintMessage($message); } /** * Chains to the wrapped reporter. * @param string $message Text to display. * @access public */ function paintFormattedMessage($message) { $this->reporter->paintFormattedMessage($message); } /** * Chains to the wrapped reporter. * @param string $type Event type as text. * @param mixed $payload Message or object. * @return boolean Should return false if this * type of signal should fail the * test suite. * @access public */ function paintSignal($type, $payload) { $this->reporter->paintSignal($type, $payload); } } /** * For sending messages to multiple reporters at * the same time. * @package SimpleTest * @subpackage UnitTester */ class MultipleReporter { private $reporters = array(); /** * Adds a reporter to the subscriber list. * @param SimpleScorer $reporter Reporter to receive events. * @access public */ function attachReporter($reporter) { $this->reporters[] = $reporter; } /** * Signals that the next evaluation will be a dry * run. That is, the structure events will be * recorded, but no tests will be run. * @param boolean $is_dry Dry run if true. * @access public */ function makeDry($is_dry = true) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->makeDry($is_dry); } } /** * Accessor for current status. Will be false * if there have been any failures or exceptions. * If any reporter reports a failure, the whole * suite fails. * @return boolean True if no failures. * @access public */ function getStatus() { for ($i = 0; $i < count($this->reporters); $i++) { if (! $this->reporters[$i]->getStatus()) { return false; } } return true; } /** * The reporter has a veto on what should be run. * It requires all reporters to want to run the method. * @param string $test_case_name name of test case. * @param string $method Name of test method. * @access public */ function shouldInvoke($test_case_name, $method) { for ($i = 0; $i < count($this->reporters); $i++) { if (! $this->reporters[$i]->shouldInvoke($test_case_name, $method)) { return false; } } return true; } /** * Every reporter gets a chance to wrap the invoker. * @param SimpleInvoker $invoker Individual test runner. * @return SimpleInvoker Wrapped test runner. * @access public */ function createInvoker($invoker) { for ($i = 0; $i < count($this->reporters); $i++) { $invoker = $this->reporters[$i]->createInvoker($invoker); } return $invoker; } /** * Gets the formatter for privateiables and other small * generic data items. * @return SimpleDumper Formatter. * @access public */ function getDumper() { return new SimpleDumper(); } /** * Paints the start of a group test. * @param string $test_name Name of test or other label. * @param integer $size Number of test cases starting. * @access public */ function paintGroupStart($test_name, $size) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintGroupStart($test_name, $size); } } /** * Paints the end of a group test. * @param string $test_name Name of test or other label. * @access public */ function paintGroupEnd($test_name) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintGroupEnd($test_name); } } /** * Paints the start of a test case. * @param string $test_name Name of test or other label. * @access public */ function paintCaseStart($test_name) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintCaseStart($test_name); } } /** * Paints the end of a test case. * @param string $test_name Name of test or other label. * @access public */ function paintCaseEnd($test_name) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintCaseEnd($test_name); } } /** * Paints the start of a test method. * @param string $test_name Name of test or other label. * @access public */ function paintMethodStart($test_name) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintMethodStart($test_name); } } /** * Paints the end of a test method. * @param string $test_name Name of test or other label. * @access public */ function paintMethodEnd($test_name) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintMethodEnd($test_name); } } /** * Chains to the wrapped reporter. * @param string $message Message is ignored. * @access public */ function paintPass($message) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintPass($message); } } /** * Chains to the wrapped reporter. * @param string $message Message is ignored. * @access public */ function paintFail($message) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintFail($message); } } /** * Chains to the wrapped reporter. * @param string $message Text of error formatted by * the test case. * @access public */ function paintError($message) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintError($message); } } /** * Chains to the wrapped reporter. * @param Exception $exception Exception to display. * @access public */ function paintException($exception) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintException($exception); } } /** * Prints the message for skipping tests. * @param string $message Text of skip condition. * @access public */ function paintSkip($message) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintSkip($message); } } /** * Chains to the wrapped reporter. * @param string $message Text to display. * @access public */ function paintMessage($message) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintMessage($message); } } /** * Chains to the wrapped reporter. * @param string $message Text to display. * @access public */ function paintFormattedMessage($message) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintFormattedMessage($message); } } /** * Chains to the wrapped reporter. * @param string $type Event type as text. * @param mixed $payload Message or object. * @return boolean Should return false if this * type of signal should fail the * test suite. * @access public */ function paintSignal($type, $payload) { for ($i = 0; $i < count($this->reporters); $i++) { $this->reporters[$i]->paintSignal($type, $payload); } } } ?> Swift-4.2.1/test-suite/lib/simpletest/selector.php 100644 0 0 6412 12000050366 17332 0 ustar 0 0 name = $name; } /** * Accessor for name. * @returns string $name Name to match. */ function getName() { return $this->name; } /** * Compares with name attribute of widget. * @param SimpleWidget $widget Control to compare. * @access public */ function isMatch($widget) { return ($widget->getName() == $this->name); } } /** * Used to extract form elements for testing against. * Searches by visible label or alt text. * @package SimpleTest * @subpackage WebTester */ class SimpleByLabel { private $label; /** * Stashes the name for later comparison. * @param string $label Visible text to match. */ function __construct($label) { $this->label = $label; } /** * Comparison. Compares visible text of widget or * related label. * @param SimpleWidget $widget Control to compare. * @access public */ function isMatch($widget) { if (! method_exists($widget, 'isLabel')) { return false; } return $widget->isLabel($this->label); } } /** * Used to extract form elements for testing against. * Searches dy id attribute. * @package SimpleTest * @subpackage WebTester */ class SimpleById { private $id; /** * Stashes the name for later comparison. * @param string $id ID atribute to match. */ function __construct($id) { $this->id = $id; } /** * Comparison. Compares id attribute of widget. * @param SimpleWidget $widget Control to compare. * @access public */ function isMatch($widget) { return $widget->isId($this->id); } } /** * Used to extract form elements for testing against. * Searches by visible label, name or alt text. * @package SimpleTest * @subpackage WebTester */ class SimpleByLabelOrName { private $label; /** * Stashes the name/label for later comparison. * @param string $label Visible text to match. */ function __construct($label) { $this->label = $label; } /** * Comparison. Compares visible text of widget or * related label or name. * @param SimpleWidget $widget Control to compare. * @access public */ function isMatch($widget) { if (method_exists($widget, 'isLabel')) { if ($widget->isLabel($this->label)) { return true; } } return ($widget->getName() == $this->label); } } ?> Swift-4.2.1/test-suite/lib/simpletest/shell_tester.php 100644 0 0 24343 12000050366 20232 0 ustar 0 0 output = false; } /** * Actually runs the command. Does not trap the * error stream output as this need PHP 4.3+. * @param string $command The actual command line * to run. * @return integer Exit code. * @access public */ function execute($command) { $this->output = false; exec($command, $this->output, $ret); return $ret; } /** * Accessor for the last output. * @return string Output as text. * @access public */ function getOutput() { return implode("\n", $this->output); } /** * Accessor for the last output. * @return array Output as array of lines. * @access public */ function getOutputAsList() { return $this->output; } } /** * Test case for testing of command line scripts and * utilities. Usually scripts that are external to the * PHP code, but support it in some way. * @package SimpleTest * @subpackage UnitTester */ class ShellTestCase extends SimpleTestCase { private $current_shell; private $last_status; private $last_command; /** * Creates an empty test case. Should be subclassed * with test methods for a functional test case. * @param string $label Name of test case. Will use * the class name if none specified. * @access public */ function __construct($label = false) { parent::__construct($label); $this->current_shell = $this->createShell(); $this->last_status = false; $this->last_command = ''; } /** * Executes a command and buffers the results. * @param string $command Command to run. * @return boolean True if zero exit code. * @access public */ function execute($command) { $shell = $this->getShell(); $this->last_status = $shell->execute($command); $this->last_command = $command; return ($this->last_status === 0); } /** * Dumps the output of the last command. * @access public */ function dumpOutput() { $this->dump($this->getOutput()); } /** * Accessor for the last output. * @return string Output as text. * @access public */ function getOutput() { $shell = $this->getShell(); return $shell->getOutput(); } /** * Accessor for the last output. * @return array Output as array of lines. * @access public */ function getOutputAsList() { $shell = $this->getShell(); return $shell->getOutputAsList(); } /** * Called from within the test methods to register * passes and failures. * @param boolean $result Pass on true. * @param string $message Message to display describing * the test state. * @return boolean True on pass * @access public */ function assertTrue($result, $message = false) { return $this->assert(new TrueExpectation(), $result, $message); } /** * Will be true on false and vice versa. False * is the PHP definition of false, so that null, * empty strings, zero and an empty array all count * as false. * @param boolean $result Pass on false. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertFalse($result, $message = '%s') { return $this->assert(new FalseExpectation(), $result, $message); } /** * Will trigger a pass if the two parameters have * the same value only. Otherwise a fail. This * is for testing hand extracted text, etc. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertEqual($first, $second, $message = "%s") { return $this->assert( new EqualExpectation($first), $second, $message); } /** * Will trigger a pass if the two parameters have * a different value. Otherwise a fail. This * is for testing hand extracted text, etc. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertNotEqual($first, $second, $message = "%s") { return $this->assert( new NotEqualExpectation($first), $second, $message); } /** * Tests the last status code from the shell. * @param integer $status Expected status of last * command. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertExitCode($status, $message = "%s") { $message = sprintf($message, "Expected status code of [$status] from [" . $this->last_command . "], but got [" . $this->last_status . "]"); return $this->assertTrue($status === $this->last_status, $message); } /** * Attempt to exactly match the combined STDERR and * STDOUT output. * @param string $expected Expected output. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertOutput($expected, $message = "%s") { $shell = $this->getShell(); return $this->assert( new EqualExpectation($expected), $shell->getOutput(), $message); } /** * Scans the output for a Perl regex. If found * anywhere it passes, else it fails. * @param string $pattern Regex to search for. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertOutputPattern($pattern, $message = "%s") { $shell = $this->getShell(); return $this->assert( new PatternExpectation($pattern), $shell->getOutput(), $message); } /** * If a Perl regex is found anywhere in the current * output then a failure is generated, else a pass. * @param string $pattern Regex to search for. * @param $message Message to display. * @return boolean True if pass. * @access public */ function assertNoOutputPattern($pattern, $message = "%s") { $shell = $this->getShell(); return $this->assert( new NoPatternExpectation($pattern), $shell->getOutput(), $message); } /** * File existence check. * @param string $path Full filename and path. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertFileExists($path, $message = "%s") { $message = sprintf($message, "File [$path] should exist"); return $this->assertTrue(file_exists($path), $message); } /** * File non-existence check. * @param string $path Full filename and path. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertFileNotExists($path, $message = "%s") { $message = sprintf($message, "File [$path] should not exist"); return $this->assertFalse(file_exists($path), $message); } /** * Scans a file for a Perl regex. If found * anywhere it passes, else it fails. * @param string $pattern Regex to search for. * @param string $path Full filename and path. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertFilePattern($pattern, $path, $message = "%s") { return $this->assert( new PatternExpectation($pattern), implode('', file($path)), $message); } /** * If a Perl regex is found anywhere in the named * file then a failure is generated, else a pass. * @param string $pattern Regex to search for. * @param string $path Full filename and path. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertNoFilePattern($pattern, $path, $message = "%s") { return $this->assert( new NoPatternExpectation($pattern), implode('', file($path)), $message); } /** * Accessor for current shell. Used for testing the * the tester itself. * @return Shell Current shell. * @access protected */ protected function getShell() { return $this->current_shell; } /** * Factory for the shell to run the command on. * @return Shell New shell object. * @access protected */ protected function createShell() { return new SimpleShell(); } } ?> Swift-4.2.1/test-suite/lib/simpletest/simpletest.php 100644 0 0 27615 12000050366 17733 0 ustar 0 0 = 0) { require_once(dirname(__FILE__) . '/reflection_php5.php'); } else { require_once(dirname(__FILE__) . '/reflection_php4.php'); } require_once(dirname(__FILE__) . '/default_reporter.php'); require_once(dirname(__FILE__) . '/compatibility.php'); /**#@-*/ /** * Registry and test context. Includes a few * global options that I'm slowly getting rid of. * @package SimpleTest * @subpackage UnitTester */ class SimpleTest { /** * Reads the SimpleTest version from the release file. * @return string Version string. * @access public */ static function getVersion() { $content = file(dirname(__FILE__) . '/VERSION'); return trim($content[0]); } /** * Sets the name of a test case to ignore, usually * because the class is an abstract case that should * not be run. Once PHP4 is dropped this will disappear * as a public method and "abstract" will rule. * @param string $class Add a class to ignore. * @access public */ static function ignore($class) { $registry = &SimpleTest::getRegistry(); $registry['IgnoreList'][strtolower($class)] = true; } /** * Scans the now complete ignore list, and adds * all parent classes to the list. If a class * is not a runnable test case, then it's parents * wouldn't be either. This is syntactic sugar * to cut down on ommissions of ignore()'s or * missing abstract declarations. This cannot * be done whilst loading classes wiithout forcing * a particular order on the class declarations and * the ignore() calls. It's just nice to have the ignore() * calls at the top of the file before the actual declarations. * @param array $classes Class names of interest. * @access public */ static function ignoreParentsIfIgnored($classes) { $registry = &SimpleTest::getRegistry(); foreach ($classes as $class) { if (SimpleTest::isIgnored($class)) { $reflection = new SimpleReflection($class); if ($parent = $reflection->getParent()) { SimpleTest::ignore($parent); } } } } /** * Puts the object to the global pool of 'preferred' objects * which can be retrieved with SimpleTest :: preferred() method. * Instances of the same class are overwritten. * @param object $object Preferred object * @access public * @see preferred() */ static function prefer($object) { $registry = &SimpleTest::getRegistry(); $registry['Preferred'][] = $object; } /** * Retrieves 'preferred' objects from global pool. Class filter * can be applied in order to retrieve the object of the specific * class * @param array|string $classes Allowed classes or interfaces. * @access public * @return array|object|null * @see prefer() */ static function preferred($classes) { if (! is_array($classes)) { $classes = array($classes); } $registry = &SimpleTest::getRegistry(); for ($i = count($registry['Preferred']) - 1; $i >= 0; $i--) { foreach ($classes as $class) { if (SimpleTestCompatibility::isA($registry['Preferred'][$i], $class)) { return $registry['Preferred'][$i]; } } } return null; } /** * Test to see if a test case is in the ignore * list. Quite obviously the ignore list should * be a separate object and will be one day. * This method is internal to SimpleTest. Don't * use it. * @param string $class Class name to test. * @return boolean True if should not be run. * @access public */ static function isIgnored($class) { $registry = &SimpleTest::getRegistry(); return isset($registry['IgnoreList'][strtolower($class)]); } /** * Sets proxy to use on all requests for when * testing from behind a firewall. Set host * to false to disable. This will take effect * if there are no other proxy settings. * @param string $proxy Proxy host as URL. * @param string $username Proxy username for authentication. * @param string $password Proxy password for authentication. * @access public */ static function useProxy($proxy, $username = false, $password = false) { $registry = &SimpleTest::getRegistry(); $registry['DefaultProxy'] = $proxy; $registry['DefaultProxyUsername'] = $username; $registry['DefaultProxyPassword'] = $password; } /** * Accessor for default proxy host. * @return string Proxy URL. * @access public */ static function getDefaultProxy() { $registry = &SimpleTest::getRegistry(); return $registry['DefaultProxy']; } /** * Accessor for default proxy username. * @return string Proxy username for authentication. * @access public */ static function getDefaultProxyUsername() { $registry = &SimpleTest::getRegistry(); return $registry['DefaultProxyUsername']; } /** * Accessor for default proxy password. * @return string Proxy password for authentication. * @access public */ static function getDefaultProxyPassword() { $registry = &SimpleTest::getRegistry(); return $registry['DefaultProxyPassword']; } /** * Accessor for global registry of options. * @return hash All stored values. * @access private */ protected static function &getRegistry() { static $registry = false; if (! $registry) { $registry = SimpleTest::getDefaults(); } return $registry; } /** * Accessor for the context of the current * test run. * @return SimpleTestContext Current test run. * @access public */ static function getContext() { static $context = false; if (! $context) { $context = new SimpleTestContext(); } return $context; } /** * Constant default values. * @return hash All registry defaults. * @access private */ protected static function getDefaults() { return array( 'MockBaseClass' => 'SimpleMock', 'IgnoreList' => array(), 'DefaultProxy' => false, 'DefaultProxyUsername' => false, 'DefaultProxyPassword' => false, 'Preferred' => array(new HtmlReporter(), new TextReporter(), new XmlReporter())); } /** * @deprecated */ static function setMockBaseClass($mock_base) { $registry = &SimpleTest::getRegistry(); $registry['MockBaseClass'] = $mock_base; } /** * @deprecated */ static function getMockBaseClass() { $registry = &SimpleTest::getRegistry(); return $registry['MockBaseClass']; } } /** * Container for all components for a specific * test run. Makes things like error queues * available to PHP event handlers, and also * gets around some nasty reference issues in * the mocks. * @package SimpleTest */ class SimpleTestContext { private $test; private $reporter; private $resources; /** * Clears down the current context. * @access public */ function clear() { $this->resources = array(); } /** * Sets the current test case instance. This * global instance can be used by the mock objects * to send message to the test cases. * @param SimpleTestCase $test Test case to register. * @access public */ function setTest($test) { $this->clear(); $this->test = $test; } /** * Accessor for currently running test case. * @return SimpleTestCase Current test. * @access public */ function getTest() { return $this->test; } /** * Sets the current reporter. This * global instance can be used by the mock objects * to send messages. * @param SimpleReporter $reporter Reporter to register. * @access public */ function setReporter($reporter) { $this->clear(); $this->reporter = $reporter; } /** * Accessor for current reporter. * @return SimpleReporter Current reporter. * @access public */ function getReporter() { return $this->reporter; } /** * Accessor for the Singleton resource. * @return object Global resource. * @access public */ function get($resource) { if (! isset($this->resources[$resource])) { $this->resources[$resource] = new $resource(); } return $this->resources[$resource]; } } /** * Interrogates the stack trace to recover the * failure point. * @package SimpleTest * @subpackage UnitTester */ class SimpleStackTrace { private $prefixes; /** * Stashes the list of target prefixes. * @param array $prefixes List of method prefixes * to search for. */ function __construct($prefixes) { $this->prefixes = $prefixes; } /** * Extracts the last method name that was not within * Simpletest itself. Captures a stack trace if none given. * @param array $stack List of stack frames. * @return string Snippet of test report with line * number and file. * @access public */ function traceMethod($stack = false) { $stack = $stack ? $stack : $this->captureTrace(); foreach ($stack as $frame) { if ($this->frameLiesWithinSimpleTestFolder($frame)) { continue; } if ($this->frameMatchesPrefix($frame)) { return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']'; } } return ''; } /** * Test to see if error is generated by SimpleTest itself. * @param array $frame PHP stack frame. * @return boolean True if a SimpleTest file. * @access private */ protected function frameLiesWithinSimpleTestFolder($frame) { if (isset($frame['file'])) { $path = substr(SIMPLE_TEST, 0, -1); if (strpos($frame['file'], $path) === 0) { if (dirname($frame['file']) == $path) { return true; } } } return false; } /** * Tries to determine if the method call is an assert, etc. * @param array $frame PHP stack frame. * @return boolean True if matches a target. * @access private */ protected function frameMatchesPrefix($frame) { foreach ($this->prefixes as $prefix) { if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) { return true; } } return false; } /** * Grabs a current stack trace. * @return array Fulle trace. * @access private */ protected function captureTrace() { if (function_exists('debug_backtrace')) { return array_reverse(debug_backtrace()); } return array(); } } ?> Swift-4.2.1/test-suite/lib/simpletest/socket.php 100644 0 0 21425 12000050366 17023 0 ustar 0 0 clearError(); } /** * Test for an outstanding error. * @return boolean True if there is an error. * @access public */ function isError() { return ($this->error != ''); } /** * Accessor for an outstanding error. * @return string Empty string if no error otherwise * the error message. * @access public */ function getError() { return $this->error; } /** * Sets the internal error. * @param string Error message to stash. * @access protected */ function setError($error) { $this->error = $error; } /** * Resets the error state to no error. * @access protected */ function clearError() { $this->setError(''); } } class SimpleFileSocket extends SimpleStickyError { private $handle; private $is_open = false; private $sent = ''; private $block_size; /** * Opens a socket for reading and writing. * @param SimpleUrl $file Target URI to fetch. * @param integer $block_size Size of chunk to read. * @access public */ function __construct($file, $block_size = 1024) { parent::__construct(); if (! ($this->handle = $this->openFile($file, $error))) { $file_string = $file->asString(); $this->setError("Cannot open [$file_string] with [$error]"); return; } $this->is_open = true; $this->block_size = $block_size; } /** * Writes some data to the socket and saves alocal copy. * @param string $message String to send to socket. * @return boolean True if successful. * @access public */ function write($message) { return true; } /** * Reads data from the socket. The error suppresion * is a workaround for PHP4 always throwing a warning * with a secure socket. * @return integer/boolean Incoming bytes. False * on error. * @access public */ function read() { $raw = @fread($this->handle, $this->block_size); if ($raw === false) { $this->setError('Cannot read from socket'); $this->close(); } return $raw; } /** * Accessor for socket open state. * @return boolean True if open. * @access public */ function isOpen() { return $this->is_open; } /** * Closes the socket preventing further reads. * Cannot be reopened once closed. * @return boolean True if successful. * @access public */ function close() { if (!$this->is_open) return false; $this->is_open = false; return fclose($this->handle); } /** * Accessor for content so far. * @return string Bytes sent only. * @access public */ function getSent() { return $this->sent; } /** * Actually opens the low level socket. * @param SimpleUrl $file SimpleUrl file target. * @param string $error Recipient of error message. * @param integer $timeout Maximum time to wait for connection. * @access protected */ protected function openFile($file, &$error) { return @fopen($file->asString(), 'r'); } } /** * Wrapper for TCP/IP socket. * @package SimpleTest * @subpackage WebTester */ class SimpleSocket extends SimpleStickyError { private $handle; private $is_open = false; private $sent = ''; private $lock_size; /** * Opens a socket for reading and writing. * @param string $host Hostname to send request to. * @param integer $port Port on remote machine to open. * @param integer $timeout Connection timeout in seconds. * @param integer $block_size Size of chunk to read. * @access public */ function __construct($host, $port, $timeout, $block_size = 255) { parent::__construct(); if (! ($this->handle = $this->openSocket($host, $port, $error_number, $error, $timeout))) { $this->setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds"); return; } $this->is_open = true; $this->block_size = $block_size; SimpleTestCompatibility::setTimeout($this->handle, $timeout); } /** * Writes some data to the socket and saves alocal copy. * @param string $message String to send to socket. * @return boolean True if successful. * @access public */ function write($message) { if ($this->isError() || ! $this->isOpen()) { return false; } $count = fwrite($this->handle, $message); if (! $count) { if ($count === false) { $this->setError('Cannot write to socket'); $this->close(); } return false; } fflush($this->handle); $this->sent .= $message; return true; } /** * Reads data from the socket. The error suppresion * is a workaround for PHP4 always throwing a warning * with a secure socket. * @return integer/boolean Incoming bytes. False * on error. * @access public */ function read() { if ($this->isError() || ! $this->isOpen()) { return false; } $raw = @fread($this->handle, $this->block_size); if ($raw === false) { $this->setError('Cannot read from socket'); $this->close(); } return $raw; } /** * Accessor for socket open state. * @return boolean True if open. * @access public */ function isOpen() { return $this->is_open; } /** * Closes the socket preventing further reads. * Cannot be reopened once closed. * @return boolean True if successful. * @access public */ function close() { $this->is_open = false; return fclose($this->handle); } /** * Accessor for content so far. * @return string Bytes sent only. * @access public */ function getSent() { return $this->sent; } /** * Actually opens the low level socket. * @param string $host Host to connect to. * @param integer $port Port on host. * @param integer $error_number Recipient of error code. * @param string $error Recipoent of error message. * @param integer $timeout Maximum time to wait for connection. * @access protected */ protected function openSocket($host, $port, &$error_number, &$error, $timeout) { return @fsockopen($host, $port, $error_number, $error, $timeout); } } /** * Wrapper for TCP/IP socket over TLS. * @package SimpleTest * @subpackage WebTester */ class SimpleSecureSocket extends SimpleSocket { /** * Opens a secure socket for reading and writing. * @param string $host Hostname to send request to. * @param integer $port Port on remote machine to open. * @param integer $timeout Connection timeout in seconds. * @access public */ function __construct($host, $port, $timeout) { parent::__construct($host, $port, $timeout); } /** * Actually opens the low level socket. * @param string $host Host to connect to. * @param integer $port Port on host. * @param integer $error_number Recipient of error code. * @param string $error Recipient of error message. * @param integer $timeout Maximum time to wait for connection. * @access protected */ function openSocket($host, $port, &$error_number, &$error, $timeout) { return parent::openSocket("tls://$host", $port, $error_number, $error, $timeout); } } ?> Swift-4.2.1/test-suite/lib/simpletest/tag.php 100644 0 0 113317 12000050366 16330 0 ustar 0 0 name = strtolower(trim($name)); $this->attributes = $attributes; $this->content = ''; } /** * Check to see if the tag can have both start and * end tags with content in between. * @return boolean True if content allowed. * @access public */ function expectEndTag() { return true; } /** * The current tag should not swallow all content for * itself as it's searchable page content. Private * content tags are usually widgets that contain default * values. * @return boolean False as content is available * to other tags by default. * @access public */ function isPrivateContent() { return false; } /** * Appends string content to the current content. * @param string $content Additional text. * @access public */ function addContent($content) { $this->content .= (string)$content; } /** * Adds an enclosed tag to the content. * @param SimpleTag $tag New tag. * @access public */ function addTag($tag) { } /** * Accessor for tag name. * @return string Name of tag. * @access public */ function getTagName() { return $this->name; } /** * List of legal child elements. * @return array List of element names. * @access public */ function getChildElements() { return array(); } /** * Accessor for an attribute. * @param string $label Attribute name. * @return string Attribute value. * @access public */ function getAttribute($label) { $label = strtolower($label); if (! isset($this->attributes[$label])) { return false; } return (string)$this->attributes[$label]; } /** * Sets an attribute. * @param string $label Attribute name. * @return string $value New attribute value. * @access protected */ protected function setAttribute($label, $value) { $this->attributes[strtolower($label)] = $value; } /** * Accessor for the whole content so far. * @return string Content as big raw string. * @access public */ function getContent() { return $this->content; } /** * Accessor for content reduced to visible text. Acts * like a text mode browser, normalising space and * reducing images to their alt text. * @return string Content as plain text. * @access public */ function getText() { return SimpleHtmlSaxParser::normalise($this->content); } /** * Test to see if id attribute matches. * @param string $id ID to test against. * @return boolean True on match. * @access public */ function isId($id) { return ($this->getAttribute('id') == $id); } } /** * Base url. * @package SimpleTest * @subpackage WebTester */ class SimpleBaseTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('base', $attributes); } /** * Base tag is not a block tag. * @return boolean false * @access public */ function expectEndTag() { return false; } } /** * Page title. * @package SimpleTest * @subpackage WebTester */ class SimpleTitleTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('title', $attributes); } } /** * Link. * @package SimpleTest * @subpackage WebTester */ class SimpleAnchorTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('a', $attributes); } /** * Accessor for URL as string. * @return string Coerced as string. * @access public */ function getHref() { $url = $this->getAttribute('href'); if (is_bool($url)) { $url = ''; } return $url; } } /** * Form element. * @package SimpleTest * @subpackage WebTester */ class SimpleWidget extends SimpleTag { private $value; private $label; private $is_set; /** * Starts with a named tag with attributes only. * @param string $name Tag name. * @param hash $attributes Attribute names and * string values. */ function __construct($name, $attributes) { parent::__construct($name, $attributes); $this->value = false; $this->label = false; $this->is_set = false; } /** * Accessor for name submitted as the key in * GET/POST privateiables hash. * @return string Parsed value. * @access public */ function getName() { return $this->getAttribute('name'); } /** * Accessor for default value parsed with the tag. * @return string Parsed value. * @access public */ function getDefault() { return $this->getAttribute('value'); } /** * Accessor for currently set value or default if * none. * @return string Value set by form or default * if none. * @access public */ function getValue() { if (! $this->is_set) { return $this->getDefault(); } return $this->value; } /** * Sets the current form element value. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { $this->value = $value; $this->is_set = true; return true; } /** * Resets the form element value back to the * default. * @access public */ function resetValue() { $this->is_set = false; } /** * Allows setting of a label externally, say by a * label tag. * @param string $label Label to attach. * @access public */ function setLabel($label) { $this->label = trim($label); } /** * Reads external or internal label. * @param string $label Label to test. * @return boolean True is match. * @access public */ function isLabel($label) { return $this->label == trim($label); } /** * Dispatches the value into the form encoded packet. * @param SimpleEncoding $encoding Form packet. * @access public */ function write($encoding) { if ($this->getName()) { $encoding->add($this->getName(), $this->getValue()); } } } /** * Text, password and hidden field. * @package SimpleTest * @subpackage WebTester */ class SimpleTextTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('input', $attributes); if ($this->getAttribute('value') === false) { $this->setAttribute('value', ''); } } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * Sets the current form element value. Cannot * change the value of a hidden field. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { if ($this->getAttribute('type') == 'hidden') { return false; } return parent::setValue($value); } } /** * Submit button as input tag. * @package SimpleTest * @subpackage WebTester */ class SimpleSubmitTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('input', $attributes); if ($this->getAttribute('value') === false) { $this->setAttribute('value', 'Submit'); } } /** * Tag contains no end element. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * Disables the setting of the button value. * @param string $value Ignored. * @return boolean True if allowed. * @access public */ function setValue($value) { return false; } /** * Value of browser visible text. * @return string Visible label. * @access public */ function getLabel() { return $this->getValue(); } /** * Test for a label match when searching. * @param string $label Label to test. * @return boolean True on match. * @access public */ function isLabel($label) { return trim($label) == trim($this->getLabel()); } } /** * Image button as input tag. * @package SimpleTest * @subpackage WebTester */ class SimpleImageSubmitTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('input', $attributes); } /** * Tag contains no end element. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * Disables the setting of the button value. * @param string $value Ignored. * @return boolean True if allowed. * @access public */ function setValue($value) { return false; } /** * Value of browser visible text. * @return string Visible label. * @access public */ function getLabel() { if ($this->getAttribute('title')) { return $this->getAttribute('title'); } return $this->getAttribute('alt'); } /** * Test for a label match when searching. * @param string $label Label to test. * @return boolean True on match. * @access public */ function isLabel($label) { return trim($label) == trim($this->getLabel()); } /** * Dispatches the value into the form encoded packet. * @param SimpleEncoding $encoding Form packet. * @param integer $x X coordinate of click. * @param integer $y Y coordinate of click. * @access public */ function write($encoding, $x = 1, $y = 1) { if ($this->getName()) { $encoding->add($this->getName() . '.x', $x); $encoding->add($this->getName() . '.y', $y); } else { $encoding->add('x', $x); $encoding->add('y', $y); } } } /** * Submit button as button tag. * @package SimpleTest * @subpackage WebTester */ class SimpleButtonTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * Defaults are very browser dependent. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('button', $attributes); } /** * Check to see if the tag can have both start and * end tags with content in between. * @return boolean True if content allowed. * @access public */ function expectEndTag() { return true; } /** * Disables the setting of the button value. * @param string $value Ignored. * @return boolean True if allowed. * @access public */ function setValue($value) { return false; } /** * Value of browser visible text. * @return string Visible label. * @access public */ function getLabel() { return $this->getContent(); } /** * Test for a label match when searching. * @param string $label Label to test. * @return boolean True on match. * @access public */ function isLabel($label) { return trim($label) == trim($this->getLabel()); } } /** * Content tag for text area. * @package SimpleTest * @subpackage WebTester */ class SimpleTextAreaTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('textarea', $attributes); } /** * Accessor for starting value. * @return string Parsed value. * @access public */ function getDefault() { return $this->wrap(SimpleHtmlSaxParser::decodeHtml($this->getContent())); } /** * Applies word wrapping if needed. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { return parent::setValue($this->wrap($value)); } /** * Test to see if text should be wrapped. * @return boolean True if wrapping on. * @access private */ function wrapIsEnabled() { if ($this->getAttribute('cols')) { $wrap = $this->getAttribute('wrap'); if (($wrap == 'physical') || ($wrap == 'hard')) { return true; } } return false; } /** * Performs the formatting that is peculiar to * this tag. There is strange behaviour in this * one, including stripping a leading new line. * Go figure. I am using Firefox as a guide. * @param string $text Text to wrap. * @return string Text wrapped with carriage * returns and line feeds * @access private */ protected function wrap($text) { $text = str_replace("\r\r\n", "\r\n", str_replace("\n", "\r\n", $text)); $text = str_replace("\r\n\n", "\r\n", str_replace("\r", "\r\n", $text)); if (strncmp($text, "\r\n", strlen("\r\n")) == 0) { $text = substr($text, strlen("\r\n")); } if ($this->wrapIsEnabled()) { return wordwrap( $text, (integer)$this->getAttribute('cols'), "\r\n"); } return $text; } /** * The content of textarea is not part of the page. * @return boolean True. * @access public */ function isPrivateContent() { return true; } } /** * File upload widget. * @package SimpleTest * @subpackage WebTester */ class SimpleUploadTag extends SimpleWidget { /** * Starts with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('input', $attributes); } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * Dispatches the value into the form encoded packet. * @param SimpleEncoding $encoding Form packet. * @access public */ function write($encoding) { if (! file_exists($this->getValue())) { return; } $encoding->attach( $this->getName(), implode('', file($this->getValue())), basename($this->getValue())); } } /** * Drop down widget. * @package SimpleTest * @subpackage WebTester */ class SimpleSelectionTag extends SimpleWidget { private $options; private $choice; /** * Starts with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('select', $attributes); $this->options = array(); $this->choice = false; } /** * Adds an option tag to a selection field. * @param SimpleOptionTag $tag New option. * @access public */ function addTag($tag) { if ($tag->getTagName() == 'option') { $this->options[] = $tag; } } /** * Text within the selection element is ignored. * @param string $content Ignored. * @access public */ function addContent($content) { } /** * Scans options for defaults. If none, then * the first option is selected. * @return string Selected field. * @access public */ function getDefault() { for ($i = 0, $count = count($this->options); $i < $count; $i++) { if ($this->options[$i]->getAttribute('selected') !== false) { return $this->options[$i]->getDefault(); } } if ($count > 0) { return $this->options[0]->getDefault(); } return ''; } /** * Can only set allowed values. * @param string $value New choice. * @return boolean True if allowed. * @access public */ function setValue($value) { for ($i = 0, $count = count($this->options); $i < $count; $i++) { if ($this->options[$i]->isValue($value)) { $this->choice = $i; return true; } } return false; } /** * Accessor for current selection value. * @return string Value attribute or * content of opton. * @access public */ function getValue() { if ($this->choice === false) { return $this->getDefault(); } return $this->options[$this->choice]->getValue(); } } /** * Drop down widget. * @package SimpleTest * @subpackage WebTester */ class MultipleSelectionTag extends SimpleWidget { private $options; private $values; /** * Starts with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('select', $attributes); $this->options = array(); $this->values = false; } /** * Adds an option tag to a selection field. * @param SimpleOptionTag $tag New option. * @access public */ function addTag($tag) { if ($tag->getTagName() == 'option') { $this->options[] = &$tag; } } /** * Text within the selection element is ignored. * @param string $content Ignored. * @access public */ function addContent($content) { } /** * Scans options for defaults to populate the * value array(). * @return array Selected fields. * @access public */ function getDefault() { $default = array(); for ($i = 0, $count = count($this->options); $i < $count; $i++) { if ($this->options[$i]->getAttribute('selected') !== false) { $default[] = $this->options[$i]->getDefault(); } } return $default; } /** * Can only set allowed values. Any illegal value * will result in a failure, but all correct values * will be set. * @param array $desired New choices. * @return boolean True if all allowed. * @access public */ function setValue($desired) { $achieved = array(); foreach ($desired as $value) { $success = false; for ($i = 0, $count = count($this->options); $i < $count; $i++) { if ($this->options[$i]->isValue($value)) { $achieved[] = $this->options[$i]->getValue(); $success = true; break; } } if (! $success) { return false; } } $this->values = $achieved; return true; } /** * Accessor for current selection value. * @return array List of currently set options. * @access public */ function getValue() { if ($this->values === false) { return $this->getDefault(); } return $this->values; } } /** * Option for selection field. * @package SimpleTest * @subpackage WebTester */ class SimpleOptionTag extends SimpleWidget { /** * Stashes the attributes. */ function __construct($attributes) { parent::__construct('option', $attributes); } /** * Does nothing. * @param string $value Ignored. * @return boolean Not allowed. * @access public */ function setValue($value) { return false; } /** * Test to see if a value matches the option. * @param string $compare Value to compare with. * @return boolean True if possible match. * @access public */ function isValue($compare) { $compare = trim($compare); if (trim($this->getValue()) == $compare) { return true; } return trim($this->getContent()) == $compare; } /** * Accessor for starting value. Will be set to * the option label if no value exists. * @return string Parsed value. * @access public */ function getDefault() { if ($this->getAttribute('value') === false) { return $this->getContent(); } return $this->getAttribute('value'); } /** * The content of options is not part of the page. * @return boolean True. * @access public */ function isPrivateContent() { return true; } } /** * Radio button. * @package SimpleTest * @subpackage WebTester */ class SimpleRadioButtonTag extends SimpleWidget { /** * Stashes the attributes. * @param array $attributes Hash of attributes. */ function __construct($attributes) { parent::__construct('input', $attributes); if ($this->getAttribute('value') === false) { $this->setAttribute('value', 'on'); } } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * The only allowed value sn the one in the * "value" attribute. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { if ($value === false) { return parent::setValue($value); } if ($value != $this->getAttribute('value')) { return false; } return parent::setValue($value); } /** * Accessor for starting value. * @return string Parsed value. * @access public */ function getDefault() { if ($this->getAttribute('checked') !== false) { return $this->getAttribute('value'); } return false; } } /** * Checkbox widget. * @package SimpleTest * @subpackage WebTester */ class SimpleCheckboxTag extends SimpleWidget { /** * Starts with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('input', $attributes); if ($this->getAttribute('value') === false) { $this->setAttribute('value', 'on'); } } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * The only allowed value in the one in the * "value" attribute. The default for this * attribute is "on". If this widget is set to * true, then the usual value will be taken. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { if ($value === false) { return parent::setValue($value); } if ($value === true) { return parent::setValue($this->getAttribute('value')); } if ($value != $this->getAttribute('value')) { return false; } return parent::setValue($value); } /** * Accessor for starting value. The default * value is "on". * @return string Parsed value. * @access public */ function getDefault() { if ($this->getAttribute('checked') !== false) { return $this->getAttribute('value'); } return false; } } /** * A group of multiple widgets with some shared behaviour. * @package SimpleTest * @subpackage WebTester */ class SimpleTagGroup { private $widgets = array(); /** * Adds a tag to the group. * @param SimpleWidget $widget * @access public */ function addWidget($widget) { $this->widgets[] = $widget; } /** * Accessor to widget set. * @return array All widgets. * @access protected */ protected function &getWidgets() { return $this->widgets; } /** * Accessor for an attribute. * @param string $label Attribute name. * @return boolean Always false. * @access public */ function getAttribute($label) { return false; } /** * Fetches the name for the widget from the first * member. * @return string Name of widget. * @access public */ function getName() { if (count($this->widgets) > 0) { return $this->widgets[0]->getName(); } } /** * Scans the widgets for one with the appropriate * ID field. * @param string $id ID value to try. * @return boolean True if matched. * @access public */ function isId($id) { for ($i = 0, $count = count($this->widgets); $i < $count; $i++) { if ($this->widgets[$i]->isId($id)) { return true; } } return false; } /** * Scans the widgets for one with the appropriate * attached label. * @param string $label Attached label to try. * @return boolean True if matched. * @access public */ function isLabel($label) { for ($i = 0, $count = count($this->widgets); $i < $count; $i++) { if ($this->widgets[$i]->isLabel($label)) { return true; } } return false; } /** * Dispatches the value into the form encoded packet. * @param SimpleEncoding $encoding Form packet. * @access public */ function write($encoding) { $encoding->add($this->getName(), $this->getValue()); } } /** * A group of tags with the same name within a form. * @package SimpleTest * @subpackage WebTester */ class SimpleCheckboxGroup extends SimpleTagGroup { /** * Accessor for current selected widget or false * if none. * @return string/array Widget values or false if none. * @access public */ function getValue() { $values = array(); $widgets = $this->getWidgets(); for ($i = 0, $count = count($widgets); $i < $count; $i++) { if ($widgets[$i]->getValue() !== false) { $values[] = $widgets[$i]->getValue(); } } return $this->coerceValues($values); } /** * Accessor for starting value that is active. * @return string/array Widget values or false if none. * @access public */ function getDefault() { $values = array(); $widgets = $this->getWidgets(); for ($i = 0, $count = count($widgets); $i < $count; $i++) { if ($widgets[$i]->getDefault() !== false) { $values[] = $widgets[$i]->getDefault(); } } return $this->coerceValues($values); } /** * Accessor for current set values. * @param string/array/boolean $values Either a single string, a * hash or false for nothing set. * @return boolean True if all values can be set. * @access public */ function setValue($values) { $values = $this->makeArray($values); if (! $this->valuesArePossible($values)) { return false; } $widgets = $this->getWidgets(); for ($i = 0, $count = count($widgets); $i < $count; $i++) { $possible = $widgets[$i]->getAttribute('value'); if (in_array($widgets[$i]->getAttribute('value'), $values)) { $widgets[$i]->setValue($possible); } else { $widgets[$i]->setValue(false); } } return true; } /** * Tests to see if a possible value set is legal. * @param string/array/boolean $values Either a single string, a * hash or false for nothing set. * @return boolean False if trying to set a * missing value. * @access private */ protected function valuesArePossible($values) { $matches = array(); $widgets = &$this->getWidgets(); for ($i = 0, $count = count($widgets); $i < $count; $i++) { $possible = $widgets[$i]->getAttribute('value'); if (in_array($possible, $values)) { $matches[] = $possible; } } return ($values == $matches); } /** * Converts the output to an appropriate format. This means * that no values is false, a single value is just that * value and only two or more are contained in an array. * @param array $values List of values of widgets. * @return string/array/boolean Expected format for a tag. * @access private */ protected function coerceValues($values) { if (count($values) == 0) { return false; } elseif (count($values) == 1) { return $values[0]; } else { return $values; } } /** * Converts false or string into array. The opposite of * the coercian method. * @param string/array/boolean $value A single item is converted * to a one item list. False * gives an empty list. * @return array List of values, possibly empty. * @access private */ protected function makeArray($value) { if ($value === false) { return array(); } if (is_string($value)) { return array($value); } return $value; } } /** * A group of tags with the same name within a form. * Used for radio buttons. * @package SimpleTest * @subpackage WebTester */ class SimpleRadioGroup extends SimpleTagGroup { /** * Each tag is tried in turn until one is * successfully set. The others will be * unchecked if successful. * @param string $value New value. * @return boolean True if any allowed. * @access public */ function setValue($value) { if (! $this->valueIsPossible($value)) { return false; } $index = false; $widgets = $this->getWidgets(); for ($i = 0, $count = count($widgets); $i < $count; $i++) { if (! $widgets[$i]->setValue($value)) { $widgets[$i]->setValue(false); } } return true; } /** * Tests to see if a value is allowed. * @param string Attempted value. * @return boolean True if a valid value. * @access private */ protected function valueIsPossible($value) { $widgets = $this->getWidgets(); for ($i = 0, $count = count($widgets); $i < $count; $i++) { if ($widgets[$i]->getAttribute('value') == $value) { return true; } } return false; } /** * Accessor for current selected widget or false * if none. * @return string/boolean Value attribute or * content of opton. * @access public */ function getValue() { $widgets = $this->getWidgets(); for ($i = 0, $count = count($widgets); $i < $count; $i++) { if ($widgets[$i]->getValue() !== false) { return $widgets[$i]->getValue(); } } return false; } /** * Accessor for starting value that is active. * @return string/boolean Value of first checked * widget or false if none. * @access public */ function getDefault() { $widgets = $this->getWidgets(); for ($i = 0, $count = count($widgets); $i < $count; $i++) { if ($widgets[$i]->getDefault() !== false) { return $widgets[$i]->getDefault(); } } return false; } } /** * Tag to keep track of labels. * @package SimpleTest * @subpackage WebTester */ class SimpleLabelTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('label', $attributes); } /** * Access for the ID to attach the label to. * @return string For attribute. * @access public */ function getFor() { return $this->getAttribute('for'); } } /** * Tag to aid parsing the form. * @package SimpleTest * @subpackage WebTester */ class SimpleFormTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('form', $attributes); } } /** * Tag to aid parsing the frames in a page. * @package SimpleTest * @subpackage WebTester */ class SimpleFrameTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function __construct($attributes) { parent::__construct('frame', $attributes); } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } } ?> Swift-4.2.1/test-suite/lib/simpletest/test_case.php 100644 0 0 51360 12000050366 17506 0 ustar 0 0 label = $label; } } /** * Accessor for the test name for subclasses. * @return string Name of the test. * @access public */ function getLabel() { return $this->label ? $this->label : get_class($this); } /** * This is a placeholder for skipping tests. In this * method you place skipIf() and skipUnless() calls to * set the skipping state. * @access public */ function skip() { } /** * Will issue a message to the reporter and tell the test * case to skip if the incoming flag is true. * @param string $should_skip Condition causing the tests to be skipped. * @param string $message Text of skip condition. * @access public */ function skipIf($should_skip, $message = '%s') { if ($should_skip && ! $this->should_skip) { $this->should_skip = true; $message = sprintf($message, 'Skipping [' . get_class($this) . ']'); $this->reporter->paintSkip($message . $this->getAssertionLine()); } } /** * Accessor for the private variable $_shoud_skip * @access public */ function shouldSkip() { return $this->should_skip; } /** * Will issue a message to the reporter and tell the test * case to skip if the incoming flag is false. * @param string $shouldnt_skip Condition causing the tests to be run. * @param string $message Text of skip condition. * @access public */ function skipUnless($shouldnt_skip, $message = false) { $this->skipIf(! $shouldnt_skip, $message); } /** * Used to invoke the single tests. * @return SimpleInvoker Individual test runner. * @access public */ function createInvoker() { return new SimpleExceptionTrappingInvoker( new SimpleErrorTrappingInvoker(new SimpleInvoker($this))); } /** * Uses reflection to run every method within itself * starting with the string "test" unless a method * is specified. * @param SimpleReporter $reporter Current test reporter. * @return boolean True if all tests passed. * @access public */ function run($reporter) { $context = SimpleTest::getContext(); $context->setTest($this); $context->setReporter($reporter); $this->reporter = $reporter; $started = false; foreach ($this->getTests() as $method) { if ($reporter->shouldInvoke($this->getLabel(), $method)) { $this->skip(); if ($this->should_skip) { break; } if (! $started) { $reporter->paintCaseStart($this->getLabel()); $started = true; } $invoker = $this->reporter->createInvoker($this->createInvoker()); $invoker->before($method); $invoker->invoke($method); $invoker->after($method); } } if ($started) { $reporter->paintCaseEnd($this->getLabel()); } unset($this->reporter); return $reporter->getStatus(); } /** * Gets a list of test names. Normally that will * be all internal methods that start with the * name "test". This method should be overridden * if you want a different rule. * @return array List of test names. * @access public */ function getTests() { $methods = array(); foreach (get_class_methods(get_class($this)) as $method) { if ($this->isTest($method)) { $methods[] = $method; } } return $methods; } /** * Tests to see if the method is a test that should * be run. Currently any method that starts with 'test' * is a candidate unless it is the constructor. * @param string $method Method name to try. * @return boolean True if test method. * @access protected */ protected function isTest($method) { if (strtolower(substr($method, 0, 4)) == 'test') { return ! SimpleTestCompatibility::isA($this, strtolower($method)); } return false; } /** * Announces the start of the test. * @param string $method Test method just started. * @access public */ function before($method) { $this->reporter->paintMethodStart($method); $this->observers = array(); } /** * Sets up unit test wide variables at the start * of each test method. To be overridden in * actual user test cases. * @access public */ function setUp() { } /** * Clears the data set in the setUp() method call. * To be overridden by the user in actual user test cases. * @access public */ function tearDown() { } /** * Announces the end of the test. Includes private clean up. * @param string $method Test method just finished. * @access public */ function after($method) { for ($i = 0; $i < count($this->observers); $i++) { $this->observers[$i]->atTestEnd($method, $this); } $this->reporter->paintMethodEnd($method); } /** * Sets up an observer for the test end. * @param object $observer Must have atTestEnd() * method. * @access public */ function tell($observer) { $this->observers[] = &$observer; } /** * @deprecated */ function pass($message = "Pass") { if (! isset($this->reporter)) { trigger_error('Can only make assertions within test methods'); } $this->reporter->paintPass( $message . $this->getAssertionLine()); return true; } /** * Sends a fail event with a message. * @param string $message Message to send. * @access public */ function fail($message = "Fail") { if (! isset($this->reporter)) { trigger_error('Can only make assertions within test methods'); } $this->reporter->paintFail( $message . $this->getAssertionLine()); return false; } /** * Formats a PHP error and dispatches it to the * reporter. * @param integer $severity PHP error code. * @param string $message Text of error. * @param string $file File error occoured in. * @param integer $line Line number of error. * @access public */ function error($severity, $message, $file, $line) { if (! isset($this->reporter)) { trigger_error('Can only make assertions within test methods'); } $this->reporter->paintError( "Unexpected PHP error [$message] severity [$severity] in [$file line $line]"); } /** * Formats an exception and dispatches it to the * reporter. * @param Exception $exception Object thrown. * @access public */ function exception($exception) { $this->reporter->paintException($exception); } /** * For user defined expansion of the available messages. * @param string $type Tag for sorting the signals. * @param mixed $payload Extra user specific information. */ function signal($type, $payload) { if (! isset($this->reporter)) { trigger_error('Can only make assertions within test methods'); } $this->reporter->paintSignal($type, $payload); } /** * Runs an expectation directly, for extending the * tests with new expectation classes. * @param SimpleExpectation $expectation Expectation subclass. * @param mixed $compare Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assert($expectation, $compare, $message = '%s') { if ($expectation->test($compare)) { return $this->pass(sprintf( $message, $expectation->overlayMessage($compare, $this->reporter->getDumper()))); } else { return $this->fail(sprintf( $message, $expectation->overlayMessage($compare, $this->reporter->getDumper()))); } } /** * Uses a stack trace to find the line of an assertion. * @return string Line number of first assert* * method embedded in format string. * @access public */ function getAssertionLine() { $trace = new SimpleStackTrace(array('assert', 'expect', 'pass', 'fail', 'skip')); return $trace->traceMethod(); } /** * Sends a formatted dump of a variable to the * test suite for those emergency debugging * situations. * @param mixed $variable Variable to display. * @param string $message Message to display. * @return mixed The original variable. * @access public */ function dump($variable, $message = false) { $dumper = $this->reporter->getDumper(); $formatted = $dumper->dump($variable); if ($message) { $formatted = $message . "\n" . $formatted; } $this->reporter->paintFormattedMessage($formatted); return $variable; } /** * Accessor for the number of subtests including myelf. * @return integer Number of test cases. * @access public */ function getSize() { return 1; } } /** * Helps to extract test cases automatically from a file. */ class SimpleFileLoader { /** * Builds a test suite from a library of test cases. * The new suite is composed into this one. * @param string $test_file File name of library with * test case classes. * @return TestSuite The new test suite. * @access public */ function load($test_file) { $existing_classes = get_declared_classes(); $existing_globals = get_defined_vars(); include_once($test_file); $new_globals = get_defined_vars(); $this->makeFileVariablesGlobal($existing_globals, $new_globals); $new_classes = array_diff(get_declared_classes(), $existing_classes); if (empty($new_classes)) { $new_classes = $this->scrapeClassesFromFile($test_file); } $classes = $this->selectRunnableTests($new_classes); return $this->createSuiteFromClasses($test_file, $classes); } /** * Imports new variables into the global namespace. * @param hash $existing Variables before the file was loaded. * @param hash $new Variables after the file was loaded. * @access private */ protected function makeFileVariablesGlobal($existing, $new) { $globals = array_diff(array_keys($new), array_keys($existing)); foreach ($globals as $global) { $_GLOBALS[$global] = $new[$global]; } } /** * Lookup classnames from file contents, in case the * file may have been included before. * Note: This is probably too clever by half. Figuring this * out after a failed test case is going to be tricky for us, * never mind the user. A test case should not be included * twice anyway. * @param string $test_file File name with classes. * @access private */ protected function scrapeClassesFromFile($test_file) { preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi', file_get_contents($test_file), $matches ); return $matches[1]; } /** * Calculates the incoming test cases. Skips abstract * and ignored classes. * @param array $candidates Candidate classes. * @return array New classes which are test * cases that shouldn't be ignored. * @access public */ function selectRunnableTests($candidates) { $classes = array(); foreach ($candidates as $class) { if (TestSuite::getBaseTestCase($class)) { $reflection = new SimpleReflection($class); if ($reflection->isAbstract()) { SimpleTest::ignore($class); } else { $classes[] = $class; } } } return $classes; } /** * Builds a test suite from a class list. * @param string $title Title of new group. * @param array $classes Test classes. * @return TestSuite Group loaded with the new * test cases. * @access public */ function createSuiteFromClasses($title, $classes) { if (count($classes) == 0) { $suite = new BadTestSuite($title, "No runnable test cases in [$title]"); return $suite; } SimpleTest::ignoreParentsIfIgnored($classes); $suite = new TestSuite($title); foreach ($classes as $class) { if (! SimpleTest::isIgnored($class)) { $suite->add($class); } } return $suite; } } /** * This is a composite test class for combining * test cases and other RunnableTest classes into * a group test. * @package SimpleTest * @subpackage UnitTester */ class TestSuite { private $label; private $test_cases; /** * Sets the name of the test suite. * @param string $label Name sent at the start and end * of the test. * @access public */ function TestSuite($label = false) { $this->label = $label; $this->test_cases = array(); } /** * Accessor for the test name for subclasses. If the suite * wraps a single test case the label defaults to the name of that test. * @return string Name of the test. * @access public */ function getLabel() { if (! $this->label) { return ($this->getSize() == 1) ? get_class($this->test_cases[0]) : get_class($this); } else { return $this->label; } } /** * Adds a test into the suite by instance or class. The class will * be instantiated if it's a test suite. * @param SimpleTestCase $test_case Suite or individual test * case implementing the * runnable test interface. * @access public */ function add($test_case) { if (! is_string($test_case)) { $this->test_cases[] = $test_case; } elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') { $this->test_cases[] = new $test_case(); } else { $this->test_cases[] = $test_case; } } /** * Builds a test suite from a library of test cases. * The new suite is composed into this one. * @param string $test_file File name of library with * test case classes. * @access public */ function addFile($test_file) { $extractor = new SimpleFileLoader(); $this->add($extractor->load($test_file)); } /** * Delegates to a visiting collector to add test * files. * @param string $path Path to scan from. * @param SimpleCollector $collector Directory scanner. * @access public */ function collect($path, $collector) { $collector->collect($this, $path); } /** * Invokes run() on all of the held test cases, instantiating * them if necessary. * @param SimpleReporter $reporter Current test reporter. * @access public */ function run($reporter) { $reporter->paintGroupStart($this->getLabel(), $this->getSize()); for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) { if (is_string($this->test_cases[$i])) { $class = $this->test_cases[$i]; $test = new $class(); $test->run($reporter); unset($test); } else { $this->test_cases[$i]->run($reporter); } } $reporter->paintGroupEnd($this->getLabel()); return $reporter->getStatus(); } /** * Number of contained test cases. * @return integer Total count of cases in the group. * @access public */ function getSize() { $count = 0; foreach ($this->test_cases as $case) { if (is_string($case)) { if (! SimpleTest::isIgnored($case)) { $count++; } } else { $count += $case->getSize(); } } return $count; } /** * Test to see if a class is derived from the * SimpleTestCase class. * @param string $class Class name. * @access public */ static function getBaseTestCase($class) { while ($class = get_parent_class($class)) { $class = strtolower($class); if ($class == 'simpletestcase' || $class == 'testsuite') { return $class; } } return false; } } /** * This is a failing group test for when a test suite hasn't * loaded properly. * @package SimpleTest * @subpackage UnitTester */ class BadTestSuite { private $label; private $error; /** * Sets the name of the test suite and error message. * @param string $label Name sent at the start and end * of the test. * @access public */ function BadTestSuite($label, $error) { $this->label = $label; $this->error = $error; } /** * Accessor for the test name for subclasses. * @return string Name of the test. * @access public */ function getLabel() { return $this->label; } /** * Sends a single error to the reporter. * @param SimpleReporter $reporter Current test reporter. * @access public */ function run($reporter) { $reporter->paintGroupStart($this->getLabel(), $this->getSize()); $reporter->paintFail('Bad TestSuite [' . $this->getLabel() . '] with error [' . $this->error . ']'); $reporter->paintGroupEnd($this->getLabel()); return $reporter->getStatus(); } /** * Number of contained test cases. Always zero. * @return integer Total count of cases in the group. * @access public */ function getSize() { return 0; } } ?> Swift-4.2.1/test-suite/lib/simpletest/unit_tester.php 100644 0 0 35411 12000050366 20100 0 ustar 0 0 assert(new TrueExpectation(), $result, $message); } /** * Will be true on false and vice versa. False * is the PHP definition of false, so that null, * empty strings, zero and an empty array all count * as false. * @param boolean $result Pass on false. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertFalse($result, $message = '%s') { return $this->assert(new FalseExpectation(), $result, $message); } /** * Will be true if the value is null. * @param null $value Supposedly null value. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertNull($value, $message = '%s') { $dumper = new SimpleDumper(); $message = sprintf( $message, '[' . $dumper->describeValue($value) . '] should be null'); return $this->assertTrue(! isset($value), $message); } /** * Will be true if the value is set. * @param mixed $value Supposedly set value. * @param string $message Message to display. * @return boolean True on pass. * @access public */ function assertNotNull($value, $message = '%s') { $dumper = new SimpleDumper(); $message = sprintf( $message, '[' . $dumper->describeValue($value) . '] should not be null'); return $this->assertTrue(isset($value), $message); } /** * Type and class test. Will pass if class * matches the type name or is a subclass or * if not an object, but the type is correct. * @param mixed $object Object to test. * @param string $type Type name as string. * @param string $message Message to display. * @return boolean True on pass. * @access public */ function assertIsA($object, $type, $message = '%s') { return $this->assert( new IsAExpectation($type), $object, $message); } /** * Type and class mismatch test. Will pass if class * name or underling type does not match the one * specified. * @param mixed $object Object to test. * @param string $type Type name as string. * @param string $message Message to display. * @return boolean True on pass. * @access public */ function assertNotA($object, $type, $message = '%s') { return $this->assert( new NotAExpectation($type), $object, $message); } /** * Will trigger a pass if the two parameters have * the same value only. Otherwise a fail. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertEqual($first, $second, $message = '%s') { return $this->assert( new EqualExpectation($first), $second, $message); } /** * Will trigger a pass if the two parameters have * a different value. Otherwise a fail. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertNotEqual($first, $second, $message = '%s') { return $this->assert( new NotEqualExpectation($first), $second, $message); } /** * Will trigger a pass if the if the first parameter * is near enough to the second by the margin. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param mixed $margin Fuzziness of match. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertWithinMargin($first, $second, $margin, $message = '%s') { return $this->assert( new WithinMarginExpectation($first, $margin), $second, $message); } /** * Will trigger a pass if the two parameters differ * by more than the margin. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param mixed $margin Fuzziness of match. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertOutsideMargin($first, $second, $margin, $message = '%s') { return $this->assert( new OutsideMarginExpectation($first, $margin), $second, $message); } /** * Will trigger a pass if the two parameters have * the same value and same type. Otherwise a fail. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertIdentical($first, $second, $message = '%s') { return $this->assert( new IdenticalExpectation($first), $second, $message); } /** * Will trigger a pass if the two parameters have * the different value or different type. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertNotIdentical($first, $second, $message = '%s') { return $this->assert( new NotIdenticalExpectation($first), $second, $message); } /** * Will trigger a pass if both parameters refer * to the same object or value. Fail otherwise. * This will cause problems testing objects under * E_STRICT. * TODO: Replace with expectation. * @param mixed $first Reference to check. * @param mixed $second Hopefully the same variable. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertReference(&$first, &$second, $message = '%s') { $dumper = new SimpleDumper(); $message = sprintf( $message, '[' . $dumper->describeValue($first) . '] and [' . $dumper->describeValue($second) . '] should reference the same object'); return $this->assertTrue( SimpleTestCompatibility::isReference($first, $second), $message); } /** * Will trigger a pass if both parameters refer * to the same object. Fail otherwise. This has * the same semantics at the PHPUnit assertSame. * That is, if values are passed in it has roughly * the same affect as assertIdentical. * TODO: Replace with expectation. * @param mixed $first Object reference to check. * @param mixed $second Hopefully the same object. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertSame($first, $second, $message = '%s') { $dumper = new SimpleDumper(); $message = sprintf( $message, '[' . $dumper->describeValue($first) . '] and [' . $dumper->describeValue($second) . '] should reference the same object'); return $this->assertTrue($first === $second, $message); } /** * Will trigger a pass if both parameters refer * to different objects. Fail otherwise. The objects * have to be identical though. * @param mixed $first Object reference to check. * @param mixed $second Hopefully not the same object. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertClone($first, $second, $message = '%s') { $dumper = new SimpleDumper(); $message = sprintf( $message, '[' . $dumper->describeValue($first) . '] and [' . $dumper->describeValue($second) . '] should not be the same object'); $identical = new IdenticalExpectation($first); return $this->assertTrue( $identical->test($second) && ! ($first === $second), $message); } /** * Will trigger a pass if both parameters refer * to different variables. Fail otherwise. The objects * have to be identical references though. * This will fail under E_STRICT with objects. Use * assertClone() for this. * @param mixed $first Object reference to check. * @param mixed $second Hopefully not the same object. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertCopy(&$first, &$second, $message = "%s") { $dumper = new SimpleDumper(); $message = sprintf( $message, "[" . $dumper->describeValue($first) . "] and [" . $dumper->describeValue($second) . "] should not be the same object"); return $this->assertFalse( SimpleTestCompatibility::isReference($first, $second), $message); } /** * Will trigger a pass if the Perl regex pattern * is found in the subject. Fail otherwise. * @param string $pattern Perl regex to look for including * the regex delimiters. * @param string $subject String to search in. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertPattern($pattern, $subject, $message = '%s') { return $this->assert( new PatternExpectation($pattern), $subject, $message); } /** * Will trigger a pass if the perl regex pattern * is not present in subject. Fail if found. * @param string $pattern Perl regex to look for including * the regex delimiters. * @param string $subject String to search in. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertNoPattern($pattern, $subject, $message = '%s') { return $this->assert( new NoPatternExpectation($pattern), $subject, $message); } /** * Prepares for an error. If the error mismatches it * passes through, otherwise it is swallowed. Any * left over errors trigger failures. * @param SimpleExpectation/string $expected The error to match. * @param string $message Message on failure. * @access public */ function expectError($expected = false, $message = '%s') { $queue = SimpleTest::getContext()->get('SimpleErrorQueue'); $queue->expectError($this->coerceExpectation($expected), $message); } /** * Prepares for an exception. If the error mismatches it * passes through, otherwise it is swallowed. Any * left over errors trigger failures. * @param SimpleExpectation/Exception $expected The error to match. * @param string $message Message on failure. * @access public */ function expectException($expected = false, $message = '%s') { $queue = SimpleTest::getContext()->get('SimpleExceptionTrap'); $line = $this->getAssertionLine(); $queue->expectException($expected, $message . $line); } /** * Creates an equality expectation if the * object/value is not already some type * of expectation. * @param mixed $expected Expected value. * @return SimpleExpectation Expectation object. * @access private */ protected function coerceExpectation($expected) { if ($expected == false) { return new TrueExpectation(); } if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) { return $expected; } return new EqualExpectation( is_string($expected) ? str_replace('%', '%%', $expected) : $expected); } } ?> Swift-4.2.1/test-suite/lib/simpletest/url.php 100644 0 0 42556 12000050366 16345 0 ustar 0 0 chompCoordinates($url); $this->setCoordinates($x, $y); $this->scheme = $this->chompScheme($url); if ($this->scheme === 'file') { // Unescaped backslashes not used in directory separator context // will get caught by this, but they should have been urlencoded // anyway so we don't care. If this ends up being a problem, the // host regexp must be modified to match for backslashes when // the scheme is file. $url = str_replace('\\', '/', $url); } list($this->username, $this->password) = $this->chompLogin($url); $this->host = $this->chompHost($url); $this->port = false; if (preg_match('/(.*?):(.*)/', $this->host, $host_parts)) { if ($this->scheme === 'file' && strlen($this->host) === 2) { // DOS drive was placed in authority; promote it to path. $url = '/' . $this->host . $url; $this->host = false; } else { $this->host = $host_parts[1]; $this->port = (integer)$host_parts[2]; } } $this->path = $this->chompPath($url); $this->request = $this->parseRequest($this->chompRequest($url)); $this->fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false); $this->target = false; } /** * Extracts the X, Y coordinate pair from an image map. * @param string $url URL so far. The coordinates will be * removed. * @return array X, Y as a pair of integers. * @access private */ protected function chompCoordinates(&$url) { if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) { $url = $matches[1]; return array((integer)$matches[2], (integer)$matches[3]); } return array(false, false); } /** * Extracts the scheme part of an incoming URL. * @param string $url URL so far. The scheme will be * removed. * @return string Scheme part or false. * @access private */ protected function chompScheme(&$url) { if (preg_match('#^([^/:]*):(//)(.*)#', $url, $matches)) { $url = $matches[2] . $matches[3]; return $matches[1]; } return false; } /** * Extracts the username and password from the * incoming URL. The // prefix will be reattached * to the URL after the doublet is extracted. * @param string $url URL so far. The username and * password are removed. * @return array Two item list of username and * password. Will urldecode() them. * @access private */ protected function chompLogin(&$url) { $prefix = ''; if (preg_match('#^(//)(.*)#', $url, $matches)) { $prefix = $matches[1]; $url = $matches[2]; } if (preg_match('#^([^/]*)@(.*)#', $url, $matches)) { $url = $prefix . $matches[2]; $parts = split(":", $matches[1]); return array( urldecode($parts[0]), isset($parts[1]) ? urldecode($parts[1]) : false); } $url = $prefix . $url; return array(false, false); } /** * Extracts the host part of an incoming URL. * Includes the port number part. Will extract * the host if it starts with // or it has * a top level domain or it has at least two * dots. * @param string $url URL so far. The host will be * removed. * @return string Host part guess or false. * @access private */ protected function chompHost(&$url) { if (preg_match('!^(//)(.*?)(/.*|\?.*|#.*|$)!', $url, $matches)) { $url = $matches[3]; return $matches[2]; } if (preg_match('!(.*?)(\.\./|\./|/|\?|#|$)(.*)!', $url, $matches)) { $tlds = SimpleUrl::getAllTopLevelDomains(); if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) { $url = $matches[2] . $matches[3]; return $matches[1]; } elseif (preg_match('/[a-z0-9\-]+\.[a-z0-9\-]+\.[a-z0-9\-]+/i', $matches[1])) { $url = $matches[2] . $matches[3]; return $matches[1]; } } return false; } /** * Extracts the path information from the incoming * URL. Strips this path from the URL. * @param string $url URL so far. The host will be * removed. * @return string Path part or '/'. * @access private */ protected function chompPath(&$url) { if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) { $url = $matches[2] . $matches[3]; return ($matches[1] ? $matches[1] : ''); } return ''; } /** * Strips off the request data. * @param string $url URL so far. The request will be * removed. * @return string Raw request part. * @access private */ protected function chompRequest(&$url) { if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) { $url = $matches[2] . $matches[3]; return $matches[1]; } return ''; } /** * Breaks the request down into an object. * @param string $raw Raw request. * @return SimpleFormEncoding Parsed data. * @access private */ protected function parseRequest($raw) { $this->raw = $raw; $request = new SimpleGetEncoding(); foreach (split("&", $raw) as $pair) { if (preg_match('/(.*?)=(.*)/', $pair, $matches)) { $request->add($matches[1], urldecode($matches[2])); } elseif ($pair) { $request->add($pair, ''); } } return $request; } /** * Accessor for protocol part. * @param string $default Value to use if not present. * @return string Scheme name, e.g "http". * @access public */ function getScheme($default = false) { return $this->scheme ? $this->scheme : $default; } /** * Accessor for user name. * @return string Username preceding host. * @access public */ function getUsername() { return $this->username; } /** * Accessor for password. * @return string Password preceding host. * @access public */ function getPassword() { return $this->password; } /** * Accessor for hostname and port. * @param string $default Value to use if not present. * @return string Hostname only. * @access public */ function getHost($default = false) { return $this->host ? $this->host : $default; } /** * Accessor for top level domain. * @return string Last part of host. * @access public */ function getTld() { $path_parts = pathinfo($this->getHost()); return (isset($path_parts['extension']) ? $path_parts['extension'] : false); } /** * Accessor for port number. * @return integer TCP/IP port number. * @access public */ function getPort() { return $this->port; } /** * Accessor for path. * @return string Full path including leading slash if implied. * @access public */ function getPath() { if (! $this->path && $this->host) { return '/'; } return $this->path; } /** * Accessor for page if any. This may be a * directory name if ambiguious. * @return Page name. * @access public */ function getPage() { if (! preg_match('/([^\/]*?)$/', $this->getPath(), $matches)) { return false; } return $matches[1]; } /** * Gets the path to the page. * @return string Path less the page. * @access public */ function getBasePath() { if (! preg_match('/(.*\/)[^\/]*?$/', $this->getPath(), $matches)) { return false; } return $matches[1]; } /** * Accessor for fragment at end of URL after the "#". * @return string Part after "#". * @access public */ function getFragment() { return $this->fragment; } /** * Sets image coordinates. Set to false to clear * them. * @param integer $x Horizontal position. * @param integer $y Vertical position. * @access public */ function setCoordinates($x = false, $y = false) { if (($x === false) || ($y === false)) { $this->x = $this->y = false; return; } $this->x = (integer)$x; $this->y = (integer)$y; } /** * Accessor for horizontal image coordinate. * @return integer X value. * @access public */ function getX() { return $this->x; } /** * Accessor for vertical image coordinate. * @return integer Y value. * @access public */ function getY() { return $this->y; } /** * Accessor for current request parameters * in URL string form. Will return teh original request * if at all possible even if it doesn't make much * sense. * @return string Form is string "?a=1&b=2", etc. * @access public */ function getEncodedRequest() { if ($this->raw) { $encoded = $this->raw; } else { $encoded = $this->request->asUrlRequest(); } if ($encoded) { return '?' . preg_replace('/^\?/', '', $encoded); } return ''; } /** * Adds an additional parameter to the request. * @param string $key Name of parameter. * @param string $value Value as string. * @access public */ function addRequestParameter($key, $value) { $this->raw = false; $this->request->add($key, $value); } /** * Adds additional parameters to the request. * @param hash/SimpleFormEncoding $parameters Additional * parameters. * @access public */ function addRequestParameters($parameters) { $this->raw = false; $this->request->merge($parameters); } /** * Clears down all parameters. * @access public */ function clearRequest() { $this->raw = false; $this->request = new SimpleGetEncoding(); } /** * Gets the frame target if present. Although * not strictly part of the URL specification it * acts as similarily to the browser. * @return boolean/string Frame name or false if none. * @access public */ function getTarget() { return $this->target; } /** * Attaches a frame target. * @param string $frame Name of frame. * @access public */ function setTarget($frame) { $this->raw = false; $this->target = $frame; } /** * Renders the URL back into a string. * @return string URL in canonical form. * @access public */ function asString() { $path = $this->path; $scheme = $identity = $host = $port = $encoded = $fragment = ''; if ($this->username && $this->password) { $identity = $this->username . ':' . $this->password . '@'; } if ($this->getHost()) { $scheme = $this->getScheme() ? $this->getScheme() : 'http'; $scheme .= '://'; $host = $this->getHost(); } elseif ($this->getScheme() === 'file') { // Safest way; otherwise, file URLs on Windows have an extra // leading slash. It might be possible to convert file:// // URIs to local file paths, but that requires more research. $scheme = 'file://'; } if ($this->getPort() && $this->getPort() != 80 ) { $port = ':'.$this->getPort(); } if (substr($this->path, 0, 1) == '/') { $path = $this->normalisePath($this->path); } $encoded = $this->getEncodedRequest(); $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); return "$scheme$identity$host$port$path$encoded$fragment$coords"; } /** * Replaces unknown sections to turn a relative * URL into an absolute one. The base URL can * be either a string or a SimpleUrl object. * @param string/SimpleUrl $base Base URL. * @access public */ function makeAbsolute($base) { if (! is_object($base)) { $base = new SimpleUrl($base); } if ($this->getHost()) { $scheme = $this->getScheme(); $host = $this->getHost(); $port = $this->getPort() ? ':' . $this->getPort() : ''; $identity = $this->getIdentity() ? $this->getIdentity() . '@' : ''; if (! $identity) { $identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; } } else { $scheme = $base->getScheme(); $host = $base->getHost(); $port = $base->getPort() ? ':' . $base->getPort() : ''; $identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; } $path = $this->normalisePath($this->extractAbsolutePath($base)); $encoded = $this->getEncodedRequest(); $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords"); } /** * Replaces unknown sections of the path with base parts * to return a complete absolute one. * @param string/SimpleUrl $base Base URL. * @param string Absolute path. * @access private */ protected function extractAbsolutePath($base) { if ($this->getHost()) { return $this->path; } if (! $this->isRelativePath($this->path)) { return $this->path; } if ($this->path) { return $base->getBasePath() . $this->path; } return $base->getPath(); } /** * Simple test to see if a path part is relative. * @param string $path Path to test. * @return boolean True if starts with a "/". * @access private */ protected function isRelativePath($path) { return (substr($path, 0, 1) != '/'); } /** * Extracts the username and password for use in rendering * a URL. * @return string/boolean Form of username:password or false. * @access public */ function getIdentity() { if ($this->username && $this->password) { return $this->username . ':' . $this->password; } return false; } /** * Replaces . and .. sections of the path. * @param string $path Unoptimised path. * @return string Path with dots removed if possible. * @access public */ function normalisePath($path) { $path = preg_replace('|/\./|', '/', $path); return preg_replace('|/[^/]+/\.\./|', '/', $path); } /** * A pipe seperated list of all TLDs that result in two part * domain names. * @return string Pipe separated list. * @access public */ static function getAllTopLevelDomains() { return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum'; } } ?> Swift-4.2.1/test-suite/lib/simpletest/user_agent.php 100644 0 0 26104 12000050366 17666 0 ustar 0 0 cookie_jar = new SimpleCookieJar(); $this->authenticator = new SimpleAuthenticator(); } /** * Removes expired and temporary cookies as if * the browser was closed and re-opened. Authorisation * has to be obtained again as well. * @param string/integer $date Time when session restarted. * If omitted then all persistent * cookies are kept. * @access public */ function restart($date = false) { $this->cookie_jar->restartSession($date); $this->authenticator->restartSession(); } /** * Adds a header to every fetch. * @param string $header Header line to add to every * request until cleared. * @access public */ function addHeader($header) { $this->additional_headers[] = $header; } /** * Ages the cookies by the specified time. * @param integer $interval Amount in seconds. * @access public */ function ageCookies($interval) { $this->cookie_jar->agePrematurely($interval); } /** * Sets an additional cookie. If a cookie has * the same name and path it is replaced. * @param string $name Cookie key. * @param string $value Value of cookie. * @param string $host Host upon which the cookie is valid. * @param string $path Cookie path if not host wide. * @param string $expiry Expiry date. * @access public */ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { $this->cookie_jar->setCookie($name, $value, $host, $path, $expiry); } /** * Reads the most specific cookie value from the * browser cookies. * @param string $host Host to search. * @param string $path Applicable path. * @param string $name Name of cookie to read. * @return string False if not present, else the * value as a string. * @access public */ function getCookieValue($host, $path, $name) { return $this->cookie_jar->getCookieValue($host, $path, $name); } /** * Reads the current cookies within the base URL. * @param string $name Key of cookie to find. * @param SimpleUrl $base Base URL to search from. * @return string/boolean Null if there is no base URL, false * if the cookie is not set. * @access public */ function getBaseCookieValue($name, $base) { if (! $base) { return null; } return $this->getCookieValue($base->getHost(), $base->getPath(), $name); } /** * Switches off cookie sending and recieving. * @access public */ function ignoreCookies() { $this->cookies_enabled = false; } /** * Switches back on the cookie sending and recieving. * @access public */ function useCookies() { $this->cookies_enabled = true; } /** * Sets the socket timeout for opening a connection. * @param integer $timeout Maximum time in seconds. * @access public */ function setConnectionTimeout($timeout) { $this->connection_timeout = $timeout; } /** * Sets the maximum number of redirects before * a page will be loaded anyway. * @param integer $max Most hops allowed. * @access public */ function setMaximumRedirects($max) { $this->max_redirects = $max; } /** * Sets proxy to use on all requests for when * testing from behind a firewall. Set URL * to false to disable. * @param string $proxy Proxy URL. * @param string $username Proxy username for authentication. * @param string $password Proxy password for authentication. * @access public */ function useProxy($proxy, $username, $password) { if (! $proxy) { $this->proxy = false; return; } if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) { $proxy = 'http://'. $proxy; } $this->proxy = new SimpleUrl($proxy); $this->proxy_username = $username; $this->proxy_password = $password; } /** * Test to see if the redirect limit is passed. * @param integer $redirects Count so far. * @return boolean True if over. * @access private */ protected function isTooManyRedirects($redirects) { return ($redirects > $this->max_redirects); } /** * Sets the identity for the current realm. * @param string $host Host to which realm applies. * @param string $realm Full name of realm. * @param string $username Username for realm. * @param string $password Password for realm. * @access public */ function setIdentity($host, $realm, $username, $password) { $this->authenticator->setIdentityForRealm($host, $realm, $username, $password); } /** * Fetches a URL as a response object. Will keep trying if redirected. * It will also collect authentication realm information. * @param string/SimpleUrl $url Target to fetch. * @param SimpleEncoding $encoding Additional parameters for request. * @return SimpleHttpResponse Hopefully the target page. * @access public */ function fetchResponse($url, $encoding) { if ($encoding->getMethod() != 'POST') { $url->addRequestParameters($encoding); $encoding->clear(); } $response = $this->fetchWhileRedirected($url, $encoding); if ($headers = $response->getHeaders()) { if ($headers->isChallenge()) { $this->authenticator->addRealm( $url, $headers->getAuthentication(), $headers->getRealm()); } } return $response; } /** * Fetches the page until no longer redirected or * until the redirect limit runs out. * @param SimpleUrl $url Target to fetch. * @param SimpelFormEncoding $encoding Additional parameters for request. * @return SimpleHttpResponse Hopefully the target page. * @access private */ protected function fetchWhileRedirected($url, $encoding) { $redirects = 0; do { $response = $this->fetch($url, $encoding); if ($response->isError()) { return $response; } $headers = $response->getHeaders(); $location = new SimpleUrl($headers->getLocation()); $url = $location->makeAbsolute($url); if ($this->cookies_enabled) { $headers->writeCookiesToJar($this->cookie_jar, $url); } if (! $headers->isRedirect()) { break; } $encoding = new SimpleGetEncoding(); } while (! $this->isTooManyRedirects(++$redirects)); return $response; } /** * Actually make the web request. * @param SimpleUrl $url Target to fetch. * @param SimpleFormEncoding $encoding Additional parameters for request. * @return SimpleHttpResponse Headers and hopefully content. * @access protected */ protected function fetch($url, $encoding) { $request = $this->createRequest($url, $encoding); return $request->fetch($this->connection_timeout); } /** * Creates a full page request. * @param SimpleUrl $url Target to fetch as url object. * @param SimpleFormEncoding $encoding POST/GET parameters. * @return SimpleHttpRequest New request. * @access private */ protected function createRequest($url, $encoding) { $request = $this->createHttpRequest($url, $encoding); $this->addAdditionalHeaders($request); if ($this->cookies_enabled) { $request->readCookiesFromJar($this->cookie_jar, $url); } $this->authenticator->addHeaders($request, $url); return $request; } /** * Builds the appropriate HTTP request object. * @param SimpleUrl $url Target to fetch as url object. * @param SimpleFormEncoding $parameters POST/GET parameters. * @return SimpleHttpRequest New request object. * @access protected */ protected function createHttpRequest($url, $encoding) { return new SimpleHttpRequest($this->createRoute($url), $encoding); } /** * Sets up either a direct route or via a proxy. * @param SimpleUrl $url Target to fetch as url object. * @return SimpleRoute Route to take to fetch URL. * @access protected */ protected function createRoute($url) { if ($this->proxy) { return new SimpleProxyRoute( $url, $this->proxy, $this->proxy_username, $this->proxy_password); } return new SimpleRoute($url); } /** * Adds additional manual headers. * @param SimpleHttpRequest $request Outgoing request. * @access private */ protected function addAdditionalHeaders(&$request) { foreach ($this->additional_headers as $header) { $request->addHeaderLine($header); } } } ?> Swift-4.2.1/test-suite/lib/simpletest/web_tester.php 100644 0 0 150436 12000050366 17723 0 ustar 0 0 value = $value; } /** * Tests the expectation. True if it matches * a string value or an array value in any order. * @param mixed $compare Comparison value. False for * an unset field. * @return boolean True if correct. * @access public */ function test($compare) { if ($this->value === false) { return ($compare === false); } if ($this->isSingle($this->value)) { return $this->testSingle($compare); } if (is_array($this->value)) { return $this->testMultiple($compare); } return false; } /** * Tests for valid field comparisons with a single option. * @param mixed $value Value to type check. * @return boolean True if integer, string or float. * @access private */ protected function isSingle($value) { return is_string($value) || is_integer($value) || is_float($value); } /** * String comparison for simple field with a single option. * @param mixed $compare String to test against. * @returns boolean True if matching. * @access private */ protected function testSingle($compare) { if (is_array($compare) && count($compare) == 1) { $compare = $compare[0]; } if (! $this->isSingle($compare)) { return false; } return ($this->value == $compare); } /** * List comparison for multivalue field. * @param mixed $compare List in any order to test against. * @returns boolean True if matching. * @access private */ protected function testMultiple($compare) { if (is_string($compare)) { $compare = array($compare); } if (! is_array($compare)) { return false; } sort($compare); return ($this->value === $compare); } /** * Returns a human readable test message. * @param mixed $compare Comparison value. * @return string Description of success * or failure. * @access public */ function testMessage($compare) { $dumper = $this->getDumper(); if (is_array($compare)) { sort($compare); } if ($this->test($compare)) { return "Field expectation [" . $dumper->describeValue($this->value) . "]"; } else { return "Field expectation [" . $dumper->describeValue($this->value) . "] fails with [" . $dumper->describeValue($compare) . "] " . $dumper->describeDifference($this->value, $compare); } } } /** * Test for a specific HTTP header within a header block. * @package SimpleTest * @subpackage WebTester */ class HttpHeaderExpectation extends SimpleExpectation { private $expected_header; private $expected_value; /** * Sets the field and value to compare against. * @param string $header Case insenstive trimmed header name. * @param mixed $value Optional value to compare. If not * given then any value will match. If * an expectation object then that will * be used instead. * @param string $message Optiona message override. Can use %s as * a placeholder for the original message. */ function __construct($header, $value = false, $message = '%s') { parent::__construct($message); $this->expected_header = $this->normaliseHeader($header); $this->expected_value = $value; } /** * Accessor for aggregated object. * @return mixed Expectation set in constructor. * @access protected */ protected function getExpectation() { return $this->expected_value; } /** * Removes whitespace at ends and case variations. * @param string $header Name of header. * @param string Trimmed and lowecased header * name. * @access private */ protected function normaliseHeader($header) { return strtolower(trim($header)); } /** * Tests the expectation. True if it matches * a string value or an array value in any order. * @param mixed $compare Raw header block to search. * @return boolean True if header present. * @access public */ function test($compare) { return is_string($this->findHeader($compare)); } /** * Searches the incoming result. Will extract the matching * line as text. * @param mixed $compare Raw header block to search. * @return string Matching header line. * @access protected */ protected function findHeader($compare) { $lines = split("\r\n", $compare); foreach ($lines as $line) { if ($this->testHeaderLine($line)) { return $line; } } return false; } /** * Compares a single header line against the expectation. * @param string $line A single line to compare. * @return boolean True if matched. * @access private */ protected function testHeaderLine($line) { if (count($parsed = split(':', $line, 2)) < 2) { return false; } list($header, $value) = $parsed; if ($this->normaliseHeader($header) != $this->expected_header) { return false; } return $this->testHeaderValue($value, $this->expected_value); } /** * Tests the value part of the header. * @param string $value Value to test. * @param mixed $expected Value to test against. * @return boolean True if matched. * @access protected */ protected function testHeaderValue($value, $expected) { if ($expected === false) { return true; } if (SimpleExpectation::isExpectation($expected)) { return $expected->test(trim($value)); } return (trim($value) == trim($expected)); } /** * Returns a human readable test message. * @param mixed $compare Raw header block to search. * @return string Description of success * or failure. * @access public */ function testMessage($compare) { if (SimpleExpectation::isExpectation($this->expected_value)) { $message = $this->expected_value->overlayMessage($compare, $this->getDumper()); } else { $message = $this->expected_header . ($this->expected_value ? ': ' . $this->expected_value : ''); } if (is_string($line = $this->findHeader($compare))) { return "Searching for header [$message] found [$line]"; } else { return "Failed to find header [$message]"; } } } /** * Test for a specific HTTP header within a header block that * should not be found. * @package SimpleTest * @subpackage WebTester */ class NoHttpHeaderExpectation extends HttpHeaderExpectation { private $expected_header; private $expected_value; /** * Sets the field and value to compare against. * @param string $unwanted Case insenstive trimmed header name. * @param string $message Optiona message override. Can use %s as * a placeholder for the original message. */ function __construct($unwanted, $message = '%s') { parent::__construct($unwanted, false, $message); } /** * Tests that the unwanted header is not found. * @param mixed $compare Raw header block to search. * @return boolean True if header present. * @access public */ function test($compare) { return ($this->findHeader($compare) === false); } /** * Returns a human readable test message. * @param mixed $compare Raw header block to search. * @return string Description of success * or failure. * @access public */ function testMessage($compare) { $expectation = $this->getExpectation(); if (is_string($line = $this->findHeader($compare))) { return "Found unwanted header [$expectation] with [$line]"; } else { return "Did not find unwanted header [$expectation]"; } } } /** * Test for a text substring. * @package SimpleTest * @subpackage UnitTester */ class TextExpectation extends SimpleExpectation { private $substring; /** * Sets the value to compare against. * @param string $substring Text to search for. * @param string $message Customised message on failure. * @access public */ function __construct($substring, $message = '%s') { parent::__construct($message); $this->substring = $substring; } /** * Accessor for the substring. * @return string Text to match. * @access protected */ protected function getSubstring() { return $this->substring; } /** * Tests the expectation. True if the text contains the * substring. * @param string $compare Comparison value. * @return boolean True if correct. * @access public */ function test($compare) { return (strpos($compare, $this->substring) !== false); } /** * Returns a human readable test message. * @param mixed $compare Comparison value. * @return string Description of success * or failure. * @access public */ function testMessage($compare) { if ($this->test($compare)) { return $this->describeTextMatch($this->getSubstring(), $compare); } else { $dumper = $this->getDumper(); return "Text [" . $this->getSubstring() . "] not detected in [" . $dumper->describeValue($compare) . "]"; } } /** * Describes a pattern match including the string * found and it's position. * @param string $substring Text to search for. * @param string $subject Subject to search. * @access protected */ protected function describeTextMatch($substring, $subject) { $position = strpos($subject, $substring); $dumper = $this->getDumper(); return "Text [$substring] detected at character [$position] in [" . $dumper->describeValue($subject) . "] in region [" . $dumper->clipString($subject, 100, $position) . "]"; } } /** * Fail if a substring is detected within the * comparison text. * @package SimpleTest * @subpackage UnitTester */ class NoTextExpectation extends TextExpectation { /** * Sets the reject pattern * @param string $substring Text to search for. * @param string $message Customised message on failure. * @access public */ function __construct($substring, $message = '%s') { parent::__construct($substring, $message); } /** * Tests the expectation. False if the substring appears * in the text. * @param string $compare Comparison value. * @return boolean True if correct. * @access public */ function test($compare) { return ! parent::test($compare); } /** * Returns a human readable test message. * @param string $compare Comparison value. * @return string Description of success * or failure. * @access public */ function testMessage($compare) { if ($this->test($compare)) { $dumper = $this->getDumper(); return "Text [" . $this->getSubstring() . "] not detected in [" . $dumper->describeValue($compare) . "]"; } else { return $this->describeTextMatch($this->getSubstring(), $compare); } } } /** * Test case for testing of web pages. Allows * fetching of pages, parsing of HTML and * submitting forms. * @package SimpleTest * @subpackage WebTester */ class WebTestCase extends SimpleTestCase { private $browser; private $ignore_errors = false; /** * Creates an empty test case. Should be subclassed * with test methods for a functional test case. * @param string $label Name of test case. Will use * the class name if none specified. * @access public */ function __construct($label = false) { parent::__construct($label); } /** * Announces the start of the test. * @param string $method Test method just started. * @access public */ function before($method) { parent::before($method); $this->setBrowser($this->createBrowser()); } /** * Announces the end of the test. Includes private clean up. * @param string $method Test method just finished. * @access public */ function after($method) { $this->unsetBrowser(); parent::after($method); } /** * Gets a current browser reference for setting * special expectations or for detailed * examination of page fetches. * @return SimpleBrowser Current test browser object. * @access public */ function getBrowser() { return $this->browser; } /** * Gets a current browser reference for setting * special expectations or for detailed * examination of page fetches. * @param SimpleBrowser $browser New test browser object. * @access public */ function setBrowser($browser) { return $this->browser = $browser; } /** * Clears the current browser reference to help the * PHP garbage collector. * @access public */ function unsetBrowser() { unset($this->browser); } /** * Creates a new default web browser object. * Will be cleared at the end of the test method. * @return TestBrowser New browser. * @access public */ function createBrowser() { return new SimpleBrowser(); } /** * Gets the last response error. * @return string Last low level HTTP error. * @access public */ function getTransportError() { return $this->browser->getTransportError(); } /** * Accessor for the currently selected URL. * @return string Current location or false if * no page yet fetched. * @access public */ function getUrl() { return $this->browser->getUrl(); } /** * Dumps the current request for debugging. * @access public */ function showRequest() { $this->dump($this->browser->getRequest()); } /** * Dumps the current HTTP headers for debugging. * @access public */ function showHeaders() { $this->dump($this->browser->getHeaders()); } /** * Dumps the current HTML source for debugging. * @access public */ function showSource() { $this->dump($this->browser->getContent()); } /** * Dumps the visible text only for debugging. * @access public */ function showText() { $this->dump(wordwrap($this->browser->getContentAsText(), 80)); } /** * Simulates the closing and reopening of the browser. * Temporary cookies will be discarded and timed * cookies will be expired if later than the * specified time. * @param string/integer $date Time when session restarted. * If ommitted then all persistent * cookies are kept. Time is either * Cookie format string or timestamp. * @access public */ function restart($date = false) { if ($date === false) { $date = time(); } $this->browser->restart($date); } /** * Moves cookie expiry times back into the past. * Useful for testing timeouts and expiries. * @param integer $interval Amount to age in seconds. * @access public */ function ageCookies($interval) { $this->browser->ageCookies($interval); } /** * Disables frames support. Frames will not be fetched * and the frameset page will be used instead. * @access public */ function ignoreFrames() { $this->browser->ignoreFrames(); } /** * Switches off cookie sending and recieving. * @access public */ function ignoreCookies() { $this->browser->ignoreCookies(); } /** * Skips errors for the next request only. You might * want to confirm that a page is unreachable for * example. * @access public */ function ignoreErrors() { $this->ignore_errors = true; } /** * Issues a fail if there is a transport error anywhere * in the current frameset. Only one such error is * reported. * @param string/boolean $result HTML or failure. * @return string/boolean $result Passes through result. * @access private */ protected function failOnError($result) { if (! $this->ignore_errors) { if ($error = $this->browser->getTransportError()) { $this->fail($error); } } $this->ignore_errors = false; return $result; } /** * Adds a header to every fetch. * @param string $header Header line to add to every * request until cleared. * @access public */ function addHeader($header) { $this->browser->addHeader($header); } /** * Sets the maximum number of redirects before * the web page is loaded regardless. * @param integer $max Maximum hops. * @access public */ function setMaximumRedirects($max) { if (! $this->browser) { trigger_error( 'Can only set maximum redirects in a test method, setUp() or tearDown()'); } $this->browser->setMaximumRedirects($max); } /** * Sets the socket timeout for opening a connection and * receiving at least one byte of information. * @param integer $timeout Maximum time in seconds. * @access public */ function setConnectionTimeout($timeout) { $this->browser->setConnectionTimeout($timeout); } /** * Sets proxy to use on all requests for when * testing from behind a firewall. Set URL * to false to disable. * @param string $proxy Proxy URL. * @param string $username Proxy username for authentication. * @param string $password Proxy password for authentication. * @access public */ function useProxy($proxy, $username = false, $password = false) { $this->browser->useProxy($proxy, $username, $password); } /** * Fetches a page into the page buffer. If * there is no base for the URL then the * current base URL is used. After the fetch * the base URL reflects the new location. * @param string $url URL to fetch. * @param hash $parameters Optional additional GET data. * @return boolean/string Raw page on success. * @access public */ function get($url, $parameters = false) { return $this->failOnError($this->browser->get($url, $parameters)); } /** * Fetches a page by POST into the page buffer. * If there is no base for the URL then the * current base URL is used. After the fetch * the base URL reflects the new location. * @param string $url URL to fetch. * @param hash $parameters Optional additional GET data. * @return boolean/string Raw page on success. * @access public */ function post($url, $parameters = false) { return $this->failOnError($this->browser->post($url, $parameters)); } /** * Does a HTTP HEAD fetch, fetching only the page * headers. The current base URL is unchanged by this. * @param string $url URL to fetch. * @param hash $parameters Optional additional GET data. * @return boolean True on success. * @access public */ function head($url, $parameters = false) { return $this->failOnError($this->browser->head($url, $parameters)); } /** * Equivalent to hitting the retry button on the * browser. Will attempt to repeat the page fetch. * @return boolean True if fetch succeeded. * @access public */ function retry() { return $this->failOnError($this->browser->retry()); } /** * Equivalent to hitting the back button on the * browser. * @return boolean True if history entry and * fetch succeeded. * @access public */ function back() { return $this->failOnError($this->browser->back()); } /** * Equivalent to hitting the forward button on the * browser. * @return boolean True if history entry and * fetch succeeded. * @access public */ function forward() { return $this->failOnError($this->browser->forward()); } /** * Retries a request after setting the authentication * for the current realm. * @param string $username Username for realm. * @param string $password Password for realm. * @return boolean/string HTML on successful fetch. Note * that authentication may still have * failed. * @access public */ function authenticate($username, $password) { return $this->failOnError( $this->browser->authenticate($username, $password)); } /** * Gets the cookie value for the current browser context. * @param string $name Name of cookie. * @return string Value of cookie or false if unset. * @access public */ function getCookie($name) { return $this->browser->getCurrentCookieValue($name); } /** * Sets a cookie in the current browser. * @param string $name Name of cookie. * @param string $value Cookie value. * @param string $host Host upon which the cookie is valid. * @param string $path Cookie path if not host wide. * @param string $expiry Expiry date. * @access public */ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { $this->browser->setCookie($name, $value, $host, $path, $expiry); } /** * Accessor for current frame focus. Will be * false if no frame has focus. * @return integer/string/boolean Label if any, otherwise * the position in the frameset * or false if none. * @access public */ function getFrameFocus() { return $this->browser->getFrameFocus(); } /** * Sets the focus by index. The integer index starts from 1. * @param integer $choice Chosen frame. * @return boolean True if frame exists. * @access public */ function setFrameFocusByIndex($choice) { return $this->browser->setFrameFocusByIndex($choice); } /** * Sets the focus by name. * @param string $name Chosen frame. * @return boolean True if frame exists. * @access public */ function setFrameFocus($name) { return $this->browser->setFrameFocus($name); } /** * Clears the frame focus. All frames will be searched * for content. * @access public */ function clearFrameFocus() { return $this->browser->clearFrameFocus(); } /** * Clicks a visible text item. Will first try buttons, * then links and then images. * @param string $label Visible text or alt text. * @return string/boolean Raw page or false. * @access public */ function click($label) { return $this->failOnError($this->browser->click($label)); } /** * Checks for a click target. * @param string $label Visible text or alt text. * @return boolean True if click target. * @access public */ function assertClickable($label, $message = '%s') { return $this->assertTrue( $this->browser->isClickable($label), sprintf($message, "Click target [$label] should exist")); } /** * Clicks the submit button by label. The owning * form will be submitted by this. * @param string $label Button label. An unlabeled * button can be triggered by 'Submit'. * @param hash $additional Additional form values. * @return boolean/string Page on success, else false. * @access public */ function clickSubmit($label = 'Submit', $additional = false) { return $this->failOnError( $this->browser->clickSubmit($label, $additional)); } /** * Clicks the submit button by name attribute. The owning * form will be submitted by this. * @param string $name Name attribute of button. * @param hash $additional Additional form values. * @return boolean/string Page on success. * @access public */ function clickSubmitByName($name, $additional = false) { return $this->failOnError( $this->browser->clickSubmitByName($name, $additional)); } /** * Clicks the submit button by ID attribute. The owning * form will be submitted by this. * @param string $id ID attribute of button. * @param hash $additional Additional form values. * @return boolean/string Page on success. * @access public */ function clickSubmitById($id, $additional = false) { return $this->failOnError( $this->browser->clickSubmitById($id, $additional)); } /** * Checks for a valid button label. * @param string $label Visible text. * @return boolean True if click target. * @access public */ function assertSubmit($label, $message = '%s') { return $this->assertTrue( $this->browser->isSubmit($label), sprintf($message, "Submit button [$label] should exist")); } /** * Clicks the submit image by some kind of label. Usually * the alt tag or the nearest equivalent. The owning * form will be submitted by this. Clicking outside of * the boundary of the coordinates will result in * a failure. * @param string $label Alt attribute of button. * @param integer $x X-coordinate of imaginary click. * @param integer $y Y-coordinate of imaginary click. * @param hash $additional Additional form values. * @return boolean/string Page on success. * @access public */ function clickImage($label, $x = 1, $y = 1, $additional = false) { return $this->failOnError( $this->browser->clickImage($label, $x, $y, $additional)); } /** * Clicks the submit image by the name. Usually * the alt tag or the nearest equivalent. The owning * form will be submitted by this. Clicking outside of * the boundary of the coordinates will result in * a failure. * @param string $name Name attribute of button. * @param integer $x X-coordinate of imaginary click. * @param integer $y Y-coordinate of imaginary click. * @param hash $additional Additional form values. * @return boolean/string Page on success. * @access public */ function clickImageByName($name, $x = 1, $y = 1, $additional = false) { return $this->failOnError( $this->browser->clickImageByName($name, $x, $y, $additional)); } /** * Clicks the submit image by ID attribute. The owning * form will be submitted by this. Clicking outside of * the boundary of the coordinates will result in * a failure. * @param integer/string $id ID attribute of button. * @param integer $x X-coordinate of imaginary click. * @param integer $y Y-coordinate of imaginary click. * @param hash $additional Additional form values. * @return boolean/string Page on success. * @access public */ function clickImageById($id, $x = 1, $y = 1, $additional = false) { return $this->failOnError( $this->browser->clickImageById($id, $x, $y, $additional)); } /** * Checks for a valid image with atht alt text or title. * @param string $label Visible text. * @return boolean True if click target. * @access public */ function assertImage($label, $message = '%s') { return $this->assertTrue( $this->browser->isImage($label), sprintf($message, "Image with text [$label] should exist")); } /** * Submits a form by the ID. * @param string $id Form ID. No button information * is submitted this way. * @return boolean/string Page on success. * @access public */ function submitFormById($id) { return $this->failOnError($this->browser->submitFormById($id)); } /** * Follows a link by name. Will click the first link * found with this link text by default, or a later * one if an index is given. Match is case insensitive * with normalised space. * @param string $label Text between the anchor tags. * @param integer $index Link position counting from zero. * @return boolean/string Page on success. * @access public */ function clickLink($label, $index = 0) { return $this->failOnError($this->browser->clickLink($label, $index)); } /** * Follows a link by id attribute. * @param string $id ID attribute value. * @return boolean/string Page on success. * @access public */ function clickLinkById($id) { return $this->failOnError($this->browser->clickLinkById($id)); } /** * Tests for the presence of a link label. Match is * case insensitive with normalised space. * @param string $label Text between the anchor tags. * @param mixed $expected Expected URL or expectation object. * @param string $message Message to display. Default * can be embedded with %s. * @return boolean True if link present. * @access public */ function assertLink($label, $expected = true, $message = '%s') { $url = $this->browser->getLink($label); if ($expected === true || ($expected !== true && $url === false)) { return $this->assertTrue($url !== false, sprintf($message, "Link [$label] should exist")); } if (! SimpleExpectation::isExpectation($expected)) { $expected = new IdenticalExpectation($expected); } return $this->assert($expected, $url->asString(), sprintf($message, "Link [$label] should match")); } /** * Tests for the non-presence of a link label. Match is * case insensitive with normalised space. * @param string/integer $label Text between the anchor tags * or ID attribute. * @param string $message Message to display. Default * can be embedded with %s. * @return boolean True if link missing. * @access public */ function assertNoLink($label, $message = '%s') { return $this->assertTrue( $this->browser->getLink($label) === false, sprintf($message, "Link [$label] should not exist")); } /** * Tests for the presence of a link id attribute. * @param string $id Id attribute value. * @param mixed $expected Expected URL or expectation object. * @param string $message Message to display. Default * can be embedded with %s. * @return boolean True if link present. * @access public */ function assertLinkById($id, $expected = true, $message = '%s') { $url = $this->browser->getLinkById($id); if ($expected === true) { return $this->assertTrue($url !== false, sprintf($message, "Link ID [$id] should exist")); } if (! SimpleExpectation::isExpectation($expected)) { $expected = new IdenticalExpectation($expected); } return $this->assert($expected, $url->asString(), sprintf($message, "Link ID [$id] should match")); } /** * Tests for the non-presence of a link label. Match is * case insensitive with normalised space. * @param string $id Id attribute value. * @param string $message Message to display. Default * can be embedded with %s. * @return boolean True if link missing. * @access public */ function assertNoLinkById($id, $message = '%s') { return $this->assertTrue( $this->browser->getLinkById($id) === false, sprintf($message, "Link ID [$id] should not exist")); } /** * Sets all form fields with that label, or name if there * is no label attached. * @param string $name Name of field in forms. * @param string $value New value of field. * @return boolean True if field exists, otherwise false. * @access public */ function setField($label, $value, $position=false) { return $this->browser->setField($label, $value, $position); } /** * Sets all form fields with that name. * @param string $name Name of field in forms. * @param string $value New value of field. * @return boolean True if field exists, otherwise false. * @access public */ function setFieldByName($name, $value, $position=false) { return $this->browser->setFieldByName($name, $value, $position); } /** * Sets all form fields with that id. * @param string/integer $id Id of field in forms. * @param string $value New value of field. * @return boolean True if field exists, otherwise false. * @access public */ function setFieldById($id, $value) { return $this->browser->setFieldById($id, $value); } /** * Confirms that the form element is currently set * to the expected value. A missing form will always * fail. If no value is given then only the existence * of the field is checked. * @param string $name Name of field in forms. * @param mixed $expected Expected string/array value or * false for unset fields. * @param string $message Message to display. Default * can be embedded with %s. * @return boolean True if pass. * @access public */ function assertField($label, $expected = true, $message = '%s') { $value = $this->browser->getField($label); return $this->assertFieldValue($label, $value, $expected, $message); } /** * Confirms that the form element is currently set * to the expected value. A missing form element will always * fail. If no value is given then only the existence * of the field is checked. * @param string $name Name of field in forms. * @param mixed $expected Expected string/array value or * false for unset fields. * @param string $message Message to display. Default * can be embedded with %s. * @return boolean True if pass. * @access public */ function assertFieldByName($name, $expected = true, $message = '%s') { $value = $this->browser->getFieldByName($name); return $this->assertFieldValue($name, $value, $expected, $message); } /** * Confirms that the form element is currently set * to the expected value. A missing form will always * fail. If no ID is given then only the existence * of the field is checked. * @param string/integer $id Name of field in forms. * @param mixed $expected Expected string/array value or * false for unset fields. * @param string $message Message to display. Default * can be embedded with %s. * @return boolean True if pass. * @access public */ function assertFieldById($id, $expected = true, $message = '%s') { $value = $this->browser->getFieldById($id); return $this->assertFieldValue($id, $value, $expected, $message); } /** * Tests the field value against the expectation. * @param string $identifier Name, ID or label. * @param mixed $value Current field value. * @param mixed $expected Expected value to match. * @param string $message Failure message. * @return boolean True if pass * @access protected */ protected function assertFieldValue($identifier, $value, $expected, $message) { if ($expected === true) { return $this->assertTrue( isset($value), sprintf($message, "Field [$identifier] should exist")); } if (! SimpleExpectation::isExpectation($expected)) { $identifier = str_replace('%', '%%', $identifier); $expected = new FieldExpectation( $expected, "Field [$identifier] should match with [%s]"); } return $this->assert($expected, $value, $message); } /** * Checks the response code against a list * of possible values. * @param array $responses Possible responses for a pass. * @param string $message Message to display. Default * can be embedded with %s. * @return boolean True if pass. * @access public */ function assertResponse($responses, $message = '%s') { $responses = (is_array($responses) ? $responses : array($responses)); $code = $this->browser->getResponseCode(); $message = sprintf($message, "Expecting response in [" . implode(", ", $responses) . "] got [$code]"); return $this->assertTrue(in_array($code, $responses), $message); } /** * Checks the mime type against a list * of possible values. * @param array $types Possible mime types for a pass. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertMime($types, $message = '%s') { $types = (is_array($types) ? $types : array($types)); $type = $this->browser->getMimeType(); $message = sprintf($message, "Expecting mime type in [" . implode(", ", $types) . "] got [$type]"); return $this->assertTrue(in_array($type, $types), $message); } /** * Attempt to match the authentication type within * the security realm we are currently matching. * @param string $authentication Usually basic. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertAuthentication($authentication = false, $message = '%s') { if (! $authentication) { $message = sprintf($message, "Expected any authentication type, got [" . $this->browser->getAuthentication() . "]"); return $this->assertTrue( $this->browser->getAuthentication(), $message); } else { $message = sprintf($message, "Expected authentication [$authentication] got [" . $this->browser->getAuthentication() . "]"); return $this->assertTrue( strtolower($this->browser->getAuthentication()) == strtolower($authentication), $message); } } /** * Checks that no authentication is necessary to view * the desired page. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertNoAuthentication($message = '%s') { $message = sprintf($message, "Expected no authentication type, got [" . $this->browser->getAuthentication() . "]"); return $this->assertFalse($this->browser->getAuthentication(), $message); } /** * Attempts to match the current security realm. * @param string $realm Name of security realm. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertRealm($realm, $message = '%s') { if (! SimpleExpectation::isExpectation($realm)) { $realm = new EqualExpectation($realm); } return $this->assert( $realm, $this->browser->getRealm(), "Expected realm -> $message"); } /** * Checks each header line for the required value. If no * value is given then only an existence check is made. * @param string $header Case insensitive header name. * @param mixed $value Case sensitive trimmed string to * match against. An expectation object * can be used for pattern matching. * @return boolean True if pass. * @access public */ function assertHeader($header, $value = false, $message = '%s') { return $this->assert( new HttpHeaderExpectation($header, $value), $this->browser->getHeaders(), $message); } /** * Confirms that the header type has not been received. * Only the landing page is checked. If you want to check * redirect pages, then you should limit redirects so * as to capture the page you want. * @param string $header Case insensitive header name. * @return boolean True if pass. * @access public */ function assertNoHeader($header, $message = '%s') { return $this->assert( new NoHttpHeaderExpectation($header), $this->browser->getHeaders(), $message); } /** * Tests the text between the title tags. * @param string/SimpleExpectation $title Expected title. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertTitle($title = false, $message = '%s') { if (! SimpleExpectation::isExpectation($title)) { $title = new EqualExpectation($title); } return $this->assert($title, $this->browser->getTitle(), $message); } /** * Will trigger a pass if the text is found in the plain * text form of the page. * @param string $text Text to look for. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertText($text, $message = '%s') { return $this->assert( new TextExpectation($text), $this->browser->getContentAsText(), $message); } /** * Will trigger a pass if the text is not found in the plain * text form of the page. * @param string $text Text to look for. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertNoText($text, $message = '%s') { return $this->assert( new NoTextExpectation($text), $this->browser->getContentAsText(), $message); } /** * Will trigger a pass if the Perl regex pattern * is found in the raw content. * @param string $pattern Perl regex to look for including * the regex delimiters. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertPattern($pattern, $message = '%s') { return $this->assert( new PatternExpectation($pattern), $this->browser->getContent(), $message); } /** * Will trigger a pass if the perl regex pattern * is not present in raw content. * @param string $pattern Perl regex to look for including * the regex delimiters. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertNoPattern($pattern, $message = '%s') { return $this->assert( new NoPatternExpectation($pattern), $this->browser->getContent(), $message); } /** * Checks that a cookie is set for the current page * and optionally checks the value. * @param string $name Name of cookie to test. * @param string $expected Expected value as a string or * false if any value will do. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertCookie($name, $expected = false, $message = '%s') { $value = $this->getCookie($name); if (! $expected) { return $this->assertTrue( $value, sprintf($message, "Expecting cookie [$name]")); } if (! SimpleExpectation::isExpectation($expected)) { $expected = new EqualExpectation($expected); } return $this->assert($expected, $value, "Expecting cookie [$name] -> $message"); } /** * Checks that no cookie is present or that it has * been successfully cleared. * @param string $name Name of cookie to test. * @param string $message Message to display. * @return boolean True if pass. * @access public */ function assertNoCookie($name, $message = '%s') { return $this->assertTrue( $this->getCookie($name) === null or $this->getCookie($name) === false, sprintf($message, "Not expecting cookie [$name]")); } /** * Called from within the test methods to register * passes and failures. * @param boolean $result Pass on true. * @param string $message Message to display describing * the test state. * @return boolean True on pass * @access public */ function assertTrue($result, $message = false) { return $this->assert(new TrueExpectation(), $result, $message); } /** * Will be true on false and vice versa. False * is the PHP definition of false, so that null, * empty strings, zero and an empty array all count * as false. * @param boolean $result Pass on false. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertFalse($result, $message = '%s') { return $this->assert(new FalseExpectation(), $result, $message); } /** * Will trigger a pass if the two parameters have * the same value only. Otherwise a fail. This * is for testing hand extracted text, etc. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertEqual($first, $second, $message = '%s') { return $this->assert( new EqualExpectation($first), $second, $message); } /** * Will trigger a pass if the two parameters have * a different value. Otherwise a fail. This * is for testing hand extracted text, etc. * @param mixed $first Value to compare. * @param mixed $second Value to compare. * @param string $message Message to display. * @return boolean True on pass * @access public */ function assertNotEqual($first, $second, $message = '%s') { return $this->assert( new NotEqualExpectation($first), $second, $message); } /** * Uses a stack trace to find the line of an assertion. * @return string Line number of first assert* * method embedded in format string. * @access public */ function getAssertionLine() { $trace = new SimpleStackTrace(array('assert', 'click', 'pass', 'fail')); return $trace->traceMethod(); } } ?> Swift-4.2.1/test-suite/lib/simpletest/xml.php 100644 0 0 46410 12000050366 16334 0 ustar 0 0 namespace = ($namespace ? $namespace . ':' : ''); $this->indent = $indent; } /** * Calculates the pretty printing indent level * from the current level of nesting. * @param integer $offset Extra indenting level. * @return string Leading space. * @access protected */ protected function getIndent($offset = 0) { return str_repeat( $this->indent, count($this->getTestList()) + $offset); } /** * Converts character string to parsed XML * entities string. * @param string text Unparsed character data. * @return string Parsed character data. * @access public */ function toParsedXml($text) { return str_replace( array('&', '<', '>', '"', '\''), array('&', '<', '>', '"', '''), $text); } /** * Paints the start of a group test. * @param string $test_name Name of test that is starting. * @param integer $size Number of test cases starting. * @access public */ function paintGroupStart($test_name, $size) { parent::paintGroupStart($test_name, $size); print $this->getIndent(); print "<" . $this->namespace . "group size=\"$size\">\n"; print $this->getIndent(1); print "<" . $this->namespace . "name>" . $this->toParsedXml($test_name) . "" . $this->namespace . "name>\n"; } /** * Paints the end of a group test. * @param string $test_name Name of test that is ending. * @access public */ function paintGroupEnd($test_name) { print $this->getIndent(); print "" . $this->namespace . "group>\n"; parent::paintGroupEnd($test_name); } /** * Paints the start of a test case. * @param string $test_name Name of test that is starting. * @access public */ function paintCaseStart($test_name) { parent::paintCaseStart($test_name); print $this->getIndent(); print "<" . $this->namespace . "case>\n"; print $this->getIndent(1); print "<" . $this->namespace . "name>" . $this->toParsedXml($test_name) . "" . $this->namespace . "name>\n"; } /** * Paints the end of a test case. * @param string $test_name Name of test that is ending. * @access public */ function paintCaseEnd($test_name) { print $this->getIndent(); print "" . $this->namespace . "case>\n"; parent::paintCaseEnd($test_name); } /** * Paints the start of a test method. * @param string $test_name Name of test that is starting. * @access public */ function paintMethodStart($test_name) { parent::paintMethodStart($test_name); print $this->getIndent(); print "<" . $this->namespace . "test>\n"; print $this->getIndent(1); print "<" . $this->namespace . "name>" . $this->toParsedXml($test_name) . "" . $this->namespace . "name>\n"; } /** * Paints the end of a test method. * @param string $test_name Name of test that is ending. * @param integer $progress Number of test cases ending. * @access public */ function paintMethodEnd($test_name) { print $this->getIndent(); print "" . $this->namespace . "test>\n"; parent::paintMethodEnd($test_name); } /** * Paints pass as XML. * @param string $message Message to encode. * @access public */ function paintPass($message) { parent::paintPass($message); print $this->getIndent(1); print "<" . $this->namespace . "pass>"; print $this->toParsedXml($message); print "" . $this->namespace . "pass>\n"; } /** * Paints failure as XML. * @param string $message Message to encode. * @access public */ function paintFail($message) { parent::paintFail($message); print $this->getIndent(1); print "<" . $this->namespace . "fail>"; print $this->toParsedXml($message); print "" . $this->namespace . "fail>\n"; } /** * Paints error as XML. * @param string $message Message to encode. * @access public */ function paintError($message) { parent::paintError($message); print $this->getIndent(1); print "<" . $this->namespace . "exception>"; print $this->toParsedXml($message); print "" . $this->namespace . "exception>\n"; } /** * Paints exception as XML. * @param Exception $exception Exception to encode. * @access public */ function paintException($exception) { parent::paintException($exception); print $this->getIndent(1); print "<" . $this->namespace . "exception>"; $message = 'Unexpected exception of type [' . get_class($exception) . '] with message ['. $exception->getMessage() . '] in ['. $exception->getFile() . ' line ' . $exception->getLine() . ']'; print $this->toParsedXml($message); print "" . $this->namespace . "exception>\n"; } /** * Paints the skipping message and tag. * @param string $message Text to display in skip tag. * @access public */ function paintSkip($message) { parent::paintSkip($message); print $this->getIndent(1); print "<" . $this->namespace . "skip>"; print $this->toParsedXml($message); print "" . $this->namespace . "skip>\n"; } /** * Paints a simple supplementary message. * @param string $message Text to display. * @access public */ function paintMessage($message) { parent::paintMessage($message); print $this->getIndent(1); print "<" . $this->namespace . "message>"; print $this->toParsedXml($message); print "" . $this->namespace . "message>\n"; } /** * Paints a formatted ASCII message such as a * privateiable dump. * @param string $message Text to display. * @access public */ function paintFormattedMessage($message) { parent::paintFormattedMessage($message); print $this->getIndent(1); print "<" . $this->namespace . "formatted>"; print ""; print "" . $this->namespace . "formatted>\n"; } /** * Serialises the event object. * @param string $type Event type as text. * @param mixed $payload Message or object. * @access public */ function paintSignal($type, $payload) { parent::paintSignal($type, $payload); print $this->getIndent(1); print "<" . $this->namespace . "signal type=\"$type\">"; print ""; print "" . $this->namespace . "signal>\n"; } /** * Paints the test document header. * @param string $test_name First test top level * to start. * @access public * @abstract */ function paintHeader($test_name) { if (! SimpleReporter::inCli()) { header('Content-type: text/xml'); } print "namespace) { print " xmlns:" . $this->namespace . "=\"www.lastcraft.com/SimpleTest/Beta3/Report\""; } print "?>\n"; print "<" . $this->namespace . "run>\n"; } /** * Paints the test document footer. * @param string $test_name The top level test. * @access public * @abstract */ function paintFooter($test_name) { print "" . $this->namespace . "run>\n"; } } /** * Accumulator for incoming tag. Holds the * incoming test structure information for * later dispatch to the reporter. * @package SimpleTest * @subpackage UnitTester */ class NestingXmlTag { private $name; private $attributes; /** * Sets the basic test information except * the name. * @param hash $attributes Name value pairs. * @access public */ function NestingXmlTag($attributes) { $this->name = false; $this->attributes = $attributes; } /** * Sets the test case/method name. * @param string $name Name of test. * @access public */ function setName($name) { $this->name = $name; } /** * Accessor for name. * @return string Name of test. * @access public */ function getName() { return $this->name; } /** * Accessor for attributes. * @return hash All attributes. * @access protected */ protected function getAttributes() { return $this->attributes; } } /** * Accumulator for incoming method tag. Holds the * incoming test structure information for * later dispatch to the reporter. * @package SimpleTest * @subpackage UnitTester */ class NestingMethodTag extends NestingXmlTag { /** * Sets the basic test information except * the name. * @param hash $attributes Name value pairs. * @access public */ function NestingMethodTag($attributes) { $this->NestingXmlTag($attributes); } /** * Signals the appropriate start event on the * listener. * @param SimpleReporter $listener Target for events. * @access public */ function paintStart(&$listener) { $listener->paintMethodStart($this->getName()); } /** * Signals the appropriate end event on the * listener. * @param SimpleReporter $listener Target for events. * @access public */ function paintEnd(&$listener) { $listener->paintMethodEnd($this->getName()); } } /** * Accumulator for incoming case tag. Holds the * incoming test structure information for * later dispatch to the reporter. * @package SimpleTest * @subpackage UnitTester */ class NestingCaseTag extends NestingXmlTag { /** * Sets the basic test information except * the name. * @param hash $attributes Name value pairs. * @access public */ function NestingCaseTag($attributes) { $this->NestingXmlTag($attributes); } /** * Signals the appropriate start event on the * listener. * @param SimpleReporter $listener Target for events. * @access public */ function paintStart(&$listener) { $listener->paintCaseStart($this->getName()); } /** * Signals the appropriate end event on the * listener. * @param SimpleReporter $listener Target for events. * @access public */ function paintEnd(&$listener) { $listener->paintCaseEnd($this->getName()); } } /** * Accumulator for incoming group tag. Holds the * incoming test structure information for * later dispatch to the reporter. * @package SimpleTest * @subpackage UnitTester */ class NestingGroupTag extends NestingXmlTag { /** * Sets the basic test information except * the name. * @param hash $attributes Name value pairs. * @access public */ function NestingGroupTag($attributes) { $this->NestingXmlTag($attributes); } /** * Signals the appropriate start event on the * listener. * @param SimpleReporter $listener Target for events. * @access public */ function paintStart(&$listener) { $listener->paintGroupStart($this->getName(), $this->getSize()); } /** * Signals the appropriate end event on the * listener. * @param SimpleReporter $listener Target for events. * @access public */ function paintEnd(&$listener) { $listener->paintGroupEnd($this->getName()); } /** * The size in the attributes. * @return integer Value of size attribute or zero. * @access public */ function getSize() { $attributes = $this->getAttributes(); if (isset($attributes['SIZE'])) { return (integer)$attributes['SIZE']; } return 0; } } /** * Parser for importing the output of the XmlReporter. * Dispatches that output to another reporter. * @package SimpleTest * @subpackage UnitTester */ class SimpleTestXmlParser { private $listener; private $expat; private $tag_stack; private $in_content_tag; private $content; private $attributes; /** * Loads a listener with the SimpleReporter * interface. * @param SimpleReporter $listener Listener of tag events. * @access public */ function SimpleTestXmlParser(&$listener) { $this->listener = &$listener; $this->expat = &$this->createParser(); $this->tag_stack = array(); $this->in_content_tag = false; $this->content = ''; $this->attributes = array(); } /** * Parses a block of XML sending the results to * the listener. * @param string $chunk Block of text to read. * @return boolean True if valid XML. * @access public */ function parse($chunk) { if (! xml_parse($this->expat, $chunk)) { trigger_error('XML parse error with ' . xml_error_string(xml_get_error_code($this->expat))); return false; } return true; } /** * Sets up expat as the XML parser. * @return resource Expat handle. * @access protected */ protected function &createParser() { $expat = xml_parser_create(); xml_set_object($expat, $this); xml_set_element_handler($expat, 'startElement', 'endElement'); xml_set_character_data_handler($expat, 'addContent'); xml_set_default_handler($expat, 'defaultContent'); return $expat; } /** * Opens a new test nesting level. * @return NestedXmlTag The group, case or method tag * to start. * @access private */ protected function pushNestingTag($nested) { array_unshift($this->tag_stack, $nested); } /** * Accessor for current test structure tag. * @return NestedXmlTag The group, case or method tag * being parsed. * @access private */ protected function &getCurrentNestingTag() { return $this->tag_stack[0]; } /** * Ends a nesting tag. * @return NestedXmlTag The group, case or method tag * just finished. * @access private */ protected function popNestingTag() { return array_shift($this->tag_stack); } /** * Test if tag is a leaf node with only text content. * @param string $tag XML tag name. * @return @boolean True if leaf, false if nesting. * @private */ protected function isLeaf($tag) { return in_array($tag, array( 'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'SKIP', 'MESSAGE', 'FORMATTED', 'SIGNAL')); } /** * Handler for start of event element. * @param resource $expat Parser handle. * @param string $tag Element name. * @param hash $attributes Name value pairs. * Attributes without content * are marked as true. * @access protected */ protected function startElement($expat, $tag, $attributes) { $this->attributes = $attributes; if ($tag == 'GROUP') { $this->pushNestingTag(new NestingGroupTag($attributes)); } elseif ($tag == 'CASE') { $this->pushNestingTag(new NestingCaseTag($attributes)); } elseif ($tag == 'TEST') { $this->pushNestingTag(new NestingMethodTag($attributes)); } elseif ($this->isLeaf($tag)) { $this->in_content_tag = true; $this->content = ''; } } /** * End of element event. * @param resource $expat Parser handle. * @param string $tag Element name. * @access protected */ protected function endElement($expat, $tag) { $this->in_content_tag = false; if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) { $nesting_tag = $this->popNestingTag(); $nesting_tag->paintEnd($this->listener); } elseif ($tag == 'NAME') { $nesting_tag = &$this->getCurrentNestingTag(); $nesting_tag->setName($this->content); $nesting_tag->paintStart($this->listener); } elseif ($tag == 'PASS') { $this->listener->paintPass($this->content); } elseif ($tag == 'FAIL') { $this->listener->paintFail($this->content); } elseif ($tag == 'EXCEPTION') { $this->listener->paintError($this->content); } elseif ($tag == 'SKIP') { $this->listener->paintSkip($this->content); } elseif ($tag == 'SIGNAL') { $this->listener->paintSignal( $this->attributes['TYPE'], unserialize($this->content)); } elseif ($tag == 'MESSAGE') { $this->listener->paintMessage($this->content); } elseif ($tag == 'FORMATTED') { $this->listener->paintFormattedMessage($this->content); } } /** * Content between start and end elements. * @param resource $expat Parser handle. * @param string $text Usually output messages. * @access protected */ protected function addContent($expat, $text) { if ($this->in_content_tag) { $this->content .= $text; } return true; } /** * XML and Doctype handler. Discards all such content. * @param resource $expat Parser handle. * @param string $default Text of default content. * @access protected */ protected function defaultContent($expat, $default) { } } ?> Swift-4.2.1/test-suite/lib/yaymock/classes/Yay.php 100644 0 0 14451 12000050366 17216 0 ustar 0 0 . */ //require 'Yay/Expectations.php'; //require 'Yay/Matchers/OptionalMatcher.php'; //require 'Yay/Matchers/AnyMatcher.php'; //require 'Yay/Matchers/IdenticalMatcher.php'; //require 'Yay/Matchers/EqualMatcher.php'; //require 'Yay/Matchers/PatternMatcher.php'; //require 'Yay/Matchers/ReferenceMatcher.php'; //require 'Yay/Matchers/BoundsMatcher.php'; //require 'Yay/Actions/ReturnValueAction.php'; //require 'Yay/Actions/ReturnReferenceAction.php'; //require 'Yay/Actions/ThrowAction.php'; //require 'Yay/Actions/CallbackAction.php'; /** * A convenience factory class. * @author Chris Corbyn
Expectations::create()->exactly(2)->of($mock);
* @param int $n
* @return Yay_Expectations
*/
public function exactly($n)
{
return $this->_setEndpoint(new Yay_Expectations_ExactlyExpectation($n));
}
/**
* Expect at least $n Invocations on a mock object specified with a following
* of() clause.
* Example: Expectations::create()->atLeast(2)->of($mock);
* @param int $n
* @return Yay_Expectations
*/
public function atLeast($n)
{
return $this->_setEndpoint(new Yay_Expectations_AtLeastExpectation($n));
}
/**
* Expect at most $n Invocations on a mock object specified with a following
* of() clause.
* Example: Expectations::create()->atMost(2)->of($mock);
* @param int $n
* @return Yay_Expectations
*/
public function atMost($n)
{
return $this->_setEndpoint(new Yay_Expectations_AtMostExpectation($n));
}
/**
* Expect at between $min and $max Invocations on a mock object specified
* with a following of() clause.
* Example: Expectations::create()->atLeast(2)->of($mock);
* @param int $n
* @return Yay_Expectations
*/
public function between($min, $max)
{
return $this->_setEndpoint(new Yay_Expectations_BetweenExpectation($min, $max));
}
/**
* Ignore Invocations on the $mock object specified.
* @param Yay_MockObject $mock
* @return Yay_Expectations
*/
public function ignoring(Yay_MockObject $mock)
{
return $this->atLeast(0)->of($mock);
}
/**
* Allow Invocations on the $mock object specified.
* This does exactly the same thing as ignoring() but it allows a semantically
* different meaning in the test case.
* @param Yay_MockObject $mock
* @return Yay_Expectations
*/
public function allowing(Yay_MockObject $mock)
{
return $this->ignoring($mock);
}
/**
* Deny Invocations on the $mock object specified.
* @param Yay_MockObject $mock
* @return Yay_Expectations
*/
public function never(Yay_MockObject $mock)
{
return $this->exactly(0)->of($mock);
}
/**
* Specify the MockObject which the Invocation will occur.
* This method returns the mock object in record mode.
* @param Yay_MockObject $mock
* @return Yay_InvocationProxy
*/
public function of(Yay_MockObject $mock)
{
$this->_getEndpoint()->of($mock);
return new Yay_InvocationProxy($this, $mock);
}
/**
* Specify the Action to run if a match occurs.
* @param Yay_Action $action
*/
public function will(Yay_Action $action)
{
$this->_getEndpoint()->will($action);
return $this;
}
/**
* Only be expected when in the given State predicate.
* @param Yay_StatePredicate $predicate
*/
public function when(Yay_StatePredicate $predicate)
{
$this->_getEndpoint()->when($predicate);
return $this;
}
/**
* Activate the given $state if a match occurs.
* @param Yay_State $state
*/
public function then(Yay_State $state)
{
$this->_getEndpoint()->then($state);
return $this;
}
/**
* Constrain the current expectation to occur in the given sequence.
* @param Yay_Sequence $seq
*/
public function inSequence(Yay_Sequence $seq)
{
$this->_getEndpoint()->inSequence($seq);
return $this;
}
/**
* A wrapper for will(Yay::returnValue($value)).
* @param mixed $value
*/
public function returns($value)
{
$this->_getEndpoint()->will(new Yay_Actions_ReturnValueAction($value));
return $this;
}
/**
* A wrapper for will(Yay::returnReference($ref)).
* @param mixed $ref
*/
public function returnsReference(&$ref)
{
$this->_getEndpoint()->will(new Yay_Actions_ReturnReferenceAction($ref));
return $this;
}
/**
* A wrapper for will(Yay::throwException($e)).
* @param Exception $e
*/
public function throws(Exception $e)
{
$this->_getEndpoint()->will(new Yay_Actions_ThrowAction($e));
return $this;
}
/**
* A wrapper for will(Yay::call($callback)).
* @param callback $callback
*/
public function calls($callback)
{
$this->_getEndpoint()->will(new Yay_Actions_CallbackAction($callback));
return $this;
}
/**
* Record any Invocations on the MockObject whilst it's in record mode.
* @param Yay_Invocation $invocation
*/
public function recordInvocation(Yay_Invocation $invocation)
{
$this->_getEndpoint()->recordInvocation($invocation);
}
/**
* Returns the Expectation stack.
* @return Yay_Expectation
*/
public function getExpectations()
{
return $this->_expectations;
}
// -- Private methods
/**
* Apply a new Expectation to the stack and tag it as the endpoint for recording.
* @param Yay_Expectation $expectation
* @return Yay_Expectations
* @access private
*/
private function _setEndpoint(Yay_Expectation $expectation)
{
$this->_expectations[] = $expectation;
$this->_currentEndpoint = $expectation;
return $this;
}
/**
* Gets the current endpoint (current expectation).
* @return Yay_Expectation
* @access private
*/
private function _getEndpoint()
{
if (!isset($this->_currentEndpoint))
{
throw new BadMethodCallException(
'No cardinality clause has yet been made. First call one(), atLeast(), ' .
'atMost(), exactly(), between(), ignoring(), allowing() or never() ' .
'before performing this operation.'
);
}
else
{
return $this->_currentEndpoint;
}
}
}
Swift-4.2.1/test-suite/lib/yaymock/classes/Yay/Expectations/AbstractExpectation.php 100644 0 0 17663 12000050366 25643 0 ustar 0 0 .
*/
//require 'Yay/Mockery.php';
//require 'Yay/Expectation.php';
//require 'Yay/ExpectationProvider.php';
//require 'Yay/Invocation.php';
//require 'Yay/InvocationRecorder.php';
//require 'Yay/InvocationProxy.php';
//require 'Yay/Action.php';
//require 'Yay/Matcher.php';
//require 'Yay/Matchers/IdenticalMatcher.php';
//require 'Yay/State.php';
//require 'Yay/StatePredicate.php';
//require 'Yay/Sequence.php';
//require 'Yay/Description.php';
//require 'Yay/MockGenerator.php';
/**
* A base Expectation which other Expectations extend.
* @author Chris Corbyn