openium/symfony-toolkit

Openium Web Toolkit for Symfony Project

安装次数: 7,474

依赖者: 0

建议者: 0

安全性: 0

星标: 2

关注者: 6

分支: 0

开放问题: 0

类型:symfony-bundle

4.1.6 2024-03-25 14:56 UTC

README

此 symfony 扩展提供了许多常见场景的抽象。

安装

打开命令行控制台,进入您的项目目录并执行

$ composer require openium/symfony-toolkit

对于 Symfony 7 使用 v4

对于 Symfony 6 使用 v3

对于 Symfony < 6 使用 v2

使用方法

AbstractController

为控制器添加 2 个受保护的方法

  • getContentFromRequest: 从请求中获取 JSON 主体
  • getMultipartContent: 从 multipart 请求中获取 JSON 主体
  • extractObjectFromString: 从字符串中获取 JSON(由 getContentFromRequest 和 getMultipartContent 使用)
  • getFilterParameters: 从请求中获取过滤器查询参数

过滤器

添加一个包含来自查询参数的过滤器的类。

要获取过滤器,请在 AbstractController 中使用 getFilterParameters。

您还可以使用 FilterRepositoryUtils->applyFilters() 在查询中定义排序、限制和偏移量。

关于过滤器的说明

  • 如果传递了页面参数但没有限制参数,则限制设置为 10
  • 如果传递了 order-by 参数但没有 order 参数,则排序设置为 ASC

PaginatedResult

PaginatedResult 允许您为使用了过滤器的端点获取格式化的结果。

ServerService

此服务提供了一种获取实际服务器 URL 的方式。

添加 ServerServiceInterface 并使用依赖注入,使用其中的 getBasePath() 方法。

    function myFunc(ServerServiceInterface $serverService): mixed
    {
        // ...
        $basePath = $serverService->getBasePath();
        // ...
    }

FileUploaderService

此服务帮助您管理具有上传 文件引用 的实体。注意,此服务仅允许一个上传属性。

首先,实现您的实体 WithUploadInterface。

然后,您可以使用 WithUploadTrait,它包含实现接口所需的一些方法和属性。

然后,将 FileUploaderServiceInterface 服务注入到您的实体事件监听器中。

最后,像这样使用服务

  • prepareUploadPath 在 prePersist 和 preUpdate 中,在持久化到数据库之前设置实体属性
    $fileUploaderService->prepareUploadPath($entity);
  • upload 在 postPersist 和 postUpdate 中,将上传移动到正确的目录
    $fileUploaderService->upload($entity);
  • removeUpload 在 postPersist 和 postRemove 中,删除上传文件
    $fileUploaderService->removeUpload($entity);

AtHelper

允许您使用 Unix AT 命令执行一些命令。

  • 要创建新的 AT 作业
    
    // $cmd command to execute
    // $timestamp when the command will be executed
    // $path path where the at creation command will be executed
    // &$result result of at
    $output = $atHelper->createAtCommandFromPath($cmd, $timestamp, $path, $result);
    
    // get at job number
    $jobNumber = $atHelper->extractJobNumberFromAtOutput($output);
  • 要删除现有的 AT 作业,从 extractJobNumberFromAtOutput() 方法中保存 jobNumber 并使用它与 removeAtCommand() 方法。
    $removeSuccess = $atHelper->removeAtCommand($jobNumber);

DoctrineExceptionHandlerService

将 doctrine 异常转换为 HttpException。

在大多数情况下,异常将是一个 BadRequestHttpException。

但如果数据库错误涉及到冲突,该方法将抛出 ConflictHttpException。

要使用它,您需要注入 DoctrineExceptionHandlerServiceInterface 服务。

        try {
            $this->em->persist($y);
            $this->em->flush();
        } catch (\Exception $e) {
            $this->doctrineExceptionHandlerService->toHttpException($e);
        }

与 doctrine 异常配合良好,但不能与其他/自定义异常配合

ExceptionFormatService

将异常转换为 JSON 响应。异常的响应现在是通用的,这意味着您可以向响应提供自己的代码、文本和消息。

如果您想添加特定的代码,首先覆盖包中的服务。您必须在 config/services.yaml 中添加自己的服务。

例如

    openium_symfony_toolkit.exception_format:
        class: App\Service\ExceptionFormatService
        arguments:
            - '@kernel'
        public: true

然后,您需要在项目中创建一个 ExceptionFormatService 并扩展包中的那个。

可以覆盖 2 个方法和一个属性

  • genericExceptionResponse 将定义每个部分的异常: $code, $text, $message
  • addKeyToErrorArray 将向最终的 JSON 对象添加键
  • $jsonKeys 用于覆盖最终的json键

示例

<?php
namespace App\Service;

use Openium\SymfonyToolKitBundle\Service\ExceptionFormatService as BaseExceptionFormatService;
use Openium\SymfonyToolKitBundle\Service\ExceptionFormatServiceInterface;

class ExceptionFormatService extends BaseExceptionFormatService implements ExceptionFormatServiceInterface {

    protected array $jsonKeys = [
        'code' => 'statusCode',
        'text' => 'statusText',
        'message' => 'message',
    ];
    
    public function genericExceptionResponse(Exception $exception): array
    {
        // You define conditions and exceptions[ExceptionFormatExtendService.php](Tests%2FService%2FExceptionFormatExtendService.php) you want here 
        if ($exception instanceof MyException) {
            $code = 123;
            $text = 'This is my custom exception text';
            $message = $text;
            return [$code, $text, $message];
        }
        // Or use the default method in the toolkit
        return parent::genericExceptionResponse($exception);
    }

    public function addKeyToErrorArray(array $error, Exception $exception): array
    {
        if ($exception instanceof MyException) {
            $error['MyNewKey'] = 'value';
        }
        return $error;
    }
}

您格式化的异常将被用于 formatExceptionResponse 方法中。这样您就可以处理自定义异常。

    $response = $this->exceptionFormat->formatExceptionResponse($exception);

PathExceptionListener

监听器捕获内核异常,并通过 ExceptionFormatService 将它们转换为 HttpException。

默认启用并具有以下配置

parameters:
  openium_symfony_toolkit.kernel_exception_listener_enable: true
  openium_symfony_toolkit.kernel_exception_listener_path: '/api'
  openium_symfony_toolkit.kernel_exception_listener_class: 'Openium\SymfonyToolKitBundle\EventListener\PathExceptionListener'

它使用 ExceptionFormatService 自动格式化仅定义在 exception_listener_path 参数中的路由的内核异常

MemoryUtils

用于显示内存使用情况或将字节数转换为可读的字符串。

$str = MemoryUtils::convert(1024);
// $str = '1 kb';

$phpMemory = MemoryUtils::getMemoryUsage();
// apply convert() to actual php memory usage

ContentExtractorService

用于从具有特定键的数组中提取数据类型。

    $myString = ContentExtractorUtils::getString($content, $key);

具有允许空值、设置默认值和设置是否必需的选项。

方法列表

  • getString
  • getBool
  • getInt
  • getFloat
  • getDateTimeInterface
  • getArray

所有方法在值缺失或类型不正确(取决于参数)时,都会抛出带有正确消息的 400 HTTP 错误。

所有这些方法背后都是控制方法。

检查方法列表

  • checkKeyExists
  • checkKeyIsString
  • checkKeyIsBoolean
  • checkKeyIsInt
  • checkKeyIsFloat
  • checkKeyIsArray

checkKeyIs{type} 方法使用 checkKeyExists()。

此类中的所有方法都是静态的。

DateStringUtils

提供静态方法从字符串中获取日期

public static function getDateTimeFromString(
    string $dateString,
    ?string $format = null,
    ?DateTimeZone $timeZone = null
): DateTime | false

如果没有提供格式,该方法将尝试确定正确的日期格式。

可以检测两种格式

  • ATOM 'Y-m-d\TH:i:sP'
  • ISO8601 'Y-m-d\TH:i:sO'

如果没有检测到格式,该方法将回退到 'Y-m-d' 格式,如果字符串无法解析为 DateTime,则返回 false。