浏览代码

Add allowEmptyData option to validation processor

phpdevcommunity 8 月之前
父节点
当前提交
81058e74c5
共有 2 个文件被更改,包括 12 次插入5 次删除
  1. 7 3
      src/Schema/AbstractSchema.php
  2. 5 2
      src/Schema/SchemaAccessor.php

+ 7 - 3
src/Schema/AbstractSchema.php

@@ -50,16 +50,20 @@ abstract class AbstractSchema
 
     final public function processHttpRequest(ServerRequestInterface $request): SchemaAccessor
     {
+        if ($request->getHeader('Content-Type')[0] === 'application/json') {
+            return $this->processJsonInput($request->getBody()->getContents());
+        }
         return $this->process($request->getParsedBody());
     }
+
     final public function processHttpQuery(ServerRequestInterface $request): SchemaAccessor
     {
-        return $this->process($request->getQueryParams());
+        return $this->process($request->getQueryParams(), true);
     }
 
-    final public function process(array $data): SchemaAccessor
+    final public function process(array $data, bool $allowEmptyData = false): SchemaAccessor
     {
-        $accessor = new SchemaAccessor($data, $this);
+        $accessor = new SchemaAccessor($data, $this, $allowEmptyData);
         $accessor->execute();
         return $accessor;
     }

+ 5 - 2
src/Schema/SchemaAccessor.php

@@ -14,16 +14,19 @@ final class SchemaAccessor
     private ?\ArrayObject $data = null;
     private bool $executed = false;
 
-    public function __construct(array $initialData, Schema $schema)
+    private bool $allowEmptyData;
+
+    public function __construct(array $initialData, Schema $schema, bool $allowEmptyData = false)
     {
         $this->initialData = $initialData;
         $this->schema = $schema;
+        $this->allowEmptyData = $allowEmptyData;
     }
 
     public function execute(): void
     {
         $data = $this->initialData;
-        if (empty($data)) {
+        if (empty($data) && $this->allowEmptyData === false) {
             throw new InvalidDataException('No data provided', 0);
         }