<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Hreflang
{
    public static function init(): void
    {
        add_filter('pll_rel_hreflang_attributes', array(__CLASS__, 'add_x_default'), 20);
    }

    public static function add_x_default($hreflangs)
    {
        if (! is_array($hreflangs) || isset($hreflangs['x-default'])) {
            return is_array($hreflangs) ? $hreflangs : array();
        }

if (! class_exists('PufferGo_Polylang')) {
            return $hreflangs;
        } $default = PufferGo_Polylang::default_language();

        if ('' === $default) {
            return $hreflangs;
        } $url = self::find_url($hreflangs, $default);

        if ('' !== $url) {
            $hreflangs['x-default'] = $url;
        }

return $hreflangs;
    }

    private static function find_url(array $hreflangs, string $default): string
    {
        $lookup = array();

        foreach ($hreflangs as $code => $url) {
            $lookup[ strtolower((string) $code) ] = (string) $url;
        } $locale = str_replace('_', '-', PufferGo_Polylang::locale_for($default));
        $candidates = array(strtolower($locale), strtolower($default), strtolower((string) strtok($locale, '-')), );

        foreach ($candidates as $candidate) {
            if ('' !== $candidate && isset($lookup[ $candidate ])) {
                return $lookup[ $candidate ];
            }
        }

return '';
    }
}
