public static function create($site, $domain, $active = false)
{
global $wpdb;
// Allow passing a site object in
if (is_object($site) && isset($site->blog_id)) {
$site = $site->blog_id;
}
if (!is_numeric($site)) {
return new \WP_Error('mercator.mapping.invalid_id');
}
$site = absint($site);
$active = (bool) $active;
// Did we get a full URL?
if (strpos($domain, '://') !== false) {
// Parse just the domain out
$domain = parse_url($domain, PHP_URL_HOST);
}
// Does this domain exist already?
$existing = static::get_by_domain($domain);
if (is_wp_error($existing)) {
return $existing;
}
if (!empty($existing)) {
// Domain exists already...
if ($site !== $existing->get_site_id()) {
// ...and points to another site
return new \WP_Error('mercator.mapping.domain_exists');
}
// ...and points to this site, so nothing to do
return $existing;
}
// Create the mapping!
$prev_errors = !empty($GLOBALS['EZSQL_ERROR']) ? $GLOBALS['EZSQL_ERROR'] : array();
$suppress = $wpdb->suppress_errors(true);
$result = $wpdb->insert($wpdb->dmtable, array('blog_id' => $site, 'domain' => $domain, 'active' => $active), array('%d', '%s', '%d'));
$wpdb->suppress_errors($suppress);
if (empty($result)) {
// Check that the table exists...
if (check_table() === 'created') {
// Table created, try again
return static::create($site, $domain);
}
// Other error. We suppressed errors before, so we need to make sure
// we handle that now.
$recent_errors = array_diff_key($GLOBALS['EZSQL_ERROR'], $prev_errors);
while (count($recent_errors) > 0) {
$error = array_shift($recent_errors);
$wpdb->print_error($error['error_str']);
}
return new \WP_Error('mercator.mapping.insert_failed');
}
// Ensure the cache is flushed
wp_cache_delete('id:' . $site, 'domain_mapping');
wp_cache_delete('domain:' . $domain, 'domain_mapping');
$mapping = static::get($wpdb->insert_id);
/**
* Fires after a mapping has been created.
*
* @param Mercator\Mapping $mapping The mapping object.
*/
do_action('mercator.mapping.created', $mapping);
return $mapping;
}