first commit

This commit is contained in:
zhouyangyang 2022-06-14 15:49:44 +08:00
commit c08202d8cf
17 changed files with 642 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
/tests export-ignore
/.github export-ignore

25
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,25 @@
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
name: Release
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false

73
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,73 @@
name: PHPUnit
on: [ push, pull_request ]
env:
SWOOLE_VERSION: '4.8.10'
SWOW_VERSION: 'develop'
jobs:
ci:
name: Test PHP ${{ matrix.php-version }} on ${{ matrix.engine }}
runs-on: "${{ matrix.os }}"
strategy:
matrix:
os: [ ubuntu-latest ]
php-version: [ '7.3', '7.4', '8.0' ]
engine: [ 'none', 'swoole', 'swow' ]
exclude:
- php-version: '7.3'
engine: 'swow'
- php-version: '7.4'
engine: 'swow'
max-parallel: 5
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
tools: phpize
ini-values: opcache.enable_cli=0
coverage: none
- name: Setup Swoole
if: ${{ matrix.engine == 'swoole' }}
run: |
cd /tmp
sudo apt-get update
sudo apt-get install libcurl4-openssl-dev
wget https://github.com/swoole/swoole-src/archive/v${SWOOLE_VERSION}.tar.gz -O swoole.tar.gz
mkdir -p swoole
tar -xf swoole.tar.gz -C swoole --strip-components=1
rm swoole.tar.gz
cd swoole
phpize
./configure --enable-openssl --enable-http2 --enable-swoole-curl --enable-swoole-json
make -j$(nproc)
sudo make install
sudo sh -c "echo extension=swoole > /etc/php/${{ matrix.php-version }}/cli/conf.d/swoole.ini"
php --ri swoole
- name: Setup Swow
if: ${{ matrix.engine == 'swow' }}
run: |
cd /tmp
wget https://github.com/swow/swow/archive/"${SWOW_VERSION}".tar.gz -O swow.tar.gz
mkdir -p swow
tar -xf swow.tar.gz -C swow --strip-components=1
rm swow.tar.gz
cd swow/ext || exit
phpize
./configure --enable-debug
make -j "$(nproc)"
sudo make install
sudo sh -c "echo extension=swow > /etc/php/${{ matrix.php-version }}/cli/conf.d/swow.ini"
php --ri swow
- name: Setup Packages
run: composer update -o --no-scripts
- name: Run Test Cases
run: |
vendor/bin/php-cs-fixer fix --dry-run
composer analyse
composer test

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
/.idea
/vendor/
composer.lock
*.cache
*.log

89
.php-cs-fixer.php Normal file
View File

@ -0,0 +1,89 @@
<?php
$header = <<<'EOF'
This file is part of Hyperf.
@link https://www.hyperf.io
@document https://hyperf.wiki
@contact group@hyperf.io
@license https://github.com/hyperf/hyperf/blob/master/LICENSE
EOF;
return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules([
'@PSR2' => true,
'@Symfony' => true,
'@DoctrineAnnotation' => true,
'@PhpCsFixer' => true,
'header_comment' => [
'comment_type' => 'PHPDoc',
'header' => $header,
'separate' => 'none',
'location' => 'after_declare_strict',
],
'array_syntax' => [
'syntax' => 'short'
],
'list_syntax' => [
'syntax' => 'short'
],
'concat_space' => [
'spacing' => 'one'
],
'blank_line_before_statement' => [
'statements' => [
'declare',
],
],
'general_phpdoc_annotation_remove' => [
'annotations' => [
'author'
],
],
'ordered_imports' => [
'imports_order' => [
'class', 'function', 'const',
],
'sort_algorithm' => 'alpha',
],
'single_line_comment_style' => [
'comment_types' => [
],
],
'yoda_style' => [
'always_move_variable' => false,
'equal' => false,
'identical' => false,
],
'phpdoc_align' => [
'align' => 'left',
],
'multiline_whitespace_before_semicolons' => [
'strategy' => 'no_multi_line',
],
'constant_case' => [
'case' => 'lower',
],
'class_attributes_separation' => true,
'combine_consecutive_unsets' => true,
'declare_strict_types' => true,
'linebreak_after_opening_tag' => true,
'lowercase_static_reference' => true,
'no_useless_else' => true,
'no_unused_imports' => true,
'not_operator_with_successor_space' => true,
'not_operator_with_space' => false,
'ordered_class_elements' => true,
'php_unit_strict' => false,
'phpdoc_separation' => false,
'single_quote' => true,
'standardize_not_equals' => true,
'multiline_comment_opening_closing' => true,
])
->setFinder(
PhpCsFixer\Finder::create()
->exclude('vendor')
->in(__DIR__)
)
->setUsingCache(false);

6
.phpstorm.meta.php Normal file
View File

@ -0,0 +1,6 @@
<?php
namespace PHPSTORM_META {
// Reflect
override(\Psr\Container\ContainerInterface::get(0), map('@'));
}

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Hyperf
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

5
README.md Normal file
View File

@ -0,0 +1,5 @@
# component-creator
```
composer create-project hyperf/component-creator
```

57
composer.json Normal file
View File

@ -0,0 +1,57 @@
{
"name": "zyimm/hyperf-mmds-oss",
"type": "library",
"license": "MIT",
"keywords": [
"php",
"hyperf",
"oss"
],
"description": "",
"autoload": {
"psr-4": {
"Zyimm\\MmdsOss\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"HyperfTest\\": "tests"
}
},
"require": {
"php": ">=7.4",
"ext-json": "*",
"ext-fileinfo": "*",
"hyperf/framework": "~2.2.0",
"hyperf/guzzle": "~2.2.0",
"hyperf/http-server": "~2.2.0",
"hyperf/json-rpc": "^2.2",
"hyperf/logger": "~2.2.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.0",
"mockery/mockery": "^1.0",
"phpstan/phpstan": "^1.0",
"phpunit/phpunit": ">=7.0",
"swoole/ide-helper": "^4.5"
},
"suggest": {
"swow/swow": "Required to create swow components."
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"optimize-autoloader": true,
"sort-packages": true
},
"scripts": {
"test": "phpunit -c phpunit.xml --colors=always",
"analyse": "phpstan analyse --memory-limit 1024M -l 0 ./src",
"cs-fix": "php-cs-fixer fix $1"
},
"extra": {
"hyperf": {
"config": "Zyimm\\MmdsOss\\ConfigProvider"
}
}
}

15
phpunit.xml Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php"
backupGlobals="false"
backupStaticAttributes="false"
verbose="true"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuite name="Testsuite">
<directory>./tests/</directory>
</testsuite>
</phpunit>

7
publish/mmds_oss.php Normal file
View File

@ -0,0 +1,7 @@
<?php
return [
'xy_oss_service_name' => env('XY_OSS_SERVICE', 'mmds'),
'xy_oss_group_name' => env('XY_OSS_GROUP', 'mmds-hoge'),
'xy_oss_url' => env('XY_OSS_URL', 'https://static-mmds.aihoge.com'),
'xy_oss_bucket_name' => env('XY_OOS_BUCKET_NAME', 'mmdsstatic')
];

40
src/ConfigProvider.php Normal file
View File

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Zyimm\MmdsOss;
class ConfigProvider
{
public function __invoke(): array
{
return [
'dependencies' => [
],
'publish' => [
[
'id' => 'MmdsOss',
'description' => 'The config for oss.',
'source' => __DIR__ . '/../publish/mmds_oss.php',
'destination' => BASE_PATH . '/config/autoload/mmds_oss.php',
],
],
'commands' => [
],
'annotations' => [
'scan' => [
'paths' => [
__DIR__,
],
],
],
];
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace Zyimm\MmdsOss\Exception;
use RuntimeException;
class OssException extends RuntimeException
{
}

230
src/Oss.php Normal file
View File

@ -0,0 +1,230 @@
<?php
namespace Zyimm\MmdsOss;
use Carbon\Carbon;
use finfo;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use Zyimm\MmdsOss\Exception\OssException;
class Oss
{
public array $oss = [];
public ?string $authorization = null;
/**
* @Inject()
* @var ClientFactory
*/
public ClientFactory $clientFactory;
/**
* @Inject
* @var RequestInterface
*/
public RequestInterface $request;
/**
* @Inject
*
* @var ConfigInterface
*/
public ConfigInterface $config;
/**
* upload
*
* @return array
* @throws ContainerExceptionInterface
* @throws GuzzleException
* @throws NotFoundExceptionInterface
*/
public function upload(): array
{
$file = $this->request->file('file');
$file_content = file_get_contents($file->getPathname());
$fInfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $fInfo->buffer($file_content);
$file_info = [
'name' => 'file',
'contents' => fopen($file->getPathname(), 'r'),
'filename' => Carbon::now()->getTimestampMs().uniqid().'.'.$file->getExtension(),
];
$result = $this->getSecretKey()->bucket()->ossUpload($file_info);
return [
'url' => $result['file_url'] ?? '',
'size' => $result['file_size'] ?? 0,
'mime_type' => $mimeType
];
}
/**
* getUploadAttr
*
* @return array
* @throws ContainerExceptionInterface
* @throws GuzzleException
* @throws NotFoundExceptionInterface
*/
public function getUploadAttr(): array
{
$this->getSecretKey()->bucket();
return [
'timestamp' => time(),
'filestorage-authorization' => $this->authorization,
'bucket' => $this->getBucketName()
];
}
/**
* ossUpload
*
* @param $file_info
* @return array
* @throws GuzzleException
*/
private function ossUpload($file_info): array
{
$client = $this->clientFactory->create([
'base_uri' => $this->getBaseUri(),
'headers' => array_merge($this->request->getHeaders(), [
'filestorage-authorization' => $this->authorization,
'timestamp' => time()
])
]);
$path = 'backend/normalUpload';
$response = $client->request($this->request->getMethod(), $path, [
'multipart' => [
$file_info,
[
'name' => 'object_key',
'contents' => $file_info['filename']
],
[
'name' => 'bucket',
'contents' => $this->getBucketName()
]
]
]);
$data = json_decode($response->getBody()->getContents(), true);
if (isset($data['error_code']) && (int) $data['error_code'] == 200) {
return $data['result'] ?? [];
} else {
throw new OssException($data['error_message'] ?? 'oss upload error',
$data['error_code'] ?? __LINE__);
}
}
private function getBaseUri()
{
return $this->config->get('mmds_oss.xy_oss_url');
}
private function getBucketName()
{
return $this->config->get('mmds_oss.xy_oss_bucket_name');
}
/**
* getSecretKey
*
* @return Oss
* @throws ContainerExceptionInterface
* @throws GuzzleException
* @throws NotFoundExceptionInterface
*/
private function bucket(): Oss
{
$this->getSecretKey();
$time = time();
$this->authorization = $this->oss['access_key_id'].':'.base64_encode(
hash_hmac('sha1',
$this->oss['secret_key'],
(string) $time, true));
$bucket = $this->getBucketName();
$client = $this->clientFactory->create([
'base_uri' => $this->getBaseUri(),
'headers' => [
'filestorage-authorization' => $this->authorization,
'timestamp' => $time,
'Content-Type' => 'application/json'
]
]);
$path = '/backend/bucket';
$response = $client->request('POST', $path, [
'json' => [
'bucket_name' => $bucket
],
]);
$data = json_decode($response->getBody()->getContents(), true);
if (isset($data['error_code']) && (int) $data['error_code'] == 200) {
$this->logger()->info('oss', $data);
} else {
throw new OssException($data['error_message'] ?? 'oss upload error',
$data['error_code'] ?? __LINE__);
}
return $this;
}
/**
* getSecretKey
*
* @throws GuzzleException
*/
private function getSecretKey(): Oss
{
if (!$this->oss) {
$client = $this->clientFactory->create([
'base_uri' => $this->getBaseUri(),
'headers' => $this->request->getHeaders()
]);
$path = '/backend/secretKey?'.http_build_query([
'service_name' => $this->config->get('mmds_oss.xy_oss_service_name'),
'group_name' => $this->config->get('mmds_oss.xy_oss_group_name'),
]);
$response = $client->request('GET', $path);
$data = json_decode($response->getBody()->getContents(), true);
if (isset($data['error_code']) && (int) $data['error_code'] == 200) {
$this->oss = [
'access_key_id' => $data['result']['accessKeyId'] ?? null,
'secret_key' => $data['result']['secretKey'] ?? null
];
} else {
throw new OssException($data['error_message'] ?? 'oss error',
$data['error_code'] ?? __LINE__);
}
}
return $this;
}
/**
* logger
*
* @return LoggerInterface
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function logger(): LoggerInterface
{
return ApplicationContext::getContainer()->get(LoggerFactory::class)->get('oss');
}
}

View File

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace HyperfTest\Cases;
use PHPUnit\Framework\TestCase;
/**
* Class AbstractTestCase.
*/
abstract class AbstractTestCase extends TestCase
{
}

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace HyperfTest\Cases;
/**
* @internal
* @coversNothing
*/
class ExampleTest extends AbstractTestCase
{
public function testExample()
{
$this->assertTrue(true);
}
}

12
tests/bootstrap.php Normal file
View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
require_once dirname(dirname(__FILE__)) . '/vendor/autoload.php';