Symfony - DateTime 作为参数

Symfony - DateTime as param

我在使用 Symfony 定义日期时间参数时遇到问题。

如果 last_scan_date 为 null,我将尝试 return null 如果没有 return 结果!

错误说:

Argument 2 passed to checkLastScan() must be an instance of DateTime, string given

我的函数:

public function checkLastScan($hash, \DateTime $lastScanDate)
{
    $findLastScan = $this->getMyRepository()->findOneBy([
        'hash' => $hash,
        'lastScanDate' => $lastScanDate
    ]);

    if (!$findLastScan) {
        throw new \Exception('Not found!');
    }

    if ($lastScanDate === null) {
        return null;
    } else {
        return $findLastScan;
    }
}

我的电话:

$this->requirePostParams(['hash', 'last_scan_date']);

$this->container->get('app')->checkLastScan(
        $this->data['hash'],
        $this->data['last_scan_date']
    );

    return $this->success();

和实体:

/**
 * @ORM\Column(name="last_scan_date", type="date", nullable=true)
 */
private $lastScanDate;

也许问题是在需要 post 参数时,例如:

/**
 * Require post params
 *
 * @param $params
 */
protected function requirePostParams($params)
{
    $currentRequest = $this->get('request_stack')->getCurrentRequest();

    $postData = $currentRequest->request->all();

    $postContent = json_decode($currentRequest->getContent(), true);

    if (!empty($postContent)) {
        $postData = $postContent;
    }

    $this->data = $postData;

    $missingParams = [];

    foreach ($params as $param) {
        if (!array_key_exists($param, $postData)) {
            $missingParams[] = $param;
        }
    }

如果$this->data(我一开始问了,但你没有正确回答我)只是POST数组,当然数组的所有成员都被视为字符串。

您必须解析 last_scan_date 字符串并将其转换为 DateTime 类型。

这是函数的代码(将 YOUR_POST_FORMAT 的值更改为您在 HTML 表单中使用的格式):

/**
 * Require post params
 *
 * @param $params
 */
protected function requirePostParams($params)
{
    $currentRequest = $this->get('request_stack')->getCurrentRequest();

    $postData = $currentRequest->request->all();

    $postContent = json_decode($currentRequest->getContent(), true);

    if (!empty($postContent)) {
        $postData = $postContent;
    }

    // HERE YOU PARSE STRING TO DATETIME TYPE
    if (isset($postData['last_scan_date']) && !empty($postData['last_scan_date'])) {
        $postData['last_scan_date'] = DateTime::createFromFormat('YOUR POST FORMAT', $postData['last_scan_date'])
    } else {
        $postData['last_scan_date'] = null;
    }

    $this->data = $postData;

    $missingParams = [];

    foreach ($params as $param) {
        if (!array_key_exists($param, $postData)) {
            $missingParams[] = $param;
        }
    }
}