Skip to content

Commit

Permalink
added Http::metadata (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
MartkCz authored and Milan Felix Šulc committed Feb 12, 2019
1 parent 65c7d90 commit acb2be7
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,10 @@ Collection of extra functions:

- `isIco($s)` - trader identification number (Czech only)
- `isRc($s)`- personal identification number (Czech and Slovak only)


## `Http`

Collection of extra functions:

- `metadata($s)` - gets http metadata from string, returns as `[name => content]`
51 changes: 51 additions & 0 deletions src/Http.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php declare(strict_types = 1);

namespace Contributte\Utils;

use LogicException;
use Nette\StaticClass;

class Http
{

use StaticClass;

/** @var string */
private static $metadataPattern = '
~<\s*meta\s
# using lookahead to capture type to $1
(?=[^>]*?
\b(?:name|property|http-equiv)\s*=\s*
(?|"\s*([^"]*?)\s*"|\'\s*([^\']*?)\s*\'|
([^"\'>]*?)(?=\s*/?\s*>|\s\w+\s*=))
)
# capture content to $2
[^>]*?\bcontent\s*=\s*
(?|"\s*([^"]*?)\s*"|\'\s*([^\']*?)\s*\'|
([^"\'>]*?)(?=\s*/?\s*>|\s\w+\s*=))
[^>]*>
~ix';

/**
* Gets http metadata from string
*
* @return string[] [name => content]
*/
public static function metadata(string $content): array
{
if (preg_match_all(self::$metadataPattern, $content, $matches) !== false) {
$combine = array_combine($matches[1], $matches[2]);
if ($combine === false) {
throw new LogicException('Matches count is not equal.');
}

return $combine;
}

return [];
}

}
33 changes: 33 additions & 0 deletions tests/cases/Http.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php declare(strict_types = 1);

/**
* Test: Http
*/

require_once __DIR__ . '/../bootstrap.php';

use Contributte\Utils\Http;
use Tester\Assert;

// Http::metadata
test(function (): void {
Assert::equal([
'bar' => 'foo',
'bar1' => 'foo',
'bar2 bar' => 'foo',
'bar3' => 'foo',
'bar4' => 'foo',
'bar5' => 'foo',
'bar6.bar' => 'foo',
'bar7.bar' => 'foo',
], Http::metadata('
<meta content = foo name = bar />
<meta content = foo name = bar1 >
<meta name= bar2 bar content= foo >
<meta content="foo" name="bar3">
<meta name ="bar4" content = " foo ">
<meta name= "bar5" content=" foo ">
<meta name="bar6.bar" content="foo ">
<meta content=\' foo\' name = bar7.bar >
'));
});

0 comments on commit acb2be7

Please sign in to comment.