customers = $customers; } /** * Imports customers. * * @since 0.1.0 * * @param array $rows Rows keyed by column name. * @param bool $dry_run Only check the rows. * @param bool $send_welcome Send the welcome email to each new customer. * @return array|WP_Error */ public function import( array $rows, bool $dry_run, bool $send_welcome = false ) { $rows = array_values( $rows ); if ( array() === $rows ) { return Errors::invalid( array( 'rows' => __( 'The file has no rows.', 'hostkhata' ) ) ); } if ( count( $rows ) > self::MAX_ROWS ) { /* translators: %d: maximum number of rows. */ return Errors::invalid( array( 'rows' => sprintf( __( 'Import at most %d rows at a time.', 'hostkhata' ), self::MAX_ROWS ) ) ); } if ( ! $send_welcome ) { add_filter( 'hostkhata_send_welcome_email', '__return_false' ); } $results = array(); $ok = 0; $seen = array(); foreach ( $rows as $index => $row ) { $result = $this->one( $row, $dry_run, $seen ); if ( is_wp_error( $result ) ) { $data = (array) $result->get_error_data(); $results[] = array( 'row' => $index + 1, 'ok' => false, 'errors' => isset( $data['errors'] ) ? (array) $data['errors'] : array( 'row' => $result->get_error_message() ), ); continue; } ++$ok; $results[] = array( 'row' => $index + 1, 'ok' => true, 'errors' => array(), 'id' => $dry_run ? 0 : (int) ( $result['id'] ?? 0 ), ); } if ( ! $send_welcome ) { remove_filter( 'hostkhata_send_welcome_email', '__return_false' ); } return array( 'dry_run' => $dry_run, 'created' => $dry_run ? 0 : $ok, 'valid' => $ok, 'failed' => count( $rows ) - $ok, 'results' => $results, ); } /** * Checks or creates one row. * * @param mixed $row Row. * @param bool $dry_run Dry run. * @param array $seen Email addresses already used earlier in the file. * @return array|WP_Error */ private function one( $row, bool $dry_run, array &$seen ) { if ( ! is_array( $row ) ) { return Errors::invalid( array( 'row' => __( 'This row is not valid.', 'hostkhata' ) ) ); } // The export writes tags separated by semicolons, so the import accepts them too. if ( isset( $row['tags'] ) && is_string( $row['tags'] ) ) { $row['tags'] = str_replace( array( ';', '|' ), ',', $row['tags'] ); } $email = isset( $row['email'] ) && is_string( $row['email'] ) ? strtolower( trim( $row['email'] ) ) : ''; if ( '' !== $email && isset( $seen[ $email ] ) ) { return Errors::invalid( array( 'email' => __( 'This email address appears twice in the file.', 'hostkhata' ) ) ); } if ( $dry_run ) { $clean = CustomerInput::clean( $row, true ); if ( $clean['errors'] ) { return Errors::invalid( $clean['errors'] ); } if ( email_exists( $clean['data']['email'] ) ) { return Errors::invalid( array( 'email' => __( 'A user with this email address already exists.', 'hostkhata' ) ) ); } $seen[ $email ] = true; return array( 'id' => 0 ); } $result = $this->customers->create( $row ); if ( ! is_wp_error( $result ) && '' !== $email ) { $seen[ $email ] = true; } return $result; } }