public function Redirect::createRedirect in File (Field) Paths 8
Creates a redirect for a moved File field.
Parameters
string $source: The source file URL.
string $path: The moved file URL.
\Drupal\Core\Language\Language $language: The language of the source file.
Overrides RedirectInterface::createRedirect
File
- src/
Redirect.php, line 67
Class
- Redirect
- Service for creating file redirects.
Namespace
Drupal\filefield_pathsCode
public function createRedirect($source, $path, Language $language) {
$this->logger
->debug('Creating redirect from @source to @path.', [
'@source' => $source,
'@path' => $path,
]);
/** @var \Drupal\redirect\Entity\Redirect $redirect */
$redirect = $this->redirectStorage
->create([]);
$parsed_source = $this
->getPath($source);
$parsed_path = $this
->getPath($path);
$redirect
->setSource($parsed_source);
$redirect
->setRedirect($parsed_path);
$redirect
->setStatusCode($this->configFactory
->get('redirect.settings')
->get('default_status_code'));
// Check if the redirect doesn't already exist before saving.
$hash = $redirect
->generateHash($parsed_path, [], $language
->getId());
$redirects = $this->redirectStorage
->loadByProperties([
'hash' => $hash,
]);
if (empty($redirects)) {
// Redirect does not exist yet, save as new one.
$redirect
->save();
}
}