Newer
Older
tonitalia-pluginsoci / includes / class-user-manager.php
<?php
/**
 * WordPress user creation and profile meta.
 *
 * @package TonItaliaRegistration
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class TON_Reg_User_Manager
 */
class TON_Reg_User_Manager {

	/**
	 * @param array<string,mixed> $data Registration data.
	 * @return int|WP_Error User ID.
	 */
	public static function create_subscriber( $data ) {
		$email = sanitize_email( $data['email'] );
		if ( email_exists( $email ) ) {
			return new WP_Error( 'ton_reg_email_exists', __( 'Questa email è già registrata.', 'ton-italia-registration' ) );
		}

		$password = wp_generate_password( 24, true, true );
		$login    = self::unique_login_from_email( $email );

		$user_id = wp_insert_user(
			array(
				'user_login'   => $login,
				'user_email'   => $email,
				'user_pass'    => $password,
				'first_name'   => sanitize_text_field( $data['nome'] ),
				'last_name'    => sanitize_text_field( $data['cognome'] ),
				'display_name' => sanitize_text_field( $data['nome'] . ' ' . $data['cognome'] ),
				'role'         => 'subscriber',
			)
		);

		if ( is_wp_error( $user_id ) ) {
			return $user_id;
		}

		self::sync_user_meta( (int) $user_id, $data );

		return (int) $user_id;
	}

	/**
	 * @param string $email Email.
	 * @return string
	 */
	private static function unique_login_from_email( $email ) {
		$base = sanitize_user( current( explode( '@', $email ) ), true );
		if ( '' === $base ) {
			$base = 'socio';
		}
		$login = $base;
		$i     = 1;
		while ( username_exists( $login ) ) {
			$login = $base . $i;
			++$i;
		}
		return $login;
	}

	/**
	 * @param int                 $user_id User ID.
	 * @param array<string,mixed> $data    Data.
	 */
	public static function sync_user_meta( $user_id, $data ) {
		$keys = array(
			'cognome',
			'nome',
			'luogo_nascita',
			'provincia_nascita',
			'data_nascita',
			'codice_fiscale',
			'comune_residenza',
			'provincia_residenza',
			'indirizzo',
			'numero_civico',
			'cap',
			'telefono',
		);
		foreach ( $keys as $key ) {
			if ( isset( $data[ $key ] ) ) {
				update_user_meta( $user_id, 'ton_reg_' . $key, $data[ $key ] );
			}
		}
		update_user_meta( $user_id, 'ton_reg_registration_id', isset( $data['registration_id'] ) ? (int) $data['registration_id'] : 0 );
	}

	/**
	 * @param string $value Codice fiscale.
	 * @return bool
	 */
	public static function validate_codice_fiscale( $value ) {
		$value = strtoupper( preg_replace( '/\s+/', '', $value ) );
		return (bool) preg_match( '/^[A-Z]{6}[0-9]{2}[A-Z][0-9]{2}[A-Z][0-9]{3}[A-Z]$/', $value );
	}

	/**
	 * @param string $date Date Y-m-d.
	 * @return bool
	 */
	public static function is_minor( $date ) {
		if ( ! $date ) {
			return false;
		}
		$birth = strtotime( $date );
		if ( ! $birth ) {
			return false;
		}
		$eighteen = strtotime( '-18 years' );
		return $birth > $eighteen;
	}
}