<?php

use Symfony\Component\Validator\ConstraintViolationListInterface;

/**
 * Shared handling of Symfony validator violations for request validators.
 */
trait ValidatesRequests
{
    /**
     * @param ConstraintViolationListInterface $issues
     * @throws \InvalidArgumentException
     * @return void
     */
    protected static function throwOnIssues(ConstraintViolationListInterface $issues): void
    {
        if (count($issues) === 0) {
            return;
        }

        $response = [
            'success' => false,
            'errors' => []
        ];
        foreach ($issues as $issue) {
            $response['errors'][] = [
                'field' => $issue->getPropertyPath(),
                'message' => $issue->getMessage()
            ];
        }

        throw new \InvalidArgumentException(json_encode($response));
    }
}
