Skip to content

Commit

Permalink
//
Browse files Browse the repository at this point in the history
  • Loading branch information
madou1217 committed Oct 24, 2022
1 parent 9f49e9f commit 4e7f1a9
Show file tree
Hide file tree
Showing 8 changed files with 230 additions and 24 deletions.
29 changes: 29 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Tests

on:
push:
branches: [ master ]
pull_request:

jobs:
phpunit:
strategy:
matrix:
# 需要在以下 PHP 版本中测试
php_version: [ 8.1 ]
runs-on: ubuntu-latest
steps:
# 检出代码
- uses: actions/checkout@v2
# 初始化 PHP 环境
- name: Setup PHP environment
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php_version }}
coverage: xdebug
# 安装 composer 依赖
- name: Install dependencies
run: composer install
# 执行 PHPUnit 测试
- name: PHPUnit check
run: ./vendor/bin/phpunit --coverage-text
1 change: 1 addition & 0 deletions .phpunit.result.cache
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":1,"defects":{"WeatherTest::testGetWeatherWithInvalidType":3,"WeatherTest::testGetWeather":3,"WeatherTest::testGetForecastsWeather":3,"WeatherTest::testGetWeatherInfo":3,"WeatherTest::testGetLiveWeather":3},"times":{"WeatherTest::testGetWeatherWithInvalidType":0.054,"WeatherTest::testGetWeather":0.495,"WeatherTest::testGetLiveWeather":0.001,"WeatherTest::testGetForecastsWeather":0,"WeatherTest::testGetWeatherInfo":0.388}}
90 changes: 78 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,93 @@
<h1 align="center"> weather </h1>

<p align="center"> 高德天气.</p>

# 高德天气sdk
> 之前项目用过,但写的比较随意,刚好看到比较优质的教程,学习一下
## Installing

```shell
$ composer require madou1217/weather -vvv
```

### 使用方法:

```php
<?php
require __DIR__ .'/vendor/autoload.php';

use Madou1217\Weather\Weather;

// 高德开放平台应用 Key
$key = 'xxxxxxxxxxxxxxxxxxxxx';
$weather = new Weather($key);

// 城市 , 城市名称 或者 高德地图中城市对应的 adcode
$city_name = "乌鲁木齐市"

var_dump($weather->weatherInfo($city_name));

// 获取实时天气
$city_code = "654000";
$weather->getLiveWeather($city_code);

// 获取预报天气
$weather->getForecastWeather($city_code);

```

### 在Laravel中使用:

.env 中添加:

```
AMAP_WEATHER_KEY=xxxxxxxxx
```

config/weathers.php 中:

``` php
<?php

return [
'amap' => [
'key' => env('AMAP_WEATHER_KEY','U_DEFAULT_KEY'),
],
]
```

#### 可以用两种方式来获取 Overtrue\Weather\Weather 实例:

- 方法参数注入

```php
<?php

use Madou1217\Weather\Weather;

public function weather(Weather $weather)
{
$response = $weather->weatherInfo('乌鲁木齐市');
//TODO ...
}
```

## Usage
- 服务名访问

```php
<?php

TODO
use Madou1217\Weather\Weather;

## Contributing
public function weather()
{
$response = app('weather')->weatherInfo('乌鲁木齐市');
// TODO ...
}
```

You can contribute in one of three ways:

1. File bug reports using the [issue tracker](https://github.com/madou1217/weather/issues).
2. Answer questions or fix bugs on the [issue tracker](https://github.com/madou1217/weather/issues).
3. Contribute new features or update the wiki.
## 参考
- ### 学习地址: https://learnku.com/courses/creating-package
- ### [高德开放平台](https://lbs.amap.com/api/webservice/guide/api/weatherinfo)

_The code contribution process is not very formal. You just need to make sure that you follow the PSR-0, PSR-1, and PSR-2 coding guidelines. Any new code contributions must be accompanied by unit tests where applicable._

## License

Expand Down
8 changes: 8 additions & 0 deletions src/Exceptions/Exception.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Madou1217\Weather\Exceptions;

class Exception extends \Exception
{

}
2 changes: 1 addition & 1 deletion src/Exceptions/HttpException.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Madou1217\Weather\Exceptions;

class HttpException extends \Exception
class HttpException extends Exception
{

}
2 changes: 1 addition & 1 deletion src/Exceptions/InvalidArgumentException.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Madou1217\Weather\Exceptions;

class InvalidArgumentException extends \Exception
class InvalidArgumentException extends Exception
{

}
43 changes: 33 additions & 10 deletions src/Weather.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use InvalidArgumentException;
use Madou1217\Weather\Exceptions\HttpException;
use Madou1217\Weather\Exceptions\InvalidArgumentException;

class Weather
{
Expand All @@ -27,30 +27,53 @@ public function __construct(string $key)

/**
* @param string $city city_name | city_code
* @param int $type
* @param string $type 可选值:base/all
*
* base:返回实况天气
* all:返回预报天气
*
* @return array
* @throws GuzzleException
* @throws HttpException
* @throws InvalidArgumentException
*/
public function weatherInfo(string $city, int $type = 1)
public function weatherInfo(string $city, string $type = 'base'): array

{
$url = sprintf("%s/v3/weather/weatherInfo", $this->base_url);

if (!\in_array(\strtolower($type), [1, 2])) {
throw new InvalidArgumentException('Invalid type value(1:base/ 2:all),you are : '.$type);
if (!\in_array(\strtolower($type), ['base', 'all'])) {
throw new InvalidArgumentException('Invalid type value(base / all),you are: '.$type);
}

$query = [
'key' => $this->key,
'city' => $city,
'output' => 'json',
'extensions' => $type,
];
try {
$response = $this->client->get($url, [
'key' => $this->key,
'city' => $city,
'output' => 'json',
'extensions' => $type == 1 ? 'base' : 'all',
'query' => $query,
]);
return json_decode($response->getBody()->getContents(), true) ?: [];
} catch (\Exception $e) {
throw new HttpException($e->getMessage(), $e->getCode(), $e);
}
}

/**
* 获取实时天气
*/
public function getLiveWeather(string $city): array
{
return $this->weatherInfo($city, 'base');
}

/**
* 返回预报天气
*/
public function getForecastWeather(string $city): array
{
return $this->weatherInfo($city, 'all');
}
}
79 changes: 79 additions & 0 deletions tests/WeatherTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use Madou1217\Weather\Exceptions\HttpException;
use Madou1217\Weather\Exceptions\InvalidArgumentException;
use Madou1217\Weather\Weather;
use PHPUnit\Framework\TestCase;

class WeatherTest extends TestCase
{
// 检查 $type 参数
/**
* @throws GuzzleException
* @throws HttpException
*/
public function testGetWeatherWithInvalidType()
{
$w = new Weather('mock-key');
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid type value(base / all),you are: foo');
$w->weatherInfo('乌鲁木齐市', 'foo');
$this->fail('Failed to assert getWeather throw exception with invalid argument.');
}


/**
* @throws GuzzleException
* @throws InvalidArgumentException
* @throws HttpException
*/
public function testGetWeatherInfo()
{
// 创建模拟接口响应值。
$response = new Response(200, [], '{"success": true}');

// 创建模拟 http client。
$client = \Mockery::mock(Client::class);

// 指定将会产生的行为(在后续的测试中将会按下面的参数来调用)。
$client->allows()->get('https://restapi.amap.com/v3/weather/weatherInfo', [
'query' => [
'key' => 'mock-key',
'city' => '乌鲁木齐市',
'output' => 'json',
'extensions' => 'base',
],
])->andReturn($response);

// 将 `getHttpClient` 方法替换为上面创建的 http client 为返回值的模拟方法。
$w = \Mockery::mock(Weather::class, ['mock-key'])->makePartial();
$w->allows()->getHttpClient()->andReturn($client); // $client 为上面创建的模拟实例。

// 然后调用 `getWeather` 方法,并断言返回值为模拟的返回值。
$this->assertSame(['success' => true], $w->weatherInfo('乌鲁木齐市'));
}


public function testGetLiveWeather()
{
// 将 getWeather 接口模拟为返回固定内容,以测试参数传递是否正确
$w = \Mockery::mock(Weather::class, ['mock-key'])->makePartial();
$w->expects()->weatherInfo('乌鲁木齐市', 'base')->andReturn(['success' => true]);

// 断言正确传参并返回
$this->assertSame(['success' => true], $w->getLiveWeather('乌鲁木齐市'));
}

public function testGetForecastsWeather()
{
// 将 getWeather 接口模拟为返回固定内容,以测试参数传递是否正确
$w = \Mockery::mock(Weather::class, ['mock-key'])->makePartial();
$w->expects()->weatherInfo('乌鲁木齐市', 'all')->andReturn(['success' => true]);

// 断言正确传参并返回
$this->assertSame(['success' => true], $w->getForecastWeather('乌鲁木齐市'));
}
}

0 comments on commit 4e7f1a9

Please sign in to comment.