ParseException example

/** * Parses a YAML file into a PHP value. * * @param string $filename The path to the YAML file to be parsed * @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior * * @throws ParseException If the file could not be read or the YAML is not valid */
    public function parseFile(string $filename, int $flags = 0): mixed
    {
        if (!is_file($filename)) {
            throw new ParseException(sprintf('File "%s" does not exist.', $filename));
        }

        if (!is_readable($filename)) {
            throw new ParseException(sprintf('File "%s" cannot be read.', $filename));
        }

        $this->filename = $filename;

        try {
            return $this->parse(file_get_contents($filename)$flags);
        } finally {
            
// U+0085 NEXT LINE             'N' => "\xC2\x85",
            // U+00A0 NO-BREAK SPACE             '_' => "\xC2\xA0",
            // U+2028 LINE SEPARATOR             'L' => "\xE2\x80\xA8",
            // U+2029 PARAGRAPH SEPARATOR             'P' => "\xE2\x80\xA9",
            'x' => self::utf8chr(hexdec(substr($value, 2, 2))),
            'u' => self::utf8chr(hexdec(substr($value, 2, 4))),
            'U' => self::utf8chr(hexdec(substr($value, 2, 8))),
            default => throw new ParseException(sprintf('Found unknown escape character "%s".', $value)),
        };
    }

    /** * Get the UTF-8 character for the given code point. */
    private static function utf8chr(int $c): string
    {
        if (0x80 > $c %= 0x200000) {
            return \chr($c);
        }
        

            }
        }

        return $this->display($io$filesInfo);
    }

    private function validate(string $content, int $flags, string $file = null): array
    {
        $prevErrorHandler = set_error_handler(function D$level$message$file$line) use (&$prevErrorHandler) {
            if (\E_USER_DEPRECATED === $level) {
                throw new ParseException($message$this->getParser()->getRealCurrentLineNb() + 1);
            }

            return $prevErrorHandler ? $prevErrorHandler($level$message$file$line) : false;
        });

        try {
            $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
        } catch (ParseException $e) {
            return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
        } finally {
            restore_error_handler();
        }

            }
        }

        return $this->display($io$filesInfo);
    }

    private function validate(string $content, int $flags, string $file = null): array
    {
        $prevErrorHandler = set_error_handler(function D$level$message$file$line) use (&$prevErrorHandler) {
            if (\E_USER_DEPRECATED === $level) {
                throw new ParseException($message$this->getParser()->getRealCurrentLineNb() + 1);
            }

            return $prevErrorHandler ? $prevErrorHandler($level$message$file$line) : false;
        });

        try {
            $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
        } catch (ParseException $e) {
            return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
        } finally {
            restore_error_handler();
        }
break;
            case '{':
                $result = self::parseMapping($value$flags$i$references);
                ++$i;
                break;
            default:
                $result = self::parseScalar($value$flags, null, $i, true, $references);
        }

        // some comments are allowed at the end         if (preg_replace('/\s*#.*$/A', '', substr($value$i))) {
            throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value$i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
        }

        if (null !== $tag && '' !== $tag) {
            return new TaggedValue($tag$result);
        }

        return $result;
    }

    /** * Dumps a given PHP variable to a YAML string. * * @param mixed $value The PHP variable to convert * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string * * @throws DumpException When trying to dump PHP resource */
/** * Parses a YAML file into a PHP value. * * @param string $filename The path to the YAML file to be parsed * @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior * * @throws ParseException If the file could not be read or the YAML is not valid */
    public function parseFile(string $filename, int $flags = 0): mixed
    {
        if (!is_file($filename)) {
            throw new ParseException(sprintf('File "%s" does not exist.', $filename));
        }

        if (!is_readable($filename)) {
            throw new ParseException(sprintf('File "%s" cannot be read.', $filename));
        }

        $this->filename = $filename;

        try {
            return $this->parse(file_get_contents($filename)$flags);
        } finally {
            


            $event = new MailerDeliveryEvent($name$payload['id']$payload);
            // reason is only available on failed messages             $event->setReason($this->getReason($payload));
        } else {
            $name = match ($payload['event']) {
                'clicked' => MailerEngagementEvent::CLICK,
                'unsubscribed' => MailerEngagementEvent::UNSUBSCRIBE,
                'opened' => MailerEngagementEvent::OPEN,
                'complained' => MailerEngagementEvent::SPAM,
                default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['event'])),
            };
            $event = new MailerEngagementEvent($name$payload['id']$payload);
        }
        if (!$date = \DateTimeImmutable::createFromFormat('U.u', $payload['timestamp'])) {
            throw new ParseException(sprintf('Invalid date "%s".', $payload['timestamp']));
        }
        $event->setDate($date);
        $event->setRecipientEmail($payload['recipient']);
        $event->setMetadata($payload['user-variables']);
        $event->setTags($payload['tags']);

        
// U+0085 NEXT LINE             'N' => "\xC2\x85",
            // U+00A0 NO-BREAK SPACE             '_' => "\xC2\xA0",
            // U+2028 LINE SEPARATOR             'L' => "\xE2\x80\xA8",
            // U+2029 PARAGRAPH SEPARATOR             'P' => "\xE2\x80\xA9",
            'x' => self::utf8chr(hexdec(substr($value, 2, 2))),
            'u' => self::utf8chr(hexdec(substr($value, 2, 4))),
            'U' => self::utf8chr(hexdec(substr($value, 2, 8))),
            default => throw new ParseException(sprintf('Found unknown escape character "%s".', $value)),
        };
    }

    /** * Get the UTF-8 character for the given code point. */
    private static function utf8chr(int $c): string
    {
        if (0x80 > $c %= 0x200000) {
            return \chr($c);
        }
        
break;
            case '{':
                $result = self::parseMapping($value$flags$i$references);
                ++$i;
                break;
            default:
                $result = self::parseScalar($value$flags, null, $i, true, $references);
        }

        // some comments are allowed at the end         if (preg_replace('/\s*#.*$/A', '', substr($value$i))) {
            throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value$i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
        }

        if (null !== $tag && '' !== $tag) {
            return new TaggedValue($tag$result);
        }

        return $result;
    }

    /** * Dumps a given PHP variable to a YAML string. * * @param mixed $value The PHP variable to convert * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string * * @throws DumpException When trying to dump PHP resource */
'deferred' => MailerDeliveryEvent::DEFERRED,
                'bounce' => MailerDeliveryEvent::BOUNCE,
            };
            $event = new MailerDeliveryEvent($name$payload['sg_message_id']$payload);
            $event->setReason($payload['reason'] ?? '');
        } else {
            $name = match ($payload['event']) {
                'click' => MailerEngagementEvent::CLICK,
                'unsubscribe' => MailerEngagementEvent::UNSUBSCRIBE,
                'open' => MailerEngagementEvent::OPEN,
                'spamreport' => MailerEngagementEvent::SPAM,
                default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['unsubscribe'])),
            };
            $event = new MailerEngagementEvent($name$payload['sg_message_id']$payload);
        }

        if (!$date = \DateTimeImmutable::createFromFormat('U', $payload['timestamp'])) {
            throw new ParseException(sprintf('Invalid date "%s".', $payload['timestamp']));
        }

        $event->setDate($date);
        $event->setRecipientEmail($payload['email']);
        $event->setMetadata([]);
        
'blocked' => MailerDeliveryEvent::DROPPED,
            };

            $event = new MailerDeliveryEvent($name$payload['MessageID']$payload);
            $event->setReason($this->getReason($payload));
        } else {
            $name = match ($payload['event']) {
                'click' => MailerEngagementEvent::CLICK,
                'open' => MailerEngagementEvent::OPEN,
                'spam' => MailerEngagementEvent::SPAM,
                'unsub' => MailerEngagementEvent::UNSUBSCRIBE,
                default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['event'])),
            };
            $event = new MailerEngagementEvent($name$payload['MessageID']$payload);
        }

        if (!$date = \DateTimeImmutable::createFromFormat('U', $payload['time'])) {
            throw new ParseException(sprintf('Invalid date "%s".', $payload['time']));
        }

        $event->setDate($date);
        $event->setRecipientEmail($payload['email']);

        
'Delivery' => MailerDeliveryEvent::DELIVERED,
                'Bounce' => MailerDeliveryEvent::BOUNCE,
            };
            $event = new MailerDeliveryEvent($name$payload['MessageID']$payload);
            $event->setReason($payload['Description'] ?? '');
        } else {
            $name = match ($payload['RecordType']) {
                'Click' => MailerEngagementEvent::CLICK,
                'SubscriptionChange' => MailerEngagementEvent::UNSUBSCRIBE,
                'Open' => MailerEngagementEvent::OPEN,
                'SpamComplaint' => MailerEngagementEvent::SPAM,
                default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['RecordType'])),
            };
            $event = new MailerEngagementEvent($name$payload['MessageID']$payload);
        }
        $payloadDate = match ($payload['RecordType']) {
            'Delivery' => $payload['DeliveredAt'],
            'Bounce' => $payload['BouncedAt'],
            'Click' => $payload['ReceivedAt'],
            'SubscriptionChange' => $payload['ChangedAt'],
            'Open' => $payload['ReceivedAt'],
            'SpamComplaint' => $payload['BouncedAt'],
            default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['RecordType'])),
        };


namespace Symfony\Component\Yaml\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Yaml\Exception\ParseException;

class ParseExceptionTest extends TestCase
{
    public function testGetMessage()
    {
        $exception = new ParseException('Error message', 42, 'foo: bar', '/var/www/app/config.yml');
        $message = 'Error message in "/var/www/app/config.yml" at line 42 (near "foo: bar")';

        $this->assertEquals($message$exception->getMessage());
    }

    public function testGetMessageWithUnicodeInFilename()
    {
        $exception = new ParseException('Error message', 42, 'foo: bar', 'äöü.yml');
        $message = 'Error message in "äöü.yml" at line 42 (near "foo: bar")';

        $this->assertEquals($message$exception->getMessage());
    }


            $event = new MailerDeliveryEvent($name$payload['message-id']$payload);
        } else {
            $name = match ($payload['event']) {
                'click' => MailerEngagementEvent::CLICK,
                'unsubscribed' => MailerEngagementEvent::UNSUBSCRIBE,
                'unique_opened' => MailerEngagementEvent::OPEN,
                'opened' => MailerEngagementEvent::OPEN,
                'proxy_open' => MailerEngagementEvent::OPEN,
                'complaint' => MailerEngagementEvent::SPAM,
                default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['event'])),
            };
            $event = new MailerEngagementEvent($name$payload['message-id']$payload);
        }

        if (!$date = \DateTimeImmutable::createFromFormat('U', $payload['ts_event'])) {
            throw new ParseException(sprintf('Invalid date "%s".', $payload['ts_event']));
        }

        if (
            \in_array($payload['event']['deferred', 'soft_bounce', 'hard_bounce', 'invalid_email', 'blocked', 'error'], true)
            && isset($payload['reason'])
        )
Home | Imprint | This part of the site doesn't use cookies.