Skip to content

Commit

Permalink
Tests
Browse files Browse the repository at this point in the history
  • Loading branch information
smnandre committed May 14, 2024
1 parent 2bc7bfd commit d4a9a9a
Show file tree
Hide file tree
Showing 5 changed files with 123 additions and 25 deletions.
45 changes: 36 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,27 @@
This library provides a simple way to interact with the Google PageSpeed Insights API.

```php
use PageSpeed\Api\PageSpeedApi;
use PageSpeed\Api\Analysis\Category;use PageSpeed\Api\PageSpeedApi;

$api = new PageSpeedApi('YOUR_API');

$audit = $api->audit('https://www.example.com');
$analysis = $api->analyse('https://www.example.com');

echo $audit->getScore(); // 100
echo $audit->performanceScore(); // 100
echo $audit->getAccessibilityScore(); // 100
// LightHouse scores
echo $audit->getPerformancesScore(); // 100
echo $audit->getAccessibilityScore(); // 88
echo $audit->getBestPracticesScore(); // 100
echo $audit->getSeoScore(); // 90

// Loading Experience metrics
echo $audit->getLargestContentfulPaint(); //
echo $audit->getInteractiveToNextPaint(); //
echo $audit->getCumulativeLayoutShift(); //
echo $audit->getFirstContentfulPaint(); //
echo $audit->getFirstInputDelay(); //
echo $audit->getTimeToFirstByte(); //
```


## Installation

```bash
Expand All @@ -33,16 +41,35 @@ use PageSpeed\Api\PageSpeedApi;
$api = new PageSpeedApi('YOUR_API');
```

### Audit Strategy
### Parameters

#### Audit Strategy

```php
// Mobile strategy (default)
$audit = $api->audit('https://example.com/', 'mobile');
$audit = $api->analyse('https://example.com/', 'mobile');

// Desktop strategy
$audit = $api->audit('https://example.com/', 'desktop');
$audit = $api->analyse('https://example.com/', 'desktop');
```

#### Analysis Categories


### Response

#### Analysis


#### Loading Experience


#### Original Loading Experience

..

#### Lighthouse

```php
use PageSpeed\Api\PageSpeedApi;

Expand Down
42 changes: 29 additions & 13 deletions src/PageSpeedApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,45 @@ public function __construct(
$this->client = $client ?? HttpClient::create();
}

public function analyse(string $url, ?Strategy $strategy = null, ?string $locale = null, array $category = []): Analysis
public function analyse(string $url, Strategy|string|null $strategy = null, ?string $locale = null, array $categories = []): Analysis
{
if (!filter_var($url, FILTER_VALIDATE_URL)) {
throw new \InvalidArgumentException('Invalid URL provided.');
}

// PageSpeed API uses multiple category parameters
$category = array_map(fn (Category $cat) => strtoupper(str_replace('-', '_', $cat->value)), Category::cases());
if (is_string($strategy)) {
if (!in_array($strategy, Strategy::values())) {
throw new \InvalidArgumentException(sprintf('Invalid strategy "%s" provided.', $strategy));
}
$strategy = Strategy::from($strategy);
}

if ($locale && !preg_match('/^[a-z]{2}(_[A-Z]{2})?$/', $locale)) {
throw new \InvalidArgumentException(sprintf('Invalid locale "%s" provided.', $locale));
}

$cache = __DIR__ . '/../tests/cache/cache-' . urlencode(str_replace(['://', '.'], '-', $url)) . $strategy?->value. '.json';
if (file_exists($cache)) {
/** @phpstan-ignore-next-line */
return Analysis::create(json_decode(file_get_contents($cache), true, 512, JSON_THROW_ON_ERROR));
foreach ($categories as $i => $category) {
if (!$category instanceof Category) {
if (!in_array($category, Strategy::values())) {
throw new \InvalidArgumentException(sprintf('Invalid category "%s" provided.', $category));
}
$categories[$i] = Category::from($category);
}
}
if([] === $categories = array_unique($categories)) {
$categories = Category::cases();
}

// PageSpeed API uses multiple category parameters
$category = array_map(fn (Category $cat) => strtoupper(str_replace('-', '_', $cat->value)), $categories);

$response = $this->get('runPagespeed?category='.implode('&category=', $category), [
'url' => $url,
'strategy' => $strategy?->value,
'locale' => $locale,
'category' => $category,
]);

file_put_contents($cache, json_encode($response));

return Analysis::create($response);
}

Expand All @@ -75,13 +91,13 @@ private function get(string $uri, array $parameters = []): array
'headers' => [
'Accept' => 'application/json',
'User-Agent' => 'PageSpeed.md',
'X-PageSpeed-Api' => self::BASE_URI
'X-PageSpeed-Api' => self::BASE_URI,
],
]);

// if (200 !== $response->getStatusCode()) {
// throw new \RuntimeException('An error occurred while fetching the data.', $response->getStatusCode(), $response->getContent());
// }
if (200 !== $response->getStatusCode()) {
throw new \RuntimeException('Unexpected response code "%s" returned by PageSpeed Api.', $response->getStatusCode());
}

return $response->toArray();
}
Expand Down
4 changes: 2 additions & 2 deletions src/PageSpeedApiInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
interface PageSpeedApiInterface
{
/**
* @param list<Category> $category
* @param list<Category> $categories
*/
public function analyse(string $url, ?Strategy $strategy = null, ?string $locale = null, array $category = []): Analysis;
public function analyse(string $url, ?Strategy $strategy = null, ?string $locale = null, array $categories = []): Analysis;
}
2 changes: 1 addition & 1 deletion tests/Unit/AnalysisTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* file that was distributed with this source code.
*/

namespace PageSpeed\Api\Tests\Unit\Audit;
namespace PageSpeed\Api\Tests\Unit;

use PageSpeed\Api\Analysis;
use PageSpeed\Api\Tests\Fixtures\AnalysisFactory;
Expand Down
55 changes: 55 additions & 0 deletions tests/Unit/PageSpeedApiTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

/*
* This file is part of the pagespeed/api package.
*
* (c) Simon Andre <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace PageSpeed\Api\Tests\Unit;

use PageSpeed\Api\Analysis;
use PageSpeed\Api\PageSpeedApi;
use PageSpeed\Api\Tests\Fixtures\AnalysisFactory;
use PageSpeed\Api\Tests\Fixtures\LighthouseCategoryResultFactory;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\JsonMockResponse;

#[CoversClass(PageSpeedApi::class)]
class PageSpeedApiTest extends TestCase
{
public function testAnalysis(): void
{
$response = JsonMockResponse::fromFile(__DIR__.'/../Fixtures/response.json');
$api = new PageSpeedApi('API_KEY', new MockHttpClient($response));

$analysis = $api->analyse('https://example.com');

self::assertInstanceOf(Analysis::class, $analysis);
}

#[DataProvider('provideInvalidParameters')]
public function testAnalysisInvalidParameters(array $parameters): void
{
$api = new PageSpeedApi();
self::expectException(\InvalidArgumentException::class);

$api->analyse(...$parameters);
}

public static function provideInvalidParameters(): iterable
{
yield 'invalid_url' => [['https://']];
yield 'invalid_strategy' => [['https://example.com', 'invalid']];
yield 'invalid_locale' => [['https://example.com', null, 'invalid']];
yield 'invalid_category' => [['https://example.com', null, null, ['invalid']]];
}
}

0 comments on commit d4a9a9a

Please sign in to comment.