function fontsquirrel_api_entity_presave in @font-your-face 8.3
Implements hook_entity_presave().
File
- modules/
fontsquirrel_api/ fontsquirrel_api.module, line 38 - Font Squirrel API module file.
Code
function fontsquirrel_api_entity_presave(EntityInterface $entity) {
if ($entity instanceof Font) {
if ($entity->pid->value == 'fontsquirrel_api' && $entity
->isActivated()) {
$metadata = $entity
->getMetadata();
$directory_location = _fontsquirrel_api_get_font_directory_location($entity);
\Drupal::service('file_system')
->prepareDirectory($directory_location, FileSystemInterface::CREATE_DIRECTORY);
$zip_location = file_build_uri('fontyourface/fontsquirrel/' . $metadata['path'] . '-fontfacekit.zip');
// Throw an exception; make it hard if this fails.
$uri = 'https://www.fontsquirrel.com/fontfacekit/' . $metadata['path'];
$response = \Drupal::httpClient()
->get($uri, [
'headers' => [
'Accept' => 'text/plain',
],
]);
if (!file_exists(\Drupal::service('file_system')
->realpath($zip_location))) {
\Drupal::service('file_system')
->saveData($response
->getBody(), $zip_location);
}
$files = [];
$font_pathinfo = pathinfo($metadata['font_filename']);
if ($zip = zip_open(\Drupal::service('file_system')
->realpath($zip_location))) {
while ($entry = zip_read($zip)) {
$entry_name = zip_entry_name($entry);
$path_info = pathinfo($entry_name);
if (strpos($path_info['filename'], $font_pathinfo['filename'] . '-webfont') !== FALSE && in_array($path_info['extension'], [
'eot',
'ttf',
'woff',
'svg',
])) {
$files[$path_info['extension']] = $path_info['filename'] . '.' . $path_info['extension'];
$data = zip_entry_read($entry, zip_entry_filesize($entry));
\Drupal::service('file_system')
->saveData($data, $directory_location . '/' . $path_info['filename'] . '.' . $path_info['extension'], FileSystemInterface::EXISTS_REPLACE);
}
zip_entry_close($entry);
}
zip_close($zip);
}
if (!empty($files)) {
$css_file = _fontsquirrel_api_generate_fontfamily_css_stylesheet($entity->css_family->value, $files);
\Drupal::service('file_system')
->saveData($css_file, $directory_location . '/fontyourface-stylesheet.css', FileSystemInterface::EXISTS_REPLACE);
}
}
}
}