diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index d78a1e2..243ecda 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -68,6 +68,9 @@ jobs: #run: composer validate --strict # Currently we’re installing mf2/tests from a commit ref. run: composer validate + - name: Run static analysis + run: composer phpstan -- --error-format=github + - name: Run Test Suite run: XDEBUG_MODE=coverage ./vendor/bin/phpunit tests --coverage-text diff --git a/.gitignore b/.gitignore index ab80a84..9ef93dc 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ composer.lock .idea/ /bin/test /.phpunit.result.cache +/phpstan.neon diff --git a/Mf2/Parser.php b/Mf2/Parser.php index cb2aea6..6263630 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -1,9 +1,12 @@ |(object{}&stdClass), + * id?: string, + * lang?: string, + * shape?: string, + * coords?: string, + * children?: array, + * }>, + * rels: array>|(object{}&stdClass), + * rel-urls: (object{}&stdClass)|array, + * alternates?: non-empty-list, + * } Canonical MF2 array structure */ -function parse($input, $url = null, $convertClassic = true) { +function parse($input, ?string $url = null, bool $convertClassic = true): array { $parser = new Parser($input, $url); return $parser->parse($convertClassic); } @@ -57,12 +88,40 @@ function parse($input, $url = null, $convertClassic = true) { * h-entry resulting in a 410 Gone page with a stub h-entry explaining the reason for deletion). Look in $curlInfo['http_code'] * for the actual value. * - * @param string $url The URL to fetch + * @param non-empty-string $url The URL to fetch * @param bool $convertClassic (optional, default true) whether or not to convert classic microformats - * @param array &$curlInfo (optional) the results of curl_getinfo will be placed in this variable for debugging - * @return array|null canonical microformats2 array structure on success, null on failure + * @param array &$curlInfo (optional) the results of curl_getinfo will be placed in this variable for debugging + * @return array{ + * items: list|(object{}&stdClass), + * id?: string, + * lang?: string, + * shape?: string, + * coords?: string, + * children?: array, + * }>, + * rels: array>|(object{}&stdClass), + * rel-urls: (object{}&stdClass)|array, + * alternates?: non-empty-list, + * }|null canonical microformats2 array structure on success, null on failure */ -function fetch($url, $convertClassic = true, &$curlInfo = []) { +function fetch(string $url, bool $convertClassic = true, array &$curlInfo = []): ?array { $version = '0'; if (is_array($curl = curl_version())) { $version = $curl['version']; @@ -70,9 +129,9 @@ function fetch($url, $convertClassic = true, &$curlInfo = []) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 5); if (version_compare($version, '7.21.6', '>=')) { @@ -86,6 +145,7 @@ function fetch($url, $convertClassic = true, &$curlInfo = []) { curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Accept: text/html' )); + /** @var string|false $html For PHPStan: We are enabling CURLOPT_RETURNTRANSFER so true cannot occur. */ $html = curl_exec($ch); if ($html === false) { @@ -97,13 +157,13 @@ function fetch($url, $convertClassic = true, &$curlInfo = []) { curl_close($ch); } - if (strpos(strtolower($info['content_type']), 'html') === false) { + if (strpos(strtolower($info['content_type'] ?? ''), 'html') === false) { // The content was not delivered as HTML, do not attempt to parse it. return null; } # ensure the final URL is used to resolve relative URLs - $url = $info['url']; + $url = $info['url'] ?? $url; return parse($html, $url, $convertClassic); } @@ -111,19 +171,18 @@ function fetch($url, $convertClassic = true, &$curlInfo = []) { /** * Unicode to HTML Entities * @param string $input String containing characters to convert into HTML entities - * @return string */ -function unicodeToHtmlEntities($input) { +function unicodeToHtmlEntities(string $input): string { // Convert all non-ASCII characters to HTML numeric entities. $convmap = [ 0x80, 0x1FFFFF, 0, 0x10FFFF, ]; - return mb_encode_numericentity($input, $convmap, mb_detect_encoding($input), true); + return mb_encode_numericentity($input, $convmap, mb_detect_encoding($input) ?: mb_internal_encoding(), true); } -function unicodeTrim($str) { - return preg_replace('/^\s+|\s+$/u', '', $str); +function unicodeTrim(string $str): string { + return preg_replace('/^\s+|\s+$/u', '', $str) ?? ''; } /** @@ -134,12 +193,12 @@ function unicodeTrim($str) { * * @param string $class A space delimited list of classnames * @param string $prefix The prefix to look for - * @return string|array The prefixed name of the first microfomats class found or false + * @return string[] The prefixed name of the first microfomats class found or false */ -function mfNamesFromClass($class, $prefix = 'h-') { +function mfNamesFromClass(string $class, string $prefix = 'h-'): array { $class = str_replace(array(' ', ' ', "\n"), ' ', $class); $classes = explode(' ', $class); - $classes = preg_grep('#^(h|p|u|dt|e)-([a-z0-9]+-)?[a-z]+(-[a-z]+)*$#', $classes); + $classes = preg_grep('#^(h|p|u|dt|e)-([a-z0-9]+-)?[a-z]+(-[a-z]+)*$#', $classes) ?: []; $matches = array(); foreach ($classes as $classname) { @@ -155,10 +214,8 @@ function mfNamesFromClass($class, $prefix = 'h-') { /** * Registered with the XPath object and used within XPaths for finding root elements. - * @param string $class - * @return bool */ -function classHasMf2RootClassname($class) { +function classHasMf2RootClassname(string $class): bool { return count(mfNamesFromClass($class, 'h-')) > 0; } @@ -168,10 +225,9 @@ function classHasMf2RootClassname($class) { * Returns all the p-, u-, dt- or e- prefixed classnames it finds in a * space-separated string. * - * @param string $class - * @return array + * @return array> */ -function nestedMfPropertyNamesFromClass($class) { +function nestedMfPropertyNamesFromClass(string $class): array { $prefixes = array('p-', 'u-', 'dt-', 'e-'); $propertyNames = array(); @@ -183,7 +239,7 @@ function nestedMfPropertyNamesFromClass($class) { } foreach ($propertyNames as $property => $prefixes) { - $propertyNames[$property] = array_unique($prefixes); + $propertyNames[$property] = array_values(array_unique($prefixes)); } return $propertyNames; @@ -194,17 +250,19 @@ function nestedMfPropertyNamesFromClass($class) { * * @param DOMElement $e The element to get the classname for * @param string $prefix The prefix to look for - * @return mixed See return value of mf2\Parser::mfNameFromClass() + * @return string[] See return value of mf2\Parser::mfNamesFromClass() */ -function mfNamesFromElement(\DOMElement $e, $prefix = 'h-') { +function mfNamesFromElement(\DOMElement $e, string $prefix = 'h-'): array { $class = $e->getAttribute('class'); return mfNamesFromClass($class, $prefix); } /** - * Wraps nestedMfPropertyNamesFromClass to handle an element as input + * Wraps nestedMfPropertyNamesFromClass to handle an element as input* + * + * @return array> */ -function nestedMfPropertyNamesFromElement(\DOMElement $e) { +function nestedMfPropertyNamesFromElement(\DOMElement $e): array { $class = $e->getAttribute('class'); return nestedMfPropertyNamesFromClass($class); } @@ -212,10 +270,8 @@ function nestedMfPropertyNamesFromElement(\DOMElement $e) { /** * Converts various time formats to HH:MM * @param string $time The time to convert - * @return string */ -function convertTimeFormat($time) { - $hh = $mm = $ss = ''; +function convertTimeFormat(string $time): string { preg_match('/(\d{1,2}):?(\d{2})?:?(\d{2})?(a\.?m\.?|p\.?m\.?)?/i', $time, $matches); // If no am/pm is specified: @@ -233,7 +289,7 @@ function convertTimeFormat($time) { $hh += 12; } - $hh = str_pad($hh, 2, '0', STR_PAD_LEFT); + $hh = str_pad((string) $hh, 2, '0', STR_PAD_LEFT); // Minutes. $mm = (empty($matches[2]) ) ? '00' : $matches[2]; @@ -256,14 +312,15 @@ function convertTimeFormat($time) { * Normalize an ordinal date to YYYY-MM-DD * This function should only be called after validating the $dtValue * matches regex \d{4}-\d{2} - * @param string $dtValue - * @return string */ -function normalizeOrdinalDate($dtValue) { +function normalizeOrdinalDate(string $dtValue): string { list($year, $day) = explode('-', $dtValue, 2); $day = intval($day); if ($day < 367 && $day > 0) { $date = \DateTime::createFromFormat('Y-z', $dtValue); + if ($date === false) { + return ''; + } $date->modify('-1 day'); # 'z' format is zero-based so need to adjust if ($date->format('Y') === $year) { return $date->format('Y-m-d'); @@ -274,10 +331,9 @@ function normalizeOrdinalDate($dtValue) { /** * If a date value has a timezone offset, normalize it. - * @param string $dtValue - * @return string isolated, normalized TZ offset for implied TZ for other dt- properties + * @return ?string isolated, normalized TZ offset for implied TZ for other dt- properties */ -function normalizeTimezoneOffset(&$dtValue) { +function normalizeTimezoneOffset(string &$dtValue): ?string { preg_match('/Z|[+-]\d{1,2}:?(\d{2})?$/i', $dtValue, $matches); if (empty($matches)) { @@ -293,15 +349,18 @@ function normalizeTimezoneOffset(&$dtValue) { if ( strlen($timezoneOffset) <= 2 ) { $timezoneOffset .= '00'; } - $timezoneOffset = str_pad($timezoneOffset, 4, 0, STR_PAD_LEFT); + $timezoneOffset = str_pad($timezoneOffset, 4, '0', STR_PAD_LEFT); $timezoneOffset = $plus_minus . $timezoneOffset; - $dtValue = preg_replace('/Z?[+-]\d{1,2}:?(\d{2})?$/i', $timezoneOffset, $dtValue); + $dtValue = preg_replace('/Z?[+-]\d{1,2}:?(\d{2})?$/i', $timezoneOffset, $dtValue) ?? $dtValue; } return $timezoneOffset; } -function applySrcsetUrlTransformation($srcset, $transformation) { +/** + * @param callable(string): string $transformation + */ +function applySrcsetUrlTransformation(string $srcset, callable $transformation): string { return implode(', ', array_filter(array_map(function ($srcsetPart) use ($transformation) { $parts = explode(" \t\n\r\0\x0B", trim($srcsetPart), 2); $parts[0] = rtrim($parts[0]); @@ -327,48 +386,43 @@ function applySrcsetUrlTransformation($srcset, $transformation) { */ class Parser { /** @var string The baseurl (if any) to use for this parse */ - public $baseurl; + public string $baseurl; /** @var DOMXPath object which can be used to query over any fragment*/ - public $xpath; + public DOMXPath $xpath; /** @var DOMDocument */ - public $doc; + public DOMDocument $doc; - /** @var SplObjectStorage */ - protected $parsed; + /** @var SplObjectStorage> */ + protected SplObjectStorage $parsed; - /** - * @var bool - */ - public $jsonMode; + public bool $jsonMode; - /** @var boolean Whether to include experimental language parsing in the result */ - public $lang = false; + /** @var bool Whether to include experimental language parsing in the result */ + public bool $lang = false; /** @var bool Whether to include alternates object (dropped from spec in favor of rel-urls) */ - public $enableAlternates = false; + public bool $enableAlternates = false; /** - * Elements upgraded to mf2 during backcompat - * @var SplObjectStorage + * @var SplObjectStorage> Elements upgraded to mf2 during backcompat */ - protected $upgraded; + protected SplObjectStorage $upgraded; /** - * Whether to convert classic microformats - * @var bool + * @var bool Whether to convert classic microformats */ - public $convertClassic; + public bool $convertClassic; /** * Constructor * - * @param DOMDocument|string $input The data to parse. A string of HTML or a DOMDocument - * @param string $url The URL of the parsed document, for relative URL resolution - * @param boolean $jsonMode Whether or not to use a stdClass instance for an empty `rels` dictionary. This breaks PHP looping over rels, but allows the output to be correctly serialized as JSON. + * @param DOMDocument|string|null $input The data to parse. A string of HTML or a DOMDocument + * @param ?string $url The URL of the parsed document, for relative URL resolution + * @param bool $jsonMode Whether or not to use a stdClass instance for an empty `rels` dictionary. This breaks PHP looping over rels, but allows the output to be correctly serialized as JSON. */ - public function __construct($input, $url = null, $jsonMode = false) { + public function __construct($input, ?string $url = null, bool $jsonMode = false) { $emptyDocDefault = ''; libxml_use_internal_errors(true); if (is_string($input)) { @@ -383,7 +437,7 @@ public function __construct($input, $url = null, $jsonMode = false) { $doc = new DOMDocument(); @$doc->loadHTML(unicodeToHtmlEntities($input), \LIBXML_NOWARNING); } - } elseif (is_a($input, 'DOMDocument')) { + } elseif ($input instanceof DOMDocument) { $doc = clone $input; } else { $doc = new DOMDocument(); @@ -395,8 +449,10 @@ public function __construct($input, $url = null, $jsonMode = false) { $this->xpath->registerNamespace('php', 'http://php.net/xpath'); $this->xpath->registerPhpFunctions('\\Mf2\\classHasMf2RootClassname'); + $url = $url ?? ''; $baseurl = $url; - foreach ($this->xpath->query('//base[@href]') as $base) { + /** @var DOMElement $base */ + foreach ($this->xpath->query('//base[@href]') ?: [] as $base) { $baseElementUrl = $base->getAttribute('href'); if (parse_url($baseElementUrl, PHP_URL_SCHEME) === null) { @@ -414,7 +470,11 @@ public function __construct($input, $url = null, $jsonMode = false) { } // Ignore