private function checkCode(
        Request $request,
        $clientId
    ) {
        // code is required and must in valid format.
        $code = $request->request->get('code');
        $errors = $this->validator->validate($code, [
            new \Symfony\Component\Validator\Constraints\NotBlank(),
            new \AuthBucket\OAuth2\Symfony\Component\Validator\Constraints\Code(),
        ]);
        if (count($errors) > 0) {
            throw new InvalidRequestException([
                'error_description' => 'The request includes an invalid parameter value.',
            ]);
        }

        // Check code with database record.
        $codeManager = $this->modelManagerFactory->getModelManager('code');
        $result = $codeManager->readModelOneBy([
            'code' => $code,
        ]);
        if ($result === null || $result->getClientId() !== $clientId) {
            throw new InvalidGrantException([
                'error_description' => 'The provided authorization grant is invalid.',
            ]);
        } elseif ($result->getExpires() < new \DateTime()) {
            throw new InvalidGrantException([
                'error_description' => 'The provided authorization grant is expired.',
            ]);
        }

        return [$result->getUsername(), $result->getScope()];
    }