Skip to content

Commit

Permalink
Merge pull request #592 from WordPress/feature/idnaencoder-add-input-…
Browse files Browse the repository at this point in the history
…validation
  • Loading branch information
schlessera authored Nov 8, 2021
2 parents 96f082a + fe4bce1 commit 9d3b445
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/IdnaEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace WpOrg\Requests;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Utility\InputValidator;

/**
* IDNA URL encoder
Expand Down Expand Up @@ -54,8 +56,13 @@ class IdnaEncoder {
*
* @param string $hostname Hostname
* @return string Punycode-encoded hostname
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
*/
public static function encode($hostname) {
if (InputValidator::is_string_or_stringable($hostname) === false) {
throw InvalidArgument::create(1, '$hostname', 'string|Stringable', gettype($hostname));
}

$parts = explode('.', $hostname);
foreach ($parts as &$part) {
$part = self::to_ascii($part);
Expand Down
31 changes: 31 additions & 0 deletions tests/IdnaEncoderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace WpOrg\Requests\Tests;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\IdnaEncoder;
use WpOrg\Requests\Tests\Fixtures\StringableObject;
use WpOrg\Requests\Tests\TestCase;
Expand Down Expand Up @@ -182,6 +183,36 @@ public function dataInvalidUnicode() {
);
}

/**
* Tests receiving an exception when an invalid input type is passed.
*
* @dataProvider dataInvalidInputType
*
* @param mixed $data Data to encode.
*
* @return void
*/
public function testInvalidInputType($data) {
$this->expectException(InvalidArgument::class);
$this->expectExceptionMessage('Argument #1 ($hostname) must be of type string');

IdnaEncoder::encode($data);
}

/**
* Data Provider.
*
* @return array
*/
public function dataInvalidInputType() {
return array(
'null' => array(null),
'boolean false' => array(false),
'integer' => array(12345),
'array' => array(array(1, 2, 3)),
);
}

public function testASCIITooLong() {
$this->expectException(Exception::class);
$this->expectExceptionMessage('Provided string is too long');
Expand Down

0 comments on commit 9d3b445

Please sign in to comment.