Skip to content

Commit

Permalink
Drupal 9 support.
Browse files Browse the repository at this point in the history
  • Loading branch information
jacerider committed Jan 25, 2021
1 parent fbb4db4 commit 2cff640
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 56 deletions.
2 changes: 1 addition & 1 deletion real_favicon.info.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ name: 'Real Favicon'
description: 'A favicon generator for all platforms utilizing http:https://realfavicongenerator.net.'
package: JaceRider
type: module
core: 8.x
core_version_requirement: ^9
58 changes: 44 additions & 14 deletions src/Entity/RealFavicon.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityMalformedException;
use Drupal\Core\File\FileSystemInterface;

/**
* Defines the Favicon entity.
Expand All @@ -30,6 +32,12 @@
* "label" = "label",
* "uuid" = "uuid"
* },
* config_export = {
* "id",
* "label",
* "tags",
* "archive",
* },
* links = {
* "canonical" = "/admin/structure/real-favicon/{real_favicon}",
* "add-form" = "/admin/structure/real-favicon/add",
Expand Down Expand Up @@ -64,6 +72,8 @@ class RealFavicon extends ConfigEntityBase implements RealFaviconInterface {

/**
* The folder where Real Favicons exist.
*
* @var string
*/
protected $directory = 'public:https://favicon';

Expand All @@ -79,7 +89,7 @@ public function setTagsAsString($string) {
}

/**
* Get the tags as string.
* {@inheritDoc}
*/
public function getTagsAsString() {
$tags = $this->get('tags');
Expand Down Expand Up @@ -130,10 +140,10 @@ public function getManifestLargeImage() {
}

/**
* Set the archive as base64 encoded string.
* {@inheritDoc}
*/
public function setArchive($zip_path) {
$data = strtr(base64_encode(addslashes(gzcompress(serialize(file_get_contents($zip_path)),9))), '+/=', '-_,');
$data = strtr(base64_encode(addslashes(gzcompress(serialize(file_get_contents($zip_path)), 9))), '+/=', '-_,');
$parts = str_split($data, 200000);
$this->set('archive', $parts);
}
Expand All @@ -156,10 +166,10 @@ public function getThumbnail($image_name = 'favicon-16x16.png') {
/**
* Return the location where Iconifys exist.
*
* @return [string]
* @return string
* The directory path.
*/
protected function getDirectory() {
public function getDirectory() {
return $this->directory . '/' . $this->id();
}

Expand All @@ -172,6 +182,7 @@ public function preSave(EntityStorageInterface $storage) {
if (!$this->isNew()) {
$original = $storage->loadUnchanged($this->getOriginalId());
}
/** @var \Drupal\real_favicon\Entity\RealFaviconInterface $original */

if (is_string($this->get('tags'))) {
$this->setTagsAsString($this->get('tags'));
Expand All @@ -190,8 +201,11 @@ public function preSave(EntityStorageInterface $storage) {
*/
public static function preDelete(EntityStorageInterface $storage, array $entities) {
parent::preDelete($storage, $entities);
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
foreach ($entities as $entity) {
file_unmanaged_delete_recursive($entity->getDirectory());
/** @var \Drupal\real_favicon\Entity\RealFaviconInterface $entity */
$file_system->deleteRecursive($entity->getDirectory());
// Clean up empty directory. Will fail silently if it is not empty.
@rmdir($entity->directory);
}
Expand All @@ -210,32 +224,42 @@ protected function archiveDecode() {
/**
* Properly extract and store an IcoMoon zip file.
*
* @param [string] $zip_path
* @param string $zip_path
* The absolute path to the zip file.
*/
public function archiveExtract($zip_path) {
$archiver = archiver_get_archiver($zip_path);
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
/** @var \Drupal\Core\Archiver\ArchiverManager $archiver_manager */
$archiver_manager = \Drupal::service('plugin.manager.archiver');
$archiver = $archiver_manager->getInstance(['filepath' => $zip_path]);
if (!$archiver) {
throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $zip_path)));
throw new \Exception(t('Cannot extract %file, not a valid archive.', ['%file' => $zip_path]));
}

$directory = $this->getDirectory();
file_unmanaged_delete_recursive($directory);
file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
$file_system->deleteRecursive($directory);
$file_system->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
$archiver->extract($directory);

drupal_set_message(t('Real Favicon package has been successfully %op.', ['%op' => ($this->isNew() ? t('updated') : t('added'))]));
\Drupal::messenger()->addMessage(t('Real Favicon package has been successfully %op.', ['%op' => ($this->isNew() ? t('updated') : t('added'))]));
}

/**
* Get valid tags as strings.
*/
public function getValidTagsAsString() {
return implode(PHP_EOL, $this->getValidTags()) . PHP_EOL;
}

/**
* Get valid tags.
*/
public function getValidTags() {
$base_path = base_path();
$html = $this->getTagsAsString();
$found = array();
$missing = array();
$found = [];
$missing = [];

$dom = new \DOMDocument();
$dom->loadHTML($html);
Expand Down Expand Up @@ -283,6 +307,12 @@ public function getValidTags() {
return $found;
}

/**
* Normalize path.
*
* @return string
* The normalized path.
*/
protected function normalizePath($file_path) {
return file_url_transform_relative(file_create_url($this->getDirectory() . $file_path));
}
Expand Down
33 changes: 32 additions & 1 deletion src/Entity/RealFaviconInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,36 @@
*/
interface RealFaviconInterface extends ConfigEntityInterface {

// Add get/set methods for your configuration properties here.
/**
* Return the location where Iconifys exist.
*
* @return string
* The directory path.
*/
public function getDirectory();

/**
* Get the tags as a string.
*
* @return string
* The tags as a string.
*/
public function getTagsAsString();

/**
* Get a favicon image.
*
* @return string
* The favicon image.
*/
public function getThumbnail($image_name = 'favicon-16x16.png');

/**
* Set the archive as base64 encoded string.
*
* @param string $zip_path
* The zip path.
*/
public function setArchive($zip_path);

}
2 changes: 1 addition & 1 deletion src/Form/RealFaviconDeleteForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function getConfirmText() {
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->entity->delete();

drupal_set_message(
\Drupal::messenger()->addMessage(
$this->t('content @type: deleted @label.',
[
'@type' => $this->entity->bundle(),
Expand Down
53 changes: 28 additions & 25 deletions src/Form/RealFaviconForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

namespace Drupal\real_favicon\Form;

use Drupal\Component\Utility\Environment;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;

/**
* Class RealFaviconForm.
* Class real favicon form.
*
* @package Drupal\real_favicon\Form
* @package Drupal\entity\Form
*/
class RealFaviconForm extends EntityForm {

Expand All @@ -18,50 +19,51 @@ class RealFaviconForm extends EntityForm {
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);

$real_favicon = $this->entity;
/** @var \Drupal\entity\Entity\RealFaviconInterface $entity */
$entity = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#maxlength' => 255,
'#default_value' => $real_favicon->label(),
'#default_value' => $entity->label(),
'#description' => $this->t("Label for the Favicon."),
'#required' => TRUE,
];

$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $real_favicon->id(),
'#default_value' => $entity->id(),
'#machine_name' => [
'exists' => '\Drupal\real_favicon\Entity\RealFavicon::load',
'replace_pattern' => '[^a-z0-9-]+',
'replace' => '-',
],
'#disabled' => !$real_favicon->isNew(),
'#disabled' => !$entity->isNew(),
];

$form['tags'] = [
'#type' => 'textarea',
'#title' => $this->t('Tags'),
'#default_value' => $real_favicon->getTagsAsString(),
'#default_value' => $entity->getTagsAsString(),
'#description' => t('Paste the code provided by <a href="@url" target="_blank">@url</a>. Make sure each link is on a separate line. It is fine to paste links with paths like "/apple-touch-icon-57x57.png" as these will be converted to the correct paths automatically.', ['@url' => 'http:https://realfavicongenerator.net/']),
'#required' => TRUE,
];

$validators = array(
'file_validate_extensions' => array('zip'),
'file_validate_size' => array(file_upload_max_size()),
);
$form['file'] = array(
$validators = [
'file_validate_extensions' => ['zip'],
'file_validate_size' => [Environment::getUploadMaxSize()],
];
$form['file'] = [
'#type' => 'file',
'#title' => t('Upload a zip file from realfavicongenerator.net to install'),
'#description' => array(
'#description' => [
'#theme' => 'file_upload_help',
'#description' => t('For example: %filename from your local computer. This only needs to be done once.', array('%filename' => 'favicons.zip')),
'#description' => t('For example: %filename from your local computer. This only needs to be done once.', ['%filename' => 'favicons.zip']),
'#upload_validators' => $validators,
),
],
'#size' => 50,
'#upload_validators' => $validators,
);
];

return $form;
}
Expand All @@ -85,34 +87,35 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$real_favicon = $this->entity;
/** @var \Drupal\entity\Entity\RealFaviconInterface $entity */
$entity = $this->entity;

if ($this->file) {
try {
$zip_path = $this->file->getFileUri();
$real_favicon->setArchive($zip_path);
$entity->setArchive($zip_path);
}
catch (Exception $e) {
catch (\Exception $e) {
$form_state->setErrorByName('file', $e->getMessage());
return;
}
}

$status = $real_favicon->save();
$status = $entity->save();

switch ($status) {
case SAVED_NEW:
drupal_set_message($this->t('Created the %label Favicon.', [
'%label' => $real_favicon->label(),
\Drupal::messenger()->addMessage($this->t('Created the %label Favicon.', [
'%label' => $entity->label(),
]));
break;

default:
drupal_set_message($this->t('Saved the %label Favicon.', [
'%label' => $real_favicon->label(),
\Drupal::messenger()->addMessage($this->t('Saved the %label Favicon.', [
'%label' => $entity->label(),
]));
}
$form_state->setRedirectUrl($real_favicon->urlInfo('collection'));
$form_state->setRedirectUrl($entity->toUrl('collection'));
}

}
17 changes: 4 additions & 13 deletions src/Form/RealFaviconSettingsForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\real_favicon\RealFaviconSync;

/**
* Class RealFaviconSettingsForm.
*
Expand Down Expand Up @@ -50,33 +48,26 @@ public function buildForm(array $form, FormStateInterface $form_state, array $fa
$config = $this->config('real_favicon.settings');
$config_themes = $config->get('themes');

$form['themes'] = array(
$form['themes'] = [
'#type' => 'details',
'#title' => $this->t('Theme Favicons'),
'#description' => $this->t('A favicon can be set per theme.'),
'#open' => TRUE,
'#tree' => TRUE,
);
];

foreach ($theme_options as $id => $name) {
$form['themes'][$id] = array(
$form['themes'][$id] = [
'#type' => 'select',
'#title' => $this->t('%name Favicon', ['%name' => $name]),
'#options' => [0 => '- Use Drupal Default -'] + $favicon_options,
'#default_value' => !empty($config_themes[$id]) && isset($favicon_options[$config_themes[$id]]) ? $config_themes[$id] : 0,
);
];
}

return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
Expand Down
Loading

0 comments on commit 2cff640

Please sign in to comment.