Σ(゚Д゚;≡;゚д゚)Σ(゚Д゚;≡;゚д゚)Σ(゚Д゚;≡;゚д゚)始,故人唐宰相鲁公,🆚开府南服,余以布衣从戎。明年,别公漳水湄。后明年,公以事过张睢阳庙及颜杲卿所尝往来处,悲歌慷慨,卒不负其言而从之游。今其诗具在,可考也。😭
namespaced.php 0000644 00000002501 15233107570 0007356 0 ustar 00 <?php
require_once dirname(dirname(__FILE__)) . '/autoload.php';
if (PHP_VERSION_ID < 50300) {
return;
}
/*
* This file is just for convenience, to allow developers to reduce verbosity when
* they add this project to their libraries.
*
* Replace this:
*
* $x = ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_encrypt(...$args);
*
* with this:
*
* use ParagonIE\Sodium\Compat;
*
* $x = Compat::crypto_aead_xchacha20poly1305_encrypt(...$args);
*/
spl_autoload_register(function ($class) {
if ($class[0] === '\\') {
$class = substr($class, 1);
}
$namespace = 'ParagonIE\\Sodium';
// Does the class use the namespace prefix?
$len = strlen($namespace);
if (strncmp($namespace, $class, $len) !== 0) {
// no, move to the next registered autoloader
return false;
}
// Get the relative class name
$relative_class = substr($class, $len);
// Replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = dirname(dirname(__FILE__)) . '/namespaced/' . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require_once $file;
return true;
}
return false;
});
sodium_compat.php 0000644 00000057730 15233107570 0010137 0 ustar 00 <?php
namespace Sodium;
require_once dirname(dirname(__FILE__)) . '/autoload.php';
use ParagonIE_Sodium_Compat;
/**
* This file will monkey patch the pure-PHP implementation in place of the
* PECL functions, but only if they do not already exist.
*
* Thus, the functions just proxy to the appropriate ParagonIE_Sodium_Compat
* method.
*/
if (!is_callable('\\Sodium\\bin2hex')) {
/**
* @see ParagonIE_Sodium_Compat::bin2hex()
* @param string $string
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function bin2hex($string)
{
return ParagonIE_Sodium_Compat::bin2hex($string);
}
}
if (!is_callable('\\Sodium\\compare')) {
/**
* @see ParagonIE_Sodium_Compat::compare()
* @param string $a
* @param string $b
* @return int
* @throws \SodiumException
* @throws \TypeError
*/
function compare($a, $b)
{
return ParagonIE_Sodium_Compat::compare($a, $b);
}
}
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_decrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string|bool
*/
function crypto_aead_aes256gcm_decrypt($message, $assocData, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt($message, $assocData, $nonce, $key);
} catch (\TypeError $ex) {
return false;
} catch (\SodiumException $ex) {
return false;
}
}
}
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_encrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_aead_aes256gcm_encrypt($message, $assocData, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt($message, $assocData, $nonce, $key);
}
}
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_is_available')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available()
* @return bool
*/
function crypto_aead_aes256gcm_is_available()
{
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available();
}
}
if (!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_decrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string|bool
*/
function crypto_aead_chacha20poly1305_decrypt($message, $assocData, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt($message, $assocData, $nonce, $key);
} catch (\TypeError $ex) {
return false;
} catch (\SodiumException $ex) {
return false;
}
}
}
if (!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_encrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_aead_chacha20poly1305_encrypt($message, $assocData, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt($message, $assocData, $nonce, $key);
}
}
if (!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_ietf_decrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string|bool
*/
function crypto_aead_chacha20poly1305_ietf_decrypt($message, $assocData, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt($message, $assocData, $nonce, $key);
} catch (\TypeError $ex) {
return false;
} catch (\SodiumException $ex) {
return false;
}
}
}
if (!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_ietf_encrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_aead_chacha20poly1305_ietf_encrypt($message, $assocData, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt($message, $assocData, $nonce, $key);
}
}
if (!is_callable('\\Sodium\\crypto_auth')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_auth()
* @param string $message
* @param string $key
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_auth($message, $key)
{
return ParagonIE_Sodium_Compat::crypto_auth($message, $key);
}
}
if (!is_callable('\\Sodium\\crypto_auth_verify')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_auth_verify()
* @param string $mac
* @param string $message
* @param string $key
* @return bool
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_auth_verify($mac, $message, $key)
{
return ParagonIE_Sodium_Compat::crypto_auth_verify($mac, $message, $key);
}
}
if (!is_callable('\\Sodium\\crypto_box')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box()
* @param string $message
* @param string $nonce
* @param string $kp
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_box($message, $nonce, $kp)
{
return ParagonIE_Sodium_Compat::crypto_box($message, $nonce, $kp);
}
}
if (!is_callable('\\Sodium\\crypto_box_keypair')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_keypair()
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_box_keypair()
{
return ParagonIE_Sodium_Compat::crypto_box_keypair();
}
}
if (!is_callable('\\Sodium\\crypto_box_keypair_from_secretkey_and_publickey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey()
* @param string $sk
* @param string $pk
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_box_keypair_from_secretkey_and_publickey($sk, $pk)
{
return ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey($sk, $pk);
}
}
if (!is_callable('\\Sodium\\crypto_box_open')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_open()
* @param string $message
* @param string $nonce
* @param string $kp
* @return string|bool
*/
function crypto_box_open($message, $nonce, $kp)
{
try {
return ParagonIE_Sodium_Compat::crypto_box_open($message, $nonce, $kp);
} catch (\TypeError $ex) {
return false;
} catch (\SodiumException $ex) {
return false;
}
}
}
if (!is_callable('\\Sodium\\crypto_box_publickey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_publickey()
* @param string $keypair
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_box_publickey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_box_publickey($keypair);
}
}
if (!is_callable('\\Sodium\\crypto_box_publickey_from_secretkey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey()
* @param string $sk
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_box_publickey_from_secretkey($sk)
{
return ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey($sk);
}
}
if (!is_callable('\\Sodium\\crypto_box_seal')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_seal_open()
* @param string $message
* @param string $publicKey
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_box_seal($message, $publicKey)
{
return ParagonIE_Sodium_Compat::crypto_box_seal($message, $publicKey);
}
}
if (!is_callable('\\Sodium\\crypto_box_seal_open')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_seal_open()
* @param string $message
* @param string $kp
* @return string|bool
*/
function crypto_box_seal_open($message, $kp)
{
try {
return ParagonIE_Sodium_Compat::crypto_box_seal_open($message, $kp);
} catch (\TypeError $ex) {
return false;
} catch (\SodiumException $ex) {
return false;
}
}
}
if (!is_callable('\\Sodium\\crypto_box_secretkey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_secretkey()
* @param string $keypair
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_box_secretkey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_box_secretkey($keypair);
}
}
if (!is_callable('\\Sodium\\crypto_generichash')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash()
* @param string $message
* @param string|null $key
* @param int $outLen
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_generichash($message, $key = null, $outLen = 32)
{
return ParagonIE_Sodium_Compat::crypto_generichash($message, $key, $outLen);
}
}
if (!is_callable('\\Sodium\\crypto_generichash_final')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash_final()
* @param string|null $ctx
* @param int $outputLength
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_generichash_final(&$ctx, $outputLength = 32)
{
return ParagonIE_Sodium_Compat::crypto_generichash_final($ctx, $outputLength);
}
}
if (!is_callable('\\Sodium\\crypto_generichash_init')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash_init()
* @param string|null $key
* @param int $outLen
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_generichash_init($key = null, $outLen = 32)
{
return ParagonIE_Sodium_Compat::crypto_generichash_init($key, $outLen);
}
}
if (!is_callable('\\Sodium\\crypto_generichash_update')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash_update()
* @param string|null $ctx
* @param string $message
* @return void
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_generichash_update(&$ctx, $message = '')
{
ParagonIE_Sodium_Compat::crypto_generichash_update($ctx, $message);
}
}
if (!is_callable('\\Sodium\\crypto_kx')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_kx()
* @param string $my_secret
* @param string $their_public
* @param string $client_public
* @param string $server_public
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_kx($my_secret, $their_public, $client_public, $server_public)
{
return ParagonIE_Sodium_Compat::crypto_kx(
$my_secret,
$their_public,
$client_public,
$server_public,
true
);
}
}
if (!is_callable('\\Sodium\\crypto_pwhash')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash()
* @param int $outlen
* @param string $passwd
* @param string $salt
* @param int $opslimit
* @param int $memlimit
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_pwhash($outlen, $passwd, $salt, $opslimit, $memlimit)
{
return ParagonIE_Sodium_Compat::crypto_pwhash($outlen, $passwd, $salt, $opslimit, $memlimit);
}
}
if (!is_callable('\\Sodium\\crypto_pwhash_str')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_str()
* @param string $passwd
* @param int $opslimit
* @param int $memlimit
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_pwhash_str($passwd, $opslimit, $memlimit)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_str($passwd, $opslimit, $memlimit);
}
}
if (!is_callable('\\Sodium\\crypto_pwhash_str_verify')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_str_verify()
* @param string $passwd
* @param string $hash
* @return bool
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_pwhash_str_verify($passwd, $hash)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_str_verify($passwd, $hash);
}
}
if (!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256()
* @param int $outlen
* @param string $passwd
* @param string $salt
* @param int $opslimit
* @param int $memlimit
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_pwhash_scryptsalsa208sha256($outlen, $passwd, $salt, $opslimit, $memlimit)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256($outlen, $passwd, $salt, $opslimit, $memlimit);
}
}
if (!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str()
* @param string $passwd
* @param int $opslimit
* @param int $memlimit
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_pwhash_scryptsalsa208sha256_str($passwd, $opslimit, $memlimit)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str($passwd, $opslimit, $memlimit);
}
}
if (!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str_verify')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify()
* @param string $passwd
* @param string $hash
* @return bool
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_pwhash_scryptsalsa208sha256_str_verify($passwd, $hash)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify($passwd, $hash);
}
}
if (!is_callable('\\Sodium\\crypto_scalarmult')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_scalarmult()
* @param string $n
* @param string $p
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_scalarmult($n, $p)
{
return ParagonIE_Sodium_Compat::crypto_scalarmult($n, $p);
}
}
if (!is_callable('\\Sodium\\crypto_scalarmult_base')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_scalarmult_base()
* @param string $n
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_scalarmult_base($n)
{
return ParagonIE_Sodium_Compat::crypto_scalarmult_base($n);
}
}
if (!is_callable('\\Sodium\\crypto_secretbox')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_secretbox()
* @param string $message
* @param string $nonce
* @param string $key
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_secretbox($message, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_secretbox($message, $nonce, $key);
}
}
if (!is_callable('\\Sodium\\crypto_secretbox_open')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_secretbox_open()
* @param string $message
* @param string $nonce
* @param string $key
* @return string|bool
*/
function crypto_secretbox_open($message, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_secretbox_open($message, $nonce, $key);
} catch (\TypeError $ex) {
return false;
} catch (\SodiumException $ex) {
return false;
}
}
}
if (!is_callable('\\Sodium\\crypto_shorthash')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_shorthash()
* @param string $message
* @param string $key
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_shorthash($message, $key = '')
{
return ParagonIE_Sodium_Compat::crypto_shorthash($message, $key);
}
}
if (!is_callable('\\Sodium\\crypto_sign')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign()
* @param string $message
* @param string $sk
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign($message, $sk)
{
return ParagonIE_Sodium_Compat::crypto_sign($message, $sk);
}
}
if (!is_callable('\\Sodium\\crypto_sign_detached')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_detached()
* @param string $message
* @param string $sk
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_detached($message, $sk)
{
return ParagonIE_Sodium_Compat::crypto_sign_detached($message, $sk);
}
}
if (!is_callable('\\Sodium\\crypto_sign_keypair')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_keypair()
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_keypair()
{
return ParagonIE_Sodium_Compat::crypto_sign_keypair();
}
}
if (!is_callable('\\Sodium\\crypto_sign_open')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_open()
* @param string $signedMessage
* @param string $pk
* @return string|bool
*/
function crypto_sign_open($signedMessage, $pk)
{
try {
return ParagonIE_Sodium_Compat::crypto_sign_open($signedMessage, $pk);
} catch (\TypeError $ex) {
return false;
} catch (\SodiumException $ex) {
return false;
}
}
}
if (!is_callable('\\Sodium\\crypto_sign_publickey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_publickey()
* @param string $keypair
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_publickey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_sign_publickey($keypair);
}
}
if (!is_callable('\\Sodium\\crypto_sign_publickey_from_secretkey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey()
* @param string $sk
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_publickey_from_secretkey($sk)
{
return ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey($sk);
}
}
if (!is_callable('\\Sodium\\crypto_sign_secretkey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_secretkey()
* @param string $keypair
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_secretkey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_sign_secretkey($keypair);
}
}
if (!is_callable('\\Sodium\\crypto_sign_seed_keypair')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_seed_keypair()
* @param string $seed
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_seed_keypair($seed)
{
return ParagonIE_Sodium_Compat::crypto_sign_seed_keypair($seed);
}
}
if (!is_callable('\\Sodium\\crypto_sign_verify_detached')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_verify_detached()
* @param string $signature
* @param string $message
* @param string $pk
* @return bool
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_verify_detached($signature, $message, $pk)
{
return ParagonIE_Sodium_Compat::crypto_sign_verify_detached($signature, $message, $pk);
}
}
if (!is_callable('\\Sodium\\crypto_sign_ed25519_pk_to_curve25519')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519()
* @param string $pk
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_ed25519_pk_to_curve25519($pk)
{
return ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519($pk);
}
}
if (!is_callable('\\Sodium\\crypto_sign_ed25519_sk_to_curve25519')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519()
* @param string $sk
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_sign_ed25519_sk_to_curve25519($sk)
{
return ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519($sk);
}
}
if (!is_callable('\\Sodium\\crypto_stream')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_stream()
* @param int $len
* @param string $nonce
* @param string $key
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_stream($len, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_stream($len, $nonce, $key);
}
}
if (!is_callable('\\Sodium\\crypto_stream_xor')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_stream_xor()
* @param string $message
* @param string $nonce
* @param string $key
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function crypto_stream_xor($message, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_stream_xor($message, $nonce, $key);
}
}
if (!is_callable('\\Sodium\\hex2bin')) {
/**
* @see ParagonIE_Sodium_Compat::hex2bin()
* @param string $string
* @return string
* @throws \SodiumException
* @throws \TypeError
*/
function hex2bin($string)
{
return ParagonIE_Sodium_Compat::hex2bin($string);
}
}
if (!is_callable('\\Sodium\\memcmp')) {
/**
* @see ParagonIE_Sodium_Compat::memcmp()
* @param string $a
* @param string $b
* @return int
* @throws \SodiumException
* @throws \TypeError
*/
function memcmp($a, $b)
{
return ParagonIE_Sodium_Compat::memcmp($a, $b);
}
}
if (!is_callable('\\Sodium\\memzero')) {
/**
* @see ParagonIE_Sodium_Compat::memzero()
* @param string $str
* @return void
* @throws \SodiumException
* @throws \TypeError
*/
function memzero(&$str)
{
ParagonIE_Sodium_Compat::memzero($str);
}
}
if (!is_callable('\\Sodium\\randombytes_buf')) {
/**
* @see ParagonIE_Sodium_Compat::randombytes_buf()
* @param int $amount
* @return string
* @throws \TypeError
*/
function randombytes_buf($amount)
{
return ParagonIE_Sodium_Compat::randombytes_buf($amount);
}
}
if (!is_callable('\\Sodium\\randombytes_uniform')) {
/**
* @see ParagonIE_Sodium_Compat::randombytes_uniform()
* @param int $upperLimit
* @return int
* @throws \SodiumException
* @throws \Error
*/
function randombytes_uniform($upperLimit)
{
return ParagonIE_Sodium_Compat::randombytes_uniform($upperLimit);
}
}
if (!is_callable('\\Sodium\\randombytes_random16')) {
/**
* @see ParagonIE_Sodium_Compat::randombytes_random16()
* @return int
*/
function randombytes_random16()
{
return ParagonIE_Sodium_Compat::randombytes_random16();
}
}
if (!defined('\\Sodium\\CRYPTO_AUTH_BYTES')) {
require_once dirname(__FILE__) . '/constants.php';
}
php72compat.php 0000644 00000121355 15233107570 0007433 0 ustar 00 <?php
require_once dirname(dirname(__FILE__)) . '/autoload.php';
/**
* This file will monkey patch the pure-PHP implementation in place of the
* PECL functions and constants, but only if they do not already exist.
*
* Thus, the functions or constants just proxy to the appropriate
* ParagonIE_Sodium_Compat method or class constant, respectively.
*/
foreach (array(
'BASE64_VARIANT_ORIGINAL',
'BASE64_VARIANT_ORIGINAL_NO_PADDING',
'BASE64_VARIANT_URLSAFE',
'BASE64_VARIANT_URLSAFE_NO_PADDING',
'CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES',
'CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES',
'CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES',
'CRYPTO_AEAD_CHACHA20POLY1305_ABYTES',
'CRYPTO_AEAD_AES256GCM_KEYBYTES',
'CRYPTO_AEAD_AES256GCM_NSECBYTES',
'CRYPTO_AEAD_AES256GCM_NPUBBYTES',
'CRYPTO_AEAD_AES256GCM_ABYTES',
'CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES',
'CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES',
'CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES',
'CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES',
'CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES',
'CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NSECBYTES',
'CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES',
'CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES',
'CRYPTO_AUTH_BYTES',
'CRYPTO_AUTH_KEYBYTES',
'CRYPTO_BOX_SEALBYTES',
'CRYPTO_BOX_SECRETKEYBYTES',
'CRYPTO_BOX_PUBLICKEYBYTES',
'CRYPTO_BOX_KEYPAIRBYTES',
'CRYPTO_BOX_MACBYTES',
'CRYPTO_BOX_NONCEBYTES',
'CRYPTO_BOX_SEEDBYTES',
'CRYPTO_KDF_BYTES_MIN',
'CRYPTO_KDF_BYTES_MAX',
'CRYPTO_KDF_CONTEXTBYTES',
'CRYPTO_KDF_KEYBYTES',
'CRYPTO_KX_BYTES',
'CRYPTO_KX_KEYPAIRBYTES',
'CRYPTO_KX_PRIMITIVE',
'CRYPTO_KX_SEEDBYTES',
'CRYPTO_KX_PUBLICKEYBYTES',
'CRYPTO_KX_SECRETKEYBYTES',
'CRYPTO_KX_SESSIONKEYBYTES',
'CRYPTO_GENERICHASH_BYTES',
'CRYPTO_GENERICHASH_BYTES_MIN',
'CRYPTO_GENERICHASH_BYTES_MAX',
'CRYPTO_GENERICHASH_KEYBYTES',
'CRYPTO_GENERICHASH_KEYBYTES_MIN',
'CRYPTO_GENERICHASH_KEYBYTES_MAX',
'CRYPTO_PWHASH_SALTBYTES',
'CRYPTO_PWHASH_STRPREFIX',
'CRYPTO_PWHASH_ALG_ARGON2I13',
'CRYPTO_PWHASH_ALG_ARGON2ID13',
'CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE',
'CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE',
'CRYPTO_PWHASH_MEMLIMIT_MODERATE',
'CRYPTO_PWHASH_OPSLIMIT_MODERATE',
'CRYPTO_PWHASH_MEMLIMIT_SENSITIVE',
'CRYPTO_PWHASH_OPSLIMIT_SENSITIVE',
'CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES',
'CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX',
'CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE',
'CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE',
'CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE',
'CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE',
'CRYPTO_SCALARMULT_BYTES',
'CRYPTO_SCALARMULT_SCALARBYTES',
'CRYPTO_SHORTHASH_BYTES',
'CRYPTO_SHORTHASH_KEYBYTES',
'CRYPTO_SECRETBOX_KEYBYTES',
'CRYPTO_SECRETBOX_MACBYTES',
'CRYPTO_SECRETBOX_NONCEBYTES',
'CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES',
'CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES',
'CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES',
'CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH',
'CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PULL',
'CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY',
'CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL',
'CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX',
'CRYPTO_SIGN_BYTES',
'CRYPTO_SIGN_SEEDBYTES',
'CRYPTO_SIGN_PUBLICKEYBYTES',
'CRYPTO_SIGN_SECRETKEYBYTES',
'CRYPTO_SIGN_KEYPAIRBYTES',
'CRYPTO_STREAM_KEYBYTES',
'CRYPTO_STREAM_NONCEBYTES',
'CRYPTO_STREAM_XCHACHA20_KEYBYTES',
'CRYPTO_STREAM_XCHACHA20_NONCEBYTES',
'LIBRARY_MAJOR_VERSION',
'LIBRARY_MINOR_VERSION',
'LIBRARY_VERSION_MAJOR',
'LIBRARY_VERSION_MINOR',
'VERSION_STRING'
) as $constant
) {
if (!defined("SODIUM_$constant") && defined("ParagonIE_Sodium_Compat::$constant")) {
define("SODIUM_$constant", constant("ParagonIE_Sodium_Compat::$constant"));
}
}
if (!is_callable('sodium_add')) {
/**
* @see ParagonIE_Sodium_Compat::add()
* @param string $val
* @param string $addv
* @return void
* @throws SodiumException
*/
function sodium_add(&$val, $addv)
{
ParagonIE_Sodium_Compat::add($val, $addv);
}
}
if (!is_callable('sodium_base642bin')) {
/**
* @see ParagonIE_Sodium_Compat::bin2base64()
* @param string $string
* @param int $variant
* @param string $ignore
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_base642bin($string, $variant, $ignore ='')
{
return ParagonIE_Sodium_Compat::base642bin($string, $variant, $ignore);
}
}
if (!is_callable('sodium_bin2base64')) {
/**
* @see ParagonIE_Sodium_Compat::bin2base64()
* @param string $string
* @param int $variant
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_bin2base64($string, $variant)
{
return ParagonIE_Sodium_Compat::bin2base64($string, $variant);
}
}
if (!is_callable('sodium_bin2hex')) {
/**
* @see ParagonIE_Sodium_Compat::hex2bin()
* @param string $string
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_bin2hex($string)
{
return ParagonIE_Sodium_Compat::bin2hex($string);
}
}
if (!is_callable('sodium_compare')) {
/**
* @see ParagonIE_Sodium_Compat::compare()
* @param string $a
* @param string $b
* @return int
* @throws SodiumException
* @throws TypeError
*/
function sodium_compare($a, $b)
{
return ParagonIE_Sodium_Compat::compare($a, $b);
}
}
if (!is_callable('sodium_crypto_aead_aes256gcm_decrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string|bool
*/
function sodium_crypto_aead_aes256gcm_decrypt($message, $assocData, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt($message, $assocData, $nonce, $key);
} catch (Error $ex) {
return false;
} catch (Exception $ex) {
return false;
}
}
}
if (!is_callable('sodium_crypto_aead_aes256gcm_encrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_aead_aes256gcm_encrypt($message, $assocData, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt($message, $assocData, $nonce, $key);
}
}
if (!is_callable('sodium_crypto_aead_aes256gcm_is_available')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available()
* @return bool
*/
function sodium_crypto_aead_aes256gcm_is_available()
{
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available();
}
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_decrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string|bool
*/
function sodium_crypto_aead_chacha20poly1305_decrypt($message, $assocData, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt($message, $assocData, $nonce, $key);
} catch (Error $ex) {
return false;
} catch (Exception $ex) {
return false;
}
}
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_encrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_aead_chacha20poly1305_encrypt($message, $assocData, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt($message, $assocData, $nonce, $key);
}
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_aead_chacha20poly1305_keygen()
{
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_keygen();
}
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_ietf_decrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string|bool
*/
function sodium_crypto_aead_chacha20poly1305_ietf_decrypt($message, $assocData, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt($message, $assocData, $nonce, $key);
} catch (Error $ex) {
return false;
} catch (Exception $ex) {
return false;
}
}
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_ietf_encrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_aead_chacha20poly1305_ietf_encrypt($message, $assocData, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt($message, $assocData, $nonce, $key);
}
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_ietf_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_aead_chacha20poly1305_ietf_keygen()
{
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_keygen();
}
}
if (!is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_decrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_decrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string|bool
*/
function sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($message, $assocData, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_decrypt($message, $assocData, $nonce, $key, true);
} catch (Error $ex) {
return false;
} catch (Exception $ex) {
return false;
}
}
}
if (!is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_encrypt()
* @param string $message
* @param string $assocData
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_aead_xchacha20poly1305_ietf_encrypt($message, $assocData, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_encrypt($message, $assocData, $nonce, $key, true);
}
}
if (!is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_aead_xchacha20poly1305_ietf_keygen()
{
return ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_keygen();
}
}
if (!is_callable('sodium_crypto_auth')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_auth()
* @param string $message
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_auth($message, $key)
{
return ParagonIE_Sodium_Compat::crypto_auth($message, $key);
}
}
if (!is_callable('sodium_crypto_auth_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_auth_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_auth_keygen()
{
return ParagonIE_Sodium_Compat::crypto_auth_keygen();
}
}
if (!is_callable('sodium_crypto_auth_verify')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_auth_verify()
* @param string $mac
* @param string $message
* @param string $key
* @return bool
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_auth_verify($mac, $message, $key)
{
return ParagonIE_Sodium_Compat::crypto_auth_verify($mac, $message, $key);
}
}
if (!is_callable('sodium_crypto_box')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box()
* @param string $message
* @param string $nonce
* @param string $kp
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_box($message, $nonce, $kp)
{
return ParagonIE_Sodium_Compat::crypto_box($message, $nonce, $kp);
}
}
if (!is_callable('sodium_crypto_box_keypair')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_keypair()
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_box_keypair()
{
return ParagonIE_Sodium_Compat::crypto_box_keypair();
}
}
if (!is_callable('sodium_crypto_box_keypair_from_secretkey_and_publickey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey()
* @param string $sk
* @param string $pk
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_box_keypair_from_secretkey_and_publickey($sk, $pk)
{
return ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey($sk, $pk);
}
}
if (!is_callable('sodium_crypto_box_open')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_open()
* @param string $message
* @param string $nonce
* @param string $kp
* @return string|bool
*/
function sodium_crypto_box_open($message, $nonce, $kp)
{
try {
return ParagonIE_Sodium_Compat::crypto_box_open($message, $nonce, $kp);
} catch (Error $ex) {
return false;
} catch (Exception $ex) {
return false;
}
}
}
if (!is_callable('sodium_crypto_box_publickey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_publickey()
* @param string $keypair
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_box_publickey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_box_publickey($keypair);
}
}
if (!is_callable('sodium_crypto_box_publickey_from_secretkey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey()
* @param string $sk
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_box_publickey_from_secretkey($sk)
{
return ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey($sk);
}
}
if (!is_callable('sodium_crypto_box_seal')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_seal()
* @param string $message
* @param string $publicKey
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_box_seal($message, $publicKey)
{
return ParagonIE_Sodium_Compat::crypto_box_seal($message, $publicKey);
}
}
if (!is_callable('sodium_crypto_box_seal_open')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_seal_open()
* @param string $message
* @param string $kp
* @return string|bool
* @throws SodiumException
*/
function sodium_crypto_box_seal_open($message, $kp)
{
try {
return ParagonIE_Sodium_Compat::crypto_box_seal_open($message, $kp);
} catch (SodiumException $ex) {
if ($ex->getMessage() === 'Argument 2 must be CRYPTO_BOX_KEYPAIRBYTES long.') {
throw $ex;
}
return false;
}
}
}
if (!is_callable('sodium_crypto_box_secretkey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_secretkey()
* @param string $keypair
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_box_secretkey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_box_secretkey($keypair);
}
}
if (!is_callable('sodium_crypto_box_seed_keypair')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_box_seed_keypair()
* @param string $seed
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_box_seed_keypair($seed)
{
return ParagonIE_Sodium_Compat::crypto_box_seed_keypair($seed);
}
}
if (!is_callable('sodium_crypto_generichash')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash()
* @param string $message
* @param string|null $key
* @param int $outLen
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_generichash($message, $key = null, $outLen = 32)
{
return ParagonIE_Sodium_Compat::crypto_generichash($message, $key, $outLen);
}
}
if (!is_callable('sodium_crypto_generichash_final')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash_final()
* @param string|null $ctx
* @param int $outputLength
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_generichash_final(&$ctx, $outputLength = 32)
{
return ParagonIE_Sodium_Compat::crypto_generichash_final($ctx, $outputLength);
}
}
if (!is_callable('sodium_crypto_generichash_init')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash_init()
* @param string|null $key
* @param int $outLen
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_generichash_init($key = null, $outLen = 32)
{
return ParagonIE_Sodium_Compat::crypto_generichash_init($key, $outLen);
}
}
if (!is_callable('sodium_crypto_generichash_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_generichash_keygen()
{
return ParagonIE_Sodium_Compat::crypto_generichash_keygen();
}
}
if (!is_callable('sodium_crypto_generichash_update')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_generichash_update()
* @param string|null $ctx
* @param string $message
* @return void
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_generichash_update(&$ctx, $message = '')
{
ParagonIE_Sodium_Compat::crypto_generichash_update($ctx, $message);
}
}
if (!is_callable('sodium_crypto_kdf_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_kdf_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_kdf_keygen()
{
return ParagonIE_Sodium_Compat::crypto_kdf_keygen();
}
}
if (!is_callable('sodium_crypto_kdf_derive_from_key')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_kdf_derive_from_key()
* @param int $subkey_len
* @param int $subkey_id
* @param string $context
* @param string $key
* @return string
* @throws Exception
*/
function sodium_crypto_kdf_derive_from_key($subkey_len, $subkey_id, $context, $key)
{
return ParagonIE_Sodium_Compat::crypto_kdf_derive_from_key(
$subkey_len,
$subkey_id,
$context,
$key
);
}
}
if (!is_callable('sodium_crypto_kx')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_kx()
* @param string $my_secret
* @param string $their_public
* @param string $client_public
* @param string $server_public
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_kx($my_secret, $their_public, $client_public, $server_public)
{
return ParagonIE_Sodium_Compat::crypto_kx(
$my_secret,
$their_public,
$client_public,
$server_public
);
}
}
if (!is_callable('sodium_crypto_kx_seed_keypair')) {
/**
* @param string $seed
* @return string
* @throws Exception
*/
function sodium_crypto_kx_seed_keypair($seed)
{
return ParagonIE_Sodium_Compat::crypto_kx_seed_keypair($seed);
}
}
if (!is_callable('sodium_crypto_kx_keypair')) {
/**
* @return string
* @throws Exception
*/
function sodium_crypto_kx_keypair()
{
return ParagonIE_Sodium_Compat::crypto_kx_keypair();
}
}
if (!is_callable('sodium_crypto_kx_client_session_keys')) {
/**
* @param string $keypair
* @param string $serverPublicKey
* @return array{0: string, 1: string}
* @throws SodiumException
*/
function sodium_crypto_kx_client_session_keys($keypair, $serverPublicKey)
{
return ParagonIE_Sodium_Compat::crypto_kx_client_session_keys($keypair, $serverPublicKey);
}
}
if (!is_callable('sodium_crypto_kx_server_session_keys')) {
/**
* @param string $keypair
* @param string $clientPublicKey
* @return array{0: string, 1: string}
* @throws SodiumException
*/
function sodium_crypto_kx_server_session_keys($keypair, $clientPublicKey)
{
return ParagonIE_Sodium_Compat::crypto_kx_server_session_keys($keypair, $clientPublicKey);
}
}
if (!is_callable('sodium_crypto_kx_secretkey')) {
/**
* @param string $keypair
* @return string
* @throws Exception
*/
function sodium_crypto_kx_secretkey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_kx_secretkey($keypair);
}
}
if (!is_callable('sodium_crypto_kx_publickey')) {
/**
* @param string $keypair
* @return string
* @throws Exception
*/
function sodium_crypto_kx_publickey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_kx_publickey($keypair);
}
}
if (!is_callable('sodium_crypto_pwhash')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash()
* @param int $outlen
* @param string $passwd
* @param string $salt
* @param int $opslimit
* @param int $memlimit
* @param int|null $algo
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_pwhash($outlen, $passwd, $salt, $opslimit, $memlimit, $algo = null)
{
return ParagonIE_Sodium_Compat::crypto_pwhash($outlen, $passwd, $salt, $opslimit, $memlimit, $algo);
}
}
if (!is_callable('sodium_crypto_pwhash_str')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_str()
* @param string $passwd
* @param int $opslimit
* @param int $memlimit
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_pwhash_str($passwd, $opslimit, $memlimit)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_str($passwd, $opslimit, $memlimit);
}
}
if (!is_callable('sodium_crypto_pwhash_str_needs_rehash')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_str_needs_rehash()
* @param string $hash
* @param int $opslimit
* @param int $memlimit
* @return bool
*
* @throws SodiumException
*/
function sodium_crypto_pwhash_str_needs_rehash($hash, $opslimit, $memlimit)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_str_needs_rehash($hash, $opslimit, $memlimit);
}
}
if (!is_callable('sodium_crypto_pwhash_str_verify')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_str_verify()
* @param string $passwd
* @param string $hash
* @return bool
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_pwhash_str_verify($passwd, $hash)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_str_verify($passwd, $hash);
}
}
if (!is_callable('sodium_crypto_pwhash_scryptsalsa208sha256')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256()
* @param int $outlen
* @param string $passwd
* @param string $salt
* @param int $opslimit
* @param int $memlimit
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_pwhash_scryptsalsa208sha256($outlen, $passwd, $salt, $opslimit, $memlimit)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256($outlen, $passwd, $salt, $opslimit, $memlimit);
}
}
if (!is_callable('sodium_crypto_pwhash_scryptsalsa208sha256_str')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str()
* @param string $passwd
* @param int $opslimit
* @param int $memlimit
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_pwhash_scryptsalsa208sha256_str($passwd, $opslimit, $memlimit)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str($passwd, $opslimit, $memlimit);
}
}
if (!is_callable('sodium_crypto_pwhash_scryptsalsa208sha256_str_verify')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify()
* @param string $passwd
* @param string $hash
* @return bool
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_pwhash_scryptsalsa208sha256_str_verify($passwd, $hash)
{
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify($passwd, $hash);
}
}
if (!is_callable('sodium_crypto_scalarmult')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_scalarmult()
* @param string $n
* @param string $p
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_scalarmult($n, $p)
{
return ParagonIE_Sodium_Compat::crypto_scalarmult($n, $p);
}
}
if (!is_callable('sodium_crypto_scalarmult_base')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_scalarmult_base()
* @param string $n
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_scalarmult_base($n)
{
return ParagonIE_Sodium_Compat::crypto_scalarmult_base($n);
}
}
if (!is_callable('sodium_crypto_secretbox')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_secretbox()
* @param string $message
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_secretbox($message, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_secretbox($message, $nonce, $key);
}
}
if (!is_callable('sodium_crypto_secretbox_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_secretbox_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_secretbox_keygen()
{
return ParagonIE_Sodium_Compat::crypto_secretbox_keygen();
}
}
if (!is_callable('sodium_crypto_secretbox_open')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_secretbox_open()
* @param string $message
* @param string $nonce
* @param string $key
* @return string|bool
*/
function sodium_crypto_secretbox_open($message, $nonce, $key)
{
try {
return ParagonIE_Sodium_Compat::crypto_secretbox_open($message, $nonce, $key);
} catch (Error $ex) {
return false;
} catch (Exception $ex) {
return false;
}
}
}
if (!is_callable('sodium_crypto_secretstream_xchacha20poly1305_init_push')) {
/**
* @param string $key
* @return array<int, string>
* @throws SodiumException
*/
function sodium_crypto_secretstream_xchacha20poly1305_init_push($key)
{
return ParagonIE_Sodium_Compat::crypto_secretstream_xchacha20poly1305_init_push($key);
}
}
if (!is_callable('sodium_crypto_secretstream_xchacha20poly1305_push')) {
/**
* @param string $state
* @param string $msg
* @param string $aad
* @param int $tag
* @return string
* @throws SodiumException
*/
function sodium_crypto_secretstream_xchacha20poly1305_push(&$state, $msg, $aad = '', $tag = 0)
{
return ParagonIE_Sodium_Compat::crypto_secretstream_xchacha20poly1305_push($state, $msg, $aad, $tag);
}
}
if (!is_callable('sodium_crypto_secretstream_xchacha20poly1305_init_pull')) {
/**
* @param string $header
* @param string $key
* @return string
* @throws Exception
*/
function sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $key)
{
return ParagonIE_Sodium_Compat::crypto_secretstream_xchacha20poly1305_init_pull($header, $key);
}
}
if (!is_callable('sodium_crypto_secretstream_xchacha20poly1305_pull')) {
/**
* @param string $state
* @param string $cipher
* @param string $aad
* @return bool|array{0: string, 1: int}
* @throws SodiumException
*/
function sodium_crypto_secretstream_xchacha20poly1305_pull(&$state, $cipher, $aad = '')
{
return ParagonIE_Sodium_Compat::crypto_secretstream_xchacha20poly1305_pull($state, $cipher, $aad);
}
}
if (!is_callable('sodium_crypto_secretstream_xchacha20poly1305_rekey')) {
/**
* @param string $state
* @return void
* @throws SodiumException
*/
function sodium_crypto_secretstream_xchacha20poly1305_rekey(&$state)
{
ParagonIE_Sodium_Compat::crypto_secretstream_xchacha20poly1305_rekey($state);
}
}
if (!is_callable('sodium_crypto_secretstream_xchacha20poly1305_keygen')) {
/**
* @return string
* @throws Exception
*/
function sodium_crypto_secretstream_xchacha20poly1305_keygen()
{
return ParagonIE_Sodium_Compat::crypto_secretstream_xchacha20poly1305_keygen();
}
}
if (!is_callable('sodium_crypto_shorthash')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_shorthash()
* @param string $message
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_shorthash($message, $key = '')
{
return ParagonIE_Sodium_Compat::crypto_shorthash($message, $key);
}
}
if (!is_callable('sodium_crypto_shorthash_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_shorthash_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_shorthash_keygen()
{
return ParagonIE_Sodium_Compat::crypto_shorthash_keygen();
}
}
if (!is_callable('sodium_crypto_sign')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign()
* @param string $message
* @param string $sk
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign($message, $sk)
{
return ParagonIE_Sodium_Compat::crypto_sign($message, $sk);
}
}
if (!is_callable('sodium_crypto_sign_detached')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_detached()
* @param string $message
* @param string $sk
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_detached($message, $sk)
{
return ParagonIE_Sodium_Compat::crypto_sign_detached($message, $sk);
}
}
if (!is_callable('sodium_crypto_sign_keypair_from_secretkey_and_publickey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_keypair_from_secretkey_and_publickey()
* @param string $sk
* @param string $pk
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_keypair_from_secretkey_and_publickey($sk, $pk)
{
return ParagonIE_Sodium_Compat::crypto_sign_keypair_from_secretkey_and_publickey($sk, $pk);
}
}
if (!is_callable('sodium_crypto_sign_keypair')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_keypair()
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_keypair()
{
return ParagonIE_Sodium_Compat::crypto_sign_keypair();
}
}
if (!is_callable('sodium_crypto_sign_open')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_open()
* @param string $signedMessage
* @param string $pk
* @return string|bool
*/
function sodium_crypto_sign_open($signedMessage, $pk)
{
try {
return ParagonIE_Sodium_Compat::crypto_sign_open($signedMessage, $pk);
} catch (Error $ex) {
return false;
} catch (Exception $ex) {
return false;
}
}
}
if (!is_callable('sodium_crypto_sign_publickey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_publickey()
* @param string $keypair
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_publickey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_sign_publickey($keypair);
}
}
if (!is_callable('sodium_crypto_sign_publickey_from_secretkey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey()
* @param string $sk
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_publickey_from_secretkey($sk)
{
return ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey($sk);
}
}
if (!is_callable('sodium_crypto_sign_secretkey')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_secretkey()
* @param string $keypair
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_secretkey($keypair)
{
return ParagonIE_Sodium_Compat::crypto_sign_secretkey($keypair);
}
}
if (!is_callable('sodium_crypto_sign_seed_keypair')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_seed_keypair()
* @param string $seed
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_seed_keypair($seed)
{
return ParagonIE_Sodium_Compat::crypto_sign_seed_keypair($seed);
}
}
if (!is_callable('sodium_crypto_sign_verify_detached')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_verify_detached()
* @param string $signature
* @param string $message
* @param string $pk
* @return bool
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_verify_detached($signature, $message, $pk)
{
return ParagonIE_Sodium_Compat::crypto_sign_verify_detached($signature, $message, $pk);
}
}
if (!is_callable('sodium_crypto_sign_ed25519_pk_to_curve25519')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519()
* @param string $pk
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_ed25519_pk_to_curve25519($pk)
{
return ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519($pk);
}
}
if (!is_callable('sodium_crypto_sign_ed25519_sk_to_curve25519')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519()
* @param string $sk
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_sign_ed25519_sk_to_curve25519($sk)
{
return ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519($sk);
}
}
if (!is_callable('sodium_crypto_stream')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_stream()
* @param int $len
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_stream($len, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_stream($len, $nonce, $key);
}
}
if (!is_callable('sodium_crypto_stream_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_stream_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_stream_keygen()
{
return ParagonIE_Sodium_Compat::crypto_stream_keygen();
}
}
if (!is_callable('sodium_crypto_stream_xor')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_stream_xor()
* @param string $message
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_stream_xor($message, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_stream_xor($message, $nonce, $key);
}
}
require_once dirname(__FILE__) . '/stream-xchacha20.php';
if (!is_callable('sodium_hex2bin')) {
/**
* @see ParagonIE_Sodium_Compat::hex2bin()
* @param string $string
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_hex2bin($string)
{
return ParagonIE_Sodium_Compat::hex2bin($string);
}
}
if (!is_callable('sodium_increment')) {
/**
* @see ParagonIE_Sodium_Compat::increment()
* @param string $string
* @return void
* @throws SodiumException
* @throws TypeError
*/
function sodium_increment(&$string)
{
ParagonIE_Sodium_Compat::increment($string);
}
}
if (!is_callable('sodium_library_version_major')) {
/**
* @see ParagonIE_Sodium_Compat::library_version_major()
* @return int
*/
function sodium_library_version_major()
{
return ParagonIE_Sodium_Compat::library_version_major();
}
}
if (!is_callable('sodium_library_version_minor')) {
/**
* @see ParagonIE_Sodium_Compat::library_version_minor()
* @return int
*/
function sodium_library_version_minor()
{
return ParagonIE_Sodium_Compat::library_version_minor();
}
}
if (!is_callable('sodium_version_string')) {
/**
* @see ParagonIE_Sodium_Compat::version_string()
* @return string
*/
function sodium_version_string()
{
return ParagonIE_Sodium_Compat::version_string();
}
}
if (!is_callable('sodium_memcmp')) {
/**
* @see ParagonIE_Sodium_Compat::memcmp()
* @param string $a
* @param string $b
* @return int
* @throws SodiumException
* @throws TypeError
*/
function sodium_memcmp($a, $b)
{
return ParagonIE_Sodium_Compat::memcmp($a, $b);
}
}
if (!is_callable('sodium_memzero')) {
/**
* @see ParagonIE_Sodium_Compat::memzero()
* @param string $str
* @return void
* @throws SodiumException
* @throws TypeError
*/
function sodium_memzero(&$str)
{
ParagonIE_Sodium_Compat::memzero($str);
}
}
if (!is_callable('sodium_pad')) {
/**
* @see ParagonIE_Sodium_Compat::pad()
* @param string $unpadded
* @param int $blockSize
* @return int
* @throws SodiumException
* @throws TypeError
*/
function sodium_pad($unpadded, $blockSize)
{
return ParagonIE_Sodium_Compat::pad($unpadded, $blockSize, true);
}
}
if (!is_callable('sodium_unpad')) {
/**
* @see ParagonIE_Sodium_Compat::pad()
* @param string $padded
* @param int $blockSize
* @return int
* @throws SodiumException
* @throws TypeError
*/
function sodium_unpad($padded, $blockSize)
{
return ParagonIE_Sodium_Compat::unpad($padded, $blockSize, true);
}
}
if (!is_callable('sodium_randombytes_buf')) {
/**
* @see ParagonIE_Sodium_Compat::randombytes_buf()
* @param int $amount
* @return string
* @throws Exception
*/
function sodium_randombytes_buf($amount)
{
return ParagonIE_Sodium_Compat::randombytes_buf($amount);
}
}
if (!is_callable('sodium_randombytes_uniform')) {
/**
* @see ParagonIE_Sodium_Compat::randombytes_uniform()
* @param int $upperLimit
* @return int
* @throws Exception
*/
function sodium_randombytes_uniform($upperLimit)
{
return ParagonIE_Sodium_Compat::randombytes_uniform($upperLimit);
}
}
if (!is_callable('sodium_randombytes_random16')) {
/**
* @see ParagonIE_Sodium_Compat::randombytes_random16()
* @return int
* @throws Exception
*/
function sodium_randombytes_random16()
{
return ParagonIE_Sodium_Compat::randombytes_random16();
}
}
php72compat_const.php 0000644 00000010765 15233107570 0010643 0 ustar 00 <?php
const SODIUM_LIBRARY_MAJOR_VERSION = 9;
const SODIUM_LIBRARY_MINOR_VERSION = 1;
const SODIUM_LIBRARY_VERSION = '1.0.8';
const SODIUM_BASE64_VARIANT_ORIGINAL = 1;
const SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING = 3;
const SODIUM_BASE64_VARIANT_URLSAFE = 5;
const SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING = 7;
const SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES = 32;
const SODIUM_CRYPTO_AEAD_AES256GCM_NSECBYTES = 0;
const SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES = 12;
const SODIUM_CRYPTO_AEAD_AES256GCM_ABYTES = 16;
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES = 32;
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES = 0;
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES = 8;
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES = 16;
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES = 32;
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES = 0;
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES = 12;
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES = 16;
const SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES = 32;
const SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NSECBYTES = 0;
const SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES = 24;
const SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES = 16;
const SODIUM_CRYPTO_AUTH_BYTES = 32;
const SODIUM_CRYPTO_AUTH_KEYBYTES = 32;
const SODIUM_CRYPTO_BOX_SEALBYTES = 16;
const SODIUM_CRYPTO_BOX_SECRETKEYBYTES = 32;
const SODIUM_CRYPTO_BOX_PUBLICKEYBYTES = 32;
const SODIUM_CRYPTO_BOX_KEYPAIRBYTES = 64;
const SODIUM_CRYPTO_BOX_MACBYTES = 16;
const SODIUM_CRYPTO_BOX_NONCEBYTES = 24;
const SODIUM_CRYPTO_BOX_SEEDBYTES = 32;
const SODIUM_CRYPTO_KDF_BYTES_MIN = 16;
const SODIUM_CRYPTO_KDF_BYTES_MAX = 64;
const SODIUM_CRYPTO_KDF_CONTEXTBYTES = 8;
const SODIUM_CRYPTO_KDF_KEYBYTES = 32;
const SODIUM_CRYPTO_KX_BYTES = 32;
const SODIUM_CRYPTO_KX_PRIMITIVE = 'x25519blake2b';
const SODIUM_CRYPTO_KX_SEEDBYTES = 32;
const SODIUM_CRYPTO_KX_KEYPAIRBYTES = 64;
const SODIUM_CRYPTO_KX_PUBLICKEYBYTES = 32;
const SODIUM_CRYPTO_KX_SECRETKEYBYTES = 32;
const SODIUM_CRYPTO_KX_SESSIONKEYBYTES = 32;
const SODIUM_CRYPTO_GENERICHASH_BYTES = 32;
const SODIUM_CRYPTO_GENERICHASH_BYTES_MIN = 16;
const SODIUM_CRYPTO_GENERICHASH_BYTES_MAX = 64;
const SODIUM_CRYPTO_GENERICHASH_KEYBYTES = 32;
const SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN = 16;
const SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX = 64;
const SODIUM_CRYPTO_PWHASH_SALTBYTES = 16;
const SODIUM_CRYPTO_PWHASH_STRPREFIX = '$argon2id$';
const SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13 = 1;
const SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13 = 2;
const SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE = 33554432;
const SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE = 4;
const SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE = 134217728;
const SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE = 6;
const SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE = 536870912;
const SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE = 8;
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES = 32;
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX = '$7$';
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE = 534288;
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE = 16777216;
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE = 33554432;
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE = 1073741824;
const SODIUM_CRYPTO_SCALARMULT_BYTES = 32;
const SODIUM_CRYPTO_SCALARMULT_SCALARBYTES = 32;
const SODIUM_CRYPTO_SHORTHASH_BYTES = 8;
const SODIUM_CRYPTO_SHORTHASH_KEYBYTES = 16;
const SODIUM_CRYPTO_SECRETBOX_KEYBYTES = 32;
const SODIUM_CRYPTO_SECRETBOX_MACBYTES = 16;
const SODIUM_CRYPTO_SECRETBOX_NONCEBYTES = 24;
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES = 17;
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES = 24;
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES = 32;
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH = 0;
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PULL = 1;
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY = 2;
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL = 3;
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX = 0x3fffffff80;
const SODIUM_CRYPTO_SIGN_BYTES = 64;
const SODIUM_CRYPTO_SIGN_SEEDBYTES = 32;
const SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES = 32;
const SODIUM_CRYPTO_SIGN_SECRETKEYBYTES = 64;
const SODIUM_CRYPTO_SIGN_KEYPAIRBYTES = 96;
const SODIUM_CRYPTO_STREAM_KEYBYTES = 32;
const SODIUM_CRYPTO_STREAM_NONCEBYTES = 24;
const SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES = 32;
const SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES = 24;
ristretto255.php 0000644 00000016052 15233107570 0007557 0 ustar 00 <?php
if (!defined('SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES')) {
define(
'SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES',
ParagonIE_Sodium_Compat::CRYPTO_CORE_RISTRETTO255_BYTES
);
define('SODIUM_COMPAT_POLYFILLED_RISTRETTO255', true);
}
if (!defined('SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES')) {
define(
'SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES',
ParagonIE_Sodium_Compat::CRYPTO_CORE_RISTRETTO255_HASHBYTES
);
}
if (!defined('SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES')) {
define(
'SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES',
ParagonIE_Sodium_Compat::CRYPTO_CORE_RISTRETTO255_SCALARBYTES
);
}
if (!defined('SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES')) {
define(
'SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES',
ParagonIE_Sodium_Compat::CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES
);
}
if (!defined('SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES')) {
define(
'SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES',
ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES
);
}
if (!defined('SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES')) {
define(
'SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES',
ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_RISTRETTO255_BYTES
);
}
if (!is_callable('sodium_crypto_core_ristretto255_add')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_add()
*
* @param string $p
* @param string $q
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_add($p, $q)
{
return ParagonIE_Sodium_Compat::ristretto255_add($p, $q, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_from_hash')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_from_hash()
*
* @param string $r
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_from_hash($r)
{
return ParagonIE_Sodium_Compat::ristretto255_from_hash($r, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_is_valid_point')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_is_valid_point()
*
* @param string $p
* @return bool
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_is_valid_point($p)
{
return ParagonIE_Sodium_Compat::ristretto255_is_valid_point($p, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_random')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_random()
*
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_random()
{
return ParagonIE_Sodium_Compat::ristretto255_random(true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_scalar_add')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_add()
*
* @param string $p
* @param string $q
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_scalar_add($p, $q)
{
return ParagonIE_Sodium_Compat::ristretto255_scalar_add($p, $q, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_scalar_complement')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_complement()
*
* @param string $p
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_scalar_complement($p)
{
return ParagonIE_Sodium_Compat::ristretto255_scalar_complement($p, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_scalar_invert')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_invert()
*
* @param string $p
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_scalar_invert($p)
{
return ParagonIE_Sodium_Compat::ristretto255_scalar_invert($p, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_scalar_mul')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_mul()
*
* @param string $p
* @param string $q
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_scalar_mul($p, $q)
{
return ParagonIE_Sodium_Compat::ristretto255_scalar_mul($p, $q, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_scalar_negate')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_negate()
*
* @param string $p
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_scalar_negate($p)
{
return ParagonIE_Sodium_Compat::ristretto255_scalar_negate($p, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_scalar_random')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_random()
*
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_scalar_random()
{
return ParagonIE_Sodium_Compat::ristretto255_scalar_random(true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_scalar_reduce')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_reduce()
*
* @param string $p
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_scalar_reduce($p)
{
return ParagonIE_Sodium_Compat::ristretto255_scalar_reduce($p, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_scalar_sub')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_sub()
*
* @param string $p
* @param string $q
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_scalar_sub($p, $q)
{
return ParagonIE_Sodium_Compat::ristretto255_scalar_sub($p, $q, true);
}
}
if (!is_callable('sodium_crypto_core_ristretto255_sub')) {
/**
* @see ParagonIE_Sodium_Compat::ristretto255_sub()
*
* @param string $p
* @param string $q
* @return string
* @throws SodiumException
*/
function sodium_crypto_core_ristretto255_sub($p, $q)
{
return ParagonIE_Sodium_Compat::ristretto255_sub($p, $q, true);
}
}
if (!is_callable('sodium_crypto_scalarmult_ristretto255')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_scalarmult_ristretto255()
* @param string $n
* @param string $p
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_scalarmult_ristretto255($n, $p)
{
return ParagonIE_Sodium_Compat::scalarmult_ristretto255($n, $p, true);
}
}
if (!is_callable('sodium_crypto_scalarmult_ristretto255_base')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_scalarmult_ristretto255_base()
* @param string $n
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_scalarmult_ristretto255_base($n)
{
return ParagonIE_Sodium_Compat::scalarmult_ristretto255_base($n, true);
}
} constants.php 0000644 00000010101 15233107570 0007265 0 ustar 00 <?php
namespace Sodium;
require_once dirname(dirname(__FILE__)) . '/autoload.php';
use ParagonIE_Sodium_Compat;
const CRYPTO_AEAD_AES256GCM_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_KEYBYTES;
const CRYPTO_AEAD_AES256GCM_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_NSECBYTES;
const CRYPTO_AEAD_AES256GCM_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_NPUBBYTES;
const CRYPTO_AEAD_AES256GCM_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_ABYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_ABYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES;
const CRYPTO_AUTH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_AUTH_BYTES;
const CRYPTO_AUTH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AUTH_KEYBYTES;
const CRYPTO_BOX_SEALBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SEALBYTES;
const CRYPTO_BOX_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SECRETKEYBYTES;
const CRYPTO_BOX_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES;
const CRYPTO_BOX_KEYPAIRBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES;
const CRYPTO_BOX_MACBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_MACBYTES;
const CRYPTO_BOX_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_NONCEBYTES;
const CRYPTO_BOX_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SEEDBYTES;
const CRYPTO_KX_BYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_BYTES;
const CRYPTO_KX_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_SEEDBYTES;
const CRYPTO_KX_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_PUBLICKEYBYTES;
const CRYPTO_KX_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_SECRETKEYBYTES;
const CRYPTO_GENERICHASH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES;
const CRYPTO_GENERICHASH_BYTES_MIN = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MIN;
const CRYPTO_GENERICHASH_BYTES_MAX = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MAX;
const CRYPTO_GENERICHASH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES;
const CRYPTO_GENERICHASH_KEYBYTES_MIN = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MIN;
const CRYPTO_GENERICHASH_KEYBYTES_MAX = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MAX;
const CRYPTO_SCALARMULT_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_BYTES;
const CRYPTO_SCALARMULT_SCALARBYTES = ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_SCALARBYTES;
const CRYPTO_SHORTHASH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SHORTHASH_BYTES;
const CRYPTO_SHORTHASH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SHORTHASH_KEYBYTES;
const CRYPTO_SECRETBOX_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES;
const CRYPTO_SECRETBOX_MACBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_MACBYTES;
const CRYPTO_SECRETBOX_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES;
const CRYPTO_SIGN_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_BYTES;
const CRYPTO_SIGN_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_SEEDBYTES;
const CRYPTO_SIGN_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_PUBLICKEYBYTES;
const CRYPTO_SIGN_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_SECRETKEYBYTES;
const CRYPTO_SIGN_KEYPAIRBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_KEYPAIRBYTES;
const CRYPTO_STREAM_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_STREAM_KEYBYTES;
const CRYPTO_STREAM_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_STREAM_NONCEBYTES;
stream-xchacha20.php 0000644 00000002407 15233107570 0010315 0 ustar 00 <?php
if (!is_callable('sodium_crypto_stream_xchacha20')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_stream_xchacha20()
* @param int $len
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_stream_xchacha20($len, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_stream_xchacha20($len, $nonce, $key, true);
}
}
if (!is_callable('sodium_crypto_stream_xchacha20_keygen')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_stream_xchacha20_keygen()
* @return string
* @throws Exception
*/
function sodium_crypto_stream_xchacha20_keygen()
{
return ParagonIE_Sodium_Compat::crypto_stream_xchacha20_keygen();
}
}
if (!is_callable('sodium_crypto_stream_xchacha20_xor')) {
/**
* @see ParagonIE_Sodium_Compat::crypto_stream_xchacha20_xor()
* @param string $message
* @param string $nonce
* @param string $key
* @return string
* @throws SodiumException
* @throws TypeError
*/
function sodium_crypto_stream_xchacha20_xor($message, $nonce, $key)
{
return ParagonIE_Sodium_Compat::crypto_stream_xchacha20_xor($message, $nonce, $key, true);
}
}
abstract-main.php 0000644 00000005277 15233603101 0010007 0 ustar 00 <?php
namespace Yoast\WP\Lib;
use Exception;
use Yoast\WP\Lib\Dependency_Injection\Container_Registry;
use Yoast\WP\SEO\Loader;
use YoastSEO_Vendor\Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Abstract class to extend for the main class in a plugin.
*/
abstract class Abstract_Main {
/**
* The DI container.
*
* @var ContainerInterface|null
*/
protected $container;
/**
* Loads the plugin.
*
* @throws Exception If loading fails and YOAST_ENVIRONMENT is development.
*/
public function load() {
if ( $this->container ) {
return;
}
try {
$this->container = $this->get_container();
Container_Registry::register( $this->get_name(), $this->container );
if ( ! $this->container ) {
return;
}
if ( ! $this->container->has( Loader::class ) ) {
return;
}
$this->container->get( Loader::class )->load();
} catch ( Exception $e ) {
if ( $this->is_development() ) {
throw $e;
}
// Don't crash the entire site, simply don't load.
}
}
/**
* Magic getter for retrieving a property.
*
* @param string $property The property to retrieve.
*
* @return string The value of the property.
*
* @throws Exception When the property doesn't exist.
*/
public function __get( $property ) {
$surfaces = $this->get_surfaces();
if ( isset( $surfaces[ $property ] ) ) {
$this->{$property} = $this->container->get( $surfaces[ $property ] );
return $this->{$property};
}
throw new Exception( "Property $property does not exist." );
}
/**
* Checks if the given property exists as a surface.
*
* @param string $property The property to retrieve.
*
* @return bool True when property is set.
*/
public function __isset( $property ) {
return isset( $this->surfaces[ $property ] );
}
/**
* Loads the DI container.
*
* @return ContainerInterface|null The DI container.
*
* @throws Exception If something goes wrong generating the DI container.
*/
abstract protected function get_container();
/**
* Gets the name of the plugin.
*
* @return string The name.
*/
abstract protected function get_name();
/**
* Gets the surfaces of this plugin.
*
* @return array A mapping of surface name to the responsible class.
*/
abstract protected function get_surfaces();
/**
* Returns whether or not we're in an environment for Yoast development.
*
* @return bool Whether or not to load in development mode.
*/
protected function is_development() {
try {
return \WPSEO_Utils::is_development_mode();
}
catch ( \Exception $exception ) {
// E.g. when WordPress and/or WordPress SEO are not loaded.
return \defined( 'YOAST_ENVIRONMENT' ) && \YOAST_ENVIRONMENT === 'development';
}
}
}
migrations/constants.php 0000644 00000001132 15233603101 0011434 0 ustar 00 <?php
namespace Yoast\WP\Lib\Migrations;
/**
* Yoast migrations constants class.
*/
class Constants {
const MYSQL_MAX_IDENTIFIER_LENGTH = 64;
const SQL_UNKNOWN_QUERY_TYPE = 1;
const SQL_SELECT = 2;
const SQL_INSERT = 4;
const SQL_UPDATE = 8;
const SQL_DELETE = 16;
const SQL_ALTER = 32;
const SQL_DROP = 64;
const SQL_CREATE = 128;
const SQL_SHOW = 256;
const SQL_RENAME = 512;
const SQL_SET = 1024;
}
migrations/migration.php 0000644 00000014354 15233603101 0011423 0 ustar 00 <?php
namespace Yoast\WP\Lib\Migrations;
/**
* Base migration class.
*/
abstract class Migration {
/**
* The plugin this migration belongs to.
*
* @var string
*/
public static $plugin = 'unknown';
/**
* The adapter.
*
* @var Adapter
*/
private $adapter;
/**
* Performs the migration.
*
* @return void
*/
abstract public function up();
/**
* Reverts the migration.
*
* @return void
*/
abstract public function down();
/**
* Creates a new migration.
*
* @param Adapter $adapter The current adapter.
*/
public function __construct( Adapter $adapter ) {
$this->set_adapter( $adapter );
}
/**
* Sets an adapter.
*
* @param Adapter $adapter The adapter to set.
*
* @return $this|null
*/
public function set_adapter( $adapter ) {
if ( ! $adapter instanceof Adapter ) {
return;
}
$this->adapter = $adapter;
return $this;
}
/**
* Returns the current adapter.
*
* @return object
*/
public function get_adapter() {
return $this->adapter;
}
/**
* Creates a database.
*
* @param string $name The name of the database.
* @param array|null $options The options.
*
* @return bool
*/
public function create_database( $name, $options = null ) {
return $this->adapter->create_database( $name, $options );
}
/**
* Drops a database.
*
* @param string $name The name of the database.
*
* @return bool
*/
public function drop_database( $name ) {
return $this->adapter->drop_database( $name );
}
/**
* Drops a table.
*
* @param string $table_name The name of the table.
*
* @return bool
*/
public function drop_table( $table_name ) {
return $this->adapter->drop_table( $table_name );
}
/**
* Renames a table.
*
* @param string $name The name of the table.
* @param string $new_name The new name of the table.
*
* @return bool
*/
public function rename_table( $name, $new_name ) {
return $this->adapter->rename_table( $name, $new_name );
}
/**
* Renames a column.
*
* @param string $table_name The name of the table.
* @param string $column_name The column name.
* @param string $new_column_name The new column name.
*
* @return bool
*/
public function rename_column( $table_name, $column_name, $new_column_name ) {
return $this->adapter->rename_column( $table_name, $column_name, $new_column_name );
}
/**
* Adds a column.
*
* @param string $table_name The name of the table.
* @param string $column_name The column name.
* @param string $type The column type.
* @param array|string $options The options.
*
* @return bool
*/
public function add_column( $table_name, $column_name, $type, $options = [] ) {
return $this->adapter->add_column( $table_name, $column_name, $type, $options );
}
/**
* Removes a column.
*
* @param string $table_name The name of the table.
* @param string $column_name The column name.
*
* @return bool
*/
public function remove_column( $table_name, $column_name ) {
return $this->adapter->remove_column( $table_name, $column_name );
}
/**
* Changes a column.
*
* @param string $table_name The name of the table.
* @param string $column_name The column name.
* @param string $type The column type.
* @param array|string $options The options.
*
* @return bool
*/
public function change_column( $table_name, $column_name, $type, $options = [] ) {
return $this->adapter->change_column( $table_name, $column_name, $type, $options );
}
/**
* Adds an index.
*
* @param string $table_name The name of the table.
* @param array|string $column_name The column name.
* @param array|string $options The options.
*
* @return bool
*/
public function add_index( $table_name, $column_name, $options = [] ) {
return $this->adapter->add_index( $table_name, $column_name, $options );
}
/**
* Removes an index.
*
* @param string $table_name The name of the table.
* @param array|string $column_name The column name.
* @param array|string $options The options.
*
* @return bool
*/
public function remove_index( $table_name, $column_name, $options = [] ) {
return $this->adapter->remove_index( $table_name, $column_name, $options );
}
/**
* Adds timestamps.
*
* @param string $table_name The name of the table.
* @param string $created_column_name Created at column name.
* @param string $updated_column_name Updated at column name.
*
* @return bool
*/
public function add_timestamps( $table_name, $created_column_name = 'created_at', $updated_column_name = 'updated_at' ) {
return $this->adapter->add_timestamps( $table_name, $created_column_name, $updated_column_name );
}
/**
* Removes timestamps.
*
* @param string $table_name The name of the table.
* @param string $created_column_name Created at column name.
* @param string $updated_column_name Updated at column name.
*
* @return bool
*/
public function remove_timestamps( $table_name, $created_column_name = 'created_at', $updated_column_name = 'updated_at' ) {
return $this->adapter->remove_timestamps( $table_name, $created_column_name, $updated_column_name );
}
/**
* Creates a table.
*
* @param string $table_name The name of the table.
* @param array|string $options The options.
*
* @return bool|Table
*/
public function create_table( $table_name, $options = [] ) {
return $this->adapter->create_table( $table_name, $options );
}
/**
* Execute a query and return the first result.
*
* @param string $sql The query to run.
*
* @return array
*/
public function select_one( $sql ) {
return $this->adapter->select_one( $sql );
}
/**
* Execute a query and return all results.
*
* @param string $sql The query to run.
*
* @return array
*/
public function select_all( $sql ) {
return $this->adapter->select_all( $sql );
}
/**
* Execute a query.
*
* @param string $sql The query to run.
*
* @return bool
*/
public function query( $sql ) {
return $this->adapter->query( $sql );
}
/**
* Returns a quoted string.
*
* @param string $str The string to quote.
*
* @return string
*/
public function quote_string( $str ) {
return $this->adapter->quote_string( $str );
}
}
migrations/adapter.php 0000644 00000064653 15233603101 0011061 0 ustar 00 <?php
namespace Yoast\WP\Lib\Migrations;
use Exception;
use Yoast\WP\Lib\Model;
/**
* Yoast migrations adapter class.
*/
class Adapter {
/**
* The version of this adapter.
*
* @var string
*/
private $version = '1.0';
/**
* Whether or not a transaction has been started.
*
* @var bool
*/
private $in_transaction = false;
/**
* Returns the current database name.
*
* @return string
*/
public function get_database_name() {
global $wpdb;
return $wpdb->dbname;
}
/**
* Checks support for migrations.
*
* @return bool
*/
public function supports_migrations() {
return true;
}
/**
* Returns all column native types.
*
* @return array
*/
public function native_database_types() {
$types = [
'primary_key' => [
'name' => 'integer',
'limit' => 11,
'null' => false,
],
'string' => [
'name' => 'varchar',
'limit' => 255,
],
'text' => [ 'name' => 'text' ],
'tinytext' => [ 'name' => 'tinytext' ],
'mediumtext' => [ 'name' => 'mediumtext' ],
'integer' => [
'name' => 'int',
'limit' => 11,
],
'tinyinteger' => [ 'name' => 'tinyint' ],
'smallinteger' => [ 'name' => 'smallint' ],
'mediuminteger' => [ 'name' => 'mediumint' ],
'biginteger' => [ 'name' => 'bigint' ],
'float' => [ 'name' => 'float' ],
'decimal' => [
'name' => 'decimal',
'scale' => 0,
'precision' => 10,
],
'datetime' => [ 'name' => 'datetime' ],
'timestamp' => [ 'name' => 'timestamp' ],
'time' => [ 'name' => 'time' ],
'date' => [ 'name' => 'date' ],
'binary' => [ 'name' => 'blob' ],
'tinybinary' => [ 'name' => 'tinyblob' ],
'mediumbinary' => [ 'name' => 'mediumblob' ],
'longbinary' => [ 'name' => 'longblob' ],
'boolean' => [
'name' => 'tinyint',
'limit' => 1,
],
'enum' => [
'name' => 'enum',
'values' => [],
],
'uuid' => [
'name' => 'char',
'limit' => 36,
],
'char' => [ 'name' => 'char' ],
];
return $types;
}
/**
* Checks if a table exists.
*
* @param string $table The table name.
*
* @return bool
*/
public function has_table( $table ) {
return $this->table_exists( $table );
}
/**
* Allows overriding the hardcoded schema table name constant in case of parallel migrations.
*
* @return string
*/
public function get_schema_version_table_name() {
return Model::get_table_name( 'migrations' );
}
/**
* Create the schema table, if necessary.
*/
public function create_schema_version_table() {
if ( ! $this->has_table( $this->get_schema_version_table_name() ) ) {
$t = $this->create_table( $this->get_schema_version_table_name() );
$t->column( 'version', 'string', [ 'limit' => 191 ] );
$t->finish();
$this->add_index( $this->get_schema_version_table_name(), 'version', [ 'unique' => true ] );
}
}
/**
* Starts a transaction.
*/
public function start_transaction() {
if ( $this->in_transaction() === false ) {
$this->begin_transaction();
}
}
/**
* Commits a transaction.
*/
public function commit_transaction() {
if ( $this->in_transaction() ) {
$this->commit();
}
}
/**
* Rollbacks a transaction.
*/
public function rollback_transaction() {
if ( $this->in_transaction() ) {
$this->rollback();
}
}
/**
* Quotes a table name string.
*
* @param string $text Table name.
*
* @return string
*/
public function quote_table( $text ) {
return '`' . $text . '`';
}
/**
* Return the SQL definition of a column.
*
* @param string $column_name The column name.
* @param string $type The type of the column.
* @param array|null $options Column options.
*
* @return string
*/
public function column_definition( $column_name, $type, $options = null ) {
$col = new Column( $this, $column_name, $type, $options );
return $col->__toString();
}
/**
* Checks if a database exists.
*
* @param string $database The database name.
*
* @return bool
*/
public function database_exists( $database ) {
$ddl = 'SHOW DATABASES';
$result = $this->select_all( $ddl );
if ( \count( $result ) === 0 ) {
return false;
}
foreach ( $result as $dbrow ) {
if ( $dbrow['Database'] === $database ) {
return true;
}
}
return false;
}
/**
* Creates a database.
*
* @param string $db The database name.
*
* @return bool
*/
public function create_database( $db ) {
if ( $this->database_exists( $db ) ) {
return false;
}
$ddl = \sprintf( 'CREATE DATABASE %s', $this->identifier( $db ) );
$result = $this->query( $ddl );
return $result === true;
}
/**
* Drops a database.
*
* @param string $db The database name.
*
* @return bool
*/
public function drop_database( $db ) {
if ( ! $this->database_exists( $db ) ) {
return false;
}
$ddl = \sprintf( 'DROP DATABASE IF EXISTS %s', $this->identifier( $db ) );
$result = $this->query( $ddl );
return $result === true;
}
/**
* Checks if a table exists.
*
* @param string $table The table name.
*
* @return bool
*/
public function table_exists( $table ) {
global $wpdb;
// We need last error to be clear so we can check against it easily.
$previous_last_error = $wpdb->last_error;
$previous_suppress_errors = $wpdb->suppress_errors;
$wpdb->last_error = '';
$wpdb->suppress_errors = true;
$result = $wpdb->query( "SELECT * FROM $table LIMIT 1" );
// Restore the last error, as this is not truly an error and we don't want to alarm people.
$wpdb->last_error = $previous_last_error;
$wpdb->suppress_errors = $previous_suppress_errors;
return $result !== false;
}
/**
* Wrapper to execute a query.
*
* @param string $query The query to run.
*
* @return bool
*/
public function execute( $query ) {
return $this->query( $query );
}
/**
* Executes a query.
*
* @param string $query The query to run.
*
* @return bool Whether or not the query was performed succesfully.
*/
public function query( $query ) {
global $wpdb;
$query_type = $this->determine_query_type( $query );
$data = [];
if ( $query_type === Constants::SQL_SELECT || $query_type === Constants::SQL_SHOW ) {
$data = $wpdb->get_results( $query, ARRAY_A );
if ( $data === false ) {
return false;
}
return $data;
}
else {
// INSERT, DELETE, etc...
$result = $wpdb->query( $query );
if ( $result === false ) {
return false;
}
if ( $query_type === Constants::SQL_INSERT ) {
return $wpdb->insert_id;
}
return true;
}
}
/**
* Returns a single result for a query.
*
* @param string $query The query to run.
*
* @return array|false An associative array of the result.
*/
public function select_one( $query ) {
global $wpdb;
$query_type = $this->determine_query_type( $query );
if ( $query_type === Constants::SQL_SELECT || $query_type === Constants::SQL_SHOW ) {
$result = $wpdb->query( $query );
if ( $result === false ) {
return false;
}
return $wpdb->last_result[0];
}
return false;
}
/**
* Returns all results for a query.
*
* @param string $query The query to run.
*
* @return array An array of associative arrays.
*/
public function select_all( $query ) {
return $this->query( $query );
}
/**
* Use this method for non-SELECT queries.
* Or anything where you dont necessarily expect a result string, e.g. DROPs, CREATEs, etc.
*
* @param string $ddl The query to run.
*
* @return bool
*/
public function execute_ddl( $ddl ) {
return $this->query( $ddl );
}
/**
* Drops a table
*
* @param string $table The table name.
*
* @return bool Whether or not the table was succesfully dropped.
*/
public function drop_table( $table ) {
$ddl = \sprintf( 'DROP TABLE IF EXISTS %s', $this->identifier( $table ) );
return $this->query( $ddl );
}
/**
* Creates a table.
*
* @param string $table_name The table name.
* @param array $options The options.
*
* @return Table
*/
public function create_table( $table_name, $options = [] ) {
return new Table( $this, $table_name, $options );
}
/**
* Escapes a string for usage in queries.
*
* @param string $text The string.
*
* @return string
*/
public function quote_string( $text ) {
global $wpdb;
return $wpdb->_escape( $text );
}
/**
* Returns a quoted string.
*
* @param string $text The string.
*
* @return string
*/
public function identifier( $text ) {
return '`' . $text . '`';
}
/**
* Renames a table.
*
* @param string $name The current table name.
* @param string $new_name The new table name.
*
* @return bool
*/
public function rename_table( $name, $new_name ) {
if ( empty( $name ) || empty( $new_name ) ) {
return false;
}
$sql = \sprintf( 'RENAME TABLE %s TO %s', $this->identifier( $name ), $this->identifier( $new_name ) );
return $this->execute_ddl( $sql );
}
/**
* Adds a column.
*
* @param string $table_name The table name.
* @param string $column_name The column name.
* @param string $type The column type.
* @param array $options Column options.
*
* @return bool
*/
public function add_column( $table_name, $column_name, $type, $options = [] ) {
if ( empty( $table_name ) || empty( $column_name ) || empty( $type ) ) {
return false;
}
// Default types.
if ( ! \array_key_exists( 'limit', $options ) ) {
$options['limit'] = null;
}
if ( ! \array_key_exists( 'precision', $options ) ) {
$options['precision'] = null;
}
if ( ! \array_key_exists( 'scale', $options ) ) {
$options['scale'] = null;
}
$sql = \sprintf( 'ALTER TABLE %s ADD `%s` %s', $this->identifier( $table_name ), $column_name, $this->type_to_sql( $type, $options ) );
$sql .= $this->add_column_options( $type, $options );
return $this->execute_ddl( $sql );
}
/**
* Drops a column.
*
* @param string $table_name The table name.
* @param string $column_name The column name.
*
* @return bool
*/
public function remove_column( $table_name, $column_name ) {
$sql = \sprintf( 'ALTER TABLE %s DROP COLUMN %s', $this->identifier( $table_name ), $this->identifier( $column_name ) );
return $this->execute_ddl( $sql );
}
/**
* Renames a column.
*
* @param string $table_name The table name.
* @param string $column_name The column name.
* @param string $new_column_name The new column name.
*
* @return bool
*/
public function rename_column( $table_name, $column_name, $new_column_name ) {
if ( empty( $table_name ) || empty( $column_name ) || empty( $new_column_name ) ) {
return false;
}
$column_info = $this->column_info( $table_name, $column_name );
$current_type = $column_info['type'];
$sql = \sprintf( 'ALTER TABLE %s CHANGE %s %s %s', $this->identifier( $table_name ), $this->identifier( $column_name ), $this->identifier( $new_column_name ), $current_type );
$sql .= $this->add_column_options( $current_type, $column_info );
return $this->execute_ddl( $sql );
}
/**
* Changes a column.
*
* @param string $table_name The table name.
* @param string $column_name The column name.
* @param string $type The column type.
* @param array $options Column options.
*
* @return bool
*/
public function change_column( $table_name, $column_name, $type, $options = [] ) {
if ( empty( $table_name ) || empty( $column_name ) || empty( $type ) ) {
return false;
}
$column_info = $this->column_info( $table_name, $column_name );
// Default types.
if ( ! \array_key_exists( 'limit', $options ) ) {
$options['limit'] = null;
}
if ( ! \array_key_exists( 'precision', $options ) ) {
$options['precision'] = null;
}
if ( ! \array_key_exists( 'scale', $options ) ) {
$options['scale'] = null;
}
$sql = \sprintf( 'ALTER TABLE `%s` CHANGE `%s` `%s` %s', $table_name, $column_name, $column_name, $this->type_to_sql( $type, $options ) );
$sql .= $this->add_column_options( $type, $options );
return $this->execute_ddl( $sql );
}
/**
* Returns the database information for a column.
*
* @param string $table The table name.
* @param string $column The column name.
*
* @return array|null
*/
public function column_info( $table, $column ) {
if ( empty( $table ) || empty( $column ) ) {
return null;
}
try {
$sql = \sprintf( "SHOW FULL COLUMNS FROM %s LIKE '%s'", $this->identifier( $table ), $column );
$result = $this->select_one( $sql );
if ( \is_array( $result ) ) {
$result = \array_change_key_case( $result, \CASE_LOWER );
}
return $result;
} catch ( \Exception $e ) {
return null;
}
}
/**
* Adds an index.
*
* @param string $table_name The table name.
* @param array|string $column_name The column name(s).
* @param array $options Index options.
*
* @return bool
*/
public function add_index( $table_name, $column_name, $options = [] ) {
if ( empty( $table_name ) || empty( $column_name ) ) {
return false;
}
// Unique index?
if ( \is_array( $options ) && \array_key_exists( 'unique', $options ) && $options['unique'] === true ) {
$unique = true;
}
else {
$unique = false;
}
// Did the user specify an index name?
if ( \is_array( $options ) && \array_key_exists( 'name', $options ) ) {
$index_name = $options['name'];
}
else {
$index_name = $this->get_index_name( $table_name, $column_name );
}
if ( \strlen( $index_name ) > Constants::MYSQL_MAX_IDENTIFIER_LENGTH ) {
return false;
}
if ( ! \is_array( $column_name ) ) {
$column_names = [ $column_name ];
}
else {
$column_names = $column_name;
}
$cols = [];
foreach ( $column_names as $name ) {
$cols[] = $this->identifier( $name );
}
$sql = \sprintf(
'CREATE %sINDEX %s ON %s(%s)',
( $unique === true ) ? 'UNIQUE ' : '',
$this->identifier( $index_name ),
$this->identifier( $table_name ),
\implode( ', ', $cols )
);
return $this->execute_ddl( $sql );
}
/**
* Drops an index.
*
* @param string $table_name The table name.
* @param array|string $column_name The column name(s).
* @param array $options Index options.
*
* @return bool
*/
public function remove_index( $table_name, $column_name, $options = [] ) {
if ( empty( $table_name ) || empty( $column_name ) ) {
return false;
}
// Did the user specify an index name?
if ( \is_array( $options ) && \array_key_exists( 'name', $options ) ) {
$index_name = $options['name'];
}
else {
$index_name = $this->get_index_name( $table_name, $column_name );
}
$sql = \sprintf( 'DROP INDEX %s ON %s', $this->identifier( $index_name ), $this->identifier( $table_name ) );
return $this->execute_ddl( $sql );
}
/**
* Adds timestamps.
*
* @param string $table_name The table name.
* @param string $created_column_name Created at column name.
* @param string $updated_column_name Updated at column name.
*
* @return bool
*/
public function add_timestamps( $table_name, $created_column_name, $updated_column_name ) {
if ( empty( $table_name ) || empty( $created_column_name ) || empty( $updated_column_name ) ) {
return false;
}
$created_at = $this->add_column( $table_name, $created_column_name, 'datetime' );
$updated_at = $this->add_column(
$table_name,
$updated_column_name,
'timestamp',
[
'null' => false,
'default' => 'CURRENT_TIMESTAMP',
'extra' => 'ON UPDATE CURRENT_TIMESTAMP',
]
);
return $created_at && $updated_at;
}
/**
* Removes timestamps.
*
* @param string $table_name The table name.
* @param string $created_column_name Created at column name.
* @param string $updated_column_name Updated at column name.
*
* @return bool Whether or not the timestamps were removed.
*/
public function remove_timestamps( $table_name, $created_column_name, $updated_column_name ) {
if ( empty( $table_name ) || empty( $created_column_name ) || empty( $updated_column_name ) ) {
return false;
}
$updated_at = $this->remove_column( $table_name, $created_column_name );
$created_at = $this->remove_column( $table_name, $updated_column_name );
return $created_at && $updated_at;
}
/**
* Checks an index.
*
* @param string $table_name The table name.
* @param array|string $column_name The column name(s).
* @param array $options Index options.
*
* @return bool Whether or not the index exists.
*/
public function has_index( $table_name, $column_name, $options = [] ) {
if ( empty( $table_name ) || empty( $column_name ) ) {
return false;
}
// Did the user specify an index name?
if ( \is_array( $options ) && \array_key_exists( 'name', $options ) ) {
$index_name = $options['name'];
}
else {
$index_name = $this->get_index_name( $table_name, $column_name );
}
$indexes = $this->indexes( $table_name );
foreach ( $indexes as $idx ) {
if ( $idx['name'] === $index_name ) {
return true;
}
}
return false;
}
/**
* Returns all indexes of a table.
*
* @param string $table_name The table name.
*
* @return array
*/
public function indexes( $table_name ) {
$sql = \sprintf( 'SHOW KEYS FROM %s', $this->identifier( $table_name ) );
$result = $this->select_all( $sql );
$indexes = [];
foreach ( $result as $row ) {
// Skip primary.
if ( $row['Key_name'] === 'PRIMARY' ) {
continue;
}
$indexes[] = [
'name' => $row['Key_name'],
'unique' => (int) $row['Non_unique'] === 0,
];
}
return $indexes;
}
/**
* Converts a type to sql. Default options:
* $limit = null, $precision = null, $scale = null
*
* @param string $type The native type.
* @param array $options The options.
*
* @return string The SQL type.
*
* @throws Exception If invalid arguments are supplied.
*/
public function type_to_sql( $type, $options = [] ) {
$natives = $this->native_database_types();
if ( ! \array_key_exists( $type, $natives ) ) {
$error = \sprintf( "Error:I dont know what column type of '%s' maps to for MySQL.", $type );
$error .= "\nYou provided: {$type}\n";
$error .= "Valid types are: \n";
$types = \array_keys( $natives );
foreach ( $types as $t ) {
if ( $t === 'primary_key' ) {
continue;
}
$error .= "\t{$t}\n";
}
throw new Exception( $error );
}
$scale = null;
$precision = null;
$limit = null;
if ( isset( $options['precision'] ) ) {
$precision = $options['precision'];
}
if ( isset( $options['scale'] ) ) {
$scale = $options['scale'];
}
if ( isset( $options['limit'] ) ) {
$limit = $options['limit'];
}
if ( isset( $options['values'] ) ) {
$values = $options['values'];
}
$native_type = $natives[ $type ];
if ( \is_array( $native_type ) && \array_key_exists( 'name', $native_type ) ) {
$column_type_sql = $native_type['name'];
}
else {
return $native_type;
}
if ( $type === 'decimal' || $type === 'float' ) {
// Ignore limit, use precison and scale.
if ( $precision === null && \array_key_exists( 'precision', $native_type ) ) {
$precision = $native_type['precision'];
}
if ( $scale === null && \array_key_exists( 'scale', $native_type ) ) {
$scale = $native_type['scale'];
}
if ( $precision !== null ) {
if ( \is_int( $scale ) ) {
$column_type_sql .= \sprintf( '(%d, %d)', $precision, $scale );
}
else {
$column_type_sql .= \sprintf( '(%d)', $precision );
}
}
else {
if ( $scale ) {
throw new Exception( "Error adding $type column: precision cannot be empty if scale is specified" );
}
}
}
elseif ( $type === 'enum' ) {
if ( empty( $values ) ) {
throw new Exception( 'Error adding enum column: there must be at least one value defined' );
}
else {
$column_type_sql .= \sprintf(
"('%s')",
\implode( "','", \array_map( [ $this, 'quote_string' ], $values ) )
);
}
}
// Not a decimal column.
if ( $limit === null && \array_key_exists( 'limit', $native_type ) ) {
$limit = $native_type['limit'];
}
if ( $limit ) {
$column_type_sql .= \sprintf( '(%d)', $limit );
}
return $column_type_sql;
}
/**
* Adds column options.
*
* @param string $type The native type.
* @param array $options The options.
*
* @return string The SQL statement for the column options.
*
* @throws Exception If invalid arguments are supplied.
*/
public function add_column_options( $type, $options ) {
$sql = '';
if ( ! \is_array( $options ) ) {
return $sql;
}
if ( \array_key_exists( 'unsigned', $options ) && $options['unsigned'] === true ) {
$sql .= ' UNSIGNED';
}
if ( \array_key_exists( 'character', $options ) ) {
$sql .= \sprintf( ' CHARACTER SET %s', $this->identifier( $options['character'] ) );
}
if ( \array_key_exists( 'collate', $options ) ) {
$sql .= \sprintf( ' COLLATE %s', $this->identifier( $options['collate'] ) );
}
if ( \array_key_exists( 'auto_increment', $options ) && $options['auto_increment'] === true ) {
$sql .= ' auto_increment';
}
if ( \array_key_exists( 'default', $options ) && $options['default'] !== null ) {
if ( $this->is_sql_method_call( $options['default'] ) ) {
throw new Exception( 'MySQL does not support function calls as default values, constants only.' );
}
if ( \is_int( $options['default'] ) ) {
$default_format = '%d';
}
elseif ( \is_bool( $options['default'] ) ) {
$default_format = "'%d'";
}
elseif ( $options['default'] === 'CURRENT_TIMESTAMP' ) {
$default_format = '%s';
}
else {
$default_format = "'%s'";
}
$default_value = \sprintf( $default_format, $options['default'] );
$sql .= \sprintf( ' DEFAULT %s', $default_value );
}
if ( \array_key_exists( 'null', $options ) ) {
if ( $options['null'] === false || $options['null'] === 'NO' ) {
$sql .= ' NOT NULL';
}
elseif ( $type === 'timestamp' ) {
$sql .= ' NULL';
}
}
if ( \array_key_exists( 'comment', $options ) ) {
$sql .= \sprintf( " COMMENT '%s'", $this->quote_string( $options['comment'] ) );
}
if ( \array_key_exists( 'extra', $options ) ) {
$sql .= \sprintf( ' %s', $this->quote_string( $options['extra'] ) );
}
if ( \array_key_exists( 'after', $options ) ) {
$sql .= \sprintf( ' AFTER %s', $this->identifier( $options['after'] ) );
}
return $sql;
}
/**
* Returns a list of all versions that have been migrated.
*
* @return string[] The version numbers that have been migrated.
*/
public function get_migrated_versions() {
$result = $this->select_all( \sprintf( 'SELECT version FROM %s', $this->get_schema_version_table_name() ) );
return \array_column( $result, 'version' );
}
/**
* Adds a migrated version.
*
* @param string $version The version.
*
* @return bool Whether or not the version was succesfully set.
*/
public function add_version( $version ) {
$sql = \sprintf( "INSERT INTO %s (version) VALUES ('%s')", $this->get_schema_version_table_name(), $version );
return $this->execute_ddl( $sql );
}
/**
* Removes a migrated version.
*
* @param string $version The version.
*
* @return bool Whether or not the version was succesfully removed.
*/
public function remove_version( $version ) {
$sql = \sprintf( "DELETE FROM %s WHERE version = '%s'", $this->get_schema_version_table_name(), $version );
return $this->execute_ddl( $sql );
}
/**
* Returns a message displaying the current version
*
* @return string
*/
public function __toString() {
return self::class . ', version ' . $this->version;
}
/**
* Returns an index name.
*
* @param string $table_name The table name.
* @param string $column_name The column name.
*
* @return string The index name.
*/
private function get_index_name( $table_name, $column_name ) {
$name = \preg_replace( '/\\W/', '_', $table_name );
$name = \preg_replace( '/\\_{2,}/', '_', $name );
// If the column parameter is an array then the user wants to create a multi-column index.
if ( \is_array( $column_name ) ) {
$column_str = \implode( '_and_', $column_name );
}
else {
$column_str = $column_name;
}
$name .= \sprintf( '_%s', $column_str );
return $name;
}
/**
* Returns the type of a query.
*
* @param string $query The query to run.
*
* @return int The query type.
*/
private function determine_query_type( $query ) {
$query = \strtolower( \trim( $query ) );
$match = [];
\preg_match( '/^(\\w)*/i', $query, $match );
$type = $match[0];
switch ( $type ) {
case 'select':
return Constants::SQL_SELECT;
case 'update':
return Constants::SQL_UPDATE;
case 'delete':
return Constants::SQL_DELETE;
case 'insert':
return Constants::SQL_INSERT;
case 'alter':
return Constants::SQL_ALTER;
case 'drop':
return Constants::SQL_DROP;
case 'create':
return Constants::SQL_CREATE;
case 'show':
return Constants::SQL_SHOW;
case 'rename':
return Constants::SQL_RENAME;
case 'set':
return Constants::SQL_SET;
default:
return Constants::SQL_UNKNOWN_QUERY_TYPE;
}
}
/**
* Detect whether or not the string represents a function call and if so
* do not wrap it in single-quotes, otherwise do wrap in single quotes.
*
* @param string $text The string.
*
* @return bool Whether or not it's a SQL function call.
*/
private function is_sql_method_call( $text ) {
$text = \trim( $text );
if ( \substr( $text, -2, 2 ) === '()' ) {
return true;
}
return false;
}
/**
* Checks if a transaction is active.
*
* @return bool
*/
private function in_transaction() {
return $this->in_transaction;
}
/**
* Starts a transaction.
*
* @return void
*
* @throws Exception If a transaction was already started.
*/
private function begin_transaction() {
global $wpdb;
if ( $this->in_transaction === true ) {
throw new Exception( 'Transaction already started' );
}
$wpdb->query( 'START TRANSACTION' );
$this->in_transaction = true;
}
/**
* Commits a transaction.
*
* @return void
*
* @throws Exception If no transaction was strated.
*/
private function commit() {
global $wpdb;
if ( $this->in_transaction === false ) {
throw new Exception( 'Transaction not started' );
}
$wpdb->query( 'COMMIT' );
$this->in_transaction = false;
}
/**
* Rollbacks a transaction.
*
* @return void
*
* @throws Exception If no transaction was started.
*/
private function rollback() {
global $wpdb;
if ( $this->in_transaction === false ) {
throw new Exception( 'Transaction not started' );
}
$wpdb->query( 'ROLLBACK' );
$this->in_transaction = false;
}
}
migrations/table.php 0000644 00000013761 15233603101 0010522 0 ustar 00 <?php
namespace Yoast\WP\Lib\Migrations;
use Exception;
/**
* Yoast migrations table class.
*/
class Table {
/**
* The adapter.
*
* @var Adapter
*/
private $adapter;
/**
* The name
*
* @var string
*/
private $name;
/**
* The options
*
* @var array
*/
private $options;
/**
* The SQL representation of this table.
*
* @var string
*/
private $sql = '';
/**
* Whether or not the table has been initialized.
*
* @var bool
*/
private $initialized = false;
/**
* The columns
*
* @var Column[]
*/
private $columns = [];
/**
* The primary keys.
*
* @var string[]
*/
private $primary_keys = [];
/**
* Whether or not to auto generate the id.
*
* @var bool
*/
private $auto_generate_id = true;
/**
* Creates an instance of the Adapter.
*
* @param Adapter $adapter The current adapter.
* @param string $name The table name.
* @param array $options The options.
*
* @throws Exception If invalid arguments are passed.
*/
public function __construct( $adapter, $name, $options = [] ) {
// Sanity checks.
if ( ! $adapter instanceof Adapter ) {
throw new Exception( 'Invalid MySQL Adapter instance.' );
}
if ( ! $name ) {
throw new Exception( "Invalid 'name' parameter" );
}
$this->adapter = $adapter;
$this->name = $name;
$this->options = $options;
$this->init_sql( $name, $options );
if ( \array_key_exists( 'id', $options ) ) {
if ( \is_bool( $options['id'] ) && $options['id'] === false ) {
$this->auto_generate_id = false;
}
// If its a string then we want to auto-generate an integer-based
// primary key with this name.
if ( \is_string( $options['id'] ) ) {
$this->auto_generate_id = true;
$this->primary_keys[] = $options['id'];
}
}
}
/**
* Create a column
*
* @param string $column_name The column name.
* @param string $type The column type.
* @param array $options The options.
*/
public function column( $column_name, $type, $options = [] ) {
// If there is already a column by the same name then silently fail and continue.
foreach ( $this->columns as $column ) {
if ( $column->name === $column_name ) {
return;
}
}
$column_options = [];
if ( \array_key_exists( 'primary_key', $options ) ) {
if ( $options['primary_key'] ) {
$this->primary_keys[] = $column_name;
}
}
if ( \array_key_exists( 'auto_increment', $options ) ) {
if ( $options['auto_increment'] ) {
$column_options['auto_increment'] = true;
}
}
$column_options = \array_merge( $column_options, $options );
$column = new Column( $this->adapter, $column_name, $type, $column_options );
$this->columns[] = $column;
}
/**
* Shortcut to create timestamps columns (default created_at, updated_at)
*
* @param string $created_column_name Created at column name.
* @param string $updated_column_name Updated at column name.
*/
public function timestamps( $created_column_name = 'created_at', $updated_column_name = 'updated_at' ) {
$this->column( $created_column_name, 'datetime' );
$this->column(
$updated_column_name,
'timestamp',
[
'null' => false,
'default' => 'CURRENT_TIMESTAMP',
'extra' => 'ON UPDATE CURRENT_TIMESTAMP',
]
);
}
/**
* Get all primary keys
*
* @return string
*/
private function keys() {
if ( \count( $this->primary_keys ) > 0 ) {
$lead = ' PRIMARY KEY (';
$quoted = [];
foreach ( $this->primary_keys as $key ) {
$quoted[] = \sprintf( '%s', $this->adapter->identifier( $key ) );
}
$primary_key_sql = ",\n" . $lead . \implode( ',', $quoted ) . ')';
return $primary_key_sql;
}
return '';
}
/**
* Table definition
*
* @param bool $wants_sql Whether or not to return SQL or execute the query. Defaults to false.
*
* @return bool|string
*
* @throws Exception If the table definition has not been intialized.
*/
public function finish( $wants_sql = false ) {
if ( ! $this->initialized ) {
throw new Exception( \sprintf( "Table Definition: '%s' has not been initialized", $this->name ) );
}
$opt_str = '';
if ( \is_array( $this->options ) && \array_key_exists( 'options', $this->options ) ) {
$opt_str = $this->options['options'];
}
else {
if ( isset( $this->adapter->db_info['charset'] ) ) {
$opt_str = ' DEFAULT CHARSET=' . $this->adapter->db_info['charset'];
}
else {
$opt_str = ' DEFAULT CHARSET=utf8';
}
}
$close_sql = \sprintf( ') %s;', $opt_str );
$create_table_sql = $this->sql;
if ( $this->auto_generate_id === true ) {
$this->primary_keys[] = 'id';
$primary_id = new Column(
$this->adapter,
'id',
'integer',
[
'unsigned' => true,
'null' => false,
'auto_increment' => true,
]
);
$create_table_sql .= $primary_id->to_sql() . ",\n";
}
$create_table_sql .= $this->columns_to_str();
$create_table_sql .= $this->keys() . $close_sql;
if ( $wants_sql ) {
return $create_table_sql;
}
return $this->adapter->execute_ddl( $create_table_sql );
}
/**
* Get SQL for all columns.
*
* @return string The SQL.
*/
private function columns_to_str() {
$str = '';
$fields = [];
$len = \count( $this->columns );
for ( $i = 0; $i < $len; $i++ ) {
$c = $this->columns[ $i ];
$fields[] = $c->__toString();
}
return \implode( ",\n", $fields );
}
/**
* Init create sql statement.
*
* @param string $name The name.
* @param array $options The options.
*/
private function init_sql( $name, $options ) {
// Are we forcing table creation? If so, drop it first.
if ( \array_key_exists( 'force', $options ) && $options['force'] === true ) {
$this->adapter->drop_table( $name );
}
$temp = '';
if ( \array_key_exists( 'temporary', $options ) ) {
$temp = ' TEMPORARY';
}
$create_sql = \sprintf( 'CREATE%s TABLE ', $temp );
$create_sql .= \sprintf( "%s (\n", $this->adapter->identifier( $name ) );
$this->sql .= $create_sql;
$this->initialized = true;
}
}
migrations/column.php 0000644 00000003465 15233603101 0010730 0 ustar 00 <?php
namespace Yoast\WP\Lib\Migrations;
use Exception;
/**
* Yoast migrations column class.
*/
class Column {
/**
* The adapter.
*
* @var Adapter
*/
private $adapter;
/**
* The name.
*
* @var string
*/
public $name;
/**
* The type.
*
* @var mixed
*/
public $type;
/**
* The properties.
*
* @var mixed
*/
public $properties;
/**
* The options.
*
* @var array
*/
private $options = [];
/**
* Creates an instance of a column.
*
* @param Adapter $adapter The current adapter.
* @param string $name The name of the column.
* @param string $type The type of the column.
* @param array $options The column options.
*
* @throws Exception If invalid arguments provided.
*/
public function __construct( $adapter, $name, $type, $options = [] ) {
if ( ! $adapter instanceof Adapter ) {
throw new Exception( 'Invalid Adapter instance.' );
}
if ( empty( $name ) || ! \is_string( $name ) ) {
throw new Exception( "Invalid 'name' parameter" );
}
if ( empty( $type ) || ! \is_string( $type ) ) {
throw new Exception( "Invalid 'type' parameter" );
}
$this->adapter = $adapter;
$this->name = $name;
$this->type = $type;
$this->options = $options;
}
/**
* Returns the SQL of this column.
*
* @return string
*/
public function to_sql() {
$column_sql = \sprintf( '%s %s', $this->adapter->identifier( $this->name ), $this->sql_type() );
$column_sql .= $this->adapter->add_column_options( $this->type, $this->options );
return $column_sql;
}
/**
* The SQL string version.
*
* @return string
*/
public function __toString() {
return $this->to_sql();
}
/**
* The SQL type.
*
* @return string
*/
private function sql_type() {
return $this->adapter->type_to_sql( $this->type, $this->options );
}
}
orm.php 0000644 00000206360 15233603101 0006053 0 ustar 00 <?php
namespace Yoast\WP\Lib;
use ReturnTypeWillChange;
use wpdb;
use Yoast\WP\SEO\Config\Migration_Status;
/**
* Yoast ORM class.
*
* Based on Idiorm
*
* URL: http://github.com/j4mie/idiorm/
*
* A single-class super-simple database abstraction layer for PHP.
* Provides (nearly) zero-configuration object-relational mapping
* and a fluent interface for building basic, commonly-used queries.
*
* BSD Licensed.
*
* Copyright (c) 2010, Jamie Matthews
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The methods documented below are magic methods that conform to PSR-1.
* This documentation exposes these methods to doc generators and IDEs.
*
* @see http://www.php-fig.org/psr/psr-1/
*/
class ORM implements \ArrayAccess {
/*
* --- CLASS CONSTANTS ---
*/
const CONDITION_FRAGMENT = 0;
const CONDITION_VALUES = 1;
/*
* --- INSTANCE PROPERTIES ---
*/
/**
* Holds the class name. Wrapped find_one and find_many classes will return an instance or instances of this class.
*
* @var string
*/
protected $class_name;
/**
* Holds the name of the table the current ORM instance is associated with.
*
* @var string
*/
protected $table_name;
/**
* Holds the alias for the table to be used in SELECT queries.
*
* @var string
*/
protected $table_alias = null;
/**
* Values to be bound to the query.
*
* @var array
*/
protected $values = [];
/**
* Columns to select in the result.
*
* @var array
*/
protected $result_columns = [ '*' ];
/**
* Are we using the default result column or have these been manually changed?
*
* @var bool
*/
protected $using_default_result_columns = true;
/**
* Holds the join sources.
*
* @var array
*/
protected $join_sources = [];
/**
* Should the query include a DISTINCT keyword?
*
* @var bool
*/
protected $distinct = false;
/**
* Is this a raw query?
*
* @var bool
*/
protected $is_raw_query = false;
/**
* The raw query.
*
* @var string
*/
protected $raw_query = '';
/**
* The raw query parameters.
*
* @var array
*/
protected $raw_parameters = [];
/**
* Array of WHERE clauses.
*
* @var array
*/
protected $where_conditions = [];
/**
* LIMIT.
*
* @var int
*/
protected $limit = null;
/**
* OFFSET.
*
* @var int
*/
protected $offset = null;
/**
* ORDER BY.
*
* @var array
*/
protected $order_by = [];
/**
* GROUP BY.
*
* @var array
*/
protected $group_by = [];
/**
* HAVING.
*
* @var array
*/
protected $having_conditions = [];
/**
* The data for a hydrated instance of the class.
*
* @var array
*/
protected $data = [];
/**
* Lifetime of the object.
*
* @var array
*/
protected $dirty_fields = [];
/**
* Fields that are to be inserted in the DB raw.
*
* @var array
*/
protected $expr_fields = [];
/**
* Is this a new object (has create() been called)?
*
* @var bool
*/
protected $is_new = false;
/**
* Name of the column to use as the primary key for
* this instance only. Overrides the config settings.
*
* @var string
*/
protected $instance_id_column = null;
/*
* --- STATIC METHODS ---
*/
/**
* Factory method, return an instance of this class bound to the supplied
* table name.
*
* A repeat of content in parent::for_table, so that created class is ORM.
*
* @param string $table_name The table to create instance for.
*
* @return ORM Instance of the ORM.
*/
public static function for_table( $table_name ) {
return new static( $table_name, [] );
}
/**
* Executes a raw query as a wrapper for wpdb::query.
* Useful for queries that can't be accomplished through Idiorm,
* particularly those using engine-specific features.
*
* @example raw_execute('INSERT OR REPLACE INTO `widget` (`id`, `name`) SELECT `id`, `name` FROM `other_table`')
* @example raw_execute('SELECT `name`, AVG(`order`) FROM `customer` GROUP BY `name` HAVING AVG(`order`) > 10')
*
* @param string $query The raw SQL query.
* @param array $parameters Optional bound parameters.
*
* @return bool Success.
*/
public static function raw_execute( $query, $parameters = [] ) {
return self::execute( $query, $parameters );
}
/**
* Internal helper method for executing statements.
*
* @param string $query The query.
* @param array $parameters An array of parameters to be bound in to the query.
*
* @return bool|int Response of wpdb::query
*/
protected static function execute( $query, $parameters = [] ) {
/**
* The global WordPress database variable.
*
* @var wpdb
*/
global $wpdb;
$show_errors = $wpdb->show_errors;
if ( YoastSEO()->classes->get( Migration_Status::class )->get_error( 'free' ) ) {
$wpdb->show_errors = false;
}
$parameters = \array_filter(
$parameters,
static function( $parameter ) {
return $parameter !== null;
}
);
if ( ! empty( $parameters ) ) {
$query = $wpdb->prepare( $query, $parameters );
}
$result = $wpdb->query( $query );
$wpdb->show_errors = $show_errors;
return $result;
}
/*
* --- INSTANCE METHODS ---
*/
/**
* "Private" constructor; shouldn't be called directly.
* Use the ORM::for_table factory method instead.
*
* @param string $table_name Table name.
* @param array $data Data to populate table.
*/
protected function __construct( $table_name, $data = [] ) {
$this->table_name = $table_name;
$this->data = $data;
}
/**
* Sets the name of the class which the wrapped methods should return instances of.
*
* @param string $class_name The classname to set.
*
* @return void
*/
public function set_class_name( $class_name ) {
$this->class_name = $class_name;
}
/**
* Creates a new, empty instance of the class. Used to add a new row to your database. May optionally be passed an
* associative array of data to populate the instance. If so, all fields will be flagged as dirty so all will be
* saved to the database when save() is called.
*
* @param array|null $data Data to populate table.
*
* @return bool|Model|ORM
*/
public function create( $data = null ) {
$this->is_new = true;
if ( ! \is_null( $data ) ) {
$this->hydrate( $data )->force_all_dirty();
}
return $this->create_model_instance( $this );
}
/**
* Specifies the ID column to use for this instance or array of instances only.
* This overrides the id_column and id_column_overrides settings.
*
* This is mostly useful for libraries built on top of Idiorm, and will not normally be used in manually built
* queries. If you don't know why you would want to use this, you should probably just ignore it.
*
* @param string $id_column The ID column.
*
* @return ORM
*/
public function use_id_column( $id_column ) {
$this->instance_id_column = $id_column;
return $this;
}
/**
* Creates an ORM instance from the given row (an associative array of data fetched from the database).
*
* @param array $row A row from the database.
*
* @return bool|Model
*/
protected function create_instance_from_row( $row ) {
$instance = self::for_table( $this->table_name );
$instance->use_id_column( $this->instance_id_column );
$instance->hydrate( $row );
return $this->create_model_instance( $instance );
}
/**
* Tells the ORM that you are expecting a single result back from your query, and execute it. Will return a single
* instance of the ORM class, or false if no rows were returned. As a shortcut, you may supply an ID as a parameter
* to this method. This will perform a primary key lookup on the table.
*
* @param int|null $id An (optional) ID.
*
* @return bool|Model
*/
public function find_one( $id = null ) {
if ( ! \is_null( $id ) ) {
$this->where_id_is( $id );
}
$this->limit( 1 );
$rows = $this->run();
if ( empty( $rows ) ) {
return false;
}
return $this->create_instance_from_row( $rows[0] );
}
/**
* Tells the ORM that you are expecting multiple results from your query, and execute it. Will return an array of
* instances of the ORM class, or an empty array if no rows were returned.
*
* @return array
*/
public function find_many() {
$rows = $this->run();
if ( $rows === false ) {
return [];
}
return \array_map( [ $this, 'create_instance_from_row' ], $rows );
}
/**
* Creates an instance of the model class associated with this wrapper and populate it with the supplied Idiorm
* instance.
*
* @param ORM $orm The ORM used by model.
*
* @return bool|Model Instance of the model class.
*/
protected function create_model_instance( $orm ) {
if ( $orm === false ) {
return false;
}
/**
* An instance of Model is being made.
*
* @var Model $model
*/
$model = new $this->class_name();
$model->set_orm( $orm );
return $model;
}
/**
* Tells the ORM that you are expecting multiple results from your query, and execute it. Will return an array, or
* an empty array if no rows were returned.
*
* @return array The query results.
*/
public function find_array() {
return $this->run();
}
/**
* Tells the ORM that you wish to execute a COUNT query.
*
* @param string $column The table column.
*
* @return float|int An integer representing the number of rows returned.
*/
public function count( $column = '*' ) {
return $this->call_aggregate_db_function( __FUNCTION__, $column );
}
/**
* Tells the ORM that you wish to execute a MAX query.
*
* @param string $column The table column.
*
* @return float|int The max value of the chosen column.
*/
public function max( $column ) {
return $this->call_aggregate_db_function( __FUNCTION__, $column );
}
/**
* Tells the ORM that you wish to execute a MIN query.
*
* @param string $column The table column.
*
* @return float|int The min value of the chosen column.
*/
public function min( $column ) {
return $this->call_aggregate_db_function( __FUNCTION__, $column );
}
/**
* Tells the ORM that you wish to execute a AVG query.
*
* @param string $column The table column.
*
* @return float|int The average value of the chosen column.
*/
public function avg( $column ) {
return $this->call_aggregate_db_function( __FUNCTION__, $column );
}
/**
* Tells the ORM that you wish to execute a SUM query.
*
* @param string $column The table column.
*
* @return float|int The sum of the chosen column.
*/
public function sum( $column ) {
return $this->call_aggregate_db_function( __FUNCTION__, $column );
}
/**
* Returns the select query as SQL.
*
* @return string The select query in SQL.
*/
public function get_sql() {
return $this->build_select();
}
/**
* Returns the update query as SQL.
*
* @return string The update query in SQL.
*/
public function get_update_sql() {
return $this->build_update();
}
/**
* Executes an aggregate query on the current connection.
*
* @param string $sql_function The aggregate function to call eg. MIN, COUNT, etc.
* @param string $column The column to execute the aggregate query against.
*
* @return int
*/
protected function call_aggregate_db_function( $sql_function, $column ) {
$alias = \strtolower( $sql_function );
$sql_function = \strtoupper( $sql_function );
if ( $column !== '*' ) {
$column = $this->quote_identifier( $column );
}
$result_columns = $this->result_columns;
$this->result_columns = [];
$this->select_expr( "{$sql_function}({$column})", $alias );
$result = $this->find_one();
$this->result_columns = $result_columns;
$return_value = 0;
if ( $result !== false && isset( $result->{$alias} ) ) {
if ( ! \is_numeric( $result->{$alias} ) ) {
$return_value = $result->{$alias};
}
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- Reason: This loose comparison seems intended.
elseif ( (int) $result->{$alias} == (float) $result->{$alias} ) {
$return_value = (int) $result->{$alias};
}
else {
$return_value = (float) $result->{$alias};
}
}
return $return_value;
}
/**
* Hydrates (populate) this instance of the class from an associative array of data. This will usually be called
* only from inside the class, but it's public in case you need to call it directly.
*
* @param array $data Data to populate table.
*
* @return ORM
*/
public function hydrate( $data = [] ) {
$this->data = $data;
return $this;
}
/**
* Forces the ORM to flag all the fields in the $data array as "dirty" and therefore update them when save() is
* called.
*
* @return ORM
*/
public function force_all_dirty() {
$this->dirty_fields = $this->data;
return $this;
}
/**
* Performs a raw query. The query can contain placeholders in either named or question mark style. If placeholders
* are used, the parameters should be an array of values which will be bound to the placeholders in the query.
* If this method is called, all other query building methods will be ignored.
*
* @param array $query The query.
* @param array $parameters The parameters. Defaults to an empty array.
*
* @return ORM
*/
public function raw_query( $query, $parameters = [] ) {
$this->is_raw_query = true;
$this->raw_query = $query;
$this->raw_parameters = $parameters;
return $this;
}
/**
* Adds an alias for the main table to be used in SELECT queries.
*
* @param string $alias The alias.
*
* @return ORM
*/
public function table_alias( $alias ) {
$this->table_alias = $alias;
return $this;
}
/**
* Adds an unquoted expression to the set of columns returned by the SELECT query. Internal method.
*
* @param string $expr The expression.
* @param string|null $alias The alias to return the expression as. Defaults to null.
*
* @return ORM
*/
protected function add_result_column( $expr, $alias = null ) {
if ( ! \is_null( $alias ) ) {
$expr .= ' AS ' . $this->quote_identifier( $alias );
}
if ( $this->using_default_result_columns ) {
$this->result_columns = [ $expr ];
$this->using_default_result_columns = false;
}
else {
$this->result_columns[] = $expr;
}
return $this;
}
/**
* Counts the number of columns that belong to the primary key and their value is null.
*
* @return int The amount of null columns.
*
* @throws \Exception Primary key ID contains null value(s).
* @throws \Exception Primary key ID missing from row or is null.
*/
public function count_null_id_columns() {
if ( \is_array( $this->get_id_column_name() ) ) {
return \count( \array_filter( $this->id(), 'is_null' ) );
}
else {
return \is_null( $this->id() ) ? 1 : 0;
}
}
/**
* Adds a column to the list of columns returned by the SELECT query.
*
* @param string $column The column. Defaults to '*'.
* @param string|null $alias The alias to return the column as. Defaults to null.
*
* @return ORM
*/
public function select( $column, $alias = null ) {
$column = $this->quote_identifier( $column );
return $this->add_result_column( $column, $alias );
}
/**
* Adds an unquoted expression to the list of columns returned by the SELECT query.
*
* @param string $expr The expression.
* @param string|null $alias The alias to return the column as. Defaults to null.
*
* @return ORM
*/
public function select_expr( $expr, $alias = null ) {
return $this->add_result_column( $expr, $alias );
}
/**
* Adds columns to the list of columns returned by the SELECT query.
*
* This defaults to '*'.
* Many columns can be supplied as either an array or as a list of parameters to the method.
* Note that the alias must not be numeric - if you want a numeric alias then prepend it with some alpha chars. eg.
* a1.
*
* @example select_many(array('column', 'column2', 'column3'), 'column4', 'column5');
* @example select_many(array('alias' => 'column', 'column2', 'alias2' => 'column3'), 'column4', 'column5');
* @example select_many('column', 'column2', 'column3');
*
* @return ORM
*/
public function select_many() {
$columns = \func_get_args();
if ( ! empty( $columns ) ) {
$columns = $this->normalise_select_many_columns( $columns );
foreach ( $columns as $alias => $column ) {
if ( \is_numeric( $alias ) ) {
$alias = null;
}
$this->select( $column, $alias );
}
}
return $this;
}
/**
* Adds an unquoted expression to the list of columns returned by the SELECT query.
*
* Many columns can be supplied as either an array or as a list of parameters to the method.
* Note that the alias must not be numeric - if you want a numeric alias then prepend it with some alpha chars. eg.
* a1
*
* @example select_many_expr(array('alias' => 'column', 'column2', 'alias2' => 'column3'), 'column4', 'column5')
* @example select_many_expr('column', 'column2', 'column3')
* @example select_many_expr(array('column', 'column2', 'column3'), 'column4', 'column5')
*
* @return ORM
*/
public function select_many_expr() {
$columns = \func_get_args();
if ( ! empty( $columns ) ) {
$columns = $this->normalise_select_many_columns( $columns );
foreach ( $columns as $alias => $column ) {
if ( \is_numeric( $alias ) ) {
$alias = null;
}
$this->select_expr( $column, $alias );
}
}
return $this;
}
/**
* Takes a column specification for the select many methods and convert it into a normalised array of columns and
* aliases.
*
* It is designed to turn the following styles into a normalised array:
* array(array('alias' => 'column', 'column2', 'alias2' => 'column3'), 'column4', 'column5'))
*
* @param array $columns The columns.
*
* @return array
*/
protected function normalise_select_many_columns( $columns ) {
$return = [];
foreach ( $columns as $column ) {
if ( \is_array( $column ) ) {
foreach ( $column as $key => $value ) {
if ( ! \is_numeric( $key ) ) {
$return[ $key ] = $value;
}
else {
$return[] = $value;
}
}
}
else {
$return[] = $column;
}
}
return $return;
}
/**
* Adds a DISTINCT keyword before the list of columns in the SELECT query.
*
* @return ORM
*/
public function distinct() {
$this->distinct = true;
return $this;
}
/**
* Add a JOIN source to the query. Internal method.
*
* The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this
* will be prepended to JOIN.
*
* The table should be the name of the table to join to.
*
* The constraint may be either a string or an array with three elements. If it
* is a string, it will be compiled into the query as-is, with no escaping. The
* recommended way to supply the constraint is as an array with three elements:
*
* first_column, operator, second_column
*
* Example: array('user.id', '=', 'profile.user_id')
*
* will compile to
*
* ON `user`.`id` = `profile`.`user_id`
*
* The final (optional) argument specifies an alias for the joined table.
*
* @param string $join_operator The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be
* prepended to JOIN.
* @param string $table The table should be the name of the table to join to.
* @param string $constraint The constraint.
* @param string|null $table_alias The alias for the joined table. Defaults to null.
*
* @return ORM
*/
protected function add_join_source( $join_operator, $table, $constraint, $table_alias = null ) {
$join_operator = \trim( "{$join_operator} JOIN" );
$table = $this->quote_identifier( $table );
// Add table alias if present.
if ( ! \is_null( $table_alias ) ) {
$table_alias = $this->quote_identifier( $table_alias );
$table .= " {$table_alias}";
}
// Build the constraint.
if ( \is_array( $constraint ) ) {
list( $first_column, $operator, $second_column ) = $constraint;
$first_column = $this->quote_identifier( $first_column );
$second_column = $this->quote_identifier( $second_column );
$constraint = "{$first_column} {$operator} {$second_column}";
}
$this->join_sources[] = "{$join_operator} {$table} ON {$constraint}";
return $this;
}
/**
* Adds a RAW JOIN source to the query.
*
* @param string $table The table name.
* @param string $constraint The constraint.
* @param string $table_alias The table alias.
* @param array $parameters The parameters. Defaults to an empty array.
*
* @return ORM
*/
public function raw_join( $table, $constraint, $table_alias, $parameters = [] ) {
// Add table alias if present.
if ( ! \is_null( $table_alias ) ) {
$table_alias = $this->quote_identifier( $table_alias );
$table .= " {$table_alias}";
}
$this->values = \array_merge( $this->values, $parameters );
// Build the constraint.
if ( \is_array( $constraint ) ) {
list( $first_column, $operator, $second_column ) = $constraint;
$first_column = $this->quote_identifier( $first_column );
$second_column = $this->quote_identifier( $second_column );
$constraint = "{$first_column} {$operator} {$second_column}";
}
$this->join_sources[] = "{$table} ON {$constraint}";
return $this;
}
/**
* Adds a simple JOIN source to the query.
*
* @param string $table The table name.
* @param string $constraint The constraint.
* @param string|null $table_alias The table alias. Defaults to null.
*
* @return ORM
*/
public function join( $table, $constraint, $table_alias = null ) {
return $this->add_join_source( '', $table, $constraint, $table_alias );
}
/**
* Adds an INNER JOIN source to the query.
*
* @param string $table The table name.
* @param string $constraint The constraint.
* @param string|null $table_alias The table alias. Defaults to null.
*
* @return ORM
*/
public function inner_join( $table, $constraint, $table_alias = null ) {
return $this->add_join_source( 'INNER', $table, $constraint, $table_alias );
}
/**
* Adds a LEFT OUTER JOIN source to the query.
*
* @param string $table The table name.
* @param string $constraint The constraint.
* @param string|null $table_alias The table alias. Defaults to null.
*
* @return ORM
*/
public function left_outer_join( $table, $constraint, $table_alias = null ) {
return $this->add_join_source( 'LEFT OUTER', $table, $constraint, $table_alias );
}
/**
* Adds a RIGHT OUTER JOIN source to the query.
*
* @param string $table The table name.
* @param string $constraint The constraint.
* @param string|null $table_alias The table alias. Defaults to null.
*
* @return ORM
*/
public function right_outer_join( $table, $constraint, $table_alias = null ) {
return $this->add_join_source( 'RIGHT OUTER', $table, $constraint, $table_alias );
}
/**
* Adds a FULL OUTER JOIN source to the query.
*
* @param string $table The table name.
* @param string $constraint The constraint.
* @param string|null $table_alias The table alias. Defaults to null.
*
* @return ORM
*/
public function full_outer_join( $table, $constraint, $table_alias = null ) {
return $this->add_join_source( 'FULL OUTER', $table, $constraint, $table_alias );
}
/**
* Adds a HAVING condition to the query. Internal method.
*
* @param string $fragment The fragment.
* @param array $values The values. Defaults to an empty array.
*
* @return ORM
*/
protected function add_having( $fragment, $values = [] ) {
return $this->add_condition( 'having', $fragment, $values );
}
/**
* Adds a HAVING condition to the query. Internal method.
*
* @param string $column_name The table column.
* @param string $separator The separator.
* @param mixed $value The value.
*
* @return ORM
*/
protected function add_simple_having( $column_name, $separator, $value ) {
return $this->add_simple_condition( 'having', $column_name, $separator, $value );
}
/**
* Adds a HAVING clause with multiple values (like IN and NOT IN). Internal method.
*
* @param string|array $column_name The table column.
* @param string $separator The separator.
* @param array $values The values.
*
* @return ORM
*/
public function add_having_placeholder( $column_name, $separator, $values ) {
if ( ! \is_array( $column_name ) ) {
$data = [ $column_name => $values ];
}
else {
$data = $column_name;
}
$result = $this;
foreach ( $data as $key => $val ) {
$column = $result->quote_identifier( $key );
$placeholders = $result->create_placeholders( $val );
$result = $result->add_having( "{$column} {$separator} ({$placeholders})", $val );
}
return $result;
}
/**
* Adds a HAVING clause with no parameters(like IS NULL and IS NOT NULL). Internal method.
*
* @param string $column_name The column name.
* @param string $operator The operator.
*
* @return ORM
*/
public function add_having_no_value( $column_name, $operator ) {
$conditions = \is_array( $column_name ) ? $column_name : [ $column_name ];
$result = $this;
foreach ( $conditions as $column ) {
$column = $this->quote_identifier( $column );
$result = $result->add_having( "{$column} {$operator}" );
}
return $result;
}
/**
* Adds a WHERE condition to the query. Internal method.
*
* @param string $fragment The fragment.
* @param array $values The values. Defaults to an empty array.
*
* @return ORM
*/
protected function add_where( $fragment, $values = [] ) {
return $this->add_condition( 'where', $fragment, $values );
}
/**
* Adds a WHERE condition to the query. Internal method.
*
* @param string|array $column_name The table column.
* @param string $separator The separator.
* @param mixed $value The value.
*
* @return ORM
*/
protected function add_simple_where( $column_name, $separator, $value ) {
return $this->add_simple_condition( 'where', $column_name, $separator, $value );
}
/**
* Adds a WHERE clause with multiple values (like IN and NOT IN).
*
* @param string|array $column_name The table column.
* @param string $separator The separator.
* @param array $values The values.
*
* @return ORM
*/
public function add_where_placeholder( $column_name, $separator, $values ) {
if ( ! \is_array( $column_name ) ) {
$data = [ $column_name => $values ];
}
else {
$data = $column_name;
}
$result = $this;
foreach ( $data as $key => $val ) {
$column = $result->quote_identifier( $key );
$placeholders = $result->create_placeholders( $val );
$result = $result->add_where( "{$column} {$separator} ({$placeholders})", $val );
}
return $result;
}
/**
* Adds a WHERE clause with no parameters(like IS NULL and IS NOT NULL).
*
* @param string $column_name The column name.
* @param string $operator The operator.
*
* @return ORM
*/
public function add_where_no_value( $column_name, $operator ) {
$conditions = \is_array( $column_name ) ? $column_name : [ $column_name ];
$result = $this;
foreach ( $conditions as $column ) {
$column = $this->quote_identifier( $column );
$result = $result->add_where( "{$column} {$operator}" );
}
return $result;
}
/**
* Adds a HAVING or WHERE condition to the query. Internal method.
*
* @param string $type The type.
* @param string $fragment The fragment.
* @param array $values The values. Defaults to empty array.
*
* @return ORM
*/
protected function add_condition( $type, $fragment, $values = [] ) {
$conditions_class_property_name = "{$type}_conditions";
if ( ! \is_array( $values ) ) {
$values = [ $values ];
}
\array_push(
$this->{$conditions_class_property_name},
[
self::CONDITION_FRAGMENT => $fragment,
self::CONDITION_VALUES => $values,
]
);
return $this;
}
/**
* Compiles a simple COLUMN SEPARATOR VALUE style HAVING or WHERE condition into a string and value ready to be
* passed to the add_condition method.
*
* Avoids duplication of the call to quote_identifier.
* If column_name is an associative array, it will add a condition for each column.
*
* @param string $type The type.
* @param string|array $column_name The table column.
* @param string $separator The separator.
* @param mixed $value The value.
*
* @return ORM
*/
protected function add_simple_condition( $type, $column_name, $separator, $value ) {
$multiple = \is_array( $column_name ) ? $column_name : [ $column_name => $value ];
$result = $this;
foreach ( $multiple as $key => $val ) {
// Add the table name in case of ambiguous columns.
if ( \count( $result->join_sources ) > 0 && \strpos( $key, '.' ) === false ) {
$table = $result->table_name;
if ( ! \is_null( $result->table_alias ) ) {
$table = $result->table_alias;
}
$key = "{$table}.{$key}";
}
$key = $result->quote_identifier( $key );
$placeholder = ( $val === null ) ? 'NULL' : '%s';
$result = $result->add_condition( $type, "{$key} {$separator} {$placeholder}", $val );
}
return $result;
}
/**
* Returns a string containing the given number of question marks, separated by commas. Eg "?, ?, ?".
*
* @param array $fields Fields to create placeholder for.
*
* @return string
*/
protected function create_placeholders( $fields ) {
if ( ! empty( $fields ) ) {
$db_fields = [];
foreach ( $fields as $key => $value ) {
// Process expression fields directly into the query.
if ( \array_key_exists( $key, $this->expr_fields ) ) {
$db_fields[] = $value;
}
else {
$db_fields[] = ( $value === null ) ? 'NULL' : '%s';
}
}
return \implode( ', ', $db_fields );
}
return '';
}
/**
* Filters a column/value array returning only those columns that belong to a compound primary key.
*
* If the key contains a column that does not exist in the given array, a null value will be returned for it.
*
* @param mixed $value The value.
*
* @return array
*/
protected function get_compound_id_column_values( $value ) {
$filtered = [];
foreach ( $this->get_id_column_name() as $key ) {
$filtered[ $key ] = isset( $value[ $key ] ) ? $value[ $key ] : null;
}
return $filtered;
}
/**
* Filters an array containing compound column/value arrays.
*
* @param array $values The values.
*
* @return array
*/
protected function get_compound_id_column_values_array( $values ) {
$filtered = [];
foreach ( $values as $value ) {
$filtered[] = $this->get_compound_id_column_values( $value );
}
return $filtered;
}
/**
* Add a WHERE column = value clause to your query. Each time this is called in the chain, an additional WHERE will
* be added, and these will be ANDed together when the final query is built.
*
* If you use an array in $column_name, a new clause will be added for each element. In this case, $value is
* ignored.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where( $column_name, $value = null ) {
return $this->where_equal( $column_name, $value );
}
/**
* More explicitly named version of for the where() method. Can be used if preferred.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where_equal( $column_name, $value = null ) {
return $this->add_simple_where( $column_name, '=', $value );
}
/**
* Add a WHERE column != value clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where_not_equal( $column_name, $value = null ) {
return $this->add_simple_where( $column_name, '!=', $value );
}
/**
* Queries the table by its primary key. Special method.
*
* If primary key is compound, only the columns that belong to they key will be used for the query.
*
* @param string $id The ID.
*
* @return ORM
*/
public function where_id_is( $id ) {
return \is_array( $this->get_id_column_name() ) ? $this->where( $this->get_compound_id_column_values( $id ), null ) : $this->where( $this->get_id_column_name(), $id );
}
/**
* Allows adding a WHERE clause that matches any of the conditions specified in the array. Each element in the
* associative array will be a different condition, where the key will be the column name.
*
* By default, an equal operator will be used against all columns, but it can be overriden for any or every column
* using the second parameter.
*
* Each condition will be ORed together when added to the final query.
*
* @param array $values The values.
* @param string $operator The operator.
*
* @return ORM
*/
public function where_any_is( $values, $operator = '=' ) {
$data = [];
$query = [ '((' ];
$first = true;
foreach ( $values as $value ) {
if ( $first ) {
$first = false;
}
else {
$query[] = ') OR (';
}
$firstsub = true;
foreach ( $value as $key => $item ) {
$op = \is_string( $operator ) ? $operator : ( isset( $operator[ $key ] ) ? $operator[ $key ] : '=' );
if ( $op === '=' && $item === null ) {
$op = 'IS';
}
if ( $firstsub ) {
$firstsub = false;
}
else {
$query[] = 'AND';
}
$query[] = $this->quote_identifier( $key );
$data[] = $item;
$query[] = $op;
$query[] = ( ( $item === null ) ? 'NULL' : '%s' );
}
}
$query[] = '))';
return $this->where_raw( \implode( ' ', $query ), $data );
}
/**
* Queries the table by its primary key.
*
* Similar to where_id_is() but allowing multiple primary keys.
* If primary key is compound, only the columns that belong to they key will be used for the query.
*
* @param string[] $ids The IDs.
*
* @return ORM
*/
public function where_id_in( $ids ) {
return \is_array( $this->get_id_column_name() ) ? $this->where_any_is( $this->get_compound_id_column_values_array( $ids ) ) : $this->where_in( $this->get_id_column_name(), $ids );
}
/**
* Adds a WHERE ... LIKE clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where_like( $column_name, $value = null ) {
return $this->add_simple_where( $column_name, 'LIKE', $value );
}
/**
* Adds where WHERE ... NOT LIKE clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where_not_like( $column_name, $value = null ) {
return $this->add_simple_where( $column_name, 'NOT LIKE', $value );
}
/**
* Adds a WHERE ... > clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where_gt( $column_name, $value = null ) {
return $this->add_simple_where( $column_name, '>', $value );
}
/**
* Adds a WHERE ... < clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where_lt( $column_name, $value = null ) {
return $this->add_simple_where( $column_name, '<', $value );
}
/**
* Adds a WHERE ... >= clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where_gte( $column_name, $value = null ) {
return $this->add_simple_where( $column_name, '>=', $value );
}
/**
* Adds a WHERE ... <= clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value. Defaults to null.
*
* @return ORM
*/
public function where_lte( $column_name, $value = null ) {
return $this->add_simple_where( $column_name, '<=', $value );
}
/**
* Adds a WHERE ... IN clause to your query.
*
* @param string|array $column_name The table column.
* @param array $values The values.
*
* @return ORM
*/
public function where_in( $column_name, $values ) {
return $this->add_where_placeholder( $column_name, 'IN', $values );
}
/**
* Adds a WHERE ... NOT IN clause to your query.
*
* @param string|array $column_name The table column.
* @param array $values The values.
*
* @return ORM
*/
public function where_not_in( $column_name, $values ) {
return $this->add_where_placeholder( $column_name, 'NOT IN', $values );
}
/**
* Adds a WHERE column IS NULL clause to your query.
*
* @param string|array $column_name The table column.
*
* @return ORM
*/
public function where_null( $column_name ) {
return $this->add_where_no_value( $column_name, 'IS NULL' );
}
/**
* Adds a WHERE column IS NOT NULL clause to your query.
*
* @param string|array $column_name The table column.
*
* @return ORM
*/
public function where_not_null( $column_name ) {
return $this->add_where_no_value( $column_name, 'IS NOT NULL' );
}
/**
* Adds a raw WHERE clause to the query. The clause should contain question mark placeholders, which will be bound
* to the parameters supplied in the second argument.
*
* @param string $clause The clause that should contain question mark placeholders.
* @param array $parameters The parameters to include in the query.
*
* @return ORM
*/
public function where_raw( $clause, $parameters = [] ) {
return $this->add_where( $clause, $parameters );
}
/**
* Adds a LIMIT to the query.
*
* @param int $limit The limit.
*
* @return ORM
*/
public function limit( $limit ) {
$this->limit = $limit;
return $this;
}
/**
* Adds an OFFSET to the query.
*
* @param int $offset The offset.
*
* @return ORM
*/
public function offset( $offset ) {
$this->offset = $offset;
return $this;
}
/**
* Adds an ORDER BY clause to the query.
*
* @param string $column_name The column name.
* @param string $ordering The ordering. DESC or ASC.
*
* @return ORM
*/
protected function add_order_by( $column_name, $ordering ) {
$column_name = $this->quote_identifier( $column_name );
$this->order_by[] = "{$column_name} {$ordering}";
return $this;
}
/**
* Adds an ORDER BY column DESC clause.
*
* @param string|array $column_name The table column.
*
* @return ORM
*/
public function order_by_desc( $column_name ) {
return $this->add_order_by( $column_name, 'DESC' );
}
/**
* Adds an ORDER BY column ASC clause.
*
* @param string|array $column_name The table column.
*
* @return ORM
*/
public function order_by_asc( $column_name ) {
return $this->add_order_by( $column_name, 'ASC' );
}
/**
* Adds an unquoted expression as an ORDER BY clause.
*
* @param string $clause The clause.
*
* @return ORM
*/
public function order_by_expr( $clause ) {
$this->order_by[] = $clause;
return $this;
}
/**
* Adds a column to the list of columns to GROUP BY.
*
* @param string|array $column_name The table column.
*
* @return ORM
*/
public function group_by( $column_name ) {
$column_name = $this->quote_identifier( $column_name );
$this->group_by[] = $column_name;
return $this;
}
/**
* Adds an unquoted expression to the list of columns to GROUP BY.
*
* @param string $expr The expression.
*
* @return ORM
*/
public function group_by_expr( $expr ) {
$this->group_by[] = $expr;
return $this;
}
/**
* Adds a HAVING column = value clause to your query.
*
* Each time this is called in the chain, an additional HAVING will be added, and these will be ANDed together when
* the final query is built.
*
* If you use an array in $column_name, a new clause will be added for each element. In this case, $value is
* ignored.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value.
*
* @return ORM
*/
public function having( $column_name, $value = null ) {
return $this->having_equal( $column_name, $value );
}
/**
* Adds a having equal to your query.
*
* More explicitly named version of for the having() method. Can be used if preferred.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value.
*
* @return ORM
*/
public function having_equal( $column_name, $value = null ) {
return $this->add_simple_having( $column_name, '=', $value );
}
/**
* Adds a HAVING column != value clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed|null $value The value.
*
* @return ORM
*/
public function having_not_equal( $column_name, $value = null ) {
return $this->add_simple_having( $column_name, '!=', $value );
}
/**
* Queries the table by its primary key. Special method.
*
* If primary key is compound, only the columns that belong to they key will be used for the query.
*
* @param string $id The ID.
*
* @return ORM
*/
public function having_id_is( $id ) {
return \is_array( $this->get_id_column_name() ) ? $this->having( $this->get_compound_id_column_values( $id ), null ) : $this->having( $this->get_id_column_name(), $id );
}
/**
* Adds a HAVING ... LIKE clause to your query.
*
* @param string|array $column_name The table column.
* @param string|null $value The value.
*
* @return ORM
*/
public function having_like( $column_name, $value = null ) {
return $this->add_simple_having( $column_name, 'LIKE', $value );
}
/**
* Adds where HAVING ... NOT LIKE clause to your query.
*
* @param string|array $column_name The table column.
* @param string|null $value The value.
*
* @return ORM
*/
public function having_not_like( $column_name, $value = null ) {
return $this->add_simple_having( $column_name, 'NOT LIKE', $value );
}
/**
* Adds a HAVING ... > clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed $value The value.
*
* @return ORM
*/
public function having_gt( $column_name, $value = null ) {
return $this->add_simple_having( $column_name, '>', $value );
}
/**
* Adds a HAVING ... < clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed $value The value.
*
* @return ORM
*/
public function having_lt( $column_name, $value = null ) {
return $this->add_simple_having( $column_name, '<', $value );
}
/**
* Adds a HAVING ... >= clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed $value The value. Defaults to null.
*
* @return ORM
*/
public function having_gte( $column_name, $value = null ) {
return $this->add_simple_having( $column_name, '>=', $value );
}
/**
* Adds a HAVING ... <= clause to your query.
*
* @param string|array $column_name The table column.
* @param mixed $value The value.
*
* @return ORM
*/
public function having_lte( $column_name, $value = null ) {
return $this->add_simple_having( $column_name, '<=', $value );
}
/**
* Adds a HAVING ... IN clause to your query.
*
* @param string|array $column_name The table column.
* @param array|null $values The values. Defaults to null.
*
* @return ORM
*/
public function having_in( $column_name, $values = null ) {
return $this->add_having_placeholder( $column_name, 'IN', $values );
}
/**
* Adds a HAVING ... NOT IN clause to your query.
*
* @param string|array $column_name The table column.
* @param array|null $values The values. Defaults to null.
*
* @return ORM
*/
public function having_not_in( $column_name, $values = null ) {
return $this->add_having_placeholder( $column_name, 'NOT IN', $values );
}
/**
* Adds a HAVING column IS NULL clause to your query.
*
* @param string|array $column_name The table column.
*
* @return ORM
*/
public function having_null( $column_name ) {
return $this->add_having_no_value( $column_name, 'IS NULL' );
}
/**
* Adds a HAVING column IS NOT NULL clause to your query.
*
* @param string|array $column_name The table column.
*
* @return ORM
*/
public function having_not_null( $column_name ) {
return $this->add_having_no_value( $column_name, 'IS NOT NULL' );
}
/**
* Adds a raw HAVING clause to the query. The clause should contain question mark placeholders, which will be bound
* to the parameters supplied in the second argument.
*
* @param string $clause The clause that should contain question mark placeholders.
* @param array $parameters The parameters to include in the query.
*
* @return ORM
*/
public function having_raw( $clause, $parameters = [] ) {
return $this->add_having( $clause, $parameters );
}
/**
* Builds a SELECT statement based on the clauses that have been passed to this instance by chaining method calls.
*
* @return string
*/
protected function build_select() {
// If the query is raw, just set the $this->values to be the raw query parameters and return the raw query.
if ( $this->is_raw_query ) {
$this->values = $this->raw_parameters;
return $this->raw_query;
}
// Build and return the full SELECT statement by concatenating the results of calling each separate builder method.
return $this->join_if_not_empty(
' ',
[
$this->build_select_start(),
$this->build_join(),
$this->build_where(),
$this->build_group_by(),
$this->build_having(),
$this->build_order_by(),
$this->build_limit(),
$this->build_offset(),
]
);
}
/**
* Builds the start of the SELECT statement.
*
* @return string
*/
protected function build_select_start() {
$fragment = 'SELECT ';
$result_columns = \implode( ', ', $this->result_columns );
if ( $this->distinct ) {
$result_columns = 'DISTINCT ' . $result_columns;
}
$fragment .= "{$result_columns} FROM " . $this->quote_identifier( $this->table_name );
if ( ! \is_null( $this->table_alias ) ) {
$fragment .= ' ' . $this->quote_identifier( $this->table_alias );
}
return $fragment;
}
/**
* Builds the JOIN sources.
*
* @return string
*/
protected function build_join() {
if ( \count( $this->join_sources ) === 0 ) {
return '';
}
return \implode( ' ', $this->join_sources );
}
/**
* Builds the WHERE clause(s).
*
* @return string
*/
protected function build_where() {
return $this->build_conditions( 'where' );
}
/**
* Build the HAVING clause(s)
*
* @return string
*/
protected function build_having() {
return $this->build_conditions( 'having' );
}
/**
* Builds GROUP BY.
*
* @return string
*/
protected function build_group_by() {
if ( \count( $this->group_by ) === 0 ) {
return '';
}
return 'GROUP BY ' . \implode( ', ', $this->group_by );
}
/**
* Builds a WHERE or HAVING clause.
*
* @param string $type Where or having.
*
* @return string
*/
protected function build_conditions( $type ) {
$conditions_class_property_name = "{$type}_conditions";
// If there are no clauses, return empty string.
if ( \count( $this->{$conditions_class_property_name} ) === 0 ) {
return '';
}
$conditions = [];
foreach ( $this->{$conditions_class_property_name} as $condition ) {
$conditions[] = $condition[ self::CONDITION_FRAGMENT ];
$this->values = \array_merge( $this->values, $condition[ self::CONDITION_VALUES ] );
}
return \strtoupper( $type ) . ' ' . \implode( ' AND ', $conditions );
}
/**
* Builds ORDER BY.
*
* @return string
*/
protected function build_order_by() {
if ( \count( $this->order_by ) === 0 ) {
return '';
}
return 'ORDER BY ' . \implode( ', ', $this->order_by );
}
/**
* Builds LIMIT.
*
* @return string
*/
protected function build_limit() {
if ( ! \is_null( $this->limit ) ) {
return "LIMIT {$this->limit}";
}
return '';
}
/**
* Builds OFFSET.
*
* @return string
*/
protected function build_offset() {
if ( ! \is_null( $this->offset ) ) {
return 'OFFSET ' . $this->offset;
}
return '';
}
/**
* Joins strings if they are not empty.
*
* @param string $glue Glue.
* @param string[] $pieces Pieces to join.
*
* @return string
*/
protected function join_if_not_empty( $glue, $pieces ) {
$filtered_pieces = [];
foreach ( $pieces as $piece ) {
if ( \is_string( $piece ) ) {
$piece = \trim( $piece );
}
if ( ! empty( $piece ) ) {
$filtered_pieces[] = $piece;
}
}
return \implode( $glue, $filtered_pieces );
}
/**
* Quotes a string that is used as an identifier (table names, column names etc).
* This method can also deal with dot-separated identifiers eg table.column.
*
* @param string|string[] $identifier One or more identifiers.
*
* @return string
*/
protected function quote_one_identifier( $identifier ) {
$parts = \explode( '.', $identifier );
$parts = \array_map( [ $this, 'quote_identifier_part' ], $parts );
return \implode( '.', $parts );
}
/**
* Quotes a string that is used as an identifier (table names, column names etc) or an array containing multiple
* identifiers. This method can also deal with dot-separated identifiers eg table.column.
*
* @param string|string[] $identifier One or more identifiers.
*
* @return string
*/
protected function quote_identifier( $identifier ) {
if ( \is_array( $identifier ) ) {
$result = \array_map( [ $this, 'quote_one_identifier' ], $identifier );
return \implode( ', ', $result );
}
else {
return $this->quote_one_identifier( $identifier );
}
}
/**
* Quotes a single part of an identifier, using the identifier quote character specified in the config
* (or autodetected).
*
* @param string $part The part to quote.
*
* @return string
*/
protected function quote_identifier_part( $part ) {
if ( $part === '*' ) {
return $part;
}
$quote_character = '`';
// Double up any identifier quotes to escape them.
return $quote_character . \str_replace( $quote_character, $quote_character . $quote_character, $part ) . $quote_character;
}
/**
* Executes the SELECT query that has been built up by chaining methods on this class.
* Return an array of rows as associative arrays.
*
* @return array|false The result rows. False if the query failed.
*/
protected function run() {
global $wpdb;
$query = $this->build_select();
$success = self::execute( $query, $this->values );
if ( $success === false ) {
// If the query fails run the migrations and try again.
// Action is intentionally undocumented and should not be used by third-parties.
\do_action( '_yoast_run_migrations' );
$success = self::execute( $query, $this->values );
}
$this->reset_idiorm_state();
if ( $success === false ) {
return false;
}
$rows = [];
foreach ( $wpdb->last_result as $row ) {
$rows[] = \get_object_vars( $row );
}
return $rows;
}
/**
* Resets the Idiorm instance state.
*/
private function reset_idiorm_state() {
$this->values = [];
$this->result_columns = [ '*' ];
$this->using_default_result_columns = true;
}
/**
* Returns the raw data wrapped by this ORM instance as an associative array. Column names may optionally be
* supplied as arguments, if so, only those keys will be returned.
*
* @return array Associative array of the raw data.
*/
public function as_array() {
if ( \func_num_args() === 0 ) {
return $this->data;
}
$args = \func_get_args();
return \array_intersect_key( $this->data, \array_flip( $args ) );
}
/**
* Returns the value of a property of this object (database row) or null if not present.
*
* If a column-names array is passed, it will return a associative array with the value of each column or null if
* it is not present.
*
* @param string|array $key Key.
*
* @return array|mixed|null
*/
public function get( $key ) {
if ( \is_array( $key ) ) {
$result = [];
foreach ( $key as $column ) {
$result[ $column ] = isset( $this->data[ $column ] ) ? $this->data[ $column ] : null;
}
return $result;
}
else {
return isset( $this->data[ $key ] ) ? $this->data[ $key ] : null;
}
}
/**
* Returns the name of the column in the database table which contains the primary key ID of the row.
*
* @return string The primary key ID of the row.
*/
protected function get_id_column_name() {
if ( ! \is_null( $this->instance_id_column ) ) {
return $this->instance_id_column;
}
return 'id';
}
/**
* Gets the primary key ID of this object.
*
* @param bool $disallow_null Whether to allow null IDs.
*
* @return array|mixed|null
*
* @throws \Exception Primary key ID contains null value(s).
* @throws \Exception Primary key ID missing from row or is null.
*/
public function id( $disallow_null = false ) {
$id = $this->get( $this->get_id_column_name() );
if ( $disallow_null ) {
if ( \is_array( $id ) ) {
foreach ( $id as $id_part ) {
if ( $id_part === null ) {
throw new \Exception( 'Primary key ID contains null value(s)' );
}
}
}
else {
if ( $id === null ) {
throw new \Exception( 'Primary key ID missing from row or is null' );
}
}
}
return $id;
}
/**
* Sets a property to a particular value on this object.
*
* To set multiple properties at once, pass an associative array as the first parameter and leave out the second
* parameter. Flags the properties as 'dirty' so they will be saved to the database when save() is called.
*
* @param string|array $key Key.
* @param string|null $value Value.
*
* @return ORM
*/
public function set( $key, $value = null ) {
return $this->set_orm_property( $key, $value );
}
/**
* Set a property to a particular value on this object as expression.
*
* To set multiple properties at once, pass an associative array as the first parameter and leave out the second
* parameter. Flags the properties as 'dirty' so they will be saved to the database when save() is called.
*
* @param string|array $key Key.
* @param string|null $value Value.
*
* @return ORM
*/
public function set_expr( $key, $value = null ) {
return $this->set_orm_property( $key, $value, true );
}
/**
* Sets a property on the ORM object.
*
* @param string|array $key Key.
* @param string|null $value Value.
* @param bool $expr Expression.
*
* @return ORM
*/
protected function set_orm_property( $key, $value = null, $expr = false ) {
if ( ! \is_array( $key ) ) {
$key = [ $key => $value ];
}
foreach ( $key as $field => $value ) {
$this->data[ $field ] = $value;
$this->dirty_fields[ $field ] = $value;
if ( $expr === false && isset( $this->expr_fields[ $field ] ) ) {
unset( $this->expr_fields[ $field ] );
}
else {
if ( $expr === true ) {
$this->expr_fields[ $field ] = true;
}
}
}
return $this;
}
/**
* Checks whether the given field has been changed since this object was saved.
*
* @param mixed $key Key.
*
* @return bool
*/
public function is_dirty( $key ) {
return \array_key_exists( $key, $this->dirty_fields );
}
/**
* Checks whether the model was the result of a call to create() or not.
*
* @return bool
*/
public function is_new() {
return $this->is_new;
}
/**
* Saves any fields which have been modified on this object to the database.
*
* @return bool True on success.
*
* @throws \Exception Primary key ID contains null value(s).
* @throws \Exception Primary key ID missing from row or is null.
*/
public function save() {
global $wpdb;
// Remove any expression fields as they are already baked into the query.
$values = \array_values( \array_diff_key( $this->dirty_fields, $this->expr_fields ) );
if ( ! $this->is_new ) {
// UPDATE.
// If there are no dirty values, do nothing.
if ( empty( $values ) && empty( $this->expr_fields ) ) {
return true;
}
$query = \implode( ' ', [ $this->build_update(), $this->add_id_column_conditions() ] );
$id = $this->id( true );
if ( \is_array( $id ) ) {
$values = \array_merge( $values, \array_values( $id ) );
}
else {
$values[] = $id;
}
}
else {
// INSERT.
$query = $this->build_insert();
}
$success = self::execute( $query, $values );
// If we've just inserted a new record, set the ID of this object.
if ( $this->is_new ) {
$this->is_new = false;
if ( $this->count_null_id_columns() !== 0 ) {
$column = $this->get_id_column_name();
// If the primary key is compound, assign the last inserted id to the first column.
if ( \is_array( $column ) ) {
$column = \reset( $column );
}
// Explicitly cast to int to make dealing with Id's simpler.
$this->data[ $column ] = (int) $wpdb->insert_id;
}
}
$this->dirty_fields = [];
$this->expr_fields = [];
return $success;
}
/**
* Extracts and gathers all dirty column names from the given model instances.
*
* @param array $models Array of model instances to be inserted.
*
* @return array The distinct set of columns that are dirty in at least one of the models.
*
* @throws \InvalidArgumentException Instance to be inserted is not a new one.
*/
public function get_dirty_column_names( $models ) {
$dirty_column_names = [];
foreach ( $models as $model ) {
if ( ! $model->orm->is_new() ) {
throw new \InvalidArgumentException( 'Instance to be inserted is not a new one' );
}
// Remove any expression fields as they are already baked into the query.
$dirty_fields = \array_diff_key( $model->orm->dirty_fields, $model->orm->expr_fields );
$dirty_column_names = \array_merge( $dirty_column_names, $dirty_fields );
}
$dirty_column_names = \array_keys( $dirty_column_names );
return $dirty_column_names;
}
/**
* Inserts multiple rows in a single query. Expects new rows as it's a strictly insert function, not an update one.
*
* @example From the Indexable_Link_Builder class: $this->seo_links_repository->query()->insert_many( $links );
*
* @param array $models Array of model instances to be inserted.
*
* @return bool True for successful insert, false for failed.
*
* @throws \InvalidArgumentException Invalid instances to be inserted.
* @throws \InvalidArgumentException Instance to be inserted is not a new one.
*/
public function insert_many( $models ) {
// Validate the input first.
if ( ! \is_array( $models ) ) {
throw new \InvalidArgumentException( 'Invalid instances to be inserted' );
}
if ( empty( $models ) ) {
return true;
}
$success = true;
/**
* Filter: 'wpseo_chunk_bulked_insert_queries' - Allow filtering the chunk size of each bulked INSERT query.
*
* @api int The chunk size of the bulked INSERT queries.
*/
$chunk = \apply_filters( 'wpseo_chunk_bulk_insert_queries', 100 );
$chunk = ! \is_int( $chunk ) ? 100 : $chunk;
$chunk = ( $chunk <= 0 ) ? 100 : $chunk;
$chunked_models = \array_chunk( $models, $chunk );
foreach ( $chunked_models as $models_chunk ) {
$values = [];
// First, we'll gather all the dirty fields throughout the models to be inserted.
$dirty_column_names = $this->get_dirty_column_names( $models_chunk );
// Now, we're creating all dirty fields throughout the models and
// setting them to null if they don't exist in each model.
foreach ( $models_chunk as $model ) {
$model_values = [];
foreach ( $dirty_column_names as $dirty_column ) {
// Set the value to null if it hasn't been set already.
if ( ! isset( $model->orm->dirty_fields[ $dirty_column ] ) ) {
$model->orm->dirty_fields[ $dirty_column ] = null;
}
// Only register the value if it is not null.
if ( ! is_null( $model->orm->dirty_fields[ $dirty_column ] ) ) {
$model_values[] = $model->orm->dirty_fields[ $dirty_column ];
}
}
$values = \array_merge( $values, $model_values );
}
// We now have the same set of dirty columns in all our models and also gathered all values.
$query = $this->build_insert_many( $models_chunk, $dirty_column_names );
$success = $success && (bool) self::execute( $query, $values );
}
return $success;
}
/**
* Updates many records in the database.
*
* @return int|bool The number of rows changed if the query was succesful. False otherwise.
*/
public function update_many() {
// Remove any expression fields as they are already baked into the query.
$values = \array_values( \array_diff_key( $this->dirty_fields, $this->expr_fields ) );
// UPDATE.
// If there are no dirty values, do nothing.
if ( empty( $values ) && empty( $this->expr_fields ) ) {
return true;
}
$query = $this->join_if_not_empty( ' ', [ $this->build_update(), $this->build_where() ] );
$success = self::execute( $query, \array_merge( $values, $this->values ) );
$this->dirty_fields = [];
$this->expr_fields = [];
return $success;
}
/**
* Adds a WHERE clause for every column that belongs to the primary key.
*
* @return string The where part of the query.
*/
public function add_id_column_conditions() {
$query = [];
$query[] = 'WHERE';
$keys = \is_array( $this->get_id_column_name() ) ? $this->get_id_column_name() : [ $this->get_id_column_name() ];
$first = true;
foreach ( $keys as $key ) {
if ( $first ) {
$first = false;
}
else {
$query[] = 'AND';
}
$query[] = $this->quote_identifier( $key );
$query[] = '= %s';
}
return \implode( ' ', $query );
}
/**
* Builds an UPDATE query.
*
* @return string The update query.
*/
protected function build_update() {
$query = [];
$query[] = "UPDATE {$this->quote_identifier($this->table_name)} SET";
$field_list = [];
foreach ( $this->dirty_fields as $key => $value ) {
if ( ! \array_key_exists( $key, $this->expr_fields ) ) {
$value = ( $value === null ) ? 'NULL' : '%s';
}
$field_list[] = "{$this->quote_identifier($key)} = {$value}";
}
$query[] = \implode( ', ', $field_list );
return \implode( ' ', $query );
}
/**
* Builds an INSERT query.
*
* @return string The insert query.
*/
protected function build_insert() {
$query = [];
$query[] = 'INSERT INTO';
$query[] = $this->quote_identifier( $this->table_name );
$field_list = \array_map( [ $this, 'quote_identifier' ], \array_keys( $this->dirty_fields ) );
$query[] = '(' . \implode( ', ', $field_list ) . ')';
$query[] = 'VALUES';
$placeholders = $this->create_placeholders( $this->dirty_fields );
$query[] = "({$placeholders})";
return \implode( ' ', $query );
}
/**
* Builds a bulk INSERT query.
*
* @param array $models Array of model instances to be inserted.
* @param array $dirty_column_names Array of dirty fields to be used in INSERT.
*
* @return string The insert query.
*/
protected function build_insert_many( $models, $dirty_column_names ) {
$example_model = $models[0];
$total_placeholders = '';
$query = [];
$query[] = 'INSERT INTO';
$query[] = $this->quote_identifier( $example_model->orm->table_name );
$field_list = \array_map( [ $this, 'quote_identifier' ], $dirty_column_names );
$query[] = '(' . \implode( ', ', $field_list ) . ')';
$query[] = 'VALUES';
// We assign placeholders per model for dirty fields that have values and NULL for dirty fields that don't.
foreach ( $models as $model ) {
$placeholder = [];
foreach ( $dirty_column_names as $dirty_field ) {
$placeholder[] = ( $model->orm->dirty_fields[ $dirty_field ] === null ) ? 'NULL' : '%s';
}
$placeholders = \implode( ', ', $placeholder );
$total_placeholders .= "({$placeholders}),";
}
$query[] = \rtrim( $total_placeholders, ',' );
return \implode( ' ', $query );
}
/**
* Deletes this record from the database.
*
* @return string The delete query.
*
* @throws \Exception Primary key ID contains null value(s).
* @throws \Exception Primary key ID missing from row or is null.
*/
public function delete() {
$query = [ 'DELETE FROM', $this->quote_identifier( $this->table_name ), $this->add_id_column_conditions() ];
return self::execute( \implode( ' ', $query ), \is_array( $this->id( true ) ) ? \array_values( $this->id( true ) ) : [ $this->id( true ) ] );
}
/**
* Deletes many records from the database.
*
* @return bool|int Response of wpdb::query.
*/
public function delete_many() {
// Build and return the full DELETE statement by concatenating
// the results of calling each separate builder method.
$query = $this->join_if_not_empty(
' ',
[
'DELETE FROM',
$this->quote_identifier( $this->table_name ),
$this->build_where(),
]
);
return self::execute( $query, $this->values );
}
/*
* --- ArrayAccess ---
*/
/**
* Checks whether the data has the key.
*
* @param mixed $offset Key.
*
* @return bool Whether the data has the key.
*/
#[ReturnTypeWillChange]
public function offsetExists( $offset ) {
return \array_key_exists( $offset, $this->data );
}
/**
* Retrieves the value of the key.
*
* @param mixed $offset Key.
*
* @return array|mixed|null The value.
*/
#[ReturnTypeWillChange]
public function offsetGet( $offset ) {
return $this->get( $offset );
}
/**
* Sets the value of the key.
*
* @param string|int $offset Key.
* @param mixed $value Value.
*/
#[ReturnTypeWillChange]
public function offsetSet( $offset, $value ) {
if ( \is_null( $offset ) ) {
return;
}
$this->set( $offset, $value );
}
/**
* Removes the given key from the data.
*
* @param mixed $offset Key.
*/
#[ReturnTypeWillChange]
public function offsetUnset( $offset ) {
unset( $this->data[ $offset ] );
unset( $this->dirty_fields[ $offset ] );
}
/*
* --- MAGIC METHODS ---
*/
/**
* Handles magic get via offset.
*
* @param mixed $key Key.
*
* @return array|mixed|null The value in the offset.
*/
public function __get( $key ) {
return $this->offsetGet( $key );
}
/**
* Handles magic set via offset.
*
* @param string|int $key Key.
* @param mixed $value Value.
*/
public function __set( $key, $value ) {
$this->offsetSet( $key, $value );
}
/**
* Handles magic unset via offset.
*
* @param mixed $key Key.
*/
public function __unset( $key ) {
$this->offsetUnset( $key );
}
/**
* Handles magic isset via offset.
*
* @param mixed $key Key.
*
* @return bool Whether the offset has the key.
*/
public function __isset( $key ) {
return $this->offsetExists( $key );
}
}
dependency-injection/container-registry.php 0000644 00000004125 15233603101 0015177 0 ustar 00 <?php
namespace Yoast\WP\Lib\Dependency_Injection;
use YoastSEO_Vendor\Symfony\Component\DependencyInjection\ContainerInterface;
use YoastSEO_Vendor\Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
/**
* Container_Registry class.
*/
class Container_Registry {
/**
* The registered containers.
*
* @var ContainerInterface[]
*/
private static $containers = [];
/**
* Register a container.
*
* @param string $name The name of the container.
* @param ContainerInterface $container The container.
*
* @return void
*/
public static function register( $name, ContainerInterface $container ) {
self::$containers[ $name ] = $container;
}
// phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- PHPCS doesn't take into account exceptions thrown in called methods.
/**
* Get an instance from a specific container.
*
* @param string $name The name of the container.
* @param string $id The ID of the service.
* @param int $invalid_behaviour The behaviour when the service could not be found.
*
* @return object|null The service.
*
* @throws ServiceCircularReferenceException When a circular reference is detected.
* @throws ServiceNotFoundException When the service is not defined.
*/
public static function get( $name, $id, $invalid_behaviour = 1 ) {
if ( ! \array_key_exists( $name, self::$containers ) ) {
if ( $invalid_behaviour === ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE ) {
throw new ServiceNotFoundException( $id );
}
return null;
}
return self::$containers[ $name ]->get( $id, $invalid_behaviour );
}
// phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
/**
* Attempts to find a given service ID in all registered containers.
*
* @param string $id The service ID.
*
* @return string|null The name of the container if the service was found.
*/
public static function find( $id ) {
foreach ( self::$containers as $name => $container ) {
if ( $container->has( $id ) ) {
return $name;
}
}
}
}
model.php 0000644 00000055460 15233603101 0006361 0 ustar 00 <?php
namespace Yoast\WP\Lib;
use JsonSerializable;
use ReturnTypeWillChange;
/**
* Make Model compatible with WordPress.
*
* Model base class. Your model objects should extend
* this class. A minimal subclass would look like:
*
* class Widget extends Model {
* }
*/
class Model implements JsonSerializable {
/**
* Default ID column for all models. Can be overridden by adding
* a public static $id_column property to your model classes.
*
* @var string
*/
const DEFAULT_ID_COLUMN = 'id';
/**
* Default foreign key suffix used by relationship methods.
*
* @var string
*/
const DEFAULT_FOREIGN_KEY_SUFFIX = '_id';
/**
* Set a prefix for model names. This can be a namespace or any other
* abitrary prefix such as the PEAR naming convention.
*
* @example Model::$auto_prefix_models = 'MyProject_MyModels_'; //PEAR
* @example Model::$auto_prefix_models = '\MyProject\MyModels\'; //Namespaces
*
* @var string
*/
public static $auto_prefix_models = '\Yoast\WP\SEO\Models\\';
/**
* Set true to to ignore namespace information when computing table names
* from class names.
*
* @example Model::$short_table_names = true;
* @example Model::$short_table_names = false; // default
*
* @var bool
*/
public static $short_table_names = false;
/**
* The ORM instance used by this model instance to communicate with the database.
*
* @var ORM
*/
public $orm;
/**
* The table name for the implemented Model.
*
* @var string
*/
public static $table;
/**
* Whether or not this model uses timestamps.
*
* @var bool
*/
protected $uses_timestamps = false;
/**
* Which columns contain boolean values.
*
* @var array
*/
protected $boolean_columns = [];
/**
* Which columns contain int values.
*
* @var array
*/
protected $int_columns = [];
/**
* Which columns contain float values.
*
* @var array
*/
protected $float_columns = [];
/**
* Hacks around the Model to provide WordPress prefix to tables.
*
* @param string $class_name Type of Model to load.
* @param bool $yoast_prefix Optional. True to prefix the table name with the Yoast prefix.
*
* @return ORM Wrapper to use.
*/
public static function of_type( $class_name, $yoast_prefix = true ) {
// Prepend namespace to the class name.
$class = static::$auto_prefix_models . $class_name;
// Set the class variable to the custom value based on the WPDB prefix.
$class::$table = static::get_table_name( $class_name, $yoast_prefix );
return static::factory( $class_name, null );
}
/**
* Creates a model without the Yoast prefix.
*
* @param string $class_name Type of Model to load.
*
* @return ORM
*/
public static function of_wp_type( $class_name ) {
return static::of_type( $class_name, false );
}
/**
* Exposes method to get the table name to use.
*
* @param string $table_name Simple table name.
* @param bool $yoast_prefix Optional. True to prefix the table name with the Yoast prefix.
*
* @return string Prepared full table name.
*/
public static function get_table_name( $table_name, $yoast_prefix = true ) {
global $wpdb;
// Allow the use of WordPress internal tables.
if ( $yoast_prefix ) {
$table_name = 'yoast_' . $table_name;
}
return $wpdb->prefix . \strtolower( $table_name );
}
/**
* Sets the table name for the given class name.
*
* @param string $class_name The class to set the table name for.
*
* @return void
*/
protected function set_table_name( $class_name ) {
// Prepend namespace to the class name.
$class = static::$auto_prefix_models . $class_name;
$class::$table = static::get_table_name( $class_name );
}
/**
* Retrieve the value of a static property on a class. If the
* class or the property does not exist, returns the default
* value supplied as the third argument (which defaults to null).
*
* @param string $class_name The target class name.
* @param string $property The property to get the value for.
* @param mixed|null $default_value Default value when property does not exist.
*
* @return mixed|null The value of the property.
*/
protected static function get_static_property( $class_name, $property, $default_value = null ) {
if ( ! \class_exists( $class_name ) || ! \property_exists( $class_name, $property ) ) {
return $default_value;
}
if ( ! isset( $class_name::${$property} ) ) {
return $default_value;
}
return $class_name::${$property};
}
/**
* Static method to get a table name given a class name.
* If the supplied class has a public static property
* named $table, the value of this property will be
* returned.
*
* If not, the class name will be converted using
* the class_name_to_table_name() method.
*
* If Model::$short_table_names == true or public static
* property $table_use_short_name == true then $class_name passed
* to class_name_to_table_name() is stripped of namespace information.
*
* @param string $class_name The class name to get the table name for.
*
* @return string The table name.
*/
protected static function get_table_name_for_class( $class_name ) {
$specified_table_name = static::get_static_property( $class_name, 'table' );
$use_short_class_name = static::use_short_table_name( $class_name );
if ( $use_short_class_name ) {
$exploded_class_name = \explode( '\\', $class_name );
$class_name = \end( $exploded_class_name );
}
if ( $specified_table_name === null ) {
return static::class_name_to_table_name( $class_name );
}
return $specified_table_name;
}
/**
* Should short table names, disregarding class namespaces, be computed?
*
* $class_property overrides $global_option, unless $class_property is null.
*
* @param string $class_name The class name to get short name for.
*
* @return bool True when short table name should be used.
*/
protected static function use_short_table_name( $class_name ) {
$class_property = static::get_static_property( $class_name, 'table_use_short_name' );
if ( $class_property === null ) {
return static::$short_table_names;
}
return $class_property;
}
/**
* Convert a namespace to the standard PEAR underscore format.
*
* Then convert a class name in CapWords to a table name in
* lowercase_with_underscores.
*
* Finally strip doubled up underscores.
*
* For example, CarTyre would be converted to car_tyre. And
* Project\Models\CarTyre would be project_models_car_tyre.
*
* @param string $class_name The class name to get the table name for.
*
* @return string The table name.
*/
protected static function class_name_to_table_name( $class_name ) {
$find = [
'/\\\\/',
'/(?<=[a-z])([A-Z])/',
'/__/',
];
$replacements = [
'_',
'_$1',
'_',
];
$class_name = \ltrim( $class_name, '\\' );
$class_name = \preg_replace( $find, $replacements, $class_name );
return \strtolower( $class_name );
}
/**
* Return the ID column name to use for this class. If it is
* not set on the class, returns null.
*
* @param string $class_name The class name to get the ID column for.
*
* @return string|null The ID column name.
*/
protected static function get_id_column_name( $class_name ) {
return static::get_static_property( $class_name, 'id_column', static::DEFAULT_ID_COLUMN );
}
/**
* Build a foreign key based on a table name. If the first argument
* (the specified foreign key column name) is null, returns the second
* argument (the name of the table) with the default foreign key column
* suffix appended.
*
* @param string $specified_foreign_key_name The keyname to build.
* @param string $table_name The table name to build the key name for.
*
* @return string The built foreign key name.
*/
protected static function build_foreign_key_name( $specified_foreign_key_name, $table_name ) {
if ( $specified_foreign_key_name !== null ) {
return $specified_foreign_key_name;
}
return $table_name . static::DEFAULT_FOREIGN_KEY_SUFFIX;
}
/**
* Factory method used to acquire instances of the given class.
* The class name should be supplied as a string, and the class
* should already have been loaded by PHP (or a suitable autoloader
* should exist). This method actually returns a wrapped ORM object
* which allows a database query to be built. The wrapped ORM object is
* responsible for returning instances of the correct class when
* its find_one or find_many methods are called.
*
* @param string $class_name The target class name.
*
* @return ORM Instance of the ORM wrapper.
*/
public static function factory( $class_name ) {
$class_name = static::$auto_prefix_models . $class_name;
$table_name = static::get_table_name_for_class( $class_name );
$wrapper = ORM::for_table( $table_name );
$wrapper->set_class_name( $class_name );
$wrapper->use_id_column( static::get_id_column_name( $class_name ) );
return $wrapper;
}
/**
* Internal method to construct the queries for both the has_one and
* has_many methods. These two types of association are identical; the
* only difference is whether find_one or find_many is used to complete
* the method chain.
*
* @param string $associated_class_name The associated class name.
* @param string|null $foreign_key_name The foreign key name in the associated table.
* @param string|null $foreign_key_name_in_current_models_table The foreign key in the current models table.
*
* @return ORM Instance of the ORM.
*
* @throws \Exception When ID of current model has a null value.
*/
protected function has_one_or_many( $associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null ) {
$base_table_name = static::get_table_name_for_class( \get_class( $this ) );
$foreign_key_name = static::build_foreign_key_name( $foreign_key_name, $base_table_name );
/*
* Value of foreign_table.{$foreign_key_name} we're looking for. Where foreign_table is the actual
* database table in the associated model.
*/
if ( $foreign_key_name_in_current_models_table === null ) {
// Matches foreign_table.{$foreign_key_name} with the value of "{$this->table}.{$this->id()}".
$where_value = $this->id();
}
else {
// Matches foreign_table.{$foreign_key_name} with "{$this->table}.{$foreign_key_name_in_current_models_table}".
$where_value = $this->{$foreign_key_name_in_current_models_table};
}
return static::factory( $associated_class_name )->where( $foreign_key_name, $where_value );
}
/**
* Helper method to manage one-to-one relations where the foreign
* key is on the associated table.
*
* @param string $associated_class_name The associated class name.
* @param string|null $foreign_key_name The foreign key name in the associated table.
* @param string|null $foreign_key_name_in_current_models_table The foreign key in the current models table.
*
* @return ORM Instance of the ORM.
*
* @throws \Exception When ID of current model has a null value.
*/
protected function has_one( $associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null ) {
return $this->has_one_or_many( $associated_class_name, $foreign_key_name, $foreign_key_name_in_current_models_table );
}
/**
* Helper method to manage one-to-many relations where the foreign
* key is on the associated table.
*
* @param string $associated_class_name The associated class name.
* @param string|null $foreign_key_name The foreign key name in the associated table.
* @param string|null $foreign_key_name_in_current_models_table The foreign key in the current models table.
*
* @return ORM Instance of the ORM.
*
* @throws \Exception When ID has a null value.
*/
protected function has_many( $associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null ) {
$this->set_table_name( $associated_class_name );
return $this->has_one_or_many( $associated_class_name, $foreign_key_name, $foreign_key_name_in_current_models_table );
}
/**
* Helper method to manage one-to-one and one-to-many relations where
* the foreign key is on the base table.
*
* @param string $associated_class_name The associated class name.
* @param string|null $foreign_key_name The foreign key in the current models table.
* @param string|null $foreign_key_name_in_associated_models_table The foreign key in the associated table.
*
* @return $this|null Instance of the foreign model.
*/
protected function belongs_to( $associated_class_name, $foreign_key_name = null, $foreign_key_name_in_associated_models_table = null ) {
$this->set_table_name( $associated_class_name );
$associated_table_name = static::get_table_name_for_class( static::$auto_prefix_models . $associated_class_name );
$foreign_key_name = static::build_foreign_key_name( $foreign_key_name, $associated_table_name );
$associated_object_id = $this->{$foreign_key_name};
$desired_record = null;
if ( $foreign_key_name_in_associated_models_table === null ) {
/*
* Comparison: "{$associated_table_name}.primary_key = {$associated_object_id}".
*
* NOTE: primary_key is a placeholder for the actual primary key column's name in $associated_table_name.
*/
return static::factory( $associated_class_name )->where_id_is( $associated_object_id );
}
// Comparison: "{$associated_table_name}.{$foreign_key_name_in_associated_models_table} = {$associated_object_id}".
return static::factory( $associated_class_name )
->where( $foreign_key_name_in_associated_models_table, $associated_object_id );
}
/**
* Helper method to manage many-to-many relationships via an intermediate model. See
* README for a full explanation of the parameters.
*
* @param string $associated_class_name The associated class name.
* @param string|null $join_class_name The class name to join.
* @param string|null $key_to_base_table The key to the the current models table.
* @param string|null $key_to_associated_table The key to the associated table.
* @param string|null $key_in_base_table The key in the current models table.
* @param string|null $key_in_associated_table The key in the associated table.
*
* @return ORM Instance of the ORM.
*/
protected function has_many_through( $associated_class_name, $join_class_name = null, $key_to_base_table = null, $key_to_associated_table = null, $key_in_base_table = null, $key_in_associated_table = null ) {
$base_class_name = \get_class( $this );
/*
* The class name of the join model, if not supplied, is formed by
* concatenating the names of the base class and the associated class,
* in alphabetical order.
*/
if ( $join_class_name === null ) {
$base_model = \explode( '\\', $base_class_name );
$base_model_name = \end( $base_model );
if ( \strpos( $base_model_name, static::$auto_prefix_models ) === 0 ) {
$base_model_name = \substr( $base_model_name, \strlen( static::$auto_prefix_models ), \strlen( $base_model_name ) );
}
// Paris wasn't checking the name settings for the associated class.
$associated_model = \explode( '\\', $associated_class_name );
$associated_model_name = \end( $associated_model );
if ( \strpos( $associated_model_name, static::$auto_prefix_models ) === 0 ) {
$associated_model_name = \substr( $associated_model_name, \strlen( static::$auto_prefix_models ), \strlen( $associated_model_name ) );
}
$class_names = [ $base_model_name, $associated_model_name ];
\sort( $class_names, \SORT_STRING );
$join_class_name = \implode( '', $class_names );
}
// Get table names for each class.
$base_table_name = static::get_table_name_for_class( $base_class_name );
$associated_table_name = static::get_table_name_for_class( static::$auto_prefix_models . $associated_class_name );
$join_table_name = static::get_table_name_for_class( static::$auto_prefix_models . $join_class_name );
// Get ID column names.
$base_table_id_column = ( $key_in_base_table === null ) ? static::get_id_column_name( $base_class_name ) : $key_in_base_table;
$associated_table_id_column = ( $key_in_associated_table === null ) ? static::get_id_column_name( static::$auto_prefix_models . $associated_class_name ) : $key_in_associated_table;
// Get the column names for each side of the join table.
$key_to_base_table = static::build_foreign_key_name( $key_to_base_table, $base_table_name );
$key_to_associated_table = static::build_foreign_key_name( $key_to_associated_table, $associated_table_name );
/* phpcs:ignore Squiz.PHP.CommentedOutCode.Found -- Reason: This is commented out code.
" SELECT {$associated_table_name}.*
FROM {$associated_table_name} JOIN {$join_table_name}
ON {$associated_table_name}.{$associated_table_id_column} = {$join_table_name}.{$key_to_associated_table}
WHERE {$join_table_name}.{$key_to_base_table} = {$this->$base_table_id_column} ;"
*/
return static::factory( $associated_class_name )
->select( "{$associated_table_name}.*" )
->join(
$join_table_name,
[
"{$associated_table_name}.{$associated_table_id_column}",
'=',
"{$join_table_name}.{$key_to_associated_table}",
]
)
->where( "{$join_table_name}.{$key_to_base_table}", $this->{$base_table_id_column} );
}
/**
* Set the wrapped ORM instance associated with this Model instance.
*
* @param ORM $orm The ORM instance to set.
*
* @return void
*/
public function set_orm( $orm ) {
$this->orm = $orm;
}
/**
* Magic getter method, allows $model->property access to data.
*
* @param string $property The property to get.
*
* @return mixed The value of the property
*/
public function __get( $property ) {
$value = $this->orm->get( $property );
if ( $value !== null && \in_array( $property, $this->boolean_columns, true ) ) {
return (bool) $value;
}
if ( $value !== null && \in_array( $property, $this->int_columns, true ) ) {
return (int) $value;
}
if ( $value !== null && \in_array( $property, $this->float_columns, true ) ) {
return (float) $value;
}
return $value;
}
/**
* Magic setter method, allows $model->property = 'value' access to data.
*
* @param string $property The property to set.
* @param string $value The value to set.
*
* @return void
*/
public function __set( $property, $value ) {
if ( $value !== null && \in_array( $property, $this->boolean_columns, true ) ) {
$value = ( $value ) ? '1' : '0';
}
if ( $value !== null && \in_array( $property, $this->int_columns, true ) ) {
$value = (string) $value;
}
if ( $value !== null && \in_array( $property, $this->float_columns, true ) ) {
$value = (string) $value;
}
$this->orm->set( $property, $value );
}
/**
* Magic unset method, allows unset($model->property)
*
* @param string $property The property to unset.
*
* @return void
*/
public function __unset( $property ) {
$this->orm->__unset( $property );
}
/**
* JSON serializer.
*
* @return array The data of this object.
*/
#[ReturnTypeWillChange]
public function jsonSerialize() {
return $this->orm->as_array();
}
/**
* Strips all nested dependencies from the debug info.
*
* @return array
*/
public function __debugInfo() {
return $this->orm->as_array();
}
/**
* Magic isset method, allows isset($model->property) to work correctly.
*
* @param string $property The property to check.
*
* @return bool True when value is set.
*/
public function __isset( $property ) {
return $this->orm->__isset( $property );
}
/**
* Getter method, allows $model->get('property') access to data
*
* @param string $property The property to get.
*
* @return string The value of a property.
*/
public function get( $property ) {
return $this->orm->get( $property );
}
/**
* Setter method, allows $model->set('property', 'value') access to data.
*
* @param string|array $property The property to set.
* @param string|null $value The value to give.
*
* @return static Current object.
*/
public function set( $property, $value = null ) {
$this->orm->set( $property, $value );
return $this;
}
/**
* Setter method, allows $model->set_expr('property', 'value') access to data.
*
* @param string|array $property The property to set.
* @param string|null $value The value to give.
*
* @return static Current object.
*/
public function set_expr( $property, $value = null ) {
$this->orm->set_expr( $property, $value );
return $this;
}
/**
* Check whether the given property has changed since the object was created or saved.
*
* @param string $property The property to check.
*
* @return bool True when field is changed.
*/
public function is_dirty( $property ) {
return $this->orm->is_dirty( $property );
}
/**
* Check whether the model was the result of a call to create() or not.
*
* @return bool True when is new.
*/
public function is_new() {
return $this->orm->is_new();
}
/**
* Wrapper for Idiorm's as_array method.
*
* @return array The models data as array.
*/
public function as_array() {
$args = \func_get_args();
return \call_user_func_array( [ $this->orm, 'as_array' ], $args );
}
/**
* Save the data associated with this model instance to the database.
*
* @return bool True on success.
*/
public function save() {
if ( $this->uses_timestamps ) {
if ( ! $this->created_at ) {
$this->created_at = \gmdate( 'Y-m-d H:i:s' );
}
$this->updated_at = \gmdate( 'Y-m-d H:i:s' );
}
return $this->orm->save();
}
/**
* Delete the database row associated with this model instance.
*
* @return bool|int Response of wpdb::query.
*/
public function delete() {
return $this->orm->delete();
}
/**
* Get the database ID of this model instance.
*
* @return int The database ID of the models instance.
*
* @throws \Exception When the ID is a null value.
*/
public function id() {
return $this->orm->id();
}
/**
* Hydrate this model instance with an associative array of data.
* WARNING: The keys in the array MUST match with columns in the
* corresponding database table. If any keys are supplied which
* do not match up with columns, the database will throw an error.
*
* @param array $data The data to pass to the ORM.
*
* @return void
*/
public function hydrate( $data ) {
$this->orm->hydrate( $data )->force_all_dirty();
}
/**
* Calls static methods directly on the ORM
*
* @param string $method The method to call.
* @param array $arguments The arguments to use.
*
* @return array Result of the static call.
*/
public static function __callStatic( $method, $arguments ) {
if ( ! \function_exists( 'get_called_class' ) ) {
return [];
}
$model = static::factory( \get_called_class() );
return \call_user_func_array( [ $model, $method ], $arguments );
}
}
packages/League/Container/Exception/ContainerException.php 0000644 00000000415 15233617221 0017720 0 ustar 00 <?php
namespace Automattic\WooCommerce\Vendor\League\Container\Exception;
use Automattic\WooCommerce\Vendor\Psr\Container\ContainerExceptionInterface;
use RuntimeException;
class ContainerException extends RuntimeException implements ContainerExceptionInterface
{
}
packages/League/Container/Exception/NotFoundException.php 0000644 00000000432 15233617221 0017531 0 ustar 00 <?php
namespace Automattic\WooCommerce\Vendor\League\Container\Exception;
use Automattic\WooCommerce\Vendor\Psr\Container\NotFoundExceptionInterface;
use InvalidArgumentException;
class NotFoundException extends InvalidArgumentException implements NotFoundExceptionInterface
{
}
packages/League/Container/ContainerAwareInterface.php 0000644 00000002012 15233617221 0016677 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container;
use Automattic\WooCommerce\Vendor\Psr\Container\ContainerInterface;
interface ContainerAwareInterface
{
/**
* Set a container
*
* @param ContainerInterface $container
*
* @return self
*/
public function setContainer(ContainerInterface $container) : ContainerAwareInterface;
/**
* Get the container
*
* @return ContainerInterface
*/
public function getContainer() : ContainerInterface;
/**
* Set a container. This will be removed in favour of setContainer receiving Container in next major release.
*
* @param Container $container
*
* @return self
*/
public function setLeagueContainer(Container $container) : self;
/**
* Get the container. This will be removed in favour of getContainer returning Container in next major release.
*
* @return Container
*/
public function getLeagueContainer() : Container;
}
packages/League/Container/Container.php 0000644 00000015204 15233617221 0014105 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container;
use Automattic\WooCommerce\Vendor\League\Container\Definition\{DefinitionAggregate, DefinitionInterface, DefinitionAggregateInterface};
use Automattic\WooCommerce\Vendor\League\Container\Exception\{NotFoundException, ContainerException};
use Automattic\WooCommerce\Vendor\League\Container\Inflector\{InflectorAggregate, InflectorInterface, InflectorAggregateInterface};
use Automattic\WooCommerce\Vendor\League\Container\ServiceProvider\{
ServiceProviderAggregate,
ServiceProviderAggregateInterface,
ServiceProviderInterface
};
use Automattic\WooCommerce\Vendor\Psr\Container\ContainerInterface;
class Container implements ContainerInterface
{
/**
* @var boolean
*/
protected $defaultToShared = false;
/**
* @var DefinitionAggregateInterface
*/
protected $definitions;
/**
* @var ServiceProviderAggregateInterface
*/
protected $providers;
/**
* @var InflectorAggregateInterface
*/
protected $inflectors;
/**
* @var ContainerInterface[]
*/
protected $delegates = [];
/**
* Construct.
*
* @param DefinitionAggregateInterface|null $definitions
* @param ServiceProviderAggregateInterface|null $providers
* @param InflectorAggregateInterface|null $inflectors
*/
public function __construct(
DefinitionAggregateInterface $definitions = null,
ServiceProviderAggregateInterface $providers = null,
InflectorAggregateInterface $inflectors = null
) {
$this->definitions = $definitions ?? new DefinitionAggregate;
$this->providers = $providers ?? new ServiceProviderAggregate;
$this->inflectors = $inflectors ?? new InflectorAggregate;
if ($this->definitions instanceof ContainerAwareInterface) {
$this->definitions->setLeagueContainer($this);
}
if ($this->providers instanceof ContainerAwareInterface) {
$this->providers->setLeagueContainer($this);
}
if ($this->inflectors instanceof ContainerAwareInterface) {
$this->inflectors->setLeagueContainer($this);
}
}
/**
* Add an item to the container.
*
* @param string $id
* @param mixed $concrete
* @param boolean $shared
*
* @return DefinitionInterface
*/
public function add(string $id, $concrete = null, bool $shared = null) : DefinitionInterface
{
$concrete = $concrete ?? $id;
$shared = $shared ?? $this->defaultToShared;
return $this->definitions->add($id, $concrete, $shared);
}
/**
* Proxy to add with shared as true.
*
* @param string $id
* @param mixed $concrete
*
* @return DefinitionInterface
*/
public function share(string $id, $concrete = null) : DefinitionInterface
{
return $this->add($id, $concrete, true);
}
/**
* Whether the container should default to defining shared definitions.
*
* @param boolean $shared
*
* @return self
*/
public function defaultToShared(bool $shared = true) : ContainerInterface
{
$this->defaultToShared = $shared;
return $this;
}
/**
* Get a definition to extend.
*
* @param string $id [description]
*
* @return DefinitionInterface
*/
public function extend(string $id) : DefinitionInterface
{
if ($this->providers->provides($id)) {
$this->providers->register($id);
}
if ($this->definitions->has($id)) {
return $this->definitions->getDefinition($id);
}
throw new NotFoundException(
sprintf('Unable to extend alias (%s) as it is not being managed as a definition', $id)
);
}
/**
* Add a service provider.
*
* @param ServiceProviderInterface|string $provider
*
* @return self
*/
public function addServiceProvider($provider) : self
{
$this->providers->add($provider);
return $this;
}
/**
* {@inheritdoc}
*/
public function get($id, bool $new = false)
{
if ($this->definitions->has($id)) {
$resolved = $this->definitions->resolve($id, $new);
return $this->inflectors->inflect($resolved);
}
if ($this->definitions->hasTag($id)) {
$arrayOf = $this->definitions->resolveTagged($id, $new);
array_walk($arrayOf, function (&$resolved) {
$resolved = $this->inflectors->inflect($resolved);
});
return $arrayOf;
}
if ($this->providers->provides($id)) {
$this->providers->register($id);
if (!$this->definitions->has($id) && !$this->definitions->hasTag($id)) {
throw new ContainerException(sprintf('Service provider lied about providing (%s) service', $id));
}
return $this->get($id, $new);
}
foreach ($this->delegates as $delegate) {
if ($delegate->has($id)) {
$resolved = $delegate->get($id);
return $this->inflectors->inflect($resolved);
}
}
throw new NotFoundException(sprintf('Alias (%s) is not being managed by the container or delegates', $id));
}
/**
* {@inheritdoc}
*/
public function has($id) : bool
{
if ($this->definitions->has($id)) {
return true;
}
if ($this->definitions->hasTag($id)) {
return true;
}
if ($this->providers->provides($id)) {
return true;
}
foreach ($this->delegates as $delegate) {
if ($delegate->has($id)) {
return true;
}
}
return false;
}
/**
* Allows for manipulation of specific types on resolution.
*
* @param string $type
* @param callable|null $callback
*
* @return InflectorInterface
*/
public function inflector(string $type, callable $callback = null) : InflectorInterface
{
return $this->inflectors->add($type, $callback);
}
/**
* Delegate a backup container to be checked for services if it
* cannot be resolved via this container.
*
* @param ContainerInterface $container
*
* @return self
*/
public function delegate(ContainerInterface $container) : self
{
$this->delegates[] = $container;
if ($container instanceof ContainerAwareInterface) {
$container->setLeagueContainer($this);
}
return $this;
}
}
packages/League/Container/Argument/ClassNameInterface.php 0000644 00000000375 15233617221 0017437 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Argument;
interface ClassNameInterface
{
/**
* Return the class name.
*
* @return string
*/
public function getClassName() : string;
}
packages/League/Container/Argument/RawArgumentInterface.php 0000644 00000000400 15233617221 0020012 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Argument;
interface RawArgumentInterface
{
/**
* Return the value of the raw argument.
*
* @return mixed
*/
public function getValue();
}
packages/League/Container/Argument/ClassNameWithOptionalValue.php 0000644 00000001326 15233617221 0021152 0 ustar 00 <?php
namespace Automattic\WooCommerce\Vendor\League\Container\Argument;
class ClassNameWithOptionalValue implements ClassNameInterface
{
/**
* @var string
*/
private $className;
/**
* @var mixed
*/
private $optionalValue;
/**
* @param string $className
* @param mixed $optionalValue
*/
public function __construct(string $className, $optionalValue)
{
$this->className = $className;
$this->optionalValue = $optionalValue;
}
/**
* @inheritDoc
*/
public function getClassName(): string
{
return $this->className;
}
public function getOptionalValue()
{
return $this->optionalValue;
}
}
packages/League/Container/Argument/RawArgument.php 0000644 00000000730 15233617221 0016177 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Argument;
class RawArgument implements RawArgumentInterface
{
/**
* @var mixed
*/
protected $value;
/**
* Construct.
*
* @param mixed $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* {@inheritdoc}
*/
public function getValue()
{
return $this->value;
}
}
packages/League/Container/Argument/ArgumentResolverInterface.php 0000644 00000001453 15233617221 0021073 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Argument;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareInterface;
use ReflectionFunctionAbstract;
interface ArgumentResolverInterface extends ContainerAwareInterface
{
/**
* Resolve an array of arguments to their concrete implementations.
*
* @param array $arguments
*
* @return array
*/
public function resolveArguments(array $arguments) : array;
/**
* Resolves the correct arguments to be passed to a method.
*
* @param ReflectionFunctionAbstract $method
* @param array $args
*
* @return array
*/
public function reflectArguments(ReflectionFunctionAbstract $method, array $args = []) : array;
}
packages/League/Container/Argument/ArgumentResolverTrait.php 0000644 00000007206 15233617221 0020260 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Argument;
use Automattic\WooCommerce\Vendor\League\Container\Container;
use Automattic\WooCommerce\Vendor\League\Container\Exception\{ContainerException, NotFoundException};
use Automattic\WooCommerce\Vendor\League\Container\ReflectionContainer;
use Automattic\WooCommerce\Vendor\Psr\Container\ContainerInterface;
use ReflectionFunctionAbstract;
use ReflectionParameter;
trait ArgumentResolverTrait
{
/**
* {@inheritdoc}
*/
public function resolveArguments(array $arguments) : array
{
return array_map(function ($argument) {
$justStringValue = false;
if ($argument instanceof RawArgumentInterface) {
return $argument->getValue();
} elseif ($argument instanceof ClassNameInterface) {
$id = $argument->getClassName();
} elseif (!is_string($argument)) {
return $argument;
} else {
$justStringValue = true;
$id = $argument;
}
$container = null;
try {
$container = $this->getLeagueContainer();
} catch (ContainerException $e) {
if ($this instanceof ReflectionContainer) {
$container = $this;
}
}
if ($container !== null) {
try {
return $container->get($id);
} catch (NotFoundException $exception) {
if ($argument instanceof ClassNameWithOptionalValue) {
return $argument->getOptionalValue();
}
if ($justStringValue) {
return $id;
}
throw $exception;
}
}
if ($argument instanceof ClassNameWithOptionalValue) {
return $argument->getOptionalValue();
}
// Just a string value.
return $id;
}, $arguments);
}
/**
* {@inheritdoc}
*/
public function reflectArguments(ReflectionFunctionAbstract $method, array $args = []) : array
{
$arguments = array_map(function (ReflectionParameter $param) use ($method, $args) {
$name = $param->getName();
$type = $param->getType();
if (array_key_exists($name, $args)) {
return new RawArgument($args[$name]);
}
if ($type) {
if (PHP_VERSION_ID >= 70100) {
$typeName = $type->getName();
} else {
$typeName = (string) $type;
}
$typeName = ltrim($typeName, '?');
if ($param->isDefaultValueAvailable()) {
return new ClassNameWithOptionalValue($typeName, $param->getDefaultValue());
}
return new ClassName($typeName);
}
if ($param->isDefaultValueAvailable()) {
return new RawArgument($param->getDefaultValue());
}
throw new NotFoundException(sprintf(
'Unable to resolve a value for parameter (%s) in the function/method (%s)',
$name,
$method->getName()
));
}, $method->getParameters());
return $this->resolveArguments($arguments);
}
/**
* @return ContainerInterface
*/
abstract public function getContainer() : ContainerInterface;
/**
* @return Container
*/
abstract public function getLeagueContainer() : Container;
}
packages/League/Container/Argument/ClassName.php 0000644 00000000752 15233617221 0015615 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Argument;
class ClassName implements ClassNameInterface
{
/**
* @var string
*/
protected $value;
/**
* Construct.
*
* @param string $value
*/
public function __construct(string $value)
{
$this->value = $value;
}
/**
* {@inheritdoc}
*/
public function getClassName() : string
{
return $this->value;
}
}
packages/League/Container/ContainerAwareTrait.php 0000644 00000003262 15233617221 0016072 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container;
use Automattic\WooCommerce\Vendor\League\Container\Exception\ContainerException;
use Automattic\WooCommerce\Vendor\Psr\Container\ContainerInterface;
trait ContainerAwareTrait
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var Container
*/
protected $leagueContainer;
/**
* Set a container.
*
* @param ContainerInterface $container
*
* @return ContainerAwareInterface
*/
public function setContainer(ContainerInterface $container) : ContainerAwareInterface
{
$this->container = $container;
return $this;
}
/**
* Get the container.
*
* @return ContainerInterface
*/
public function getContainer() : ContainerInterface
{
if ($this->container instanceof ContainerInterface) {
return $this->container;
}
throw new ContainerException('No container implementation has been set.');
}
/**
* Set a container.
*
* @param Container $container
*
* @return self
*/
public function setLeagueContainer(Container $container) : ContainerAwareInterface
{
$this->container = $container;
$this->leagueContainer = $container;
return $this;
}
/**
* Get the container.
*
* @return Container
*/
public function getLeagueContainer() : Container
{
if ($this->leagueContainer instanceof Container) {
return $this->leagueContainer;
}
throw new ContainerException('No container implementation has been set.');
}
}
packages/League/Container/ServiceProvider/ServiceProviderAggregateInterface.php 0000644 00000001663 15233617221 0024045 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\ServiceProvider;
use IteratorAggregate;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareInterface;
interface ServiceProviderAggregateInterface extends ContainerAwareInterface, IteratorAggregate
{
/**
* Add a service provider to the aggregate.
*
* @param string|ServiceProviderInterface $provider
*
* @return self
*/
public function add($provider) : ServiceProviderAggregateInterface;
/**
* Determines whether a service is provided by the aggregate.
*
* @param string $service
*
* @return boolean
*/
public function provides(string $service) : bool;
/**
* Invokes the register method of a provider that provides a specific service.
*
* @param string $service
*
* @return void
*/
public function register(string $service);
}
packages/League/Container/ServiceProvider/ServiceProviderAggregate.php 0000644 00000005433 15233617221 0022223 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\ServiceProvider;
use Generator;
use Automattic\WooCommerce\Vendor\League\Container\{ContainerAwareInterface, ContainerAwareTrait};
use Automattic\WooCommerce\Vendor\League\Container\Exception\ContainerException;
class ServiceProviderAggregate implements ServiceProviderAggregateInterface
{
use ContainerAwareTrait;
/**
* @var ServiceProviderInterface[]
*/
protected $providers = [];
/**
* @var array
*/
protected $registered = [];
/**
* {@inheritdoc}
*/
public function add($provider) : ServiceProviderAggregateInterface
{
if (is_string($provider) && $this->getContainer()->has($provider)) {
$provider = $this->getContainer()->get($provider);
} elseif (is_string($provider) && class_exists($provider)) {
$provider = new $provider;
}
if (in_array($provider, $this->providers, true)) {
return $this;
}
if ($provider instanceof ContainerAwareInterface) {
$provider->setLeagueContainer($this->getLeagueContainer());
}
if ($provider instanceof BootableServiceProviderInterface) {
$provider->boot();
}
if ($provider instanceof ServiceProviderInterface) {
$this->providers[] = $provider;
return $this;
}
throw new ContainerException(
'A service provider must be a fully qualified class name or instance ' .
'of (\Automattic\WooCommerce\Vendor\League\Container\ServiceProvider\ServiceProviderInterface)'
);
}
/**
* {@inheritdoc}
*/
public function provides(string $service) : bool
{
foreach ($this->getIterator() as $provider) {
if ($provider->provides($service)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function getIterator() : Generator
{
$count = count($this->providers);
for ($i = 0; $i < $count; $i++) {
yield $this->providers[$i];
}
}
/**
* {@inheritdoc}
*/
public function register(string $service)
{
if (false === $this->provides($service)) {
throw new ContainerException(
sprintf('(%s) is not provided by a service provider', $service)
);
}
foreach ($this->getIterator() as $provider) {
if (in_array($provider->getIdentifier(), $this->registered, true)) {
continue;
}
if ($provider->provides($service)) {
$this->registered[] = $provider->getIdentifier();
$provider->register();
}
}
}
}
packages/League/Container/ServiceProvider/BootableServiceProviderInterface.php 0000644 00000000643 15233617221 0023703 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\ServiceProvider;
interface BootableServiceProviderInterface extends ServiceProviderInterface
{
/**
* Method will be invoked on registration of a service provider implementing
* this interface. Provides ability for eager loading of Service Providers.
*
* @return void
*/
public function boot();
}
packages/League/Container/ServiceProvider/ServiceProviderInterface.php 0000644 00000002526 15233617221 0022235 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\ServiceProvider;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareInterface;
interface ServiceProviderInterface extends ContainerAwareInterface
{
/**
* Returns a boolean if checking whether this provider provides a specific
* service or returns an array of provided services if no argument passed.
*
* @param string $service
*
* @return boolean
*/
public function provides(string $service) : bool;
/**
* Use the register method to register items with the container via the
* protected $this->leagueContainer property or the `getLeagueContainer` method
* from the ContainerAwareTrait.
*
* @return void
*/
public function register();
/**
* Set a custom id for the service provider. This enables
* registering the same service provider multiple times.
*
* @param string $id
*
* @return self
*/
public function setIdentifier(string $id) : ServiceProviderInterface;
/**
* The id of the service provider uniquely identifies it, so
* that we can quickly determine if it has already been registered.
* Defaults to get_class($provider).
*
* @return string
*/
public function getIdentifier() : string;
}
packages/League/Container/ServiceProvider/AbstractServiceProvider.php 0000644 00000001605 15233617221 0022075 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\ServiceProvider;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareTrait;
abstract class AbstractServiceProvider implements ServiceProviderInterface
{
use ContainerAwareTrait;
/**
* @var array
*/
protected $provides = [];
/**
* @var string
*/
protected $identifier;
/**
* {@inheritdoc}
*/
public function provides(string $alias) : bool
{
return in_array($alias, $this->provides, true);
}
/**
* {@inheritdoc}
*/
public function setIdentifier(string $id) : ServiceProviderInterface
{
$this->identifier = $id;
return $this;
}
/**
* {@inheritdoc}
*/
public function getIdentifier() : string
{
return $this->identifier ?? get_class($this);
}
}
packages/League/Container/Inflector/InflectorAggregateInterface.php 0000644 00000001261 15233617221 0021463 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Inflector;
use IteratorAggregate;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareInterface;
interface InflectorAggregateInterface extends ContainerAwareInterface, IteratorAggregate
{
/**
* Add an inflector to the aggregate.
*
* @param string $type
* @param callable $callback
*
* @return Inflector
*/
public function add(string $type, callable $callback = null) : Inflector;
/**
* Applies all inflectors to an object.
*
* @param object $object
* @return object
*/
public function inflect($object);
}
packages/League/Container/Inflector/InflectorAggregate.php 0000644 00000002373 15233617221 0017647 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Inflector;
use Generator;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareTrait;
class InflectorAggregate implements InflectorAggregateInterface
{
use ContainerAwareTrait;
/**
* @var Inflector[]
*/
protected $inflectors = [];
/**
* {@inheritdoc}
*/
public function add(string $type, callable $callback = null) : Inflector
{
$inflector = new Inflector($type, $callback);
$this->inflectors[] = $inflector;
return $inflector;
}
/**
* {@inheritdoc}
*/
public function getIterator() : Generator
{
$count = count($this->inflectors);
for ($i = 0; $i < $count; $i++) {
yield $this->inflectors[$i];
}
}
/**
* {@inheritdoc}
*/
public function inflect($object)
{
foreach ($this->getIterator() as $inflector) {
$type = $inflector->getType();
if (! $object instanceof $type) {
continue;
}
$inflector->setLeagueContainer($this->getLeagueContainer());
$inflector->inflect($object);
}
return $object;
}
}
packages/League/Container/Inflector/Inflector.php 0000644 00000005426 15233617221 0016042 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Inflector;
use Automattic\WooCommerce\Vendor\League\Container\Argument\ArgumentResolverInterface;
use Automattic\WooCommerce\Vendor\League\Container\Argument\ArgumentResolverTrait;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareTrait;
class Inflector implements ArgumentResolverInterface, InflectorInterface
{
use ArgumentResolverTrait;
use ContainerAwareTrait;
/**
* @var string
*/
protected $type;
/**
* @var callable|null
*/
protected $callback;
/**
* @var array
*/
protected $methods = [];
/**
* @var array
*/
protected $properties = [];
/**
* Construct.
*
* @param string $type
* @param callable|null $callback
*/
public function __construct(string $type, callable $callback = null)
{
$this->type = $type;
$this->callback = $callback;
}
/**
* {@inheritdoc}
*/
public function getType() : string
{
return $this->type;
}
/**
* {@inheritdoc}
*/
public function invokeMethod(string $name, array $args) : InflectorInterface
{
$this->methods[$name] = $args;
return $this;
}
/**
* {@inheritdoc}
*/
public function invokeMethods(array $methods) : InflectorInterface
{
foreach ($methods as $name => $args) {
$this->invokeMethod($name, $args);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function setProperty(string $property, $value) : InflectorInterface
{
$this->properties[$property] = $this->resolveArguments([$value])[0];
return $this;
}
/**
* {@inheritdoc}
*/
public function setProperties(array $properties) : InflectorInterface
{
foreach ($properties as $property => $value) {
$this->setProperty($property, $value);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function inflect($object)
{
$properties = $this->resolveArguments(array_values($this->properties));
$properties = array_combine(array_keys($this->properties), $properties);
// array_combine() can technically return false
foreach ($properties ?: [] as $property => $value) {
$object->{$property} = $value;
}
foreach ($this->methods as $method => $args) {
$args = $this->resolveArguments($args);
/** @var callable $callable */
$callable = [$object, $method];
call_user_func_array($callable, $args);
}
if ($this->callback !== null) {
call_user_func($this->callback, $object);
}
}
}
packages/League/Container/Inflector/InflectorInterface.php 0000644 00000002475 15233617221 0017664 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Inflector;
interface InflectorInterface
{
/**
* Get the type.
*
* @return string
*/
public function getType() : string;
/**
* Defines a method to be invoked on the subject object.
*
* @param string $name
* @param array $args
*
* @return self
*/
public function invokeMethod(string $name, array $args) : InflectorInterface;
/**
* Defines multiple methods to be invoked on the subject object.
*
* @param array $methods
*
* @return self
*/
public function invokeMethods(array $methods) : InflectorInterface;
/**
* Defines a property to be set on the subject object.
*
* @param string $property
* @param mixed $value
*
* @return self
*/
public function setProperty(string $property, $value) : InflectorInterface;
/**
* Defines multiple properties to be set on the subject object.
*
* @param array $properties
*
* @return self
*/
public function setProperties(array $properties) : InflectorInterface;
/**
* Apply inflections to an object.
*
* @param object $object
*
* @return void
*/
public function inflect($object);
}
packages/League/Container/Definition/DefinitionAggregate.php 0000644 00000005645 15233617221 0020162 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Definition;
use Generator;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareTrait;
use Automattic\WooCommerce\Vendor\League\Container\Exception\NotFoundException;
class DefinitionAggregate implements DefinitionAggregateInterface
{
use ContainerAwareTrait;
/**
* @var DefinitionInterface[]
*/
protected $definitions = [];
/**
* Construct.
*
* @param DefinitionInterface[] $definitions
*/
public function __construct(array $definitions = [])
{
$this->definitions = array_filter($definitions, function ($definition) {
return ($definition instanceof DefinitionInterface);
});
}
/**
* {@inheritdoc}
*/
public function add(string $id, $definition, bool $shared = false) : DefinitionInterface
{
if (!$definition instanceof DefinitionInterface) {
$definition = new Definition($id, $definition);
}
$this->definitions[] = $definition
->setAlias($id)
->setShared($shared)
;
return $definition;
}
/**
* {@inheritdoc}
*/
public function has(string $id) : bool
{
foreach ($this->getIterator() as $definition) {
if ($id === $definition->getAlias()) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function hasTag(string $tag) : bool
{
foreach ($this->getIterator() as $definition) {
if ($definition->hasTag($tag)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function getDefinition(string $id) : DefinitionInterface
{
foreach ($this->getIterator() as $definition) {
if ($id === $definition->getAlias()) {
return $definition->setLeagueContainer($this->getLeagueContainer());
}
}
throw new NotFoundException(sprintf('Alias (%s) is not being handled as a definition.', $id));
}
/**
* {@inheritdoc}
*/
public function resolve(string $id, bool $new = false)
{
return $this->getDefinition($id)->resolve($new);
}
/**
* {@inheritdoc}
*/
public function resolveTagged(string $tag, bool $new = false) : array
{
$arrayOf = [];
foreach ($this->getIterator() as $definition) {
if ($definition->hasTag($tag)) {
$arrayOf[] = $definition->setLeagueContainer($this->getLeagueContainer())->resolve($new);
}
}
return $arrayOf;
}
/**
* {@inheritdoc}
*/
public function getIterator() : Generator
{
$count = count($this->definitions);
for ($i = 0; $i < $count; $i++) {
yield $this->definitions[$i];
}
}
}
packages/League/Container/Definition/DefinitionAggregateInterface.php 0000644 00000003101 15233617221 0021764 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Definition;
use IteratorAggregate;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareInterface;
interface DefinitionAggregateInterface extends ContainerAwareInterface, IteratorAggregate
{
/**
* Add a definition to the aggregate.
*
* @param string $id
* @param mixed $definition
* @param boolean $shared
*
* @return DefinitionInterface
*/
public function add(string $id, $definition, bool $shared = false) : DefinitionInterface;
/**
* Checks whether alias exists as definition.
*
* @param string $id
*
* @return boolean
*/
public function has(string $id) : bool;
/**
* Checks whether tag exists as definition.
*
* @param string $tag
*
* @return boolean
*/
public function hasTag(string $tag) : bool;
/**
* Get the definition to be extended.
*
* @param string $id
*
* @return DefinitionInterface
*/
public function getDefinition(string $id) : DefinitionInterface;
/**
* Resolve and build a concrete value from an id/alias.
*
* @param string $id
* @param boolean $new
*
* @return mixed
*/
public function resolve(string $id, bool $new = false);
/**
* Resolve and build an array of concrete values from a tag.
*
* @param string $tag
* @param boolean $new
*
* @return mixed
*/
public function resolveTagged(string $tag, bool $new = false);
}
packages/League/Container/Definition/DefinitionInterface.php 0000644 00000004765 15233617221 0020176 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Definition;
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareInterface;
interface DefinitionInterface extends ContainerAwareInterface
{
/**
* Add a tag to the definition.
*
* @param string $tag
*
* @return self
*/
public function addTag(string $tag) : DefinitionInterface;
/**
* Does the definition have a tag?
*
* @param string $tag
*
* @return boolean
*/
public function hasTag(string $tag) : bool;
/**
* Set the alias of the definition.
*
* @param string $id
*
* @return DefinitionInterface
*/
public function setAlias(string $id) : DefinitionInterface;
/**
* Get the alias of the definition.
*
* @return string
*/
public function getAlias() : string;
/**
* Set whether this is a shared definition.
*
* @param boolean $shared
*
* @return self
*/
public function setShared(bool $shared) : DefinitionInterface;
/**
* Is this a shared definition?
*
* @return boolean
*/
public function isShared() : bool;
/**
* Get the concrete of the definition.
*
* @return mixed
*/
public function getConcrete();
/**
* Set the concrete of the definition.
*
* @param mixed $concrete
*
* @return DefinitionInterface
*/
public function setConcrete($concrete) : DefinitionInterface;
/**
* Add an argument to be injected.
*
* @param mixed $arg
*
* @return self
*/
public function addArgument($arg) : DefinitionInterface;
/**
* Add multiple arguments to be injected.
*
* @param array $args
*
* @return self
*/
public function addArguments(array $args) : DefinitionInterface;
/**
* Add a method to be invoked
*
* @param string $method
* @param array $args
*
* @return self
*/
public function addMethodCall(string $method, array $args = []) : DefinitionInterface;
/**
* Add multiple methods to be invoked
*
* @param array $methods
*
* @return self
*/
public function addMethodCalls(array $methods = []) : DefinitionInterface;
/**
* Handle instantiation and manipulation of value and return.
*
* @param boolean $new
*
* @return mixed
*/
public function resolve(bool $new = false);
}
packages/League/Container/Definition/Definition.php 0000644 00000013032 15233617221 0016340 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container\Definition;
use Automattic\WooCommerce\Vendor\League\Container\Argument\{
ArgumentResolverInterface, ArgumentResolverTrait, ClassNameInterface, RawArgumentInterface
};
use Automattic\WooCommerce\Vendor\League\Container\ContainerAwareTrait;
use ReflectionClass;
use ReflectionException;
class Definition implements ArgumentResolverInterface, DefinitionInterface
{
use ArgumentResolverTrait;
use ContainerAwareTrait;
/**
* @var string
*/
protected $alias;
/**
* @var mixed
*/
protected $concrete;
/**
* @var boolean
*/
protected $shared = false;
/**
* @var array
*/
protected $tags = [];
/**
* @var array
*/
protected $arguments = [];
/**
* @var array
*/
protected $methods = [];
/**
* @var mixed
*/
protected $resolved;
/**
* Constructor.
*
* @param string $id
* @param mixed $concrete
*/
public function __construct(string $id, $concrete = null)
{
$concrete = $concrete ?? $id;
$this->alias = $id;
$this->concrete = $concrete;
}
/**
* {@inheritdoc}
*/
public function addTag(string $tag) : DefinitionInterface
{
$this->tags[$tag] = true;
return $this;
}
/**
* {@inheritdoc}
*/
public function hasTag(string $tag) : bool
{
return isset($this->tags[$tag]);
}
/**
* {@inheritdoc}
*/
public function setAlias(string $id) : DefinitionInterface
{
$this->alias = $id;
return $this;
}
/**
* {@inheritdoc}
*/
public function getAlias() : string
{
return $this->alias;
}
/**
* {@inheritdoc}
*/
public function setShared(bool $shared = true) : DefinitionInterface
{
$this->shared = $shared;
return $this;
}
/**
* {@inheritdoc}
*/
public function isShared() : bool
{
return $this->shared;
}
/**
* {@inheritdoc}
*/
public function getConcrete()
{
return $this->concrete;
}
/**
* {@inheritdoc}
*/
public function setConcrete($concrete) : DefinitionInterface
{
$this->concrete = $concrete;
$this->resolved = null;
return $this;
}
/**
* {@inheritdoc}
*/
public function addArgument($arg) : DefinitionInterface
{
$this->arguments[] = $arg;
return $this;
}
/**
* {@inheritdoc}
*/
public function addArguments(array $args) : DefinitionInterface
{
foreach ($args as $arg) {
$this->addArgument($arg);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function addMethodCall(string $method, array $args = []) : DefinitionInterface
{
$this->methods[] = [
'method' => $method,
'arguments' => $args
];
return $this;
}
/**
* {@inheritdoc}
*/
public function addMethodCalls(array $methods = []) : DefinitionInterface
{
foreach ($methods as $method => $args) {
$this->addMethodCall($method, $args);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function resolve(bool $new = false)
{
$concrete = $this->concrete;
if ($this->isShared() && $this->resolved !== null && $new === false) {
return $this->resolved;
}
if (is_callable($concrete)) {
$concrete = $this->resolveCallable($concrete);
}
if ($concrete instanceof RawArgumentInterface) {
$this->resolved = $concrete->getValue();
return $concrete->getValue();
}
if ($concrete instanceof ClassNameInterface) {
$concrete = $concrete->getClassName();
}
if (is_string($concrete) && class_exists($concrete)) {
$concrete = $this->resolveClass($concrete);
}
if (is_object($concrete)) {
$concrete = $this->invokeMethods($concrete);
}
if (is_string($concrete) && $this->getContainer()->has($concrete)) {
$concrete = $this->getContainer()->get($concrete);
}
$this->resolved = $concrete;
return $concrete;
}
/**
* Resolve a callable.
*
* @param callable $concrete
*
* @return mixed
*/
protected function resolveCallable(callable $concrete)
{
$resolved = $this->resolveArguments($this->arguments);
return call_user_func_array($concrete, $resolved);
}
/**
* Resolve a class.
*
* @param string $concrete
*
* @return object
*
* @throws ReflectionException
*/
protected function resolveClass(string $concrete)
{
$resolved = $this->resolveArguments($this->arguments);
$reflection = new ReflectionClass($concrete);
return $reflection->newInstanceArgs($resolved);
}
/**
* Invoke methods on resolved instance.
*
* @param object $instance
*
* @return object
*/
protected function invokeMethods($instance)
{
foreach ($this->methods as $method) {
$args = $this->resolveArguments($method['arguments']);
/** @var callable $callable */
$callable = [$instance, $method['method']];
call_user_func_array($callable, $args);
}
return $instance;
}
}
packages/League/Container/ReflectionContainer.php 0000644 00000006454 15233617221 0016127 0 ustar 00 <?php declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\League\Container;
use Automattic\WooCommerce\Vendor\League\Container\Argument\{ArgumentResolverInterface, ArgumentResolverTrait};
use Automattic\WooCommerce\Vendor\League\Container\Exception\NotFoundException;
use Automattic\WooCommerce\Vendor\Psr\Container\ContainerInterface;
use ReflectionClass;
use ReflectionException;
use ReflectionFunction;
use ReflectionMethod;
class ReflectionContainer implements ArgumentResolverInterface, ContainerInterface
{
use ArgumentResolverTrait;
use ContainerAwareTrait;
/**
* @var boolean
*/
protected $cacheResolutions = false;
/**
* Cache of resolutions.
*
* @var array
*/
protected $cache = [];
/**
* {@inheritdoc}
*
* @throws ReflectionException
*/
public function get($id, array $args = [])
{
if ($this->cacheResolutions === true && array_key_exists($id, $this->cache)) {
return $this->cache[$id];
}
if (! $this->has($id)) {
throw new NotFoundException(
sprintf('Alias (%s) is not an existing class and therefore cannot be resolved', $id)
);
}
$reflector = new ReflectionClass($id);
$construct = $reflector->getConstructor();
$resolution = $construct === null
? new $id
: $resolution = $reflector->newInstanceArgs($this->reflectArguments($construct, $args))
;
if ($this->cacheResolutions === true) {
$this->cache[$id] = $resolution;
}
return $resolution;
}
/**
* {@inheritdoc}
*/
public function has($id) : bool
{
return class_exists($id);
}
/**
* Invoke a callable via the container.
*
* @param callable $callable
* @param array $args
*
* @return mixed
*
* @throws ReflectionException
*/
public function call(callable $callable, array $args = [])
{
if (is_string($callable) && strpos($callable, '::') !== false) {
$callable = explode('::', $callable);
}
if (is_array($callable)) {
if (is_string($callable[0])) {
$callable[0] = $this->getContainer()->get($callable[0]);
}
$reflection = new ReflectionMethod($callable[0], $callable[1]);
if ($reflection->isStatic()) {
$callable[0] = null;
}
return $reflection->invokeArgs($callable[0], $this->reflectArguments($reflection, $args));
}
if (is_object($callable)) {
$reflection = new ReflectionMethod($callable, '__invoke');
return $reflection->invokeArgs($callable, $this->reflectArguments($reflection, $args));
}
$reflection = new ReflectionFunction(\Closure::fromCallable($callable));
return $reflection->invokeArgs($this->reflectArguments($reflection, $args));
}
/**
* Whether the container should default to caching resolutions and returning
* the cache on following calls.
*
* @param boolean $option
*
* @return self
*/
public function cacheResolutions(bool $option = true) : ContainerInterface
{
$this->cacheResolutions = $option;
return $this;
}
}
packages/Psr/Container/ContainerExceptionInterface.php 0000644 00000000264 15233617221 0017147 0 ustar 00 <?php
namespace Automattic\WooCommerce\Vendor\Psr\Container;
/**
* Base interface representing a generic exception in a container.
*/
interface ContainerExceptionInterface
{
}
packages/Psr/Container/ContainerInterface.php 0000644 00000002056 15233617221 0015271 0 ustar 00 <?php
declare(strict_types=1);
namespace Automattic\WooCommerce\Vendor\Psr\Container;
/**
* Describes the interface of a container that exposes methods to read its entries.
*/
interface ContainerInterface
{
/**
* Finds an entry of the container by its identifier and returns it.
*
* @param string $id Identifier of the entry to look for.
*
* @throws NotFoundExceptionInterface No entry was found for **this** identifier.
* @throws ContainerExceptionInterface Error while retrieving the entry.
*
* @return mixed Entry.
*/
public function get(string $id);
/**
* Returns true if the container can return an entry for the given identifier.
* Returns false otherwise.
*
* `has($id)` returning true does not mean that `get($id)` will not throw an exception.
* It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
*
* @param string $id Identifier of the entry to look for.
*
* @return bool
*/
public function has(string $id);
}
packages/Psr/Container/NotFoundExceptionInterface.php 0000644 00000000274 15233617221 0016762 0 ustar 00 <?php
namespace Automattic\WooCommerce\Vendor\Psr\Container;
/**
* No entry was found in the container.
*/
interface NotFoundExceptionInterface extends ContainerExceptionInterface
{
}
data/languages.php 0000644 00000007612 15233644314 0010147 0 ustar 00 <?php
/**
* Compiled data. Do not edit.
*/
return ['aa'=>'Afar','ab'=>'Abkhazian','ae'=>'Avestan','af'=>'Afrikaans','ak'=>'Akan','am'=>'Amharic','an'=>'Aragonese','ar'=>'Arabic','arq'=>'Algerian Arabic','ary'=>'Moroccan Arabic','as'=>'Assamese','ast'=>'Asturian','av'=>'Avaric','ay'=>'Aymara','az'=>'Azerbaijani','azb'=>'South Azerbaijani','ba'=>'Bashkir','bal'=>'Baluchi','bcc'=>'Southern Balochi','be'=>'Belarusian','bg'=>'Bulgarian','bgn'=>'Western Balochi','bho'=>'Bhojpuri','bi'=>'Bislama','bm'=>'Bambara','bn'=>'Bengali','bo'=>'Tibetan','br'=>'Breton','brx'=>'Bodo (India)','bs'=>'Bosnian','ca'=>'Catalan','ce'=>'Chechen','ceb'=>'Cebuano','ch'=>'Chamorro','ckb'=>'Central Kurdish','co'=>'Corsican','cr'=>'Cree','cs'=>'Czech','cu'=>'Church Slavic','cv'=>'Chuvash','cy'=>'Welsh','da'=>'Danish','de'=>'German','dsb'=>'Lower Sorbian','dv'=>'Dhivehi','dz'=>'Dzongkha','ee'=>'Ewe','el'=>'Greek','en'=>'English','eo'=>'Esperanto','es'=>'Spanish','et'=>'Estonian','eu'=>'Basque','fa'=>'Persian','ff'=>'Fulah','fi'=>'Finnish','fj'=>'Fijian','fo'=>'Faroese','fon'=>'Fon','fr'=>'French','frp'=>'Arpitan','fuc'=>'Pulaar','fur'=>'Friulian','fy'=>'Western Frisian','ga'=>'Irish','gax'=>'Borana-Arsi-Guji Oromo','gd'=>'Scottish Gaelic','gl'=>'Galician','gn'=>'Guarani','gu'=>'Gujarati','gv'=>'Manx','ha'=>'Hausa','haw'=>'Hawaiian','haz'=>'Hazaragi','he'=>'Hebrew','hi'=>'Hindi','ho'=>'Hiri Motu','hr'=>'Croatian','hsb'=>'Upper Sorbian','ht'=>'Haitian','hu'=>'Hungarian','hy'=>'Armenian','hz'=>'Herero','ia'=>'Interlingua','id'=>'Indonesian','ie'=>'Interlingue','ig'=>'Igbo','ii'=>'Sichuan Yi','ik'=>'Inupiaq','io'=>'Ido','is'=>'Icelandic','it'=>'Italian','iu'=>'Inuktitut','ja'=>'Japanese','jv'=>'Javanese','ka'=>'Georgian','kaa'=>'Kara-Kalpak','kab'=>'Kabyle','kg'=>'Kongo','ki'=>'Kikuyu','kj'=>'Kuanyama','kk'=>'Kazakh','kl'=>'Kalaallisut','km'=>'Central Khmer','kmr'=>'Northern Kurdish','kn'=>'Kannada','ko'=>'Korean','kr'=>'Kanuri','ks'=>'Kashmiri','ku'=>'Kurdish','kv'=>'Komi','kw'=>'Cornish','ky'=>'Kirghiz','la'=>'Latin','lb'=>'Luxembourgish','lg'=>'Ganda','li'=>'Limburgan','lij'=>'Ligurian','lmo'=>'Lombard','ln'=>'Lingala','lo'=>'Lao','lt'=>'Lithuanian','lu'=>'Luba-Katanga','lv'=>'Latvian','mai'=>'Maithili','mfe'=>'Morisyen','mg'=>'Malagasy','mh'=>'Marshallese','mi'=>'Maori','mk'=>'Macedonian','ml'=>'Malayalam','mn'=>'Mongolian','mr'=>'Marathi','ms'=>'Malay','mt'=>'Maltese','my'=>'Burmese','na'=>'Nauru','nb'=>'Norwegian Bokmål','nd'=>'North Ndebele','ne'=>'Nepali','ng'=>'Ndonga','nl'=>'Dutch','nn'=>'Norwegian Nynorsk','no'=>'Norwegian','nqo'=>'N\'Ko','nr'=>'South Ndebele','nv'=>'Navajo','ny'=>'Nyanja','oc'=>'Occitan (post 1500)','oj'=>'Ojibwa','om'=>'Oromo','or'=>'Oriya','ory'=>'Oriya (individual language)','os'=>'Ossetian','pa'=>'Panjabi','pap'=>'Papiamento','pcd'=>'Picard','pcm'=>'Nigerian Pidgin','pi'=>'Pali','pl'=>'Polish','ps'=>'Pushto','pt'=>'Portuguese','qu'=>'Quechua','rhg'=>'Rohingya','rm'=>'Romansh','rn'=>'Rundi','ro'=>'Romanian','ru'=>'Russian','rw'=>'Kinyarwanda','sa'=>'Sanskrit','sah'=>'Yakut','sc'=>'Sardinian','scn'=>'Sicilian','sd'=>'Sindhi','se'=>'Northern Sami','sg'=>'Sango','sh'=>'Serbo-Croatian','si'=>'Sinhala','sk'=>'Slovak','skr'=>'Saraiki','sl'=>'Slovenian','sm'=>'Samoan','sn'=>'Shona','so'=>'Somali','sq'=>'Albanian','sr'=>'Serbian','ss'=>'Swati','st'=>'Southern Sotho','su'=>'Sundanese','sv'=>'Swedish','sw'=>'Swahili','syr'=>'Syriac','szl'=>'Silesian','ta'=>'Tamil','te'=>'Telugu','tg'=>'Tajik','th'=>'Thai','ti'=>'Tigrinya','tk'=>'Turkmen','tl'=>'Tagalog','tn'=>'Tswana','to'=>'Tonga (Tonga Islands)','tr'=>'Turkish','ts'=>'Tsonga','tt'=>'Tatar','tw'=>'Twi','twd'=>'Twents','ty'=>'Tahitian','tzm'=>'Central Atlas Tamazight','ug'=>'Uighur','uk'=>'Ukrainian','ur'=>'Urdu','uz'=>'Uzbek','ve'=>'Venda','vec'=>'Venetian','vi'=>'Vietnamese','vo'=>'Volapük','wa'=>'Walloon','wo'=>'Wolof','xh'=>'Xhosa','yi'=>'Yiddish','yo'=>'Yoruba','za'=>'Zhuang','zgh'=>'Standard Moroccan Tamazight','zh'=>'Chinese','zu'=>'Zulu','tlh'=>'Klingon']; data/regions.php 0000644 00000011721 15233644314 0007643 0 ustar 00 <?php
/**
* Compiled data. Do not edit.
*/
return ['AD'=>'Andorra','AE'=>'United Arab Emirates','AF'=>'Afghanistan','AG'=>'Antigua and Barbuda','AI'=>'Anguilla','AL'=>'Albania','AM'=>'Armenia','AO'=>'Angola','AQ'=>'Antarctica','AR'=>'Argentina','AS'=>'American Samoa','AT'=>'Austria','AU'=>'Australia','AW'=>'Aruba','AX'=>'Åland Islands','AZ'=>'Azerbaijan','BA'=>'Bosnia and Herzegovina','BB'=>'Barbados','BD'=>'Bangladesh','BE'=>'Belgium','BF'=>'Burkina Faso','BG'=>'Bulgaria','BH'=>'Bahrain','BI'=>'Burundi','BJ'=>'Benin','BL'=>'Saint Barthélemy','BM'=>'Bermuda','BN'=>'Brunei Darussalam','BO'=>'Bolivia','BQ'=>'Bonaire, Sint Eustatius and Saba','BR'=>'Brazil','BS'=>'Bahamas','BT'=>'Bhutan','BV'=>'Bouvet Island','BW'=>'Botswana','BY'=>'Belarus','BZ'=>'Belize','CA'=>'Canada','CC'=>'Cocos (Keeling) Islands','CD'=>'The Democratic Republic of the Congo','CF'=>'Central African Republic','CG'=>'Congo','CH'=>'Switzerland','CI'=>'Côte d\'Ivoire','CK'=>'Cook Islands','CL'=>'Chile','CM'=>'Cameroon','CN'=>'China','CO'=>'Colombia','CR'=>'Costa Rica','CU'=>'Cuba','CV'=>'Cabo Verde; Cape Verde','CW'=>'Curaçao','CX'=>'Christmas Island','CY'=>'Cyprus','CZ'=>'Czech Republic','DE'=>'Germany','DJ'=>'Djibouti','DK'=>'Denmark','DM'=>'Dominica','DO'=>'Dominican Republic','DZ'=>'Algeria','EC'=>'Ecuador','EE'=>'Estonia','EG'=>'Egypt','EH'=>'Western Sahara','ER'=>'Eritrea','ES'=>'Spain','ET'=>'Ethiopia','FI'=>'Finland','FJ'=>'Fiji','FK'=>'Falkland Islands (Malvinas)','FM'=>'Federated States of Micronesia','FO'=>'Faroe Islands','FR'=>'France','GA'=>'Gabon','GB'=>'United Kingdom','GD'=>'Grenada','GE'=>'Georgia','GF'=>'French Guiana','GG'=>'Guernsey','GH'=>'Ghana','GI'=>'Gibraltar','GL'=>'Greenland','GM'=>'Gambia','GN'=>'Guinea','GP'=>'Guadeloupe','GQ'=>'Equatorial Guinea','GR'=>'Greece','GS'=>'South Georgia and the South Sandwich Islands','GT'=>'Guatemala','GU'=>'Guam','GW'=>'Guinea-Bissau','GY'=>'Guyana','HK'=>'Hong Kong','HM'=>'Heard Island and McDonald Islands','HN'=>'Honduras','HR'=>'Croatia','HT'=>'Haiti','HU'=>'Hungary','ID'=>'Indonesia','IE'=>'Ireland','IL'=>'Israel','IM'=>'Isle of Man','IN'=>'India','IO'=>'British Indian Ocean Territory','IQ'=>'Iraq','IR'=>'Islamic Republic of Iran','IS'=>'Iceland','IT'=>'Italy','JE'=>'Jersey','JM'=>'Jamaica','JO'=>'Jordan','JP'=>'Japan','KE'=>'Kenya','KG'=>'Kyrgyzstan','KH'=>'Cambodia','KI'=>'Kiribati','KM'=>'Comoros','KN'=>'Saint Kitts and Nevis','KP'=>'Democratic People\'s Republic of Korea','KR'=>'Republic of Korea','KW'=>'Kuwait','KY'=>'Cayman Islands','KZ'=>'Kazakhstan','LA'=>'Lao People\'s Democratic Republic','LB'=>'Lebanon','LC'=>'Saint Lucia','LI'=>'Liechtenstein','LK'=>'Sri Lanka','LR'=>'Liberia','LS'=>'Lesotho','LT'=>'Lithuania','LU'=>'Luxembourg','LV'=>'Latvia','LY'=>'Libya','MA'=>'Morocco','MC'=>'Monaco','MD'=>'Moldova','ME'=>'Montenegro','MF'=>'Saint Martin (French part)','MG'=>'Madagascar','MH'=>'Marshall Islands','MK'=>'The Former Yugoslav Republic of Macedonia','ML'=>'Mali','MM'=>'Myanmar','MN'=>'Mongolia','MO'=>'Macao','MP'=>'Northern Mariana Islands','MQ'=>'Martinique','MR'=>'Mauritania','MS'=>'Montserrat','MT'=>'Malta','MU'=>'Mauritius','MV'=>'Maldives','MW'=>'Malawi','MX'=>'Mexico','MY'=>'Malaysia','MZ'=>'Mozambique','NA'=>'Namibia','NC'=>'New Caledonia','NE'=>'Niger','NF'=>'Norfolk Island','NG'=>'Nigeria','NI'=>'Nicaragua','NL'=>'Netherlands','NO'=>'Norway','NP'=>'Nepal','NR'=>'Nauru','NU'=>'Niue','NZ'=>'New Zealand','OM'=>'Oman','PA'=>'Panama','PE'=>'Peru','PF'=>'French Polynesia','PG'=>'Papua New Guinea','PH'=>'Philippines','PK'=>'Pakistan','PL'=>'Poland','PM'=>'Saint Pierre and Miquelon','PN'=>'Pitcairn','PR'=>'Puerto Rico','PS'=>'State of Palestine','PT'=>'Portugal','PW'=>'Palau','PY'=>'Paraguay','QA'=>'Qatar','RE'=>'Réunion','RO'=>'Romania','RS'=>'Serbia','RU'=>'Russian Federation','RW'=>'Rwanda','SA'=>'Saudi Arabia','SB'=>'Solomon Islands','SC'=>'Seychelles','SD'=>'Sudan','SE'=>'Sweden','SG'=>'Singapore','SH'=>'Saint Helena, Ascension and Tristan da Cunha','SI'=>'Slovenia','SJ'=>'Svalbard and Jan Mayen','SK'=>'Slovakia','SL'=>'Sierra Leone','SM'=>'San Marino','SN'=>'Senegal','SO'=>'Somalia','SR'=>'Suriname','SS'=>'South Sudan','ST'=>'Sao Tome and Principe','SV'=>'El Salvador','SX'=>'Sint Maarten (Dutch part)','SY'=>'Syrian Arab Republic','SZ'=>'Swaziland','TC'=>'Turks and Caicos Islands','TD'=>'Chad','TF'=>'French Southern Territories','TG'=>'Togo','TH'=>'Thailand','TJ'=>'Tajikistan','TK'=>'Tokelau','TL'=>'Timor-Leste','TM'=>'Turkmenistan','TN'=>'Tunisia','TO'=>'Tonga','TR'=>'Turkey','TT'=>'Trinidad and Tobago','TV'=>'Tuvalu','TW'=>'Taiwan','TZ'=>'United Republic of Tanzania','UA'=>'Ukraine','UG'=>'Uganda','UM'=>'United States Minor Outlying Islands','US'=>'United States','UY'=>'Uruguay','UZ'=>'Uzbekistan','VA'=>'Holy See (Vatican City State)','VC'=>'Saint Vincent and the Grenadines','VE'=>'Venezuela','VG'=>'British Virgin Islands','VI'=>'U.S. Virgin Islands','VN'=>'Viet Nam','VU'=>'Vanuatu','WF'=>'Wallis and Futuna','WS'=>'Samoa','YE'=>'Yemen','YT'=>'Mayotte','ZA'=>'South Africa','ZM'=>'Zambia','ZW'=>'Zimbabwe','ZZ'=>'Private use']; data/locales.php 0000644 00000014232 15233644314 0007617 0 ustar 00 <?php
/**
* Compiled data. Do not edit.
*/
return ['af'=>[0=>'Afrikaans',1=>'Afrikaans'],'am'=>[0=>'Amharic',1=>'አማርኛ'],'arg'=>[0=>'Aragonese',1=>'Aragonés'],'ar'=>[0=>'Arabic',1=>'العربية'],'ary'=>[0=>'Moroccan Arabic',1=>'العربية المغربية'],'as'=>[0=>'Assamese',1=>'অসমীয়া'],'azb'=>[0=>'South Azerbaijani',1=>'گؤنئی آذربایجان'],'az'=>[0=>'Azerbaijani',1=>'Azərbaycan dili'],'bel'=>[0=>'Belarusian',1=>'Беларуская мова'],'bg_BG'=>[0=>'Bulgarian',1=>'Български'],'bn_BD'=>[0=>'Bengali (Bangladesh)',1=>'বাংলা'],'bo'=>[0=>'Tibetan',1=>'བོད་ཡིག'],'bs_BA'=>[0=>'Bosnian',1=>'Bosanski'],'ca'=>[0=>'Catalan',1=>'Català'],'ceb'=>[0=>'Cebuano',1=>'Cebuano'],'cs_CZ'=>[0=>'Czech',1=>'Čeština'],'cy'=>[0=>'Welsh',1=>'Cymraeg'],'da_DK'=>[0=>'Danish',1=>'Dansk'],'de_AT'=>[0=>'German (Austria)',1=>'Deutsch (Österreich)'],'de_CH'=>[0=>'German (Switzerland)',1=>'Deutsch (Schweiz)'],'de_DE_formal'=>[0=>'German (Formal)',1=>'Deutsch (Sie)'],'de_DE'=>[0=>'German',1=>'Deutsch'],'de_CH_informal'=>[0=>'German (Switzerland, Informal)',1=>'Deutsch (Schweiz, Du)'],'dsb'=>[0=>'Lower Sorbian',1=>'Dolnoserbšćina'],'dzo'=>[0=>'Dzongkha',1=>'རྫོང་ཁ'],'el'=>[0=>'Greek',1=>'Ελληνικά'],'en_NZ'=>[0=>'English (New Zealand)',1=>'English (New Zealand)'],'en_AU'=>[0=>'English (Australia)',1=>'English (Australia)'],'en_ZA'=>[0=>'English (South Africa)',1=>'English (South Africa)'],'en_GB'=>[0=>'English (UK)',1=>'English (UK)'],'en_CA'=>[0=>'English (Canada)',1=>'English (Canada)'],'eo'=>[0=>'Esperanto',1=>'Esperanto'],'es_ES'=>[0=>'Spanish (Spain)',1=>'Español'],'es_CL'=>[0=>'Spanish (Chile)',1=>'Español de Chile'],'es_VE'=>[0=>'Spanish (Venezuela)',1=>'Español de Venezuela'],'es_EC'=>[0=>'Spanish (Ecuador)',1=>'Español de Ecuador'],'es_DO'=>[0=>'Spanish (Dominican Republic)',1=>'Español de República Dominicana'],'es_UY'=>[0=>'Spanish (Uruguay)',1=>'Español de Uruguay'],'es_PR'=>[0=>'Spanish (Puerto Rico)',1=>'Español de Puerto Rico'],'es_MX'=>[0=>'Spanish (Mexico)',1=>'Español de México'],'es_GT'=>[0=>'Spanish (Guatemala)',1=>'Español de Guatemala'],'es_CO'=>[0=>'Spanish (Colombia)',1=>'Español de Colombia'],'es_CR'=>[0=>'Spanish (Costa Rica)',1=>'Español de Costa Rica'],'es_PE'=>[0=>'Spanish (Peru)',1=>'Español de Perú'],'es_AR'=>[0=>'Spanish (Argentina)',1=>'Español de Argentina'],'et'=>[0=>'Estonian',1=>'Eesti'],'eu'=>[0=>'Basque',1=>'Euskara'],'fa_AF'=>[0=>'Persian (Afghanistan)',1=>'(فارسی (افغانستان'],'fa_IR'=>[0=>'Persian',1=>'فارسی'],'fi'=>[0=>'Finnish',1=>'Suomi'],'fr_CA'=>[0=>'French (Canada)',1=>'Français du Canada'],'fr_FR'=>[0=>'French (France)',1=>'Français'],'fr_BE'=>[0=>'French (Belgium)',1=>'Français de Belgique'],'fur'=>[0=>'Friulian',1=>'Friulian'],'fy'=>[0=>'Frisian',1=>'Frysk'],'gd'=>[0=>'Scottish Gaelic',1=>'Gàidhlig'],'gl_ES'=>[0=>'Galician',1=>'Galego'],'gu'=>[0=>'Gujarati',1=>'ગુજરાતી'],'haz'=>[0=>'Hazaragi',1=>'هزاره گی'],'he_IL'=>[0=>'Hebrew',1=>'עִבְרִית'],'hi_IN'=>[0=>'Hindi',1=>'हिन्दी'],'hr'=>[0=>'Croatian',1=>'Hrvatski'],'hsb'=>[0=>'Upper Sorbian',1=>'Hornjoserbšćina'],'hu_HU'=>[0=>'Hungarian',1=>'Magyar'],'hy'=>[0=>'Armenian',1=>'Հայերեն'],'id_ID'=>[0=>'Indonesian',1=>'Bahasa Indonesia'],'is_IS'=>[0=>'Icelandic',1=>'Íslenska'],'it_IT'=>[0=>'Italian',1=>'Italiano'],'ja'=>[0=>'Japanese',1=>'日本語'],'jv_ID'=>[0=>'Javanese',1=>'Basa Jawa'],'ka_GE'=>[0=>'Georgian',1=>'ქართული'],'kab'=>[0=>'Kabyle',1=>'Taqbaylit'],'kk'=>[0=>'Kazakh',1=>'Қазақ тілі'],'km'=>[0=>'Khmer',1=>'ភាសាខ្មែរ'],'kn'=>[0=>'Kannada',1=>'ಕನ್ನಡ'],'ko_KR'=>[0=>'Korean',1=>'한국어'],'ckb'=>[0=>'Kurdish (Sorani)',1=>'كوردی'],'kir'=>[0=>'Kyrgyz',1=>'Кыргызча'],'lo'=>[0=>'Lao',1=>'ພາສາລາວ'],'lt_LT'=>[0=>'Lithuanian',1=>'Lietuvių kalba'],'lv'=>[0=>'Latvian',1=>'Latviešu valoda'],'mk_MK'=>[0=>'Macedonian',1=>'Македонски јазик'],'ml_IN'=>[0=>'Malayalam',1=>'മലയാളം'],'mn'=>[0=>'Mongolian',1=>'Монгол'],'mr'=>[0=>'Marathi',1=>'मराठी'],'ms_MY'=>[0=>'Malay',1=>'Bahasa Melayu'],'my_MM'=>[0=>'Myanmar (Burmese)',1=>'ဗမာစာ'],'nb_NO'=>[0=>'Norwegian (Bokmål)',1=>'Norsk bokmål'],'ne_NP'=>[0=>'Nepali',1=>'नेपाली'],'nl_NL'=>[0=>'Dutch',1=>'Nederlands'],'nl_BE'=>[0=>'Dutch (Belgium)',1=>'Nederlands (België)'],'nl_NL_formal'=>[0=>'Dutch (Formal)',1=>'Nederlands (Formeel)'],'nn_NO'=>[0=>'Norwegian (Nynorsk)',1=>'Norsk nynorsk'],'oci'=>[0=>'Occitan',1=>'Occitan'],'pa_IN'=>[0=>'Panjabi (India)',1=>'ਪੰਜਾਬੀ'],'pl_PL'=>[0=>'Polish',1=>'Polski'],'ps'=>[0=>'Pashto',1=>'پښتو'],'pt_BR'=>[0=>'Portuguese (Brazil)',1=>'Português do Brasil'],'pt_PT'=>[0=>'Portuguese (Portugal)',1=>'Português'],'pt_PT_ao90'=>[0=>'Portuguese (Portugal, AO90)',1=>'Português (AO90)'],'pt_AO'=>[0=>'Portuguese (Angola)',1=>'Português de Angola'],'rhg'=>[0=>'Rohingya',1=>'Ruáinga'],'ro_RO'=>[0=>'Romanian',1=>'Română'],'ru_RU'=>[0=>'Russian',1=>'Русский'],'sah'=>[0=>'Sakha',1=>'Сахалыы'],'snd'=>[0=>'Sindhi',1=>'سنڌي'],'si_LK'=>[0=>'Sinhala',1=>'සිංහල'],'sk_SK'=>[0=>'Slovak',1=>'Slovenčina'],'skr'=>[0=>'Saraiki',1=>'سرائیکی'],'sl_SI'=>[0=>'Slovenian',1=>'Slovenščina'],'sq'=>[0=>'Albanian',1=>'Shqip'],'sr_RS'=>[0=>'Serbian',1=>'Српски језик'],'sv_SE'=>[0=>'Swedish',1=>'Svenska'],'sw'=>[0=>'Swahili',1=>'Kiswahili'],'szl'=>[0=>'Silesian',1=>'Ślōnskŏ gŏdka'],'ta_IN'=>[0=>'Tamil',1=>'தமிழ்'],'ta_LK'=>[0=>'Tamil (Sri Lanka)',1=>'தமிழ்'],'te'=>[0=>'Telugu',1=>'తెలుగు'],'th'=>[0=>'Thai',1=>'ไทย'],'tl'=>[0=>'Tagalog',1=>'Tagalog'],'tr_TR'=>[0=>'Turkish',1=>'Türkçe'],'tt_RU'=>[0=>'Tatar',1=>'Татар теле'],'tah'=>[0=>'Tahitian',1=>'Reo Tahiti'],'ug_CN'=>[0=>'Uighur',1=>'ئۇيغۇرچە'],'uk'=>[0=>'Ukrainian',1=>'Українська'],'ur'=>[0=>'Urdu',1=>'اردو'],'uz_UZ'=>[0=>'Uzbek',1=>'O‘zbekcha'],'vi'=>[0=>'Vietnamese',1=>'Tiếng Việt'],'zh_TW'=>[0=>'Chinese (Taiwan)',1=>'繁體中文'],'zh_CN'=>[0=>'Chinese (China)',1=>'简体中文'],'zh_HK'=>[0=>'Chinese (Hong Kong)',1=>'香港中文']]; data/gp.php 0000644 00000001603 15233644314 0006601 0 ustar 00 <?php
/**
* Compiled data. Do not edit.
*/
return ['version'=>'4.0.0','aliases'=>['arg'=>'an','bg-bg'=>'bg','bn-bd'=>'bn','bre'=>'br','bs-ba'=>'bs','ca-valencia'=>'ca-val','cs-cz'=>'cs','da-dk'=>'da','de-de'=>'de','ewe'=>'ee','en-us'=>'en','es-es'=>'es','fa-ir'=>'fa','fr-fr'=>'fr','gl-es'=>'gl','haw-us'=>'haw','he-il'=>'he','hi-in'=>'hi','hu-hu'=>'hu','id-id'=>'id','is-is'=>'is','it-it'=>'it','jv-id'=>'jv','ka-ge'=>'ka','ko-kr'=>'ko','lb-lu'=>'lb','lt-lt'=>'lt','me-me'=>'me','mg-mg'=>'mg','mk-mk'=>'mk','ml-in'=>'ml','ms-my'=>'ms','my-mm'=>'mya','ne-np'=>'ne','nb-no'=>'nb','nl-nl'=>'nl','nn-no'=>'nn','pa-in'=>'pa','art-xpirate'=>'pirate','pl-pl'=>'pl','pt-pt'=>'pt','pt-pt-ao90'=>'pt-ao90','ro-ro'=>'ro','ru-ru'=>'ru','si-lk'=>'si','sk-sk'=>'sk','sl-si'=>'sl','so-so'=>'so','sr-rs'=>'sr','su-id'=>'su','sv-se'=>'sv','ta-in'=>'ta','tr-tr'=>'tr','tt-ru'=>'tt','ug-cn'=>'ug','uz-uz'=>'uz']]; data/plurals.php 0000644 00000005633 15233644314 0007664 0 ustar 00 <?php
/**
* Compiled data. Do not edit.
*/
return ['ak'=>1,'am'=>1,'ar'=>2,'ary'=>2,'be'=>3,'bm'=>4,'bo'=>4,'br'=>1,'bs'=>3,'cs'=>5,'cy'=>6,'dz'=>4,'ff'=>1,'fr'=>1,'ga'=>7,'gd'=>8,'gv'=>9,'hr'=>10,'id'=>4,'ii'=>4,'iu'=>11,'ja'=>4,'ka'=>4,'kk'=>4,'km'=>4,'kn'=>4,'ko'=>4,'kw'=>11,'ky'=>4,'ln'=>1,'lo'=>4,'lt'=>12,'lv'=>13,'mg'=>1,'mi'=>1,'mk'=>14,'ms'=>4,'mt'=>15,'my'=>4,'nr'=>4,'oc'=>1,'pl'=>16,'ro'=>17,'ru'=>3,'sa'=>11,'sg'=>4,'sk'=>5,'sl'=>18,'sm'=>4,'sr'=>3,'su'=>4,'th'=>4,'ti'=>1,'tl'=>1,'to'=>4,'tt'=>4,'ug'=>4,'uk'=>3,'vi'=>4,'wa'=>1,'wo'=>4,'yo'=>4,'zh'=>4,''=>[0=>[0=>'n != 1',1=>[1=>'one','0,2,3…'=>'other']],1=>[0=>'n > 1',1=>['0,1'=>'one','2,3,4…'=>'other']],2=>[0=>'n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100 >= 3 && n%100<=10 ? 3 : n%100 >= 11 && n%100<=99 ? 4 : 5',1=>[0=>'zero',1=>'one',2=>'two','3,4,5…'=>'few','11,12,13…'=>'many','100,101,102…'=>'other']],3=>[0=>'(n%10==1 && n%100!=11 ? 0 : n%10 >= 2 && n%10<=4 &&(n%100<10||n%100 >= 20)? 1 : 2)',1=>['1,21,31…'=>'one','2,3,4…'=>'few','0,5,6…'=>'other']],4=>[0=>'0',1=>['0,1,2…'=>'other']],5=>[0=>'( n == 1 ) ? 0 : ( n >= 2 && n <= 4 ) ? 1 : 2',1=>[1=>'one','2,3,4'=>'few','0,5,6…'=>'other']],6=>[0=>'n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n==3 ? 3 : n==6 ? 4 : 5',1=>[0=>'zero',1=>'one',2=>'two',3=>'few',6=>'many','4,5,7…'=>'other']],7=>[0=>'n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4',1=>[1=>'one',2=>'two','0,3,4…'=>'few','7,8,9…'=>'many','11,12,13…'=>'other']],8=>[0=>'n==1||n==11 ? 0 : n==2||n==12 ? 1 :(n >= 3 && n<=10)||(n >= 13 && n<=19)? 2 : 3',1=>['1,11'=>'one','2,12'=>'two','3,4,5…'=>'few','0,20,21…'=>'other']],9=>[0=>'n%10==1 ? 0 : n%10==2 ? 1 : n%20==0 ? 2 : 3',1=>['1,11,21…'=>'one','2,12,22…'=>'two','0,20,100…'=>'few','3,4,5…'=>'other']],10=>[0=>'n%10==1 && n%100!=11 ? 0 : n%10 >= 2 && n%10<=4 &&(n%100<10||n%100 >= 20)? 1 : 2',1=>['1,21,31…'=>'one','2,3,4…'=>'few','0,5,6…'=>'other']],11=>[0=>'n == 1 ? 0 : n == 2 ? 1 : 2',1=>[1=>'one',2=>'two','0,3,4…'=>'other']],12=>[0=>'(n%10==1 && n%100!=11 ? 0 : n%10 >= 2 &&(n%100<10||n%100 >= 20)? 1 : 2)',1=>['1,21,31…'=>'one','2,3,4…'=>'few','0,10,11…'=>'other']],13=>[0=>'n%10==0||( n%100 >= 11 && n%100<=19)? 0 :(n%10==1 && n%100!=11 ? 1 : 2)',1=>['0,10,11…'=>'zero','1,21,31…'=>'one','2,3,4…'=>'other']],14=>[0=>'( n % 10 == 1 && n % 100 != 11 ) ? 0 : 1',1=>['1,21,31…'=>'one','0,2,3…'=>'other']],15=>[0=>'(n==1 ? 0 : n==0||( n%100>1 && n%100<11)? 1 :(n%100>10 && n%100<20)? 2 : 3)',1=>[1=>'one','0,2,3…'=>'few','11,12,13…'=>'many','20,21,22…'=>'other']],16=>[0=>'(n==1 ? 0 : n%10 >= 2 && n%10<=4 &&(n%100<10||n%100 >= 20)? 1 : 2)',1=>[1=>'one','2,3,4…'=>'few','0,5,6…'=>'other']],17=>[0=>'(n==1 ? 0 :(((n%100>19)||(( n%100==0)&&(n!=0)))? 2 : 1))',1=>[1=>'one','0,2,3…'=>'few','20,21,22…'=>'other']],18=>[0=>'n%100==1 ? 0 : n%100==2 ? 1 : n%100==3||n%100==4 ? 2 : 3',1=>['1,101,201…'=>'one','2,102,202…'=>'two','3,4,103…'=>'few','0,5,6…'=>'other']]]]; compiled/locales.php 0000644 00000001052 15233644314 0010476 0 ustar 00 <?php
/**
* Downgraded for PHP 5.6 compatibility. Do not edit.
* @noinspection ALL
*/
function loco_parse_wp_locale( $tag ) { if( ! preg_match( '/^([a-z]{2,3})(?:[-_]([a-z]{2}))?(?:[-_]([a-z\\d]{3,8}))?$/i', $tag, $tags ) ){ throw new InvalidArgumentException('Invalid WordPress locale: '.json_encode($tag) ); } $data = [ 'lang' => strtolower( $tags[1] ), ]; if( array_key_exists(2,$tags) && $tags[2] ){ $data['region'] = strtoupper($tags[2]); } if( array_key_exists(3,$tags) && $tags[3] ){ $data['variant'] = strtolower($tags[3]); } return $data; }
compiled/README.md 0000644 00000000222 15233644314 0007620 0 ustar 00 # Compiled libraries
These files are built from the Loco core. Do not edit!
They've been converted down for PHP 5.2 compatibility in WordPress.
compiled/gettext.php 0000644 00000202357 15233644314 0010553 0 ustar 00 <?php
/**
* Downgraded for PHP 5.6 compatibility. Do not edit.
* @noinspection ALL
*/
interface LocoArrayInterface extends ArrayAccess, Iterator, Countable, JsonSerializable {
public function getArrayCopy(); }
class LocoHeaders extends ArrayIterator implements LocoArrayInterface {
private $map = [];
public function __construct(array $raw = [] ){ if( $raw ){ $keys = array_keys( $raw ); $this->map = array_combine( array_map( 'strtolower', $keys ), $keys ); parent::__construct($raw); } }
public function normalize( $k ) { $k = strtolower($k); return array_key_exists($k,$this->map) ? $this->map[$k] : null; }
public function add($key, $val ) { $this->offsetSet( $key, $val ); return $this; }
public function __toString() { $pairs = []; foreach( $this as $key => $val ){ $pairs[] = $key.': '.$val; } return implode("\n", $pairs ); }
public function trimmed( $prop ) { return trim( $this->__get($prop) ); }
public function has( $key) { return array_key_exists( strtolower($key), $this->map ); }
public function __get( $key ){ return $this->offsetGet( $key ); }
public function __set( $key, $val ) { $this->offsetSet( $key, $val ); }
#[ReturnTypeWillChange]
public function offsetExists( $key ) { return $this->has($key); }
#[ReturnTypeWillChange]
public function offsetGet( $key ) { $k = $this->normalize($key); if( is_null($k) ){ return ''; } return parent::offsetGet($k); }
#[ReturnTypeWillChange]
public function offsetSet( $key, $value ) { $k = strtolower($key); if( isset($this->map[$k]) && $key !== $this->map[$k] ){ parent::offsetUnset( $this->map[$k] ); } $this->map[$k] = $key; parent::offsetSet( $key, $value ); }
#[ReturnTypeWillChange]
public function offsetUnset( $key ) { $k = strtolower($key); if( isset($this->map[$k]) ){ parent::offsetUnset( $this->map[$k] ); unset( $this->map[$k] ); } }
#[ReturnTypeWillChange]
public function jsonSerialize() { return $this->getArrayCopy(); } }
function loco_normalize_charset( $cs ) { if( preg_match('/^UTF-?(8|16-?(LE|BE)?)$/i',$cs,$r,PREG_UNMATCHED_AS_NULL) ){ return '8' === $r[1] ? 'UTF-8' : 'UTF-16'.$r[2]; } try { return mb_preferred_mime_name($cs); } catch( ValueError $e ){ try { if( preg_match('/^csISO(\\w+)/i',$cs,$r) || preg_match('/^(\\w+)8$/',$cs,$r) ){ return mb_preferred_mime_name($r[1]); } throw $e; } catch( ValueError $e ){ throw new InvalidArgumentException('Unsupported character encoding: '.$cs ); } } }
class LocoPoHeaders extends LocoHeaders {
private $cs = null;
public function getCharset() { $cs = $this->cs; if( is_null($cs) ){ $cs = ''; $raw = $this->offsetGet('content-type'); if( $raw && preg_match('!\\bcharset[= ]+([-\\w]+)!',$raw,$r) ){ try { $cs = loco_normalize_charset($r[1]); } catch( InvalidArgumentException $e ){ } catch( Exception $e ){ trigger_error( $e->getMessage(), E_USER_NOTICE ); } } $this->cs = $cs; } return $cs; }
public function setCharset( $to ) { $to = loco_normalize_charset($to); $from = $this->getCharset(); $this->cs = $to; $this['Content-Type'] = 'text/plain; charset='.$to; if( '' !== $from && $from !== $to ){ foreach( $this as $key => $val ){ $this[$key] = mb_convert_encoding($val,$to,$from); } } return $to; }
public static function fromMsgstr( $str ) { $headers = new LocoPoHeaders; $key = ''; foreach( preg_split('/[\\r\\n]+/',$str) as $line ){ $i = strpos($line,':'); if( is_int($i) ){ $key = trim( substr($line,0,$i), " \t" ); $headers->offsetSet( $key, ltrim( substr($line,++$i)," \t" ) ); } else if( '' !== $key ){ $headers->offsetSet( $key, $headers->offsetGet($key)."\n".$line ); } } $cs = $headers->getCharset(); if( '' !== $cs && 'UTF-8' !== $cs && 'UTF-8' !== mb_detect_encoding($str,['UTF-8',$cs],true) ){ foreach( $headers as $key => $val ){ $headers[$key] = mb_convert_encoding($val,'UTF-8',[$cs]); } } return $headers; }
public static function fromSource( $raw ) { $po = new LocoPoParser($raw); $po->parse(0); return $po->getHeader(); } }
function loco_convert_utf8( $str, $enc, $strict ) { if( '' === $enc || 'UTF-8' === $enc || 'US-ASCII' === $enc ){ if( false === preg_match('//u',$str) ){ if( $strict ){ $e = new Loco_error_ParseException( $enc ? 'Invalid '.$enc.' encoding' : 'Unknown character encoding' ); if( preg_match('/^(?:[\\x00-\\x7F]|[\\xC0-\\xDF][\\x80-\\xBF]|[\\xE0-\\xEF][\\x80-\\xBF]{2}|[\\xF0-\\xFF][\\x80-\\xBF]{3})*/',$str,$r) && $str !== $r[0] ){ $e->setOffsetContext( strlen($r[0]), $str ); } throw $e; } $str = loco_fix_utf8($str); } } else if( 'ISO-8859-1' === $enc ) { $str = mb_convert_encoding( $str, 'UTF-8', 'Windows-1252' ); } else { $str = mb_convert_encoding( $str, 'UTF-8', $enc ); } return $str; }
function loco_fix_utf8( $str ) { $fix = ''; while( is_string($str) && '' !== $str ){ if( preg_match('/^(?:[\\x00-\\x7F]|[\\xC0-\\xDF][\\x80-\\xBF]|[\\xE0-\\xEF][\\x80-\\xBF]{2}|[\\xF0-\\xFF][\\x80-\\xBF]{3})+/',$str,$r) ){ $fix .= $r[0]; $str = substr($str, strlen($r[0]) ); } else { $fix.= mb_convert_encoding( $str[0], 'UTF-8', 'Windows-1252' ); $str = substr($str,1); } } return loco_convert_utf8($fix,'',true); }
abstract class LocoGettextParser {
private $head = null;
private $cs = '';
abstract public function parse( $limit = -1 );
protected function setHeader( LocoPoHeaders $head ) { $this->head = $head; $cs = $head->getCharset(); if( '' !== $cs ){ if( '' === $this->cs ){ $this->setCharset($cs); } } return $head; }
public function getHeader() { return $this->head; }
protected function setCharset( $cs ) { $this->cs = $cs; }
protected function getCharset() { return $this->cs; }
protected function str( $str ) { if( '' !== $str ){ $str = loco_convert_utf8($str,$this->cs,false); } return $str; }
protected function initMsgKey( $key ) { $r = explode("\4",$key); $value = [ 'source' => array_pop($r), 'target' => '', ]; if( isset($r[0]) ){ $value['context'] = $r[0]; } return $value; } }
function loco_remove_bom( $s, &$c ) { $bom = substr($s,0,2); if( "\xFF\xFE" === $bom ){ $c = 'UTF-16LE'; return substr($s,2); } if( "\xFE\xFF" === $bom ){ $c = 'UTF-16BE'; return substr($s,2); } if( "\xEF\xBB" === $bom && "\xBF" === $s[2] ){ $c = 'UTF-8'; return substr($s,3); } $c = ''; return $s; }
function loco_parse_reference_id( $refs, &$_id ) { if( false === ( $n = strpos($refs,'loco:') ) ){ $_id = ''; return $refs; } $_id = substr($refs, $n+5, 24 ); $refs = substr_replace( $refs, '', $n, 29 ); return trim( $refs ); }
class LocoPoParser extends LocoGettextParser implements Iterator {
private $lines = [];
private $i;
private $k;
private $m;
public function __construct( $src ){ if( '' !== $src ){ $src = loco_remove_bom($src,$cs); if( $cs && 'UTF-8' !== $cs ){ $src = mb_convert_encoding( $src, 'UTF-8', $cs ); $cs = 'UTF-8'; } if( 'UTF-8' === $cs ){ $this->setCharset('UTF-8'); } $this->lines = preg_split('/(\\r\\n?|\\n)/', $src ); } }
#[ReturnTypeWillChange]
public function rewind() { $this->i = -1; $this->k = -1; $this->next(); }
#[ReturnTypeWillChange]
public function valid() { return is_int($this->i); }
#[ReturnTypeWillChange]
public function key() { return $this->k; }
#[ReturnTypeWillChange]
public function current() { return $this->m; }
#[ReturnTypeWillChange]
public function next() { $valid = false; $entry = [ '#' => [], 'id' => [null], 'str' => [null] ]; $i = $this->i; while( array_key_exists(++$i,$this->lines) ){ $line = $this->lines[$i]; try { if( '' === $line ){ if( $valid ){ break; } continue; } $c = $line[0]; if( '#' === $c ){ if( $valid ){ $i--; break; } if( '#' === $line ){ continue; } $f = $line[1]; $entry['#'][$f][] = trim( substr( $line, 1+strlen($f) ), " \n\r\t"); } else if( preg_match('/^msg(id(?:_plural)?|ctxt|str(?:\\[(\\d+)])?)[ \\t]*/', $line, $r ) ){ if( isset($r[2]) ){ $key = 'str'; $idx = (int) $r[2]; } else { $key = $r[1]; $idx = 0; } if( $valid && 'str' !== $key && null !== $entry['str'][0] ){ $i--; break; } $snip = strlen($r[0]); if( '"' !== substr($line,$snip,1) ){ throw new Exception('Expected " to follow msg'.$key); } $val = ''; $line = substr($line,$snip); while( true ){ if( '"' === $line || ! substr($line,-1) === '"' ){ throw new Exception('Unterminated msg'.$key ); } $val .= substr( $line, 1, -1 ); $j = $i + 1; if( array_key_exists($j,$this->lines) && ( $line = $this->lines[$j] ) && '"' === $line[0] ){ $i = $j; } else { break; } } if( ! $valid ){ $valid = true; } if( 'id_plural' === $key ){ $key = 'id'; $idx = 1; } $entry[$key][$idx] = stripcslashes($val); } else if( preg_match('/^[ \\t]+$/',$line) ){ if( $valid ) { break; } } else if( '"' === $c ){ throw new Exception('String encountered without keyword'); } else { throw new Exception('Junk'); } } catch( Exception $e ){ } } if( $valid ){ ++$this->k; $this->i = $i; $this->m = $entry; } else { $this->i = null; $this->k = null; $this->m = null; } }
public function parse( $limit = -1 ) { $this->rewind(); if( ! $this->valid() ){ throw new Loco_error_ParseException('Invalid PO file'); } $entry = $this->current(); if( '' !== $entry['id'][0] || isset($entry['ctxt']) || is_null($entry['str'][0]) ){ $head = $this->setHeader( new LocoPoHeaders ); } else { $head = $this->setHeader( LocoPoHeaders::fromMsgstr($entry['str'][0]) ); } if( 0 === $limit ){ return []; } $i = -1; $assets = []; $lk = $head['X-Loco-Lookup']; while( $this->valid() ){ $entry = $this->current(); $msgid = $entry['id'][0]; if( is_null($msgid) ){ $this->next(); continue; } if( ++$i === $limit ){ return $assets; } $asset = [ 'source' => $this->str( $msgid ), 'target' => $this->str( (string) $entry['str'][0] ), 'context' => null, ]; $prev_entry = null; if( isset($entry['ctxt']) ){ $asset['context'] = $this->str( $entry['ctxt'][0] ); } $cmt = $entry['#']; if( isset($cmt[' ']) ){ $asset['comment'] = $this->str( implode("\n", $cmt[' '] ) ); } if( isset($cmt['.']) ){ $asset['notes'] = $this->str( implode("\n", $cmt['.'] ) ); } if( isset($cmt[':']) ){ if( $refs = implode( ' ', $cmt[':'] ) ) { $refs = $this->str($refs); if( $refs = loco_parse_reference_id( $refs, $_id ) ){ $asset['refs'] = $refs; } if( $_id ){ $asset['_id'] = $_id; } } } if( isset($cmt[',']) ){ foreach( $cmt[','] as $flags ){ foreach( explode(',',$flags) as $flag ){ if( $flag = trim($flag," \t") ){ if( preg_match('/^((?:no-)?\w+)-format/', $flag, $r ) ){ $asset['format'] = $r[1]; } else if( 'fuzzy' === $flag ){ $asset['flag'] = 4; } } } } } if( isset($cmt['|']) ){ $p = new LocoPoParser(''); $p->lines = $cmt['|']; $p->setCharset( $this->getCharset() ); try { $prev_entry = $p->parse(); } catch( Loco_error_ParseException $e ){ } if( $prev_entry ){ $msgid = $prev_entry[0]['source']; if( $lk && 'text' !== $lk ){ $asset[$lk] = $asset['source']; $asset['source'] = $msgid; } else if( substr($msgid,0,5) === 'loco:' ){ $asset['_id'] = substr($msgid,5); } else { $asset['prev'] = $prev_entry; $prev_entry = null; } } } $assets[] = $asset; if( isset($entry['id'][1]) ){ $idx = 0; $pidx = count($assets) - 1; $num = max( 2, count($entry['str']) ); while( ++$idx < $num ){ $plural = [ 'source' => '', 'target' => isset($entry['str'][$idx]) ? $this->str($entry['str'][$idx]) : '', 'plural' => $idx, 'parent' => $pidx, ]; if( 1 === $idx ){ $plural['source'] = $this->str($entry['id'][1]); if( is_array($prev_entry) && isset($prev_entry[1]) ){ if( $lk && 'text' !== $lk ){ $plural[$lk] = $plural['source']; $plural['source'] = $prev_entry[1]['source']; } } } if( isset($asset['flag']) ){ $plural['flag'] = $asset['flag']; } $assets[] = $plural; } } $this->next(); } if( -1 === $i ){ throw new Loco_error_ParseException('Invalid PO file'); } else if( 0 === $i && '' === $assets[0]['source'] && '' === $assets[0]['target'] ){ throw new Loco_error_ParseException('Invalid PO file' ); } return $assets; } }
class LocoMoParser extends LocoGettextParser {
private $bin;
private $be = null;
private $n = null;
private $o = null;
private $t = null;
private $v = null;
public function __construct( $bin ){ $this->bin = $bin; }
public function getAt( $idx ) { $offset = $this->targetOffset(); $offset += ( $idx * 8 ); $len = $this->integerAt( $offset ); $idx = $this->integerAt( $offset + 4 ); $txt = $this->bytes( $idx, $len ); if( false !== strpos($txt,"\0") ){ return explode( "\0", $txt ); } return $txt; }
public function parse( $limit = -1 ) { $i = -1; $r = []; $sourceOffset = $this->sourceOffset(); $targetOffset = $this->targetOffset(); $soffset = $sourceOffset; $toffset = $targetOffset; while( $soffset < $targetOffset ){ $len = $this->integerAt( $soffset ); $idx = $this->integerAt( $soffset + 4 ); $src = $this->bytes( $idx, $len ); $eot = strpos( $src, "\x04" ); if( false === $eot ){ $context = null; } else { $context = $this->str( substr($src, 0, $eot ) ); $src = substr( $src, $eot+1 ); } $sources = explode( "\0", $src, 2 ); $len = $this->integerAt( $toffset ); $idx = $this->integerAt( $toffset + 4 ); $targets = explode( "\0", $this->bytes( $idx, $len ) ); if( -1 === $i && '' === $sources[0] && is_null($context) ){ $this->setHeader( LocoPoHeaders::fromMsgstr($targets[0]) ); } if( ++$i > $limit && -1 !== $limit ){ break; } $r[$i] = [ 'source' => $this->str( $sources[0] ), 'target' => $this->str( $targets[0] ), 'context' => $context, ]; if( isset($sources[1]) ){ $p = count($r) - 1; $nforms = max( 2, count($targets) ); for( $n = 1; $n < $nforms; $n++ ){ $r[++$i] = [ 'source' => 1 === $n && isset($sources[1]) ? $this->str($sources[1]) : '', 'target' => isset($targets[$n]) ? $this->str( $targets[$n] ) : '', 'parent' => $p, 'plural' => $n, ]; } } $soffset += 8; $toffset += 8; } return $r; }
public function isBigendian() { if( is_null($this->be) ){ $str = $this->words( 0, 1 ); if( "\xDE\x12\x04\x95" === $str ){ $this->be = false; } else if( "\x95\x04\x12\xDE" === $str ){ $this->be = true; } else { throw new Loco_error_ParseException('Invalid MO format'); } } return $this->be; }
public function version() { if( is_null($this->v) ){ $this->v = $this->integerWord(1); } return $this->v; }
#[ReturnTypeWillChange]
public function count() { if( is_null($this->n) ){ $this->n = $this->integerWord(2); } return $this->n; }
public function sourceOffset() { if( is_null($this->o) ){ $this->o = $this->integerWord(3); } return $this->o; }
public function targetOffset() { if( is_null($this->t) ){ $this->t = $this->integerWord(4); } return $this->t; }
public function getHashTable() { $s = $this->integerWord(5); $h = $this->integerWord(6); return $this->bytes( $h, $s * 4 ); }
private function bytes( $offset, $length ) { $s = substr( $this->bin, $offset, $length ); if( strlen($s) !== $length ){ throw new Loco_error_ParseException('Failed to read '.$length.' bytes at ['.$offset.']' ); } return $s; }
private function words( $offset, $length ) { return $this->bytes( $offset * 4, $length * 4 ); }
private function integerWord( $offset ) { return $this->integerAt( $offset * 4 ); }
private function integerAt( $offset ) { $str = $this->bytes( $offset, 4 ); $fmt = $this->isBigendian() ? 'N' : 'V'; $arr = unpack( $fmt, $str ); if( ! isset($arr[1]) || ! is_int($arr[1]) ){ throw new Loco_error_ParseException('Failed to read integer at byte '.$offset); } return $arr[1]; } }
class LocoJedParser extends LocoGettextParser {
private $ld;
public function __construct( array $struct ){ $this->ld = $struct; }
public function parse( $limit = -1 ) { $values = []; foreach( $this->ld as $messages ){ if( ! is_array($messages) ){ throw new Loco_error_ParseException('Array expected'); } $msgid = key($messages); if( '' === $msgid ){ $this->setHeader( new LocoJedHeaders($messages['']) ); unset($messages['']); } else { $this->setHeader( new LocoJedHeaders ); } $values[] = [ 'source' => '', 'target' => $this->getHeader(), ]; $i = -1; foreach( $messages as $key => $list ){ if( ++$i === $limit ){ break; } $value = $this->initMsgKey($key); $index = count($values); foreach( $list as $j => $msgstr ){ if( ! is_string($msgstr) ){ throw new Loco_error_ParseException('msgstr must be scalar'); } $value['target'] = $msgstr; if( 0 < $j ){ $value['plural'] = $j; $value['parent'] = $index; $value['source'] = ''; } $values[] = $value; } } } return $values; } }
class LocoJedHeaders extends LocoPoHeaders {
public function __construct( array $raw = [] ) { foreach( ['Language'=>'lang','plural_forms'=>'Plural-Forms'] as $canonical => $alias ){ if( array_key_exists($alias,$raw) && ! array_key_exists($canonical,$raw) ){ $raw[$canonical] = $raw[$alias]; } } parent::__construct($raw); } }
class LocoMoPhpParser extends LocoGettextParser {
private $msgs;
public function __construct( array $struct ){ $this->msgs = $struct['messages']; unset($struct['messages']); $this->setHeader( new LocoPoHeaders($struct) ); }
public function parse( $limit = -1 ) { $values = [ [ 'source' => '', 'target' => $this->getHeader(), ] ]; $i = -1; foreach( $this->msgs as $key => $bin ){ if( ++$i === $limit ){ break; } $value = $this->initMsgKey($key); $index = count($values); foreach( explode("\0",$bin) as $i => $msgstr ){ $value['target'] = $msgstr; if( 0 < $i ){ $value['plural'] = $i; $value['parent'] = $index; $value['source'] = ''; } $values[] = $value; } } return $values; } }
abstract class LocoPo {
public static function pair( $key, $text, $width = 79, $eol = "\n", $esc = '\\n' ) { if( '' === $text ){ return $key.' ""'; } $text = addcslashes( $text, "\t\x0B\x0C\x07\x08\\\"" ); if( $esc ) { $text = preg_replace('/\\r\\n?|\\n/', $esc.$eol, $text, -1, $nbr ); } else { $eol = "\n"; $text = preg_replace_callback('/\\r\\n?|\\n/',[__CLASS__,'replace_br'], $text, -1, $nbr ); } if( $nbr ){ } else if( $width && $width < mb_strlen($text,'UTF-8') + strlen($key) + 3 ){ } else { return $key.' "'.$text.'"'; } $lines = [ $key.' "' ]; if( $width ){ $width -= 2; $a = '/^.{0,'.($width-1).'}[-– .,:;?!)\\]}>]/u'; $b = '/^[^-– .,:;?!)\\]}>]+/u'; foreach( explode($eol,$text) as $unwrapped ){ $length = mb_strlen( $unwrapped, 'UTF-8' ); while( $length > $width ){ if( preg_match( $a, $unwrapped, $r ) ){ $line = $r[0]; } else if( preg_match( $b, $unwrapped, $r ) ){ $line = $r[0]; } else { throw new Exception('Wrapping error'); } $lines[] = $line; $trunc = mb_strlen($line,'UTF-8'); $length -= $trunc; $unwrapped = (string) substr( $unwrapped, strlen($line) ); if( ( '' === $unwrapped && 0 !== $length ) || ( 0 === $length && '' !== $unwrapped ) ){ throw new Exception('Truncation error'); } } if( 0 !== $length ){ $lines[] = $unwrapped; } } } else { foreach( explode($eol,$text) as $unwrapped ){ $lines[] = $unwrapped; } } return implode('"'.$eol.'"',$lines).'"'; }
private static function replace_br( array $r ) { return addcslashes($r[0],"\r\n")."\n"; }
public static function refs( $text, $width = 76, $eol = "\n" ) { $text = preg_replace('/\\s+/u', ' ', $text ); if( $width ){ $text = wordwrap( $text, $width, $eol.'#: ' ); } return '#: '.$text; }
public static function prefix( $text, $prefix, $eol = "\n" ) { return $prefix . implode($eol.$prefix, self::split($text) ); }
public static function split( $text ) { $lines = preg_split('/\\R/u', $text ); if( false === $lines ){ if( false === preg_match('//u',$text) ){ $text = mb_convert_encoding( $text, 'UTF-8', 'Windows-1252' ); } $lines = preg_split('/\\r?\\n+/', $text ); } return $lines; }
public static function trim( $text ) { $lines = []; $deferred = null; foreach( explode("\n",$text) as $line ){ if( '' === $line ){ continue; } if( preg_match('/^msg[a-z]+(?:\\[\\d+])? ""/',$line) ){ $deferred = $line; continue; } if( $deferred && '"' === $line[0] ){ $lines[] = $deferred; $deferred = null; } $lines[] = $line; } return implode("\n",$lines); } }
class LocoPoIndex extends ArrayIterator {
public function compare( LocoPoMessage $a, LocoPoMessage $b ) { $h = $a->getHash(); if( ! isset($this[$h]) ){ return 1; } $j = $b->getHash(); if( ! isset($this[$j]) ){ return -1; } return $this[$h] > $this[$j] ? 1 : -1; } }
class LocoPoMessage extends ArrayObject {
public function __construct( array $r ){ $r['key'] = $r['source']; parent::__construct($r); }
public function __get( $prop ) { return $this->offsetExists($prop) ? $this->offsetGet($prop) : null; }
public function isFuzzy() { return 4 === $this->__get('flag'); }
public function getFormat() { $f = $this->__get('format'); if( is_string($f) && '' !== $f ){ return $f; } return ''; }
private function getPoFlags() { $flags = []; foreach( array_merge( [$this], $this->__get('plurals')?:[] ) as $form ){ if( $form->isFuzzy() ){ $flags[0] = 'fuzzy'; } $f = $form->getFormat(); if( '' !== $f ){ $flags[1] = $f.'-format'; } } return array_values($flags); }
public function getHash() { $hash = $this->getKey(); if( $this->offsetExists('plurals') ){ foreach( $this->offsetGet('plurals') as $p ){ $hash .= "\0".$p->getKey(); break; } } return $hash; }
public function getKey() { $msgid = (string) $this['source']; $msgctxt = (string) $this->__get('context'); if( '' !== $msgctxt ){ if( '' === $msgid ){ $msgid = '('.$msgctxt.')'; } $msgid = $msgctxt."\4".$msgid; } return $msgid; }
public function exportSerial( $f = 'target' ) { $a = [ $this[$f] ]; if( $this->offsetExists('plurals') ){ $plurals = $this->offsetGet('plurals'); if( is_array($plurals) ){ foreach( $plurals as $p ){ $a[] = $p[$f]; } } } return $a; }
public function __toString(){ return $this->render( 79, 76 ); }
public function render( $width, $ref_width, $max_forms = 0 ) { $s = []; try { if( $text = $this->__get('comment') ) { $s[] = LocoPo::prefix( $text, '# '); } if( $text = $this->__get('notes') ) { $s[] = LocoPo::prefix( $text, '#. '); } if( $text = $this->__get('refs') ){ $s[] = LocoPo::refs( $text, $ref_width ); } if( $texts = $this->getPoFlags() ){ $s[] = '#, '.implode(', ',$texts); } $prev = $this->__get('prev'); if( is_array($prev) && $prev ){ foreach( new LocoPoIterator($prev) as $p ){ $text = $p->render( max(0,$width-3), 0 ); $s[] = LocoPo::prefix( LocoPo::trim($text),'#| '); break; } } $text = $this->__get('context'); if( is_string($text) && '' !== $text ){ $s[] = LocoPo::pair('msgctxt', $text, $width ); } $s[] = LocoPo::pair( 'msgid', $this['source'], $width ); $target = $this['target']; $plurals = $this->__get('plurals'); if( is_array($plurals) ){ if( array_key_exists(0,$plurals) ){ $p = $plurals[0]; $s[] = LocoPo::pair('msgid_plural', $p['source'], $width ); $s[] = LocoPo::pair('msgstr[0]', $target, $width ); $i = 0; while( array_key_exists($i,$plurals) ){ $p = $plurals[$i]; if( ++$i === $max_forms ){ break; } $s[] = LocoPo::pair('msgstr['.$i.']', $p['target'], $width ); } } else if( isset($this['plural_key']) ){ $s[] = LocoPo::pair('msgid_plural', $this['plural_key'], $width ); $s[] = LocoPo::pair('msgstr[0]', $target, $width ); } else { trigger_error('Missing plural_key in zero plural export'); $s[] = LocoPo::pair('msgstr', $target, $width ); } } else { $s[] = LocoPo::pair('msgstr', $target, $width ); } } catch( Exception $e ){ trigger_error( $e->getMessage(), E_USER_WARNING ); } return implode("\n",$s)."\n"; }
public function merge( LocoPoMessage $def, $translate = false ) { if( $def->getHash() !== $this->getHash() ){ $prev = [ 'source' => '', 'target' => '' ]; $prev = $this->diff('source',$def,$prev); $prev = $this->diff('context',$def,$prev); $this['flag'] = 4; $this['prev'] = [ $prev ]; $defPlural = $def->getPlural(0); $ourPlural = $this->getPlural(0); if( $defPlural && $ourPlural ) { $ourPlural->merge($defPlural); if( $ourPlural->offsetExists('prev') ) { $this['prev'][] = $ourPlural->prev[0]+['parent'=>0,'plural'=>1]; $ourPlural->offsetUnset('prev'); } } else if( $defPlural ){ $this['plurals'] = [ clone $defPlural ]; } else if( $ourPlural ){ $this['prev'][] = $ourPlural->exportBasic() + ['parent'=>0,'plural'=>1]; $this->offsetUnset('plurals'); } } foreach( ['notes','refs','format'] as $f ){ if( $def->offsetExists($f) ){ $this->offsetSet($f,$def->offsetGet($f)); } else if( $this->offsetExists($f) ){ $this->offsetUnset($f); } } if( $translate && '' === $this['target'] && '' !== $def['target'] ){ $this['target'] = $def['target']; if( $def->offsetExists('comment') ) { $this['comment'] = $def['comment']; } if( $this->offsetExists('plurals') ){ foreach( $this['plurals'] as $i => $ourPlural ){ if( '' === $ourPlural['target'] ){ $defPlural = $def->getPlural($i); if( $defPlural ){ $ourPlural['target'] = $defPlural['target']; } } } } } }
private function diff( $key, LocoPoMessage $def, array $prev ) { $old = $this->__get($key); $new = $def->__get($key); if( $new !== $old ){ $this->offsetSet($key,$new); if( is_string($old) && '' !== $old ){ $prev[$key] = $old; } } return $prev; }
private function getPlural( $i ) { if( $this->offsetExists('plurals') ){ $plurals = $this->offsetGet('plurals'); if( is_array($plurals) && array_key_exists($i,$plurals) ){ return $plurals[$i]; } } return null; }
private function exportBasic() { return [ 'source' => $this['source'], 'context' => $this->context, 'target' => '', ]; }
public function export() { $a = $this->getArrayCopy(); unset($a['key']); if( array_key_exists('plurals',$a) ){ foreach( $a['plurals'] as $i => $p ){ if( $p instanceof ArrayObject ){ $a['plurals'][$i] = $p->getArrayCopy(); } } } return $a; }
public function strip() { $this['target'] = ''; $plurals = $this->plurals; if( is_array($plurals) ){ foreach( $plurals as $p ){ $p->strip(); } } return $this; }
public function translated() { $n = 0; if( '' !== (string) $this['target'] ){ $n++; } if( $this->offsetExists('plurals') ){ foreach( $this->offsetGet('plurals') as $plural ) { if( '' !== (string) $plural['target']) { $n++; } } } return $n; } }
class LocoPoIterator implements Iterator, Countable {
private $po;
private $headers = null;
private $i;
private $t;
private $j;
private $z = 0;
private $w = 79;
public function __construct( $po ){ if( is_array($po) ){ $this->po = $po; } else if( $po instanceof Traversable ){ $this->po = iterator_to_array($po,false); } else { throw new InvalidArgumentException('PO data must be array or iterator'); } $this->t = count( $this->po ); if( 0 === $this->t ){ throw new InvalidArgumentException('Empty PO data'); } $h = $po[0]; if( '' !== $h['source'] || ( isset($h['context']) && '' !== $h['context'] ) || ( isset($po[1]['parent']) && 0 === $po[1]['parent'] ) ){ $this->z = -1; } }
public function push( LocoPoMessage $p ) { $raw = $p->export(); $plurals = $p->plurals; unset($raw['plurals']); $i = count($this->po); $this->po[$i] = $raw; $this->t++; if( is_array($plurals) ) { $j = 0; foreach( $plurals as $p ) { $raw = $p->export(); $raw['parent'] = $i; $raw['plural'] = ++$j; $this->po[] = $raw; $this->t++; } } }
public function concat( $more ) { foreach( $more as $message ){ $this->push($message); } return $this; }
public function __clone() { if( $this->headers ){ $this->headers = new LocoPoHeaders( $this->headers->getArrayCopy() ); } }
#[ReturnTypeWillChange]
public function count() { return $this->t - ( $this->z + 1 ); }
public function wrap( $width ) { if( $width > 0 ){ $this->w = max( 15, $width ); } else { $this->w = 0; } return $this; }
#[ReturnTypeWillChange]
public function rewind() { $this->i = $this->z; $this->j = -1; $this->next(); }
#[ReturnTypeWillChange]
public function key() { return $this->j; }
#[ReturnTypeWillChange]
public function valid() { return is_int($this->i); }
#[ReturnTypeWillChange]
public function next() { $i = $this->i; while( ++$i < $this->t ){ if( array_key_exists('parent',$this->po[$i]) ){ continue; } $this->j++; $this->i = $i; return; } $this->i = null; $this->j = null; }
#[ReturnTypeWillChange]
public function current() { return $this->item( $this->i ); }
private function item( $i ) { $po = $this->po; $parent = new LocoPoMessage( $po[$i] ); $plurals = []; $nonseq = $parent->offsetExists('child'); $j = $nonseq ? $parent['child'] : $i+1; while( isset($po[$j]['parent']) && $i === $po[$j]['parent'] ){ $plurals[] = new LocoPoMessage($po[$j++]); } if( $plurals ){ $parent['plurals'] = $plurals; } return $parent; }
public function exportEntry( $i ) { return $this->item( $i + ( 1-$this->z) ); }
public function getArrayCopy() { $po = $this->po; if( 0 === $this->z ){ $po[0]['target'] = (string) $this->getHeaders(); } return $po; }
public function clear() { if( 0 === $this->z ){ $this->po = [ $this->po[0] ]; $this->t = 1; } else { $this->po = []; $this->t = 0; } }
public function getHeaders() { if( is_null($this->headers) ){ $header = $this->po[0]; if( 0 === $this->z ){ $value = $header['target']; if( is_string($value) ){ $this->headers = LocoPoHeaders::fromMsgstr($value); } else if( $value instanceof LocoPoHeaders ){ $this->headers = $value; } else if( is_array($value) ){ $this->headers = new LocoPoHeaders($value); } } else { $this->headers = new LocoPoHeaders; } } return $this->headers; }
public function setHeaders( LocoPoHeaders $head ) { $this->headers = $head; if( 0 === $this->z ){ $this->po[0]['target'] = null; } return $this; }
public function initPo() { if( 0 === $this->z ){ unset( $this->po[0]['flag'] ); } return $this; }
public function initPot() { if( 0 === $this->z ){ $this->po[0]['flag'] = 4; } return $this; }
public function strip() { $po = $this->po; $i = count($po); $z = $this->z; while( --$i > $z ){ $po[$i]['target'] = ''; } $this->po = $po; return $this; }
public function __toString() { try { return $this->render(); } catch( Exception $e ){ trigger_error( $e->getMessage(), E_USER_WARNING ); return ''; } }
public function render( callable $sorter = null ) { $width = $this->w; $ref_width = max( 0, $width - 3 ); $h = $this->exportHeader(); $msg = new LocoPoMessage( $h ); $s = $msg->render( $width, $ref_width ); if( $sorter ){ $msgs = []; foreach( $this as $msg ){ $msgs[] = $msg; } usort( $msgs, $sorter ); } else { $msgs = $this; } $h = $this->getHeaders()->offsetGet('Plural-Forms'); if( is_string($h) && preg_match('/nplurals\\s*=\\s*(\\d)/',$h,$r) ){ $max_pl = (int) $r[1]; } else { $max_pl = 0; } foreach( $msgs as $msg ){ $s .= "\n".$msg->render( $width, $ref_width, $max_pl ); } return $s; }
public function exportJed() { $head = $this->getHeaders(); $a = [ '' => [ 'domain' => $head['domain'], 'lang' => $head['language'], 'plural-forms' => $head['plural-forms'], ] ]; foreach( $this as $message ){ if( $message->translated() ){ $a[ $message->getKey() ] = $message->exportSerial(); } } return $a; }
private function exportHeader() { if( 0 === $this->z ){ $h = $this->po[0]; } else { $h = [ 'source' => '', 'target' => '' ]; } if( $this->headers ){ $h['target'] = (string) $this->headers; } return $h; }
public function exportRefs( $grep = '' ) { $a = []; if( '' === $grep ) { $grep = '/(\\S+):\\d+/'; } else { $grep = '/(\\S*'.$grep.'):\\d+/'; } $self = get_class($this); $base = [ $this->exportHeader() ]; foreach( $this as $message ){ if( preg_match_all( $grep, (string) $message->refs, $r ) ){ foreach( $r[1] as $ref ) { if( array_key_exists($ref,$a) ){ $po = $a[$ref]; } else { $po = new $self($base); $a[$ref] = $po; } $po->push($message); } } } return $a; }
public function splitRefs( array $map = null ) { $a = []; $self = get_class($this); $base = [ $this->exportHeader() ]; if( is_array($map) ){ $grep = implode('|',array_keys($map)); } else { $grep = '[a-z]+'; } foreach( $this as $message ){ $refs = ltrim( (string) $message->refs ); if( '' !== $refs ){ if( preg_match_all('/\\S+\\.('.$grep.'):\\d+/', $refs, $r, PREG_SET_ORDER ) ){ $tmp = []; foreach( $r as $rr ) { list( $ref, $ext ) = $rr; $tmp[$ext][$ref] = true; } foreach( $tmp as $ext => $refs ){ if( is_array($map) ){ $ext = $map[$ext]; } if( array_key_exists($ext,$a) ){ $po = $a[$ext]; } else { $po = new $self($base); $a[$ext] = $po; } $message = clone $message; $message['refs'] = implode(' ',array_keys($refs) ); $po->push($message); } } } } return $a; }
public function getHashes() { $a = []; foreach( $this as $msg ){ $a[] = $msg->getKey(); } sort( $a, SORT_STRING ); return $a; }
public function equalSource( LocoPoIterator $that ) { return $this->getHashes() === $that->getHashes(); }
public function equal( LocoPoIterator $that ) { if( $this->t !== $that->t ){ return false; } $i = $this->z; $fields = [ 'source', 'context', 'notes', 'refs', 'target', 'comment', 'flag', 'parent', 'plural' ]; while( ++$i < $this->t ){ $a = $this->po[$i]; $b = $that->po[$i]; foreach( $fields as $f ){ $af = isset($a[$f]) ? $a[$f] : ''; $bf = isset($b[$f]) ? $b[$f] : ''; if( $af !== $bf ){ return false; } } } return true; }
public function sort( callable $func = null ) { $order = []; foreach( $this as $msg ){ $order[] = $msg; } usort( $order, $func ?: [__CLASS__,'compare'] ); $this->clear(); foreach( $order as $p ){ $this->push($p); } return $this; }
public static function compare( LocoPoMessage $a, LocoPoMessage $b ) { $h = $a->getHash(); $j = $b->getHash(); $n = strcasecmp( $h, $j ); if( 0 === $n ){ $n = strcmp( $h, $j ); if( 0 === $n ){ return 0; } } return $n > 0 ? 1 : -1; }
public function createSorter() { $index = []; foreach( $this as $i => $msg ){ $index[ $msg->getHash() ] = $i; } $obj = new LocoPoIndex( $index ); return [ $obj, 'compare' ]; } }
class LocoMoTable {
private $size = 0;
private $bin = '';
private $map = null;
public function __construct( $data = '' ){ if( is_array($data) ){ $this->compile( $data ); } else if( '' !== $data ){ $this->parse( $data ); } }
#[ReturnTypeWillChange]
public function count() { if( is_null($this->size) ){ if( $this->bin ){ $this->size = (int) ( strlen( $this->bin ) / 4 ); } else if( is_array($this->map) ){ $this->size = count($this->map); } else { return 0; } if( ! self::is_prime($this->size) || $this->size < 3 ){ throw new Exception('Size expected to be prime number above 2, got '.$this->size); } } return $this->size; }
public function bytes() { return $this->count() * 4; }
public function __toString() { return $this->bin; }
public function export() { if( is_null($this->map) ){ $this->parse($this->bin); } return $this->map; }
private function reset( $length ) { $this->size = max( 3, self::next_prime( $length * 4 / 3 ) ); $this->bin = ''; $this->map = []; return $this->size; }
public function compile( array $msgids ) { $hash_tab_size = $this->reset( count($msgids) ); $packed = array_fill( 0, $hash_tab_size, "\0\0\0\0" ); $j = 0; foreach( $msgids as $msgid ){ $hash_val = self::hashpjw( $msgid ); $idx = $hash_val % $hash_tab_size; if( array_key_exists($idx, $this->map) ){ $incr = 1 + ( $hash_val % ( $hash_tab_size - 2 ) ); do { $idx += $incr; if( $hash_val === $idx ){ throw new Exception('Unable to find empty slot in hash table'); } $idx %= $hash_tab_size; } while( array_key_exists($idx, $this->map ) ); } $this->map[$idx] = $j; $packed[$idx] = pack('V', ++$j ); } $this->bin = implode('',$packed); }
public function lookup( $msgid, array $msgids ) { $hash_val = self::hashpjw( $msgid ); $idx = $hash_val % $this->size; $incr = 1 + ( $hash_val % ( $this->size - 2 ) ); while( true ){ if( ! array_key_exists($idx, $this->map) ){ break; } $j = $this->map[$idx]; if( isset($msgids[$j]) && $msgid === $msgids[$j] ){ return $j; } $idx += $incr; if( $idx === $hash_val ){ break; } $idx %= $this->size; } return -1; }
private function parse( $bin ) { $this->bin = $bin; $this->size = null; $hash_tab_size = $this->count(); $this->map = []; $idx = -1; $byte = 0; while( ++$idx < $hash_tab_size ){ $word = substr( $this->bin, $byte, 4 ); if( "\0\0\0\0" !== $word ){ list(,$j) = unpack('V', $word ); $this->map[$idx] = $j - 1; } $byte += 4; } }
public static function hashpjw( $str ) { $i = -1; $hval = 0; $len = strlen($str); while( ++$i < $len ){ $ord = ord( substr($str,$i,1) ); $hval = ( $hval << 4 ) + $ord; $g = $hval & 0xf0000000; if( $g !== 0 ){ $hval ^= $g >> 24; $hval ^= $g; } } return $hval; }
private static function next_prime( $seed ) { $seed = (int) floor($seed); $seed |= 1; while ( ! self::is_prime($seed) ){ $seed += 2; } return $seed; }
private static function is_prime( $num ) { if( 1 === $num ){ return false; } if( 2 === $num ){ return true; } if( $num % 2 == 0 ) { return false; } for( $i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) { if($num % $i == 0 ){ return false; } } return true; } }
class LocoMo {
private $bin;
private $msgs;
private $head;
private $hash = null;
private $use_fuzzy = false;
private $cs = null;
public function __construct( Iterator $export, LocoPoHeaders $head = null ){ if( $head ){ $this->head = $head; } else { $this->head = new LocoPoHeaders; $this->setHeader('Project-Id-Version','Loco'); } $this->msgs = $export; $this->bin = ''; }
public function setCharset( $cs ) { $cs = $this->head->setCharset($cs); $this->cs = 'UTF-8' === $cs ? null : $cs; }
public function enableHash() { $this->hash = new LocoMoTable; }
public function useFuzzy() { $this->use_fuzzy = true; }
public function setHeader( $key, $val ) { $this->head->add($key,$val); return $this; }
private function str( $s ) { if( $cs = $this->cs ){ $s = mb_convert_encoding($s,$cs,['UTF-8']); } return $s; }
public function compile() { $table = ['']; $sources = ['']; $targets = [ (string) $this->head ]; $fuzzy_flag = 4; $skip_fuzzy = ! $this->use_fuzzy; if( $this->head->has('Plural-Forms') && preg_match('/^nplurals=(\\d)/',$this->head->trimmed('Plural-Forms'), $r) ){ $nplurals = (int) $r[1]; $maxplural = max( 0, $nplurals-1 ); } else { $maxplural = 1; } $unique = []; foreach( $this->msgs as $r ){ if( $skip_fuzzy && isset($r['flag']) && $fuzzy_flag === $r['flag'] ){ continue; } $msgid = $this->str( $r['key'] ); if( isset($r['context']) ){ $msgctxt = $this->str( $r['context'] ); if( '' !== $msgctxt ){ if( '' === $msgid ){ $msgid = '('.$msgctxt.')'; } $msgid = $msgctxt."\x04".$msgid; } } if( '' === $msgid ){ continue; } if( array_key_exists($msgid,$unique) ){ continue; } $unique[$msgid] = true; $msgstr = $this->str( $r['target'] ); if( '' === $msgstr ){ continue; } $table[] = $msgid; if( isset($r['plurals']) ){ if( $r['plurals'] ){ $i = 0; foreach( $r['plurals'] as $i => $p ){ if( $i === 0 ){ $msgid .= "\0".$this->str($p['key']); } $msgstr .= "\0".$this->str($p['target']); } while( $maxplural > ++$i ){ $msgstr .= "\0"; } } else if( isset($r['plural_key']) ){ $msgid .= "\0".$this->str($r['plural_key']); } } $sources[] = $msgid; $targets[] = $msgstr; } asort( $sources, SORT_STRING ); $this->bin = "\xDE\x12\x04\x95\x00\x00\x00\x00"; $n = count($sources); $this->writeInteger( $n ); $offset = 28; $this->writeInteger( $offset ); $offset += $n * 8; $this->writeInteger( $offset ); if( $this->hash ){ sort( $table, SORT_STRING ); $this->hash->compile( $table ); $s = $this->hash->count(); } else { $s = 0; } $this->writeInteger( $s ); $offset += $n * 8; $this->writeInteger( $offset ); if( $s ){ $offset += $s * 4; } $source = ''; foreach( $sources as $str ){ $source .= $str."\0"; $this->writeInteger( $strlen = strlen($str) ); $this->writeInteger( $offset ); $offset += $strlen + 1; } $target = ''; foreach( array_keys($sources) as $i ){ $str = $targets[$i]; $target .= $str."\0"; $this->writeInteger( $strlen = strlen($str) ); $this->writeInteger( $offset ); $offset += $strlen + 1; } if( $this->hash ){ $this->bin .= $this->hash->__toString(); } $this->bin .= $source; $this->bin .= $target; return $this->bin; }
private function writeInteger( $num ) { $this->bin .= pack( 'V', $num ); } }
interface LocoTokensInterface extends Iterator {
public function advance();
public function ignore( ...$symbols ); }
class LocoTokenizer implements LocoTokensInterface { const T_LITERAL = 0; const T_UNKNOWN = -1;
private $src;
private $pos;
private $line;
private $col;
private $max;
private $rules = [];
private $skip = [];
private $tok;
private $len;
public function __construct( $src = '' ){ $this->init($src); }
public function parse( $src ) { return iterator_to_array( $this->generate($src) ); }
public function generate( $src ) { $this->init($src); while( $this->valid() ){ yield $this->current(); $this->next(); } }
public function init( $src ) { $this->src = $src; $this->rewind(); return $this; }
public function define( $grep, $t = 0 ) { if('^' !== $grep[1] ){ throw new InvalidArgumentException('Expression '.$grep.' isn\'t anchored'); } if( ! is_int($t) && ! is_callable($t) ){ throw new InvalidArgumentException('Non-integer token must be valid callback'); } $sniff = $grep[2]; if( $sniff === preg_quote($sniff,$grep[0]) ){ $this->rules[$sniff][] = [ $grep, $t ]; } else { $this->rules[''][] = [ $grep, $t ]; } return $this; }
public function ignore( ...$symbols ) { $this->skip += array_fill_keys( $symbols, true ); return $this; }
#[ReturnTypeWillChange]
public function current() { return $this->tok; }
public function advance() { $tok = $this->current(); $this->next(); return $tok; }
#[ReturnTypeWillChange]
public function next() { $tok = null; $offset = $this->pos; $column = $this->col; $line = $this->line; while( $offset <= $this->max ){ $t = null; $s = ''; $text = substr($this->src,$offset); foreach( [$text[0],''] as $k ){ if( isset($this->rules[$k]) ) { foreach( $this->rules[$k] as $rule) { if( preg_match($rule[0], $text, $match ) ) { $s = $match[0]; $t = $rule[1]; if( ! is_int($t) ) { $t = call_user_func( $t, $s, $match ); } break 2; } } } } if( is_null($t) ){ $n = preg_match('/^./u',$text,$match); if( false === $n ){ $s = $text[0]; $match = [ mb_convert_encoding($s,'UTF-8','Windows-1252') ]; } $s = (string) $match[0]; $t = self::T_UNKNOWN; } $length = strlen($s); if( 0 === $length ){ throw new Loco_error_ParseException('Failed to match anything'); } $offset += $length; $lines = preg_split('/\\r?\\n/',$s); $nlines = count($lines); if( $nlines > 1 ){ $next_line = $line + ( $nlines - 1 ); $next_column = strlen( end($lines) ); } else { $next_line = $line; $next_column = $column + $length; } if( array_key_exists($t,$this->skip) ){ $line = $next_line; $column = $next_column; continue; } $tok = self::T_LITERAL === $t ? $s : [ $t, $s, $line, $column ]; $line = $next_line; $column = $next_column; $this->len++; break; } $this->tok = $tok; $this->pos = $offset; $this->col = $column; $this->line = $line; }
#[ReturnTypeWillChange]
public function key() { return $this->len ? $this->len-1 : null; }
#[ReturnTypeWillChange]
public function valid() { return null !== $this->tok; }
#[ReturnTypeWillChange]
public function rewind() { $this->len = 0; $this->pos = 0; $this->col = 0; $this->line = 1; $this->max = strlen($this->src) - 1; $this->next(); } }
function loco_utf8_chr( $u ){ if( $u < 0x80 ){ if( $u < 0 ){ throw new RangeException( sprintf('%d is out of Unicode range', $u ) ); } return chr($u); } if( $u < 0x800 ) { return chr( ($u>>6) & 0x1F | 0xC0 ).chr( $u & 0x3F | 0x80 ); } if( $u < 0x10000 ) { return chr( $u>>12 & 15 | 0xE0 ).chr( $u>>6 & 0x3F | 0x80 ).chr( $u & 0x3F | 0x80 ); } if( $u < 0x110000 ) { return chr( $u>>18 & 7 | 0xF0 ).chr( $u>>12 & 0x3F | 0x80 ).chr( $u>>6 & 0x3F | 0x80 ).chr( $u & 0x3F | 0x80 ); } throw new RangeException( sprintf('\\x%X is out of Unicode range', $u ) ); }
function loco_resolve_surrogates( $s ){ return preg_replace_callback('/\\xED([\\xA0-\\xAF])([\\x80-\\xBF])\\xED([\\xB0-\\xBF])([\\x80-\\xBF])/', '_loco_resolve_surrogates', $s ); }
function _loco_resolve_surrogates( array $r ){ return loco_utf8_chr ( ( ( ( ( 832 | ( ord($r[1]) & 0x3F ) ) << 6 ) | ( ord($r[2]) & 0x3F ) ) - 0xD800 ) * 0x400 + ( ( ( ( 832 | ( ord($r[3]) & 0x3F ) ) << 6 ) | ( ord($r[4]) & 0x3F ) ) - 0xDC00 ) + 0x10000 ); }
class LocoEscapeParser {
private $map;
private $grep;
public function __construct( array $map = [] ){ $this->map = $map; $rules = ['\\\\']; if( $map ){ $rules[] = '['.implode(array_keys($map)).']'; } if( ! isset($map['U']) ) { $rules[] = 'U[0-9A-Fa-f]{5,8}'; } if( ! isset($map['u']) ) { $rules[] = 'u(?:\\{[0-9A-Fa-f]+\\}|[0-9A-Fa-f]{1,4})(?:\\\\u(?:\\{[0-9A-Fa-f]+\\}|[0-9A-Fa-f]{1,4}))*'; } $this->grep = '/\\\\('.implode('|',$rules).')/'; }
final public function unescape( $s ) { if( '' !== $s ) { return $this->stripSlashes( preg_replace_callback($this->grep, [$this, 'unescapeMatch'], $s) ); } return ''; }
final public function unescapeMatch( array $r ) { $s = $r[0]; $c = $s[1]; if( isset($this->map[$c]) ){ return $this->map[$c]; } if( 'u' === $c ){ $str = ''; $surrogates = false; foreach( explode('\\u',$s) as $i => $h ){ if( '' !== $h ){ $h = ltrim( trim($h,'{}'),'0'); $u = intval($h,16); $str.= loco_utf8_chr($u); if( ! $surrogates ){ $surrogates = $u >= 0xD800 && $u <= 0xDBFF; } } } if( $surrogates ){ $str = loco_resolve_surrogates($str); } return $str; } if( 'U' === $c ){ return loco_utf8_chr( intval(substr($s,2),16) ); } if( 'x' === $c ){ return chr( intval(substr($s,2),16) ); } if( ctype_digit($c) ){ return chr( intval(substr($s,1),8) ); } return $s; }
protected function stripSlashes( $s ) { return stripcslashes($s); } }
class LocoJsTokens extends LocoTokenizer { const T_KWORD = 1; const T_REGEX = 2;
private static $lex = null;
protected static $words = [ 'true' => 1, 'false' => 1, 'null' => 1, 'break' => T_BREAK, 'else' => T_ELSE, 'new' => T_NEW, 'var' => 1, 'case' => T_CASE, 'finally' => T_FINALLY, 'return' => T_RETURN, 'void' => 1, 'catch' => T_CATCH, 'for' => T_FOR, 'switch' => T_SWITCH, 'while' => T_WHILE, 'continue' => T_CONTINUE, 'function' => T_FUNCTION, 'this' => T_STRING, 'with' => 1, 'default' => T_DEFAULT, 'if' => T_IF, 'throw' => T_THROW, 'delete' => 1, 'in' => 1, 'try' => T_TRY, 'do' => T_DO, 'instanceof' => 1, 'typeof' => 1, ];
public static function decapse( $encapsed ) { $s = substr($encapsed,1,-1); $l = self::$lex; if( is_null($l) ){ $l = new LocoEscapeParser( [ 'U' => 'U', 'a' => 'a', ] ); self::$lex = $l; } return $l->unescape($s); }
public function __construct( $src = '' ){ $this->ignore(T_WHITESPACE); $this->define('/^(?:\\\\u[0-9A-F]{4,4}|[$_\\pL\\p{Nl}])(?:\\\\u[0-9A-F]{4}|[$_\\pL\\pN\\p{Mn}\\p{Mc}\\p{Pc}])*/ui', [$this,'matchWord'] ); $this->define('/^\\s+/u', T_WHITESPACE ); $this->define('!^//.*!', T_COMMENT ); $this->define('!^/\\*.*\\*/!Us', [$this,'matchComment'] ); $this->define('/^"(?:\\\\.|[^\\r\\n\\p{Zl}\\p{Zp}"\\\\])*"/u', T_CONSTANT_ENCAPSED_STRING ); $this->define('/^\'(?:\\\\.|[^\\r\\n\\p{Zl}\\p{Zp}\'\\\\])*\'/u', T_CONSTANT_ENCAPSED_STRING ); $this->define('/^[-+;,<>.=:|&^!?*%~(){}[\\]]/'); parent::__construct($src); }
public function matchWord( $s ) { if( array_key_exists($s,self::$words) ){ return self::$words[$s]; } return T_STRING; }
public function matchComment( $s ) { if( substr($s,0,3) === '/**' ){ return T_DOC_COMMENT; } return T_COMMENT; } }
interface LocoExtractorInterface {
public function setDomain( $default );
public function tokenize( $src );
public function extract( LocoExtracted $strings, LocoTokensInterface $tokens, $fileref = '' );
public function extractSource( $src, $fileref ); }
class LocoExtracted implements Countable {
private $exp = [];
private $reg = [];
private $dom = [];
private $dflt = '';
public function extractSource( LocoExtractorInterface $ext, $src, $fileref = '' ) { $ext->extract( $this, $ext->tokenize($src), $fileref ); return $this; }
public function export() { return $this->exp; }
#[ReturnTypeWillChange]
public function count() { return count( $this->exp ); }
public function getDomainCounts() { return $this->dom; }
public function setDomain( $default ) { $this->dflt = $default; return $this; }
public function getDomain() { return $this->dflt; }
private function key( array $entry ) { $key = (string) $entry['source']; foreach( ['context','domain'] as $i => $prop ){ if( array_key_exists($prop,$entry) ) { $add = (string) $entry[$prop]; if( '' !== $add ){ $key .= ord($i).$add; } } } return $key; }
public function pushEntry( array $entry, $domain ) { if( '' === $domain || '*' === $domain ){ $domain = $this->dflt; } $entry['id'] = ''; $entry['target'] = ''; $entry['domain'] = $domain; $key = $this->key($entry); if( isset($this->reg[$key]) ){ $index = $this->reg[$key]; $clash = $this->exp[$index]; if( $value = $this->mergeField( $clash, $entry, 'refs', ' ') ){ $this->exp[$index]['refs'] = $value; } if( $value = $this->mergeField( $clash, $entry, 'notes', "\n") ){ $this->exp[$index]['notes'] = $value; } } else { $index = count($this->exp); $this->reg[$key] = $index; $this->exp[$index] = $entry; if( isset($this->dom[$domain]) ){ $this->dom[$domain]++; } else { $this->dom[$domain] = 1; } } return $index; }
public function pushPlural( array $entry, $sindex ) { $parent = $this->exp[$sindex]; $domain = $parent['domain']; $pkey = $this->key($parent)."\2"; if( ! array_key_exists($pkey,$this->reg) ){ $pindex = count($this->exp); $this->reg[$pkey] = $pindex; $entry += [ 'id' => '', 'target' => '', 'plural' => 1, 'parent' => $sindex, 'domain' => $domain, ]; $this->exp[$pindex] = $entry; if( isset($entry['format']) && ! isset( $parent['format']) ) { $this->exp[$sindex]['format'] = $entry['format']; } if( $pindex !== $sindex + $entry['plural']) { $this->exp[$sindex]['child'] = $pindex; } } }
public function mergeField( array $old, array $new, $field, $glue ) { $prev = isset($old[$field]) ? $old[$field] : ''; if( isset($new[$field]) ){ $text = $new[$field]; if( '' !== $prev && $prev !== $text ){ if( 'notes' === $field && preg_match( '/^'.preg_quote( rtrim($text,'. '),'/').'[. ]*$/mu', $prev ) ) { $text = $prev; } else { $text = $prev.$glue.$text; } } return $text; } return $prev; }
public function filter( $domain ) { if( '' === $domain ){ $domain = $this->dflt; } $map = []; $newOffset = 1; $matchAll = '*' === $domain; $raw = [ [ 'id' => '', 'source' => '', 'target' => '', 'domain' => $matchAll ? '' : $domain, ] ]; foreach( $this->exp as $oldOffset => $r ){ if( isset($r['parent']) ){ if( isset($map[$r['parent']]) ){ $r['parent'] = $map[ $r['parent'] ]; $raw[ $newOffset++ ] = $r; } } else { if( $matchAll ){ $match = true; } else if( isset($r['domain']) ){ $match = $domain === $r['domain']; } else { $match = $domain === ''; } if( $match ){ $map[ $oldOffset ] = $newOffset; $raw[ $newOffset++ ] = $r; } } } return $raw; } }
abstract class LocoExtractor implements LocoExtractorInterface {
private $rules;
private $wp = [];
private $domain = '';
abstract protected function fsniff( $str );
abstract protected function decapse( $raw );
abstract protected function comment( $comment );
public function __construct( array $rules ){ $this->rules = $rules; }
public function setDomain( $default ) { $this->domain = $default; return $this; }
public function headerize( array $tags, $domain = '' ) { if( isset($this->wp[$domain]) ){ $this->wp[$domain] += $tags; } else { $this->wp[$domain] = $tags; } return $this; }
protected function getHeaders() { return $this->wp; }
final public function extractSource( $src, $fileref ) { $strings = new LocoExtracted; $this->extract( $strings, $this->tokenize($src), $fileref ); return $strings; }
public function rule( $keyword ) { return isset($this->rules[$keyword]) ? $this->rules[$keyword] : ''; }
protected function push( LocoExtracted $strings, $rule, array $args, $comment = '', $ref = '' ) { $s = strpos( $rule, 's'); $p = strpos( $rule, 'p'); $c = strpos( $rule, 'c'); $d = strpos( $rule, 'd'); if( false === $s || ! isset($args[$s]) ){ return null; } $msgid = $args[$s]; if( ! is_string($msgid) ){ return null; } $entry = [ 'source' => $msgid, ]; if( is_int($c) && isset($args[$c]) ){ $entry['context'] = $args[$c]; } else if( '' === $msgid ){ return null; } if( $ref ){ $entry['refs'] = $ref; } if( is_int($d) && array_key_exists($d,$args) ){ $domain = $args[$d]; if( is_null($domain) ){ $domain = ''; } } else if( '' === $this->domain ) { $domain = $strings->getDomain(); } else { $domain = $this->domain; } $format = ''; $comment = $this->comment($comment); if( '' !== $comment ){ if( preg_match('/^xgettext:\\s*([-a-z]+)-format\\s*/mi', $comment, $r, PREG_OFFSET_CAPTURE ) ){ $format = $r[1][0]; $entry['format'] = $format; $comment = trim( substr_replace( $comment,'', $r[0][1], strlen($r[0][0]) ) ); } if( preg_match('/^references?:( *.+:\\d+)*\\s*/mi', $comment, $r, PREG_OFFSET_CAPTURE ) ){ $entry['refs'] = trim($r[1][0],' '); $comment = trim( substr_replace( $comment, '', $r[0][1], strlen($r[0][0]) ) ); } $entry['notes'] = $comment; } $msgid_plural = is_int($p) && isset($args[$p]) ? $args[$p] : ''; if( '' === $format ){ $format = $this->fsniff($msgid); if( '' !== $format ){ $entry['format'] = $format; } else if( '' !== $msgid_plural ){ $format = $this->fsniff($msgid_plural); if( '' !== $format ){ $entry['format'] = $format; } } } $index = $strings->pushEntry($entry,$domain); if( '' !== $msgid_plural ){ $entry = [ 'source' => $msgid_plural, ]; if( '' !== $format ) { $entry['format'] = $format; } $strings->pushPlural($entry,$index); } return $index; }
protected function utf8( $str ) { if( false === preg_match('//u',$str) ){ $str = mb_convert_encoding( $str, 'UTF-8', 'Windows-1252' ); } return $str; } }
class LocoPHPTokens implements LocoTokensInterface, Countable {
private $i = null;
private $tokens;
private $skip_tokens;
private $literal_tokens;
public function __construct( array $tokens ){ $this->tokens = $tokens; $this->reset(); }
public function reset() { $this->rewind(); $this->literal_tokens = []; $this->skip_tokens = []; }
public function literal( ...$symbols ) { $this->literal_tokens += array_fill_keys($symbols,true); return $this; }
public function ignore( ...$symbols ) { $this->skip_tokens += array_fill_keys($symbols,true); return $this; }
public function export() { return array_values( iterator_to_array($this) ); }
public function advance() { if( $this->valid() ){ $tok = $this->current(); $this->next(); return $tok; } return null; }
#[ReturnTypeWillChange]
public function rewind() { $this->i = ( false === reset($this->tokens) ? null : key($this->tokens) ); }
#[ReturnTypeWillChange]
public function valid() { while( is_int($this->i) ){ $tok = $this->tokens[$this->i]; if( array_key_exists( is_array($tok)?$tok[0]:$tok, $this->skip_tokens ) ){ $this->next(); } else { return true; } } return false; }
#[ReturnTypeWillChange]
public function key() { return $this->i; }
#[ReturnTypeWillChange]
public function next() { $this->i = ( false === next($this->tokens) ? null : key($this->tokens) ); }
#[ReturnTypeWillChange]
public function current() { $tok = $this->tokens[$this->i]; if( is_array($tok) && isset($this->literal_tokens[$tok[0]]) ){ return $tok[1]; } return $tok; }
public function __toString() { $s = []; foreach( $this as $token ){ $s[] = is_array($token) ? $token[1] : $token; } return implode('',$s); }
#[ReturnTypeWillChange]
public function count() { return count($this->tokens); } }
class LocoPHPEscapeParser extends LocoEscapeParser {
public function __construct(){ parent::__construct( [ 'n' => "\n", 'r' => "\r", 't' => "\t", 'v' => "\x0B", 'f' => "\x0C", 'e' => "\x1B", '$' => '$', '\\' => '\\', '"' => '"', ] ); }
protected function stripSlashes( $s ) { return preg_replace_callback('/\\\\(x[0-9A-Fa-f]{1,2}|[0-3]?[0-7]{1,2})/', [$this,'unescapeMatch'], $s, -1, $n ); } }
function loco_unescape_php_string( $s ) { static $l; if( is_null($l) ) { $l = new LocoPHPEscapeParser; } return $l->unescape($s); }
function loco_decapse_php_string( $s ) { if( '' === $s ){ return ''; } $q = $s[0]; if( "'" === $q ){ return str_replace( ['\\'.$q, '\\\\'], [$q, '\\'], substr( $s, 1, -1 ) ); } if( '"' !== $q ){ return $s; } return loco_unescape_php_string( substr($s,1,-1) ); }
function loco_parse_php_comment( $comment ) { $comment = trim( $comment,"/ \n\r\t" ); if( '' !== $comment && '*' === $comment[0] ){ $lines = []; $junk = "\r\t/ *"; foreach( explode("\n",$comment) as $line ){ $line = trim($line,$junk); if( '' !== $line ){ $lines[] = $line; } } $comment = implode("\n", $lines); } return $comment; }
function loco_parse_wp_comment( $block ) { $header = []; if( '/*' === substr($block,0,2) ){ $junk = "\r\t/ *"; foreach( explode("\n", $block) as $line ){ if( false !== ( $i = strpos($line,':') ) ){ $key = substr($line,0,$i); $val = substr($line,++$i); $header[ trim($key,$junk) ] = trim($val,$junk); } } } return $header; }
class LocoPHPExtractor extends LocoExtractor {
private $defs = [];
public function tokenize( $src ) { return new LocoPHPTokens( token_get_all($src) ); }
public function decapse( $raw ) { return loco_decapse_php_string( $raw ); }
public function fsniff( $str ) { $format = ''; $offset = 0; while( preg_match('/%(?:[1-9]\\d*\\$)?(?:\'.|[-+0 ])*\\d*(?:\\.\\d+)?(.|$)/',$str,$r,PREG_OFFSET_CAPTURE,$offset) ){ $type = $r[1][0]; list($match,$offset) = $r[0]; if( '%' === $type && '%%' !== $match ){ return ''; } if( '' === $type || ! preg_match('/^[bcdeEfFgGosuxX%]/',$type) ){ return ''; } $offset += strlen($match); if( preg_match('/^% +[a-z]/i',$match) || preg_match('/^%[b-ou-x]/i',$match) ){ continue; } $format = 'php'; } return $format; }
protected function comment( $comment ) { return preg_replace('/^translators:\\s+/mi', '', loco_parse_php_comment($comment) ); }
public function define( $name, $value ) { $this->defs[$name] = $value; return $this; }
public function extract( LocoExtracted $strings, LocoTokensInterface $tokens, $fileref = '' ) { $tokens->ignore(T_WHITESPACE); $n = 0; $depth = 0; $comment = ''; $narg = 0; $args = []; $ref = ''; $rule = ''; $wp = $this->getHeaders(); $tokens->rewind(); while( $tok = $tokens->advance() ){ if( is_string($tok) ){ $s = $tok; $t = null; } else { $t = $tok[0]; $s = $tok[1]; } if( $depth ){ if( ')' === $s || ']' === $s ){ if( 0 === --$depth ){ if( $this->push( $strings, $rule, $args, $comment, $ref ) ){ $n++; } $comment = ''; } } else if( '(' === $s || '[' === $s ){ $depth++; $args[$narg] = null; } else if( 1 === $depth ){ if( ',' === $s ){ $narg++; } else if( T_CONSTANT_ENCAPSED_STRING === $t ){ $s = self::utf8($s); $args[$narg] = $this->decapse($s); } else if( T_STRING === $t && array_key_exists($s,$this->defs) ){ $args[$narg] = $this->defs[$s]; } else { $args[$narg] = null; } } } else if( T_COMMENT === $t || T_DOC_COMMENT === $t ){ $was_header = false; $s = self::utf8($s); if( 0 === $n ){ if( false !== strpos($s,'* @package') ){ $was_header = true; } if( $wp && ( $header = loco_parse_wp_comment($s) ) ){ foreach( $wp as $domain => $tags ){ foreach( array_intersect_key($header,$tags) as $tag => $text ){ $ref = $fileref ? $fileref.':'.$tok[2]: ''; $meta = $tags[$tag]; if( is_string($meta) ){ $meta = ['notes'=>$meta]; trigger_error( $tag.' header defaulted to "notes"',E_USER_DEPRECATED); } $strings->pushEntry( ['source'=>$text,'refs'=>$ref] + $meta, (string) $domain ); $was_header = true; } } } } if( ! $was_header ) { $comment = $s; } } else if( T_STRING === $t && '(' === $tokens->advance() && ( $rule = $this->rule($s) ) ){ $ref = $fileref ? $fileref.':'.$tok[2]: ''; $depth = 1; $args = []; $narg = 0; } else if( '' !== $comment && ! preg_match('!^[/* ]+(translators|xgettext):!im',$comment) ){ $comment = ''; } } } }
class LocoJsExtractor extends LocoPHPExtractor {
public function tokenize( $src ) { return new LocoJsTokens($src); }
public function fsniff( $str ) { return parent::fsniff($str) ? 'javascript' : ''; }
public function decapse( $raw ) { return LocoJsTokens::decapse($raw); } }
class LocoTwigExtractor extends LocoPHPExtractor {
public function tokenize( $src ) { return parent::tokenize( '<?php '.preg_replace('/{#([^#]+)#}/su','/*\\1*/',$src) ); } }
class LocoBladeExtractor extends LocoPHPExtractor {
public function tokenize( $src ) { return parent::tokenize( '<?php '.preg_replace('/{{--(.+)--}}/su','/*\\1*/',$src) ); } }
class LocoWpJsonExtractor implements LocoExtractorInterface {
private static $types = [];
private $base = '.';
private $domain = '';
public function __construct() { if( defined('ABSPATH') ){ $this->setBase( rtrim(ABSPATH,'/').'/wp-includes' ); } }
public function setBase( $path ) { $this->base = $path; }
private function getType( $type ) { if( array_key_exists($type,self::$types) ){ return self::$types[$type]; } $path = $this->base.'/'.$type.'-i18n.json'; if ( ! file_exists($path) ) { throw new Exception( basename($path).' not found in '.$this->base ); } return json_decode( file_get_contents($path) ); }
public function tokenize( $src ) { $raw = json_decode($src,true); if( ! is_array($raw) || ! array_key_exists('$schema',$raw) ){ throw new InvalidArgumentException('Invalid JSON'); } if( ! preg_match('!^https?://schemas.wp.org/trunk/(block|theme)\\.json!', $raw['$schema'], $r ) ){ throw new InvalidArgumentException('Unsupported schema'); } if( '' === $this->domain && array_key_exists('textdomain',$raw) ){ $this->domain = $raw['textdomain']; } return new LocoWpJsonStrings( $raw, $this->getType($r[1]) ); }
public function setDomain( $default ) { $this->domain = $default; return $this; }
public function extract( LocoExtracted $strings, LocoTokensInterface $tokens, $fileref = '' ) { if( ! preg_match('/:\\d+$/',$fileref) ){ $fileref.=':1'; } $tokens->rewind(); while( $tok = $tokens->advance() ){ $tok['refs'] = $fileref; $strings->pushEntry( $tok, $this->domain ); } }
final public function extractSource( $src, $fileref ) { $strings = new LocoExtracted; $this->extract( $strings, $this->tokenize($src), $fileref ); return $strings; } }
class LocoWpJsonStrings extends ArrayIterator implements LocoTokensInterface {
public function __construct( array $raw, stdClass $tpl ){ parent::__construct(); $this->walk( $tpl, $raw ); }
public function advance() { $tok = $this->current(); $this->next(); return $tok; }
public function ignore( ...$symbols ) { return $this; }
private function walk( $tpl, $raw ) { if( is_string($tpl) && is_string($raw) ) { $this->offsetSet( null, [ 'context' => $tpl, 'source' => $raw, ] ); return; } if( is_array($tpl) && is_array($raw) ) { foreach ( $raw as $value ) { self::walk( $tpl[0], $value ); } } else if( is_object($tpl) && is_array($raw) ) { $group_key = '*'; foreach ( $raw as $key => $value ) { if ( isset($tpl->$key) ) { $this->walk( $tpl->$key, $value ); } else if ( isset($tpl->$group_key) ) { $this->walk( $tpl->$group_key, $value ); } } } } }
function loco_wp_extractor( $type = 'php', $ext = '' ) { if( 'json' === $type ){ return new LocoWpJsonExtractor; } static $rules = [ '__' => 'sd', '_e' => 'sd', '_c' => 'sd', '_n' => 'sp_d', '_n_noop' => 'spd', '_nc' => 'sp_d', '__ngettext' => 'spd', '__ngettext_noop' => 'spd', '_x' => 'scd', '_ex' => 'scd', '_nx' => 'sp_cd', '_nx_noop' => 'spcd', 'esc_attr__' => 'sd', 'esc_html__' => 'sd', 'esc_attr_e' => 'sd', 'esc_html_e' => 'sd', 'esc_attr_x' => 'scd', 'esc_html_x' => 'scd', ]; if( 'php' === $type ){ return substr($ext,-9) === 'blade.php' ? new LocoBladeExtractor($rules) : new LocoPHPExtractor($rules); } if( 'js' === $type ){ return new LocoJsExtractor($rules); } if( 'twig' === $type ){ return new LocoTwigExtractor($rules); } throw new InvalidArgumentException('No extractor for '.$type); }
function loco_string_percent( $n, $t ) { if( ! $t || ! $n ){ return '0'; } if( $t === $n ){ return '100'; } $dp = 0; $n = 100 * $n / $t; if( $n > 99 ){ return rtrim( number_format( min( $n, 99.9 ), ++$dp ), '.0' ); } if( $n < 0.5 ){ $n = max( $n, 0.0001 ); do { $s = number_format( $n, ++$dp ); } while( preg_match('/^0\\.0+$/',$s) && $dp < 4 ); return substr($s,1); } return number_format( $n, $dp ); }
function loco_print_progress( $translated, $untranslated, $flagged ) { $total = $translated + $untranslated; $complete = loco_string_percent( $translated - $flagged, $total ); $class = 'progress'; if( ! $translated && ! $flagged ){ $class .= ' empty'; } else if( '100' === $complete ){ $class .= ' done'; } echo '<div class="',$class,'"><div class="t">'; if( $flagged ){ $s = loco_string_percent( $flagged, $total ); echo '<div class="bar f" style="width:',$s,'%"> </div>'; } if( '0' === $complete ){ echo ' '; } else { $class = 'bar p'; $p = (int) $complete; $class .= sprintf(' p-%u', 10*floor($p/10) ); $style = 'width:'.$complete.'%'; if( $flagged ){ $remain = 100.0 - (float) $s; $style .= '; max-width: '.sprintf('%s',$remain).'%'; } echo '<div class="',$class,'" style="'.$style.'"> </div>'; } echo '</div><div class="l">',$complete,'%</div></div>'; }
class LocoFuzzyMatcher implements Countable {
private $pot = [];
private $po = [];
private $diff = [];
private $dmax = .20;
#[ReturnTypeWillChange]
public function count() { return count($this->pot); }
public function unmatched() { return array_values($this->pot); }
public function redundant() { return array_values($this->po); }
public function setFuzziness( $s ) { if( $this->po ){ throw new LogicException('Cannot setFuzziness() after calling match()'); } $this->dmax = (float) max( 0, min( (int) $s, 100 ) ) / 100; }
public function add( $a ) { $source = isset($a['source']) ? (string) $a['source'] : ''; $context = isset($a['context']) ? (string) $a['context'] : ''; $key = $source."\4".$context; $this->pot[$key] = $a; }
private function key( $a ) { $source = isset($a['source']) ? (string) $a['source'] : ''; $context = isset($a['context']) ? (string) $a['context'] : ''; return $source."\4".$context; }
protected function getRef( $a ) { $key = $this->key($a); return array_key_exists($key,$this->pot) ? $this->pot[$key] : null; }
public function match( $a ) { $old = $this->key($a); if( isset($this->pot[$old]) ){ $new = $this->pot[$old]; unset($this->pot[$old]); return $new; } $this->po[$old] = $a; $target = isset($a['target']) ? (string) $a['target'] : ''; $comment = isset($a['comment']) ? (string) $a['comment'] : ''; if( '' === $target && '' === $comment ){ return null; } if( 0 < $this->dmax ){ foreach( $this->pot as $new => $_ ){ $dist = $this->distance($old,$new); if( -1 !== $dist ){ $this->diff[] = [ $old, $new, $dist ]; } } } return null; }
private function distance( $a, $b ) { $a = strtolower($a); $b = strtolower($b); if( $a === $b ){ return 0; } $lenA = strlen($a); $lenB = strlen($b); $lenDiff = abs($lenA-$lenB); $max = min($lenA,$lenB) + $lenDiff; $max = (int) ceil( $this->dmax * $max ); if( $max < $lenDiff ) { return -1; } $len = max($lenA,$lenB); if( $len < 256 ){ $d = levenshtein($a,$b); return $d > $max ? -1 : $d; } $d = 0; for( $i = 0; $i < $len; $i+=$max ){ $aa = substr($a,$i,$max); $bb = substr($b,$i,$max); $d += levenshtein($aa,$bb); if( $d > $max ){ return -1; } } return $d; }
public function getFuzzyMatches() { $pairs = []; usort( $this->diff, [__CLASS__,'compareDistance'] ); foreach( $this->diff as $pair ){ list($old,$new) = $pair; if( ! array_key_exists($new,$this->pot) || ! array_key_exists($old,$this->po) ){ continue; } $pairs[] = [ $this->po[$old], $this->pot[$new], ]; unset($this->po[$old]); unset($this->pot[$new]); if( ! $this->po || ! $this->pot ){ break; } } $this->diff = []; return $pairs; }
public function exportPo() { $p = new LocoPoIterator([ ['source' => ''], ]); $p->concat($this->pot); return $p; }
private static function compareDistance( array $a, array $b ) { return $a[2] - $b[2]; } }
defined('T_FINALLY') || define('T_FINALLY',500); if( function_exists('loco_check_extension') ) { loco_check_extension('mbstring'); } compiled/phpunit.php 0000644 00000012106 15233644314 0010545 0 ustar 00 <?php
/**
* Downgraded for PHP 5.6 compatibility. Do not edit.
* @noinspection ALL
*/
class LocoDomQueryFilter {
private $tag = '';
private $attr = [];
public function __construct( $value ){ $id = '[-_a-z][-_a-z0-9]*'; if( ! preg_match('/^([a-z1-6]*)(#'.$id.')?(\\.'.$id.')?(\\[(\\w+)="(.+)"])?$/i', $value, $r ) ){ throw new InvalidArgumentException('Bad filter, '.$value ); } if( $r[1] ){ $this->tag = $r[1]; } if( ! empty($r[2]) ){ $this->attr['id'] = substr($r[2],1); } if( ! empty($r[3]) ){ $this->attr['class'] = substr($r[3],1); } if( ! empty($r[4]) ){ $this->attr[ $r[5] ] = $r[6]; } }
public function filter( DOMElement $el ) { if( '' !== $this->tag ){ $list = $el->getElementsByTagName($this->tag); $recursive = false; } else { $list = $el->childNodes; $recursive = true; } if( $this->attr ){ $list = $this->reduce( $list, new ArrayIterator, $recursive )->getArrayCopy(); } return $list; }
public function reduce( DOMNodeList $list, ArrayIterator $reduced, $recursive ) { foreach( $list as $node ){ if( $node instanceof DOMElement ){ $matched = false; foreach( $this->attr as $name => $value ){ if( ! $node->hasAttribute($name) ){ $matched = false; break; } $values = array_flip( explode(' ', $node->getAttribute($name) ) ); if( ! isset($values[$value]) ){ $matched = false; break; } $matched = true; } if( $matched ){ $reduced[] = $node; } if( $recursive && $node->hasChildNodes() ){ $this->reduce( $node->childNodes, $reduced, true ); } } } return $reduced; } }
class LocoDomQuery extends ArrayIterator {
public static function parse( $source ) { $dom = new DOMDocument('1.0', 'UTF-8' ); $source = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>'.$source.'</body></html>'; $used_errors = libxml_use_internal_errors(true); $opts = LIBXML_HTML_NODEFDTD; $parsed = $dom->loadHTML( $source, $opts ); $errors = libxml_get_errors(); $used_errors || libxml_use_internal_errors(false); libxml_clear_errors(); if( $errors || ! $parsed ){ $e = new Loco_error_ParseException('Unknown parse error'); foreach( $errors as $error ){ $e = new Loco_error_ParseException( trim($error->message) ); $e->setContext( $error->line, $error->column, $source ); if( LIBXML_ERR_FATAL === $error->level ){ throw $e; } } if( ! $parsed ){ throw $e; } } return $dom; }
public function __construct( $value ){ if( $value instanceof DOMDocument ){ $value = [ $value->documentElement ]; } else if( $value instanceof DOMNode ){ $value = [ $value ]; } if( is_iterable($value) ){ $nodes = []; foreach( $value as $node ){ $nodes[] = $node; } } else if( is_string($value) || method_exists($value,'__toString') ){ $value = self::parse( $value ); $nodes = [ $value->documentElement ]; } else { $type = is_object($value) ? get_class($value) : gettype($value); throw new InvalidArgumentException('Cannot construct DOM from '.$type ); } parent::__construct( $nodes ); }
public function eq( $index ) { $q = new LocoDomQuery([]); if( $el = $this[$index] ){ $q[] = $el; } return $q; }
public function find( $value ) { $q = new LocoDomQuery( [] ); $f = new LocoDomQueryFilter($value); foreach( $this as $el ){ foreach( $f->filter($el) as $match ){ $q[] = $match; } } return $q; }
public function children() { $q = new LocoDomQuery([]); foreach( $this as $el ){ if( $el instanceof DOMNode ){ foreach( $el->childNodes as $child ) { $q[] = $child; } } } return $q; }
public function text(){ $s = ''; foreach( $this as $el ){ $s .= $el->textContent; } return $s; }
public function html() { $s = ''; foreach( $this as $outer ){ foreach( $outer->childNodes as $inner ){ $s .= $inner->ownerDocument->saveXML($inner); } break; } return $s; }
public function attr( $name ) { foreach( $this as $el ){ return $el->getAttribute($name); } return null; }
public function hasClass( $class ) { foreach( $this as $el ){ $classes = $el->getAttribute('class'); if( is_string($classes) && false !== strpos($classes,$class) ){ return true; } } return false; }
public function getFormData() { parse_str( $this->serializeForm(), $data ); return $data; }
public function serializeForm() { $pairs = []; foreach( ['input','select','textarea','button'] as $type ){ foreach( $this->find($type) as $field ){ $name = $field->getAttribute('name'); if( ! $name ){ continue; } if( $field->hasAttribute('type') ){ $type = $field->getAttribute('type'); } if( 'select' === $type ){ $value = null; $f = new LocoDomQueryFilter('option'); foreach( $f->filter($field) as $option ){ if( $option->hasAttribute('value') ){ $_value = $option->getAttribute('value'); } else { $_value = $option->nodeValue; } if( $option->hasAttribute('selected') ){ $value = $_value; break; } else if( is_null($value) ){ $value = $_value; } } if( is_null($value) ){ $value = ''; } } else if( 'checkbox' === $type || 'radio' === $type ){ if( $field->hasAttribute('checked') ){ $value = $field->getAttribute('value'); } else { continue; } } else if( 'file' === $type ){ $value = ''; } else if( $field->hasAttribute('value') ){ $value = $field->getAttribute('value'); } else { $value = $field->textContent; } $pairs[] = sprintf('%s=%s', rawurlencode($name), rawurlencode($value) ); } } return implode('&',$pairs); } }